52 Commits
Author SHA1 Message Date
bit9992 05e8d34bcf Record accepted Windows native baseline and Android CI build route
native-ci / native-linux (teamspeach-native-linux-arm64, aarch64-unknown-linux-gnu) (push) Canceled after 0s
native-ci / native-linux (teamspeach-native-linux-x64, x86_64-unknown-linux-gnu) (push) Canceled after 0s
2026-11-11 11:32:53 +03:00
bit9992 5ce12714ac Refresh Understand graph for native-only Rust Slint architecture
native-ci / native-linux (teamspeach-native-linux-arm64, aarch64-unknown-linux-gnu) (push) Canceled after 0s
native-ci / native-linux (teamspeach-native-linux-x64, x86_64-unknown-linux-gnu) (push) Canceled after 0s
2026-11-10 18:28:52 +03:00
bit9992 a761afaa43 Record native cutover verification and environment blockers 2026-11-10 18:25:25 +03:00
bit9992 220852f8cb Remove Electron and make Rust Slint the sole native client 2026-11-10 17:53:53 +03:00
omar eb24965076 Implement Rust and Slint native client migration and fix desktop startup
ci / linux-arm64-cross (push) Successful in 4m7s
ci / linux-x64 (push) Successful in 4m42s
2026-11-10 15:45:24 +03:00
omar 0d11f8f99d wip: checkpoint TS6 interface parity and working settings for handoff
ci / linux-arm64-cross (push) Successful in 33m19s
ci / linux-x64 (push) Failing after 46m53s
2026-11-08 15:54:28 +03:00
omar c4707c4e8e release: prepare v0.1.7 verified editor and interface update
ci / linux-arm64-cross (push) Successful in 3m24s
ci / linux-x64 (push) Successful in 4m10s
release / linux-arm64 (push) Successful in 7m47s
release / linux-x64 (push) Successful in 8m6s
release / appimage-startup (push) Successful in 14s
release / publish (push) Successful in 20s
2026-11-02 13:44:55 +03:00
omar a4c9e7e102 docs: record authorized muted server capability probe
ci / linux-arm64-cross (push) Successful in 3m57s
ci / linux-x64 (push) Successful in 5m6s
2026-11-02 13:33:58 +03:00
omar 21085b967d docs: record native server-chat request constructors
ci / linux-arm64-cross (push) Successful in 3m44s
ci / linux-x64 (push) Successful in 3m48s
2026-11-02 12:58:34 +03:00
omar d0202247ce docs: distinguish server-hosted Matrix from account chat
ci / linux-x64 (push) Successful in 3m24s
ci / linux-arm64-cross (push) Successful in 3m45s
2026-11-02 12:39:28 +03:00
omar e4681bef35 chat: preserve source keyboard editing and list transitions 2026-11-02 12:15:05 +03:00
omar f618d8bce9 chat: add safe hybrid Markdown editing with strict CSP
ci / linux-arm64-cross (push) Successful in 3m22s
ci / linux-x64 (push) Successful in 3m32s
2026-11-02 11:32:31 +03:00
omar 3ee2bef7ce ui: match light controls and narrow chat reference layouts 2026-11-02 11:05:28 +03:00
omar 72e4ad63a8 release: prepare v0.1.6 and run ARM test subprocesses through qemu
ci / linux-x64 (push) Successful in 6m10s
ci / linux-arm64-cross (push) Successful in 6m32s
release / linux-arm64 (push) Successful in 7m22s
release / linux-x64 (push) Successful in 8m12s
release / appimage-startup (push) Successful in 18s
release / publish (push) Successful in 20s
2026-11-02 11:01:56 +03:00
omar c75c8f3d74 release: prepare v0.1.5 verified account-free snapshot
release / linux-x64 (push) Failing after 59s
ci / linux-x64 (push) Failing after 1m9s
ci / linux-arm64-cross (push) Failing after 4m15s
release / linux-arm64 (push) Successful in 4m36s
release / appimage-startup (push) Skipped
release / publish (push) Skipped
2026-11-02 10:50:54 +03:00
omar 8336f01be7 feat: match identity and transfer settings with real category controls 2026-11-02 10:18:20 +03:00
omar a1f5e43f5f feat: add protected bookmark credentials and startup options 2026-11-02 09:49:29 +03:00
omar 7108026544 test: await persisted state and exercise expanded desktop panels 2026-11-01 22:16:17 +03:00
omar cf42de67e2 feat: add account-free settings and server management panels 2026-11-01 22:14:32 +03:00
omar 672540499c fix(i18n): match original Russian bookmark guidance 2026-11-01 19:54:54 +03:00
omar 33721aee7b fix(ui): match measured empty-chat prompt geometry
Use the actual 22px glyph and secondary-pane contrast background. Packaged dark/en captures at1553x998 and880x800 completed without harness errors; wide chat region passes. Whole-screen parity still fails bookmark/tree and narrow residuals.
2026-11-01 19:52:53 +03:00
omar ceecbb790a docs: record source parity evidence and remaining acceptance gaps
Document accumulated interoperability findings and current source-backed design. Record build-specific visual results, matched acceleration policy, passing packaged behavior checks, and explicit native/ARM and strict visual acceptance limits. No complete 1:1 claim.
2026-11-01 19:47:52 +03:00
omar e6464bc4ed feat: checkpoint account-free client workflows and source-matched UI
Preserve accumulated client implementation since v0.1.4, including local identities, multi-server state, chat, administration, audio and streaming controls. Refine official-source layout, original artwork, responsive composer overflow, settings navigation and chat scroll anchoring.

Current verification: Node suite passes; isolated packaged chat and responsive control smokes pass without device capture. Native core is reused, not rebuilt in this pass. Strict whole-screen visual parity remains incomplete; no 1:1 or cross-platform acceptance claim. Local checkpoint only; no release or push.
2026-11-01 19:43:18 +03:00
omar 0486ad361f v0.1.4 released: evidence, changelog date; vad tests assert window remainders and sensitivity decisions
ci / linux-x64 (push) Successful in 2m56s
ci / linux-arm64-cross (push) Successful in 4m2s
2026-10-24 10:07:25 +03:00
omar 4b1257a84d Evidence: 0.1.4 CI excerpts (x64, ARM64 qemu) and packaged Windows smokes from 0923b32
ci / linux-x64 (push) Successful in 4m32s
ci / linux-arm64-cross (push) Successful in 5m18s
2026-10-24 09:57:23 +03:00
omar 0923b32841 Transmit race tests: settle with setImmediate (fixture timers are unreferenced; Node 22 ended the loop)
ci / linux-x64 (push) Successful in 2m48s
ci / linux-arm64-cross (push) Successful in 2m48s
release / linux-arm64 (push) Successful in 6m21s
release / linux-x64 (push) Successful in 6m51s
release / appimage-startup (push) Successful in 14s
release / publish (push) Successful in 19s
2026-10-24 09:50:56 +03:00
omar 3d623329b3 Transmit mode: only the latest set_transmit answer counts; forwarding terminology; 0.1.4
ci / linux-x64 (push) Failing after 33s
ci / linux-arm64-cross (push) Successful in 3m8s
An older answer (same settings or a restarted core) could re-enable forwarding while a newer mode
change was pending. Requests and core restarts now start a new epoch. Renderer stats count frames
forwarded to the core. v0.1.3 was tagged but never released.
2026-10-24 09:45:49 +03:00
omar a924d792b4 VAD docs: startup buffer latency stated precisely; smoke-voice-vad --exe
ci / linux-arm64-cross (push) Successful in 2m48s
ci / linux-x64 (push) Successful in 2m53s
release / linux-arm64 (push) Successful in 4m15s
release / linux-x64 (push) Successful in 4m38s
release / appimage-startup (push) Successful in 15s
release / publish (push) Failing after 9s
2026-10-24 09:31:27 +03:00
omar b7951e0693 Voice activation (core voice detector, set_transmit handshake), transmission mode in Settings → Audio, atomic prefs commit, ARM64 unit tests under qemu; version 0.1.3
ci / linux-x64 (push) Successful in 2m50s
ci / linux-arm64-cross (push) Successful in 2m50s
2026-10-24 09:29:46 +03:00
omar 8439fe062e Evidence: v0.1.2 release, packaged 0.1.2 smokes, updater E2E logs (rc.1→rc.2, rc.2→0.1.2)
ci / linux-arm64-cross (push) Successful in 2m19s
ci / linux-x64 (push) Successful in 2m41s
2026-10-24 07:41:41 +03:00
omar 9e7483601b Updater harness: hash the pending update file; updater RC proof notes
ci / linux-arm64-cross (push) Successful in 2m18s
ci / linux-x64 (push) Successful in 3m20s
release / linux-arm64 (push) Successful in 4m12s
release / linux-x64 (push) Successful in 4m30s
release / appimage-startup (push) Successful in 14s
release / publish (push) Successful in 19s
2026-10-24 07:30:23 +03:00
omar f97a651c87 TeamsPeach 0.1.2
ci / linux-arm64-cross (push) Successful in 2m51s
ci / linux-x64 (push) Successful in 3m9s
2026-10-24 07:28:47 +03:00
omar 2cf63f5d88 Evidence: packaged 0.1.2-rc.2 (ed2e123) smokes
ci / linux-x64 (push) Successful in 3m3s
ci / linux-arm64-cross (push) Successful in 2m34s
2026-10-24 07:15:35 +03:00
omar ed2e123404 Release candidate 0.1.2-rc.2
ci / linux-x64 (push) Successful in 3m45s
ci / linux-arm64-cross (push) Successful in 2m50s
release / linux-arm64 (push) Successful in 4m8s
release / linux-x64 (push) Successful in 4m36s
release / appimage-startup (push) Successful in 13s
release / publish (push) Successful in 19s
2026-10-24 07:13:20 +03:00
omar 6b8994f1cb Use the application icon asset as the in-app brand mark; drop the old inline peach; smoke checks the decoded image
ci / linux-arm64-cross (push) Successful in 2m53s
ci / linux-x64 (push) Successful in 4m54s
2026-10-24 07:12:44 +03:00
omar d505890c74 Evidence: packaged 0.1.2-rc.1 (2a71d63) real-device, menu, theme and UI smokes
ci / linux-arm64-cross (push) Successful in 2m25s
ci / linux-x64 (push) Successful in 2m40s
release / linux-arm64 (push) Successful in 5m47s
release / linux-x64 (push) Successful in 6m57s
release / appimage-startup (push) Successful in 17s
release / publish (push) Successful in 20s
2026-10-24 07:09:08 +03:00
omar 2a71d63b7b Fail closed on a missing microphone, release partial capture setup, menus show enumeration failures; deterministic packaged smoke launch; NSIS custom-profile update guard 2026-10-24 07:07:05 +03:00
omar 7afce5ab20 Release candidate 0.1.2-rc.1
ci / linux-arm64-cross (push) Successful in 3m13s
ci / linux-x64 (push) Successful in 4m14s
2026-10-24 06:40:25 +03:00
omar 5f5d30d3ed i18n: final sweep, i18n smoke and evidence, docs/i18n.md
ci / linux-arm64-cross (push) Successful in 3m51s
ci / linux-x64 (push) Successful in 4m22s
2026-10-24 06:40:15 +03:00
omar 0fffb27166 Docs: English authored prose; 0.1.2 changelog (devices, menus, theme, language, updater, icon, identity fix)
ci / linux-arm64-cross (push) Successful in 1m52s
ci / linux-x64 (push) Successful in 2m43s
2026-10-24 06:36:56 +03:00
omar 1142c9f60d Updater from public releases, English UI by default with Russian selectable, cancelable capture, English technical messages, language-independent smoke hooks
ci / linux-arm64-cross (push) Successful in 1m54s
ci / linux-x64 (push) Successful in 2m45s
2026-10-24 06:34:33 +03:00
omar ba4c7ec2af core: decode stored keys with upstream's simple_asn1 shape plus scalar left-padding; deterministic and malformed-input tests 2026-10-24 06:18:41 +03:00
omar 456041bfde Dark theme by default (stored choices kept); updateChannel pref; new peach icon (transparent); packaged device evidence
ci / linux-arm64-cross (push) Successful in 2m29s
ci / linux-x64 (push) Successful in 3m11s
2026-10-24 06:13:08 +03:00
omar 41e90fb5e8 Device menus: loading shell, stale enumeration dropped; strict origin parsing; no automatic silence warning; core transmit state at debug
ci / linux-arm64-cross (push) Successful in 1m51s
ci / linux-x64 (push) Failing after 5m39s
2026-10-24 06:09:48 +03:00
omar 401c331aa4 Core 0.1.2 (zero-leading private key load fix); capture state in diagnostics; changelog
ci / linux-arm64-cross (push) Successful in 2m0s
ci / linux-x64 (push) Successful in 2m47s
2026-10-24 06:06:49 +03:00
omar 7ad5ee8572 Voice burst and PTT diagnostics only at TEAMSPEACH_LOG=debug 2026-10-24 06:06:20 +03:00
omar a3185229ee Audio devices: fix permission origin (app://teamspeach/), real device lists, right-click device menus, voice TX diagnostics; version 0.1.2 2026-10-24 06:05:46 +03:00
omar 8153e9b88b Evidence: v0.1.1 release (static AppImage runtime), v0.1.0 marked superseded
ci / linux-arm64-cross (push) Successful in 2m13s
ci / linux-x64 (push) Successful in 2m34s
2026-10-24 05:01:13 +03:00
omar 71300ff061 0.1.1: static AppImage runtime (toolset appimage 1.0.3); core version 0.1.1
ci / linux-arm64-cross (push) Successful in 1m49s
ci / linux-x64 (push) Successful in 2m59s
release / linux-x64 (push) Successful in 4m23s
release / linux-arm64 (push) Successful in 4m28s
release / appimage-startup (push) Successful in 14s
release / publish (push) Successful in 19s
2026-10-24 04:44:22 +03:00
omar 7c9616f0bb Release gate: AppImage runtime must start in a slim container (x64 native, arm64 qemu)
ci / linux-arm64-cross (push) Successful in 3m52s
ci / linux-x64 (push) Successful in 4m29s
2026-10-24 04:37:21 +03:00
omar 4d144a581e Evidence: public switch verified anonymously
ci / linux-arm64-cross (push) Successful in 3m46s
ci / linux-x64 (push) Successful in 4m10s
2026-10-24 04:31:25 +03:00
omar 8f5d8c9e10 Public-repo CI policy (no pull_request trigger), visibility audit, v0.1.0 release evidence
ci / linux-arm64-cross (push) Successful in 3m57s
ci / linux-x64 (push) Successful in 4m32s
2026-10-24 04:31:15 +03:00
1600 changed files with 978171 additions and 13195 deletions

No files matched your search

+3
View File
@@ -12,3 +12,6 @@ LIBOPUS_NO_PKG = "1"
# with Windows 10+ (no VCRUNTIME140.dll). cc/cmake-rs see `crt-static` and build libopus with /MT.
[target.x86_64-pc-windows-msvc]
rustflags = ["-C", "target-feature=+crt-static"]
[target.aarch64-pc-windows-msvc]
rustflags = ["-C", "target-feature=+crt-static"]
+3
View File
@@ -0,0 +1,3 @@
# Native dependency recipes verify exact source bytes on every build host.
native/patches/** text eol=lf
xtask/src/*.rs text eol=lf
+167
View File
@@ -0,0 +1,167 @@
# Trusted manual runs only, on an administrator-provisioned Linux x64 runner.
# This job never installs host tools, signs production packages, publishes, or uses a device.
name: android-ci
on:
workflow_dispatch:
permissions:
contents: read
defaults:
run:
shell: bash
working-directory: ${{ github.workspace }}/android-${{ github.run_id }}
jobs:
android-arm64:
runs-on: teamspeach-android-linux-x64
env:
CARGO_TERM_COLOR: never
TARGET: aarch64-linux-android
EXPECTED_REVISION: ${{ github.sha }}
CI_RUN_ID: ${{ github.run_id }}
CARGO_TARGET_DIR: ${{ github.workspace }}/android-${{ github.run_id }}/target
GRADLE_USER_HOME: ${{ github.workspace }}/android-${{ github.run_id }}/.gradle-ci
ANDROID_HOME: ${{ vars.ANDROID_SDK_ROOT }}
ANDROID_SDK_ROOT: ${{ vars.ANDROID_SDK_ROOT }}
JAVA_HOME: ${{ vars.ANDROID_JAVA_HOME }}
LLVM_HOME: ${{ vars.NATIVE_LLVM_HOME }}
LIBCLANG_PATH: ${{ vars.NATIVE_LIBCLANG_PATH }}
SKIA_SOURCE_DIR: ${{ vars.NATIVE_SKIA_SOURCE_DIR }}
TEAMSPEACH_GRADLE_DISTRIBUTION: ${{ vars.ANDROID_GRADLE_DISTRIBUTION }}
TEAMSPEACH_BUNDLETOOL: ${{ vars.ANDROID_BUNDLETOOL }}
steps:
- uses: actions/checkout@v4
with:
path: android-${{ github.run_id }}
clean: true
persist-credentials: false
- name: Require provisioned Linux Android tools (no host installation)
run: |
set -euo pipefail
test "$(uname -s)" = Linux
test "$(uname -m)" = x86_64
test "$(git rev-parse HEAD)" = "$EXPECTED_REVISION"
: "${ANDROID_SDK_ROOT:?set ANDROID_SDK_ROOT to installed SDK36 with build-tools/36.0.0 and NDK28.2.13676358}"
: "${JAVA_HOME:?set ANDROID_JAVA_HOME to installed JDK17+ (JDK21 is supported)}"
: "${LLVM_HOME:?set NATIVE_LLVM_HOME to installed LLVM}"
: "${LIBCLANG_PATH:?set NATIVE_LIBCLANG_PATH to the matching libclang directory}"
: "${SKIA_SOURCE_DIR:?set NATIVE_SKIA_SOURCE_DIR to a dependency-synchronized Skia checkout}"
: "${TEAMSPEACH_GRADLE_DISTRIBUTION:?set ANDROID_GRADLE_DISTRIBUTION to local gradle-8.14.3-bin.zip}"
: "${TEAMSPEACH_BUNDLETOOL:?set ANDROID_BUNDLETOOL to local bundletool.jar}"
export ANDROID_NDK_ROOT="$ANDROID_SDK_ROOT/ndk/28.2.13676358"
export ANDROID_NDK_HOME="$ANDROID_NDK_ROOT"
export PATH="$JAVA_HOME/bin:$LLVM_HOME/bin:$ANDROID_SDK_ROOT/build-tools/36.0.0:$PATH"
for tool in cargo rustc rustup git cmake ninja python3 pkg-config clang clang++ ar llvm-strip llvm-readelf java javac jar keytool jarsigner sh zipalign aapt2 apksigner; do
command -v "$tool"
done
test -f "$ANDROID_SDK_ROOT/platforms/android-36/android.jar"
test -f "$ANDROID_NDK_ROOT/source.properties"
test -x "$ANDROID_NDK_ROOT/toolchains/llvm/prebuilt/linux-x86_64/bin/aarch64-linux-android26-clang"
test -f "$SKIA_SOURCE_DIR/BUILD.gn"
test -x "$SKIA_SOURCE_DIR/bin/gn"
test -d "$SKIA_SOURCE_DIR/third_party/externals"
test -f "$TEAMSPEACH_BUNDLETOOL"
test -d "$(rustc --print target-libdir --target "$TARGET")"
# A clean checkout and run-specific Cargo/Gradle/output trees prevent stale
# packages or dependency receipts from another job/revision being selected.
test ! -e target
test ! -e dist/android
test ! -e .gradle-ci
python3 - <<'PY'
import hashlib, os, pathlib, re, subprocess
ndk = pathlib.Path(os.environ['ANDROID_NDK_ROOT'], 'source.properties').read_text()
assert re.search(r'^Pkg\.Revision\s*=\s*28\.2\.13676358\s*$', ndk, re.M), 'NDK must match Gradle ndkVersion'
java = subprocess.check_output(['java', '-version'], stderr=subprocess.STDOUT, text=True)
assert int(re.search(r'version "(\d+)', java)[1]) >= 17, 'JDK17+ is required'
assert list(pathlib.Path(os.environ['LIBCLANG_PATH']).glob('libclang.so*')), 'matching LLVM libclang.so is required'
properties = pathlib.Path('platform/android/gradle/wrapper/gradle-wrapper.properties').read_text()
expected = re.search(r'^distributionSha256Sum=(\w+)$', properties, re.M)[1]
with open(os.environ['TEAMSPEACH_GRADLE_DISTRIBUTION'], 'rb') as source:
digest = hashlib.sha256()
for chunk in iter(lambda: source.read(1024 * 1024), b''):
digest.update(chunk)
assert digest.hexdigest() == expected, 'local Gradle zip checksum mismatch'
# No signing configuration is consumed from a dedicated runner's environment.
for name in ('TEAMSPEACH_ANDROID_KEYSTORE', 'TEAMSPEACH_ANDROID_STORE_PASSWORD', 'TEAMSPEACH_ANDROID_KEY_ALIAS', 'TEAMSPEACH_ANDROID_KEY_PASSWORD'):
assert name not in os.environ, 'remove production signing environment from this unsigned runner'
PY
echo "ANDROID_NDK_ROOT=$ANDROID_NDK_ROOT" >> "$GITHUB_ENV"
echo "ANDROID_NDK_HOME=$ANDROID_NDK_HOME" >> "$GITHUB_ENV"
echo "$JAVA_HOME/bin" >> "$GITHUB_PATH"
echo "$LLVM_HOME/bin" >> "$GITHUB_PATH"
echo "$ANDROID_SDK_ROOT/build-tools/36.0.0" >> "$GITHUB_PATH"
echo "SKIA_GN_COMMAND=$SKIA_SOURCE_DIR/bin/gn" >> "$GITHUB_ENV"
echo "SKIA_NINJA_COMMAND=$(command -v ninja)" >> "$GITHUB_ENV"
- name: Check workspace version and packaging behavior
run: |
set -euo pipefail
cargo run --locked -p xtask -- check-version
cargo test --locked -p xtask
- name: Build pinned Android WebRTC from source on Linux
run: cargo run --locked -p xtask -- deps --target "$TARGET" --llvm-dir "$LLVM_HOME"
- name: Build and verify harness first, then unsigned production (full Skia + WebRTC)
run: |
set -euo pipefail
for variant in harness production; do
if [ "$variant" = harness ]; then harness=true; else harness=false; fi
out="dist/android/$variant"
cargo run --locked -p xtask -- build --target "$TARGET" --llvm-dir "$LLVM_HOME" --skia-source "$SKIA_SOURCE_DIR" --test-harness "$harness"
# Explicit online dependency resolution supports a fresh Gradle cache.
# Bootstrap still requires the local checksum-pinned zip; SDK downloads stay disabled.
cargo run --locked -p xtask -- package --target "$TARGET" --out "$out" --test-harness "$harness" --gradle-online true
cargo run --locked -p xtask -- verify-package --target "$TARGET" --out "$out" --test-harness "$harness"
cp "$CARGO_TARGET_DIR/$TARGET/release/native-build.json" "$out/$TARGET/native-build.json"
cp native/native-deps.lock.json "$out/$TARGET/native-deps.lock.json"
cp "target/native-deps/$TARGET/provenance.json" "$out/$TARGET/dependency-provenance.json"
python3 - "$out" "$harness" <<'PY'
import hashlib, json, os, pathlib, subprocess, sys
out = pathlib.Path(sys.argv[1])
harness = sys.argv[2] == 'true'
target = os.environ['TARGET']
revision = subprocess.check_output(['git', 'rev-parse', 'HEAD'], text=True).strip()
assert revision == os.environ['EXPECTED_REVISION'], 'checkout revision changed'
receipt = json.loads((out / target / 'package-report.json').read_text())
verification = json.loads((out / target / 'verification.json').read_text())
assert receipt['testOnly'] == harness and receipt['sourceBuild']['testHarness'] == harness
assert verification['passed'] is True
assert {a['kind'] for a in receipt['artifacts']} == ({'apk'} if harness else {'apk', 'aab'})
assert all(a['signing'] == ('android-debug-test' if harness else 'unsigned-not-installable') and not a['release_eligible'] for a in receipt['artifacts'])
files = [out / a['name'] for a in receipt['artifacts']]
files += [out / target / name for name in ('package-report.json', 'verification.json', 'native-build.json', 'native-deps.lock.json', 'dependency-provenance.json')]
hashes = {}
for path in files:
with path.open('rb') as source:
digest = hashlib.sha256()
for chunk in iter(lambda: source.read(1024 * 1024), b''):
digest.update(chunk)
hashes[str(path.relative_to(out))] = digest.hexdigest()
(out / 'build-info.json').write_text(json.dumps({'schema': 1, 'revision': revision, 'run_id': os.environ['CI_RUN_ID'], 'target': target, 'testHarness': harness, 'gradleOnline': True, 'deviceAcceptance': 'not exercised', 'publicationAuthorized': False, 'sha256': hashes}, indent=2) + '\n')
PY
done
- name: Retain installable test-only ARM64 harness and exact receipts
uses: actions/upload-artifact@v3
with:
name: android-harness-arm64
path: |
android-${{ github.run_id }}/dist/android/harness/*-harness-test.apk
android-${{ github.run_id }}/dist/android/harness/build-info.json
android-${{ github.run_id }}/dist/android/harness/aarch64-linux-android/*.json
if-no-files-found: error
- name: Retain unsigned production ARM64 APK and store AAB (not installable)
uses: actions/upload-artifact@v3
with:
name: android-production-unsigned-arm64
path: |
android-${{ github.run_id }}/dist/android/production/*-unsigned.apk
android-${{ github.run_id }}/dist/android/production/*-unsigned.aab
android-${{ github.run_id }}/dist/android/production/build-info.json
android-${{ github.run_id }}/dist/android/production/aarch64-linux-android/*.json
if-no-files-found: error
+61 -80
View File
@@ -1,109 +1,90 @@
# Continuous integration on the self-hosted Gitea runner (Linux x64 container jobs).
# Everything runs inside the job container; nothing is installed on the runner host.
name: ci
# Trusted pushes/manual runs only: public pull requests must not execute on private runners.
# Runner administrators provision the native SDKs/tools; jobs never install on the host.
name: native-ci
on:
push:
branches: [main]
pull_request:
workflow_dispatch:
permissions:
contents: read
defaults:
run:
shell: bash
jobs:
linux-x64:
runs-on: ubuntu-latest
container:
image: node:22-bookworm
native-linux:
strategy:
fail-fast: false
matrix:
include:
- target: x86_64-unknown-linux-gnu
runner: teamspeach-native-linux-x64
- target: aarch64-unknown-linux-gnu
runner: teamspeach-native-linux-arm64
runs-on: ${{ matrix.runner }}
env:
CARGO_TERM_COLOR: never
CARGO_BUILD_JOBS: "2"
TARGET: ${{ matrix.target }}
LLVM_HOME: ${{ vars.NATIVE_LLVM_HOME }}
SKIA_SOURCE_DIR: ${{ vars.NATIVE_SKIA_SOURCE_DIR }}
LIBCLANG_PATH: ${{ vars.NATIVE_LIBCLANG_PATH }}
LK_CUSTOM_WEBRTC: ${{ github.workspace }}/target/native-deps/${{ matrix.target }}/webrtc
steps:
- uses: actions/checkout@v4
- name: System packages (container only)
- name: Require explicitly provisioned source and native tools
run: |
apt-get update
apt-get install -y --no-install-recommends build-essential cmake curl ca-certificates git \
xvfb xauth libnss3 libatk1.0-0 libatk-bridge2.0-0 libcups2 libdrm2 libgbm1 libgtk-3-0 \
libasound2 libxss1 libxshmfence1 libxkbcommon0 libxcomposite1 libxdamage1 libxrandr2 libpango-1.0-0
set -euo pipefail
: "${LLVM_HOME:?set NATIVE_LLVM_HOME to installed LLVM}"
: "${LIBCLANG_PATH:?set NATIVE_LIBCLANG_PATH to the libclang directory}"
: "${SKIA_SOURCE_DIR:?set NATIVE_SKIA_SOURCE_DIR to a dependency-synchronized Skia checkout}"
test -x "$LLVM_HOME/bin/clang"
test -f "$SKIA_SOURCE_DIR/BUILD.gn"
test -x "$SKIA_SOURCE_DIR/bin/gn"
echo "$LLVM_HOME/bin" >> "$GITHUB_PATH"
command -v cargo
command -v cmake
command -v ninja
command -v python3
command -v xvfb-run
command -v dbus-run-session
echo "SKIA_GN_COMMAND=$SKIA_SOURCE_DIR/bin/gn" >> "$GITHUB_ENV"
echo "SKIA_NINJA_COMMAND=$(command -v ninja)" >> "$GITHUB_ENV"
- name: Rust toolchain
run: |
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --profile minimal --default-toolchain stable
echo "$HOME/.cargo/bin" >> "$GITHUB_PATH"
- name: Native version gate
run: cargo run --locked -p xtask -- check-version
- name: glibc baseline
run: ldd --version | sed -n 1p
- name: Gitea transport unit tests (mocked HTTP, no publication)
run: python3 -m unittest discover -s xtask -p test_publish_release.py
- name: Node dependencies
run: npm ci
- name: Provision pinned WebRTC sources and archive
run: cargo run --locked -p xtask -- deps --target "$TARGET" --llvm-dir "$LLVM_HOME" --jobs "$CARGO_BUILD_JOBS"
- name: Unit tests (desktop)
run: npm test
- name: Build full native app and update helper (Skia + WebRTC defaults)
run: cargo run --locked -p xtask -- build --target "$TARGET" --llvm-dir "$LLVM_HOME" --skia-source "$SKIA_SOURCE_DIR" --jobs "$CARGO_BUILD_JOBS"
- name: Core tests
run: cargo test --manifest-path core/Cargo.toml --locked
- name: Rust workspace tests on matching native architecture
run: cargo test --locked --workspace --target "$TARGET" --jobs "$CARGO_BUILD_JOBS"
- name: Core release build
run: cargo build --manifest-path core/Cargo.toml --release --locked
- name: Build explicit native test harness
run: cargo run --locked -p xtask -- build --target "$TARGET" --llvm-dir "$LLVM_HOME" --skia-source "$SKIA_SOURCE_DIR" --jobs "$CARGO_BUILD_JOBS" --test-harness true
- name: Core binary architecture
run: node scripts/binary-arch.mjs core/target/release/teamspeach-core --expect linux-x64
- name: Native offline UI smoke (not updater end-to-end acceptance)
run: dbus-run-session -- xvfb-run -a cargo run --locked -p xtask -- smoke --target "$TARGET" --scenario offline-ui --out "native-smoke-$TARGET"
- name: Core identity smoke (stdio, offline)
run: node scripts/core-smoke.mjs core/target/release/teamspeach-core
- name: Native historical profile migration smoke
run: dbus-run-session -- xvfb-run -a cargo run --locked -p xtask -- smoke --target "$TARGET" --scenario migration --out "native-migration-$TARGET"
- name: Electron UI smoke (Xvfb, offline, disposable profile)
env:
TEAMSPEACH_SMOKE_EXTRA_ARGS: --no-sandbox
run: xvfb-run -a node scripts/smoke-ui.mjs --out smoke-out
- name: Upload smoke evidence
- name: Upload measured native smoke evidence
if: always()
uses: actions/upload-artifact@v3
with:
name: ci-smoke-linux-x64
path: smoke-out/
if-no-files-found: ignore
linux-arm64-cross:
runs-on: ubuntu-latest
container:
image: node:22-bookworm
env:
CARGO_TERM_COLOR: never
CARGO_BUILD_JOBS: "2"
CARGO_TARGET_AARCH64_UNKNOWN_LINUX_GNU_LINKER: aarch64-linux-gnu-gcc
CC_aarch64_unknown_linux_gnu: aarch64-linux-gnu-gcc
CXX_aarch64_unknown_linux_gnu: aarch64-linux-gnu-g++
AR_aarch64_unknown_linux_gnu: aarch64-linux-gnu-ar
steps:
- uses: actions/checkout@v4
- name: Cross toolchain and user-mode emulator (container only, no binfmt)
run: |
apt-get update
apt-get install -y --no-install-recommends build-essential cmake curl ca-certificates git \
gcc-aarch64-linux-gnu g++-aarch64-linux-gnu libc6-dev-arm64-cross qemu-user
- name: Rust toolchain
run: |
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --profile minimal --default-toolchain stable --target aarch64-unknown-linux-gnu
echo "$HOME/.cargo/bin" >> "$GITHUB_PATH"
- name: Core cross build (aarch64-unknown-linux-gnu)
run: cargo build --manifest-path core/Cargo.toml --release --locked --target aarch64-unknown-linux-gnu
- name: Core binary architecture
run: node scripts/binary-arch.mjs core/target/aarch64-unknown-linux-gnu/release/teamspeach-core --expect linux-arm64
- name: Required glibc symbols
run: aarch64-linux-gnu-objdump -T core/target/aarch64-unknown-linux-gnu/release/teamspeach-core | grep -o 'GLIBC_[0-9.]*' | sort -Vu | tail -n1
- name: 16 KiB page compatibility (Asahi) of the core ELF
run: node scripts/elf-pagesize.mjs core/target/aarch64-unknown-linux-gnu/release/teamspeach-core --page 16384
- name: Core identity smoke under qemu-aarch64 (emulated, not native hardware)
run: node scripts/core-smoke.mjs core/target/aarch64-unknown-linux-gnu/release/teamspeach-core --wrapper "qemu-aarch64 -L /usr/aarch64-linux-gnu"
name: native-ci-${{ matrix.target }}
path: |
native-smoke-${{ matrix.target }}/
native-migration-${{ matrix.target }}/
if-no-files-found: warn
+105 -138
View File
@@ -1,8 +1,7 @@
# Release builds on the self-hosted Gitea runner (Linux x64 job containers).
# - workflow_dispatch: build + verify packages, keep them as run artifacts (no release).
# - tag v*: same, then publish a Gitea release with the packages, only if every build job succeeded.
# Windows x64 packages are built on a Windows machine and attached separately (see README).
name: release
# Trusted tag pushes publish only after both native architectures and release assembly pass.
# Manual dispatch builds/verifies and retains artifacts without publication.
# These labels require preprovisioned matching-ISA native runners (no emulated acceptance).
name: native-release
on:
push:
@@ -17,170 +16,138 @@ defaults:
shell: bash
jobs:
linux-x64:
runs-on: ubuntu-latest
container:
image: node:22-bookworm
native-linux:
strategy:
fail-fast: false
matrix:
include:
- target: x86_64-unknown-linux-gnu
runner: teamspeach-native-linux-x64
- target: aarch64-unknown-linux-gnu
runner: teamspeach-native-linux-arm64
runs-on: ${{ matrix.runner }}
env:
CARGO_TERM_COLOR: never
CARGO_BUILD_JOBS: "2"
TARGET: ${{ matrix.target }}
LLVM_HOME: ${{ vars.NATIVE_LLVM_HOME }}
SKIA_SOURCE_DIR: ${{ vars.NATIVE_SKIA_SOURCE_DIR }}
LIBCLANG_PATH: ${{ vars.NATIVE_LIBCLANG_PATH }}
LK_CUSTOM_WEBRTC: ${{ github.workspace }}/target/native-deps/${{ matrix.target }}/webrtc
steps:
- uses: actions/checkout@v4
- name: Version gate (tag = package.json = core/Cargo.toml)
run: node scripts/check-version.mjs
- name: System packages (container only)
- name: Require explicit native source/tool provisioning
run: |
set -euo pipefail
apt-get update
apt-get install -y --no-install-recommends build-essential cmake curl ca-certificates git \
xvfb xauth libnss3 libatk1.0-0 libatk-bridge2.0-0 libcups2 libdrm2 libgbm1 libgtk-3-0 \
libasound2 libxss1 libxshmfence1 libxkbcommon0 libxcomposite1 libxdamage1 libxrandr2 libpango-1.0-0
: "${LLVM_HOME:?set NATIVE_LLVM_HOME to installed LLVM}"
: "${LIBCLANG_PATH:?set NATIVE_LIBCLANG_PATH to the libclang directory}"
: "${SKIA_SOURCE_DIR:?set NATIVE_SKIA_SOURCE_DIR to a dependency-synchronized Skia checkout}"
test -x "$LLVM_HOME/bin/clang"
test -f "$SKIA_SOURCE_DIR/BUILD.gn"
test -x "$SKIA_SOURCE_DIR/bin/gn"
echo "$LLVM_HOME/bin" >> "$GITHUB_PATH"
for tool in cargo cmake ninja python3 xvfb-run dbus-run-session linuxdeploy appimagetool unsquashfs llvm-readelf; do
command -v "$tool"
done
echo "SKIA_GN_COMMAND=$SKIA_SOURCE_DIR/bin/gn" >> "$GITHUB_ENV"
echo "SKIA_NINJA_COMMAND=$(command -v ninja)" >> "$GITHUB_ENV"
- name: Rust toolchain
- name: Tag must match native workspace version
run: cargo run --locked -p xtask -- check-version
- name: Provision pinned WebRTC sources and archive
run: cargo run --locked -p xtask -- deps --target "$TARGET" --llvm-dir "$LLVM_HOME" --jobs "$CARGO_BUILD_JOBS"
- name: Rust workspace tests on matching native architecture
run: cargo test --locked --workspace --target "$TARGET" --jobs "$CARGO_BUILD_JOBS"
- name: Build explicit native smoke harness with default Skia and WebRTC
run: cargo run --locked -p xtask -- build --target "$TARGET" --llvm-dir "$LLVM_HOME" --skia-source "$SKIA_SOURCE_DIR" --jobs "$CARGO_BUILD_JOBS" --test-harness true
- name: Native offline UI and historical profile migration smoke
run: |
set -euo pipefail
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --profile minimal --default-toolchain stable
echo "$HOME/.cargo/bin" >> "$GITHUB_PATH"
dbus-run-session -- xvfb-run -a cargo run --locked -p xtask -- smoke --target "$TARGET" --scenario offline-ui --out "native-smoke-$TARGET"
dbus-run-session -- xvfb-run -a cargo run --locked -p xtask -- smoke --target "$TARGET" --scenario migration --out "native-migration-$TARGET"
- name: Tests
- name: Rebuild production native app and update helper (no test harness)
run: cargo run --locked -p xtask -- build --target "$TARGET" --llvm-dir "$LLVM_HOME" --skia-source "$SKIA_SOURCE_DIR" --jobs "$CARGO_BUILD_JOBS"
- name: Package and inspect real native archive payloads
run: |
set -euo pipefail
npm ci
npm test
cargo test --manifest-path core/Cargo.toml --locked
cargo run --locked -p xtask -- package --target "$TARGET" --out dist/native
cargo run --locked -p xtask -- verify-package --target "$TARGET" --out dist/native
cp native/native-deps.lock.json "dist/native/$TARGET/native-deps.lock.json"
- name: Core release build and checks
run: |
set -euo pipefail
cargo build --manifest-path core/Cargo.toml --release --locked
node scripts/binary-arch.mjs core/target/release/teamspeach-core --expect linux-x64
node scripts/core-smoke.mjs core/target/release/teamspeach-core
- name: Electron UI smoke (Xvfb, offline)
env:
TEAMSPEACH_SMOKE_EXTRA_ARGS: --no-sandbox
run: xvfb-run -a node scripts/smoke-ui.mjs --out smoke-out
- name: Package
run: node scripts/dist.mjs --os linux --arch x64
- name: Package report (ELF layout of every packaged binary incl. the AppImage runtime)
run: |
set -euo pipefail
report=dist/build-info-linux-x64.txt
# sed consumes all input, so ldd never gets SIGPIPE under pipefail (head -n1 caused exit 141).
ldd --version | sed -n 1p > "$report"
git rev-parse HEAD >> "$report"
node scripts/elf-pagesize.mjs dist/linux-unpacked dist/TeamsPeach-*.AppImage --page 4096 --json dist/elf-report-linux-x64.json > elf.txt
cat elf.txt >> "$report"
sha256sum dist/*.AppImage dist/*.tar.gz >> "$report"
cat "$report"
- uses: actions/upload-artifact@v3
- name: Upload native release bundle and exact provisioning receipt
uses: actions/upload-artifact@v3
with:
name: teamspeach-linux-x64
name: teamspeach-native-${{ matrix.target }}
path: |
dist/*.AppImage
dist/*.tar.gz
dist/build-info-linux-x64.txt
dist/elf-report-linux-x64.json
dist/native/TeamsPeach-*.AppImage
dist/native/TeamsPeach-*.tar.gz
dist/native/*.yml
dist/native/native-manifest.json
dist/native/${{ matrix.target }}/package-report.json
dist/native/${{ matrix.target }}/verification.json
dist/native/${{ matrix.target }}/native-deps.lock.json
if-no-files-found: error
linux-arm64:
runs-on: ubuntu-latest
container:
image: node:22-bookworm
env:
CARGO_TERM_COLOR: never
CARGO_BUILD_JOBS: "2"
CARGO_TARGET_AARCH64_UNKNOWN_LINUX_GNU_LINKER: aarch64-linux-gnu-gcc
CC_aarch64_unknown_linux_gnu: aarch64-linux-gnu-gcc
CXX_aarch64_unknown_linux_gnu: aarch64-linux-gnu-g++
AR_aarch64_unknown_linux_gnu: aarch64-linux-gnu-ar
- name: Upload measured native smoke evidence
if: always()
uses: actions/upload-artifact@v3
with:
name: native-release-smoke-${{ matrix.target }}
path: |
native-smoke-${{ matrix.target }}/
native-migration-${{ matrix.target }}/
if-no-files-found: warn
assemble:
needs: [native-linux]
runs-on: teamspeach-native-linux-x64
steps:
- uses: actions/checkout@v4
- name: Version gate (tag = package.json = core/Cargo.toml)
run: node scripts/check-version.mjs
- name: Cross toolchain and user-mode emulator (container only, no binfmt)
run: |
set -euo pipefail
apt-get update
apt-get install -y --no-install-recommends build-essential cmake curl ca-certificates git \
gcc-aarch64-linux-gnu g++-aarch64-linux-gnu libc6-dev-arm64-cross qemu-user
- name: Rust toolchain
run: |
set -euo pipefail
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --profile minimal --default-toolchain stable --target aarch64-unknown-linux-gnu
echo "$HOME/.cargo/bin" >> "$GITHUB_PATH"
- name: Core cross build and checks
run: |
set -euo pipefail
cargo build --manifest-path core/Cargo.toml --release --locked --target aarch64-unknown-linux-gnu
node scripts/binary-arch.mjs core/target/aarch64-unknown-linux-gnu/release/teamspeach-core --expect linux-arm64
node scripts/elf-pagesize.mjs core/target/aarch64-unknown-linux-gnu/release/teamspeach-core --page 16384
node scripts/core-smoke.mjs core/target/aarch64-unknown-linux-gnu/release/teamspeach-core --wrapper "qemu-aarch64 -L /usr/aarch64-linux-gnu"
- name: Package
run: |
set -euo pipefail
npm ci
node scripts/dist.mjs --os linux --arch arm64
- name: 16 KiB page check of every packaged ELF incl. the AppImage runtime (Asahi)
run: |
set -euo pipefail
report=dist/build-info-linux-arm64.txt
echo "glibc of build sysroot: $(dpkg-query -W -f='${Version}' libc6-dev-arm64-cross)" > "$report"
git rev-parse HEAD >> "$report"
node scripts/elf-pagesize.mjs dist/linux-arm64-unpacked dist/TeamsPeach-*-arm64.AppImage --page 16384 --json dist/elf-report-linux-arm64.json > elf.txt
cat elf.txt >> "$report"
sha256sum dist/*.AppImage dist/*.tar.gz >> "$report"
cat "$report"
- uses: actions/download-artifact@v3
with:
name: teamspeach-native-x86_64-unknown-linux-gnu
path: artifacts/teamspeach-native-x86_64-unknown-linux-gnu
- uses: actions/download-artifact@v3
with:
name: teamspeach-native-aarch64-unknown-linux-gnu
path: artifacts/teamspeach-native-aarch64-unknown-linux-gnu
- name: Gitea transport unit tests (mocked HTTP, no publication)
run: python3 -m unittest discover -s xtask -p test_publish_release.py
- name: Merge strict native manifests and recheck every package digest
run: cargo run --locked -p xtask -- prepare-release --out artifacts
- uses: actions/upload-artifact@v3
with:
name: teamspeach-linux-arm64
path: |
dist/*.AppImage
dist/*.tar.gz
dist/build-info-linux-arm64.txt
dist/elf-report-linux-arm64.json
name: native-release-manifest
path: artifacts/native-manifest.json
if-no-files-found: error
publish:
needs: [linux-x64, linux-arm64]
needs: [native-linux, assemble]
if: startsWith(github.ref, 'refs/tags/v')
runs-on: ubuntu-latest
container:
image: node:22-bookworm
runs-on: teamspeach-native-linux-x64
permissions:
contents: write
steps:
- uses: actions/checkout@v4
- uses: actions/download-artifact@v3
with:
path: artifacts
- name: Publish release (draft → upload all → publish)
name: teamspeach-native-x86_64-unknown-linux-gnu
path: artifacts/teamspeach-native-x86_64-unknown-linux-gnu
- uses: actions/download-artifact@v3
with:
name: teamspeach-native-aarch64-unknown-linux-gnu
path: artifacts/teamspeach-native-aarch64-unknown-linux-gnu
- name: Validate packages, create draft, upload, verify remote hashes, publish
env:
TOKEN: ${{ secrets.GITEA_TOKEN }}
API: ${{ github.server_url }}/api/v1/repos/${{ github.repository }}
TAG: ${{ github.ref_name }}
run: |
set -euo pipefail
node scripts/check-version.mjs
cat > notes.md <<'EOF'
Linux x64 и Linux ARM64 (aarch64) собраны в CI: тесты, офлайн-проверка ядра, проверка выравнивания ELF
(для ARM64 — страницы 16 КиБ, включая загрузчик AppImage), см. build-info-*.txt.
ARM64 проверен статически и под qemu, не на Apple Silicon. Пакеты не подписаны.
Сборка Windows x64 собирается на машине разработчика из того же коммита и прикладывается отдельно
с пометкой local.
EOF
node scripts/publish-release.mjs artifacts notes.md
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
GITHUB_REF: ${{ github.ref }}
GITHUB_SERVER_URL: ${{ github.server_url }}
GITHUB_REPOSITORY: ${{ github.repository }}
run: cargo run --locked -p xtask -- publish-release --out artifacts
+7 -2
View File
@@ -1,7 +1,12 @@
# dependencies and build output
node_modules/
# Understand analysis intermediates are local; publish only the durable graph and baseline.
.ua/tmp/
.ua/.trash-*/
.ua/intermediate/*
!.ua/intermediate/scan-result.json
dist/
core-bin/
# Native Cargo artifacts
target/
core/target/
# local runtime data, logs and identities
+98
View File
@@ -0,0 +1,98 @@
{
"schemaVersion": 2,
"generatedAt": "2026-11-01",
"title": "Design System: TeamsPeach",
"extensions": {
"shadows": [
{ "name": "context-menu", "value": "1px 1px 2px 0 rgba(0, 0, 0, 0.2)", "purpose": "Official .ts-context-menu shadow; menus, device menus and composer submenus." },
{ "name": "notification", "value": "#000 4px 8px 5px 0 at opacity .25", "purpose": "Official .ts-notification ::after plate shadow for toasts." }
],
"motion": [
{ "name": "tree-pill", "value": "150ms ease-out (32ms while hovered)", "purpose": "Channel pill growth from 7/10 to 4/7 insets." },
{ "name": "action-magnify", "value": "100ms ease-out scale(1.15)", "purpose": "Toolbar and status-bar icon hover." },
{ "name": "stream-controls", "value": "opacity 120ms, transform 80ms", "purpose": "Stream tile control bar reveal." },
{ "name": "toast-entrance", "value": "180ms cubic-bezier(0.16, 1, 0.3, 1)", "purpose": "Single toast entrance; disabled with reduced motion." }
],
"breakpoints": [
{ "name": "pane-compressed", "value": "440px", "purpose": "Official tsv-view-size-category-h-compressed: 10px side padding." },
{ "name": "settings-in-sidebar", "value": "900px", "purpose": "The same settings categories node moves into sidebar resources below this width." },
{ "name": "sidebar-collapse", "value": "200px", "purpose": "Sidebar slot snaps to the 62px rail below this width." }
],
"slots": {
"sidebar": "270px default, 420 max, 52/62/72px rail for Small/Medium/Large",
"server": "500px default, 220 min",
"detail": "flexible, 295 min"
},
"source": "TeamSpeak 6.0.0.5163 installed client: main.css sha256 bc700401d04954d0…, main.js sha256 9d6bea2ee5333086…; extracted values in docs/evidence/official-parity/."
},
"components": [
{
"name": "Filled action",
"kind": "button",
"refersTo": "button-filled",
"description": "Official .tsv-button-filled: blue gradient pill for the primary action.",
"html": "<button class=\"ds-filled\">Connect</button>",
"css": ".ds-filled{font:450 15px/22px 'Noto Sans',sans-serif;padding:4px 20px;min-height:26px;border:0;border-radius:100px;background:linear-gradient(60deg,#0058FF,#1365BB);color:#fff;cursor:pointer}.ds-filled:hover{background:#1c82cc}.ds-filled:focus-visible{outline:2px solid #1588FA;outline-offset:2px}.ds-filled:disabled{opacity:.4;cursor:default}"
},
{
"name": "Toolbar pill",
"kind": "toolbar",
"description": "Official central toolbar: 26px pill on --tsv-bg, icon buttons split by 1px strong-bg lines.",
"html": "<div class=\"ds-pill\"><button aria-label=\"Microphone\"><svg width=\"22\" height=\"22\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"1.7\"><rect x=\"9\" y=\"3\" width=\"6\" height=\"11\" rx=\"3\"/><path d=\"M5.5 11a6.5 6.5 0 0 0 13 0M12 17.5V21\"/></svg></button><button aria-label=\"Speakers\"><svg width=\"22\" height=\"22\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"1.7\"><path d=\"M4.5 9.5v5h3.8l4.7 4V5.5l-4.7 4z\"/></svg></button></div>",
"css": ".ds-pill{display:inline-flex;height:26px;padding:0 20px 0 10px;border-radius:100px;background:#2b3346}.ds-pill button{position:relative;padding:0 10px 0 0;border:0;background:none;color:#fff;cursor:pointer}.ds-pill button:not(:last-child)::after{content:'';position:absolute;right:4px;top:2px;bottom:2px;width:1px;background:#0B1124}.ds-pill button[aria-pressed=true]{color:#CC3838}"
},
{
"name": "Labelled field",
"kind": "input",
"description": "Official ts-text-input: 26px, tsv-bg fill, 1.5px transparent border turning tint on focus.",
"html": "<label class=\"ds-field\">Server address<input placeholder=\"address or address:9987\"></label>",
"css": ".ds-field{display:grid;gap:4px;font:450 14px/18px 'Noto Sans',sans-serif;color:#fff}.ds-field input{font:inherit;min-height:26px;padding:2px 10px;border:1.5px solid transparent;border-radius:4px;background:#2b3346;color:#fff}.ds-field input::placeholder{color:#697A97}.ds-field input:focus-visible{outline:none;border-color:#1588FA}"
},
{
"name": "Settings category list",
"kind": "nav",
"description": "44px rows; selection fill #282F40 with a 4px tint bar and tinted icon.",
"html": "<nav class=\"ds-nav\"><button>Identity</button><button aria-current=\"page\">Audio</button><button>Video</button></nav>",
"css": ".ds-nav{display:grid;padding:8px 10px 8px 20px;background:#2b3346}.ds-nav button{position:relative;font:450 14px 'Noto Sans',sans-serif;min-height:44px;text-align:left;padding:0 20px;border:0;border-radius:4px;background:transparent;color:#fff;cursor:pointer}.ds-nav button:hover{background:#222A3C}.ds-nav button[aria-current]{background:#282F40}.ds-nav button[aria-current]::after{content:'';position:absolute;left:0;top:6px;bottom:6px;width:4px;border-radius:100px;background:#1588FA}"
},
{
"name": "Group tag",
"kind": "chip",
"description": "Server-group name beside a nickname in the tree: header-bg chip, 13px subtitle text.",
"html": "<span class=\"ds-group\">Admin</span>",
"css": ".ds-group{display:inline-block;max-width:14ch;padding:0 5px;border-radius:6px;background:#1C2539;color:#697A97;font:450 13px/17px 'Noto Sans',sans-serif;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}"
},
{
"name": "Settings section",
"kind": "card",
"refersTo": "settings-section",
"description": "Official .ts-widget-wrapper: header-bg, radius 15, 8px 20px padding, 15px semibold title.",
"html": "<section class=\"ds-card\"><h2>Microphone</h2><p>Capture device</p></section>",
"css": ".ds-card{display:grid;gap:16px;padding:8px 20px 20px;border-radius:15px;background:#1C2539;color:#fff;font:450 14px/18px 'Noto Sans',sans-serif}.ds-card h2{margin:8px 0 0;font-size:15px;line-height:19px;font-weight:600}.ds-card p{margin:0;color:#697A97;font-size:13px}"
}
],
"narrative": {
"northStar": "The official TeamSpeak 6 client, value for value",
"overview": "TeamsPeach targets the installed TeamSpeak 6 interface using extracted theme tokens, source component geometry and the three-slot window. The independent name/icon, local offline onboarding and omission of account-bound surfaces are deliberate exceptions. Source matching does not itself prove rendered or functional identity.",
"keyCharacteristics": [
"Navy dark theme (#2b3346 / #222A3C / #121A2C) with #1588FA tint; matching official light theme.",
"Three slots: 270px sidebar (62px rail), 500px server tree, flexible detail pane.",
"Noto Sans at 15/19 weight 450; official row heights 44/40/30/23.",
"Depth from the official background ladder, not shadows."
],
"rules": [
{ "name": "The Source Rule", "body": "Take target values from the installed official client with offsets in docs/evidence/official-parity/; verify actual composition with isolated screenshots and document differences.", "section": "overview" },
{ "name": "The Account-Free Rule", "body": "Omit cloud-only controls (bell, contacts, presence, Setup Chat) rather than showing controls that do nothing.", "section": "components" }
],
"dos": [
"Do keep native caption overlay colours equal to the window-bar token.",
"Do keep stock --tsv-* tokens at (0,1,0) specificity for local theme files.",
"Do document every deviation from the official client in DESIGN.md."
],
"donts": [
"Don't reinterpret or restyle the official look.",
"Don't ship TeamSpeak logos, label artwork or bundle files.",
"Don't claim feature parity from visual parity."
]
}
}
+104
View File
@@ -0,0 +1,104 @@
# .understandignore — patterns for files/dirs to exclude from analysis
# Syntax: same as .gitignore (globs, # comments, ! negation, trailing / for dirs)
# Lines below are suggestions — uncomment to activate.
# Use ! prefix to force-include something excluded by defaults.
#
# Built-in defaults (always excluded unless negated):
# node_modules/, .git/, dist/, build/, obj/, *.lock, *.min.js, etc.
#
# --- From .gitignore (uncomment to exclude) ---
# core-bin/
# core/target/
# identity*.ini
# teamspeach-identity*.ini
# smoke-out/
# smoke-voice-out/
# probe-stream-out/
# loopback-out/
# .env
# .env.*
# .DS_Store
# Thumbs.db
# --- Detected directories (uncomment to exclude) ---
# docs/
# scripts/
# test/
# --- Test file patterns (uncomment to exclude) ---
# JS / TS
# *.test.*
# *.spec.*
# *.snap
# C# / .NET
# **/*Tests.cs
# **/*Test.cs
# **/*Fixture.cs
# **/*.Tests.csproj
# Java / Kotlin
# **/src/test/**
# **/*Test.java
# **/*IT.java
# **/*Spec.kt
# Go
# **/*_test.go
# C++
# **/*_test.cc
# **/*_test.cpp
# **/*_test.cxx
# **/*Test.cc
# **/*Test.cpp
# **/*_unittest.cc
# **/*_unittest.cpp
# **/*_browsertest.cc
# **/*_benchmark.cc
# **/*Benchmark.cpp
# Python
# **/test_*.py
# **/*_test.py
# **/tests.py
# **/conftest.py
# Rust
# **/tests.rs
# **/test_*.rs
# **/*_test.rs
# **/bench_*.rs
# **/*_bench.rs
# Ruby
# **/*_spec.rb
# **/*_test.rb
# **/test_*.rb
# **/spec_helper.rb
# **/test_helper.rb
# **/rails_helper.rb
# Swift
# **/Tests/**/*.swift
# **/Specs/**/*.swift
# Исключения исследования мобильного порта; тесты и исходники остаются в карте.
**/.env*
**/*.pem
**/*.key
**/*.p12
**/*.pfx
**/identity*.ini
**/teamspeach-identity*.ini
**/credentials*
**/secrets.json
**/vendor/**
**/assets/**
**/resources/**
docs/evidence/**
native/compatibility.json
native/native-deps.lock.json
core/THIRD_PARTY_NOTICES.md
LICENSES/denoise-THIRD-PARTY-NOTICES.txt
package-lock.json
.impeccable/**
# Граф и его baseline не являются исходниками приложения.
.ua/**
.understand-anything/**
+4
View File
@@ -0,0 +1,4 @@
{
"autoUpdate": false,
"outputLanguage": "ru"
}
+70603
View File
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+20
View File
@@ -0,0 +1,20 @@
{
"lastAnalyzedAt": "2026-11-10T19:23:30.715637+00:00",
"gitCommitHash": "5ce12714acc306f6055bf1e9db3282c5af7704cb",
"version": "1.0.0",
"analyzedFiles": 372,
"workingTreeSnapshot": true,
"workingTreeFiles": [
".gitea/workflows/android.yml",
"AGENTS.md",
"CHANGELOG.md",
"README.md",
"docs/mobile-port-assessment.md",
"docs/mobile-port-progress.md",
"platform/android/build.gradle.kts",
"xtask/src/main.rs",
"xtask/src/package.rs"
],
"fingerprintBaselineCommit": "a761afaa43dddbdf78c70afb2546c79c3b1289e5",
"note": "Граф актуализирован по незакоммиченному рабочему дереву. Штатный incremental save отказал из-за dirty tree; fingerprints/scan baseline оставлены прежними для следующего воспроизводимого обновления после коммита."
}
+21
View File
@@ -0,0 +1,21 @@
# Работа над мобильным портом
## Native-only архитектура
- Единственный клиент — `native/` (Rust + Slint), протокольное ядро подключается через `core::runtime`. Electron/Node/Chromium UI и npm-сборка удалены; не возвращать их как временный host.
- Сборка, упаковка и smoke выполняются через Cargo/`xtask`. Общие ресурсы клиента находятся в `native/resources/`; версию задаёт Cargo workspace.
- Native-only не означает, что все платформы проверены. Фиксировать отдельно compile/package/runtime и реальные Android/iOS/device результаты; не переносить старые Electron passes в native acceptance.
- Android: выбран полный build/package в Linux CI (`.gitea/workflows/android.yml`); на Windows — разработка и установка APK через Platform-Tools. WSL/Docker/локальный Linux для этого маршрута не требуются; не предлагать их установку по умолчанию. Pinned WebRTC Android source-build остаётся Linux-only на CI, не обещать локальную Windows-сборку простой заменой путей.
- iOS требует macOS + Xcode/Apple SDK и соответствующий signing, локально или на отдельном macOS CI. Android workflow не доказывает iOS-готовность.
- Desktop acceptance gate: до явного подтверждения пользователя о проверенной установленной Windows-версии не выполнять push. После подтверждения зафиксировать desktop-baseline; дальнейшая мобильная работа не должна менять desktop-поведение без отдельного запроса. Изменения общих core/DSP/services проверять на desktop-регрессии; по возможности изолировать mobile-specific код.
- Windows 0.1.7 принята владельцем 2026-11-11 (подключение, канал, двусторонний голос); baseline — `desktop-baseline-0.1.7-20261111`. `main` — проверенная база, дальнейшая Android/iOS-разработка — `feature/mobile-port`. Приёмка Windows не означает Android/iOS acceptance; не менять desktop-поведение без отдельного запроса.
## Переносимая память
- В начале новой сессии прочитать `docs/mobile-port-progress.md` и относящиеся к задаче разделы `docs/mobile-port-assessment.md`. Эти документы — переносимая память проекта, а не память чата.
- Сопоставить записанную ревизию с текущим HEAD и рабочим деревом, включая staged, unstaged и относящиеся к задаче untracked-изменения. Перепроверять затронутые выводы и ссылки, а не перечитывать весь репозиторий.
- Использовать `codebase-knowledge-builder` при изучении новой подсистемы или существенном изменении ранее изученной; не запускать полный разбор ради мелкой правки. Существенные выводы подтверждать исходниками, отделяя факты, предположения и неизвестное.
- После существенных изменений обновлять соответствующие знания, ссылки на исходники, ревизию и сведения о реально проведённых проверках. Статический разбор не доказывает работоспособность на Android/iOS.
- Перед завершением сессии обновлять краткую передачу состояния в `docs/mobile-port-progress.md`, если появились новые решения, результаты или блокеры; не дублировать в ней весь разбор.
- Не перезапускать Understand-Anything каждую сессию. Использовать `.ua/knowledge-graph.json` как навигацию; обновлять при изменении архитектуры, предпочитая инкрементальное обновление. Проверять метаданные и не выдавать старый граф за актуальный. Автообновление графа оставлять выключенным без отдельного разрешения.
- Исследовательская стадия не разрешает менять исходники, запускать приложение, сборку, установочные скрипты или тесты. Для этого требуется отдельное разрешение. Не читать секреты и не помещать их в документы или граф; сохранять чужие инструкции и изменения.
+357 -1
View File
@@ -1,6 +1,362 @@
# Changelog
## 0.1.0 — unreleased
## Unreleased
- Fixed native Windows build environment capture for non-ASCII values by selecting UTF-8 in the
child MSVC activation shell; verified against real vcvarsall with a synthetic Cyrillic value.
- Pinned LF checkout for native dependency patches and recipe sources so Windows line-ending
conversion cannot invalidate exact patch checksums; expected lock hashes remain unchanged.
- Added a manual Android CI route producing separate full-feature ARM64 test-harness APK and unsigned
production APK/AAB bundles with source/build/dependency receipts. Windows developers do not need WSL.
Android packaging keeps offline Gradle by default; CI opts into dependency resolution explicitly and
isolates each package's Gradle outputs. CI runner provisioning and device acceptance remain unverified.
- Removed the Electron application, npm manifests and browser-only test/build tooling. Rust/Slint
is now the only application; native resources and versioning no longer depend on the removed tree.
Retained native profile migration and diagnostic core CLI. This cutover is not mobile runtime acceptance.
- Started the native implementation with one Cargo workspace and lockfile and pinned Rust 1.96.0.
Core/DSP dependency resolutions are preserved; the later native-only cutover removes the reference host.
- Added the native compatibility inventory; entries remain pending, not claims of feature completion.
Initial Slint software and Skia windows were exercised with a real pointer Close action;
this does not establish native voice, video, mobile support or whole-client migration completion.
- Extracted the protocol core into an embedded library with validated typed commands, joined session
lifetimes, generation-stamped events, bounded PCM and capture guards at the actual UDP-send boundary.
Diagnostic stdio remains independently usable for core inspection.
- Ported native profile import, local stores and session-bound file/icon/snapshot services. Imports retain
the original profile, preserve identity keys/UIDs and require bookmark passwords once again. Native
secret/preference pair commits recover interrupted writes; unknown staging directories are never discarded.
Windows isolated DPAPI and migration/restart smoke passed; other OS key stores and live mutations remain
separate verification gates. Snapshot format stays 0.0.1; native About labels legacy notices as historical.
- Added worker-owned CPAL audio, bounded timestamped callback queues, drift-aware Rubato conversion,
integrated Sonora AEC/NS/AGC and independent notification sinks. Capture/output revocation survives
queue congestion; source expiry remains attached through resampling to hardware presentation.
Controlled DSP/queue/permission and native worker smoke passed (generated PCM, no physical devices).
Official-peer voice, acoustic echo cancellation and mobile/Asahi hardware remain unverified.
- Added pinned source-built native WebRTC provisioning, checked desktop/mobile capture adapters and
generation-bound TS6 viewer/publisher state machines. Windows x64 CXX bridge compilation passed.
The production software decoder factory decoded synthetic H264 High, AV1, VP8 and VP9 fixtures;
all four 64×48 I420 outputs exactly matched independent FFmpeg decoding. Sustained native playback,
official TS6 peers, physical capture, hardware decode and other platforms remain separate gates.
- Proved a device-free native PeerConnection loopback through the real sender/decoder/display path
(13 decoded frames, 12 presented, terminal cleanup). Isolated WebRTC Opus symbols from the voice
core's existing codec without weakening linker checks or rewriting unrelated assembly objects.
- Rebuilt Privacy, Video, Notifications and About in the original section order. Unsupported account,
telemetry, Cisco/backend and content-report options are explicitly unavailable, never fake preferences.
Working Chromium decoder controls and installation/project details moved to linked subpages with
back-focus restoration. Report Issue uses the project's verified issue list through the external-link guard.
- Preserved native decoder-policy restart, notification overrides, trusted-site management and local
changelog/license navigation. Corrected narrow Russian update-row overlap without hiding status.
- Restored original selector wrapping, selected-preview radius clipping and whisper action tints.
Permission lists now reserve their source toolbar space and wrap badges without losing long-name
truncation; private-info descriptions and empty group states use the source sizing and spacing.
- Fixed channel right-click opening Whisper settings and silently staging a target. The normal channel
menu now leaves the current view and whisper state unchanged; only its explicit Add to Whisperlist
action stages the channel, behind the existing connection/session validity guard.
- Moved identity export and UID copy into the selected identity's context menu. Export keeps its
private-key confirmation. Disconnected nickname edits use identity Details; connected nickname
edits use the own-client information header. Removed the duplicate bookmark settings manager;
bookmarks remain editable in the sidebar.
- Language changes are saved for restart, with a cancelable restart confirmation. File-transfer
settings use the source defaults, shared rate limits and per-channel concurrency limits.
- Added generation-bound group deletion and explicit group/channel permission removal, plus the
channel icon picker. A refused icon after successful channel creation cannot create the channel
a second time; stale form/session responses do not apply to another view.
- About reports actual build metadata. Corrected identity slider layout, device-selector caption
overlap, broadcast tab/thumbnail geometry and transfer-row spacing. Migrated affected smoke scripts.
- Matched the detail header's source flex grouping, restored full-height administration panels and
bottom pagination, corrected client-list wrapping, group-badge spacing and server-info typography.
Audio device captions and broadcast title chips now use measured original text metrics.
- Whole-client pixel parity is not established; reference comparisons retain their original thresholds.
## 0.1.7 — 2026-11-02
- Matched light-theme toolbar/header/composer icon colors, header separators and chevron placement
to the installed reference. Corrected narrow chat width and input placeholder spacing.
All eight main-screen EN/RU, dark/light and wide/narrow fixture comparisons passed; this does not
establish whole-client parity or native-platform interoperability.
- Replaced the plain chat textarea with one local CodeMirror editor and the persisted Rich Text Editor
toggle. Hybrid preview uses the existing safe TS Markdown renderer; switching modes retains text,
selection and undo, while switching conversations isolates draft history. Toolbar/slash/emoji edits,
Enter/Shift+Enter, IME and refused-send preservation were exercised in the packaged offscreen app.
Constructed stylesheets keep the application CSP strict; no inline-style exception was added.
- Added the original editor's bold, italic, link, inline-code and code-block keyboard bindings.
Corrected the notification output selector's missing bottom margin using the original component rule.
- Matched list/quote authoring controls: Shift+Enter continuation, ordered/task item transitions,
Tab/Shift+Tab indentation, empty-item exit and Escape-then-Tab focus escape. Fenced code is not
mistaken for a list; quoted fences retain their quote prefix.
## 0.1.6 — 2026-11-02
Current development snapshot; full visual parity and native Asahi verification remain unfinished.
Version 0.1.5 was not published: CI rejected an empty changelog section.
- Added source-style advanced notification controls with independent persisted event choices,
confirmation before hiding advanced controls and single-event expansion.
- Corrected server-tree painting against paired hidden captures. Remaining light-theme,
narrow-layout and composer differences are not claimed fixed in this release.
- Rebuilt Identities around the original selector, inline creation/rename, selected-identity Details,
security-level controls and related bookmarks. Fixed default-profile UID leakage into selected Details,
selector popup initialization and the final improvement level briefly reverting during a list refresh.
Export and the explicit current-server nickname action remain available.
- Replaced raw File Transfer number fields with source-style keyboard/step controls that retain focus
and drafts through serialized saves. Native folder/copy restrictions, shared limits and safe defaults remain.
- Added notification category switches with real sound-policy gating, preserved per-event states and
independent event logs; concurrent state edits are serialized.
- Added nested bookmark folders with inline creation, rename, ordering, move/duplicate menus and
confirmed subtree deletion, using validated local preferences rather than a separate bookmark store.
- Extended bookmarks with a per-connection nickname, initial channel, session-bound channel drops,
startup connection and input-only startup mute. A nickname override never changes the stored identity.
- Bookmark passwords use OS-protected encryption, bound to address and server/channel purpose. Plaintext
is never persisted; Linux basic_text/unknown storage is refused. Stale metadata writes cannot overwrite
or resurrect a password, and native key-store interactions revalidate the window, bookmark and connection.
Explicit reveal, same-address duplication, address-change cleanup, restart and forgetting a password
after storage becomes unavailable were exercised with real Windows DPAPI. No live server join was performed.
- Startup bookmark enumeration is one-shot in main, so a renderer reload cannot start a second set of
connections. Automatic microphone mute is applied before connecting and never changes speaker mute.
- Added Privacy with trusted-site management and remembered confirmations; reset and concurrent
confirmation changes are serialized so an older save cannot overwrite a later reset.
- Removed the mistakenly added Remote Apps integration to honor the owner's explicit exclusion:
no listener, authorization IPC, settings page, remote-button capture or WebSocket production dependency.
- Added account-free local UID contacts and public badge artwork display. These are not myTeamSpeak
contacts, owned-badge management, cloud presence or offline messaging.
- Added server icon management bound to the listing's connection generation. Reconnecting invalidates
mutation grants; old icon/snapshot transfers cannot cancel a new session's reused transfer ID.
- Added the four-level noise-reduction control with persisted per-input settings. Processing remains
an independent implementation, not a claim of identity with TeamSpeak's private native DSP.
- Fixed key recording in the contents-layout settings host by checking the enclosing panel's visibility.
Packaged verification covers saving the binding and retaining it across an application restart.
- Isolated Mermaid rendering from the privileged application renderer; nested renderers cannot acquire
media/presentation permissions. Local diagram/math rendering and hostile-content rejection were exercised.
- Corrected smoke polling to await asynchronous IPC/import predicates instead of accepting a Promise
as a satisfied condition. Persistence checks now wait for actual saved state.
- Fixed full Changelog and Open Source Licenses pages rendering arrays as text instead of appending
their DOM nodes. Added a real offscreen navigation smoke covering document text and back-focus restoration.
- Whispers follow the original manager: Live Preview highlights the current list's clients and channels in
the server tree (resolved from the current snapshot only), "Switch to Server and Overlay" shows the list
next to the microphone's server, and the status bar Whisper History lists received whispers with Delete.
Replies and avatars use only entries whose client id and UID are still on the same server session.
- Key Bindings follow the original page: "Require exact key match" toggle, named profiles (inline
"New Profile Name" editor, rename, choose, Activate, delete of inactive profiles) and every official
hotkey action, each running the app's real operation. Push-to-mute stops sending without touching your
mute choice; global push-to-talk survives window focus loss while local keys still release on it. Go Live
opens the broadcast source chooser instead of guessing the focused application. Bindings can be in-window,
or global; with exact matching off, global keys also register their
extra-modifier combinations. keybinds.json moves to version 2; version 1 whisper bindings migrate unchanged
into one active profile and the original file is kept as `keybinds.v1-<time>.json`.
- Reworked the interface against the actual installed TeamSpeak frontend rather than the earlier
hand-reconstructed component sheet: original non-brand SVG artwork, Noto Sans 2.013, channel and
client chat layouts, membership event rows, sidebar actions, in-pane administration, settings
dropdowns/sliders and the two-stage broadcast dialog. Independent branding and account-free
behavior remain. Artwork provenance does not grant redistribution rights.
- Corrected sidebar group geometry and moved New Connection into its own account-free action slot;
bookmark add/search/disclosure retain their real persistence/navigation behavior. Language and sidebar
icon-mode selectors use original local artwork, content-based widths and restored keyboard focus.
Audio device captions use the observed system-default alias, not an inferred physical device.
- Matched device-field, VAD selector, slider, record-test and display-preview geometry to source values.
Fixed the chat spacer to use the composer's content-box height, removing a two-pixel full-history offset.
- Preserve a bottom-pinned chat on window reflow without forcing readers of older history to the end.
The regression reproduced a 119px gap after narrowing; the packaged fix retains a zero gap and
separately preserves the history reader's position. The paired harness retains this behavioral check.
- Match chat scrollbar safe-area width and system-event wrapping to the actual original renderer;
restore the localized empty-chat prompt with real draft/send-state visibility. Narrow composer tools
now overflow into working ordered menus rather than clipping. Settings categories occupy the original
narrow-sidebar position below Servers/New Connection, with source-sized previews and server columns.
- Correct empty-chat prompt geometry with the measured 22px glyph and the secondary-pane contrast
background. The focused dark/en wide-screen chat region passes; the whole screen still fails other regions.
- Use the original Russian bookmark-help wording (`Добавьте`), preserving the same save/connect behavior.
- Run both sides of visual QA with Electron's normal acceleration policy. Earlier reference captures
forced software rendering while the product did not; those comparisons remain historical evidence,
not directly comparable pixel baselines for the corrected capture policy.
- Actual whole-screen comparison still does not meet the 1:1 acceptance criterion. The refreshed 168-pair
run has no blocked captures but no fully passing screen pairs. Viewport-only timestamp comparison and
nested native-caption exclusions now avoid earlier harness false positives; thresholds are unchanged.
See `docs/evidence/official-parity/qa-parity-harness.md` for build-specific results and remaining differences.
- Initialize custom controls explicitly at renderer startup, not when audio/notification modules
import the slider helper. The Node suite and focused packaged chat/control smoke checks pass;
this does not establish complete visual or native platform parity.
- Added local TS6 theme extensions (Settings → Appearance → User Theme): the official `package.json`
schema, `<identifier>//<variant>` selection, stock fallback and a five-minute list cache with Reload.
Files load only through the restricted `tsext:` scheme (selected variant CSS, fonts, images, previews);
`@import`, remote URLs, links and path traversal are rejected and reads are bounded. Account-free; no
store or Remote Apps. Compatibility covers the package format and `--tsv-*` tokens, not official DOM
class hooks.
- Added account-free local identity management: additive import, selected-identity export, per-identity
names/nicknames, default and bookmark selection, guarded deletion, and resumable/cancellable bounded
security-level improvement. Active connections retain their chosen identity.
- Added simultaneous connection records with one isolated native core per server, explicit viewed/input
connection routing, connection-local chat, streams, recording and administrative operations.
- Added channel/server administration, local whisper lists and held targets, general legacy file browsing
and transfers, server snapshots, recording, notifications, and OS-specific local settings. Available
functionality and unverified native protocol branches are listed separately in the compatibility matrix.
- Migrated audio preferences to per-device capture/playback profiles and the official piecewise dB fader;
existing voice choices are converted on load. Automatic/hybrid/level activation, PTT release delay,
notification routing and independent processing are implemented without claiming native-DSP identity.
- Added connection/identity-scoped disk chat history, independent drafts/unread state, local rich text,
emoji/math/diagrams and server-file links. Remote images require explicit consent; account-only Matrix
editing, reactions and read receipts are not included. Local vendor assets carry redistribution notices.
- Recording finalization preserves dropped-tail timing and counts actual published bytes. Notification
event overrides and the event log are independent. Theme loading rejects directory escapes and remote
content; Small/Medium/Large and compact/detailed appearance settings use source-backed values.
- File Transfer settings apply app-wide directional concurrency and pacing limits across server tabs,
including snapshot transfers. The remembered destination is main-approved; no renderer-provided host
path is accepted and an unavailable folder never silently changes the destination.
- Unversioned legacy sidebar widths migrate lazily to the server-pane width for the three-pane layout.
Reading preferences does not rewrite the file; the next successful save records layout version 2,
while existing new-layout choices remain unchanged.
- Added a bounded ten-second in-memory microphone record/listen test using the selected output device.
It never sends test audio to a server; Finish, device/privacy changes and closing settings clear the clip.
- Bounded microphone MessagePort backlog to 200 ms using capture-context sample timestamps; renderer
stalls no longer replay older queued speech. Capture DSP preferences and channel bitrate mapping are
unchanged. Hidden 190-second speech/silence captures and a real Opus encode/decode matrix were measured;
natural-microphone and official-client subjective quality remain unproven.
- Saved servers now use an always-visible inline heading/chevron disclosure, with persisted collapsed
state; toggling the heading never connects or navigates. Removed the old detached bookmark toggle.
- Connection information now uses vertical labelled groups instead of one column per protocol field,
with locale-aware duration, byte, rate and loss units, long-value wrapping and expandable raw records.
Member menus use measured pointer/keyboard anchors, side flipping and viewport bounds, reposition on
resize and dismiss on background scrolling rather than retaining a stale sidebar offset.
- The flat application caption follows the official 44 px palette. Windows/Linux window-controls overlay
and macOS traffic lights remain OS-owned; offscreen fixtures do not claim native Snap, fullscreen,
picture-in-picture or focus behavior.
- Application chrome no longer selects text during clicks and drags; chat, inputs and useful content remain
selectable. Removed the redundant audio-muted banner and transmission-mode/key header hint without
changing mute/deafen or push-to-talk safety. The host banner now sits behind the server header card.
- Added separate channel-member collapse chevrons with compact avatar summaries and per-server persistence,
plus a bounded sidebar divider supporting pointer and keyboard resize/reset.
- Watched screen shares now have independent tiles, controls and native picture-in-picture windows. Full
screen and PiP preserve their media sessions; stopping one view leaves its siblings running. The upper
stream stage can be resized or collapsed independently of chat, with saved layout preferences.
- Stream players now put the picture first: large resizable video above chat, a small name overlay, and
controls over the picture on hover or keyboard focus instead of a permanent footer. Live statistics move
into an accessible EN/RU details disclosure. New profiles start with a larger stage; existing saved sizes,
independent streams and the broadcaster's separate local-preview controls are preserved.
- Added target-bound member context menus with server-derived capability hints, explicit unknown/denied
states, guarded confirmations for moderation and permission/group changes, native bounded avatar
selection, and visible backend errors. Menus reject stale identities and connection generations.
- Per-participant voice volume uses -200..+10 dB and an independent Mute control. Reset restores 0 dB and
unmutes. Explicit committed modifiers persist by UID; session mute remains connection-local.
- Added explicit source selection, private preview and Start/Stop P2P publishing, with a muted local tile,
quality targets, per-viewer admission and a transmission-scoped UID allowlist. Capture remains opt-in;
native OS/portal support and live official-client interoperability require separate platform evidence.
- Added selected-application audio adapters for Windows WASAPI process trees and Linux PulseAudio /
pipewire-pulse streams, with bounded IPC and outgoing per-app/master gain. macOS application-audio capture
remains unavailable. The native combined capture-to-WebRTC path is not claimed proven by UI fixtures.
- Disposable UI checks now run hidden and offscreen by default, with separate profiles, denied physical
capture/permission prompts and native dialogs disabled unless a test supplies a fixture answer. The
shared launcher asserts invisible/unfocused/nonfocusable offscreen state and mutes webContents.
Packaged tests verify bundled main-process bytes match the current offscreen-safe source before launch.
- Channel clicks now browse the channel without moving voice; double-click or the explicit Join channel
action moves voice. The header explains when the channel chat still belongs to the current voice channel.
- Available screen shares appear above chat with explicit Watch actions, including multiple announced
streams; the old member-row Watch buttons are replaced by stream indicators. Browsing never subscribes.
Unavailable discovery and denied joins remain visible errors rather than fabricated streams.
- Allowed HTML fullscreen requests from the app origin while retaining the existing camera/screen-capture
restrictions. The player uses native full screen, an exit control and native Escape, keeps the same media
session, and exits on stop/end/disconnect. Request/exit failures are reported, and teardown only exits
fullscreen owned by the stream player.
- Added an isolated Electron stream-UI/media smoke with EN/RU and light/dark captures. Synthetic directory
events and local real WebRTC media are explicitly distinguished from TS6 server interoperability.
- Fixed memory growth during microphone restart/test cycles: capture processors acknowledge shutdown,
release their ports and track listeners, and close their own capture context without interrupting the
persistent playback context. Partial audio initialization is rolled back and can be retried.
- The active chat DOM now follows the existing 500-message history limit, preserving message headers and
the visible scroll anchor. Reconnect history retains server labels instead of entire server snapshots.
- Server image caching releases obsolete avatars, banners and icons when the snapshot no longer refers
to them, including downloads that finish after removal; current resources are not arbitrarily evicted.
- Core startup failures now release child/log/readiness resources on process close, including failures
without an exit event. Core stderr applies lossless log-stream backpressure.
- Screenshare lifecycle: duplicate/unknown per-stream stop notifications no longer remove sibling shares;
cancellation stops queued ICE/offer work, releases closed peer connections, and avoids retaining stopped
sessions through empty translated-label callbacks. Added isolated generated-media pipeline/lifecycle
evidence; no codec, bitrate or throttling policy change, and no claimed FPS-cap fix.
- Added reproducible disposable-profile Electron memory workloads with generated/fake audio, native heap
and process memory evidence, and regression coverage for capture cancellation, chat and image ownership.
- Second lifecycle audit: obsolete pending image downloads no longer expose revoked URLs when a cache
key returns (A→B→A); reused client rows reload avatars when UID changes. Stream discovery ignores old
responses after newer announcements, client/channel changes or stream restarts while preserving current
failures and completing fresh discovery. Delayed output/fullscreen failures cannot report errors for
ended or replaced viewing sessions. Added disposable real-renderer interleaving and generated-WebRTC
callback regressions; the live 20 fps report remains unexplained, with no performance-policy change.
- Audio/core failure ownership: capture-processor errors stop the microphone; failed context closure
retains ownership until an explicit recovery succeeds. Explicit playback recovery settles failed
diagnostics and preserves applied volume/output selection. Core log-destination failures report an
error without crashing main or stalling stderr; exited cores reject new commands while final replies
and events drain before close.
## 0.1.4 — 2026-10-24
Version 0.1.3 was tagged but never released: a race in the transmit-mode handshake was found before
publication (an older answer could re-enable forwarding while a newer mode change was still pending). It is
fixed here.
- Added voice activation as a third transmission mode next to push to talk and the open microphone
(Settings → Audio → Voice transmission, sensitivity High / Normal / Low). The core decides locally with
the earshot voice detector (a small embedded neural network, no cloud service, no speech recognition) on
audio that has already passed the microphone processing (noise suppression, echo cancellation, gain
control). It sends from about 100 ms before a detected onset until about 400 ms after the last detected
speech. After connecting, unmuting or changing the mode the gate cannot open for 200 ms, but every frame
since then is kept (up to 300 ms) and sent with the first spurt, so the first word is complete; that first
spurt therefore starts up to 300 ms late (later spurts carry the normal 100 ms). Muting, deafening, disconnecting, a channel or codec change and
a server talk denial discard what the detector heard. Push to talk and the open microphone are unchanged;
stored settings keep their mode, and new profiles still start with push to talk.
- The transmission mode moved from Settings → Keyboard to Settings → Audio; the push-to-talk key stays in
Keyboard. The microphone test explains that it only shows the input level and never transmits.
- The renderer forwards microphone audio only after the core has confirmed the selected mode; only the
answer to the latest request counts (older answers, also from a restarted core, are ignored), and a failed
mode change is shown and nothing is sent until it is applied. Renderer diagnostics now count frames
forwarded to the core, not "sent" frames; whether voice is sent is the core's transmitting state.
- Fixed: a preference write failure no longer changes the in-memory value the app keeps using.
- ARM64 CI runs the core unit tests (voice detector, resampler, identity, codecs) under qemu-aarch64
(emulated, not native hardware).
## 0.1.2 — 2026-10-24
- Fixed: Settings → Audio listed only the system default device. Electron reports the app origin as
`app://teamspeach/` and the permission check compared it with `app://teamspeach`, so Chromium withheld
device ids and names. The audio-only permission policy now normalises origins (camera stays denied);
real inputs and outputs are listed without starting the microphone, and the default entry names the
device it points to.
- The default theme is now dark, independent of the OS; Light or System can be chosen in
Settings → Appearance and persists. A theme already saved by an earlier version is kept as is.
- Right-click (or Shift+F10 / Menu key) on the microphone and headphones buttons opens an input / output
device menu sharing the Settings selection; left click still mutes/deafens.
- Voice diagnostics: the local log records the capture device and track state; with
`TEAMSPEACH_LOG=debug` it also records push-to-talk presses with window focus and each transmission burst
(frames, peak level).
- The push-to-talk hint says when the window is not focused (the key is read only there).
- Fixed: ~1/256 newly created or imported identities could not be loaded again (private key with a leading
zero byte). Storage format unchanged.
- Replaced the application icon assets with an original peach silhouette on a transparent background,
including PNG assets and a seven-size Windows ICO. The reproducible Electron export now renders the
SVG directly to an alpha-enabled canvas instead of capturing a window, avoiding captured scrollbars.
The start, error and onboarding screens show the same icon asset instead of a separate inline drawing.
- Added an English-default interface with selectable Russian, backed by shared catalogs for the renderer
and native identity dialogs. Repository-authored documentation and technical diagnostics are English;
historical captures and server-provided content remain unchanged.
- Added update checks against published public Gitea releases, Preview and Stable channels, verified
downloads for Windows x64 NSIS and Linux x64/ARM64 AppImage installations, and manual-update guidance
for zip/tar.gz distributions. Installation requires confirmation; active sessions defer background
downloads. Version 0.1.1 and older require a first manual installation of an updater-capable version.
- Fixed capture cancellation during pending microphone acquisition and prevented device changes from
being applied when saving the selected device fails.
- A saved microphone that is no longer available is reported as unavailable; TeamsPeach no longer opens
a different microphone in its place. Choosing an available device restores capture while connected or
during the microphone test, and opens nothing otherwise. A failure while building the capture chain
releases the microphone.
- The microphone and headphones menus show a failed device enumeration instead of an earlier list.
- Windows installations started with a custom profile (`TEAMSPEACH_PROFILE_DIR`) only offer manual
updates, because the installer would restart TeamsPeach on the default profile.
## 0.1.1 — 2026-10-24
- Linux AppImages use the static AppImage runtime (electron-builder toolset `appimage` 1.0.3,
runtime 20251108). The 0.1.0 ARM64 AppImage used the legacy runtime, which needs an unversioned `libz.so`
(normally only in zlib development packages) and failed to start on stock systems.
- Release gate: every AppImage must start (`--appimage-version`) in a slim container without development
packages — natively for x64, under qemu for ARM64.
- No application changes.
## 0.1.0 — 2026-10-24 (pre-release, superseded by 0.1.1)
- Electron desktop shell (contextIsolation, sandbox, strict CSP, allowlisted IPC, `app://` protocol).
- First-run nickname with persistent P-256 identity, visible UID, rename without UID change,
Generated
+9740
View File
File diff suppressed because it is too large. Load diff
+45
View File
@@ -0,0 +1,45 @@
[workspace]
resolver = "3"
members = ["core", "dsp", "native", "xtask"]
exclude = ["core/vendor/tsclientlib", "core/vendor/tsproto", "dsp/vendor/sonora", "dsp/vendor/sonora-agc2", "native/vendor/libwebrtc-0.4.0", "native/vendor/webrtc-sys-0.3.53", "native/vendor/katex-rs-0.3.0", "native/vendor/mermaid-rs-renderer-0.3.1", "native/vendor/cpal-0.18.2", "native/vendor/i-slint-backend-android-activity-1.18.1"]
[workspace.package]
version = "0.1.7"
edition = "2024"
rust-version = "1.96"
publish = false
[workspace.dependencies]
serde = { version = "1", features = ["derive"] }
serde_json = { version = "1", features = ["raw_value", "preserve_order", "unbounded_depth"] }
thiserror = "2"
tokio = { version = "1", features = ["rt", "sync", "time", "macros"] }
slint = { version = "=1.18.1", default-features = false, features = ["std", "compat-1-18", "accessibility", "image-default-formats", "unstable-fontique-011"] }
slint-build = "=1.18.1"
cpal = "=0.18.2"
rubato = { version = "=5.0.1", default-features = false }
sonora = "=0.2.0"
sonora-ns = "=0.2.0"
libwebrtc = "=0.4.0"
webrtc-sys = "=0.3.53"
katex-native = "=0.1.1"
katex-rs = "=0.3.0"
mermaid-rs-renderer = { version = "=0.3.1", default-features = false }
cssparser = "=0.38.0"
[patch."https://github.com/ReSpeak/tsclientlib"]
tsproto = { path = "core/vendor/tsproto" }
[patch.crates-io]
sonora = { path = "dsp/vendor/sonora" }
sonora-agc2 = { path = "dsp/vendor/sonora-agc2" }
libwebrtc = { path = "native/vendor/libwebrtc-0.4.0" }
webrtc-sys = { path = "native/vendor/webrtc-sys-0.3.53" }
katex-rs = { path = "native/vendor/katex-rs-0.3.0" }
mermaid-rs-renderer = { path = "native/vendor/mermaid-rs-renderer-0.3.1" }
cpal = { path = "native/vendor/cpal-0.18.2" }
i-slint-backend-android-activity = { path = "native/vendor/i-slint-backend-android-activity-1.18.1" }
[profile.release]
lto = "thin"
codegen-units = 4
+247 -47
View File
@@ -1,62 +1,262 @@
# Design
---
name: TeamsPeach
description: The installed TeamSpeak 6 client's own visual system, reproduced from its source values.
colors:
tsv-bg-dark: "#2b3346"
tsv-bg-light: "#f5f5f5"
tsv-shaded-bg-dark: "#222A3C"
tsv-shaded-bg-light: "rgb(235, 235, 235)"
tsv-header-bg-dark: "#1C2539"
ts-new-header-bg-dark: "#121A2C"
tsv-contrast-bg-dark: "#0C1326"
tsv-contrast-bg-light: "#C9D9E5"
tsv-deviant-bg-dark: "#1E2538"
tsv-deviant-bg-light: "#d3d5de"
tsv-side-bar-bg-gradient-bottom-dark: "#1D2537"
presence-separator-presence-dark: "#171C2A"
strong-bg-dark: "#0B1124"
tsv-tint-dark: "#1588FA"
tsv-tint-light: "#5DA1CB"
tsv-tint2-light: "#22658f"
tsv-font-color-dark: "#FFFFFF"
tsv-font-color-light: "#1a1a1a"
tsv-font-subtitle-color-dark: "#697A97"
tsv-font-subtitle-color-light: "#445d77"
ts-third-font-color-dark: "#bbd6f3"
tsv-error-color-dark: "#CC3838"
tsv-error-light-color-dark: "rgb(255, 130, 130)"
tsv-away-color-dark: "#FF8B04"
presence-online-dark: "#17f78d"
tsv-online-color-dark: "#13F78D"
settings-highlight-bg-dark: "#282F40"
ts-tree-channel-bg-start-dark: "#192031"
ts-tree-channel-bg-end-dark: "#1D263A"
ts-tree-badges-bg-dark: "#222A3B"
tsv-chat-remote-bg-dark: "#697a97"
tsv-chat-self-bg-dark: "#0C1326"
ts-chat-system-message-bg-dark: "#131824"
ts-chat-system-message-text-color-dark: "#acacac"
tsv-chat-link-color: "#081cbd"
tsv-preview-bg-light: "#bccbeb"
ts-menu-action-color: "#8ac5fc"
tsv-separation-border-color-dark: "#1D1F20"
tsv-scrollbar-bg-dark: "#0B111D"
tsv-slider-track-bg-dark: "#131824"
ts-checkbox-bg-color-dark: "#0c0d0f"
tsv-commander-color: "#daa520"
typography:
body:
fontFamily: '"Noto Sans"'
fontSize: "15px"
lineHeight: "19px"
fontWeight: 450
content:
fontSize: "14px"
lineHeight: "18px"
small:
fontSize: "13px"
lineHeight: "15px"
large:
fontSize: "16px"
lineHeight: "19px"
title-small:
fontSize: "24px"
lineHeight: "28px"
fontWeight: 700
rounded:
small: "2px"
base: "4px"
large: "8px"
xlarge: "10px"
xxlarge: "15px"
xxxlarge: "20px"
pill: "100px"
spacing:
v-minimal: "2px"
v-small: "4px"
h-minimal: "5px"
v: "8px"
h-small: "10px"
v-large: "16px"
h: "20px"
h-large: "40px"
components:
button-filled:
backgroundColor: "linear-gradient(60deg, #0058FF, #1365BB)"
textColor: "#FFFFFF"
rounded: "{rounded.pill}"
padding: "4px 20px"
settings-section:
backgroundColor: "{colors.tsv-header-bg-dark}"
textColor: "{colors.tsv-font-color-dark}"
rounded: "{rounded.xxlarge}"
padding: "8px 20px"
---
Documented from the shipped interface (`app/renderer/styles/app.css`, `index.html`) — this records what is
built, it is not an aspiration. Mode: **Operate**. Direction: the category standard of voice-chat clients,
an engineering choice for a familiar working tool, executed with a restrained peach accent. The only
owner-pinned visual reference is the TeamSpeak 6 settings screenshot that the settings layout follows.
# Design System: TeamsPeach
## Overview
**North Star: "The official TeamSpeak 6 client, value for value."**
The owner asked for the installed TeamSpeak 6 client's design, without reinterpretation. Two earlier
TeamsPeach worlds (flat warm-neutral, then the Liquid Glass approximation) are retired. The target values
come from installed client 6.0.0.5163 (`main.css` sha256 `bc700401…`, `main.js` sha256 `9d6bea2e…`): theme
tokens from its webpack theme modules (`main.js` @92422 dark, @201685 light), scale tokens and component
geometry from `main.css`, layout constants from `main.js` (window slots @1273206). The extracted values
and source offsets are in `docs/evidence/official-parity/ts6spec-{shell,tree,chat,controls,settings}.md`.
Native stock theme data retains the official `--tsv-*` names in
`native/src/services/themes/stock.css`; `native/ui/` expresses the Slint geometry and presentation.
Source matching, screenshot similarity and functional parity are separate evidence claims; this document
is the retained implementation contract, not proof that every native pixel or feature matches.
The product name and application icon stay TeamsPeach's own. Retained source-derived fonts and sounds,
and historical non-brand pictograms, have provenance/redistribution limitations in `LICENSES/`.
The official JavaScript application and removed browser implementation are historical references only,
not product runtime dependencies. Native cutover does not establish visual or functional acceptance.
## Colors
Dark is the default for new profiles; light follows the official light module. Native stock token data
and the supported user-theme importer preserve the dark/light contract without a browser cascade.
Supported declaration order/specificity and `!important` are handled as data; see `docs/themes.md`.
Blue `--tsv-tint` (#1588FA dark, #5DA1CB light; `--tsv-tint2` #22658f light) marks own nickname,
selection outlines, active toggles and primary actions; green (`--presence-online`) marks talking/online
and enabled toggles; red (`--tsv-error-color`) mutes and destructive actions; orange
(`--tsv-away-color`) away and warnings. Secondary text is `--tsv-font-subtitle-color`; client names
in the tree use `--ts-third-font-color` (#bbd6f3).
## Typography
Noto Sans variable files version 2.013 from the installed client are bundled under
`native/resources/fonts/`, with SIL OFL 1.1 in `LICENSES/NotoSans-OFL.txt`. Preserve normal, italic and
oblique source semantics where the native font backend supports them. Body 15/19, content 14/18,
small 13, header titles 24/28 bold. Channel labels use 14px normal; client names use 14px semibold.
Chat names use the source hash/contrast colour calculation, with 16/19 message text and 13/15 events.
## Layout
- Two columns: sidebar `clamp(280px, 27vw, 390px)` (server header, host banner, channel tree, own-status
footer) and a workspace (connect form, or channel header + optional stream viewer + chat, or settings).
- Tree rows: channels with `#`/lock glyph, server channel icon at the right, server banner as a row
background fading from the sidebar colour; members indented under channels with avatar/status dot,
nickname (never truncated before group labels), server-configured group labels, mute/away/recording
flags, group icons and country code, and a pill "Смотреть" button for streamers.
- Settings follow the owner's pinned reference: the sidebar's room area is replaced by category navigation
(Назад к серверу, groups Пользователь / Приложение / Информация, active item with an accent bar and tint),
the workspace shows the selected category as titled cards (`.card`, 12 px radius) with an expandable
"Подробности" area for advanced video information. The connection, voice footer and any stream keep running.
- Saved servers sit above the tree as a compact list (name, address, action: Подключиться / Переключиться /
Подключено); a bookmark button in the server header shows or hides it.
- Stream viewer: black stage with the video contained, dark control bar (title, codec · resolution · fps,
mute, volume 0–100 %, fullscreen, stop). Overlay text explains every non-live state.
The desktop target is the official three-slot frame (source component names below are historical
geometry labels, not required DOM selectors):
## Colour
1. **Sidebar**, 270px default, max 420; dragging below 200 collapses it to the 62px rail.
Header gradient #121A2C → #1D2537, activity rows 44px with an always-visible 8px-radius pill inset
10px (4px gap), group captions 13px subtitle, footer 55px with a 3px separator inset 20px.
2. **Server pane**, 500px default, min 220: 44px window bar (#121A2C) carrying the toolbar
pill (26px, `--tsv-bg`, 1px `--strong-bg` separators) with microphone and speaker; separate Away action; a 10px
inverse fillet; the server tree on the 25° gradient (#252F44 → #2E374C); the 92px server header card;
channel rows 44px with a 30px pill (inset 7/10, radius 9, 1.5px outline, channel background gradient
on by default); client rows 40px with 33px avatars and 23px status plates; the 55px status bar with
40px side padding.
3. **Detail pane**, min 295, body `--tsv-shaded-bg`: 44px window bar reserving native caption
integration, 71px content header (38px icon, 24/28 bold title, segmented mode switch), 4px separator, the
stream stage, chat log and composer.
Restrained strategy: warm neutrals plus one accent; state colours only where they mean something.
Settings occupy the main and detail slots as the official settings activity does at ≥900px: category
column `clamp(30ch, 20vw, 50ch)` with 44px rows, `--settings-highlight-bg` selection and a 4px tint bar;
pages max 640px wide with section cards (`--tsv-header-bg`, radius 15, padding 8px 20px, 12px apart).
Below 900px retain category navigation without losing settings drafts/focus. Small/Large use the official
token modules (53225/68865), not browser zoom; collapsed rail widths are 52/62/72px. Compact/mobile
adaptation preserves usable targets, safe areas, IME and an independent voice strip; it is not desktop
pixel-parity evidence. Native caption integration retains the 44px design target where supported.
| Token | Light | Dark | Use |
|---|---|---|---|
| `--bg` | `#f6f3f0` | `#1b2029` | window ground, settings background |
| `--surface` | `#fffdfb` | `#242b37` | workspace, inputs, settings cards |
| `--sidebar` | `#eee9e4` | `#1e242e` | sidebar, settings navigation |
| `--sunken` | `#e6e0da` | `#171b23` | footer, UID, group labels |
| `--text` / `--text-2` / `--text-3` | `#221c18` / `#5e544d` / `#776c64` | `#e7ebf2` / `#aab3c2` / `#8e98aa` | text hierarchy |
| `--accent` | `#b24f26` | `#f09a6c` | primary buttons, selected tab, own name, focus |
| `--accent-soft` | `#fbe2d4` | `#3a3033` | current channel, active settings category |
| `--peach` | `#f3a37c` | `#f3a37c` | brand mark |
| `--talk` | `#1f8a5a` | `#4fcf8e` | talking indicator, PTT held |
| `--danger` | `#b3261e` | `#f08b82` | mute/deafen active, errors |
Resize handles are invisible 9px strips centred on each pane edge, tinted at 50% while focused or
dragged. Native window/caption colors follow the window-bar palette through real platform integration.
Theme follows the choice in Settings → Внешний вид (system by default, implemented through Electron
`nativeTheme.themeSource`, so `prefers-color-scheme` stays the single switch). The dark palette uses the
blue-gray surfaces of the owner's reference (`--bg #1b2029`, `--surface #242b37`, `--sidebar #1e242e`).
Selection, caret, scrollbars and focus rings use the palette.
## Elevation & Depth
## Type
Depth comes from the official background ladder (contrast < header < shaded < bg), not shadows.
Context menus paint `linear-gradient(#0B1124, #222C41)` at 0.8 behind a 4px blur, radius 8, shadow
`1px 1px 2px rgba(0,0,0,.2)`. Dialogs use the modal container (contrast-bg, 1px tint2 border, radius 8)
over a 25% contrast-bg wash with 2px blur. Notifications use the 15px-radius gradient plate.
Stream tiles have a 2px `--tsv-bg` border and radius 8; their 26px control bar slides in on hover.
System UI stack (`system-ui, -apple-system, "Segoe UI", "Noto Sans", Ubuntu, Cantarell, …`), 14 px base,
line-height 1.45; headings 600–650 weight at 17–24 px; monospace only for the UID and codec lists (data).
Tabular numerals for counts, times and statistics.
## Shapes
Radii follow the official scale: 2 (toolbar buttons), 4 (fields, chips), 8 (menus, tiles, composer,
dialogs), 9 (tree pills), 10 (server card, event rows, selects), 15 (settings sections, theme tiles,
notifications), pill (toolbar, filled buttons, segmented controls).
## Components
Buttons (primary, default, ghost), 34 px icon buttons with `aria-pressed` states, fields with labels above,
radio/checkbox choices with accent colour, range sliders, chat tabs with unread counters, toasts in a polite
live region (errors 10 s, others 5 s). Icons are an inline SVG sprite drawn in one 1.8 stroke style.
- **Buttons:** filled pill gradient (#0058FF → #1365BB) for primary; gray pill on `--tsv-preview-bg`;
plain tint text for secondary; 42px subtle icon buttons whose glyph tints on hover.
- **Inputs:** 26px, `--tsv-bg`, 1.5px transparent border turning tint on focus; selects in the
multiselect look (radius 10); 20px dark checkboxes with a green check; 40×20 toggles; 10px slider
tracks; segmented 26px pills.
- **Chat:** detailed and compact styles. Remote bubbles #697a97 with a 12×14 tail on the first message,
own bubbles #0C1326; compact rows use the source 65px timestamp column and 13px bold sender. Event rows
have a #131824 → transparent gradient and radius 10; composer formatting sits above the 14/18 input
and working emoji, conditional attachment and send actions.
- **Menus:** 30px rows, 22px icons, 13px subtitle section captions, disabled #9c9c9c, destructive
rgb(255,130,130), min width 170, max 260. Client group/volume subpages replace the same popup contents;
Back or Left/Escape restores the original items and focus, not a second flyout.
- **Dynamic settings:** Audio follows Microphone, Output and Processing sections; device controls move
without being recreated. Identities use the source selector/Details/Bookmarks order; creation and rename
use the inline selector editor, and Details always represent the selected identity. Export/private-key
guidance and the separately labelled Current Server Nickname action remain functional product additions.
Whisper receive/list/editor and key binding controls use actual labelled rows, not an
unstyled vertical list. Toggle labels remain left with 40×20 switches right; numeric controls stay
compact and faders include their real live output. All fields, including inputs with implicit text
type, receive the shared source control styling. These changes address the first packaged capture
batch; confirmation screenshots are QA evidence, not assumed passes.
- **Selected values:** language flags and sidebar icon-mode pictograms come from the original local
artwork where legally available. The native value control owns selection; decorative artwork is not
a second accessibility control. Default-device captions require actual platform default metadata,
not guesses from device names; absent alias metadata leaves the caption unset.
## Motion
Motion is limited to the official short state transitions (pill growth 150ms, toolbar 100ms, controls
120ms, toast 180ms); reduced motion removes them. Reduced transparency/increased contrast make menus and
notifications opaque; forced colours use system tokens.
Only colour transitions (120 ms) and the toast entrance (180 ms, exponential ease-out); everything is
disabled under `prefers-reduced-motion`.
## Documented deviations from the official client
- No TeamSpeak logo in the sidebar header: the header shows the TeamsPeach name/icon. Search filters
local server connections/bookmarks only. Connecting and identity selection use a detail-pane form.
The account-bound community action slot instead exposes the real New Connection action. Bookmark
search/add/disclosure remain working; no decorative, nonfunctional folder action is introduced.
- No notification bell, cloud contacts, myTeamSpeak presence or "Setup Chat" footer state: TeamsPeach is
strictly account-free. Offline onboarding includes a real persisted System/Dark/Light choice before
local identity creation/restoration, adapting the official `first_launch.theme` stage (render@2995390)
without its account stages. Existing profiles keep their theme and do not repeat onboarding. The footer
shows the local nickname and UID instead of cloud presence: the approved account-free exception.
- A push-to-talk hold button remains in the server footer in push-to-talk mode for pointer access;
the central toolbar preserves the source Away + microphone/speaker geometry.
- Information/Chat/Files modes are in the detail header. Open private conversations and explicitly
opened server chat are sidebar activities; no extra tab row occupies the channel chat canvas.
- Stream placement reuses the same decoded media/session between chat and the 175px tree overlay.
Tile layout and native controls require the scoped capabilities/evidence in FEATURE_COMPATIBILITY.md.
- The exact 2.013 font and retained source-derived artwork preserve reference provenance; native
component placement/state and any legally unavailable pictograms remain separate acceptance questions.
- A "System" theme tile exists beside the official Dark and Light tiles.
- New server administration, identity, snapshot, whisper, recording and file surfaces use the source
control tokens around real APIs. Token conformity alone does not establish identical screen composition.
- Local UID contacts, public badge display, bookmark folders, Privacy and the
whisper manager bind real local/server operations. They do not emulate a myTeamSpeak account.
The whisper overlay shares the settings controls and list reset; its tree preview derives only from
current-session snapshots, and received-whisper history distinguishes departed identities.
- File Transfer uses source-style icon actions and keyboard-operable minus/value/plus controls, 3/3
per-channel concurrency defaults, the saved download location and shared application rate limits.
- Notification category switches suppress all sounds in that category without erasing per-event choices
or event logs. The disabled-category message and system notification subtitles use the original strings.
- Privacy, Video, Notifications and About follow the owner's explicit original-composition choice.
Unsupported controls keep their source positions but are disabled and explained; no telemetry, cloud
account, Cisco native backend or fabricated service is introduced. Real native decoder policy,
project links and installation details live on working subpages with back-focus restoration.
About retains TeamsPeach branding and real metadata; Report Issue targets the verified project tracker.
Content reporting, Terms and five source-position social tiles explicitly state their unavailable status.
- Whole-screen comparisons remain strict failures where state, content or geometry differs. The full
192-pair checkpoint passed 56; the subsequent four-panel 32-pair checkpoint still failed all whole-screen
comparisons. Runtime workflow success is not pixel parity. Build-specific evidence and residuals are in
`docs/evidence/official-parity/qa-parity-harness.md`.
## Do's and Don'ts
- **Do** take every new value from the installed client and cite its offset in the evidence specs.
- **Do** keep native caption colors aligned with `--ts-new-header-bg` and `--tsv-font-color` where supported.
- **Do** retain stock token names and the explicitly supported native theme-import subset; no DOM fallback.
- **Don't** reinterpret, restyle or "improve" the official look; deviations above are product constraints.
- **Don't** present unavailable account or native controls as working; original-layout compatibility rows
must be disabled, explained and incapable of storing an ineffective preference.
- **Don't** claim full feature parity from visual parity; see `FEATURE_COMPATIBILITY.md`.
+295 -17
View File
@@ -1,43 +1,321 @@
# TeamsPeach ↔ TeamSpeak 6 server features
Status: **proven** = exercised against the real server 10.10.10.160 (TS6 6.0.0-beta13.1) with the real
UI, evidence path given; **implemented** = code + unit/loopback tests, no live proof yet;
**blocked** = not available, reason given. Windows x64 only unless stated.
## Native-only cutover and verification (2026-11-10)
The current product source is Rust/Slint with in-process Rust core services, native DSP, Skia and
source-built libwebrtc. The Electron runtime, interface, consumer suites and launch/build tooling have
been removed. This owner-authorized source cutover is **not** completion of all native/mobile acceptance.
`native/compatibility.json` retains 718 pending behavioral requirements; none are promoted to passes.
Historical browser-client evidence below remains useful regression history, never native acceptance.
For historical deleted source, use the revision-pinned
[pre-cutover tree](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6).
It is reference-only, not a development/runtime dependency. Current commands are Cargo/`xtask` interfaces
in README; no historical runtime or harness is needed to build the native client.
Windows x64 WebRTC was built from pinned SDK `88705b15086ecbe2c26ee91ede6203f974a0fc62` and
WebRTC `9c3a1386f07e4348c28cd85c066821cebc3b56e4`; `native/native-deps.lock.json` records the
resolved DEPS, patches, effective GN arguments, compiler, archive gates and artifact hashes.
The native CXX bridge compiled against that source-built archive. No mutable prebuilt was used.
`native/tools/codec_probe.cpp` exercised the production software-only decoder factory with four
independently encoded synthetic 64×48 single-frame fixtures. H264 High decoded through FFmpeg,
AV1 Profile 0 through dav1d, and VP8/VP9 through libvpx. Every output matched the corresponding
independent FFmpeg I420 reference byte-for-byte. Fixtures and outputs were generated under
`target/codec-fixtures`; this proves these small decode cases, not sustained playback, hardware
acceleration, official-peer compatibility or other targets.
A separate real native PeerConnection loopback negotiated and transported generated video through
the production sender, receiver and bounded display path: 13 frames decoded by libvpx, 12 presented
with the expected red pixels, and one source-stop callback. Terminal cleanup removed the pending
frame. `target/codec-fixtures/peer-loopback.png` is the captured decoded image, not a UI mock.
This check exposed and fixed duplicate Opus linkage: WebRTC's 443 external Opus symbols and their
references are isolated from the unchanged voice-core codec, while unrelated assembly objects are
preserved byte-for-byte. No physical microphone, speaker, camera, screen capture or working server
was used for these checks.
## Approved original panel composition
Historical browser-client checkpoint: the paragraphs in this section describe that build, not a native pass.
The owner selected the original TS6 composition for Privacy, Video, Notifications and About. Root
sections now retain the source order with explicit unavailable states. Actual decoder controls are in
Video → Chromium Video Options; installation diagnostics and project links are subpages of About.
Report Issue opens the verified project issue list only through the external-link confirmation.
No telemetry, account integration, Cisco backend, content-report service or social affiliation is implied.
`approved-panels-confirmed/result.json` under `C:/Users/Admin/tmp/teamspeach-parity-complete-20261102/`
passed all four workflow groups and 32 captures with no external openings, network attempts, capture
attempts or renderer errors. Locale, notification overrides, licence/changelog navigation and real
decoder-policy restart passed separately. `approved-panel-pairs` still reports 32 strict visual failures;
that result is not converted into a pixel-parity pass by the approved composition change.
## Current local workflow corrections
Historical browser-client workflow checkpoint; these behaviors remain native requirements unless corrected below.
Identity export and Copy UID are in the identity selector's context menu (also Shift+F10).
Export still requires the private-key warning confirmation. Disconnected nickname changes use
Details; a connected own-client nickname is edited in its information header. Bookmarks have one
manager in the sidebar, not a second Settings category. Language selection is persisted for restart.
The identity migration, including warning cancellation and nickname persistence, passed the actual
isolated renderer/native-CLI scenario at
`C:/Users/Admin/tmp/teamspeach-parity-complete-20261102/identity-context-fixed/result.json`.
The comprehensive packaged matrix (`full-geometry-matrix/`) completed 192 pairs: 56 passed, 136 failed,
with no blocked navigation. All eight theme/locale/size variants of main/full/few/empty, private chat,
server bans and client lists passed. Remaining whole-screen failures are not whole-client parity.
Final verification and artifact hashes are in `docs/evidence/official-parity/qa-parity-harness.md`.
Navigation intentionally omits Account/Remote Apps; local-contact, privacy, video-backend and About
content also differ. Remaining geometry is not automatically an authorized exception.
## Expanded local panels checkpoint (2026-11-01)
Historical browser-client evidence only. “Current” in the retained table means the recorded 2026-11-01 build.
This supersedes the earlier absence of local contacts below. Remote Apps remains explicitly excluded.
The earlier tables remain historical evidence, not a declaration that all current screens match TS6.
Runtime artifacts are under `C:/Users/Admin/tmp/teamspeach-exact-design-20261101/`;
the exact build hashes and limits are in `docs/evidence/official-parity/qa-parity-harness.md`.
| Surface | Current exercised result | Boundary |
|---|---|---|
| Bookmark folders and connection options | Actual editor, nickname/channel/startup persistence, current-channel insertion, stale-session drag rejection and duplication passed; real Windows DPAPI save/reveal/restart/clear passed | Startup routing was exercised with injected enumeration and real offscreen connect rejection; live joins and Linux/macOS key stores remain unverified |
| Privacy and Markdown Help | Actual trusted-host subpage and production Markdown examples opened; concurrent confirmation/reset regression passed | No cloud typing/presence or telemetry service |
| Key bindings | Actual profile/binding persistence and process restart passed after the contents-layout visibility fix | Native global shortcut registration was not exercised |
| Four-level noise reduction | All levels persisted via the native range control for the selected input device | Independent processing; no physical microphone or native-DSP identity proof |
| Remote Apps | Excluded by the owner's explicit instruction; erroneous intermediate integration removed | Historical test artifacts describe only that removed intermediate implementation |
| Server icons and snapshot transfer ownership | Main/renderer consumer tests cover session grants, reconnect, partial failure and recycled transfer IDs | No successful live server icon mutation is claimed |
| Local contacts and public badges | Model/prefs/catalog tests and actual contact add/alias/restart passed; offline state is retained honestly | Not cloud contacts, badge ownership/redeeming or global presence |
| Rich chat | Actual history IPC/restart, scope isolation and local KaTeX/Mermaid hydration passed | Synthetic messages, no server traffic; sandbox permissions tested separately |
| Rich-text composer (post-release development) | Real packaged typing, formatting, emoji/slash completion, raw/hybrid settings, selection/undo, conversation isolation, refused sends and IME passed; hostile preview stayed inert with zero network requests | Windows hidden runtime only; the separate v0.1.6 release does not include this post-cut feature |
| Identity related bookmarks | Actual nested/default assignment display and nickname-clearing restart passed without changing UID | The original identity component exposes ordinary nickname, not a separate editable phonetic field |
| Whisper manager and history | Actual hidden UI with synthetic events passed overlay switching, preview, session/recycled-ID cleanup and received-history handling | No live whisper delivery proof; two microphone attempts were refused by the test stub |
| Changelog and licenses | Actual packaged list/detail navigation and focus restoration passed after fixing stringified DOM arrays | Displays this installation's documents, not TeamSpeak service terms |
Strict whole-screen visual parity remains open. The historical pair failures below are not converted
to passes by adding functionality or changing the test wait implementation.
## Historical interoperability baseline
The table below records earlier exercised builds, not automatic proof of the current cutover. **Proven**
means the cited earlier run exercised that feature; **implemented** means its recorded implementation
scope, not a new live-server pass. Current account-free acceptance follows the table. Windows x64 only
unless stated. No new live-server mutation or physical media capture is part of the final parity run.
| Feature | Status | Evidence / reason |
|---|---|---|
| First-run nickname, P-256 identity, public UID, restart persistence, rename keeps UID | proven | `docs/evidence/runtime/2026-10-24-identity/` |
| Connect / disconnect by address | proven | identity run `04-connected.png` |
| Saved servers (name + address, no passwords): save, edit, delete, restart persistence, one-click connect, clean switch | proven | `docs/evidence/runtime/2026-10-24-servers-settings/` (connect with same UID, mic muted) + `test/prefs.test.js` |
| Sectioned settings (Идентичность, Серверы, Внешний вид, Звук, Видео, Клавиши, Информация) without dropping the connection | proven | servers-settings run: all 7 panels visited while connected, keyboard Home/arrows, Escape returns |
| Saved servers (name + address, no passwords): save, edit, delete, restart persistence, one-click connect, clean switch | proven | `docs/evidence/runtime/2026-10-24-servers-settings/` (connect with same UID, mic muted); [historical preferences tests](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/test/prefs.test.js) |
| Sectioned settings (Identity, Servers, Appearance, Audio, Video, Keys, Information) without dropping the connection | proven | servers-settings run: all 7 panels visited while connected, keyboard Home/arrows, Escape returns |
| Theme: system / dark / light | implemented | dark captured in servers-settings screenshots |
| User themes / extensions | Current implementation; format- and `--tsv-*` token-compatible, not official DOM-class compatible | `docs/themes.md`; current consumer unit suite and guarded runtime acceptance below |
| Server password on connect | implemented, not exercised | the test server has no password |
| Channel tree, join channel, password channels (inline prompt) | proven (join), implemented (password) | probe joined `cs`; no password test performed |
| Voice TX/RX (Opus via core), talking indicators, mute, deafen RX+TX block/restore, PTT, open mic | proven | `docs/evidence/runtime/2026-10-24-voice-chat/` (synthetic capture device, real path after it) |
| Voice TX/RX (Opus via core), talking indicators, mute, deafen RX+TX block/restore, PTT, open mic | proven between two TeamsPeach clients with synthetic capture | `docs/evidence/runtime/2026-10-24-voice-chat/`; the path after capture is real. Live microphone voice with the official TS6 client and Asahi hardware operation are not proven |
| Voice activation (local voice detector in the core, sensitivity High/Normal/Low, 100 ms preroll, 400 ms hangover) | proven between two TeamsPeach clients with a real speech recording as file-fed capture; detector unit tests on real speech and synthetic noise | `docs/evidence/runtime/2026-10-24-vad-dev/`, `docs/evidence/vad-0.1.4.md`: speech opens and silence closes the gate, mute/deafen/push-to-talk-not-held/disconnected send nothing, setting persists. A live microphone, an official TS6 receiver and native ARM64 hardware are not proven (ARM64 unit tests run under qemu) |
| Long-session capture freshness and offline Opus fidelity | measured with real Chromium fake-file capture and native encoder/receiver, not natural microphone or server interoperability | `docs/evidence/voice-timed-20261029.json`: before/after 190 s, 9500 frames each, stable 48 kHz mono EC/NS/AGC; 600 ms renderer stall previously replayed 30 frames in 10 ms, now discards 20 older-than-200-ms frames. Both codecs at quality 0/6/10 measured. Synthetic session did not reproduce progressive barrel coloration; subjective live report remains unresolved. Official UI estimator vs unknown native DSP/encoder distinction: `docs/evidence/voice-official-source-20261029.json`. |
| Private chat | proven | voice-chat run `15/16-*.png` |
| Channel chat | proven error path | server denies guests: TS 2568, permission 224, shown in UI |
| Server chat | implemented | not exercised live |
| Mic/output device selection | implemented; output routing proven in loopback | `2026-10-24-loopback-browser-pipeline/` |
| Mic/output device selection (Settings and right-click menus on the footer buttons) | proven on real hardware (Windows) | `2026-10-24-audio-devices/`: 6 inputs + 6 outputs listed without capture (matches the OS endpoint inventory), choice persists across restart, menus do not toggle mute/deafen; output routing also proven in loopback |
| TS6 screenshare viewing (P2P): discovery, join, answer, ICE buffering, stop | proven | `2026-10-24-ts6-stream-view/`: AV1 2560×1440 ~59 fps, 2298 frames, D3D11 decoder |
| Realign / reconnect offer renegotiation | implemented | unit tests + loopback (2 offers/2 answers); no realign seen live |
| Stream audio | implemented | live stream advertised `audio=0`; loopback 139 inbound audio packets |
| SFU streams | blocked | P2P only; `notifysfuaccessinfo` → "не поддерживается" |
| Sending own screenshare | blocked | not implemented |
| Server/channel group labels (`name_mode`), custom group icons, country | proven | `2026-10-24-tree-metadata/`: labels «куколд», «бля ща», 6 custom icons, RU |
| Independent simultaneous P2P viewers, native fullscreen/Escape and picture in picture | real local WebRTC and historical native Windows fixture proof, not new live-server proof | `C:/Users/Admin/tmp/teamspeach-ui9-20261024/dev-streams/result.json`: native PiP HWND/topmost and cleanup before the desktop-test prohibition. Redesigned player: `C:/Users/Admin/tmp/teamspeach-player-refine-20261024/final-stage/result.json`, 120 offscreen assertions covering two generated receivers, identity/continuity, controls, keyboard, resize/collapse, and actual contained-image proportions. No new native PiP/fullscreen evidence; see `docs/evidence/player-refine-20261024.md` |
| SFU streams | blocked | Exact request fields are partly recovered, but token/URL/auth values and Chromium negotiation interoperability remain unproven; see current limits below |
| Sending own screenshare | generated production sender-to-viewer media verified; native/live interoperability not established | `C:/Users/Admin/tmp/teamspeach-publisher-decoded-pass/result.json`: decoded 640×360 H.264 and audio RMS 0.1063, admission/stop/cleanup. `offscreen-broadcast-final/result.json` under the UI9 evidence root covers 14 UI cases and eight locale/theme/size captures with injected capture only |
| Server/channel group labels (`name_mode`), custom group icons, country | proven | `2026-10-24-tree-metadata/`: two server-supplied group labels retained verbatim in the raw capture, 6 custom icons, RU country code |
| Built-in group icons (ids 100, 200, 300, 500, 600) | partial | server has no file (core: `not_found`, `builtin:true`); neutral badge named after the group |
| Channel icons and channel banners | proven | tree-metadata run: 11/11 channel icons and 11/11 banners from the server's file transfer |
| Host banner | proven | tree-metadata run: server GIF rendered above the tree |
| Host banner | historical server download proven; new behind-card presentation fixture verified | `C:/Users/Admin/tmp/teamspeach-ui9-20261024/offscreen-shell-confirmed/result.json`: compact artwork, theme/locale/window sizes, selectable content, absent-banner cleanup; not a new server-media download test |
| Avatars (server file) | implemented | no client on this server has `client_flag_avatar` |
| Avatars (myTeamSpeak URL) | proven | tree-metadata run: 1 avatar (public https PNG, bytes sniffed; URL allowlisted from server data) |
| Nickname colours | matches official semantics | official UI colours own client and myTS contacts locally (`docs/evidence/ts6-official-client.md`); TeamsPeach highlights own nickname, has no contacts |
| Poke | not implemented | core supports target `poke` |
| Poke, target menus, moderation confirmations, avatar selection | historical real-shell/preload/validator fixture | `C:/Users/Admin/tmp/teamspeach-ui9-20261024/offscreen-menu/result.json`; no live moderation/avatar transactions. Current whisper/menu additions are tested separately below |
| Identity export | proven | packaged Windows run `2026-10-24-windows-package/result.json`: real core CLI export through the app (only the native save dialog answered by the harness), file starts with `[Identity]`, status shows the UID |
| Identity import / restore from backup | implemented, not exercised | uses the same core CLI; import of a file produced by the official TeamSpeak client not verified |
| Hardware video decode on/off | proven (policy) | packaged run: saved off → restart → launched with `disable-accelerated-video-decode`, engine reports `disabled_software`. Separately, the live TS6 stream decoded AV1 with `D3D11VideoDecoder` while allowed; no claim for other codecs |
| Cisco OpenH264 toggle / per-codec backend choice | not possible in this engine | Chromium WebRTC decodes H.264 with FFmpeg (OpenH264 only encodes) and exposes no decoder selection; stated in settings |
| Linux x64 / arm64 packages | in CI | release workflow written; results only from finished runs; Asahi hardware not reachable |
| Windows x64 package | local build | built on the developer PC, not in CI |
| Linux x64 / arm64 packages | released (pre-release v0.1.1), built in CI | release run #18 on `71300ff`: tests, core smoke (arm64 under qemu), every packaged arm64 ELF 16 KiB-compatible, static AppImage runtime starts in a slim container (arm64 under qemu); `docs/evidence/release-v0.1.1.md`. v0.1.0 ARM64 AppImage is broken (needs `libz.so`). Not run on Asahi hardware (target unreachable) |
| Windows x64 package | released (pre-release v0.1.1), local build | built on the developer PC from `71300ff`, static CRT core, provenance file attached; packaged smoke in `docs/evidence/runtime/2026-10-24-windows-package*/`; not tested on a pristine Windows |
| macOS, Windows ARM64 | blocked | no macOS host; Windows ARM64 needs the VS "MSVC ARM64 build tools" component (not installed) |
| Server/channel group (role) and permission management | not implemented | groups are displayed read-only; no assignment or permission editing |
| General file browser / file transfer | not implemented | file transfer is used internally only to download icons, banners and avatars |
| Other TeamSpeak 6 features not listed here | not implemented | TeamsPeach does not claim full TS6 parity |
| Server/channel group (role) and explicit client/channel permission management | implemented; controlled command/wiring coverage, not live server proof | Real verbs and target/connection-generation guards; production-shell fixture confirms group/permission payloads and cancel paths. Unknown effective rights remain server-decided |
| Per-participant local volume/mute/reset | generated native two-codec decode/mix plus real UI transport verified | Whole native suite: 66 unit tests including both codecs, gain/mute/reset and subprocess proof; max sample error 2, target mute retains other speaker exactly. Connection-scoped UID identity and recycled decode queues tested; no new live call claim |
| Channel member collapse and sidebar resize | isolated Electron UI verified | `C:/Users/Admin/tmp/teamspeach-ui9-20261024/dev-tree/result.json`; actual pointer/keyboard, per-server persistence, child headings retained; no active live-call proof |
| Selected-application broadcast audio | Windows native capture proof and synthetic bridge-to-WebRTC proof are separate; Linux runtime unverified; macOS blocked | `docs/evidence/native-app-audio-proof.json` records prior Windows 64.7 dB selection isolation, before later ancestry/lifetime fixes. `smoke-out/appaudio-synthetic/result.json` proves exact-contract PCM through production transport/worklet and decoded WebRTC. Combined native-to-WebRTC verification needs an isolated audio endpoint; prior default-output tone was potentially audible. Linux requires pactl/parec and PulseAudio or PipeWire-Pulse; macOS SDK/CoreAudio/TCC implementation is missing |
| General file browser / file transfer | Implemented in the historical browser-client cutover, not part of this baseline | Legacy TCP transfer and app-wide settings; native acceptance remains separate |
| Other features | No blanket parity claim | The current full feature matrix identifies owners, observed tests and exact remaining prerequisites |
## Earlier account-free acceptance checkpoint (2026-11-01)
Scope is strictly local/server functionality without an account; central myTeamSpeak/homebase services and
Remote Apps integration are excluded by instruction. Server-hosted `MATRIXCHAT` is not an account-only
exception: its native transport remains unimplemented (see below). No account UI is substituted for a
missing local feature. Tests use disposable state and controlled inputs; protocol fixtures do not establish
real server interoperability, and synthetic renderer IPC is never native transaction success.
Historical exercised gates: **318 Node consumer tests passed**, one deliberately skipped live release-list
test; **152 native unit tests passed**, one optional external-PCM audit ignored; **5 native stdio bridge
tests passed** after contract fixes. Full logs are in
`C:/Users/Admin/tmp/teamspeach-official-parity-20261101/qa-final/`. Actual release subprocess checks also
passed: two simultaneous core PIDs sharing the canonical identity without private-key runtime copies,
and 30 disconnected administration requests plus four malformed requests rejecting with exact errors.
Linux x64 additionally passed **154 native unit tests and 5 stdio tests** in an approved disposable
Rust 1.96 container. The same source cross-built for `aarch64-unknown-linux-gnu`; its ELF passed the
16 KiB page-alignment check (64 KiB LOAD alignment, GLIBC_2.34). It was not executed on ARM/Asahi.
Only owned temporary build files/containers were removed afterward; runner services/config were unchanged.
Actual hidden runtime passes include all twelve settings categories in EN/RU plus restart, native identity
CRUD/improvement cancellation, whisper/keybind persistence/restart, rich-chat history and safe local
math/diagram rendering, theme-resource confinement, onboarding theme-save ordering, menus, broadcast UI,
and administration/recording/file-browser controller rendering. The whole-shell batch passed 1,001 checks
over 324 cases. **224/224 class-matched visual metrics passed** at 1553×998 after correcting the independent
reference's source-observed 260 px popup modifier; this is not whole-image or whole-client identity.
| Feature family | Owner | Current observed evidence | Scope boundary |
|---|---|---|---|
| Multiple identities, additive import/export, defaults, guarded delete, hash-cash resume/cancel | AstraIdentity | Native profile/improvement and real CLI stdio tests; hidden actual create/edit/default/delete/improve-cancel passed | No official exported-key corpus claimed |
| Eight simultaneous server slots, viewed/input routing, reconnect epochs, bookmark identity | AstraConnections | Connection/media consumer units passed; actual two-core release subprocess proof passed | No new server joins; native microphone routing hardware not exercised |
| Channel CRUD/subscriptions, away/talk power, server moderation/keys/passwords/log/client database | AstraCore | Native wire/target units and 13 renderer behavioral cases passed; real disconnected-core rejections passed | Controlled protocol replies, not successful live server mutation |
| Server snapshots, typed properties, UID memberships and icons | AstraCore | Snapshot codec and main consumer suites passed | Import is non-atomic; server icon canonicalization and server feature support remain server-dependent |
| Whisper lists/groups/quick/reply, epoch gating and incoming deny | AstraAudio | Native generated Opus whisper route/block and target tests passed; local store/hold tests passed | Offline core rejection is not live whisper interoperability; contacts-only targets excluded |
| Per-device DSP, voice activation/PTT delay, dB fader, output/notification routing | AstraAudio | Native detector/mix tests and generated worklet consumer tests passed | Independent processing, not private native DSP identity; physical audio not exercised |
| Global hotkeys | AstraAudio | Windows/Linux parsing/backend tests and Linux x64/ARM compilation passed; offscreen no-helper guard passed | macOS global shortcuts unsupported; Windows/Linux OS registration/portal runtime deliberately unexercised |
| Legacy files, opaque chooser capabilities, commit/cancel/no-overwrite, global settings | AstraFiles | Real loopback TCP byte/hash/pacing/cancellation tests and main/renderer/scheduler consumer suites passed | HTTPFT/S3 explicitly unsupported; no speculative fallback; filesystem hard-link requirement fails safely |
| Recording/WAV timing, tracks, pause/finalize, notification log/matrix, OS local settings | AstraRecordThemes | Generated native PCM/WAV tests and main/renderer policy suites passed | No real microphone, OS startup/lock action, notification sound or private recording exercised |
| Local themes and appearance options | AstraRecordThemes / AstraVisual | Functional confinement suites and real selected CSS/font/image/restart/denied-remote smoke passed; actual settings pixels inspected | Package/token compatibility only, not official DOM-class compatibility |
| Local history, safe rich chat, drafts/unread, links/images, file attachments | AstraChat | Main/parser suites; actual 621-row history IPC/restart, local KaTeX/Mermaid and inert malicious-content smoke passed | Non-own-channel legacy delivery unverified; central chat excluded, server-hosted Matrix room actions missing |
| P2P stream extras, layout, internal/standalone popout and publishing controls | AstraStreams | 249 generated-media stage checks; actual sender→receiver video/Opus, admission, rate changes, pause, ban and cleanup passed | macOS selected-application audio unimplemented; standalone viewport emulation limitation below; no live SFU claim |
| Official visual system and EN/RU catalogs | AstraVisual / AstraQA | All twelve settings categories EN/RU/restart; actual full three-pane/settings/menu pixels reviewed; 224 class-matched metrics passed | Historical 22/22 source-reference probes are not whole-client identity |
The original feature inventory, owners, evidence and corrected exclusions are in
[`docs/evidence/official-parity/final-feature-matrix.json`](docs/evidence/official-parity/final-feature-matrix.json).
Consolidated results and exact package hashes: `qa-final/verification.json` and `qa-final/package-manifest.json`
under the evidence root above. The isolated package is `build/win-unpacked/TeamsPeach.exe`; no installer
was run, no version was changed and nothing was published.
## Remaining implementation gaps and external verification prerequisites
Authorized live check on 2026-11-02: `server_info` and the resulting snapshot from 10.10.10.160:9987
announced P2P=true and Matrix/SFU/HTTPFT/S3=false to core 0.1.6. Both mute flags were confirmed.
Two temporary identities disconnected cleanly and their local profiles were removed; no token,
invitation, media or server-setting mutation was attempted. This is a per-client/session advertisement,
not a claim about every server configuration. Evidence: `docs/evidence/official-parity/server-sfu-prerequisite.json`.
- **Server-hosted Matrix chat:** static frontend review on 2026-11-02 corrects the earlier blanket Matrix
exclusion. `MATRIXCHAT` selects a server-identity participation, separate from account/homebase login.
It supports channel/private rooms, invitation accept/reject and room-based edit/reply/reactions;
pinning is non-direct-room-only and other actions remain permission/event-dependent. Static native
constructors establish `chatlogintoken`, `notifychatlogintoken token=...` and
`requestchat type=private clid=<uint16>`, but well-known binding, token-to-Matrix login/renewal,
device/session lifecycle, server UUID derivation and sync/event envelopes remain unresolved.
No authenticated native/server-room exchange has been captured. Generic Matrix login is not a valid
substitute, and no inert setting or room-action controls are added. Exact source chain and scope:
`docs/evidence/official-parity/ts6spec-chat.md`, section 0.
- **SFU:** `docs/evidence/official-parity/sfu-native-inspection.json` and
`docs/evidence/official-parity/sfu-request-construction.json` recover command/envelope fields,
not authoritative token origin/renewal, exact optional/value branches or a proved mediasoup-to-Chromium
negotiation. `docs/evidence/official-parity/server-sfu-prerequisite.json` records a read-only check of the configured server's empty
SFU endpoint; it does not prove absence of an advertised runtime capability. No controlled SFU endpoint
has been exercised, so SFU remains blocked rather than falsely successful.
- **HTTPFT/S3:** `docs/evidence/ts6-filetransfer-native.json` and `docs/evidence/ts6-filetransfer-native-continuation.json` record
command arguments but not complete endpoint/base-URL binding, operation response envelopes, S3 payload
mapping or required headers/verb values. No controlled newer-storage server fixture is available.
- **macOS implementations:** selected-application audio capture is not implemented; a CoreAudio/TCC
backend is still needed. Global shortcuts are explicitly unsupported by the non-Windows/non-Linux
branch of `core/src/hotkeys.rs`. These are implementation gaps, not merely unexecuted tests.
- **Non-own-channel chat:** arbitrary legacy channel-text delivery is not established by the own-channel
and UID-bound private-message fixtures. It remains specifically unverified; current results do not
establish permission semantics or delivery to a channel the client has not joined.
- **Platform/native behavior:** hidden Windows tests and Linux cross-compilation do not prove Asahi/M1 hardware, Linux portal/global
shortcuts, physical microphone/speaker/camera/application capture, native fullscreen/PiP or official
native DSP sound identity. Those are stated as verification limits, not silently emulated passes.
- **Standalone pop-out:** the actual Electron 44.9.3 offscreen guest starts with a 0×0 native viewport.
`docs/evidence/official-parity/popout-offscreen-limitation.json` records the source-supported engine
explanation. Explicitly authorized test-only CDP viewport emulation exercises the real adopted video,
MediaStream, continuing RTP, child controls and restore/cleanup. It does not verify unmodified native
offscreen painting or a normal visible child window; production flags are not weakened for the test.
## Native runtime integration and Windows offline evidence
The native host now owns a dedicated Tokio application worker and constructs the existing profile,
connection, file, audio and stream services. `native/src/app/runtime/` routes captured shell/chat/settings
intents and authoritative core/audio/platform events; settings use an ordered bounded consumer with
pending control identities and explicit completion/error state. First-run profile/import/recovery
decisions precede writable profile ownership, and private-key import and staging-discard operations
require an explicit warning confirmation.
`ui::application::bind` constructs a generation-scoped Slint attachment without entering its event
loop. It keeps Slint objects on the UI thread, applies coalesced Send-only snapshots, drains bounded
effects/prompts, and updates latest video images without re-projecting the tree for each frame.
Native theme font bytes pass the existing confined asset policy and are registered with Slint's
pinned Fontique interface; CSS Color 4 token values are converted to the sRGB UI surface.
`AppConfig::isolated` disables network and OS/device actions. Runtime snapshots expose actual
audio-start event counters and structured settings completion errors so a denied action cannot be
mistaken for a successful operation or an unrelated stale error. Mobile call capabilities and UI
generations have separate lifetimes; desktop installation state comes from validated running-package
metadata, not a caller-supplied installed flag.
Windows x64 integration now builds through `xtask build --target x86_64-pc-windows-msvc
--test-harness true`. The full release-profile workspace test command passed, including 461 native
library tests, the real atomic-document replacement regression, connection lifetime tests and updater
contracts. The captured-speech quality test remains explicitly ignored without its external PCM fixture.
Executed native smoke reports (under the local `target/evidence/` directory):
- `native-offline-ui-03/result.json`: actual Slint software rasterization, account-free onboarding,
all twelve settings categories, EN/RU and dark/light at 390/800/1280 logical pixels, actual semantic
combobox values matching persisted selections, math/Mermaid images, literal HTML, real text-input
focus blocking local PTT, microphone permission denial with zero physical endpoint starts, refused
Unicode draft retention/undo/redo, two full profile restarts and stale session rejection.
- `native-migration-01/result.json`: generated legacy profile import, unchanged hashes of five source
files, preserved UID/default identity, security offset 42424242 and history. No existing user profile
was imported or modified. This run predates the controlled-combobox correction checked above.
- `native-media-loopback-01/result.json`: production native PeerConnections decoded moving generated
video (13 decoded, 12 presented, libvpx) and 46 decoded audio blocks / 22080 samples, RMS 0.06160.
Audio was observed at the real decoded AudioSink before the closed output gate; no speaker or
microphone was opened. This is same-host RTP/ICE/DTLS evidence, not official TS6 signaling acceptance.
Smoke failures found and corrected an OS-capability page which refused navigation, stale native
combobox captions despite persisted values, missing text-focus propagation to local shortcuts and
Windows atomic overwrite failing while the old reader remained open. Windows publication now uses
`FileRenameInformationEx` with POSIX replacement semantics, preserving existing reader handles.
These results do not establish acoustic AEC, physical capture, official-peer interoperability,
Asahi/mobile execution, OS accessibility, installed updater/relaunch or complete visual parity.
Existing Electron evidence above remains historical reference only. Its production runtime/source has
been removed by the native-only cutover; outstanding acceptance gates remain outstanding, not waived.
Windows test-only packaging produced an unsigned NSIS installer (38,668,543 bytes) and ZIP
(52,858,951 bytes) in `target/evidence/native-package-03/`. Its `x86_64-pc-windows-msvc/verification.json`
passed real archive extraction, application/helper ISA and imports, asset/license hashes and the
browser/Node/WASM exclusion checks. NSIS's x86 uninstaller/plugin are classified separately from the
x64 application. The executable extracted from that ZIP passed the complete offline UI smoke from
its own package directory: `target/evidence/native-packaged-smoke-01/result.json`.
The installer was not executed, no default installation was modified, and no release manifest/update
feed was published. Both artifacts have `testOnly=true` and `release_eligible=false`; they are not a
production migration or installed update/relaunch proof.
### Ordinary desktop startup correction
The first test ZIP failed normal Windows launch with `Attach the desktop lease after the Slint
window is realized`; offscreen smoke did not cover the winit startup ordering. Desktop attachment
now awaits Slint's native-window future on its UI executor, retains/cancels that task with the UI
generation, and propagates real initialization failures. Closing onboarding also now stops the
application before profile services exist (including failed profile inspection).
`native/examples/desktop_startup_smoke.rs` exercised the real Windows window and desktop lease,
captured its 1280×800 pixels and closed it through the normal close-request callback. Evidence:
`target/evidence/native-desktop-startup-02/`. The corrected portable `teamspeach.exe` was also started
normally with a fresh test profile, observed as a visible TeamsPeach window, then sent WM_CLOSE:
exit code 0, empty stdout/stderr. No microphone/speaker or server connection was started.
The desktop delivery is `TeamsPeach-0.1.7-win-x64-startup-fix/` and the matching ZIP; the executable
SHA256 is `9d4d898b7ea723a9e0cdff2ca47cf4dbbdb2981163a6403498ab010c7bad9a95`.
+23 -5
View File
@@ -1,10 +1,28 @@
# TeamsPeach — notices
- TeamsPeach's own code carries no open-source license yet (`UNLICENSED` in package.json): all rights
reserved by its owner until the owner chooses a license.
- Electron and Chromium license texts ship at the root of the application directory
(`LICENSE`, `LICENSES.chromium.html`), as placed there by electron-builder.
- TeamsPeach's own code carries no open-source license yet: all rights reserved by its owner until the owner
chooses a license. Removing the former renderer does not grant redistribution rights.
- The application uses native Rust/Slint UI and media components; Electron, Chromium and the renderer's
WebAssembly DSP module are not bundled runtimes.
- The native core (`teamspeach-core`, built on ReSpeak tsclientlib, libopus and other Rust crates)
ships its complete third-party notices in `teamspeach-core-THIRD_PARTY_NOTICES.md` in this folder.
has its third-party notices in `core/THIRD_PARTY_NOTICES.md` in the source tree, also exposed in native About.
This includes the earshot voice detector (MIT OR Apache-2.0), whose crate embeds the small neural network
it runs (`weights.bin`) under the same license.
- The interface font Noto Sans (variable regular and italic, version 2.013, © 2022 The Noto Project Authors) is
bundled under the SIL Open Font License 1.1; see `NotoSans-OFL.txt` in this folder. The files are the exact
copies shipped in the installed official TeamSpeak 6 client bundle, unmodified.
- `teamspeak-client-icons-PROVENANCE.md` preserves the former renderer's TeamSpeak artwork source, hashes,
transformations and rights restrictions as a historical record, not a native asset inventory. Those renderer
sprites, masks and flag files are not migrated to the native resource bundle. The TeamsPeach application icon
is retained unchanged as `native/resources/icon.png`.
- Native microphone DSP uses the WebRTC-derived Sonora AEC3, noise suppression and adaptive AGC2 chain,
BSD-3-Clause. See `sonora-NOTICE.txt` and `dsp/vendor/provenance.json` for source/version and local patch
provenance. `denoise-THIRD-PARTY-NOTICES.txt` retains the historical DSP dependency and Rust standard-library
license texts; it is not a complete dependency inventory for the native application. Native About explicitly
reports the absence of a complete native UI/media dependency notice inventory.
- The 54 notification WAV files in `native/resources/sounds/` are copied unchanged from the installed official
TeamSpeak client at the owner's direction.
No redistribution licence has been identified; source hashes and event mapping are recorded in
`teamspeak-client-sounds-PROVENANCE.md`. They are not relicensed by TeamsPeach.
- TeamSpeak is a trademark of TeamSpeak Systems GmbH. TeamsPeach is an independent client and is not
affiliated with or endorsed by TeamSpeak Systems GmbH.
+99
View File
@@ -0,0 +1,99 @@
Noto Sans 2.013 variable, axes wght 100-900 and wdth 62.5-100 (native/resources/fonts/NotoSans-VF.ttf,
NotoSans-Italic-VF.ttf): unmodified copies of the files shipped in the installed official TeamSpeak 6 client
(html/client_ui/b1d0ab70303caea663db.ttf, name ID 3 "2.013;GOOG;NotoSans-Regular", sha256
74df1f61ab9d4bfaa961c65f8dc991deaae2885b0a6a6d6a60ed23980b3c8554; html/client_ui/628d4779d07f4e15066b.ttf, name ID 3
"2.013;GOOG;NotoSans-Italic", sha256 fe5a1fafb96618733aa4ea4c14a2e76ee65fee0d042b040e374f17575467e433).
Copyright 2022 The Noto Project Authors (https://github.com/notofonts/latin-greek-cyrillic)
This Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at:
https://scripts.sil.org/OFL
-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------
PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font creation
efforts of academic and linguistic communities, and to provide a free and
open framework in which fonts may be shared and improved in partnership
with others.
The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply
to any document created using the fonts or their derivatives.
DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.
"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).
"Original Version" refers to the collection of Font Software components as
distributed by the Copyright Holder(s).
"Modified Version" refers to any derivative made by adding to, deleting,
or substituting -- in part or in whole -- any of the components of the
Original Version, by changing formats or by porting the Font Software to a
new environment.
"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.
PERMISSION & CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:
1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions, may be sold by itself.
2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.
3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the corresponding
Copyright Holder. This restriction only applies to the primary font name as
presented to the users.
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.
5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created
using the Font Software.
TERMINATION
This license becomes null and void if any of the above conditions are
not met.
DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.
File diff suppressed because it is too large. Load diff
+69
View File
@@ -0,0 +1,69 @@
TeamsPeach native capture DSP (dsp/)
===================================================================
The native microphone capture processor is linked as Rust code from TeamsPeach's
dsp/ crate. It runs Sonora's integrated AEC3, noise suppression and adaptive AGC2
chain according to the selected settings. There is no renderer WebAssembly ABI.
The noise-only filter-bank implementation remains a Rust-test-only behavioral
reference, not a second production capture stage.
Pinned Sonora packages include (all 0.2.0, BSD-3-Clause):
sonora, sonora-aec3, sonora-agc2, sonora-common-audio,
sonora-fft, sonora-ns, sonora-simd.
Source: https://github.com/dignifiedquire/sonora
Commit: a024d6ef8351add55be5e8b1d6cc35f555787660 (per the published crates'
.cargo_vcs_info.json)
Registry: crates.io; package checksums (SHA-256 of the .crate files)
sonora 0.2.0 2e1ce442ab5cb392c4067b8f2cced20be4cf12e479f6dfbf44acbe9b14ac9250
sonora-ns 0.2.0 d511feef19302c716d245c4555087d161ba91c178735ea11107dcce0d0b7a86f
sonora-fft 0.2.0 27e272c70f34363afb5382dd1818c05f8f63ef6785635736a14e9ccbbb5ba012
sonora is a pure Rust port of the WebRTC Native Code audio processing module
(M145 plus later upstream fixes), via PulseAudio's webrtc-audio-processing
extraction. TeamsPeach vendors sonora and sonora-agc2 with local mono AGC2 and
limiter channel-adapter allocation/copy reductions. Exact modified files,
upstream archive checksums and patch scope are in dsp/vendor/provenance.json;
upstream license and copyright texts are retained in each vendored package.
Other pinned Sonora packages use their registry sources. No end-to-end
allocation-free guarantee or bit-identical behavior with TeamSpeak's proprietary
DSP is claimed.
The native executable also uses the Rust standard library (core, alloc, std and
its bundled allocator and math routines), licensed MIT OR Apache-2.0. Historical
DSP dependency license texts are retained in denoise-THIRD-PARTY-NOTICES.txt;
that file is not a complete inventory of the native executable's dependencies.
License of the Sonora packages (BSD-3-Clause, verbatim):
Copyright (c) 2011, The WebRTC Project Authors. All rights reserved.
Copyright (c) 2016, Arun Raghavan and contributors. All rights reserved.
Copyright (c) 2026, dignifiedquire. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the
distribution.
* Neither the name of Google nor the names of its contributors may
be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
@@ -0,0 +1,373 @@
# Official TeamSpeak 6 client icon artwork in TeamsPeach — provenance
**Historical scope.** This document records the removed reference renderer's artwork imports and transformations.
The `app/renderer/` paths below are historical, not current native resource dependencies. The renderer SVG sprite,
mask files and country-flag files were not migrated into the native resource bundle. Their original source hashes
and redistribution restrictions are retained here; removing the renderer grants no new rights. The separate
TeamsPeach product icon was relocated unchanged to `native/resources/icon.png` (SHA-256
`87cfe10da3359eae8c000d0e5b2491524e132c4f9c34a54bfd0c94296c97c422`).
The SVG symbols in the sprite of `app/renderer/index.html` and the four mask files in `app/renderer/assets/icons/`
are artwork of the official TeamSpeak 6 client (TeamSpeak Systems GmbH), copied from the client installed on the
owner's workstation at the owner's direction (2026-11-01 brief: the installed client's design, value for value).
**Licence status.** No licence grant for redistributing this artwork has been identified. The installed client is
governed by its own licence agreement (`licenses/en/la_desktop.html` in the client installation). TeamsPeach does not
relicense this artwork and does not claim the right to publish it; it is not covered by TeamsPeach's own terms or by
any open-source licence in this folder. TeamSpeak logos, wordmarks, `teamspeak_label`, brand icons, presets and
account/myTeamSpeak-only artwork were deliberately not included; the TeamsPeach name and product icon remain the
product brand (current path `native/resources/icon.png`).
## Source
- Installation: `%LOCALAPPDATA%/Programs/TeamSpeak/html/client_ui` (TeamSpeak.exe file version 6.0.0.0; DESIGN.md
records build 6.0.0.5163 for the same bundle).
- `main.js` sha256 `9d6bea2ee5333086555c36584621c1b3462a83042ce746d3229d6766a9b82c39`; `main.css` sha256 `bc700401d04954d07f82570b060335e2278166db4f618f6cf3dcf8fde1834adf`.
- `images/icons/settings.json` sha256 `82c6a1be9a052fcbabe5b762c21c7893947703fd4db13094c92c48f89ba76f76` maps each TSIcon id to its file.
- TSIcon enum: `main.js` webpack module 58917 (`e.Settings="settings"`, … at offset ≈1959558); the `ts-icon`
renderer is at offset ≈10686241. Offsets below (`@N`) are character offsets in `main.js`.
## Transformations (render-preserving)
Each source file becomes one `<symbol id="i-<TSIcon id>">`. Applied mechanically by a one-off conversion, nothing redrawn:
1. `style` attributes converted to equivalent presentation attributes, because the renderer CSP (`style-src 'self'`)
blocks inline styles. Where a `style` declaration and an official colour class (`tsv-icon-*-fill|stroke`) set the
same property, the class (which the inline style always overrode) would be dropped; no source file needed this.
2. `enable-background` (SVG 1.1 hint, no rendering effect) dropped from `chat_poke.svg` and `chat_poke_solid.svg`.
3. Element ids prefixed with the symbol id (`i-away--label`) and their `url(#…)` references rewritten, so ids stay
unique in one document. Editor metadata (`serif:id`, Inkscape/Sodipodi attributes and `<metadata>`), XML
declarations, DOCTYPEs, comments, `version`, `xml:space`, root `width/height/x/y/id` are omitted.
4. `viewBox` is written as `0 0 <int w> <int h>`, exactly as the official `ts-icon` renderer rewrites it; every
source already had that form. Root class names (`tsv-icon-audio-input`, …) are kept on the symbol.
5. `shape-rendering="geometricPrecision"` is set on each symbol, as the official renderer sets it on every inline icon.
6. At runtime `icon()`/`setIcon()` in `app/renderer/js/dom.js` copy the symbol content inline into the `<svg>` with the
symbol's root class and attributes, as the official `ts-icon` renderer injects `innerHTML`. Ids referenced by
`url(#…)` get a per-instance suffix; other ids regain their source id so official id selectors (`#label`,
`#bar1_step0`, …) apply.
Mask files (`client_detailed_mask.svg`, `contact_mask.svg`, `server_mask.svg`, `channel_mask.svg`) are byte-identical
copies, used as CSS `-webkit-mask` images exactly as the official `ts-icon-stack` (`@3162500`) does.
## Symbols
| Symbol | Source | Source file | sha256 (source) |
|---|---|---|---|
| `i-delay-low` | DelayLow | `images/icons/delay_low.svg` | `16a2c7e08cdcf636a917b1fd3f99445869f0d0c6c24ce3cd6bf80885872a1832` |
| `i-delay-medium` | DelayMedium | `images/icons/delay_medium.svg` | `fb11aab3b06c0555ce164b1e443a40d864ca24556c8fdd0b01663e42d9270700` |
| `i-delay-high` | DelayHigh | `images/icons/delay_high.svg` | `154421a45765777aac316c3a0408e3f867bc7195d22a27c96c918cce166a72ce` |
| `i-accept` | Accept | `images/icons/item_accept.svg` | `c37087a87505a50a…` |
| `i-add` | Add | `images/icons/add.svg` | `06b8d432a7e8265e…` |
| `i-away` | Away | `images/icons/away.svg` | `1dfbb5649223e71e…` |
| `i-away-small` | AwaySmall | `images/icons/away_small.svg` | `dc1ac78a381a1621…` |
| `i-bookmark` | Bookmark | `images/icons/bookmark.svg` | `7c838e615fcdc016…` |
| `i-bookmarks` | BookmarkEdit | `images/icons/bookmarks.svg` | `eb3e1ec7f17c4ef2…` |
| `i-channel` | Channel | `images/icons/channel.svg` | `da88eccbd1bbb7ca…` |
| `i-channel-commander` | ChannelCommander | `images/icons/channel_commander.svg` | `496637e240474ef3…` |
| `i-channel-create` | ChannelCreate | `images/icons/channel_create.svg` | `450e18178dcd006f…` |
| `i-channel-default` | ChannelDefault | `images/icons/channel_default.svg` | `d5937550d3415c0e…` |
| `i-channel-mask` | ChannelMask | `images/icons/channel_mask.svg` | `69e1d3e053e77256…` |
| `i-channel-red` | ChannelRed | `images/icons/channel_restricted.svg` | `80853e27620d57f7…` |
| `i-channel-show-chat` | ChannelShowChat | `images/icons/channel_show_chat.svg` | `16d2d6354dc4b2e1…` |
| `i-channel-status-full` | ChannelStatusFull | `images/icons/channel_status_full.svg` | `6653c7e2bc19548d…` |
| `i-channel-status-restricted` | ChannelStatusRestricted | `images/icons/channel_status_restricted.svg` | `7f92a4e3be437977…` |
| `i-channel-yellow` | ChannelYellow | `images/icons/channel_locked.svg` | `c836375982c5c2bf…` |
| `i-chat-emoji` | ChatEmoji | `images/icons/chat_emoji.svg` | `c4e56048536a96d2…` |
| `i-chat-image` | ChatImage | `images/icons/chat_image.svg` | `b490111ba17ad580…` |
| `i-chat-poke` | ChatPoke | `images/icons/chat_poke.svg` | `482f8e135955e711…` |
| `i-chat-poke-solid` | ChatPokeSolid | `images/icons/chat_poke_solid.svg` | `0324599ddbc4c5e7…` |
| `i-chat-scroll-bottom` | ChatScrollBottom | `images/icons/chat_scroll_bottom.svg` | `ffc342c97703cbca…` |
| `i-chat-send` | ChatSend | `images/icons/chat_send.svg` | `cd23d5874caf4955…` |
| `i-checkbox-checked` | CheckboxChecked | `images/icons/checkbox_checked.svg` | `eec817685169e518…` |
| `i-checkbox-tick` | CheckboxTick | `images/icons/checkbox_tick.svg` | `c37b8bffa558868c…` |
| `i-checkbox-unchecked` | CheckboxUnchecked | `images/icons/checkbox_unchecked.svg` | `058673894173f0be…` |
| `i-client` | PlayerOff | `images/icons/client_normal.svg` | `c974ac95caaa1026…` |
| `i-client-detailed` | ClientDetailed | `images/icons/client_detailed_normal.svg` | `b16e10a88a032d32…` |
| `i-client-detailed-mask` | ClientDetailedMask | `images/icons/client_detailed_mask.svg` | `006e04703e627c8d…` |
| `i-client-detailed-placeholder` | ClientDetailedPlaceholder | `images/icons/client_detailed_placeholder.svg` | `7a35e3c9ba26e91b…` |
| `i-client-detailed-talking` | ClientDetailedTalking | `images/icons/client_detailed_talking.svg` | `01f65ddb3539c052…` |
| `i-client-detailed-voiceless` | ClientDetailedVoiceless | `images/icons/client_detailed_voiceless.svg` | `ee25d4ac9fb53035…` |
| `i-client-invisible` | ClientInvisible | `images/icons/client_invisible.svg` | `9b73e1a670795a58…` |
| `i-client-talking` | PlayerOn | `images/icons/client_talking.svg` | `f6e654923b5257d5…` |
| `i-client-voiceless` | ClientVoiceless | `images/icons/client_voiceless.svg` | `037849d56372402c…` |
| `i-connection-lost` | ConnectionLost | `images/icons/connection_lost.svg` | `8d6fa715ac1ffb0f…` |
| `i-connection-reconnecting` | ConnectionReconnecting | `images/icons/connection_reconnecting.svg` | `d998fa1936eb5fc9…` |
| `i-connection-status` | ConnectionStatus | `images/icons/connection_status.svg` | `6abd9fb0e4fd5829…` |
| `i-connection-status-label` | ConnectionStatusLabel | `images/icons/connection_status_label.svg` | `2015cb11cb504057…` |
| `i-contact-mask` | ContactMask | `images/icons/contact_mask.svg` | `176d68bc8c65caf6…` |
| `i-contact-normal` | ContactNormal | `images/icons/contact_normal.svg` | `110a7768034350b9…` |
| `i-contact-placeholder` | ContactPlaceholder | `images/icons/contact_placeholder.svg` | `d9b9390a77ed44e5…` |
| `i-contacts` | Contacts | `images/icons/contacts.svg` | `4eb8c29de4630f6f…` |
| `i-decline` | Decline | `images/icons/item_decline.svg` | `4eb1851b7e07e77d…` |
| `i-delete` | Delete | `images/icons/delete.svg` | `86b35526820aab24…` |
| `i-dots` | Dots | `images/icons/dots.svg` | `3b5bacf307ef1247…` |
| `i-download` | Download | `images/icons/download.svg` | `a8745797944f94c6…` |
| `i-download-flat` | DownloadFlat | `images/icons/download_flat.svg` | `be8f38d114ced5e2…` |
| `i-drag` | Drag | `images/icons/drag_indicator.svg` | `e07278d722fa784a…` |
| `i-edit` | Edit | `images/icons/item_edit.svg` | `0812e24304ab5359…` |
| `i-emoji` | Emoji | `images/icons/emoji.svg` | `357a4b8688ebc0da…` |
| `i-empty` | Empty | `images/icons/item_empty.svg` | `3141ea74fdb9d539…` |
| `i-exclamation-triangle` | Warning | `images/icons/exclamation-triangle.svg` | `2374cc1524f4d43a…` |
| `i-expand` | Expand | `images/icons/expand.svg` | `98a71fdbac31171d…` |
| `i-fa-align-center` | FaAlignCenter | `images/icons/fa_align-center.svg` | `1f6d10ae5947f152…` |
| `i-fa-align-justify` | FaAlignJustify | `images/icons/fa_align-justify.svg` | `ad8c53483fe90031…` |
| `i-fa-align-left` | FaAlignLeft | `images/icons/fa_align-left.svg` | `d10294d25252aac1…` |
| `i-fa-align-right` | FaAlignRight | `images/icons/fa_align-right.svg` | `eaecfe8bcd8dfbe1…` |
| `i-fa-asterisk` | FaAsterisk | `images/icons/fa_asterisk.svg` | `128f63761bc0c1b5…` |
| `i-fa-block-quote` | FaBlockquote | `images/icons/fa_block-quote.svg` | `c9259e07ca73a9d2…` |
| `i-fa-bold` | FaBold | `images/icons/fa_bold.svg` | `7ad7159a7b833081…` |
| `i-fa-chart-diagram` | FaChartDiagram | `images/icons/fa_chart-diagram.svg` | `80b9c1ca124af38b…` |
| `i-fa-code` | FaCode | `images/icons/fa_code.svg` | `af4f9b9679da1890…` |
| `i-fa-dash` | FaDash | `images/icons/fa_dash.svg` | `d5c7399ad747da9c…` |
| `i-fa-function` | FaFunction | `images/icons/fa_function.svg` | `9c2656ac652dd69b…` |
| `i-fa-h1` | FaHeading1 | `images/icons/fa_h1.svg` | `e979446418683043…` |
| `i-fa-h2` | FaHeading2 | `images/icons/fa_h2.svg` | `6032da9a2c7f9a8e…` |
| `i-fa-h3` | FaHeading3 | `images/icons/fa_h3.svg` | `0f872fd3d422585f…` |
| `i-fa-h4` | FaHeading4 | `images/icons/fa_h4.svg` | `7db6b3cc838e0706…` |
| `i-fa-h5` | FaHeading5 | `images/icons/fa_h5.svg` | `946825713599e02a…` |
| `i-fa-h6` | FaHeading6 | `images/icons/fa_h6.svg` | `9895825e957e8d19…` |
| `i-fa-heading` | FaHeading | `images/icons/fa_heading.svg` | `e6267b2415251c53…` |
| `i-fa-highlighter` | FaHighlighter | `images/icons/fa_highlighter.svg` | `72803253d03ca796…` |
| `i-fa-italic` | FaItalic | `images/icons/fa_italic.svg` | `0cdc36fdcedead43…` |
| `i-fa-link` | FaLink | `images/icons/fa_link.svg` | `251db02d8df47424…` |
| `i-fa-list-check` | FaListCheck | `images/icons/fa_list-check.svg` | `5458eae97afeea54…` |
| `i-fa-list-ol` | FaListOl | `images/icons/fa_list-ol.svg` | `f5a9b94c6deff472…` |
| `i-fa-list-ul` | FaListUl | `images/icons/fa_list-ul.svg` | `6828c3e8667836f5…` |
| `i-fa-strikethrough` | FaStrikethrough | `images/icons/fa_strikethrough.svg` | `06efdda10193edbf…` |
| `i-fa-subscript` | FaSubscript | `images/icons/fa_subscript.svg` | `cfad1c6f1915e180…` |
| `i-fa-superscript` | FaSuperscript | `images/icons/fa_superscript.svg` | `b37a64ef30ca863d…` |
| `i-fa-table` | FaTable | `images/icons/fa_table.svg` | `d61158d1bfae0288…` |
| `i-fa-underline` | FaUnderline | `images/icons/fa_underline.svg` | `8b546d77026607b1…` |
| `i-file-archive` | FileArchive | `images/icons/file_archive.svg` | `96de2a20f97e23a6…` |
| `i-file-executable` | FileExecutable | `images/icons/file_executable.svg` | `b1e36ea24752d657…` |
| `i-file-image` | FileImage | `images/icons/file_image.svg` | `0d427733c2d153a5…` |
| `i-file-pdf` | FilePdf | `images/icons/file_pdf.svg` | `4c5a7da87b63c74e…` |
| `i-file-text` | FileText | `images/icons/file_text.svg` | `531179c88753b796…` |
| `i-file-video` | FileVideo | `images/icons/file_video.svg` | `4637a535200bff33…` |
| `i-folder` | Folder | `images/icons/folder.svg` | `73c9d3232aae0e6e…` |
| `i-folder-add` | FolderAdd | `images/icons/folder_add.svg` | `59f4417f1026f72e…` |
| `i-folder-up` | FolderUp | `images/icons/folder_up.svg` | `bc208a31c007b4e8…` |
| `i-generic-file-attachment` | GenericFileAttachment | `images/icons/generic_file_attachment.svg` | `259e5b4e4d5bd9a2…` |
| `i-globe` | Globe | `images/icons/globe.svg` | `cd3ba6451e404325…` |
| `i-group-100` | server built-in group icon; `GetIcon` maps ids 1–999 to `group_<id>.svg` @2407426 | `images/icons/group_100.svg` | `1218b6852fe6c58e…` |
| `i-group-200` | server built-in group icon; `GetIcon` maps ids 1–999 to `group_<id>.svg` @2407426 | `images/icons/group_200.svg` | `959a58918fa66b26…` |
| `i-group-300` | server built-in group icon; `GetIcon` maps ids 1–999 to `group_<id>.svg` @2407426 | `images/icons/group_300.svg` | `a0d817ea944c0a5b…` |
| `i-group-500` | server built-in group icon; `GetIcon` maps ids 1–999 to `group_<id>.svg` @2407426 | `images/icons/group_500.svg` | `d8fc5f716a283bc6…` |
| `i-group-600` | server built-in group icon; `GetIcon` maps ids 1–999 to `group_<id>.svg` @2407426 | `images/icons/group_600.svg` | `dbb80d6687c16946…` |
| `i-groups` | Groups | `images/icons/groups.svg` | `1b69dd2d6b1dfbc5…` |
| `i-hidden` | Hidden | `images/icons/hidden.svg` | `96703f0789262f12…` |
| `i-info` | Info | `images/icons/info.svg` | `3f88c77dedf677b4…` |
| `i-input-muted-local` | InputMutedLocal | `images/icons/audio_input_muted_local.svg` | `389f1609902d564a…` |
| `i-item-close` | ItemClose | `images/icons/item_close.svg` | `72a1bc4ddac9a649…` |
| `i-item-collapse` | ItemCollapse | `images/icons/item_collapse.svg` | `7849a8feb879ceca…` |
| `i-item-copy` | ItemCopy | `images/icons/item_copy.svg` | `0aa0c0042d60ae9f…` |
| `i-item-expand` | ItemExpand | `images/icons/item_expand.svg` | `7a5b4228c34d4fca…` |
| `i-item-indent` | ItemIndent | `images/icons/item_indent.svg` | `3d54802e47ab6fd2…` |
| `i-item-leave` | ItemLeave | `images/icons/item_leave.svg` | `834b1096de82e6bd…` |
| `i-item-menu` | ItemMenu | `images/icons/item_menu.svg` | `b5b54c17b6cb8d00…` |
| `i-item-pin` | ItemPin | `images/icons/item_pin.svg` | `3d883f74a24916db…` |
| `i-item-settings` | ItemSettings | `images/icons/item_settings.svg` | `2c4027ab4f8c491f…` |
| `i-loading` | Loading | `images/icons/loading.svg` | `93f459dfb6937c5a…` |
| `i-lock` | Lock | `images/icons/lock.svg` | `940e806a10882ddf…` |
| `i-lock-opened` | LockOpened | `images/icons/lock_opened.svg` | `5fbac2e7a0b77d43…` |
| `i-microphone` | Input | `images/icons/audio_input.svg` | `c4a4bed2f5aa65fc…` |
| `i-microphone-slash` | InputMuted | `images/icons/audio_input_muted.svg` | `2f6a53252ec823f3…` |
| `i-microphone-slash-small` | InputMutedSmall | `images/icons/audio_input_muted_small.svg` | `87db7bab2852a36b…` |
| `i-microphone-small` | InputSmall | `images/icons/audio_input_small.svg` | `c6a3879869d73ef8…` |
| `i-mode-chat` | ModeChat | `images/icons/mode_chat.svg` | `61e4a63cf96bddc9…` |
| `i-mode-events` | ModeEvents | `images/icons/mode_events.svg` | `221a75257af47493…` |
| `i-mode-files` | ModeFiles | `images/icons/mode_files.svg` | `8b45d0235e5f304d…` |
| `i-mode-info` | ModeInfo | `images/icons/mode_info.svg` | `0f1441469a6afbf2…` |
| `i-mode-recording` | ModeRecording | `images/icons/mode_recording.svg` | `9942158cd6cba65d…` |
| `i-mode-server-bans` | ModeServerBans | `images/icons/mode_server_bans.svg` | `3864ce4c547d6943…` |
| `i-mode-server-compact` | ModeServerCompact | `images/icons/mode_server_compact.svg` | `ee8a00e62099cee4…` |
| `i-mode-server-detailed` | ModeServerDetailed | `images/icons/mode_server_detailed.svg` | `d2095ab12d5320a6…` |
| `i-mode-server-permissions` | ModeServerPermissions | `images/icons/mode_server_permissions.svg` | `9a42f928cb3c497f…` |
| `i-mode-stats` | ModeStats | `images/icons/mode_stats.svg` | `da6337edd873471d…` |
| `i-mode-streaming` | ModeStreaming | `images/icons/mode_streaming.svg` | `9266f6d1903d7c95…` |
| `i-navigation-back` | NavigationBack | `images/icons/navigation_back.svg` | `0840b7ff6c8238af…` |
| `i-navigation-forward` | NavigationForward | `images/icons/navigation_forward.svg` | `4c043e9c0751ab2b…` |
| `i-notifications` | Notifications | `images/icons/notifications.svg` | `8329f49d50a1bb65…` |
| `i-open-file` | OpenFile | `images/icons/open.svg` | `27b6c5a632b76ce8…` |
| `i-pause` | Pause | `images/icons/pause.svg` | `0ae327e335ecea24…` |
| `i-phonetic-available` | PhoneticAvailable | `images/icons/phonetic_available.svg` | `07a2790929d8bc50…` |
| `i-phonetic-unavailable` | PhoneticUnavailable | `images/icons/phonetic_unavailable.svg` | `76ab4d5bb87ed399…` |
| `i-play` | Play | `images/icons/play.svg` | `a156bbc7b646ac11…` |
| `i-privilege-key` | PrivilegeKey | `images/icons/privilege_key.svg` | `b1b241c52d781873…` |
| `i-refresh` | Refresh | `images/icons/refresh.svg` | `be320bc183d48268…` |
| `i-remove` | Remove | `images/icons/remove.svg` | `69bf994d573aefa4…` |
| `i-reply` | Reply | `images/icons/reply.svg` | `db14a05b7e0a01d0…` |
| `i-reset` | Reset | `images/icons/reset.svg` | `bcda4c52cc87f4cd…` |
| `i-search` | Search | `images/icons/search.svg` | `82e53700c60e5295…` |
| `i-server` | ServerGreen | `images/icons/server.svg` | `e154bfdff4b29dc6…` |
| `i-server-connect` | ServerConnect | `images/icons/server_connect.svg` | `cd01cc4a5a954b65…` |
| `i-server-info-users` | ServerInfoUsers | `images/icons/server_info_users.svg` | `831f971da2a118d0…` |
| `i-server-mask` | ServerMask | `images/icons/server_mask.svg` | `61dcf36ea4c6fa57…` |
| `i-settings` | Settings | `images/icons/settings.svg` | `6b3e4baed758cabb…` |
| `i-settings-addons` | SettingsAddons | `images/icons/settings_addons.svg` | `4f7eeea20e1a9793…` |
| `i-settings-appearances` | SettingsAppearances | `images/icons/settings_appearances.svg` | `217094ddb593bb5a…` |
| `i-settings-audio` | SettingsAudio | `images/icons/settings_audio.svg` | `1bc3fe384e4fcda6…` |
| `i-settings-behavior` | SettingsBehavior | `images/icons/settings_behavior.svg` | `743dc5de305ee52f…` |
| `i-settings-chat` | SettingsChat | `images/icons/settings_chat.svg` | `ba267177ededa7de…` |
| `i-settings-identities` | SettingsIdentities | `images/icons/settings_identities.svg` | `58ec6ac93a54d0fc…` |
| `i-settings-keybindings` | SettingsKeybindings | `images/icons/settings_keybindings.svg` | `d12aaf38122645c3…` |
| `i-settings-notifications` | SettingsNotifications | `images/icons/settings_notifications.svg` | `71671c67ca04aec4…` |
| `i-settings-privacy` | SettingsPrivacy | `images/icons/settings_privacy.svg` | `2786b5525bdfb5c7…` |
| `i-settings-whispers` | SettingsWhispers | `images/icons/settings_whispers.svg` | `abad49ce11dd6d10…` |
| `i-share` | Share | `images/icons/share.svg` | `fa64b0aea74ddc36…` |
| `i-slider-knob` | SliderKnob | `images/icons/slider_knob.svg` | `78d89c9dfa3ddbef…` |
| `i-speaker` | Output | `images/icons/audio_output.svg` | `131b918c2f78ca28…` |
| `i-speaker-slash` | OutputMuted | `images/icons/audio_output_muted.svg` | `859adad3f67a4109…` |
| `i-speaker-slash-small` | OutputMutedSmall | `images/icons/audio_output_muted_small.svg` | `bf534b06195aa96b…` |
| `i-speaker-small` | OutputSmall | `images/icons/audio_output_small.svg` | `c9100861f5fe9128…` |
| `i-status-recording` | StatusRecording | `images/icons/status_recording.svg` | `224f1f36ceb8edee…` |
| `i-stream-join` | StreamJoin | `images/icons/stream_join.svg` | `8bdbfa61c6ba5ed9…` |
| `i-stream-leave` | StreamLeave | `images/icons/stream_leave.svg` | `4945f241d5580522…` |
| `i-stream-maximize` | StreamMaximize | `images/icons/stream_maximize.svg` | `1e273e2190c591b8…` |
| `i-stream-minimize` | StreamMinimize | `images/icons/stream_minimize.svg` | `15ab09e5bb0a3496…` |
| `i-stream-playing` | StreamPlaying | `images/icons/stream_playing.svg` | `29017299d75b2a4b…` |
| `i-stream-settings` | StreamSettings | `images/icons/stream_settings.svg` | `7254dfc213ffcf41…` |
| `i-stream-shutdown` | StreamShutdown | `images/icons/stream_shutdown.svg` | `cf65796b2e5f0cf4…` |
| `i-transfer` | Transfer | `images/icons/transfer.svg` | `a7a1bd86f367978e…` |
| `i-upload` | Upload | `images/icons/upload.svg` | `318339a5c1476712…` |
| `i-upload-flat` | UploadFlat | `images/icons/upload_flat.svg` | `f78dee30d9d7ebab…` |
| `i-video-screen` | VideoScreen | `images/icons/video_screen.svg` | `fc504c589e8c3597…` |
| `i-viewer-small` | ViewerSmall | `images/icons/viewer_small.svg` | `6b70ae8be28dd5ba…` |
| `i-visible` | Visible | `images/icons/visible.svg` | `89150f6fc862ee7d…` |
| `i-waiting` | Waiting | `images/icons/waiting.svg` | `77659891ca6a57b5…` |
| `i-whisper` | Whisper | `images/icons/whisper.svg` | `83bcba03cb41abd2…` |
## Composite
`i-avatar` (viewBox 0 0 51 33) is the official default client avatar stack, composed only of official symbols: `i-client-detailed`
(ClientDetailed portrait) under `i-client-detailed-placeholder` placed at x=9 (the centred 33×33 `tsv-avatar` layer) and clipped by
`i-client-detailed-mask` as an alpha mask, matching `clientDetailedIcons`/`avatarImage` (@10693354) rendered by `ts-icon-stack`
(@3162500, `-webkit-mask: url(client_detailed_mask.svg)`). The talking ring is the separate `i-client-detailed-talking` layer.
## Mask assets
| File | sha256 |
|---|---|
| `app/renderer/assets/icons/channel_mask.svg` | `69e1d3e053e77256c83c539796ac01a3ddc4dc9b55e1d1ff6441ba19c5c4cc16` |
| `app/renderer/assets/icons/client_detailed_mask.svg` | `006e04703e627c8d2da6eb619647fcdf46cc466882c9fb3b05b45fa9a0a2e888` |
| `app/renderer/assets/icons/contact_mask.svg` | `176d68bc8c65caf6092ac615eaf3229e7b0c5612cde1ddc4706b0f75de72b0b2` |
| `app/renderer/assets/icons/server_mask.svg` | `61dcf36ea4c6fa5790b8dc513b2bebfe0d91b3879601eb2fedc0af5551eebb93` |
## Aliases
An alias symbol contains only `<use href="#i-<target>">`, so it renders the official target unchanged. Surface evidence is the
official usage that matches the TeamsPeach surface; entries marked UNAVAILABLE have no exact official counterpart and name the
nearest official glyph instead.
| Alias | Target | Evidence |
|---|---|---|
| `i-attachment` | `i-chat-image` | composer file picker ts-chat-image-button ChatImage (paperclip) @3571934 |
| `i-back` | `i-navigation-back` | menu Back NavigationBack @1615889 |
| `i-bell` | `i-notifications` | settings Notifications category; poke uses i-poke |
| `i-bold` | `i-fa-bold` | composer toolbar FaBold (markdown table @3507384 ff.) |
| `i-channel-green` | `i-channel` | official kebab channel-green maps to same file channel.svg (settings.json) |
| `i-channel-locked` | `i-channel-yellow` | official kebab channel-locked maps to same file channel_locked.svg (settings.json) |
| `i-check` | `i-checkbox-tick` | menu current-choice accessory CheckboxTick @1642454, @1738614 |
| `i-chevron-down` | `i-item-expand` | expander chevron ItemExpand @2864925, sections collapse @2854917 |
| `i-chevron-right` | `i-navigation-forward` | menu submenu accessory NavigationForward @1620314, @1627400 |
| `i-code` | `i-fa-code` | composer codeblock FaCode @3513668 |
| `i-commander` | `i-channel-commander` | tree commander ChannelCommander @4127418 |
| `i-copy` | `i-item-copy` | ItemCopy copy actions (28 uses), files @3834346 |
| `i-file` | `i-file-text` | UNAVAILABLE exact row source: official browser row icon not located; generic document FileText |
| `i-file-transfer` | `i-mode-files` | official kebab file-transfer maps to same file mode_files.svg (settings.json) |
| `i-fullscreen` | `i-stream-maximize` | stream enlargeImage (not fullscreen) @4061371 |
| `i-fullscreen-exit` | `i-stream-minimize` | stream enlargeImage (fullscreen) @4061351 |
| `i-gear` | `i-settings` | settings button Settings @2840824, settings title |
| `i-heading` | `i-fa-heading` | composer heading group FaHeading @3518397 |
| `i-headphones` | `i-speaker` | playback toggle Output @3992939 |
| `i-headphones-off` | `i-speaker-slash` | tree mutedIcon OutputMuted @2891233 |
| `i-image` | `i-chat-image` | composer file picker ChatImage (paperclip) @3571934 |
| `i-input` | `i-microphone` | enum key alias Input |
| `i-italic` | `i-fa-italic` | composer toolbar FaItalic |
| `i-keyboard` | `i-settings-keybindings` | settings category SettingsKeybindings |
| `i-link` | `i-fa-link` | composer toolbar FaLink @3510645 |
| `i-list` | `i-fa-list-ul` | composer lists group FaListUl @3518496 |
| `i-logout` | `i-item-leave` | kick channel/server/ban ItemLeave @1624216; NOTE official Disconnect uses ItemClose @1757045 |
| `i-message` | `i-mode-chat` | content mode Chat ModeChat @1343509 |
| `i-mic` | `i-microphone` | toolbar/call-bar capture toggle Input @3992501 |
| `i-mic-off` | `i-microphone-slash` | capture toggle InputMuted @3992484; tree mutedIcon @2891329 |
| `i-monitor` | `i-video-screen` | start stream / screen source VideoScreen @1896420, app-audio list @3720680 |
| `i-moon` | `i-away` | tree/presence state Away @2891233, @1745074 |
| `i-more` | `i-dots` | stream view settings Dots @4051881 |
| `i-output` | `i-speaker` | enum key alias Output |
| `i-palette` | `i-settings-appearances` | settings category SettingsAppearances |
| `i-permissions` | `i-mode-server-permissions` | client/channel permissions ModeServerPermissions @1630053 |
| `i-pip` | `i-expand` | UNAVAILABLE: official toolbar has no PiP glyph; nearest official = video.action.popout Expand @4064201 |
| `i-pip-exit` | `i-expand` | UNAVAILABLE: no official PiP-exit glyph; same Expand fallback, pressed state via --tsv-icon-base tint |
| `i-plus` | `i-add` | Add (26 uses) |
| `i-poke` | `i-chat-poke-solid` | client menu poke ChatPokeSolid @1627400 |
| `i-popout` | `i-expand` | video.action.popout Expand @4064201 |
| `i-priority-speaker` | `i-microphone` | official kebab priority-speaker maps to same file audio_input.svg (settings.json) |
| `i-quote` | `i-fa-block-quote` | composer toolbar FaBlockquote @3512197 |
| `i-record` | `i-status-recording` | recording status StatusRecording @1759184 |
| `i-self-avatar` | `i-contact-placeholder` | sidebar presence slot default avatar ts-presence avatarImage = ContactPlaceholder @2881456 (no account avatar) |
| `i-send` | `i-chat-send` | chat send button ChatSend @3572254 |
| `i-shield` | `i-mode-server-permissions` | legacy group-icon fallback; official permissions ModeServerPermissions @1614689 (official has no group fallback: icon 0 = none @2407426) |
| `i-sliders` | `i-item-settings` | no 1:1 official surface (legacy generic glyph); ItemSettings = settings resource @2954502. Use i-settings-behavior (OS settings), i-connection-status (connection info @4398096) |
| `i-speaker-off` | `i-speaker-slash` | playback toggle OutputMuted @3992939; stream hero mute @4075195 |
| `i-stats` | `i-mode-stats` | ModeStats content mode |
| `i-stream` | `i-mode-streaming` | screenshare toolbar ModeStreaming @2818131 |
| `i-strike` | `i-fa-strikethrough` | composer toolbar FaStrikethrough |
| `i-underline` | `i-fa-underline` | composer toolbar FaUnderline |
| `i-user` | `i-settings-identities` | identity surfaces SettingsIdentities @1914926, settings category @1376540 |
| `i-warning` | `i-exclamation-triangle` | enum key alias Warning |
| `i-x` | `i-item-close` | close/cancel ItemClose @1547254, @1607017 |
## Legacy ids that are official ids
`i-away`, `i-bookmark`, `i-channel`, `i-download`, `i-edit`, `i-emoji`, `i-folder`, `i-folder-add`, `i-folder-up`, `i-hidden`, `i-info`,
`i-lock`, `i-play`, `i-refresh`, `i-search`, `i-server`, `i-speaker` and `i-upload` now render the official icon of the same id.
`i-emoji` is `emoji.svg` (the composer button is `i-chat-emoji`, @3571700) and `i-info` is `info.svg` (the detail-pane Information
mode is `i-mode-info`, @1343385).
## Additional footer import
`i-connection-events` uses the installed `images/icons/connection_events.svg`, SHA-256
`1736f417cdf38002f3478e0a7e03809764738b657322a5b9d211f20c8d53257b`.
The conversion preserves geometry, changes inline styles to presentation attributes, prefixes IDs,
and omits XML/doctype declarations, as for the other sprite imports. No redistribution licence is implied.
## Country and language flags
The 258 SVG files in `app/renderer/assets/countries/` are byte-identical to the same-named files
under the installed client's `images/countries/`; all 258 were compared on 2026-11-01, with no mismatches.
They supply the optional server-tree country markers and the US/RU language-selection artwork.
`country-flags.js` accepts only its explicit local country-code allowlist, never arbitrary resource URLs.
Aggregate SHA-256: `eebd6910a9077dacaf199ff25fbdc12cf3d50ea35a0b27123e556ca8856cba0c`.
Input: filename-sorted records `filename + NUL + lowercase_file_sha256 + LF`, UTF-8 encoded.
The provenance and redistribution caveats above apply; these copies receive no new licence grant.
## Expanded bookmark and whisper controls
Additional symbols use the same transformations and redistribution caveats above. Source files are
under the installed client's `images/icons/`; hashes were read on 2026-11-01.
| Product symbol | Source file | SHA-256 |
|---|---|---|
| `i-folder-action` | `folder_action.svg` | `59df74a51ea024d214611b25568dfa53420f706b886ebdf9302e8c0011979d94` |
| `i-connection-whispers` | `connection_whispers.svg` | `50de820d13d6a4f08966448d81b94d59188a2f15fe9de9d730e43e83b34e65ad` |
| `i-chat-contact` | `chat_contact.svg` | `d11e41302a634d8e4f48a38ee8443e095c4c09b8d1fb87d4a4b95190c8d370a3` |
| `i-channel-select-default` | `channel_select_default.svg` | `690ebc95dff843e6257743c91fa752868bafdce63e788c47364fa80303b918a9` |
`i-chat-contact` represents a locally received whisper participant, not an account service.
## Analytics mode artwork
The owner-approved original Privacy composition uses two source symbols to describe unavailable
diagnostics modes, not to enable telemetry. The same redistribution restrictions above apply.
| Product symbol | Source file | SHA-256 |
|---|---|---|
| `i-analytics-limited` | `analytics_limited.svg` | `0d7af0589dd5dc76610ef324228ad07a364e8e5c6cd66dc9d52939f10119fe49` |
| `i-analytics-enhanced` | `analytics_enhanced.svg` | `18a012f09aaefd230c65286e594d0fcf09115473497da07421a692ea86bf1535` |
## Not included
TeamSpeak logo/label/mono marks, `ts_logo_qr.png`, `brands-*`, room presets and banners, content backgrounds, hex decorations,
contact-status, chat-room, homebase, two-factor and phone-call (myTeamSpeak account) artwork, and the other unused `*_old` files.
@@ -0,0 +1,97 @@
# Official TeamSpeak 6 client notification sounds in TeamsPeach — provenance
The 54 files in `native/resources/sounds/` (formerly `app/renderer/assets/sounds/`) are notification sounds of the official TeamSpeak 6 client
(TeamSpeak Systems GmbH), copied byte for byte from the client installed on the owner's workstation at the owner's
direction (2026-11-01 brief: the installed client's features and panels, value for value).
**Licence status.** No licence grant for redistributing these sounds has been identified. The installed client is
governed by its own licence agreement (`licenses/en/la_desktop.html` in the client installation). TeamsPeach does not
relicense these sounds and does not claim the right to publish them; they are not covered by TeamsPeach's own terms or
by any open-source licence in this folder.
## Source
- Installation: `%LOCALAPPDATA%/Programs/TeamSpeak/html/client_ui/sound/default/` (the only sound pack the client
ships; 61 files). `main.js` sha256 `9d6bea2ee5333086555c36584621c1b3462a83042ce746d3229d6766a9b82c39`.
- Event → file table: `NotificationSoundManager.soundFiles`, `main.js` webpack module 82164 (first file name at
character offset ≈2267292). Event types and sub types: module 69818 enums `J1` (event type), `l2`, `nA`, `x8`, `rJ`,
`eM`, `T9`, `rt`, `nZ`, `jk`, `KY`, `yc`, `ih` and `r.I3d` (stream). Playback: `playSoundForDefaultEvent` passes the
file name to native `tsclient_internal.playWaveFile(0, name)` (`main.js` ≈2120604). That the native side resolves
the name to `html/client_ui/sound/default/<name>.wav` is inferred from the adjacent `sound`, `client_ui`, `html` and
`.wav` strings in `TeamSpeak.dll` and from `default` being the only installed pack; the native code was not traced.
- Settings rows: coalesced setting table module 69818 `rg`; the row's Listen button (`playPreview`, module 186,
`main.js` ≈4964155) plays the first sub type of the row, an advanced row plays its own sub type, both ignoring the
throttle.
## Transformations
None. Each file is an unchanged copy (RIFF/WAVE PCM, including its original `LIST`/`CDif`/`cue `/`bext` chunks).
The native worker decodes PCM with `hound`, then resamples/mixes through the native notification output path;
it does not use Chromium's decoder. The former renderer resource paths were relocated without changing file bytes.
## Files
`time` is the official repeat throttle; a repeat within it is skipped.
| File | Official event sub types (`EventType.SubType`) | Format | Bytes | sha256 |
|---|---|---|---|---|
| `away_activated.wav` | ClientUpdate.YouAway (100 ms) | 1×16-bit 44100 Hz, 0.759 s | 67190 | `170fdd2f8fd07ce0b7077a45e9df6cdac8ddf9a8cdaf2e6bc5828944564d5acf` |
| `away_deactivated.wav` | ClientUpdate.YouPresent (100 ms) | 1×16-bit 44100 Hz, 0.758 s | 67034 | `6c00635fad802ebe62543e85fd402f8fcb5957b8d68c4e80a74d721fcab6306f` |
| `channel_created.wav` | ChannelEvent.YouCreated | 1×16-bit 44100 Hz, 1.065 s | 94194 | `9354320217fb8600c9b88a9ec34b19e1f5e242a13570d94ad0ec5811850f7ae2` |
| `channel_deleted.wav` | ChannelEvent.YouDeleted | 1×16-bit 44100 Hz, 1.028 s | 90882 | `25d80e7f1274caa9322bf5f1cd1846e5f4a2be1e978b5edbaf81693ccaf4c5dc` |
| `channel_edited.wav` | ChannelEvent.YouEdited | 1×16-bit 44100 Hz, 1.005 s | 88898 | `33605c5a802efa895ee043bbcc7cd43081c264a9602589355ced95a321c6c562` |
| `channel_moved.wav` | ChannelEvent.YouMoved | 1×16-bit 44100 Hz, 0.918 s | 81144 | `144bfc4a22c578872a998d518833c7b0cc1d60be0d81319506da5d84e3278ffd` |
| `channel_switched.wav` | ClientMove.YouSwitchedChannel | 1×16-bit 44100 Hz, 0.995 s | 87998 | `f38c9e67bbd861319d4eef15454893419285ba6dcdd05566dcb3b2042899f468` |
| `channelgroup_changed.wav` | ClientUpdate.YouChannelGroupChanged (1000 ms) | 1×16-bit 44100 Hz, 1.298 s | 114698 | `4ac60b4c0b4bb7a5784d6ae55412fdc198d89ac8a52c7cf3116cf6620f2a024e` |
| `chat_message_inbound.wav` | TextMessage.FromAnotherClient, TextMessage.FromChannel, TextMessage.FromServer | 1×16-bit 44100 Hz, 1.000 s | 88244 | `51e29bb0284b1c62447a720684dd9628034d0bd5b0c1fab2b1dde5986f457a3c` |
| `chat_message_outbound.wav` | TextMessage.ToAnotherClient | 1×16-bit 44100 Hz, 0.047 s | 4148 | `7fc8296f113485aa7d66b3f1e1e04ea3c7470d9efb238fb692a9504cf8c33ce2` |
| `connected.wav` | ConnectStatus.Connected | 1×16-bit 44100 Hz, 0.624 s | 55262 | `e9bc4136b91bc7d36dc9a561b2b8d4436244f42af65c1d01540f0b8a958c5a10` |
| `connection_lost.wav` | ConnectStatus.ConnectionLost | 1×16-bit 44100 Hz, 0.988 s | 87394 | `5566aa08c4e0f126a586ff50ed41ccbad3c5f942e75c9f924ad6578e8ccf6d45` |
| `disconnected.wav` | ConnectStatus.Disconnected | 1×16-bit 44100 Hz, 0.950 s | 84018 | `58ad23d848d07c37e0b521dadeecedbc268beaad657d4e12d03daf7b9ab16e53` |
| `error.wav` | ConnectStatus.FailedToConnect (1000 ms), LogEvent.LogError (1000 ms) | 1×16-bit 44100 Hz, 0.472 s | 41870 | `3b0589a6349d96198f496861b2be12c825a922b1b59b56d202195208014035e0` |
| `insufficient_permissions.wav` | ServerPermissionErrorEvent.Error (2000 ms) | 1×16-bit 44100 Hz, 1.370 s | 121066 | `4284bf1e85c53cb450b7ae9d488df417a372e0c23ad91bf24fcd2992b28cec1c` |
| `mic_activated.wav` | ClientUpdate.YouCaptureUnmuted (100 ms) | 1×16-bit 44100 Hz, 1.210 s | 106982 | `c44490c0f9ce270d0ee90c5f5fc4004ea39ebbdc8b6ebc5dab75cf175f9f6f83` |
| `mic_muted.wav` | ClientUpdate.YouCaptureMuted (100 ms) | 1×16-bit 44100 Hz, 1.017 s | 89936 | `528ea98a11951d8fa96a5396c12c9e3bceabf0a895e084826f3b1cfca0d4ed8e` |
| `neutral_banned_server_currentchannel.wav` | ClientMove.SomeoneInYourChannelWasBanned | 1×16-bit 44100 Hz, 2.478 s | 218768 | `599e671f50842cee1603a56f7e211686b985abd92a977b5f3c5532393213b67c` |
| `neutral_connection_connected_currentchannel.wav` | ClientMove.SomeoneInYourChannelConnected | 1×16-bit 44100 Hz, 1.446 s | 127760 | `6a4ad2636c93e88cd6247a3105a65d88af8ca3fff05f9debb09726df6074b9e0` |
| `neutral_connection_connectionlost_currentchannel.wav` | ClientMove.SomeoneInYourChannelConnectionLost | 1×16-bit 44100 Hz, 1.829 s | 161498 | `7c39ad53fd3d041fa711c97e6559c5af3ebf7b3b3285f9ae0edb4a42a92a5568` |
| `neutral_connection_disconnected_currentchannel.wav` | ClientMove.SomeoneInYourChannelDisconnected | 1×16-bit 44100 Hz, 1.900 s | 167834 | `cdbb181918c33842ae3572ad3752aabff8b47559e881862fe64ee6e40bddd6f8` |
| `neutral_kicked_channel_awayfromcurrentchannel.wav` | ClientMove.SomeoneInYourChannelWasKickedChannel | 1×16-bit 44100 Hz, 2.020 s | 178416 | `eafadd9b5f7cef69c106803bb0bac94d39880158330a3820995c4a1a897538e4` |
| `neutral_kicked_channel_tocurrentchannel.wav` | ClientMove.SomeoneWasKickedToYourChannel | 1×16-bit 44100 Hz, 1.856 s | 163914 | `29e2bf7ceaadb1d124a9f0ac8c4e1fe8c26697e3072f3d0b8936c4766416ff25` |
| `neutral_kicked_server_currentchannel.wav` | ClientMove.SomeoneInYourChannelWasKickedFromServer | 1×16-bit 44100 Hz, 2.534 s | 223686 | `2d53d3c8a338418e23c8803a8abb8b73349df5befc0af0096ae7a3bb0a376872` |
| `neutral_moved_awayfromcurrentchannel.wav` | ClientMove.SomeoneWasMovedAwayFromYourChannel (100 ms) | 1×16-bit 44100 Hz, 1.764 s | 155802 | `e2b1e2a4336a8af7e8cfcdd239f26138c3a11b045cd952d81aaa671ebd6c6c85` |
| `neutral_moved_tocurrentchannel.wav` | ClientMove.SomeoneWasMovedToYourChannel (100 ms) | 1×16-bit 44100 Hz, 1.741 s | 153818 | `569fd8904a2d6a70529ea36466cc590179ec7c4e40b6b5d40f2643fb0a25ed68` |
| `neutral_recording_active_currentchannel.wav` | ClientMove.YouSwitchedChannelRecording | 1×16-bit 44100 Hz, 1.815 s | 160290 | `7448f91c3ecd901500a954a42276a3459bbc93daa66e1080b3aead80f24cf92d` |
| `neutral_recording_started_currentchannel.wav` | ClientUpdate.SomeoneInYourChannelRecordingStarted | 1×16-bit 44100 Hz, 2.106 s | 185978 | `af5a29f7974591b010044d6a212f4238c4446f66ab27b2429e08b1c07c6a8670` |
| `neutral_recording_stopped_currentchannel.wav` | ClientUpdate.SomeoneInYourChannelRecordingStopped | 1×16-bit 44100 Hz, 2.096 s | 185126 | `3f0ab4f666518055fc05d8b5102bdddcde7b042aee6cd2527529b0753edf4557` |
| `neutral_switched_awayfromcurrentchannel.wav` | ClientMove.SomeoneLeftYourChannel (1000 ms) | 1×16-bit 44100 Hz, 1.326 s | 117182 | `d0c0fb1153a6b28f038c83ccc91bfecb218a0202171f3b2d14266fd290c5d622` |
| `neutral_switched_tocurrentchannel.wav` | ClientMove.SomeoneJoinedYourChannel (1000 ms) | 1×16-bit 44100 Hz, 1.343 s | 118682 | `d334e0e463472dfe389b1bfb2e24d254f99e00744d4f634c6eac76c0bcd6a19b` |
| `no_whisper_target_found.wav` | WhisperErrorEvent.NoSelection | 1×16-bit 44100 Hz, 1.514 s | 133786 | `6c6d1054a9b218f2ae1600c1567eeff9052802254ed1ed888c17a73a7095e5e0` |
| `recording_paused.wav` | LocalRecordingEvent.RecordingPaused (300 ms) | 2×16-bit 48000 Hz, 1.155 s | 221728 | `fee07ad4647998381f1c176c19c51ff88bff9be76c9bb999384cadec181d55ca` |
| `recording_resumed.wav` | LocalRecordingEvent.RecordingResumed (300 ms) | 2×16-bit 48000 Hz, 1.152 s | 221280 | `bbecb5fb7a9f1cf3f60cdb0ab690f8043dcf3fa7fbae69d8b4b93ebc99939d64` |
| `recording_started.wav` | LocalRecordingEvent.RecordingStarted (500 ms) | 2×16-bit 48000 Hz, 1.230 s | 236272 | `1fd58b214c851cd88b53fd61a38d71bc98d8cd407bb4270951360d4dc4e89b23` |
| `recording_stopped.wav` | LocalRecordingEvent.RecordingStopped (500 ms) | 2×16-bit 48000 Hz, 1.263 s | 242484 | `b9261ceccf4828680256b7edfbdd131781d815c30aef019dc624f4d55219967d` |
| `servergroup_assigned.wav` | ClientUpdate.YouServerGroupAssigned (1000 ms) | 1×16-bit 44100 Hz, 1.327 s | 117248 | `8f278ac08f259131eebc6a78ed700a76e036e627cb8a3ef78036f3f570c4501f` |
| `servergroup_revoked.wav` | ClientUpdate.YouServerGroupRevoked (1000 ms) | 1×16-bit 44100 Hz, 1.476 s | 130438 | `8befbc4a4025ed28de7d397ccb718c59417ea553065c50173693678b0e5d4211` |
| `sound_muted.wav` | ClientUpdate.YouPlaybackMuted (100 ms) | 1×16-bit 44100 Hz, 1.011 s | 89424 | `41cf6d43b7115e7e212f4cc75146291f0d847f079268b385fcd053090cd1e36c` |
| `sound_resumed.wav` | ClientUpdate.YouPlaybackUnmuted (100 ms) | 1×16-bit 44100 Hz, 1.018 s | 89978 | `28b0bfabfe904d54779979e652ae99122d1689aa64820e01a82db7d3c2f67cd8` |
| `stop_talking.wav` | TalkStatusChanged.YouTalkingWhileMuted, WhisperErrorEvent.NoInput (2000 ms) | 1×16-bit 48000 Hz, 0.467 s | 45742 | `c734b077fe252640535b7ba4ca607aadbf0884a8734c68cf17522b7f2f3a64bc` |
| `stream_started.wav` | StreamEvent.StreamStarted (100 ms) | 2×16-bit 48000 Hz, 1.300 s | 249812 | `55b922d7d457e0e9c6e86cbbb4bf7aa5edf310934ec673a39bd2f8e45629bf32` |
| `stream_stopped.wav` | StreamEvent.StreamStopped (100 ms) | 2×16-bit 48000 Hz, 1.233 s | 236924 | `8f8138de2d91ccdb0a2a1af112ea9acff58e845f30e79913697e025bf9b5cdba` |
| `talkpower_granted.wav` | ClientUpdate.YouTalkPowerGranted | 1×16-bit 44100 Hz, 1.267 s | 111962 | `3ef9564294f6673e3dbc945ee8b49bc381e674a31c93ab4c0363fa45b5eeadea` |
| `talkpower_requested.wav` | ClientUpdate.SomeoneRequestsTalkPower | 1×16-bit 44100 Hz, 1.720 s | 151946 | `57c1eac582806288b0e055110d265271bb597fd4556ccba01a59f87dd9ca48fc` |
| `talkpower_revoked.wav` | ClientUpdate.YouTalkPowerRevoked | 1×16-bit 44100 Hz, 1.503 s | 132770 | `02af63898cc739ef439afdc5c54420148d030532129f578c84d5e91ccd9e406f` |
| `whisper_received.wav` | WhisperEvent.WhisperReceived (2000 ms) | 1×16-bit 48000 Hz, 0.173 s | 16648 | `6c8e708f35a7025ed096e2c50677f2a2e677ada99d9c3db2546fe22e51d7d83b` |
| `you_edited_server.wav` | ServerEdited.YouEdited | 1×16-bit 44100 Hz, 1.229 s | 108638 | `1dc49aae0f48fd021e27ee642f345756b5c734512d3683bc15328d0f14188d67` |
| `you_kicked_channel.wav` | ClientMove.YouWereKickedFromChannel | 1×16-bit 44100 Hz, 1.431 s | 126418 | `3bf0594419ce06d87df94c8a8f068b882b3ff0b131b76088dfcc24cbbf370e3d` |
| `you_kicked_server.wav` | ClientMove.YouWereKickedFromServer | 1×16-bit 44100 Hz, 1.458 s | 128804 | `6e80de6a0dfcf2ead8163f8988cc664f8b09f046e1fe0337d8d8b4dd40f0afa7` |
| `you_were_banned.wav` | ClientMove.YouWereBanned | 1×16-bit 44100 Hz, 1.501 s | 132570 | `5e07d8d80230e9f663f0945b79180b363636d7dcc54962b82bf7bb20798ce0f7` |
| `you_were_moved.wav` | ClientMove.YouWereMoved | 1×16-bit 44100 Hz, 0.875 s | 77390 | `009f7b61dd7bfbdd3c6a4c4cda8d3d56af23c378d5e43654b69d421fc1b528e8` |
| `you_were_poked.wav` | TextMessage.PokedFromAnotherClient | 1×16-bit 44100 Hz, 0.936 s | 82766 | `ecb415cf29eccebb9d72ac745f7e5ac919cb0d1bcb62dc9c690fc1c0ed560385` |
| `your_channel_was_edited.wav` | ChannelEvent.YourChannelEdited | 1×16-bit 44100 Hz, 1.380 s | 121976 | `02363f9f2285747b78c271edb15dde0f99dffc0d08f07d0220b166dc940f8583` |
## Not included
`call_incoming.wav`, `call_outgoing.wav` (CallEvent, myTeamSpeak calls), `chat_inbound.wav` (MatrixMessageEvent
IncomingFollowupMessage, myTeamSpeak chat), and `chat_outbound.wav`, `client_joined.wav`, `client_left.wav`,
`incoming_call.wav`, which no official event table references. TeamsPeach has no local source for these events.
+40 -20
View File
@@ -7,17 +7,19 @@ session; items marked *inferred* come from the brief alone).
## Platform
web
native
(An Electron desktop application whose interface is HTML/CSS; target systems: Linux ARM64 on Apple M1 Pro
under Asahi Linux first, plus Linux x86-64 and Windows x86-64.)
(A Rust/Slint application targeting Linux ARM64 on Apple M1 Pro under Asahi Linux first,
plus Linux x86-64 and Windows x86-64. Other desktop/mobile targets are acceptance targets,
not a claim of tested platform support.)
## Stack
Delegated: Electron with plain JavaScript modules and HTML/CSS for the interface; a Rust native core
(ReSpeak tsclientlib) for the TeamSpeak protocol, spoken to over newline-JSON stdio. Chosen because the
screenshare viewer needs a real libwebrtc-compatible WebRTC stack (Chromium's) and the owner had no stack
preference.
Rust workspace: Slint UI in `native/`, ReSpeak tsclientlib protocol library in `core/`,
native DSP in `dsp/`, and source-built libwebrtc with Skia presentation. The application
uses typed in-process services and bounded media channels; the standalone core JSON adapter
remains a diagnostic interface, not the desktop transport. There is no browser or JavaScript
runtime. Cargo `xtask` owns dependency provisioning, builds, packaging and isolated smoke entry points.
## Users
@@ -33,30 +35,46 @@ working voice and can watch a friend's stream.
## Positioning
An independent, account-free TeamSpeak 6 client that interoperates with the official client's voice and P2P
screenshare protocol, built for platforms the official client does not serve.
An independent, account-free TeamSpeak 6 client targeting interoperability with the official client's voice
and P2P screenshare protocol on platforms the official client does not serve. This is a product goal, not
a claim of complete interoperability; the evidence matrix records the demonstrated scope.
## Operating Context
Long voice sessions with the app in the background; push-to-talk or an open microphone; occasional stream
viewing in a channel; the server is the owner's own TS6 server, administered elsewhere (no administration
from this client).
viewing and explicitly started publishing in a channel; target-bound moderation and explicit group/client
permission changes remain required, while the server remains authoritative. Historical implementation
evidence is separated from native acceptance in FEATURE_COMPATIBILITY.md.
## Capabilities and Constraints
- No myTeamSpeak account, registration or global services; identity is a local P-256 key with a public UID.
- Server-provided content (names, chat, descriptions, banners, icons) is untrusted input.
- Screenshare viewing uses the P2P path only; SFU-routed streams are reported as unsupported.
- The renderer may not choose files, paths or commands; native dialogs live in the main process.
- Later goal: broader parity with server features; out of scope: global myTeamSpeak features.
- Undecided: sending one's own screen share; global push-to-talk on Wayland; license of TeamsPeach's code.
- UI intents cannot choose arbitrary host paths or commands; native services own chooser grants and validation.
- Broader local/server parity remains required; global myTeamSpeak services are outside scope.
- Publishing, global shortcuts and platform integration require real native backends and separately scoped evidence.
- Product cutover does not establish full acceptance; no historical browser-client pass becomes a native pass.
## Brand Commitments
Name "TeamsPeach"; restrained peach accent (*inferred* from the name and brief); Russian interface language.
The owner pinned a visual reference for settings (TeamSpeak 6 style: category navigation on the left,
titled card sections on the right, dark blue-gray surfaces); settings follow it.
The owner explicitly asked for a straightforward, familiar chat UI rather than a branding exercise.
Name "TeamsPeach" and its own application icon; English as the default interface language, with Russian
selectable through the shared translation catalog. The owner's latest brief (2026-11-01) requires the
installed official TeamSpeak 6 client's design, not an interpretation: the Liquid Glass world and the
peach accent are retired. Colours, typography (bundled Noto Sans, SIL OFL), spacing, row heights,
the three-slot window (sidebar, server tree, detail pane), menus, settings and chat geometry come from
the installed client's own source values, with extraction offsets in `docs/evidence/official-parity/`.
The TeamSpeak application logo and name are not shipped. Historical non-brand SVG artwork and retained
notification sounds have provenance records in `LICENSES/`; no redistribution licence is claimed.
Removing the old interface does not remove the legal obligations of retained assets.
Account-bound surfaces (notification bell, cloud contacts, myTeamSpeak presence, Setup Chat) remain omitted.
Local UID contacts use connected-server presence only and are not a substitute for cloud synchronization.
Remaining visual and functional deviations are listed in DESIGN.md and FEATURE_COMPATIBILITY.md; visual
parity is never presented as feature parity. Offline identity onboarding and the independent brand marker
are explicit exceptions, not imitations of account functionality. New module controls bind real APIs;
source-token matching is not a substitute for rendered screenshot comparison. No preference, error or
working control is removed for visual reasons. Keyboard focus, reduced motion, reduced transparency
where supported, increased contrast and forced colours remain part of the design contract.
## Evidence on Hand
@@ -73,5 +91,7 @@ benchmarks exist and none may be invented.
## Accessibility & Inclusion
Keyboard-operable controls with visible focus, screen-reader names for icon buttons and tree rows, light and
dark themes following the OS, readable system fonts (*inferred* from the brief).
Keyboard-operable controls with visible focus, screen-reader names for icon buttons and tree rows, light
and dark themes with an optional System mode, and the official interface font bundled locally so text
renders the same on Windows and Asahi Linux. New profiles default to dark; an existing saved theme choice
is preserved.
+390 -78
View File
@@ -1,102 +1,414 @@
# TeamsPeach
Настольный клиент для серверов **TeamSpeak 6** без учётной записи myTeamSpeak: голос, чат, дерево
каналов с группами/иконками/баннерами сервера и **просмотр трансляций экрана TS6**.
Интерфейс — Electron (обычные JS-модули, HTML/CSS), протокол — нативное ядро на Rust
(`core/`, ReSpeak tsclientlib) через приватный stdio (контракт: [`docs/bridge.md`](docs/bridge.md)).
A desktop client for **TeamSpeak 6** servers without a myTeamSpeak account: voice, chat, a channel tree
with server groups, icons and banners, and **TS6 screenshare viewing**.
The interface is native **Rust/Slint**, with Skia presentation and source-built libwebrtc. The Rust
protocol library (`core/`, ReSpeak tsclientlib) runs in process through typed, bounded services.
The standalone core's diagnostic JSON adapter is documented in the [bridge contract](docs/bridge.md).
Подробная карта возможностей и доказательств: [`FEATURE_COMPATIBILITY.md`](FEATURE_COMPATIBILITY.md).
See [`FEATURE_COMPATIBILITY.md`](FEATURE_COMPATIBILITY.md) for feature status and evidence. This is not a
claim of full TeamSpeak 6 parity: official-client voice interoperability and Asahi hardware operation
have not been proven.
## Запуск для разработки (Windows / Linux)
## Development (Windows / Linux)
```
npm ci
cargo build --release --locked --manifest-path core/Cargo.toml # нужен Rust ≥ 1.89, CMake, C-компилятор
npm start
Use the pinned Rust toolchain in `rust-toolchain.toml`, a native C/C++ compiler, CMake, Python 3,
and the target's installed SDK/toolchain. Native dependencies are source-built from the revisions and
provenance gates in `native/native-deps.lock.json`; no browser runtime or JavaScript build tooling is required.
Run from the repository root, selecting the real target triple:
```sh
cargo run -p xtask -- deps --target x86_64-pc-windows-msvc
cargo run -p xtask -- build --target x86_64-pc-windows-msvc
```
Electron ищет ядро в `core/target/release` и `core/target/debug` (берётся более свежий файл).
На Windows cargo установлен rustup'ом без изменения PATH — запускайте `%USERPROFILE%\.cargo\bin\cargo.exe`
или откройте «Developer PowerShell for VS». При нехватке памяти линковки используйте `-j 2`.
Linux targets include `x86_64-unknown-linux-gnu` and `aarch64-unknown-linux-gnu`. Provisioning requires
network access and suitable installed platform tools; `xtask` does not install system SDKs. `--llvm-dir`,
`--skia-source` and `--jobs` select explicitly supplied tools/sources and build parallelism.
The normal build retains the Skia and WebRTC feature set; a reduced-feature build is not a product build.
Outputs use workspace `target/<target-triple>/release` or `CARGO_TARGET_DIR` (relative to the repository root).
Launch `teamspeach.exe` on Windows or `teamspeach` on Linux from that directory.
Отдельный профиль (не трогает основной): `TEAMSPEACH_PROFILE_DIR=<абсолютный путь> npm start`.
Set `TEAMSPEACH_PROFILE_DIR` to an absolute, separate directory before launch to avoid changing the main
profile. First-run native onboarding supports explicit read-only import of a selected historical profile;
it never silently adopts or overwrites it. See **Identity backups and profile migration** below.
## Сборка пакетов
## Packaging
```
npm run dist:win-x64 # NSIS + zip
npm run dist:linux-x64 # AppImage + tar.gz
npm run dist:linux-arm64 # AppImage + tar.gz (ядро aarch64 собирается отдельно)
```sh
cargo run -p xtask -- package --target x86_64-pc-windows-msvc --out dist/native-local
cargo run -p xtask -- verify-package --target x86_64-pc-windows-msvc --out dist/native-local
```
`scripts/dist.mjs` **отказывается** собирать пакет без ядра нужной ОС/архитектуры (проверка
заголовка PE/ELF/Mach-O), кладёт `THIRD_PARTY_NOTICES.md` ядра в `resources/licenses/` и проверяет,
что ядро действительно попало в пакет. Для Asahi (страницы 16 КиБ) есть
`node scripts/elf-pagesize.mjs <файл|папка>` — проверка выравнивания PT_LOAD, glibc и зависимостей.
Packaging consumes a completed native build and installed platform packaging tools. Use a fresh output
directory for a rebuild. Windows uses NSIS and ZIP; Linux uses AppImage and tar.gz. The package includes
native resources, core/WebRTC notices and asset provenance. Actual archive inspection checks architecture,
imports, assets/licenses, native build receipts and the absence of browser/JavaScript runtime payloads.
ARM64 Linux acceptance includes 16 KiB-compatible ELF segments; emulation is not Asahi hardware evidence.
CI: `.gitea/workflows/ci.yml` (Gitea Actions, контейнеры на Linux x64): тесты, сборка ядра,
офлайн-проверка идентичности через stdio, Electron-смоук под Xvfb, кросс-сборка ядра aarch64 с
проверкой 16 КиБ и запуском под `qemu-aarch64` (эмуляция, не железо Apple).
Local packages, unsigned packages and test-harness packages are not publication or installed-update proof.
`xtask package` and `verify-package` are local-only; `publish-release` is a separate explicit command
used by the trusted-tag workflow. No command creates tags or infers signing credentials. Redistribution
rights for retained TeamSpeak artwork/sounds and platform signing/acceptance remain separate requirements.
CI/release configuration is under `.gitea/workflows/`; an unexecuted configuration is not a successful run.
## Использование
### Native CI and releases
1. Первый запуск: один раз ввести никнейм — создаётся криптографическая идентичность (P-256),
публичный UID виден в «Настройки → Идентичность». Никнейм меняется без смены UID.
2. Ввести адрес сервера (и пароль, если нужен) → «Подключиться». Кнопка «Сохранить» добавляет адрес в
сохранённые серверы: они видны слева над деревом (значок закладки в шапке), подключение — в один клик;
если вы уже на другом сервере, кнопка называется «Переключиться» и сначала корректно отключает текущий.
Название, адрес и удаление — в «Настройки → Серверы». Пароли серверов не сохраняются; для всех серверов
используется одна и та же идентичность.
3. Клик по каналу — переход (для каналов с паролем откроется поле ввода).
4. Голос: «Нажми и говори» (по умолчанию F8 или кнопка в шапке) либо «Открытый микрофон»;
кнопки микрофона и звука внизу слева видны серверу.
5. Трансляции: у стримящего участника появится кнопка «Смотреть». Громкость, отключение звука,
полный экран, «Прекратить просмотр» — на панели под видео. В строке статуса — реально
согласованный кодек, разрешение и частота кадров.
The workflows require matching native runners labelled `teamspeach-native-linux-x64` and
`teamspeach-native-linux-arm64`. Provision Rust 1.96.0, Python 3, LLVM/libclang, CMake, Ninja,
Linux audio/window development libraries, Xvfb and D-Bus session tools before enabling them.
Set repository variables `NATIVE_LLVM_HOME`, `NATIVE_LIBCLANG_PATH` and `NATIVE_SKIA_SOURCE_DIR`
to existing tools and a dependency-synchronized Skia checkout containing `bin/gn`. Packaging also
requires linuxdeploy, appimagetool, unsquashfs and archive/LLVM inspection tools. Jobs explicitly run
`xtask deps` to provision pinned WebRTC; they do not install system SDKs on the runner.
## Резервная копия идентичности
```sh
cargo run --locked -p xtask -- check-version
python -B -m unittest discover -s xtask -p test_publish_release.py
cargo run --locked -p xtask -- prepare-release --out artifacts
```
«Настройки → Профиль → Экспортировать…» сохраняет файл в формате TeamSpeak (`.ini`) через системный
диалог. **Файл содержит закрытый ключ** — храните как пароль. Восстановление: «Импортировать…»
(после отключения от сервера; текущая идентичность заменяется только после подтверждения) или
кнопка «Восстановить из резервной копии…» на экране первого запуска. Ядро никогда не создаёт новую
идентичность поверх повреждённой.
Release assembly consumes the downloaded `teamspeach-native-<target-triple>` bundles for both Linux
architectures, including their package, payload-verification and dependency receipts. It validates all
digests and merges the native manifest. Trusted `v*` tags then use `publish-release --out artifacts`
with the workflow's `GITEA_TOKEN`, `GITHUB_REF`, `GITHUB_SERVER_URL` and `GITHUB_REPOSITORY` environment.
Publication creates a new draft, uploads and reads back all assets, checks hashes, then publishes;
it refuses to overwrite an existing release. Manual dispatch builds/verifies without publication.
The Python tests mock HTTP and never publish. Native compilation, UI smoke and device acceptance
remain separate checks; removing the Electron updater harness does not establish native update E2E.
Данные: `%APPDATA%\TeamsPeach` (Windows), `~/.config/TeamsPeach` (Linux): `core/identity.json`,
`core/profile.json`, `prefs.json`, `logs/`.
### Android development (Windows, Linux CI)
## Ограничения (честно)
The selected Android route is **develop on Windows → manually dispatch Gitea Actions → build and
package entirely on Linux CI → download artifacts → install the test-only APK with Windows `adb`**.
WSL, Docker and a local Linux installation are **not required on the developer PC**. Windows needs
the editor/source checkout, a browser for Gitea and Android SDK Platform-Tools for device installation;
the Android SDK/NDK, Java and heavy native build tools belong on the CI runner for this route.
- Трансляции только P2P (как у официального клиента по умолчанию). SFU-трансляции сервер
обозначает уведомлением — TeamsPeach пишет «не поддерживается». TURN нет: нужен прямой путь
до компьютера стримера (STUN `turn.teamspeak.com`, как у официального клиента).
- Показ своего экрана (отправка трансляции) не реализован.
- Клавиша PTT в TeamsPeach работает только пока окно активно: глобальная клавиша с удержанием
(например, через портал GlobalShortcuts на Wayland) не реализована.
- Цвет ника: официальный клиент подсвечивает собственный ник и ники контактов myTeamSpeak (локальные
связи, а не данные сервера). Без учётной записи контактов нет, поэтому TeamsPeach выделяет только свой ник.
- Аватары: показываются серверные и myTeamSpeak-аватары (публичные https-ссылки, байты проверяются по
сигнатуре). Встроенные иконки групп TeamSpeak (id 100, 200, 300, 500, 600) — нейтральный значок с
названием группы: у сервера нет этих файлов.
- Управление «Cisco OpenH264» и выбор аппаратных бэкендов из TS6 в движке Chromium недоступны;
декодирование выбирает Chromium (на Windows подтверждён аппаратный D3D11 для AV1).
- Сборки macOS и Windows ARM64 не выпускаются: нет сборочных машин. Linux ARM64 собирается
кроссом; запуск на Asahi M1 Pro не проверен — машина недоступна по SSH.
- Пакеты не подписаны: Windows SmartScreen и macOS Gatekeeper будут предупреждать.
Pinned WebRTC's [official Android source-build documentation](https://github.com/webrtc-sdk/webrtc/blob/9c3a1386f07e4348c28cd85c066821cebc3b56e4/docs/native-code/android/README.md)
states “Android development is only supported on Linux.” This is a build-host requirement for CI,
not a requirement to run Linux locally. A Windows WebRTC Android source build is not a supported
alternative. CI keeps the full **Skia + WebRTC** feature set and pinned-source/receipt checks.
## Продукт и дизайн
#### CI administrator prerequisites
Рабочий инструмент: привычная раскладка голосового чата (сервер и дерево слева, канал/чат справа),
настройки — разделы слева (Идентичность, Серверы, Внешний вид, Звук, Видео, Клавиши, Информация) и
карточки справа, как на образце владельца; тема — «как в системе», тёмная или светлая.
Системные шрифты, единственный акцент — персиковый; зелёный —
только «говорит». Всё содержимое сервера выводится как текст (`textContent`), изображения — только
байты, проверенные по сигнатуре. Renderer изолирован (contextIsolation, sandbox, строгая CSP,
список разрешённых команд в main); пути к файлам выбирает только main через системные диалоги.
The manual [`android-ci`](.gitea/workflows/android.yml) workflow is separate from the Linux desktop
workflows above. Before dispatch, an administrator must enable Gitea Actions and artifact support,
register a dedicated **Linux x64** runner labelled `teamspeach-android-linux-x64`, and provision its
toolchains and repository variables. Their presence is not established merely by committing the workflow.
## Проверки
| Repository variable | Required existing runner installation/input |
| --- | --- |
| `ANDROID_SDK_ROOT` | Android SDK with API 36, `build-tools/36.0.0` and `ndk/28.2.13676358` |
| `ANDROID_JAVA_HOME` | JDK 17+ including `keytool` (JDK 21 is acceptable) |
| `NATIVE_LLVM_HOME` | LLVM tool directory used by `xtask` |
| `NATIVE_LIBCLANG_PATH` | libclang library directory |
| `NATIVE_SKIA_SOURCE_DIR` | Dependency-synchronized Skia source checkout containing `bin/gn` |
| `ANDROID_GRADLE_DISTRIBUTION` | Local `gradle-8.14.3-bin.zip`; bootstrap verifies its committed SHA-256 |
| `ANDROID_BUNDLETOOL` | Local `bundletool.jar` for AAB inspection |
- `npm test` — модульные тесты (валидация IPC, сессия просмотра, каталог трансляций).
- `node scripts/core-smoke.mjs <ядро>` — офлайн-инварианты идентичности.
- `node scripts/smoke-ui.mjs`, `smoke-voice.mjs`, `probe-stream.mjs`, `loopback-stream.mjs`,
`smoke-tree.mjs` — реальный UI; результаты прогонов лежат в `docs/evidence/runtime/`.
Also provision the pinned Rust toolchain and `aarch64-linux-android` target, Python 3, Git, CMake,
Ninja and required Linux native-build dependencies. The workflow does not install system SDKs or
download a Gradle distribution. It source-builds pinned WebRTC via `xtask deps`, builds the ARM64
application, packages both variants and runs `verify-package`. Its explicit `--gradle-online true`
allows Gradle dependency resolution on CI; the ordinary packaging default remains offline.
Provision runner resources for the full native build; local developer-machine limits are not a CI policy.
No production signing credentials are needed or used by this unsigned-artifact workflow.
#### Dispatch, download and install from Windows
1. Deliver the source changes through the normal authorized repository process. In the repository's
**Actions** page select **android-ci** (`android.yml`), choose the intended branch/ref and dispatch it
manually. This workflow has no automatic push/tag trigger and does not publish releases.
2. Only after an actual successful run, download and extract **`android-harness-arm64`** and
**`android-production-unsigned-arm64`**. Each bundle includes root `build-info.json` identifying
the exact revision, package manifests/hashes and `aarch64-linux-android` package-verification,
native-build and dependency JSON receipts. Match the run/ref and APK SHA-256 to that evidence
before installing; a bare APK is not provenance.
For version `0.1.7`, the harness APK is `TeamsPeach-0.1.7-android-arm64-harness-test.apk`; the
production bundle contains `TeamsPeach-0.1.7-android-arm64-unsigned.apk` and `.aab`.
Use the version actually recorded by the selected run, not a stale download.
3. Use a separate **ARM64 Android 8/API 26+ test device**, enable USB debugging and approve this
PC's debugging authorization. From the extracted harness APK directory in PowerShell, with
Platform-Tools on `PATH`, select the device explicitly and install **only the harness APK**:
```powershell
adb devices -l
$serial = 'replace-with-authorized-device-serial'
Get-FileHash .\TeamsPeach-0.1.7-android-arm64-harness-test.apk -Algorithm SHA256
adb -s $serial install -t -r .\TeamsPeach-0.1.7-android-arm64-harness-test.apk
```
Compare the displayed hash with the APK entry in `build-info.json` → `sha256`. `-t` permits the intentionally
`testOnly` APK; its debug/test signature is not production signing. Each CI package has an isolated
debug key, so a later run can have a different certificate and `-r` can fail with a signature mismatch.
Never automatically uninstall anything. Do not remove a production installation or its profile to
force an update; use a separate test device. Removing a previous disposable harness installation
requires an explicit user decision: **uninstall deletes that app's data**, including local identities
and settings. The CI job never selects, installs on or runs tests against a phone.
The **unsigned production APK is not installable** until separately authorized production signing
and signature verification are completed. **An AAB is not directly installable with `adb install`**;
it requires the separate signing/store or APK-generation process. These bundles are not a release.
The harness is for test-only/offline smoke scenarios, not production feature/device acceptance.
Neither this workflow configuration nor installing a harness proves live voice, official-client
interoperability, Bluetooth/background behavior or full mobile parity. No successful CI run, generated
APK/AAB, device install or mobile acceptance is claimed here.
**iOS still requires macOS and Xcode/Apple SDKs**, either locally or on separately provisioned macOS
CI, plus appropriate signing/provisioning for devices. Windows editing does not make iOS buildable
on Windows, and this Android workflow does not build or validate iOS. See the
[mobile assessment's current decision](docs/mobile-port-assessment.md#текущее-решение-android-all-ci-2026-11-10)
for its relationship to the preserved historical investigation.
## Usage
The following is the retained behavioral contract for the native client, not a declaration that every
native/platform acceptance case has passed. Consult FEATURE_COMPATIBILITY.md for scoped evidence and gaps.
1. On first launch, enter a nickname to create a local P-256 identity without an account. Settings →
Identity manages multiple identities, their names/nicknames, default selection, additive import,
selected export and cancellable security-level improvement. Default and in-use identities cannot be
deleted. Editing a stored nickname affects future connections; it does not rename every active session.
2. Enter a server address and, if required, its password, then select Connect. Up to eight simultaneous
native connections are supported. Selecting a server tab changes the viewed server, not automatically
the microphone target; input routing has its own controls and acknowledgement. Bookmarks save a name,
address, optional local identity and folder. The sidebar editor also configures a per-connection nickname,
initial channel, startup connection and optional OS-encrypted server/channel passwords. Startup muting
affects only the microphone; it never changes output mute or unmutes a connection. The sidebar supports nested
folders, rename, duplicate, moving/reordering and confirmed subtree deletion. A security-level
rejection offers an explicit improvement action rather than starting expensive work automatically.
3. Click a channel (or focus its row and press Enter) to **browse** its heading and available streams.
This does not move your voice or change the channel-chat destination: the chat tab and composer still
name your current voice channel, and a notice explains this while browsing elsewhere. Double-click
a channel, or use **Join channel** in its header, to move voice. Password channels then show a password field.
The right-edge chevron hides or shows that channel's direct members without joining; collapsed rows show
a compact avatar summary. Collapse choices are saved per server address. Drag the sidebar divider or
focus it and use Left/Right or Home/End to resize; Enter or a double-click restores the responsive default.
4. Settings → Audio provides per-input and per-output device processing profiles. Voice activation can
use automatic speech detection, a volume gate, or a hybrid; push-to-talk can be combined with activation
and an optional release delay. Disabling both gives continuous transmission. Existing profile choices
migrate to this model. Notification output has a separate device and dB level. Processing is independent
and is not claimed bit-identical to the official client's private native DSP. Settings → Key Bindings has
named profiles (add/rename/activate/delete; only the active one is live), the official "Require exact key
match" toggle and the full official action list (push-to-talk, push-to-mute, microphone/speaker, away,
whispers, recording, disconnect, talk power, and Go Live, which opens the normal broadcast source chooser).
A binding is an in-window key or a global key (depends on the OS backend and permissions).
Older whisper-only bindings move unchanged into one active profile.
Local whisper lists/groups, quick whisper and reply use held-target epochs; failed or stale whisper
targets suppress sending rather than falling back to ordinary channel voice. Contact-only targets are
not offered without an account. The microphone test retains at most ten seconds of PCM in memory,
plays it only after an explicit Listen action through the selected output, and blocks server voice
until Finish clears the clip. Device/privacy changes and leaving settings also cancel and clear it.
The microphone and audio buttons update your server-visible mute state; muting or deafening stops transmission in every
mode. Right-click these buttons, or press Shift+F10 while focused, to select an input or output device
using the same selection as Settings → Audio. Left-click still mutes or deafens.
Deafening still blocks playback and transmission; its button state replaces the former muted banner.
5. Streaming members have a screen indicator. Select their channel to see available shares above the chat,
then choose **Watch** on a share. Several announced shares are listed separately; browsing alone never
subscribes to one. If the server flags a member as streaming but does not provide usable details, the
area shows discovery progress or the actual error instead of inventing a watchable stream.
Each watched share gets its own tile above chat and keeps playing while you browse other channels.
Volume, mute, picture in picture, full screen and Stop watching apply to that tile, not its neighbours.
The picture fills the tile: its name remains over the video while controls appear on pointer hover or
keyboard focus (always visible on coarse-pointer devices). **Stream details** opens the live statistics;
Escape closes that panel. Unavailable picture-in-picture remains disabled with an explanatory label.
Native picture in picture detaches the same video into an OS-managed floating window; full screen and
PiP do not subscribe again. Ending a share closes only its presentation; disconnecting closes all views.
Drag the divider above chat or focus it and use Up/Down or Home/End to resize the stream stage. Enter or
a double-click resets its height. Collapse hides the stage without stopping watched shares; its height
and collapsed state are saved. The chat retains usable space at the minimum window size.
6. Application chrome does not select text during interaction. Chat messages, editable fields, public
identity data and other useful content remain selectable. The server's host banner sits behind its
top card rather than in a separate panel, with a theme-aware contrast overlay.
7. Right-click a member, or focus the row and press Shift+F10 / the Menu key, for target-specific actions.
The menu uses server permission hints and distinguishes a known denial from an unknown permission that
the server must decide; group names never grant authority. Group/permission changes and moderation show
the exact target and operation before confirmation. A target that leaves, changes identity, or moves
channels closes its stale menu. Server errors are shown rather than reported as success.
Local volume uses the official -200..+10 dB taper, Mute and Reset. Reset restores 0 dB and unmutes;
explicitly committed modifiers persist by UID, while mute is session-local. Gain is applied before
voice mixing and never changes other participants.
The native avatar chooser accepts PNG/JPEG up to 128 KiB; UI intents do not supply arbitrary host paths.
Permission lists show explicit client/channel assignments, not a full effective-rights audit.
8. **Start Stream** opens the source chooser. Selecting a tile shows its thumbnail; **Next** starts
the muted private preview. Only **Go Live** publishes it. Choose an observed window/screen or
explicitly opt into a camera; camera capture does not include a microphone. Back, cancellation,
source loss and disconnect release the preview capture.
Presets and advanced controls set resolution/frame-rate and bitrate targets. Public allows viewers;
Selected participants uses a local UID allowlist (empty means nobody); Private requires a decision
per viewer. The stream can still appear in discovery. Audience settings remain locked until Stop.
Selected-application audio is opt-in: Windows uses WASAPI process-tree capture on build 20348+;
Linux uses PulseAudio/pipewire-pulse sink-input streams through `pactl` and `parec`. Pure PipeWire
without Pulse compatibility and macOS selected-application audio are not implemented.
Changing the audio source/scope/app selection never silently reopens a system picker. Changed sources
require explicit preview restart or Back and a fresh source selection, according to the native backend.
Per-app/master gains apply to the outgoing mix; clicking the percent readout resets gain to 100%.
System audio is never substituted silently, and the local tile is not another receiver subscription.
Native capture depends on OS consent and the installed desktop/portal backend; these paths are not
universal cross-platform or official-client interoperability proof.
9. Channel/server menus provide typed administration with explicit destructive confirmations and server
errors. Snapshot import is non-atomic: completed server changes are not rolled back by cancellation.
General file browsing/transfers support the legacy server transport; HTTPFT/S3 remain explicit gaps
with no speculative legacy fallback. Filesystem publication fails safely when required atomic/no-replace
semantics are unavailable. Native services approve recording/transfer destinations through chooser grants.
File Transfer settings retain an approved download folder or ask every time, and apply upload/download
concurrency across all tabs (combined at most ten) plus shared directional rate limits. Limits apply to
active file/snapshot work without restarting streams; they are conservative ceilings, not bandwidth guarantees.
10. Chat history is local and separated by own identity, server and channel/peer identity. Drafts and
unread state are connection-local. Rich text, local math/diagrams, emoji and server-file links do not
require cloud services. Remote images require explicit consent; trusted external sites can be removed
in Settings → Privacy. Central myTeamSpeak/homebase chat and cloud contacts are outside the account-free
scope. Server-hosted Matrix rooms on `MATRIXCHAT` servers are a separate, unimplemented transport:
their frontend uses the server identity, but native endpoint discovery, authentication and invite requests
remain unresolved. They are not excluded merely because they share Matrix room controls. Local UID contacts are separate.
11. Streams support hide/show without unsubscribing, ordering, focus with a secondary strip, pages,
an internal tile overlay and moving the existing stage over the server tree. Publisher admission,
kick/ban/unblock, pause and live options keep the original tracks/sessions. Standalone pop-out must
reuse the same decoded media and ownership without a second join. Historical browser-only viewport
emulation does not prove native pop-out painting or SFU interoperability.
## Local panels and integrations
- **Privacy:** manage trusted external hosts and reset remembered confirmations. Skipping a confirmation
changes that operation's local preference; reset restores prompts. No analytics service is enabled.
- **Contacts:** save server users locally by identity UID, optionally give them aliases, and show/sort/group
offline entries. Presence comes from the client's connected server snapshots, not a global service.
Public badge display does not redeem badges or claim ownership of them.
- **Remote Apps:** excluded by the owner's explicit instruction. No Remote Apps listener, authorization
IPC, page or remote-button binding is included.
- **Server icons:** the server administration pane lists, uploads, deletes and assigns icons through
legacy TeamSpeak file transfer. The server's permissions remain authoritative. A reconnect invalidates
the panel's mutation grant; HTTPFT/S3 storage is not silently treated as an empty icon collection.
- **Noise reduction:** Settings → Audio has four levels saved per input device. The implementation is
independent DSP; selected settings and generated-media checks do not prove microphone sound quality
or bit-identical behavior with the official client.
- **Saved bookmark passwords:** native protected storage uses platform secret APIs, never a plaintext
fallback. Historical encrypted passwords require explicit one-time re-entry; old ciphertext is not
reused. Reveal requires an explicit action, address changes invalidate saved credentials, and forgetting
a password remains possible if the key store is unavailable. Encryption is tied to the OS user/key store,
not a portable backup format. Hardware verification is platform-specific; simulated backends are not proof.
## Language
The interface defaults to English, independently of the operating-system language. Select Russian in
Settings → Appearance; the saved choice applies to the interface and native identity dialogs. Language
changes do not translate server names, chat messages or operating-system device names.
## Updates
Check for updates in Settings → Information. Updates come only from published releases of the public
[TeamsPeach/client repository](https://git.eeee.moe/TeamsPeach/client), without credentials. The native
updater requires a validated `rust-slint` release manifest, exact target artifacts and verified hashes.
Historical browser-client release feeds alone are insufficient for a native offer.
Windows x64 NSIS installations with a valid native installation receipt and Linux x64/ARM64 AppImages
have explicit-install paths. Portable archives and custom-profile Windows runs are manual-only;
development/test builds do not self-update. Preview includes prereleases; Stable excludes them.
Nothing installs or restarts automatically, and interrupting an active session requires confirmation.
See [Updates](docs/updates.md) for platform modes and release/acceptance requirements. No successful
published native upgrade is claimed without source/destination versions and preserved-profile evidence.
## Identity backups and profile migration
Identity export writes a TeamSpeak-format `.ini` through a native chooser after a private-key warning.
**This file contains your private key: protect it like a password.** Import is additive, preserves existing
UIDs, and never silently replaces a corrupt identity. Native onboarding also offers explicit migration
from an existing historical profile into a separate native profile; close the old client first.
Migration copies and validates identities/default selection, preferences, history, keybindings, whispers,
local volumes, file settings and extensions, leaving the source untouched. Passwords require re-entry;
legacy device identifiers require separate user-confirmed input/output/notification mapping before capture.
Interrupted staging imports need an explicit recovery decision; no silent reset or source deletion occurs.
Native data defaults to `%APPDATA%\TeamsPeachNative` on Windows,
`$XDG_CONFIG_HOME/TeamsPeachNative` (or `~/.config/TeamsPeachNative`) on Linux, and
`~/Library/Application Support/TeamsPeachNative` on macOS. These roots are separate from historical
`TeamsPeach` profiles. Mobile uses its private application container's `profile-v1` directory.
An absolute, normalized `TEAMSPEACH_PROFILE_DIR` selects a separate root; do not point it at the old profile.
## Limitations
- Screenshares use P2P only, as the official client does by default. SFU notifications are reported as
unsupported. There is no TURN relay: the viewer needs a direct network path to the streaming computer
(STUN uses `turn.teamspeak.com`, as in the official client).
- P2P screenshare publishing is implemented, but native source capture on every OS/window manager,
macOS selected-application audio and official-client interoperability are not all verified. SFU publishing
is unavailable. See the feature matrix for the precise implementation and evidence boundaries.
- In-window push-to-talk must release on focus loss. Global bindings depend on the real OS backend,
registration and permissions; hidden checks do not prove OS registration or Wayland portal operation.
No platform-wide shortcut guarantee is made.
- Local contacts are keyed by server identity UID and can be highlighted in the tree. They do not sync
with myTeamSpeak, provide global presence or enable cloud/offline chat.
- Server-stored avatars, icons and banners use TeamSpeak file transfer. myTeamSpeak avatars use public
HTTPS URLs announced by the server; downloaded image bytes are checked by signature. A myTeamSpeak
avatar was observed in the live run; server-stored avatar support is implemented but was not exercised
live because no client on the test server advertised one.
Built-in TeamSpeak group icons (IDs 100, 200, 300, 500, 600) use a neutral badge with the group name,
because the server does not supply these files.
- Native decoder policy applies to the real libwebrtc factory. Historical Chromium hardware-decoder
evidence does not establish native hardware decode, per-codec selection or Cisco backend support.
- macOS and Windows ARM64 builds are not published because build hosts are unavailable. Linux ARM64 is
cross-compiled; execution on Asahi M1 Pro hardware has not been checked because the target was
unreachable over SSH.
- Packages are unsigned. Windows SmartScreen warns about unsigned builds; macOS Gatekeeper would also
require attention for a future macOS build.
- The recorded two-way voice run used synthetic capture between two TeamsPeach clients. It does not
prove live microphone interoperability with the official TS6 client or operation on Asahi hardware.
## Product and design
The design contract reproduces the installed TeamSpeak 6 client's source values (see
DESIGN.md and `docs/evidence/official-parity/`): a three-pane window with a 270 px navigation sidebar
(collapsible to a 62 px rail) listing server connections and saved servers, a 500 px server pane with
the server header card and channel tree, and a detail pane with the channel header, stream stage, chat
and composer. Settings open in the main and detail panes with the official category column and section
cards (Identity, Servers, Appearance, Audio, Video, Keyboard, Chats, Notifications, OS Specific,
Information). Reduced-transparency, reduced-motion and forced-colors preferences have explicit fallbacks.
New profiles default to dark independently of the OS; Light and System remain selectable. Account-bound
official surfaces (notification bell, cloud contacts, myTeamSpeak presence) are intentionally absent;
local UID contacts are an independent account-free feature.
The native window must retain OS minimize, maximize/restore, close, system shortcuts and caption behavior
without fake JavaScript controls. The target app-bar geometry is 44 px and its colors follow the theme;
actual caption integration and accessibility require platform-specific evidence. Fullscreen/PiP must not
create a second media subscription. Bundled Noto Sans (OFL) and the official blue tint retain the typography
and color contract; green indicates a speaker.
Server text remains data, never executable markup. Native services validate commands and media bytes,
bind delayed actions to connection/session/UI generations, and own native chooser/path capabilities.
No embedded browser, browser sandbox, DOM or renderer/main IPC is part of the runtime architecture.
## Repository language and evidence
Repository-authored documentation, comments, logs, diagnostics, scripts and release notes are in
English. Localized UI text belongs in the shared translation catalog; technical error details stay in
English and may be shown after a localized explanation. Server content, operating-system device names
and user messages are data, not translation resources.
Historical JSON captures and screenshots in `docs/evidence/runtime/` retain the exact UI text, server
names and device names observed during each run, including Russian text. They are not translated or
rewritten to resemble the current interface. Unicode test fixtures retain their original values.
## Checks and evidence
Native verification uses the Cargo workspace and `xtask` entry points, not the removed browser harness:
```sh
cargo test --release --locked --workspace
cargo run -p xtask -- build --target x86_64-pc-windows-msvc --test-harness true
cargo run -p xtask -- smoke --target x86_64-pc-windows-msvc --scenario offline-ui --out target/evidence/native-ui
cargo run -p xtask -- smoke --target x86_64-pc-windows-msvc --scenario migration --out target/evidence/native-migration
cargo run -p xtask -- smoke --target x86_64-pc-windows-msvc --scenario media-loopback --out target/evidence/native-media
```
Use fresh output directories and disposable profiles. Test-harness builds disable real network/device/OS
actions and are not release eligible. Generated media proves only its exercised local transport/decoder
path. Live official peers, physical capture/playback, visible native windows, OS accessibility,
installed upgrades and Asahi/mobile hardware need separately authorized isolated checks.
`native/compatibility.json` preserves 718 pending acceptance requirements, not pass marks. Historical
captures in `docs/evidence/` remain exact records of their original builds; they do not prove native parity.
Strict visual comparisons previously failed and are not converted to passes by the stack cutover.
See FEATURE_COMPATIBILITY.md for recorded native evidence and explicit remaining prerequisites.
-226
View File
@@ -1,226 +0,0 @@
'use strict';
const { spawn } = require('node:child_process');
const { EventEmitter } = require('node:events');
const readline = require('node:readline');
const fs = require('node:fs');
const READY_TIMEOUT_MS = 15000;
const STOP_TIMEOUT_MS = 6000;
const AUDIO_BACKLOG_LIMIT = 128 * 1024;
const MAX_LINE_BYTES = 256 * 1024;
const TIMEOUTS = {
connect: 60000,
disconnect: 10000,
rename: 15000,
join_channel: 15000,
send_text: 15000,
stream_list: 15000,
default: 15000,
};
/**
* Owns one `teamspeach-core` child process speaking the newline-JSON protocol of docs/bridge.md.
* Emits: 'event' (core event object), 'status' ({status, code?, message?, coreVersion?}).
*/
class CoreProcess extends EventEmitter {
constructor({ binary, dataDir, logFile, logLevel }) {
super();
this.binary = binary;
this.dataDir = dataDir;
this.logFile = logFile;
this.logLevel = logLevel || 'info';
this.child = null;
this.pending = new Map();
this.nextId = 1;
this.status = 'stopped';
this.coreVersion = null;
this.stopping = false;
this.droppedAudioFrames = 0;
}
start() {
if (this.child) throw new Error('core already running');
this.stopping = false;
this.coreVersion = null;
rotateLog(this.logFile);
const log = fs.createWriteStream(this.logFile, { flags: 'a' });
log.write(`\n=== ${new Date().toISOString()} start ${this.binary}\n`);
let child;
try {
child = spawn(this.binary, ['--data-dir', this.dataDir], {
stdio: ['pipe', 'pipe', 'pipe'],
windowsHide: true,
env: { ...process.env, TEAMSPEACH_LOG: process.env.TEAMSPEACH_LOG || this.logLevel },
});
} catch (err) {
log.end();
this._setStatus('failed', { message: err.message });
return;
}
this.child = child;
this._setStatus('starting');
child.stderr.on('data', (chunk) => log.write(chunk));
child.stdin.on('error', (err) => log.write(`[main] stdin error: ${err.message}\n`));
const rl = readline.createInterface({ input: child.stdout, crlfDelay: Infinity });
rl.on('line', (line) => this._onLine(line, log));
const readyTimer = setTimeout(() => {
if (this.status === 'starting') {
log.write('[main] core did not report ready in time, terminating\n');
this._setStatus('failed', { message: 'Ядро не ответило за 15 секунд' });
child.kill();
}
}, READY_TIMEOUT_MS);
child.on('error', (err) => {
clearTimeout(readyTimer);
log.write(`[main] spawn error: ${err.message}\n`);
this._setStatus('failed', { message: err.message });
});
child.on('exit', (code, signal) => {
clearTimeout(readyTimer);
rl.close();
log.write(`[main] core exited code=${code} signal=${signal}\n`);
log.end();
this.child = null;
for (const [, entry] of this.pending) {
clearTimeout(entry.timer);
entry.resolve({ ok: false, error: { code: 'core_exited', message: 'Ядро завершило работу' } });
}
this.pending.clear();
const expected = this.stopping;
this._setStatus(expected ? 'stopped' : 'exited', { code, signal, message: exitMessage(code) });
});
this.once('ready-internal', () => clearTimeout(readyTimer));
}
_onLine(line, log) {
if (!line) return;
let msg;
try {
msg = JSON.parse(line);
} catch {
log.write(`[main] unparseable stdout line (${line.length} chars)\n`);
return;
}
if (msg === null || typeof msg !== 'object') return;
if (Object.prototype.hasOwnProperty.call(msg, 'id')) {
const entry = this.pending.get(msg.id);
if (!entry) return;
this.pending.delete(msg.id);
clearTimeout(entry.timer);
entry.resolve(msg.ok ? { ok: true, result: msg.result ?? {} } : { ok: false, error: normalizeError(msg.error) });
return;
}
if (msg.event === 'ready') {
this.coreVersion = typeof msg.core_version === 'string' ? msg.core_version : null;
if (msg.protocol !== 1) {
log.write(`[main] unsupported core protocol ${msg.protocol}\n`);
this._setStatus('failed', { message: `Неподдерживаемая версия протокола ядра: ${msg.protocol}` });
this.child?.kill();
return;
}
this.emit('ready-internal');
this._setStatus('ready', { coreVersion: this.coreVersion });
return;
}
if (typeof msg.event === 'string') this.emit('event', msg);
}
_setStatus(status, extra = {}) {
this.status = status;
this.emit('status', { status, ...extra });
}
get running() {
return this.child !== null;
}
request(cmd, args) {
if (!this.child || this.status !== 'ready') {
return Promise.resolve({ ok: false, error: { code: 'core_unavailable', message: 'Ядро не запущено' } });
}
const id = `m${this.nextId++}`;
const payload = args === undefined ? { id, cmd } : { id, cmd, args };
const line = JSON.stringify(payload) + '\n';
if (Buffer.byteLength(line) > MAX_LINE_BYTES) {
return Promise.resolve({ ok: false, error: { code: 'bad_request', message: 'Запрос слишком большой' } });
}
return new Promise((resolve) => {
const timeoutMs = TIMEOUTS[cmd] ?? TIMEOUTS.default;
const timer = setTimeout(() => {
this.pending.delete(id);
resolve({ ok: false, error: { code: 'timeout', message: `Ядро не ответило на «${cmd}» за ${Math.round(timeoutMs / 1000)} с` } });
}, timeoutMs);
this.pending.set(id, { resolve, timer });
this.child.stdin.write(line);
});
}
/** audio_frame / audio_end: never answered. Frames are dropped instead of queueing unboundedly behind a stalled pipe. */
sendAudio(cmd, args) {
if (!this.child || this.status !== 'ready') return false;
if (cmd === 'audio_frame' && this.child.stdin.writableLength > AUDIO_BACKLOG_LIMIT) {
this.droppedAudioFrames += 1;
return false;
}
this.child.stdin.write(JSON.stringify(args === undefined ? { cmd } : { cmd, args }) + '\n');
return true;
}
async stop() {
const child = this.child;
if (!child) return;
this.stopping = true;
const exited = new Promise((resolve) => child.once('exit', resolve));
if (this.status === 'ready') {
await Promise.race([this.request('shutdown'), delay(STOP_TIMEOUT_MS)]);
} else {
child.stdin.end();
}
const done = await Promise.race([exited.then(() => true), delay(STOP_TIMEOUT_MS).then(() => false)]);
if (!done && this.child) {
this.child.kill();
await Promise.race([exited, delay(2000)]);
}
}
}
function normalizeError(error) {
if (!error || typeof error !== 'object') return { code: 'internal', message: 'Пустой ответ об ошибке' };
const out = { code: String(error.code ?? 'internal'), message: String(error.message ?? '') };
if (error.ts_error && typeof error.ts_error === 'object') out.ts_error = error.ts_error;
if (error.detail && typeof error.detail === 'object') out.detail = error.detail;
return out;
}
function exitMessage(code) {
switch (code) {
case 0: return 'Ядро завершило работу';
case 2: return 'Ядро отклонило аргументы запуска';
case 3: return 'Профиль уже используется другим экземпляром TeamsPeach или каталог данных недоступен';
case 1: return 'Внутренняя ошибка ядра (подробности в журнале core.log)';
default: return `Ядро завершилось с кодом ${code}`;
}
}
function rotateLog(file) {
try {
if (fs.statSync(file).size > 5 * 1024 * 1024) fs.renameSync(file, `${file}.1`);
} catch {
// no log yet
}
}
function delay(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
module.exports = { CoreProcess };
-146
View File
@@ -1,146 +0,0 @@
'use strict';
/**
* Allowlist + argument-shape validation for renderer → core requests.
* The renderer may only call these bridge commands; `shutdown`, `audio_frame` and `audio_end`
* are main-owned (audio has its own binary IPC channel). Unknown keys are rejected like the core does.
*/
class ValidationError extends Error {
constructor(message) {
super(message);
this.code = 'bad_request';
}
}
const CONTROL_CHARS = /[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/;
const str = (min, max, { multiline = false, maxBytes } = {}) => (value, key) => {
if (typeof value !== 'string') throw new ValidationError(`${key}: ожидалась строка`);
if (value.length < min || value.length > max) throw new ValidationError(`${key}: недопустимая длина`);
if (maxBytes !== undefined && Buffer.byteLength(value, 'utf8') > maxBytes) throw new ValidationError(`${key}: слишком длинно`);
if (multiline ? CONTROL_CHARS.test(value) : /[\u0000-\u001f\u007f]/.test(value)) {
throw new ValidationError(`${key}: недопустимые управляющие символы`);
}
return value;
};
const posInt = (value, key) => {
if (!Number.isSafeInteger(value) || value < 0) throw new ValidationError(`${key}: ожидалось целое число`);
return value;
};
const bool = (value, key) => {
if (typeof value !== 'boolean') throw new ValidationError(`${key}: ожидалось true/false`);
return value;
};
const oneOf = (...allowed) => (value, key) => {
if (!allowed.includes(value)) throw new ValidationError(`${key}: недопустимое значение`);
return value;
};
const optional = (check) => {
const wrapped = (value, key) => check(value, key);
wrapped.optional = true;
return wrapped;
};
function isPlainObject(value) {
return value !== null && typeof value === 'object' && Object.getPrototypeOf(value) === Object.prototype;
}
function shape(spec) {
return (args) => {
if (args === undefined || args === null) args = {};
if (!isPlainObject(args)) throw new ValidationError('args: ожидался объект');
for (const key of Object.keys(args)) {
if (!Object.prototype.hasOwnProperty.call(spec, key)) throw new ValidationError(`${key}: неизвестный аргумент`);
}
const out = {};
for (const [key, check] of Object.entries(spec)) {
const value = args[key];
if (value === undefined) {
if (!check.optional) throw new ValidationError(`${key}: обязательный аргумент`);
continue;
}
out[key] = check(value, key);
}
return out;
};
}
const streamId = str(1, 256);
const SIGNAL_COMMANDS = new Set(['answer', 'iceCandidate']);
function signalJson(value) {
if (!isPlainObject(value)) throw new ValidationError('json: ожидался объект');
const keys = Object.keys(value);
if (keys.length !== 2 || !keys.includes('cmd') || !keys.includes('args')) throw new ValidationError('json: ожидались поля cmd и args');
if (!SIGNAL_COMMANDS.has(value.cmd)) throw new ValidationError('json.cmd: недопустимая команда сигнализации');
const args = value.args;
if (!isPlainObject(args)) throw new ValidationError('json.args: ожидался объект');
if (value.cmd === 'answer') {
shape({ answer: str(1, 60000, { multiline: true }) })(args);
} else {
shape({
mLine: posInt,
mid: str(0, 64),
sdp: str(0, 2048),
})(args);
}
const serialized = JSON.stringify(value);
if (Buffer.byteLength(serialized, 'utf8') > 60 * 1024) throw new ValidationError('json: больше 60 КиБ');
return JSON.parse(serialized);
}
const COMMANDS = {
profile_get: shape({}),
profile_create: shape({ nickname: str(1, 64) }),
rename: shape({ nickname: str(1, 64) }),
connect: shape({
address: str(1, 255),
server_password: optional(str(0, 255)),
channel: optional(str(1, 512)),
channel_password: optional(str(0, 255)),
}),
disconnect: shape({ message: optional(str(0, 80)) }),
join_channel: shape({ channel_id: posInt, password: optional(str(0, 255)) }),
send_text: (args) => {
const out = shape({
target: oneOf('channel', 'server', 'client'),
client_id: optional(posInt),
message: str(1, 8192, { multiline: true, maxBytes: 8192 }),
})(args);
if ((out.target === 'client') !== (out.client_id !== undefined)) {
throw new ValidationError('client_id: обязателен только для личных сообщений');
}
return out;
},
set_audio: shape({ input_muted: optional(bool), output_muted: optional(bool) }),
stream_list: shape({ client_id: optional(posInt) }),
stream_join: shape({ stream_id: streamId, client_id: posInt, message: optional(str(0, 200)) }),
stream_signal: shape({ stream_id: streamId, client_id: posInt, json: signalJson }),
stream_leave: shape({ stream_id: streamId, client_id: posInt }),
fetch_icon: shape({
icon_id: (v, k) => {
if (!Number.isSafeInteger(v) || v <= 0 || v > 0xffffffff) throw new ValidationError(`${k}: ожидался идентификатор иконки`);
return v;
},
}),
fetch_avatar: shape({ client_id: posInt }),
fetch_banner: shape({ channel_id: posInt }),
fetch_server_banner: shape({}),
};
/** Returns sanitized args or throws ValidationError. */
function validateRequest(cmd, args) {
if (typeof cmd !== 'string' || !Object.prototype.hasOwnProperty.call(COMMANDS, cmd)) {
const err = new ValidationError('Команда не разрешена');
err.code = 'unknown_command';
throw err;
}
return COMMANDS[cmd](args);
}
module.exports = { validateRequest, ValidationError, RENDERER_COMMANDS: Object.keys(COMMANDS) };
-531
View File
@@ -1,531 +0,0 @@
'use strict';
const path = require('node:path');
const fs = require('node:fs');
const { execFile } = require('node:child_process');
const {
app, BrowserWindow, ipcMain, protocol, session, nativeTheme, dialog, Menu, shell, clipboard,
} = require('electron');
// A disposable profile directory for tests/second instances. Set by whoever launches the app, never by the renderer.
const profileOverride = process.env.TEAMSPEACH_PROFILE_DIR;
if (profileOverride) {
if (!path.isAbsolute(profileOverride)) {
console.error('TEAMSPEACH_PROFILE_DIR must be an absolute path');
process.exit(2);
}
app.setPath('userData', profileOverride);
}
const { RENDERER_DIR, resolveCoreBinary, dataDir, logsDir, prefsFile } = require('./paths');
const { CoreProcess } = require('./core-process');
const { validateRequest } = require('./ipc-validate');
const { Prefs } = require('./prefs');
const APP_SCHEME = 'app';
const APP_HOST = 'teamspeach';
const APP_ORIGIN = `${APP_SCHEME}://${APP_HOST}`;
const CSP = [
"default-src 'none'",
"script-src 'self'",
"style-src 'self'",
"img-src 'self' data: blob:",
"media-src 'self' blob: mediastream:",
"font-src 'self'",
"connect-src 'none'",
"worker-src 'self'",
"base-uri 'none'",
"form-action 'none'",
"frame-src 'none'",
"frame-ancestors 'none'",
"object-src 'none'",
].join('; ');
const MIME = {
'.html': 'text/html; charset=utf-8',
'.js': 'text/javascript; charset=utf-8',
'.css': 'text/css; charset=utf-8',
'.svg': 'image/svg+xml',
'.png': 'image/png',
'.woff2': 'font/woff2',
'.json': 'application/json',
};
// Chromium hides host candidates behind mDNS names when the page has no capture permission.
// The TS6 streamer is native libwebrtc; plain host candidates keep LAN viewing working even while the mic is off.
app.commandLine.appendSwitch('disable-features', 'WebRtcHideLocalIpsWithMdns');
// Hardware video decoding policy is a launch-time Chromium switch, so it is read from the saved
// preferences before the app is ready and only changes after a restart.
const hardwareVideoDecodeAtLaunch = new Prefs(prefsFile()).get().hardwareVideoDecode;
if (!hardwareVideoDecodeAtLaunch) app.commandLine.appendSwitch('disable-accelerated-video-decode');
protocol.registerSchemesAsPrivileged([
{ scheme: APP_SCHEME, privileges: { standard: true, secure: true, supportFetchAPI: true, codeCache: true } },
]);
let mainWindow = null;
let core = null;
let prefs = null;
const gotInstanceLock = app.requestSingleInstanceLock();
if (!gotInstanceLock) {
app.quit();
} else {
app.on('second-instance', () => {
if (mainWindow) {
if (mainWindow.isMinimized()) mainWindow.restore();
mainWindow.focus();
}
});
}
let coreStatus = { status: 'starting' };
let connectionState = 'disconnected';
let quitting = false;
let rendererLog = null;
let rendererLogBudget = { windowStart: 0, count: 0 };
function isAppUrl(url) {
return typeof url === 'string' && url.startsWith(`${APP_ORIGIN}/`);
}
function trustedSender(event) {
return Boolean(mainWindow && event.sender === mainWindow.webContents && event.senderFrame && isAppUrl(event.senderFrame.url));
}
function sendToRenderer(channel, payload) {
if (mainWindow && !mainWindow.isDestroyed()) mainWindow.webContents.send(channel, payload);
}
// ---------- core lifecycle ----------
function startCore() {
const binary = resolveCoreBinary();
if (!binary.path) {
coreStatus = { status: 'missing', candidates: binary.candidates };
sendToRenderer('core:status', coreStatus);
return;
}
fs.mkdirSync(logsDir(), { recursive: true });
core = new CoreProcess({
binary: binary.path,
dataDir: dataDir(),
logFile: path.join(logsDir(), 'core.log'),
});
core.on('status', (status) => {
coreStatus = { ...status, binary: binary.path };
if (status.status !== 'ready') connectionState = 'disconnected';
sendToRenderer('core:status', coreStatus);
});
core.on('event', onCoreEvent);
core.start();
}
function onCoreEvent(evt) {
if (evt.event === 'audio') {
if (typeof evt.pcm !== 'string') return;
const pcm = Buffer.from(evt.pcm, 'base64');
if (pcm.length !== 1920) return;
sendToRenderer('core:audio', { pcm, speakers: Array.isArray(evt.speakers) ? evt.speakers : [] });
return;
}
if (evt.event === 'state' && typeof evt.state === 'string') connectionState = evt.state;
if (evt.event === 'state' && evt.state === 'disconnected') externalMedia.clear();
if (evt.event === 'snapshot' && Array.isArray(evt.clients)) {
for (const c of evt.clients) {
if (Array.isArray(c.myts_avatars)) for (const v of c.myts_avatars) allowExternalMedia(v && v.url);
}
}
sendToRenderer('core:event', evt);
}
async function restartCore() {
if (core) {
const old = core;
core = null;
await old.stop();
old.removeAllListeners();
}
startCore();
}
function runCoreCli(args) {
const binary = resolveCoreBinary();
if (!binary.path) return Promise.resolve({ ok: false, error: { code: 'core_missing', message: 'Исполняемый файл ядра не найден' } });
return new Promise((resolve) => {
execFile(binary.path, args, { windowsHide: true, timeout: 30000, maxBuffer: 1024 * 1024 }, (err, stdout, stderr) => {
if (stderr) appendLog('core-cli.log', stderr);
const line = String(stdout || '').trim().split(/\r?\n/).filter(Boolean).pop();
let parsed = null;
try {
parsed = line ? JSON.parse(line) : null;
} catch {
parsed = null;
}
if (parsed && typeof parsed === 'object') {
resolve(parsed.ok ? { ok: true, uid: parsed.uid } : { ok: false, error: parsed.error || { code: 'internal', message: 'Неизвестная ошибка' } });
return;
}
resolve({ ok: false, error: { code: 'internal', message: err ? err.message : 'Ядро не вернуло результат' } });
});
});
}
function appendLog(file, text) {
try {
fs.mkdirSync(logsDir(), { recursive: true });
fs.appendFileSync(path.join(logsDir(), file), `${new Date().toISOString()} ${text}\n`);
} catch {
// logging must never break the app
}
}
// ---------- external images announced by the server (http/https only) ----------
const EXTERNAL_MEDIA_LIMIT = 4 * 1024 * 1024;
const externalMedia = new Set();
let mediaSession = null;
/** Only URLs the core reported from server data may be fetched; the renderer cannot add its own. */
function allowExternalMedia(url) {
if (typeof url !== 'string' || url.length > 2048) return;
try {
const u = new URL(url);
if (u.protocol !== 'https:' && u.protocol !== 'http:') return;
} catch {
return;
}
if (externalMedia.size >= 512) externalMedia.clear();
externalMedia.add(url);
}
function sniffImage(b) {
if (b.length >= 8 && b.readUInt32BE(0) === 0x89504e47) return 'image/png';
if (b.length >= 3 && b[0] === 0xff && b[1] === 0xd8 && b[2] === 0xff) return 'image/jpeg';
if (b.length >= 6 && b.toString('latin1', 0, 4) === 'GIF8') return 'image/gif';
if (b.length >= 12 && b.toString('latin1', 0, 4) === 'RIFF' && b.toString('latin1', 8, 12) === 'WEBP') return 'image/webp';
if (b.length >= 4 && b.readUInt32BE(0) === 0x00000100) return 'image/x-icon';
return null;
}
async function fetchExternalMedia(url) {
if (typeof url !== 'string' || !externalMedia.has(url)) {
return { ok: false, error: { code: 'forbidden', message: 'Адрес не был объявлен сервером' } };
}
if (!mediaSession) mediaSession = session.fromPartition('teamspeach-media', { cache: true });
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), 15000);
try {
const res = await mediaSession.fetch(url, { signal: controller.signal, headers: { Accept: 'image/*' } });
const finalProtocol = new URL(res.url || url).protocol;
if (finalProtocol !== 'https:' && finalProtocol !== 'http:') throw new Error('redirect to a non-http scheme');
if (!res.ok) return { ok: false, error: { code: 'http_error', message: `HTTP ${res.status}` } };
const reader = res.body.getReader();
const chunks = [];
let size = 0;
for (;;) {
const { done, value } = await reader.read();
if (done) break;
size += value.byteLength;
if (size > EXTERNAL_MEDIA_LIMIT) {
controller.abort();
return { ok: false, error: { code: 'media_too_large', message: 'Изображение больше 4 МиБ' } };
}
chunks.push(Buffer.from(value));
}
const bytes = Buffer.concat(chunks);
// Servers mislabel images (e.g. text/plain); trust only the bytes.
const mime = sniffImage(bytes);
if (!mime) return { ok: false, error: { code: 'media_unsupported', message: 'Не изображение' } };
return { ok: true, result: { mime, bytes: bytes.length, data: bytes.toString('base64') } };
} catch (err) {
return { ok: false, error: { code: 'io', message: err.name === 'AbortError' ? 'Истекло время загрузки' : err.message } };
} finally {
clearTimeout(timer);
}
}
// ---------- identity backup (main-only, native dialogs) ----------
async function exportIdentity() {
const result = await dialog.showSaveDialog(mainWindow, {
title: 'Экспорт идентичности TeamsPeach',
defaultPath: path.join(app.getPath('documents'), 'teamspeach-identity.ini'),
filters: [{ name: 'Идентичность TeamSpeak', extensions: ['ini'] }],
properties: ['showOverwriteConfirmation', 'createDirectory'],
});
if (result.canceled || !result.filePath) return { ok: false, canceled: true };
const outcome = await runCoreCli(['identity', 'export', '--data-dir', dataDir(), '--out', result.filePath]);
if (outcome.ok && process.platform !== 'win32') {
try {
fs.chmodSync(result.filePath, 0o600);
} catch (err) {
appendLog('core-cli.log', `chmod failed: ${err.message}`);
}
}
return outcome.ok ? { ok: true, uid: outcome.uid, file: path.basename(result.filePath) } : outcome;
}
async function importIdentity() {
if (connectionState !== 'disconnected') {
return { ok: false, error: { code: 'connected', message: 'Сначала отключитесь от сервера' } };
}
const identityExists = fs.existsSync(path.join(dataDir(), 'identity.json'));
if (identityExists) {
const confirm = await dialog.showMessageBox(mainWindow, {
type: 'warning',
title: 'Заменить идентичность?',
message: 'Импорт заменит текущую идентичность.',
detail: 'Текущий UID будет потерян, если у вас нет его резервной копии. Серверные права и группы привязаны к UID.',
buttons: ['Отмена', 'Выбрать файл и заменить'],
defaultId: 0,
cancelId: 0,
noLink: true,
});
if (confirm.response !== 1) return { ok: false, canceled: true };
}
const pick = await dialog.showOpenDialog(mainWindow, {
title: 'Импорт идентичности',
filters: [{ name: 'Идентичность TeamSpeak', extensions: ['ini'] }, { name: 'Все файлы', extensions: ['*'] }],
properties: ['openFile'],
});
if (pick.canceled || pick.filePaths.length !== 1) return { ok: false, canceled: true };
const old = core;
core = null;
if (old) {
await old.stop();
old.removeAllListeners();
}
const args = ['identity', 'import', '--data-dir', dataDir(), '--in', pick.filePaths[0]];
if (identityExists) args.push('--replace');
const outcome = await runCoreCli(args);
startCore();
return outcome;
}
// ---------- window ----------
function createWindow() {
mainWindow = new BrowserWindow({
width: 1220,
height: 780,
minWidth: 880,
minHeight: 560,
show: false,
title: 'TeamsPeach',
backgroundColor: nativeTheme.shouldUseDarkColors ? '#1a1817' : '#f6f3f0',
icon: path.join(__dirname, '..', 'renderer', 'assets', 'icon.png'),
webPreferences: {
preload: path.join(__dirname, '..', 'preload', 'preload.js'),
contextIsolation: true,
sandbox: true,
nodeIntegration: false,
nodeIntegrationInWorker: false,
webSecurity: true,
spellcheck: false,
autoplayPolicy: 'no-user-gesture-required',
devTools: !app.isPackaged || process.env.TEAMSPEACH_DEVTOOLS === '1',
},
});
mainWindow.once('ready-to-show', () => mainWindow.show());
mainWindow.on('closed', () => {
mainWindow = null;
});
mainWindow.loadURL(`${APP_ORIGIN}/index.html`);
}
function registerProtocol() {
protocol.handle(APP_SCHEME, async (request) => {
const url = new URL(request.url);
if (url.host !== APP_HOST) return new Response('Not found', { status: 404 });
let rel;
try {
rel = decodeURIComponent(url.pathname);
} catch {
return new Response('Bad request', { status: 400 });
}
if (rel === '/' || rel === '') rel = '/index.html';
const filePath = path.normalize(path.join(RENDERER_DIR, rel));
if (!filePath.startsWith(RENDERER_DIR + path.sep)) return new Response('Forbidden', { status: 403 });
const type = MIME[path.extname(filePath).toLowerCase()];
if (!type) return new Response('Forbidden', { status: 403 });
try {
const body = await fs.promises.readFile(filePath);
return new Response(body, {
status: 200,
headers: {
'Content-Type': type,
'Content-Security-Policy': CSP,
'X-Content-Type-Options': 'nosniff',
'Cross-Origin-Opener-Policy': 'same-origin',
'Referrer-Policy': 'no-referrer',
},
});
} catch {
return new Response('Not found', { status: 404 });
}
});
}
function hardenSession() {
const ses = session.defaultSession;
ses.setPermissionRequestHandler((_wc, permission, callback, details) => {
const mediaTypes = details && Array.isArray(details.mediaTypes) ? details.mediaTypes : [];
const audioOnly = mediaTypes.length > 0 && mediaTypes.every((t) => t === 'audio');
callback(permission === 'media' && audioOnly && isAppUrl(details.requestingUrl));
});
ses.setPermissionCheckHandler((_wc, permission, requestingOrigin) => {
return (permission === 'media' || permission === 'speaker-selection') && requestingOrigin === APP_ORIGIN;
});
ses.setDisplayMediaRequestHandler((_request, callback) => callback({}));
}
app.on('web-contents-created', (_event, contents) => {
contents.on('will-navigate', (event, url) => {
if (!isAppUrl(url)) event.preventDefault();
});
contents.on('will-redirect', (event, url) => {
if (!isAppUrl(url)) event.preventDefault();
});
contents.setWindowOpenHandler(() => ({ action: 'deny' }));
contents.on('will-attach-webview', (event) => event.preventDefault());
});
// ---------- IPC ----------
function registerIpc() {
ipcMain.handle('core:request', async (event, cmd, args) => {
if (!trustedSender(event)) return { ok: false, error: { code: 'forbidden', message: 'forbidden' } };
let clean;
try {
clean = validateRequest(cmd, args);
} catch (err) {
return { ok: false, error: { code: err.code || 'bad_request', message: err.message } };
}
if (!core) return { ok: false, error: { code: 'core_unavailable', message: 'Ядро не запущено' } };
const hasArgs = Object.keys(clean).length > 0;
const response = await core.request(cmd, hasArgs ? clean : undefined);
if (!response.ok && response.error.code === 'external_media' && response.error.detail) {
const detail = response.error.detail;
allowExternalMedia(detail.url);
if (Array.isArray(detail.urls)) for (const v of detail.urls) allowExternalMedia(v && v.url);
}
return response;
});
ipcMain.on('core:audio-frame', (event, frame) => {
if (!core || !trustedSender(event)) return;
if (!(frame instanceof Uint8Array) || frame.byteLength !== 1920) return;
core.sendAudio('audio_frame', { pcm: Buffer.from(frame.buffer, frame.byteOffset, frame.byteLength).toString('base64') });
});
ipcMain.on('core:audio-end', (event) => {
if (!core || !trustedSender(event)) return;
core.sendAudio('audio_end');
});
ipcMain.handle('core:status', (event) => (trustedSender(event) ? coreStatus : null));
ipcMain.handle('core:restart', async (event) => {
if (!trustedSender(event)) return false;
await restartCore();
return true;
});
ipcMain.handle('app:info', (event) => {
if (!trustedSender(event)) return null;
return {
appVersion: app.getVersion(),
electron: process.versions.electron,
chrome: process.versions.chrome,
platform: process.platform,
arch: process.arch,
packaged: app.isPackaged,
coreVersion: core ? core.coreVersion : null,
coreBinary: coreStatus.binary || null,
dataDir: dataDir(),
logsDir: logsDir(),
};
});
ipcMain.handle('prefs:get', (event) => (trustedSender(event) ? prefs.get() : null));
ipcMain.handle('prefs:set', (event, partial) => {
if (!trustedSender(event)) return { ok: false };
try {
const next = prefs.set(partial);
if (partial && Object.prototype.hasOwnProperty.call(partial, 'theme')) nativeTheme.themeSource = next.theme;
return { ok: true, prefs: next };
} catch (err) {
return { ok: false, message: err.message };
}
});
ipcMain.handle('identity:export', (event) => (trustedSender(event) ? exportIdentity() : { ok: false }));
ipcMain.handle('identity:import', (event) => (trustedSender(event) ? importIdentity() : { ok: false }));
ipcMain.handle('media:external', (event, url) => (trustedSender(event) ? fetchExternalMedia(url) : { ok: false }));
ipcMain.handle('clipboard:write', (event, text) => {
if (!trustedSender(event) || typeof text !== 'string' || text.length > 4096) return false;
clipboard.writeText(text);
return true;
});
ipcMain.handle('app:video-status', (event) => {
if (!trustedSender(event)) return null;
return { hardwareDecodeAtLaunch: hardwareVideoDecodeAtLaunch, gpu: app.getGPUFeatureStatus() };
});
ipcMain.handle('app:relaunch', (event) => {
if (!trustedSender(event)) return false;
app.relaunch();
app.quit();
return true;
});
ipcMain.handle('app:open-logs', async (event) => {
if (!trustedSender(event)) return false;
fs.mkdirSync(logsDir(), { recursive: true });
return (await shell.openPath(logsDir())) === '';
});
ipcMain.on('app:log', (event, level, message) => {
if (!trustedSender(event) || typeof message !== 'string') return;
const now = Date.now();
if (now - rendererLogBudget.windowStart > 1000) rendererLogBudget = { windowStart: now, count: 0 };
if (++rendererLogBudget.count > 40) return;
const lvl = ['debug', 'info', 'warn', 'error'].includes(level) ? level : 'info';
if (!rendererLog) {
fs.mkdirSync(logsDir(), { recursive: true });
rendererLog = fs.createWriteStream(path.join(logsDir(), 'renderer.log'), { flags: 'a' });
}
rendererLog.write(`${new Date().toISOString()} ${lvl} ${message.slice(0, 4000).replace(/[\r\n]+/g, ' ')}\n`);
});
}
// ---------- app lifecycle ----------
app.whenReady().then(() => {
if (!gotInstanceLock) return;
Menu.setApplicationMenu(null);
prefs = new Prefs(prefsFile());
// Explicit theme choice drives Chromium's prefers-color-scheme; 'system' follows the OS.
nativeTheme.themeSource = prefs.get().theme;
registerProtocol();
hardenSession();
registerIpc();
createWindow();
startCore();
});
app.on('window-all-closed', () => app.quit());
app.on('before-quit', (event) => {
if (quitting || !core || !core.running) return;
event.preventDefault();
quitting = true;
core.stop().finally(() => app.quit());
});
-47
View File
@@ -1,47 +0,0 @@
'use strict';
const path = require('node:path');
const fs = require('node:fs');
const { app } = require('electron');
const CORE_FILE = process.platform === 'win32' ? 'teamspeach-core.exe' : 'teamspeach-core';
const APP_ROOT = path.resolve(__dirname, '..', '..');
const RENDERER_DIR = path.join(APP_ROOT, 'app', 'renderer');
/** Candidate locations of the native core. Only main decides these; nothing comes from the renderer. */
function coreCandidates() {
if (app.isPackaged) return [path.join(process.resourcesPath, 'core', CORE_FILE)];
return [
path.join(APP_ROOT, 'core', 'target', 'release', CORE_FILE),
path.join(APP_ROOT, 'core', 'target', 'debug', CORE_FILE),
];
}
/** Newest existing candidate wins in development so a fresh debug build is not shadowed by a stale release build. */
function resolveCoreBinary() {
const candidates = coreCandidates();
let best = null;
for (const candidate of candidates) {
try {
const stat = fs.statSync(candidate);
if (stat.isFile() && (!best || stat.mtimeMs > best.mtimeMs)) best = { path: candidate, mtimeMs: stat.mtimeMs };
} catch {
// missing candidate
}
}
return { path: best ? best.path : null, candidates };
}
function dataDir() {
return path.join(app.getPath('userData'), 'core');
}
function logsDir() {
return path.join(app.getPath('userData'), 'logs');
}
function prefsFile() {
return path.join(app.getPath('userData'), 'prefs.json');
}
module.exports = { APP_ROOT, RENDERER_DIR, CORE_FILE, resolveCoreBinary, dataDir, logsDir, prefsFile };
-87
View File
@@ -1,87 +0,0 @@
'use strict';
const fs = require('node:fs');
const path = require('node:path');
/**
* UI preferences owned by main (identity/nickname live in the core data dir, never here).
* Every key has a validator; unknown keys and wrong types are rejected.
*/
const SCHEMA = {
lastAddress: { default: '', check: (v) => typeof v === 'string' && v.length <= 255 && !/[\u0000-\u001f]/.test(v) },
transmitMode: { default: 'ptt', check: (v) => v === 'ptt' || v === 'open' },
pttCode: { default: 'F8', check: (v) => typeof v === 'string' && /^[A-Za-z0-9]{1,32}$/.test(v) },
inputDeviceId: { default: '', check: (v) => typeof v === 'string' && v.length <= 512 },
outputDeviceId: { default: '', check: (v) => typeof v === 'string' && v.length <= 512 },
echoCancellation: { default: true, check: (v) => typeof v === 'boolean' },
noiseSuppression: { default: true, check: (v) => typeof v === 'boolean' },
autoGainControl: { default: true, check: (v) => typeof v === 'boolean' },
voiceVolume: { default: 100, check: (v) => Number.isInteger(v) && v >= 0 && v <= 200 },
hardwareVideoDecode: { default: true, check: (v) => typeof v === 'boolean' },
streamVolume: { default: 100, check: (v) => Number.isInteger(v) && v >= 0 && v <= 100 },
theme: { default: 'system', check: (v) => v === 'system' || v === 'dark' || v === 'light' },
// Quick-access servers: name + address only. Passwords are never stored.
savedServers: { default: [], check: validServers },
};
const CONTROL = /[\u0000-\u001f\u007f]/;
function validServers(list) {
if (!Array.isArray(list) || list.length > 50) return false;
const ids = new Set();
for (const s of list) {
if (!s || typeof s !== 'object' || Array.isArray(s)) return false;
const keys = Object.keys(s);
if (keys.length !== 3 || !keys.includes('id') || !keys.includes('name') || !keys.includes('address')) return false;
if (typeof s.id !== 'string' || !/^[a-z0-9]{6,32}$/.test(s.id) || ids.has(s.id)) return false;
if (typeof s.name !== 'string' || s.name.trim().length < 1 || s.name.length > 64 || CONTROL.test(s.name)) return false;
if (typeof s.address !== 'string' || s.address.trim().length < 1 || s.address.length > 255 || CONTROL.test(s.address)) return false;
ids.add(s.id);
}
return true;
}
class Prefs {
constructor(file) {
this.file = file;
this.values = defaults();
try {
const raw = JSON.parse(fs.readFileSync(file, 'utf8'));
if (raw && typeof raw === 'object') {
for (const [key, spec] of Object.entries(SCHEMA)) {
if (Object.prototype.hasOwnProperty.call(raw, key) && spec.check(raw[key])) this.values[key] = raw[key];
}
}
} catch {
// first run or unreadable file: defaults
}
}
get() {
return { ...this.values };
}
/** Applies a validated partial update; returns the full prefs or throws. */
set(partial) {
if (!partial || typeof partial !== 'object' || Array.isArray(partial)) throw new Error('prefs: ожидался объект');
const next = { ...this.values };
for (const [key, value] of Object.entries(partial)) {
const spec = SCHEMA[key];
if (!spec) throw new Error(`prefs: неизвестный ключ ${key}`);
if (!spec.check(value)) throw new Error(`prefs: недопустимое значение ${key}`);
next[key] = value;
}
this.values = next;
fs.mkdirSync(path.dirname(this.file), { recursive: true });
const tmp = `${this.file}.tmp`;
fs.writeFileSync(tmp, JSON.stringify(next, null, 2));
fs.renameSync(tmp, this.file);
return this.get();
}
}
function defaults() {
return Object.fromEntries(Object.entries(SCHEMA).map(([key, spec]) => [key, spec.default]));
}
module.exports = { Prefs };
-33
View File
@@ -1,33 +0,0 @@
'use strict';
// Sandboxed preload: the only surface the renderer gets. No paths, no commands, no generic IPC.
const { contextBridge, ipcRenderer } = require('electron');
function subscribe(channel, callback) {
if (typeof callback !== 'function') throw new TypeError('callback must be a function');
const handler = (_event, payload) => callback(payload);
ipcRenderer.on(channel, handler);
return () => ipcRenderer.removeListener(channel, handler);
}
contextBridge.exposeInMainWorld('teamspeach', {
request: (cmd, args) => ipcRenderer.invoke('core:request', cmd, args),
sendAudioFrame: (frame) => ipcRenderer.send('core:audio-frame', frame),
endAudio: () => ipcRenderer.send('core:audio-end'),
onEvent: (callback) => subscribe('core:event', callback),
onAudio: (callback) => subscribe('core:audio', callback),
onCoreStatus: (callback) => subscribe('core:status', callback),
getCoreStatus: () => ipcRenderer.invoke('core:status'),
restartCore: () => ipcRenderer.invoke('core:restart'),
getAppInfo: () => ipcRenderer.invoke('app:info'),
getPrefs: () => ipcRenderer.invoke('prefs:get'),
setPrefs: (partial) => ipcRenderer.invoke('prefs:set', partial),
exportIdentity: () => ipcRenderer.invoke('identity:export'),
importIdentity: () => ipcRenderer.invoke('identity:import'),
copyText: (text) => ipcRenderer.invoke('clipboard:write', text),
openLogs: () => ipcRenderer.invoke('app:open-logs'),
fetchExternalMedia: (url) => ipcRenderer.invoke('media:external', url),
getVideoStatus: () => ipcRenderer.invoke('app:video-status'),
relaunch: () => ipcRenderer.invoke('app:relaunch'),
log: (level, message) => ipcRenderer.send('app:log', level, String(message)),
});
Binary file not shown.

Before

Width:  |  Height:  |  Size: 17 KiB

-370
View File
@@ -1,370 +0,0 @@
<!doctype html>
<html lang="ru">
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'self'; style-src 'self'; img-src 'self' data: blob:; media-src 'self' blob: mediastream:; font-src 'self'; connect-src 'none'; worker-src 'self'; base-uri 'none'; form-action 'none'; frame-src 'none'; object-src 'none'">
<meta name="color-scheme" content="light dark">
<title>TeamsPeach</title>
<link rel="stylesheet" href="styles/app.css">
<script type="module" src="js/app.js"></script>
</head>
<body>
<svg class="sprite" aria-hidden="true" focusable="false">
<symbol id="i-mic" viewBox="0 0 24 24"><rect x="9" y="3" width="6" height="11" rx="3"/><path d="M5.5 11a6.5 6.5 0 0 0 13 0M12 17.5V21"/></symbol>
<symbol id="i-mic-off" viewBox="0 0 24 24"><path d="M15 9.5V6a3 3 0 0 0-5.6-1.5M9 9v2a3 3 0 0 0 4.7 2.5M18.5 11a6.5 6.5 0 0 1-1 3.4M5.5 11a6.5 6.5 0 0 0 10 5.5M12 17.5V21M4 4l16 16"/></symbol>
<symbol id="i-headphones" viewBox="0 0 24 24"><path d="M4 15v-3a8 8 0 0 1 16 0v3"/><rect x="3" y="14" width="4.5" height="6.5" rx="1.6"/><rect x="16.5" y="14" width="4.5" height="6.5" rx="1.6"/></symbol>
<symbol id="i-headphones-off" viewBox="0 0 24 24"><path d="M4 15v-3a8 8 0 0 1 12.2-6.8M19.3 9A8 8 0 0 1 20 12v3"/><rect x="3" y="14" width="4.5" height="6.5" rx="1.6"/><rect x="16.5" y="14" width="4.5" height="6.5" rx="1.6"/><path d="M3.5 3.5l17 17"/></symbol>
<symbol id="i-sliders" viewBox="0 0 24 24"><path d="M4 7h9.5M18.5 7H20M4 17h3.5M12.5 17H20"/><circle cx="16" cy="7" r="2.3"/><circle cx="10" cy="17" r="2.3"/></symbol>
<symbol id="i-monitor" viewBox="0 0 24 24"><rect x="3" y="4" width="18" height="12" rx="2"/><path d="M8.5 20h7M12 16v4"/></symbol>
<symbol id="i-play" viewBox="0 0 24 24"><path d="M9 7.2v9.6l7.6-4.8z"/></symbol>
<symbol id="i-x" viewBox="0 0 24 24"><path d="M6.5 6.5l11 11M17.5 6.5l-11 11"/></symbol>
<symbol id="i-send" viewBox="0 0 24 24"><path d="M4.5 11.6L19.5 4.5l-5.2 15-2.9-6.2zM11.4 13.3l8.1-8.8"/></symbol>
<symbol id="i-copy" viewBox="0 0 24 24"><rect x="8.5" y="8.5" width="11.5" height="11.5" rx="2"/><path d="M15.5 8.5V6a2 2 0 0 0-2-2H6a2 2 0 0 0-2 2v7.5a2 2 0 0 0 2 2h2.5"/></symbol>
<symbol id="i-lock" viewBox="0 0 24 24"><rect x="5" y="11" width="14" height="9.5" rx="2"/><path d="M8.5 11V8a3.5 3.5 0 0 1 7 0v3"/></symbol>
<symbol id="i-channel" viewBox="0 0 24 24"><path d="M5 9.5h14M5 14.5h14M10.5 4.5l-2 15M15.5 4.5l-2 15"/></symbol>
<symbol id="i-logout" viewBox="0 0 24 24"><path d="M14.5 4.5h3a2 2 0 0 1 2 2v11a2 2 0 0 1-2 2h-3M10 16l4-4-4-4M14 12H4.5"/></symbol>
<symbol id="i-speaker" viewBox="0 0 24 24"><path d="M4.5 9.5v5h3.8l4.7 4V5.5l-4.7 4z"/><path d="M16.3 8.8a4.6 4.6 0 0 1 0 6.4M18.8 6.3a8.2 8.2 0 0 1 0 11.4"/></symbol>
<symbol id="i-speaker-off" viewBox="0 0 24 24"><path d="M4.5 9.5v5h3.8l4.7 4V5.5l-4.7 4z"/><path d="M16.5 9.5l5 5M21.5 9.5l-5 5"/></symbol>
<symbol id="i-fullscreen" viewBox="0 0 24 24"><path d="M4.5 9V4.5H9M15 4.5h4.5V9M19.5 15v4.5H15M9 19.5H4.5V15"/></symbol>
<symbol id="i-back" viewBox="0 0 24 24"><path d="M14.5 5.5L8 12l6.5 6.5"/></symbol>
<symbol id="i-moon" viewBox="0 0 24 24"><path d="M19.5 14.6A7.8 7.8 0 1 1 9.4 4.5a6.2 6.2 0 0 0 10.1 10.1z"/></symbol>
<symbol id="i-message" viewBox="0 0 24 24"><path d="M4.5 5.5h15v10.5h-9.5l-5.5 4z"/></symbol>
<symbol id="i-peach" viewBox="0 0 24 24"><path class="peach-body" d="M12 7.2c-4.6-1.6-8 1.6-8 6 0 4.6 3.6 8.3 8 8.3s8-3.7 8-8.3c0-4.4-3.4-7.6-8-6z"/><path class="peach-crease" d="M12 7.6c-1.8 2.6-2 8.6 0 13.6"/><path class="peach-leaf" d="M12.2 6.8c.2-2.6 2-4.2 5-4.3-.3 2.7-2.1 4.2-5 4.3z"/></symbol>
<symbol id="i-shield" viewBox="0 0 24 24"><path d="M12 3.5l7 2.6v5.4c0 4.3-2.9 7.6-7 9-4.1-1.4-7-4.7-7-9V6.1z"/></symbol>
<symbol id="i-record" viewBox="0 0 24 24"><circle cx="12" cy="12" r="6.5"/><circle cx="12" cy="12" r="2.5"/></symbol>
<symbol id="i-bookmark" viewBox="0 0 24 24"><path d="M7 4.5h10v15l-5-3.6-5 3.6z"/></symbol>
<symbol id="i-user" viewBox="0 0 24 24"><circle cx="12" cy="8.5" r="3.5"/><path d="M5 19.5c1-3.6 3.8-5.5 7-5.5s6 1.9 7 5.5"/></symbol>
<symbol id="i-palette" viewBox="0 0 24 24"><path d="M12 4a8 8 0 0 0 0 16c1.2 0 1.8-.8 1.8-1.7 0-1.3-1-1.6-1-2.6 0-1 .8-1.7 1.8-1.7H17a3 3 0 0 0 3-3C20 7.3 16.4 4 12 4z"/><circle cx="8" cy="11" r="1"/><circle cx="11" cy="7.8" r="1"/><circle cx="15" cy="8.3" r="1"/></symbol>
<symbol id="i-keyboard" viewBox="0 0 24 24"><rect x="3" y="6.5" width="18" height="11" rx="2"/><path d="M7 10h.01M10.5 10h.01M14 10h.01M17 10h.01M8 14h8"/></symbol>
<symbol id="i-info" viewBox="0 0 24 24"><circle cx="12" cy="12" r="8.5"/><path d="M12 11v5.5M12 7.8v.01"/></symbol>
</svg>
<div id="boot" class="boot" role="status">
<svg class="icon brand-mark" aria-hidden="true"><use href="#i-peach"/></svg>
<p id="boot-text">Запуск ядра…</p>
</div>
<main id="view-fatal" class="fatal" hidden>
<div class="fatal-inner">
<svg class="icon brand-mark" aria-hidden="true"><use href="#i-peach"/></svg>
<h1 id="fatal-title">Ядро недоступно</h1>
<p id="fatal-text"></p>
<ul id="fatal-list" class="fatal-list"></ul>
<div class="fatal-actions">
<button id="fatal-retry" class="btn btn-primary" type="button">Перезапустить ядро</button>
<button id="fatal-import" class="btn" type="button" hidden>Импортировать резервную копию…</button>
<button id="fatal-logs" class="btn" type="button">Открыть журналы</button>
</div>
</div>
</main>
<main id="view-onboarding" class="onboarding" hidden>
<form id="onboarding-form" class="onboarding-form" novalidate>
<svg class="icon brand-mark brand-mark-large" aria-hidden="true"><use href="#i-peach"/></svg>
<h1>Как вас называть?</h1>
<p class="lede">Никнейм видят все на сервере. Его можно сменить позже — ваш постоянный идентификатор (UID) при этом не меняется.</p>
<label class="field">
<span class="field-label">Никнейм</span>
<input id="onboarding-nick" name="nickname" type="text" autocomplete="off" spellcheck="false" maxlength="30" required aria-describedby="onboarding-hint onboarding-error">
</label>
<p id="onboarding-hint" class="hint">От 3 до 30 символов.</p>
<p id="onboarding-existing" class="hint" hidden></p>
<p id="onboarding-error" class="form-error" role="alert"></p>
<button id="onboarding-submit" class="btn btn-primary btn-wide" type="submit">Продолжить</button>
<p class="hint">TeamsPeach создаст на этом компьютере криптографическую идентичность. Регистрация не нужна.</p>
<button id="onboarding-import" class="btn btn-ghost" type="button">Восстановить из резервной копии…</button>
</form>
</main>
<div id="view-app" class="shell" hidden>
<aside class="sidebar" aria-label="Сервер">
<header class="server-head">
<div class="server-title">
<span id="server-name" class="server-name">Нет подключения</span>
<span id="conn-badge" class="conn-badge" data-state="disconnected">не подключено</span>
</div>
<button id="btn-servers" class="icon-btn" type="button" aria-expanded="false" aria-controls="servers-panel" aria-label="Сохранённые серверы" title="Сохранённые серверы">
<svg class="icon" aria-hidden="true"><use href="#i-bookmark"/></svg>
</button>
<button id="btn-disconnect" class="icon-btn" type="button" aria-label="Отключиться от сервера" title="Отключиться" hidden>
<svg class="icon" aria-hidden="true"><use href="#i-logout"/></svg>
</button>
</header>
<div id="room-side" class="room-side">
<section id="servers-panel" class="servers-panel" aria-labelledby="servers-title" hidden>
<div class="servers-head">
<h2 id="servers-title" class="servers-title">Сохранённые серверы</h2>
<button id="servers-save-current" class="btn btn-ghost btn-small" type="button" hidden>Сохранить текущий</button>
</div>
<ul id="servers-list" class="servers-list"></ul>
<p id="servers-empty" class="servers-empty">Сохранённых серверов нет. Введите адрес в форме подключения и нажмите «Сохранить».</p>
</section>
<p id="tree-empty" class="tree-empty">Каналы появятся после подключения к серверу.</p>
<img id="host-banner" class="host-banner" alt="" hidden>
<ul id="tree" class="tree" aria-label="Каналы и участники"></ul>
</div>
<nav id="settings-nav" class="settings-nav" aria-label="Разделы настроек" hidden>
<button id="settings-back" class="settings-back" type="button">
<svg class="icon" aria-hidden="true"><use href="#i-back"/></svg>Назад к серверу
</button>
<div class="settings-nav-title"><svg class="icon" aria-hidden="true"><use href="#i-sliders"/></svg>Настройки</div>
<div class="nav-group-label">Пользователь</div>
<button class="nav-item" type="button" data-panel="identity"><svg class="icon" aria-hidden="true"><use href="#i-user"/></svg>Идентичность</button>
<button class="nav-item" type="button" data-panel="servers"><svg class="icon" aria-hidden="true"><use href="#i-bookmark"/></svg>Серверы</button>
<div class="nav-group-label">Приложение</div>
<button class="nav-item" type="button" data-panel="appearance"><svg class="icon" aria-hidden="true"><use href="#i-palette"/></svg>Внешний вид</button>
<button class="nav-item" type="button" data-panel="audio"><svg class="icon" aria-hidden="true"><use href="#i-speaker"/></svg>Звук</button>
<button class="nav-item" type="button" data-panel="video"><svg class="icon" aria-hidden="true"><use href="#i-monitor"/></svg>Видео</button>
<button class="nav-item" type="button" data-panel="keys"><svg class="icon" aria-hidden="true"><use href="#i-keyboard"/></svg>Клавиши</button>
<div class="nav-group-label">Информация</div>
<button class="nav-item" type="button" data-panel="about"><svg class="icon" aria-hidden="true"><use href="#i-info"/></svg>Информация</button>
</nav>
<footer class="self">
<div class="self-id">
<span id="self-dot" class="status-dot" aria-hidden="true"></span>
<div class="self-text">
<div id="self-nick" class="self-nick"></div>
<div id="self-sub" class="self-sub"></div>
</div>
</div>
<div class="self-actions">
<button id="btn-mute" class="icon-btn" type="button" aria-pressed="false" aria-label="Микрофон" title="Выключить микрофон">
<svg class="icon" aria-hidden="true"><use href="#i-mic"/></svg>
</button>
<button id="btn-deafen" class="icon-btn" type="button" aria-pressed="false" aria-label="Звук" title="Выключить звук">
<svg class="icon" aria-hidden="true"><use href="#i-headphones"/></svg>
</button>
<button id="btn-settings" class="icon-btn" type="button" aria-label="Настройки" title="Настройки">
<svg class="icon" aria-hidden="true"><use href="#i-sliders"/></svg>
</button>
</div>
</footer>
</aside>
<main class="workspace">
<section id="connect-view" class="connect-view" aria-labelledby="connect-title">
<form id="connect-form" class="connect-form" novalidate>
<h1 id="connect-title">Подключение к серверу</h1>
<p id="connect-identity" class="lede"></p>
<label class="field">
<span class="field-label">Адрес сервера</span>
<input id="connect-address" name="address" type="text" autocomplete="off" spellcheck="false" placeholder="адрес или адрес:9987" required>
</label>
<label class="field">
<span class="field-label">Пароль сервера <span class="optional">необязательно</span></span>
<input id="connect-password" name="password" type="password" autocomplete="off">
</label>
<p id="connect-error" class="form-error" role="alert"></p>
<div class="form-actions">
<button id="connect-submit" class="btn btn-primary" type="submit">Подключиться</button>
<button id="connect-save" class="btn" type="button">Сохранить</button>
<span id="connect-status" class="form-status" role="status"></span>
</div>
</form>
</section>
<section id="session-view" class="session-view" hidden>
<header class="session-head">
<div class="session-title">
<h1 id="channel-title"></h1>
<p id="channel-topic" class="channel-topic"></p>
</div>
<div class="transmit">
<span id="transmit-hint" class="transmit-hint"></span>
<button id="btn-ptt" class="btn btn-ptt" type="button" aria-pressed="false">Удерживайте, чтобы говорить</button>
</div>
</header>
<p id="session-notice" class="notice" role="status" hidden></p>
<section id="stream-view" class="stream-view" aria-label="Трансляция" hidden>
<div class="stream-stage">
<video id="stream-video" autoplay playsinline></video>
<div id="stream-overlay" class="stream-overlay" role="status"></div>
</div>
<div class="stream-bar">
<div class="stream-meta">
<strong id="stream-title" class="stream-title"></strong>
<span id="stream-stats" class="stream-stats"></span>
</div>
<div class="stream-controls">
<button id="stream-mute" class="icon-btn" type="button" aria-pressed="false" aria-label="Звук трансляции" title="Выключить звук трансляции">
<svg class="icon" aria-hidden="true"><use href="#i-speaker"/></svg>
</button>
<input id="stream-volume" class="range" type="range" min="0" max="100" step="1" aria-label="Громкость трансляции">
<output id="stream-volume-value" class="range-value" for="stream-volume"></output>
<button id="stream-fullscreen" class="icon-btn" type="button" aria-label="Во весь экран" title="Во весь экран">
<svg class="icon" aria-hidden="true"><use href="#i-fullscreen"/></svg>
</button>
<button id="stream-stop" class="btn" type="button">Прекратить просмотр</button>
</div>
</div>
</section>
<section class="chat" aria-label="Чат">
<div id="chat-tabs" class="chat-tabs" role="tablist" aria-label="Чаты"></div>
<ol id="chat-log" class="chat-log" role="log" aria-live="polite" aria-relevant="additions" tabindex="0"></ol>
<form id="chat-form" class="composer" novalidate>
<textarea id="chat-input" rows="1" aria-label="Сообщение" placeholder="Сообщение"></textarea>
<button id="chat-send" class="icon-btn icon-btn-accent" type="submit" aria-label="Отправить" title="Отправить (Enter)">
<svg class="icon" aria-hidden="true"><use href="#i-send"/></svg>
</button>
</form>
</section>
</section>
<section id="settings-view" class="settings-view" hidden aria-label="Настройки">
<div class="settings-scroll">
<div class="settings-panel" data-panel="identity" hidden>
<h1 id="settings-title" class="panel-title">Идентичность</h1>
<section class="card" aria-labelledby="card-identity">
<h2 id="card-identity" class="card-title">Идентичность</h2>
<div class="card-row">
<span class="row-name">Уникальный идентификатор</span>
<code id="uid-value" class="uid-value"></code>
<button id="uid-copy" class="btn btn-ghost btn-small" type="button"><svg class="icon" aria-hidden="true"><use href="#i-copy"/></svg>Копировать</button>
</div>
<p class="hint">UID — отпечаток вашего открытого ключа. Серверы TeamSpeak по нему узнают вас и выдают права; смена ника его не меняет.</p>
<p id="security-level" class="hint"></p>
<div class="card-divider"></div>
<div class="form-actions">
<button id="identity-export" class="btn" type="button">Экспортировать в файл…</button>
<button id="identity-import" class="btn" type="button">Импортировать из файла…</button>
</div>
<p class="hint">Файл содержит закрытый ключ. Храните его как пароль: тот, у кого он есть, может выдавать себя за вас.</p>
<p id="identity-status" class="form-status" role="status"></p>
</section>
<section class="card" aria-labelledby="card-details">
<h2 id="card-details" class="card-title">Подробнее</h2>
<form id="rename-form" class="inline-form" novalidate>
<label class="inline-label" for="rename-input">Ник</label>
<input id="rename-input" type="text" autocomplete="off" spellcheck="false" maxlength="30">
<button id="rename-submit" class="btn btn-primary btn-small" type="submit">Сохранить</button>
</form>
<p class="hint">Ваш ник видят другие пользователи на сервере TeamSpeak. От 3 до 30 символов.</p>
<p id="rename-status" class="form-status" role="status"></p>
</section>
</div>
<div class="settings-panel" data-panel="servers" hidden>
<h1 class="panel-title">Серверы</h1>
<section class="card" aria-labelledby="card-saved">
<h2 id="card-saved" class="card-title">Сохранённые серверы</h2>
<ul id="servers-manage" class="servers-list servers-manage"></ul>
<p id="servers-manage-empty" class="hint">Сохранённых серверов нет.</p>
</section>
<section class="card" aria-labelledby="card-add-server">
<h2 id="card-add-server" class="card-title">Добавить сервер</h2>
<form id="server-add-form" class="stack-form" novalidate>
<label class="field"><span class="field-label">Название</span><input id="server-add-name" type="text" maxlength="64" autocomplete="off"></label>
<label class="field"><span class="field-label">Адрес</span><input id="server-add-address" type="text" maxlength="255" autocomplete="off" spellcheck="false" placeholder="адрес или адрес:9987"></label>
<div class="form-actions"><button class="btn btn-primary btn-small" type="submit">Добавить</button><span id="server-add-status" class="form-status" role="status"></span></div>
</form>
<p class="hint">Сохраняются только название и адрес. Пароль сервера не сохраняется — его спросят при подключении. Для всех серверов используется одна и та же ваша идентичность.</p>
</section>
</div>
<div class="settings-panel" data-panel="appearance" hidden>
<h1 class="panel-title">Внешний вид</h1>
<section class="card" aria-labelledby="card-theme">
<h2 id="card-theme" class="card-title">Тема</h2>
<fieldset class="fieldset">
<legend class="visually-hidden">Тема оформления</legend>
<label class="choice"><input type="radio" name="theme" value="system"> Как в системе</label>
<label class="choice"><input type="radio" name="theme" value="dark"> Тёмная</label>
<label class="choice"><input type="radio" name="theme" value="light"> Светлая</label>
</fieldset>
</section>
</div>
<div class="settings-panel" data-panel="audio" hidden>
<h1 class="panel-title">Звук</h1>
<section class="card" aria-labelledby="card-devices">
<h2 id="card-devices" class="card-title">Устройства</h2>
<label class="field"><span class="field-label">Микрофон</span><select id="input-device"></select></label>
<div class="meter-row">
<div class="meter" aria-hidden="true"><div id="mic-meter" class="meter-fill"></div></div>
<button id="mic-test" class="btn btn-ghost btn-small" type="button" aria-pressed="false">Проверить микрофон</button>
</div>
<label class="field"><span class="field-label">Устройство вывода</span><select id="output-device"></select></label>
</section>
<section class="card" aria-labelledby="card-volume">
<h2 id="card-volume" class="card-title">Громкость</h2>
<label class="field"><span class="field-label">Громкость голосов <output id="voice-volume-value" for="voice-volume"></output></span>
<input id="voice-volume" class="range" type="range" min="0" max="200" step="5"></label>
</section>
<section class="card" aria-labelledby="card-processing">
<h2 id="card-processing" class="card-title">Обработка микрофона</h2>
<fieldset class="fieldset">
<legend class="visually-hidden">Обработка микрофона</legend>
<label class="choice"><input id="opt-ns" type="checkbox"> Шумоподавление</label>
<label class="choice"><input id="opt-ec" type="checkbox"> Эхоподавление</label>
<label class="choice"><input id="opt-agc" type="checkbox"> Автоматическая громкость</label>
</fieldset>
</section>
</div>
<div class="settings-panel" data-panel="video" hidden>
<h1 class="panel-title">Видео</h1>
<section class="card" aria-labelledby="card-decode">
<h2 id="card-decode" class="card-title">Аппаратное ускорение</h2>
<label class="choice"><input id="opt-hwdec" type="checkbox"> Разрешить аппаратное декодирование видео</label>
<p class="hint">Движок может использовать видеокарту для декодирования трансляций. Применяется после перезапуска.</p>
<div id="hwdec-restart" class="form-actions" hidden>
<span class="form-status">Изменение вступит в силу после перезапуска TeamsPeach.</span>
<button id="hwdec-relaunch" class="btn btn-small" type="button">Перезапустить сейчас</button>
</div>
<div class="card-divider"></div>
<div class="card-row">
<span class="row-name">Бэкенд декодирования</span>
<span class="row-value">Автоматически (выбирает Chromium)</span>
</div>
<details class="card-details">
<summary>Подробности: состояние, кодеки и бэкенды</summary>
<dl class="diag-list">
<dt>Политика</dt><dd id="hwdec-status"></dd>
<dt>Текущий приём</dt><dd id="decoder-last"></dd>
</dl>
<h3 class="details-title">Кодеки приёма, объявленные движком</h3>
<ul id="codec-list" class="codec-list"></ul>
<h3 class="details-title">Недоступные настройки</h3>
<p class="hint">Переключателя Cisco OpenH264 и ручного выбора аппаратных бэкендов (NVENC, AMF, QSV и др.), как в TeamSpeak 6, здесь нет: TeamsPeach принимает видео через WebRTC движка Chromium, у которого нет API выбора декодера. H.264 Chromium декодирует через FFmpeg — OpenH264 в нём служит только кодировщиком, а кодирование (отправка своего экрана) в TeamsPeach не реализовано.</p>
</details>
</section>
</div>
<div class="settings-panel" data-panel="keys" hidden>
<h1 class="panel-title">Клавиши</h1>
<section class="card" aria-labelledby="card-transmit">
<h2 id="card-transmit" class="card-title">Передача голоса</h2>
<fieldset class="fieldset">
<legend class="visually-hidden">Режим передачи</legend>
<label class="choice"><input type="radio" name="transmit" value="ptt"> Нажми и говори</label>
<label class="choice"><input type="radio" name="transmit" value="open"> Открытый микрофон</label>
</fieldset>
<div class="card-divider"></div>
<div class="ptt-row">
<span class="row-name">Клавиша «нажми и говори»</span>
<kbd id="ptt-key" class="kbd"></kbd>
<button id="ptt-assign" class="btn btn-ghost btn-small" type="button">Назначить</button>
</div>
<p id="ptt-hint" class="hint">Клавиша работает, пока окно TeamsPeach активно. Буквенные клавиши не срабатывают во время набора текста. Esc отменяет назначение.</p>
</section>
</div>
<div class="settings-panel" data-panel="about" hidden>
<h1 class="panel-title">Информация</h1>
<section class="card" aria-labelledby="card-about">
<h2 id="card-about" class="card-title">О программе</h2>
<dl id="diag-list" class="diag-list"></dl>
<div class="card-divider"></div>
<div class="form-actions"><button id="open-logs" class="btn btn-small" type="button">Открыть журналы</button></div>
</section>
</div>
</div>
</section>
</main>
</div>
<div id="toasts" class="toasts" aria-live="polite" aria-atomic="false"></div>
</body>
</html>
-522
View File
@@ -1,522 +0,0 @@
// TeamsPeach renderer entry: core lifecycle, onboarding, connection, self controls and view routing.
import { $, h, setIcon, setText } from './dom.js';
import { S, emit, isConnected, ownChannel } from './state.js';
import { tp, call, log } from './core.js';
import { errorText, shortUid, stripBBCode } from './text.js';
import { toast } from './toast.js';
import { initTree, renderTree, updateTalking } from './tree.js';
import * as chat from './chat.js';
import * as watch from './watch.js';
import * as voice from './voice.js';
import * as settings from './settings.js';
import { serverBannerUrl, clearMedia } from './media.js';
import * as servers from './servers.js';
let hostBannerKey = null;
/** The server's host banner (hostbanner_gfx_url) above the tree; hidden when the server has none. */
function renderHostBanner() {
const img = $('#host-banner');
const server = S.snap?.server;
const key = server?.hostbanner_gfx_url ?? null;
if (key === hostBannerKey) return;
hostBannerKey = key;
img.hidden = true;
img.removeAttribute('src');
if (!key) return;
serverBannerUrl(server).then((url) => {
if (!url || hostBannerKey !== key) return;
img.src = url;
img.alt = server.hostbanner_url ? `Баннер сервера (${server.hostbanner_url})` : 'Баннер сервера';
img.hidden = false;
});
}
const VIEWS = ['#boot', '#view-fatal', '#view-onboarding', '#view-app'];
let welcomeShown = false;
let lastOwnChannel = null;
let lastAsyncError = { code: '', at: 0 };
function showView(id) {
for (const v of VIEWS) $(v).hidden = v !== id;
}
// ---------- prefs ----------
async function savePrefs(partial) {
const r = await tp.setPrefs(partial);
if (r && r.ok) S.prefs = r.prefs;
else toast(`Настройка не сохранена: ${r?.message ?? 'ошибка'}`, 'error');
renderSessionHead();
servers.renderServers();
return S.prefs;
}
// ---------- core lifecycle ----------
function onCoreStatus(status) {
S.core = status;
switch (status.status) {
case 'starting':
setText($('#boot-text'), 'Запуск ядра…');
showView('#boot');
break;
case 'stopped':
setText($('#boot-text'), 'Перезапуск ядра…');
showView('#boot');
resetConnection(null);
break;
case 'ready':
loadProfile();
break;
case 'missing':
showFatal('Ядро TeamsPeach не найдено', 'Исполняемый файл ядра отсутствует. Соберите его (см. README) или переустановите приложение. Проверенные пути:', status.candidates ?? []);
break;
default:
resetConnection(null);
showFatal('Ядро остановилось', status.message || `Код завершения ${status.code}`, []);
}
}
function showFatal(title, text, list, { allowImport = false } = {}) {
setText($('#fatal-title'), title);
setText($('#fatal-text'), text);
$('#fatal-list').replaceChildren(...list.map((item) => h('li', { text: item })));
$('#fatal-import').hidden = !allowImport;
$('#fatal-retry').hidden = S.core.status === 'missing';
showView('#view-fatal');
}
async function loadProfile() {
try {
S.profile = await call('profile_get');
} catch (err) {
if (err.code === 'identity_corrupt' || err.code === 'profile_corrupt') {
showFatal('Профиль повреждён', `${errorText(err)} TeamsPeach никогда не создаёт новую идентичность поверх повреждённой.`, [], { allowImport: true });
} else {
showFatal('Не удалось прочитать профиль', errorText(err), []);
}
return;
}
if (!S.profile.exists || !S.profile.nickname) showOnboarding();
else showApp();
}
// ---------- onboarding ----------
function showOnboarding() {
const existing = $('#onboarding-existing');
existing.hidden = !S.profile.exists;
setText(existing, S.profile.exists ? `Идентичность уже есть (UID ${S.profile.uid}). Осталось выбрать никнейм.` : '');
showView('#view-onboarding');
$('#onboarding-nick').focus();
}
async function submitOnboarding(e) {
e.preventDefault();
const input = $('#onboarding-nick');
const error = $('#onboarding-error');
const nickname = input.value.trim();
const len = [...nickname].length;
if (len < 3 || len > 30) {
input.setAttribute('aria-invalid', 'true');
setText(error, 'Никнейм должен содержать от 3 до 30 символов.');
input.focus();
return;
}
input.removeAttribute('aria-invalid');
setText(error, '');
const submit = $('#onboarding-submit');
submit.disabled = true;
setText(submit, 'Создаём идентичность…');
try {
S.profile = S.profile.exists ? await call('rename', { nickname }) : await call('profile_create', { nickname });
showApp();
toast(`Профиль создан. Ваш UID: ${S.profile.uid}`);
} catch (err) {
setText(error, errorText(err));
} finally {
submit.disabled = false;
setText(submit, 'Продолжить');
}
}
// ---------- main shell ----------
function showApp() {
showView('#view-app');
voice.startAudio();
renderAll();
if (S.view === 'main' && !isConnected()) $('#connect-address').focus();
}
function renderAll() {
renderConnection();
renderTree();
renderSelf();
renderSessionHead();
chat.renderTabs();
chat.renderLog();
settings.renderProfile();
}
function renderConnection() {
const state = S.conn.state;
const badge = $('#conn-badge');
badge.dataset.state = state;
const labels = { connecting: 'подключение…', connected: 'подключено', disconnecting: 'отключение…', disconnected: 'не подключено' };
setText(badge, labels[state] ?? state);
setText($('#server-name'), isConnected() ? S.snap.server.name || S.conn.address : S.conn.address && state !== 'disconnected' ? S.conn.address : 'Нет подключения');
$('#btn-disconnect').hidden = state === 'disconnected';
const inSettings = S.view === 'settings';
$('#settings-view').hidden = !inSettings;
$('#settings-nav').hidden = !inSettings;
$('#room-side').hidden = inSettings;
$('#connect-view').hidden = inSettings || isConnected();
$('#session-view').hidden = inSettings || !isConnected();
servers.renderServers();
const busy = state === 'connecting' || state === 'disconnecting';
$('#connect-submit').disabled = busy;
setText($('#connect-status'), state === 'connecting' ? 'Подключение…' : '');
setText($('#connect-identity'), S.profile ? `Вы войдёте как ${S.profile.nickname} · UID ${shortUid(S.profile.uid)}` : '');
if (!$('#connect-address').value && S.prefs.lastAddress) $('#connect-address').value = S.prefs.lastAddress;
}
function renderSelf() {
const p = S.profile;
if (!p) return;
setText($('#self-nick'), p.nickname ?? '');
const ch = ownChannel();
setText($('#self-sub'), isConnected() && ch ? ch.name : `UID ${shortUid(p.uid)}`);
$('#self-sub').title = `UID ${p.uid}`;
$('#self-dot').dataset.talking = String(Boolean(S.audio.transmitting));
const mute = $('#btn-mute');
mute.setAttribute('aria-pressed', String(S.audio.input_muted));
setIcon(mute.firstElementChild, S.audio.input_muted ? 'mic-off' : 'mic');
mute.title = S.audio.input_muted ? 'Включить микрофон' : 'Выключить микрофон';
mute.setAttribute('aria-label', S.audio.input_muted ? 'Микрофон выключен' : 'Микрофон включён');
const deafen = $('#btn-deafen');
deafen.setAttribute('aria-pressed', String(S.audio.output_muted));
setIcon(deafen.firstElementChild, S.audio.output_muted ? 'headphones-off' : 'headphones');
deafen.title = S.audio.output_muted ? 'Включить звук' : 'Выключить звук (и микрофон)';
deafen.setAttribute('aria-label', S.audio.output_muted ? 'Звук выключен' : 'Звук включён');
}
function renderSessionHead() {
if (!S.prefs) return;
const ch = ownChannel();
setText($('#channel-title'), ch ? ch.name : '');
setText($('#channel-topic'), ch ? stripBBCode(ch.topic) : '');
const ptt = S.prefs.transmitMode === 'ptt';
$('#btn-ptt').hidden = !ptt;
setText($('#transmit-hint'), voice.transmitHint());
const notice = $('#session-notice');
const codec = voice.channelCodecProblem();
let text = '';
if (codec) text = `Канал использует устаревший кодек (${codec}). TeamsPeach передаёт и принимает только Opus — говорить здесь не получится.`;
else if (S.audio.output_muted) text = 'Звук выключен: вы не слышите других и не передаёте голос.';
else if (S.audio.input_muted) text = 'Микрофон выключен.';
notice.hidden = !text;
setText(notice, text);
}
// ---------- connection ----------
function submitConnect(e) {
e.preventDefault();
connectTo($('#connect-address').value.trim(), { password: $('#connect-password').value });
}
function isPasswordError(err) {
const ts = err.ts_error;
return Boolean(ts && (ts.id === 1028 || /password/i.test(`${ts.name ?? ''} ${ts.message ?? ''}`)));
}
/**
* Connects to `address`. When another server is active, the user chose "Переключиться": the current
* session is closed cleanly first, so there is never more than one connection.
*/
async function connectTo(address, { password = '', switching = false } = {}) {
const error = $('#connect-error');
setText(error, '');
if (!address) {
setText(error, 'Укажите адрес сервера.');
$('#connect-address').focus();
return;
}
$('#connect-address').value = address;
if (S.conn.state !== 'disconnected') {
if (!switching) return;
await disconnect();
const deadline = Date.now() + 10000;
while (S.conn.state !== 'disconnected' && Date.now() < deadline) await new Promise((r) => setTimeout(r, 100));
if (S.conn.state !== 'disconnected') {
toast('Не удалось отключиться от текущего сервера', 'error');
return;
}
}
const args = { address };
if (password) args.server_password = password;
S.conn = { state: 'connecting', address, reason: null };
renderConnection();
renderTree();
try {
await call('connect', args);
await savePrefs({ lastAddress: address });
$('#connect-password').value = '';
} catch (err) {
if (err.code !== 'already_connected') {
setText(error, isPasswordError(err) ? `${errorText(err)}. Введите пароль сервера и подключитесь снова.` : errorText(err));
if (S.conn.state === 'connecting') S.conn = { state: 'disconnected', address, reason: null };
renderConnection();
renderTree();
if (isPasswordError(err)) $('#connect-password').focus();
}
}
}
async function disconnect() {
try {
await call('disconnect', {});
} catch (err) {
if (err.code !== 'not_connected') toast(`Отключение: ${errorText(err)}`, 'error');
}
}
function resetConnection(reason) {
const wasConnected = S.snap !== null;
S.conn = { state: 'disconnected', address: S.conn.address, reason };
S.snap = null;
S.talking.clear();
S.audio.transmitting = false;
welcomeShown = false;
lastOwnChannel = null;
watch.onDisconnected();
clearMedia();
hostBannerKey = null;
$('#host-banner').hidden = true;
voice.setPtt(false);
voice.syncCapture();
if (wasConnected) {
chat.addSystem('channel', reason ? `Отключено: ${errorText(reason)}` : 'Отключено от сервера');
}
if (reason) setText($('#connect-error'), errorText(reason));
}
function onStateEvent(evt) {
const prev = S.conn.state;
if (evt.state === 'disconnected') {
resetConnection(evt.reason ?? null);
} else {
S.conn = { state: evt.state, address: evt.address ?? S.conn.address, reason: null };
if (evt.state === 'connecting' && prev === 'connected') chat.addSystem('channel', 'Связь потеряна, переподключение…');
if (evt.state === 'connected') {
setText($('#connect-error'), '');
voice.syncCapture();
}
}
log('info', `state ${prev} → ${evt.state}`);
renderAll();
}
function onSnapshot(snap) {
S.snap = snap;
if (S.conn.state !== 'connected' && S.conn.state !== 'disconnecting') S.conn.state = 'connected';
const present = new Set(snap.clients.map((c) => c.id));
for (const id of Array.from(S.talking)) if (!present.has(id)) S.talking.delete(id);
if (!welcomeShown) {
welcomeShown = true;
chat.addSystem('server', `Подключено к «${snap.server.name}»${snap.server.version ? ` (${snap.server.version})` : ''}`);
const welcome = stripBBCode(snap.server.welcome_message).trim();
if (welcome) chat.addSystem('server', welcome);
}
if (snap.own_channel_id !== lastOwnChannel) {
lastOwnChannel = snap.own_channel_id;
const ch = ownChannel();
if (ch) chat.addSystem('channel', `Вы в канале «${ch.name}»`);
}
watch.onSnapshot();
renderHostBanner();
renderConnection();
renderTree();
renderSelf();
renderSessionHead();
chat.renderTabs();
}
function onAsyncError(error) {
const code = error?.code;
log('warn', `core error ${code}: ${error?.message ?? ''}`);
if (code === 'audio_muted' || code === 'not_connected') return;
const now = Date.now();
if (lastAsyncError.code === code && now - lastAsyncError.at < 5000) return;
lastAsyncError = { code, at: now };
if (code === 'audio_codec_unsupported') {
renderSessionHead();
return;
}
toast(errorText(error), 'error');
}
function onCoreEvent(evt) {
switch (evt.event) {
case 'state':
onStateEvent(evt);
break;
case 'snapshot':
onSnapshot(evt);
break;
case 'audio_state': {
const wasDeaf = S.audio.output_muted;
S.audio = { input_muted: Boolean(evt.input_muted), output_muted: Boolean(evt.output_muted), transmitting: Boolean(evt.transmitting) };
if (S.audio.output_muted && !wasDeaf) voice.onOutputMuted(true);
watch.applyVolume();
renderSelf();
renderSessionHead();
const self = S.snap?.own_client_id;
if (self !== undefined) updateTalking(self);
break;
}
case 'talking':
if (evt.talking) S.talking.add(evt.client_id);
else S.talking.delete(evt.client_id);
updateTalking(evt.client_id);
break;
case 'text':
chat.onText(evt);
break;
case 'stream':
watch.onStreamEvent(evt);
break;
case 'profile':
S.profile = { exists: evt.exists, uid: evt.uid, nickname: evt.nickname, security_level: evt.security_level };
renderSelf();
renderConnection();
settings.renderProfile();
break;
case 'error':
onAsyncError(evt.error);
break;
default:
break;
}
emit(evt.event, evt);
}
// ---------- self controls ----------
async function toggleAudio(key) {
try {
const result = await call('set_audio', { [key]: !S.audio[key] });
S.audio = { ...S.audio, input_muted: result.input_muted, output_muted: result.output_muted, transmitting: result.transmitting ?? S.audio.transmitting };
if (S.audio.output_muted) voice.onOutputMuted(true);
watch.applyVolume();
renderSelf();
renderSessionHead();
} catch (err) {
toast(errorText(err), 'error');
}
}
function openSettings(panel) {
S.view = 'settings';
renderConnection();
settings.open(panel);
}
async function closeSettings() {
await settings.close();
S.view = 'main';
renderConnection();
chat.renderLog();
(isConnected() ? $('#chat-input') : $('#connect-address')).focus();
}
// ---------- diagnostics for automated smoke runs (read-only) ----------
Object.defineProperty(window, 'teamspeachDiagnostics', {
value: Object.freeze({
snapshot: () => ({
core: S.core.status,
profile: S.profile ? { uid: S.profile.uid, nickname: S.profile.nickname } : null,
conn: S.conn.state,
server: S.snap?.server?.name ?? null,
ownClientId: S.snap?.own_client_id ?? null,
ownChannel: ownChannel()?.name ?? null,
clients: S.snap ? S.snap.clients.map((c) => ({ id: c.id, nickname: c.nickname, channel: c.channel_id, type: c.client_type, inputMuted: c.input_muted })) : [],
talking: Array.from(S.talking),
audio: { ...S.audio },
voice: { ...voice.voiceStats, sending: voice.isSending() },
streams: Array.from(watch.directory.streams.values()).map((s) => ({ id: s.id, clientId: s.clientId, name: s.name })),
watch: { ...watch.watchStats },
videoCodecs: settings.videoCodecs(),
}),
playback: () => voice.playbackStats(),
}),
});
// ---------- boot ----------
async function boot() {
S.prefs = await tp.getPrefs();
$('#stream-volume').value = String(S.prefs.streamVolume);
initTree({
openPrivate: (id) => chat.openPrivate(id),
openSettings,
toggleWatch: (s) => watch.toggleWatch(s),
streamOf: (id) => watch.streamOf(id),
watchingId: () => watch.watchingId(),
});
chat.initChat();
servers.initServers({ savePrefs, connectTo });
watch.initWatch({ onChange: () => renderTree(), savePrefs });
voice.initVoice({
onPtt: () => renderSessionHead(),
onTransmitChanged: () => {},
});
settings.initSettings({
savePrefs,
close: closeSettings,
onProfile: (p) => {
S.profile = p;
renderSelf();
renderConnection();
settings.renderProfile();
renderTree();
},
});
$('#onboarding-form').addEventListener('submit', submitOnboarding);
$('#onboarding-import').addEventListener('click', async () => {
const r = await tp.importIdentity();
if (r.ok) toast(`Идентичность восстановлена. UID ${r.uid}`);
else if (!r.canceled) setText($('#onboarding-error'), `Восстановление не удалось: ${errorText(r.error)}`);
});
$('#connect-form').addEventListener('submit', submitConnect);
$('#btn-disconnect').addEventListener('click', disconnect);
$('#btn-mute').addEventListener('click', () => toggleAudio('input_muted'));
$('#btn-deafen').addEventListener('click', () => toggleAudio('output_muted'));
$('#btn-settings').addEventListener('click', () => (S.view === 'settings' ? closeSettings() : openSettings()));
$('#fatal-retry').addEventListener('click', () => tp.restartCore());
$('#fatal-import').addEventListener('click', async () => {
const r = await tp.importIdentity();
if (!r.ok && !r.canceled) toast(`Импорт не удался: ${errorText(r.error)}`, 'error');
});
$('#fatal-logs').addEventListener('click', () => tp.openLogs());
tp.onEvent(onCoreEvent);
tp.onCoreStatus(onCoreStatus);
const status = await tp.getCoreStatus();
if (status) onCoreStatus(status);
}
boot().catch((err) => {
log('error', `boot failed: ${err.stack || err.message}`);
showFatal('Ошибка запуска интерфейса', String(err.message || err), []);
});
-42
View File
@@ -1,42 +0,0 @@
// Microphone → 20 ms frames of 960 signed 16-bit mono samples at 48 kHz (bridge §4.9).
const FRAME = 960;
class CaptureProcessor extends AudioWorkletProcessor {
constructor() {
super();
this.frame = new Int16Array(FRAME);
this.pos = 0;
this.sumSq = 0;
this.peak = 0;
if (sampleRate !== 48000) this.port.postMessage({ type: 'error', message: `sample rate ${sampleRate}` });
}
process(inputs, outputs) {
const input = inputs[0];
const out = outputs[0] && outputs[0][0];
if (out) out.fill(0);
if (!input || input.length === 0) return true;
const ch = input[0];
for (let i = 0; i < ch.length; i += 1) {
let s = ch[i];
if (s > 1) s = 1;
else if (s < -1) s = -1;
this.frame[this.pos] = s < 0 ? Math.round(s * 0x8000) : Math.round(s * 0x7fff);
this.pos += 1;
this.sumSq += s * s;
const a = s < 0 ? -s : s;
if (a > this.peak) this.peak = a;
if (this.pos === FRAME) {
const pcm = this.frame.buffer;
this.port.postMessage({ type: 'frame', pcm, rms: Math.sqrt(this.sumSq / FRAME), peak: this.peak }, [pcm]);
this.frame = new Int16Array(FRAME);
this.pos = 0;
this.sumSq = 0;
this.peak = 0;
}
}
return true;
}
}
registerProcessor('tp-capture', CaptureProcessor);
-145
View File
@@ -1,145 +0,0 @@
// Web Audio side of voice: one 48 kHz AudioContext, a capture worklet producing bridge-format
// frames and a playback worklet with a bounded ring buffer.
export class AudioEngine {
constructor({ onFrame, onError, log }) {
this.onFrame = onFrame;
this.onError = onError ?? (() => {});
this.log = log ?? (() => {});
this.ctx = null;
this.playback = null;
this.voiceGain = null;
this.capture = null;
this.ready = null;
this.stats = { framesOut: 0 };
this.statsWaiters = [];
}
init() {
if (!this.ready) this.ready = this._init();
return this.ready;
}
async _init() {
const ctx = new AudioContext({ sampleRate: 48000, latencyHint: 'interactive' });
this.ctx = ctx;
await ctx.audioWorklet.addModule(new URL('./capture-worklet.js', import.meta.url));
await ctx.audioWorklet.addModule(new URL('./playback-worklet.js', import.meta.url));
this.playback = new AudioWorkletNode(ctx, 'tp-playback', {
numberOfInputs: 0,
numberOfOutputs: 1,
outputChannelCount: [1],
});
this.playback.port.onmessage = (event) => {
if (event.data && event.data.type === 'stats') {
const waiters = this.statsWaiters.splice(0);
for (const resolve of waiters) resolve(event.data);
}
};
this.voiceGain = ctx.createGain();
this.playback.connect(this.voiceGain).connect(ctx.destination);
if (ctx.state !== 'running') await ctx.resume();
this.log('info', `audio: context ${ctx.sampleRate} Hz, baseLatency ${Math.round((ctx.baseLatency || 0) * 1000)} ms`);
}
setVoiceVolume(percent) {
if (this.voiceGain) this.voiceGain.gain.setTargetAtTime(percent / 100, this.ctx.currentTime, 0.02);
}
async setOutputDevice(deviceId) {
await this.init();
if (typeof this.ctx.setSinkId !== 'function') throw new Error('Выбор устройства вывода не поддерживается');
await this.ctx.setSinkId(deviceId || '');
}
/** Copies the 1920-byte frame into the worklet (transfer). */
pushPlayback(bytes) {
if (!this.playback) return;
const copy = bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);
this.playback.port.postMessage(copy, [copy]);
this.stats.framesOut += 1;
}
flushPlayback() {
if (this.playback) this.playback.port.postMessage({ type: 'flush' });
}
playbackStats() {
if (!this.playback) return Promise.resolve(null);
return new Promise((resolve) => {
this.statsWaiters.push(resolve);
this.playback.port.postMessage({ type: 'stats' });
});
}
get capturing() {
return this.capture !== null;
}
async startCapture({ deviceId, echoCancellation, noiseSuppression, autoGainControl }) {
await this.init();
this.stopCapture();
const audio = {
channelCount: 1,
echoCancellation,
noiseSuppression,
autoGainControl,
};
if (deviceId) audio.deviceId = { exact: deviceId };
let stream;
try {
stream = await navigator.mediaDevices.getUserMedia({ audio, video: false });
} catch (err) {
if (deviceId && err && err.name === 'OverconstrainedError') {
delete audio.deviceId;
stream = await navigator.mediaDevices.getUserMedia({ audio, video: false });
this.onError({ code: 'device_fallback', message: 'Выбранный микрофон недоступен, используется микрофон по умолчанию' });
} else {
throw err;
}
}
const ctx = this.ctx;
const source = ctx.createMediaStreamSource(stream);
const node = new AudioWorkletNode(ctx, 'tp-capture', {
numberOfInputs: 1,
numberOfOutputs: 1,
outputChannelCount: [1],
channelCount: 1,
channelCountMode: 'explicit',
channelInterpretation: 'speakers',
});
const sink = ctx.createGain();
sink.gain.value = 0;
node.port.onmessage = (event) => {
const data = event.data;
if (data.type === 'frame') this.onFrame(data.pcm, data.rms, data.peak);
else if (data.type === 'error') this.onError({ code: 'capture', message: data.message });
};
source.connect(node).connect(sink).connect(ctx.destination);
const track = stream.getAudioTracks()[0];
track.addEventListener('ended', () => {
if (this.capture && this.capture.stream === stream) {
this.stopCapture();
this.onError({ code: 'device_lost', message: 'Микрофон отключён' });
}
});
this.capture = { stream, source, node, sink, label: track ? track.label : '' };
this.log('info', `audio: capture started (${track ? track.getSettings().sampleRate : '?'} Hz device)`);
return this.capture.label;
}
stopCapture() {
const c = this.capture;
if (!c) return;
this.capture = null;
c.node.port.onmessage = null;
try {
c.source.disconnect();
c.node.disconnect();
c.sink.disconnect();
} catch {
// already disconnected
}
for (const t of c.stream.getTracks()) t.stop();
}
}
-78
View File
@@ -1,78 +0,0 @@
// Mixed voice from the core → speakers. Bounded ring: 200 ms capacity (oldest dropped),
// 40 ms prebuffer after every underrun, silence while empty (bridge §5 `audio`).
const CAPACITY = 9600;
const PREBUFFER = 1920;
class PlaybackProcessor extends AudioWorkletProcessor {
constructor() {
super();
this.ring = new Float32Array(CAPACITY);
this.read = 0;
this.write = 0;
this.size = 0;
this.playing = false;
this.framesIn = 0;
this.dropped = 0;
this.underruns = 0;
this.port.onmessage = (event) => {
const data = event.data;
if (data instanceof ArrayBuffer) {
this.push(new Int16Array(data));
} else if (data && data.type === 'flush') {
this.read = 0;
this.write = 0;
this.size = 0;
this.playing = false;
} else if (data && data.type === 'stats') {
this.port.postMessage({
type: 'stats',
framesIn: this.framesIn,
dropped: this.dropped,
underruns: this.underruns,
bufferedMs: Math.round((this.size / 48000) * 1000),
});
}
};
}
push(pcm) {
this.framesIn += 1;
for (let i = 0; i < pcm.length; i += 1) {
if (this.size === CAPACITY) {
this.read = (this.read + 1) % CAPACITY;
this.size -= 1;
this.dropped += 1;
}
this.ring[this.write] = pcm[i] / 32768;
this.write = (this.write + 1) % CAPACITY;
this.size += 1;
}
}
process(_inputs, outputs) {
const out = outputs[0][0];
if (!this.playing) {
if (this.size < PREBUFFER) {
out.fill(0);
return true;
}
this.playing = true;
}
for (let i = 0; i < out.length; i += 1) {
if (this.size > 0) {
out[i] = this.ring[this.read];
this.read = (this.read + 1) % CAPACITY;
this.size -= 1;
} else {
out[i] = 0;
if (this.playing) {
this.playing = false;
this.underruns += 1;
}
}
}
return true;
}
}
registerProcessor('tp-playback', PlaybackProcessor);
-259
View File
@@ -1,259 +0,0 @@
// Channel, server and private text chat. Message text is rendered as plain text only.
import { $, h, icon, reconcile, setText, formatTime } from './dom.js';
import { S, isConnected, ownChannel, clientById } from './state.js';
import { call } from './core.js';
import { errorText, stripBBCode } from './text.js';
import { toast } from './toast.js';
const MAX_MESSAGES = 500;
const chats = new Map();
let active = 'channel';
function ensureChat(key, init) {
let chat = chats.get(key);
if (!chat) {
chat = { key, messages: [], unread: 0, ...init };
chats.set(key, chat);
}
return chat;
}
ensureChat('channel', { kind: 'channel' });
ensureChat('server', { kind: 'server' });
export function initChat() {
const form = $('#chat-form');
const input = $('#chat-input');
form.addEventListener('submit', (e) => {
e.preventDefault();
send();
});
input.addEventListener('keydown', (e) => {
if (e.key === 'Enter' && !e.shiftKey && !e.isComposing) {
e.preventDefault();
send();
}
});
input.addEventListener('input', autosize);
$('#chat-tabs').addEventListener('keydown', onTabKey);
}
function autosize() {
const input = $('#chat-input');
input.style.height = 'auto';
input.style.height = `${Math.min(input.scrollHeight, 160)}px`;
}
function tabTitle(chat) {
if (chat.kind === 'channel') return ownChannel()?.name ?? 'Канал';
if (chat.kind === 'server') return 'Сервер';
const cl = clientById(chat.clientId);
return cl ? cl.nickname : `${chat.nickname} (вышел)`;
}
function targetOf(chat) {
if (chat.kind === 'client') return { target: 'client', client_id: chat.clientId };
return { target: chat.kind };
}
async function send() {
const input = $('#chat-input');
const text = input.value.replace(/\s+$/u, '');
if (!text.trim() || !isConnected()) return;
const chat = chats.get(active);
if (!chat) return;
if (chat.kind === 'client' && !clientById(chat.clientId)) {
toast('Собеседник покинул сервер', 'error');
return;
}
if (new TextEncoder().encode(text).length > 8192) {
toast('Сообщение длиннее 8 КиБ', 'error');
return;
}
input.disabled = true;
try {
await call('send_text', { ...targetOf(chat), message: text });
input.value = '';
autosize();
} catch (err) {
toast(`Сообщение не отправлено: ${errorText(err)}`, 'error');
} finally {
input.disabled = false;
input.focus();
}
}
/** Incoming `text` event (bridge §5). Our own messages arrive here too, exactly once. */
export function onText(evt) {
const own = S.snap?.own_client_id;
let key;
if (evt.target === 'channel') key = 'channel';
else if (evt.target === 'server') key = 'server';
else {
const other = evt.from_client_id === own ? evt.to_client_id : evt.from_client_id;
if (!Number.isInteger(other)) return;
key = openPrivate(other, { focus: false, nickname: evt.from_client_id === own ? undefined : evt.from_nickname });
}
addMessage(key, {
author: evt.from_nickname ?? '?',
own: evt.from_client_id === own,
authorId: evt.from_client_id,
text: stripBBCode(evt.message),
});
}
export function addSystem(key, text) {
addMessage(key, { system: true, text });
}
function addMessage(key, msg) {
const chat = chats.get(key);
if (!chat) return;
msg.time = new Date();
msg.id = `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
chat.messages.push(msg);
if (chat.messages.length > MAX_MESSAGES) chat.messages.splice(0, chat.messages.length - MAX_MESSAGES);
if (key === active && S.view === 'main') {
appendRow(chat, msg);
} else if (!msg.system && !msg.own) {
chat.unread += 1;
}
renderTabs();
}
/** Opens (or creates) a private conversation; returns its key. */
export function openPrivate(clientId, { focus = true, nickname } = {}) {
const key = `client:${clientId}`;
const cl = clientById(clientId);
const chat = ensureChat(key, { kind: 'client', clientId, nickname: nickname ?? cl?.nickname ?? '?' });
if (cl) chat.nickname = cl.nickname;
if (focus) {
select(key);
$('#chat-input').focus();
} else {
renderTabs();
}
return key;
}
function select(key) {
if (!chats.has(key)) return;
active = key;
chats.get(key).unread = 0;
renderTabs();
renderLog();
}
function closePrivate(key) {
chats.delete(key);
if (active === key) active = 'channel';
renderTabs();
renderLog();
}
export function renderTabs() {
const host = $('#chat-tabs');
const list = Array.from(chats.values());
reconcile(host, list, (c) => c.key, createTab, updateTab);
updateComposer();
}
function createTab(chat) {
const tab = h('button', { class: 'chat-tab', type: 'button', role: 'tab' }, h('span', { class: 'tab-label' }), h('span', { class: 'unread', hidden: true }));
tab.addEventListener('click', () => select(chat.key));
const wrap = h('div', { class: 'tab-wrap', role: 'presentation' }, tab);
if (chat.kind === 'client') {
const close = h('button', { class: 'tab-close icon-btn', type: 'button', 'aria-label': 'Закрыть личный чат' }, icon('x'));
close.addEventListener('click', () => closePrivate(chat.key));
wrap.appendChild(close);
}
return wrap;
}
function updateTab(wrap, chat) {
const tab = wrap.firstElementChild;
const [label, unread] = tab.children;
const title = tabTitle(chat);
setText(label, chat.kind === 'client' ? `@ ${title}` : title);
const selected = chat.key === active;
tab.setAttribute('aria-selected', String(selected));
tab.tabIndex = selected ? 0 : -1;
tab.title = chat.kind === 'channel' ? 'Чат текущего канала' : chat.kind === 'server' ? 'Чат всего сервера' : `Личные сообщения: ${title}`;
unread.hidden = chat.unread === 0;
setText(unread, chat.unread > 99 ? '99+' : String(chat.unread));
tab.setAttribute('aria-label', `${tab.title}${chat.unread ? `, непрочитанных: ${chat.unread}` : ''}`);
}
function onTabKey(e) {
if (e.key !== 'ArrowRight' && e.key !== 'ArrowLeft') return;
const tabs = Array.from(document.querySelectorAll('#chat-tabs [role="tab"]'));
const idx = tabs.indexOf(document.activeElement);
if (idx < 0) return;
const next = tabs[(idx + (e.key === 'ArrowRight' ? 1 : tabs.length - 1)) % tabs.length];
next.focus();
next.click();
e.preventDefault();
}
export function renderLog() {
const log = $('#chat-log');
const chat = chats.get(active);
log.replaceChildren();
if (!chat || chat.messages.length === 0) {
log.appendChild(h('li', { class: 'chat-empty', text: emptyText(chat) }));
updateComposer();
return;
}
let prev = null;
for (const msg of chat.messages) {
log.appendChild(rowFor(msg, prev));
prev = msg;
}
log.scrollTop = log.scrollHeight;
updateComposer();
}
function emptyText(chat) {
if (!chat) return '';
if (chat.kind === 'channel') return 'Сообщения в этом канале видят все, кто в нём находится.';
if (chat.kind === 'server') return 'Сообщения сервера видят все подключённые.';
return 'Личная переписка. Сообщения видит только собеседник.';
}
function rowFor(msg, prev) {
if (msg.system) return h('li', { class: 'msg-system', text: msg.text });
const head = !prev || prev.system || prev.authorId !== msg.authorId || msg.time - prev.time > 5 * 60 * 1000;
const li = h('li', { class: 'msg', dataset: { head: String(head), own: String(Boolean(msg.own)) } });
if (head) {
li.appendChild(h('div', { class: 'msg-head' }, h('span', { class: 'msg-author', text: msg.author }), h('time', { class: 'msg-time', datetime: msg.time.toISOString(), text: formatTime(msg.time) })));
}
li.appendChild(h('div', { class: 'msg-body', text: msg.text }));
return li;
}
function appendRow(chat, msg) {
const log = $('#chat-log');
const nearBottom = log.scrollHeight - log.scrollTop - log.clientHeight < 80;
const empty = log.querySelector('.chat-empty');
if (empty) empty.remove();
const prev = chat.messages[chat.messages.length - 2] ?? null;
log.appendChild(rowFor(msg, prev));
if (nearBottom || msg.own) log.scrollTop = log.scrollHeight;
}
export function updateComposer() {
const input = $('#chat-input');
const sendBtn = $('#chat-send');
const chat = chats.get(active);
const partnerGone = chat && chat.kind === 'client' && !clientById(chat.clientId);
const enabled = isConnected() && !partnerGone;
input.disabled = !enabled;
sendBtn.disabled = !enabled;
const title = chat ? tabTitle(chat) : '';
input.placeholder = !isConnected() ? 'Нет подключения' : partnerGone ? 'Собеседник покинул сервер' : chat?.kind === 'client' ? `Сообщение для ${title}` : chat?.kind === 'server' ? 'Сообщение всему серверу' : `Сообщение в «${title}»`;
}
/** Called when the connection ends: private chats keep their history but cannot be answered. */
export function onConnectionChanged() {
renderTabs();
}
-22
View File
@@ -1,22 +0,0 @@
// Thin wrapper over the preload API (window.teamspeach). Requests resolve to `result` or throw BridgeError.
export const tp = window.teamspeach;
export class BridgeError extends Error {
constructor(error) {
super(error?.message || error?.code || 'error');
this.code = error?.code ?? 'internal';
this.ts_error = error?.ts_error;
this.detail = error?.detail;
}
}
export async function call(cmd, args) {
const response = await tp.request(cmd, args);
if (!response || !response.ok) throw new BridgeError(response?.error);
return response.result;
}
export function log(level, message) {
tp.log(level, message);
}
-89
View File
@@ -1,89 +0,0 @@
// DOM helpers. Server-provided text only ever reaches the page through textContent / attributes.
export function $(selector, root = document) {
const el = root.querySelector(selector);
if (!el) throw new Error(`missing element ${selector}`);
return el;
}
/**
* h('button', {class: 'x', onclick, 'aria-label': 'y', dataset: {cid: 1}}, 'text', child)
* Strings become text nodes; there is no innerHTML path.
*/
export function h(tag, props = {}, ...children) {
const el = document.createElement(tag);
for (const [key, value] of Object.entries(props)) {
if (value === undefined || value === null || value === false) continue;
if (key === 'class') el.className = value;
else if (key === 'dataset') Object.assign(el.dataset, value);
else if (key === 'text') el.textContent = value;
else if (key.startsWith('on') && typeof value === 'function') el.addEventListener(key.slice(2), value);
else if (key in el && typeof value !== 'string') el[key] = value;
else el.setAttribute(key, value === true ? '' : String(value));
}
append(el, children);
return el;
}
function append(el, children) {
for (const child of children) {
if (child === undefined || child === null || child === false) continue;
if (Array.isArray(child)) append(el, child);
else if (child instanceof Node) el.appendChild(child);
else el.appendChild(document.createTextNode(String(child)));
}
}
const SVG_NS = 'http://www.w3.org/2000/svg';
/** Reference to a symbol of the inline sprite in index.html. */
export function icon(name, extraClass = '') {
const svg = document.createElementNS(SVG_NS, 'svg');
svg.setAttribute('class', `icon ${extraClass}`.trim());
svg.setAttribute('aria-hidden', 'true');
svg.setAttribute('focusable', 'false');
const use = document.createElementNS(SVG_NS, 'use');
use.setAttribute('href', `#i-${name}`);
svg.appendChild(use);
return svg;
}
export function setIcon(svg, name) {
svg.firstElementChild.setAttribute('href', `#i-${name}`);
}
/**
* Keyed list reconciliation: reuses nodes by key so focus and hover survive frequent snapshots.
* create(item) → Element; update(el, item) mutates in place.
*/
export function reconcile(container, items, keyOf, create, update) {
const existing = new Map();
for (const child of Array.from(container.children)) {
if (child.dataset.key) existing.set(child.dataset.key, child);
}
let cursor = container.firstElementChild;
for (const item of items) {
const key = keyOf(item);
let el = existing.get(key);
if (el) {
existing.delete(key);
update(el, item);
} else {
el = create(item);
el.dataset.key = key;
update(el, item);
}
if (el !== cursor) container.insertBefore(el, cursor);
else cursor = cursor.nextElementSibling;
}
for (const el of existing.values()) el.remove();
}
export function setText(el, text) {
const value = text ?? '';
if (el.textContent !== value) el.textContent = value;
}
export function formatTime(date) {
return date.toLocaleTimeString('ru-RU', { hour: '2-digit', minute: '2-digit' });
}
-91
View File
@@ -1,91 +0,0 @@
// Server images (group/channel icons, channel banners, host banner, avatars) as blob: URLs.
// Bytes come from the core's file transfer (or main's allowlisted http(s) fetch); MIME is sniffed
// upstream and re-checked here. Failures are cached as null so a missing file is not refetched.
import { tp, call, log } from './core.js';
const ALLOWED = new Set(['image/png', 'image/jpeg', 'image/gif', 'image/webp', 'image/x-icon', 'image/svg+xml']);
const cache = new Map();
function toUrl(result) {
if (!result || !ALLOWED.has(result.mime) || typeof result.data !== 'string') return null;
const bin = atob(result.data);
const bytes = new Uint8Array(bin.length);
for (let i = 0; i < bin.length; i += 1) bytes[i] = bin.charCodeAt(i);
return URL.createObjectURL(new Blob([bytes], { type: result.mime }));
}
function cached(key, load) {
if (!cache.has(key)) {
cache.set(key, load().then(toUrl).catch((err) => {
if (err.code !== 'not_found') log('info', `media ${key.split(':')[0]} unavailable: ${err.code ?? err.message}`);
return null;
}));
}
return cache.get(key);
}
async function viaCore(cmd, args) {
try {
return await call(cmd, args);
} catch (err) {
if (err.code === 'external_media' && err.detail && typeof err.detail.url === 'string') {
const r = await tp.fetchExternalMedia(err.detail.url);
if (r && r.ok) return r.result;
const e = new Error(r?.error?.message ?? 'external fetch failed');
e.code = r?.error?.code ?? 'io';
throw e;
}
throw err;
}
}
/** TeamSpeak's built-in group icon ids (bridge §4.16): the server has no file for them. */
const BUILTIN_ICONS = new Set([100, 200, 300, 500, 600]);
export function isBuiltinIcon(id) {
return BUILTIN_ICONS.has(id);
}
export function iconUrl(iconId) {
if (!iconId || isBuiltinIcon(iconId)) return Promise.resolve(null);
return cached(`icon:${iconId}`, () => call('fetch_icon', { icon_id: iconId }));
}
export function channelBannerUrl(channel) {
if (!channel.banner_url) return Promise.resolve(null);
return cached(`banner:${channel.id}:${channel.banner_url}`, () => viaCore('fetch_banner', { channel_id: channel.id }));
}
export function serverBannerUrl(server) {
if (!server?.hostbanner_gfx_url) return Promise.resolve(null);
return cached(`hostbanner:${server.hostbanner_gfx_url}`, () => viaCore('fetch_server_banner'));
}
export function avatarUrl(client) {
if (client.avatar_hash) return cached(`avatar:${client.uid}:${client.avatar_hash}`, () => call('fetch_avatar', { client_id: client.id }));
const myts = mytsAvatar(client);
if (myts) {
return cached(`myts:${myts}`, async () => {
const r = await tp.fetchExternalMedia(myts);
if (r && r.ok) return r.result;
const e = new Error(r?.error?.message ?? 'external fetch failed');
e.code = r?.error?.code ?? 'io';
throw e;
});
}
return Promise.resolve(null);
}
/** myTeamSpeak avatar URL (bridge: myts_avatars[{variant,url}]); the highest variant observed is used. */
function mytsAvatar(client) {
if (!Array.isArray(client.myts_avatars)) return null;
const list = client.myts_avatars.filter((v) => v && typeof v.url === 'string' && v.url.startsWith('https://'));
list.sort((a, b) => (b.variant ?? 0) - (a.variant ?? 0));
return list[0]?.url ?? null;
}
/** Forget everything (new server or disconnect) and release blob URLs. */
export function clearMedia() {
for (const p of cache.values()) p.then((url) => url && URL.revokeObjectURL(url));
cache.clear();
}
-3
View File
@@ -1,3 +0,0 @@
{
"type": "module"
}
-180
View File
@@ -1,180 +0,0 @@
// Saved servers (name + address only; never passwords): quick access in the sidebar and management
// in Settings → Серверы. Persisted through main's validated preferences.
import { $, h, icon, setText } from './dom.js';
import { S, isConnected } from './state.js';
import { toast } from './toast.js';
let hooks = { savePrefs: async () => S.prefs, connectTo: async () => {} };
let panelOpen = null; // null = automatic (open while disconnected)
let editingId = null;
let confirmDeleteId = null;
let confirmTimer = null;
export function initServers(h0) {
hooks = { ...hooks, ...h0 };
$('#btn-servers').addEventListener('click', () => {
panelOpen = !isPanelOpen();
renderServers();
if (panelOpen) $('#servers-list button')?.focus();
});
$('#servers-save-current').addEventListener('click', () => saveAddress(S.snap?.server?.name || S.conn.address, S.conn.address));
$('#connect-save').addEventListener('click', () => {
const address = $('#connect-address').value.trim();
if (!address) {
setText($('#connect-error'), 'Укажите адрес сервера, чтобы сохранить его.');
return;
}
saveAddress(address, address);
});
$('#server-add-form').addEventListener('submit', async (e) => {
e.preventDefault();
const name = $('#server-add-name').value.trim();
const address = $('#server-add-address').value.trim();
if (!address) {
setText($('#server-add-status'), 'Укажите адрес.');
return;
}
if (await saveAddress(name || address, address)) {
$('#server-add-name').value = '';
$('#server-add-address').value = '';
setText($('#server-add-status'), 'Сервер добавлен.');
}
});
}
function servers() {
return S.prefs?.savedServers ?? [];
}
function newId() {
const bytes = crypto.getRandomValues(new Uint8Array(8));
return Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('');
}
function sameAddress(a, b) {
const norm = (x) => x.trim().toLowerCase().replace(/:9987$/, '');
return norm(a) === norm(b);
}
async function persist(list) {
const before = servers();
const prefs = await hooks.savePrefs({ savedServers: list });
renderServers();
return prefs.savedServers !== before;
}
async function saveAddress(name, address) {
const trimmed = address.trim();
if (servers().some((s) => sameAddress(s.address, trimmed))) {
toast('Этот адрес уже сохранён');
return false;
}
if (servers().length >= 50) {
toast('Можно сохранить не больше 50 серверов', 'error');
return false;
}
const ok = await persist([...servers(), { id: newId(), name: name.trim().slice(0, 64) || trimmed, address: trimmed }]);
if (ok) toast(`Сервер «${name.trim() || trimmed}» сохранён`);
return ok;
}
function isPanelOpen() {
return panelOpen ?? !isConnected();
}
function connectedTo(server) {
return S.conn.state !== 'disconnected' && sameAddress(server.address, S.conn.address || '');
}
export function renderServers() {
const open = isPanelOpen();
$('#servers-panel').hidden = !open;
$('#btn-servers').setAttribute('aria-expanded', String(open));
const list = servers();
const canSaveCurrent = isConnected() && S.conn.address && !list.some((s) => sameAddress(s.address, S.conn.address));
$('#servers-save-current').hidden = !canSaveCurrent;
$('#servers-empty').hidden = list.length > 0;
$('#servers-list').replaceChildren(...list.map(quickRow));
$('#servers-manage-empty').hidden = list.length > 0;
$('#servers-manage').replaceChildren(...list.map(manageRow));
}
function quickRow(server) {
const current = connectedTo(server);
const busy = S.conn.state === 'connecting' || S.conn.state === 'disconnecting';
const label = current ? 'Подключено' : S.conn.state === 'disconnected' ? 'Подключиться' : 'Переключиться';
const btn = h('button', {
class: 'server-item',
type: 'button',
disabled: current || busy,
'aria-label': `${server.name}, ${server.address}. ${label}`,
title: current ? 'Вы подключены к этому серверу' : S.conn.state === 'disconnected' ? 'Подключиться' : 'Отключиться от текущего сервера и подключиться к этому',
}, icon('bookmark'), h('span', { class: 'server-text' }, h('span', { class: 'server-item-name', text: server.name }), h('span', { class: 'server-item-address', text: server.address })), h('span', { class: 'server-item-action', text: label }));
btn.addEventListener('click', () => hooks.connectTo(server.address, { switching: S.conn.state !== 'disconnected' }));
return h('li', {}, btn);
}
function manageRow(server) {
if (editingId === server.id) return editRow(server);
const edit = h('button', { class: 'btn btn-ghost btn-small', type: 'button' }, 'Изменить');
const confirming = confirmDeleteId === server.id;
const del = h('button', { class: `btn btn-ghost btn-small${confirming ? ' btn-danger' : ''}`, type: 'button' }, confirming ? 'Точно удалить?' : 'Удалить');
edit.addEventListener('click', () => {
editingId = server.id;
renderServers();
document.querySelector(`#servers-manage [data-edit="${server.id}"] input`)?.focus();
});
del.addEventListener('click', async () => {
if (confirmDeleteId !== server.id) {
confirmDeleteId = server.id;
clearTimeout(confirmTimer);
confirmTimer = setTimeout(() => {
confirmDeleteId = null;
renderServers();
}, 4000);
renderServers();
document.querySelector(`#servers-manage [data-row="${server.id}"] .btn-danger`)?.focus();
return;
}
confirmDeleteId = null;
await persist(servers().filter((s) => s.id !== server.id));
toast(`Сервер «${server.name}» удалён`);
});
return h('li', { class: 'manage-row', dataset: { row: server.id } },
h('span', { class: 'server-text' }, h('span', { class: 'server-item-name', text: server.name }), h('span', { class: 'server-item-address', text: server.address })),
edit, del);
}
function editRow(server) {
const name = h('input', { type: 'text', maxlength: '64', value: server.name, 'aria-label': 'Название сервера' });
const address = h('input', { type: 'text', maxlength: '255', value: server.address, spellcheck: 'false', 'aria-label': 'Адрес сервера' });
const cancel = h('button', { class: 'btn btn-ghost btn-small', type: 'button' }, 'Отмена');
const form = h('form', { class: 'edit-row', novalidate: true, dataset: { edit: server.id } }, name, address, h('button', { class: 'btn btn-primary btn-small', type: 'submit' }, 'Сохранить'), cancel);
cancel.addEventListener('click', () => {
editingId = null;
renderServers();
});
form.addEventListener('keydown', (e) => {
if (e.key === 'Escape') {
e.preventDefault();
editingId = null;
renderServers();
}
});
form.addEventListener('submit', async (e) => {
e.preventDefault();
const n = name.value.trim();
const a = address.value.trim();
if (!n || !a) {
toast('Название и адрес не могут быть пустыми', 'error');
return;
}
if (servers().some((s) => s.id !== server.id && sameAddress(s.address, a))) {
toast('Этот адрес уже сохранён под другим названием', 'error');
return;
}
editingId = null;
await persist(servers().map((s) => (s.id === server.id ? { id: s.id, name: n, address: a } : s)));
});
return h('li', { class: 'manage-row editing' }, form);
}
-280
View File
@@ -1,280 +0,0 @@
// Settings: profile (rename, UID, identity backup), audio devices/transmit mode, diagnostics.
import { $, h, setText } from './dom.js';
import { S, isConnected } from './state.js';
import { tp, call } from './core.js';
import { errorText, keyLabel } from './text.js';
import { toast } from './toast.js';
import * as voice from './voice.js';
import { applySink, watchStats } from './watch.js';
let hooks = { savePrefs: async () => {}, close: () => {}, onProfile: () => {} };
export function initSettings(h0) {
hooks = { ...hooks, ...h0 };
$('#settings-back').addEventListener('click', () => hooks.close());
for (const host of [$('#settings-view'), $('#settings-nav')]) {
host.addEventListener('keydown', (e) => {
if (e.key === 'Escape' && !e.defaultPrevented) hooks.close();
});
}
const nav = $('#settings-nav');
nav.addEventListener('click', (e) => {
const item = e.target.closest('.nav-item');
if (item) showPanel(item.dataset.panel);
});
nav.addEventListener('keydown', (e) => {
const items = Array.from(nav.querySelectorAll('.nav-item'));
const i = items.indexOf(document.activeElement);
if (i < 0) return;
let next = null;
if (e.key === 'ArrowDown') next = items[(i + 1) % items.length];
else if (e.key === 'ArrowUp') next = items[(i - 1 + items.length) % items.length];
else if (e.key === 'Home') next = items[0];
else if (e.key === 'End') next = items[items.length - 1];
if (next) {
e.preventDefault();
next.focus();
showPanel(next.dataset.panel);
}
});
for (const radio of document.querySelectorAll('input[name="theme"]')) {
radio.addEventListener('change', () => {
if (radio.checked) hooks.savePrefs({ theme: radio.value });
});
}
$('#rename-form').addEventListener('submit', async (e) => {
e.preventDefault();
const input = $('#rename-input');
const status = $('#rename-status');
const nickname = input.value.trim();
const len = [...nickname].length;
if (len < 3 || len > 30) {
input.setAttribute('aria-invalid', 'true');
setText(status, 'Никнейм должен содержать от 3 до 30 символов.');
return;
}
if (nickname === S.profile?.nickname) {
setText(status, 'Это уже ваш никнейм.');
return;
}
input.removeAttribute('aria-invalid');
$('#rename-submit').disabled = true;
setText(status, 'Сохраняем…');
const uidBefore = S.profile?.uid;
try {
const profile = await call('rename', { nickname });
hooks.onProfile(profile);
setText(status, profile.uid === uidBefore ? `Сохранено${isConnected() ? ' и применено на сервере' : ''}. UID не изменился.` : 'Сохранено.');
} catch (err) {
if (err.code === 'rename_not_persisted' && err.detail) {
setText(status, `Сервер показал «${err.detail.server_nickname}», но на диске остался «${err.detail.saved_nickname}»${err.detail.reverted ? '; имя на сервере возвращено' : ''}.`);
} else {
setText(status, errorText(err));
}
} finally {
$('#rename-submit').disabled = false;
}
});
$('#uid-copy').addEventListener('click', async () => {
if (S.profile?.uid && (await tp.copyText(S.profile.uid))) toast('UID скопирован');
});
$('#identity-export').addEventListener('click', async () => {
const status = $('#identity-status');
const r = await tp.exportIdentity();
if (r.canceled) return;
setText(status, r.ok ? `Сохранено в «${r.file}». UID ${r.uid}.` : `Экспорт не удался: ${errorText(r.error)}`);
});
$('#identity-import').addEventListener('click', async () => {
const status = $('#identity-status');
if (S.conn.state !== 'disconnected') {
setText(status, 'Сначала отключитесь от сервера.');
return;
}
const r = await tp.importIdentity();
if (r.canceled) return;
if (r.ok) toast(`Идентичность импортирована. UID ${r.uid}`);
else setText(status, `Импорт не удался: ${errorText(r.error)}`);
});
$('#input-device').addEventListener('change', async (e) => {
await hooks.savePrefs({ inputDeviceId: e.target.value });
await voice.restartCapture();
});
$('#output-device').addEventListener('change', async (e) => {
await hooks.savePrefs({ outputDeviceId: e.target.value });
try {
await voice.setOutputDevice(e.target.value);
} catch (err) {
toast(`Не удалось выбрать устройство вывода: ${err.message}`, 'error');
}
applySink();
});
$('#voice-volume').addEventListener('input', (e) => {
const v = Number(e.target.value);
voice.setVoiceVolume(v);
setText($('#voice-volume-value'), `${v}%`);
});
$('#voice-volume').addEventListener('change', (e) => hooks.savePrefs({ voiceVolume: Number(e.target.value) }));
for (const radio of document.querySelectorAll('input[name="transmit"]')) {
radio.addEventListener('change', async () => {
if (radio.checked) {
await hooks.savePrefs({ transmitMode: radio.value });
renderAudio();
}
});
}
$('#ptt-assign').addEventListener('click', async () => {
const btn = $('#ptt-assign');
btn.disabled = true;
setText($('#ptt-key'), 'нажмите клавишу…');
const code = await voice.capturePttKey();
btn.disabled = false;
if (code) await hooks.savePrefs({ pttCode: code });
renderAudio();
btn.focus();
});
const processing = [['#opt-ns', 'noiseSuppression'], ['#opt-ec', 'echoCancellation'], ['#opt-agc', 'autoGainControl']];
for (const [sel, key] of processing) {
$(sel).addEventListener('change', async (e) => {
await hooks.savePrefs({ [key]: e.target.checked });
await voice.restartCapture();
});
}
$('#mic-test').addEventListener('click', async () => {
const btn = $('#mic-test');
const on = btn.getAttribute('aria-pressed') !== 'true';
btn.setAttribute('aria-pressed', String(on));
setText(btn, on ? 'Остановить проверку' : 'Проверить микрофон');
await voice.setMicTest(on);
});
$('#open-logs').addEventListener('click', () => tp.openLogs());
$('#opt-hwdec').addEventListener('change', async (e) => {
await hooks.savePrefs({ hardwareVideoDecode: e.target.checked });
renderVideo();
});
$('#hwdec-relaunch').addEventListener('click', () => tp.relaunch());
}
export function renderProfile() {
const p = S.profile;
if (!p) return;
const input = $('#rename-input');
if (document.activeElement !== input) input.value = p.nickname ?? '';
setText($('#uid-value'), p.uid ?? '');
setText($('#security-level'), p.security_level !== null && p.security_level !== undefined ? `Уровень безопасности идентичности: ${p.security_level}` : '');
$('#identity-import').disabled = S.conn.state !== 'disconnected';
$('#identity-import').title = S.conn.state !== 'disconnected' ? 'Доступно после отключения от сервера' : '';
}
export function renderAudio() {
const prefs = S.prefs;
for (const radio of document.querySelectorAll('input[name="transmit"]')) radio.checked = radio.value === prefs.transmitMode;
setText($('#ptt-key'), keyLabel(prefs.pttCode));
$('#ptt-assign').disabled = false;
$('#opt-ns').checked = prefs.noiseSuppression;
$('#opt-ec').checked = prefs.echoCancellation;
$('#opt-agc').checked = prefs.autoGainControl;
$('#voice-volume').value = String(prefs.voiceVolume);
setText($('#voice-volume-value'), `${prefs.voiceVolume}%`);
}
export async function renderDiagnostics() {
const info = await tp.getAppInfo();
const rows = [
['TeamsPeach', info.appVersion],
['Ядро', info.coreVersion ?? 'не запущено'],
['Electron', info.electron],
['Chromium', info.chrome],
['Платформа', `${info.platform} ${info.arch}`],
['Исполняемый файл ядра', info.coreBinary ?? '—'],
['Каталог данных', info.dataDir],
];
$('#diag-list').replaceChildren(...rows.flatMap(([k, v]) => [h('dt', { text: k }), h('dd', { text: v })]));
$('#codec-list').replaceChildren(...videoCodecs().map((line) => h('li', { text: line })));
}
const IGNORED = new Set(['video/rtx', 'video/red', 'video/ulpfec', 'video/flexfec-03']);
export function videoCodecs() {
const caps = typeof RTCRtpReceiver.getCapabilities === 'function' ? RTCRtpReceiver.getCapabilities('video') : null;
if (!caps) return ['Возможности приёма недоступны'];
return caps.codecs.filter((c) => !IGNORED.has(c.mimeType.toLowerCase())).map((c) => `${c.mimeType.replace('video/', '')}${c.sdpFmtpLine ? ` ${c.sdpFmtpLine}` : ''}`);
}
let currentPanel = 'identity';
/** Shows one settings category; the active navigation item carries aria-current="page". */
export function showPanel(name) {
currentPanel = name;
for (const panel of document.querySelectorAll('.settings-panel')) panel.hidden = panel.dataset.panel !== name;
for (const item of document.querySelectorAll('#settings-nav .nav-item')) {
if (item.dataset.panel === name) item.setAttribute('aria-current', 'page');
else item.removeAttribute('aria-current');
}
$('#settings-view .settings-scroll').scrollTop = 0;
if (name === 'video') renderVideo();
if (name === 'audio') voice.refreshDevices();
}
export function open(panel) {
renderProfile();
renderAudio();
voice.refreshDevices();
renderDiagnostics();
renderVideo();
for (const radio of document.querySelectorAll('input[name="theme"]')) radio.checked = radio.value === S.prefs.theme;
showPanel(panel ?? currentPanel);
document.querySelector(`#settings-nav .nav-item[data-panel="${currentPanel}"]`)?.focus();
}
export async function close() {
const btn = $('#mic-test');
if (btn.getAttribute('aria-pressed') === 'true') {
btn.setAttribute('aria-pressed', 'false');
setText(btn, 'Проверить микрофон');
await voice.setMicTest(false);
}
}
// app.getGPUFeatureStatus().video_decode describes what the engine is allowed/able to use,
// not which decoder is decoding right now; that comes only from a live RTCPeerConnection.
const GPU_STATE = {
enabled: 'аппаратное декодирование разрешено и доступно движку',
enabled_on: 'аппаратное декодирование разрешено и доступно движку',
enabled_force: 'аппаратное декодирование принудительно разрешено',
disabled_software: 'аппаратное декодирование отключено, движок будет декодировать программно',
disabled_off: 'аппаратное декодирование отключено',
disabled_off_ok: 'аппаратное декодирование отключено',
unavailable_software: 'аппаратное декодирование недоступно на этом устройстве, будет программное',
unavailable_off: 'аппаратное декодирование недоступно',
unavailable_off_ok: 'аппаратное декодирование недоступно',
};
/** Saved preference vs what this run was started with vs what the engine reports vs the live decoder. */
export async function renderVideo() {
const status = await tp.getVideoStatus();
const saved = S.prefs.hardwareVideoDecode;
$('#opt-hwdec').checked = saved;
$('#hwdec-restart').hidden = !status || saved === status.hardwareDecodeAtLaunch;
if (status) {
const gpu = status.gpu?.video_decode ?? 'неизвестно';
setText($('#hwdec-status'), `В этом запуске: ${status.hardwareDecodeAtLaunch ? 'разрешено' : 'запрещено (флаг disable-accelerated-video-decode)'}. Движок Chromium: ${GPU_STATE[gpu] ?? gpu}.`);
}
const d = watchStats.decoder;
const live = watchStats.state === 'live' || watchStats.state === 'unstable';
const efficiency = watchStats.powerEfficientDecoder === true ? ' (энергоэффективный)' : watchStats.powerEfficientDecoder === false ? ' (не энергоэффективный)' : '';
setText($('#decoder-last'), d
? `${live ? 'Текущая трансляция' : 'При последнем просмотре'}: ${watchStats.codec || '—'}, декодер «${d}»${efficiency}.`
: 'Какой декодер реально работает, видно только во время просмотра трансляции.');
}
-47
View File
@@ -1,47 +0,0 @@
// Single renderer state object plus a tiny topic bus. The core snapshot is replaced wholesale (bridge §5).
export const S = {
core: { status: 'starting' },
profile: null,
prefs: null,
conn: { state: 'disconnected', address: '', reason: null },
snap: null,
audio: { input_muted: false, output_muted: false, transmitting: false },
talking: new Set(),
view: 'main',
ptt: false,
codecBlocked: null,
};
const listeners = new Map();
export function on(topic, fn) {
if (!listeners.has(topic)) listeners.set(topic, new Set());
listeners.get(topic).add(fn);
}
export function emit(topic, payload) {
const set = listeners.get(topic);
if (!set) return;
for (const fn of set) fn(payload);
}
export function ownClient() {
const snap = S.snap;
if (!snap) return null;
return snap.clients.find((c) => c.id === snap.own_client_id) ?? null;
}
export function ownChannel() {
const snap = S.snap;
if (!snap) return null;
return snap.channels.find((c) => c.id === snap.own_channel_id) ?? null;
}
export function clientById(id) {
return S.snap ? S.snap.clients.find((c) => c.id === id) ?? null : null;
}
export function isConnected() {
return S.conn.state === 'connected' && S.snap !== null;
}
-91
View File
@@ -1,91 +0,0 @@
// Which clients are currently streaming, built only from server notifications
// (notifystreamstarted / notifystreaminfo / notifystreamupdated / notifystreamstopped).
export class StreamDirectory {
constructor() {
/** @type {Map<string, {id:string, clientId:number, name:string, fields:Record<string,string>}>} */
this.streams = new Map();
this.sfuSeen = false;
}
/** Returns true when the visible set changed. */
handle(name, items) {
let changed = false;
for (const item of items) {
switch (name) {
case 'notifystreamstarted':
case 'notifystreaminfo':
case 'notifystreamupdated':
changed = this._upsert(item, name !== 'notifystreamupdated') || changed;
break;
case 'notifystreamstopped':
changed = this._remove(item) || changed;
break;
case 'notifysfuaccessinfo':
if (!this.sfuSeen) changed = true;
this.sfuSeen = true;
break;
default:
break;
}
}
return changed;
}
_upsert(item, mayCreate) {
if (!item || !item.id) return false;
const id = String(item.id);
const existing = this.streams.get(id);
const clientId = item.clid !== undefined && item.clid !== '' ? Number(item.clid) : existing?.clientId;
if (!existing && (!mayCreate || !Number.isInteger(clientId))) return false;
const fields = { ...(existing?.fields ?? {}), ...item };
this.streams.set(id, {
id,
clientId,
name: typeof fields.name === 'string' ? fields.name : '',
fields,
});
return true;
}
_remove(item) {
if (item && item.id && this.streams.delete(String(item.id))) return true;
if (item && item.clid !== undefined) {
let removed = false;
for (const [id, s] of this.streams) {
if (s.clientId === Number(item.clid)) {
this.streams.delete(id);
removed = true;
}
}
return removed;
}
return false;
}
/** Drop streams of clients that are no longer on the server. */
prune(presentClientIds) {
let changed = false;
for (const [id, s] of this.streams) {
if (!presentClientIds.has(s.clientId)) {
this.streams.delete(id);
changed = true;
}
}
return changed;
}
byClient(clientId) {
for (const s of this.streams.values()) if (s.clientId === clientId) return s;
return null;
}
get(id) {
return this.streams.get(String(id)) ?? null;
}
clear() {
this.streams.clear();
this.sfuSeen = false;
}
}
-336
View File
@@ -1,336 +0,0 @@
// One viewing session of a TS6 screenshare (P2P path). DOM-free: the RTCPeerConnection factory is injected.
//
// Wire (server text channel, via core `stream_*` commands / `stream` events):
// join → joinstreamrequest id clid msg is_remove=0
// offer ← notifyrespondjoinstreamrequest decision=1 offer=<sdp>
// answer → streamsignaling json={"cmd":"answer","args":{"answer":<sdp>}}
// ICE ↔ {"cmd":"iceCandidate","args":{"mLine","mid","sdp"}}
// realign← {"cmd":"offer"|"reconnectOffer","args":{"offer":<sdp>}} must be answered or media never starts
// leave → joinstreamrequest … is_remove=1
export const JOIN_TIMEOUT_MS = 90_000;
/** Terminal states: no further signaling is accepted once one is reached. */
const TERMINAL = new Set(['declined', 'ended', 'removed', 'failed', 'stopped', 'unsupported']);
export class StreamViewerSession {
/**
* @param {object} o
* @param {string} o.streamId
* @param {number} o.clientId streamer clid
* @param {number} o.ownClientId
* @param {string} o.message join message (our nickname)
* @param {{join:Function, send:Function, leave:Function}} o.signal async core calls
* @param {(config:object)=>RTCPeerConnection} o.createPeerConnection
* @param {RTCIceServer[]} [o.iceServers]
* @param {(state:string, detail?:string)=>void} [o.onState]
* @param {(track:MediaStreamTrack)=>void} [o.onTrack]
* @param {(level:string, msg:string)=>void} [o.log]
* @param {(fn:Function, ms:number)=>any} [o.setTimer]
* @param {(id:any)=>void} [o.clearTimer]
*/
constructor(o) {
this.streamId = String(o.streamId);
this.clientId = Number(o.clientId);
this.ownClientId = Number(o.ownClientId);
this.message = o.message ?? '';
this.signal = o.signal;
this.createPeerConnection = o.createPeerConnection;
this.iceServers = o.iceServers ?? [];
this.onState = o.onState ?? (() => {});
this.onTrack = o.onTrack ?? (() => {});
this.log = o.log ?? (() => {});
this.setTimer = o.setTimer ?? ((fn, ms) => setTimeout(fn, ms));
this.clearTimer = o.clearTimer ?? ((id) => clearTimeout(id));
this.state = 'idle';
this.detail = '';
this.pc = null;
this.queue = Promise.resolve();
this.pendingRemote = [];
this.pendingLocal = [];
this.answersSent = 0;
this.offersApplied = 0;
this.remoteCandidatesAdded = 0;
this.staleCandidates = 0;
this.candidateErrors = 0;
this.joinTimer = null;
}
get closed() {
return TERMINAL.has(this.state);
}
async start() {
this._setState('requesting');
this.joinTimer = this.setTimer(() => {
if (this.state === 'requesting') this._finish('failed', 'no_response', true);
}, JOIN_TIMEOUT_MS);
try {
await this.signal.join(this.streamId, this.clientId, this.message);
this.log('info', `watch: join sent id=${this.streamId} clid=${this.clientId}`);
} catch (err) {
if (!this.closed) this._finish('failed', describe(err), false);
}
}
/** User stopped or cancelled. Sends is_remove=1 unless the stream is already gone. */
stop() {
if (this.closed) return;
this._finish('stopped', '', true);
}
/** The stream or the connection went away underneath us: no leave command. */
terminate(reason) {
if (this.closed) return;
this._finish('ended', reason, false);
}
/** True when the notification belongs to this session (stream id + streamer/our clid). */
matches(item) {
if (!item || String(item.id) !== this.streamId) return false;
if (item.clid === undefined || item.clid === '') return true;
const clid = Number(item.clid);
return clid === this.clientId || clid === this.ownClientId;
}
/** Feeds one `stream` event item. Returns true when consumed. */
handle(name, item) {
if (this.closed) return false;
switch (name) {
case 'notifyrespondjoinstreamrequest': {
if (!this.matches(item)) return false;
this._clearJoinTimer();
const offer = typeof item.offer === 'string' ? item.offer : '';
if (item.decision === '1' && offer) {
this.log('info', `watch: join accepted, offer ${offer.length} chars (clid field=${item.clid ?? '-'})`);
this._enqueue(() => this._applyOffer(offer, 'join'));
} else {
this.log('info', `watch: join declined decision=${item.decision ?? '-'}`);
this._finish('declined', item.msg || '', false);
}
return true;
}
case 'notifystreamsignaling': {
if (!this.matches(item)) return false;
let message;
try {
message = JSON.parse(item.json ?? '');
} catch {
this.log('warn', 'watch: unparseable signaling json');
return true;
}
this._onSignal(message);
return true;
}
case 'notifystreamstopped': {
if (String(item.id) !== this.streamId) return false;
this._finish('ended', 'stream_stopped', false);
return true;
}
case 'notifystreamclientleft': {
if (String(item.id) !== this.streamId) return false;
if (Number(item.clid) === this.ownClientId) {
this._finish('removed', '', false);
return true;
}
return false;
}
case 'notifysfuaccessinfo': {
// The server routes this stream through its SFU (mediasoup); TeamsPeach only speaks the P2P path.
if (this.state === 'requesting' || this.matches(item)) {
this._finish('unsupported', 'sfu', true);
return true;
}
return false;
}
default:
return false;
}
}
_onSignal(message) {
const cmd = message && message.cmd;
const args = (message && message.args) || {};
switch (cmd) {
case 'offer':
case 'reconnectOffer': {
const sdp = typeof args.offer === 'string' ? args.offer : typeof args.sdp === 'string' ? args.sdp : '';
if (!sdp) {
this.log('warn', `watch: ${cmd} without sdp`);
return;
}
this.log('info', `watch: ${cmd} received (${sdp.length} chars)`);
this._enqueue(() => this._applyOffer(sdp, cmd));
return;
}
case 'iceCandidate':
this._enqueue(() => this._addRemoteCandidate(args));
return;
default:
this.log('info', `watch: ignored signaling cmd=${String(cmd)}`);
}
}
_ensurePc() {
if (this.pc) return this.pc;
const pc = this.createPeerConnection({ iceServers: this.iceServers });
this.pc = pc;
pc.onicecandidate = (event) => {
const c = event.candidate;
if (!c || !c.candidate || this.closed) return;
const msg = {
cmd: 'iceCandidate',
args: { mLine: c.sdpMLineIndex ?? 0, mid: c.sdpMid ?? String(c.sdpMLineIndex ?? 0), sdp: c.candidate },
};
if (this.answersSent === 0) this.pendingLocal.push(msg);
else this._send(msg).catch(() => {});
};
pc.ontrack = (event) => {
if (!this.closed) this.onTrack(event.track);
};
pc.onconnectionstatechange = () => {
if (this.closed) return;
const s = pc.connectionState;
this.log('info', `watch: connectionState=${s}`);
if (s === 'connected') this._setState('live');
else if (s === 'disconnected') this._setState('unstable');
else if (s === 'failed') this._finish('failed', 'ice_failed', true);
};
return pc;
}
async _applyOffer(sdp, reason) {
if (this.closed) return;
const pc = this._ensurePc();
if (this.state === 'requesting') this._setState('connecting');
if (pc.signalingState === 'have-remote-offer') {
// A newer offer superseded one we never answered: discard the stale one.
await pc.setRemoteDescription({ type: 'rollback' });
}
await pc.setRemoteDescription({ type: 'offer', sdp });
if (this.closed) return;
this.offersApplied += 1;
await this._flushRemoteCandidates();
const answer = await pc.createAnswer();
if (this.closed) return;
await pc.setLocalDescription(answer);
if (this.closed) return;
await this._send({ cmd: 'answer', args: { answer: pc.localDescription.sdp } });
if (this.closed) return;
this.answersSent += 1;
this.log('info', `watch: answer sent for ${reason} (#${this.answersSent})`);
const local = this.pendingLocal.splice(0);
for (const msg of local) this._send(msg).catch(() => {});
}
async _addRemoteCandidate(args) {
if (this.closed) return;
const sdp = typeof args.sdp === 'string' ? args.sdp : typeof args.candidate === 'string' ? args.candidate : '';
if (!sdp) return; // end-of-candidates marker
const mLine = Number(args.mLine);
const init = {
candidate: sdp,
sdpMid: args.mid === undefined || args.mid === null ? null : String(args.mid),
sdpMLineIndex: Number.isInteger(mLine) ? mLine : null,
};
if (init.sdpMid === null && init.sdpMLineIndex === null) init.sdpMLineIndex = 0;
if (!this.pc || !this.pc.remoteDescription) {
this.pendingRemote.push(init);
return;
}
await this._addCandidate(init);
}
async _flushRemoteCandidates() {
const list = this.pendingRemote.splice(0);
for (const init of list) await this._addCandidate(init);
}
async _addCandidate(init) {
const ufrag = candidateUfrag(init.candidate);
const current = remoteUfrags(this.pc.remoteDescription?.sdp ?? '');
if (ufrag && current.size > 0 && !current.has(ufrag)) {
// Belongs to an ICE generation replaced by a newer (reconnect) offer: skip deliberately.
this.staleCandidates += 1;
this.log('info', `watch: skipped candidate of previous ICE generation (${this.staleCandidates})`);
return;
}
try {
await this.pc.addIceCandidate(init);
this.remoteCandidatesAdded += 1;
} catch (err) {
this.candidateErrors += 1;
this.log('warn', `watch: current-generation candidate rejected (mid=${init.sdpMid} mLine=${init.sdpMLineIndex}): ${describe(err)}`);
}
}
/** No signaling leaves a closed session, so nothing can follow our is_remove=1. */
_send(json) {
if (this.closed) return Promise.resolve();
return this.signal.send(this.streamId, this.clientId, json).catch((err) => {
this.log('warn', `watch: signaling send failed: ${describe(err)}`);
throw err;
});
}
_enqueue(task) {
this.queue = this.queue.then(task).catch((err) => {
if (!this.closed) this._finish('failed', describe(err), true);
});
return this.queue;
}
_clearJoinTimer() {
if (this.joinTimer !== null) {
this.clearTimer(this.joinTimer);
this.joinTimer = null;
}
}
_finish(state, detail, sendLeave) {
if (this.closed) return;
this._clearJoinTimer();
this.pendingRemote = [];
this.pendingLocal = [];
if (this.pc) {
this.pc.onicecandidate = null;
this.pc.ontrack = null;
this.pc.onconnectionstatechange = null;
try {
this.pc.close();
} catch {
// already closed
}
}
this._setState(state, detail);
if (sendLeave) {
this.signal.leave(this.streamId, this.clientId).catch((err) => this.log('info', `watch: leave failed: ${describe(err)}`));
}
}
_setState(state, detail = '') {
this.state = state;
this.detail = detail;
this.onState(state, detail);
}
}
/** `ufrag` attribute of an ICE candidate line, if present. */
export function candidateUfrag(candidate) {
const m = / ufrag (\S+)/.exec(candidate);
return m ? m[1] : null;
}
/** All `a=ice-ufrag` values of the applied remote description. */
export function remoteUfrags(sdp) {
const set = new Set();
for (const m of sdp.matchAll(/^a=ice-ufrag:(\S+)/gm)) set.add(m[1]);
return set;
}
function describe(err) {
if (!err) return 'unknown';
if (typeof err === 'string') return err;
return err.code ? `${err.code}: ${err.message ?? ''}` : String(err.message ?? err);
}
-98
View File
@@ -1,98 +0,0 @@
// User-facing wording for bridge errors and plain-text rendering of TeamSpeak BBCode.
const ERROR_TEXT = {
bad_request: 'Некорректный запрос',
unknown_command: 'Команда не поддерживается',
profile_missing: 'Профиль ещё не создан',
profile_exists: 'Профиль уже существует',
identity_corrupt: 'Файл идентичности повреждён. Восстановите его из резервной копии (Настройки → Импорт).',
profile_corrupt: 'Файл профиля повреждён',
invalid_nickname: 'Никнейм должен содержать от 3 до 30 символов без управляющих символов',
nickname_required: 'Сначала задайте никнейм',
not_connected: 'Нет подключения к серверу',
already_connected: 'Уже подключено',
connect_failed: 'Не удалось подключиться',
server_error: 'Сервер отклонил действие',
audio_overflow: 'Очередь микрофона переполнена, часть звука пропущена',
audio_muted: 'Микрофон или звук выключены — передача не идёт',
audio_codec: 'Ошибка кодека Opus',
audio_codec_unsupported: 'Канал использует устаревший кодек (Speex/CELT): передача голоса невозможна',
rename_not_persisted: 'Сервер принял никнейм, но сохранить его на диск не удалось',
io: 'Ошибка доступа к каталогу данных',
internal: 'Внутренняя ошибка ядра',
timeout: 'Ядро не ответило вовремя',
core_unavailable: 'Ядро не запущено',
core_exited: 'Ядро завершило работу',
core_missing: 'Исполняемый файл ядра не найден',
connected: 'Сначала отключитесь от сервера',
forbidden: 'Действие запрещено',
};
/** "Код: сообщение сервера" with the TeamSpeak error id when present. */
export function errorText(error) {
if (!error) return 'Неизвестная ошибка';
const base = ERROR_TEXT[error.code] ?? error.message ?? error.code ?? 'Ошибка';
const ts = error.ts_error;
if (ts && (ts.message || ts.name)) {
const perm = ts.missing_permission !== undefined && ts.missing_permission !== null ? `, не хватает права ${ts.missing_permission}` : '';
return `${base}: ${ts.message || ts.name} (TS ${ts.id}${perm})`;
}
if (error.code === 'connect_failed' && error.message) return `${base}: ${error.message}`;
if (!ERROR_TEXT[error.code] && error.message) return error.message;
return base;
}
const BB_TAGS = /\[\/?(?:b|i|u|s|url(?:=[^\]]*)?|color(?:=[^\]]*)?|size(?:=[^\]]*)?|center|left|right|img|quote|code|list|\*|hr|table|tr|td|th)\]/gi;
/** TeamSpeak clients send BBCode; TeamsPeach shows the plain text and never interprets markup. */
export function stripBBCode(text) {
return String(text ?? '').replace(/\[url=([^\]]*)\]([\s\S]*?)\[\/url\]/gi, (_m, href, label) => {
const l = label.trim();
return l && l !== href ? `${l} (${href})` : href;
}).replace(BB_TAGS, '');
}
/** TeamSpeak spacer channels: "[cspacer]Title", "[*spacer]-", "[spacer0]…" (top level only). */
export function parseSpacer(name) {
const m = /^\[(c|r|\*)?spacer[^\]]*\](.*)$/i.exec(name);
if (!m) return null;
const kind = m[1] === 'c' ? 'center' : m[1] === 'r' ? 'right' : m[1] === '*' ? 'repeat' : 'left';
return { kind, text: m[2] };
}
export function shortUid(uid) {
if (!uid) return '';
return uid.length > 14 ? `${uid.slice(0, 8)}…${uid.slice(-4)}` : uid;
}
const KEY_NAMES = {
Space: 'Пробел',
Backquote: '`',
ControlLeft: 'Левый Ctrl',
ControlRight: 'Правый Ctrl',
AltLeft: 'Левый Alt',
AltRight: 'Правый Alt',
ShiftLeft: 'Левый Shift',
ShiftRight: 'Правый Shift',
MetaLeft: 'Левый Super',
MetaRight: 'Правый Super',
CapsLock: 'Caps Lock',
Tab: 'Tab',
};
export function keyLabel(code) {
if (!code) return 'не назначена';
if (KEY_NAMES[code]) return KEY_NAMES[code];
if (code.startsWith('Key')) return code.slice(3);
if (code.startsWith('Digit')) return code.slice(5);
if (code.startsWith('Numpad')) return `Num ${code.slice(6)}`;
return code;
}
export function pluralMembers(n) {
const mod10 = n % 10;
const mod100 = n % 100;
if (mod10 === 1 && mod100 !== 11) return `${n} участник`;
if (mod10 >= 2 && mod10 <= 4 && (mod100 < 12 || mod100 > 14)) return `${n} участника`;
return `${n} участников`;
}
-15
View File
@@ -1,15 +0,0 @@
import { $, h, icon } from './dom.js';
const MAX_TOASTS = 4;
/** Non-blocking notice in the polite live region. Errors stay longer. */
export function toast(text, kind = 'info') {
const host = $('#toasts');
const close = h('button', { class: 'icon-btn', type: 'button', 'aria-label': 'Закрыть уведомление' }, icon('x'));
const el = h('div', { class: 'toast', role: kind === 'error' ? 'alert' : 'status', dataset: { kind } }, h('span', { class: 'toast-text', text }), close);
const remove = () => el.remove();
close.addEventListener('click', remove);
host.appendChild(el);
while (host.children.length > MAX_TOASTS) host.firstElementChild.remove();
setTimeout(remove, kind === 'error' ? 10000 : 5000);
}
-345
View File
@@ -1,345 +0,0 @@
// Channel tree with members (TeamSpeak order): talking state, mute flags, server-configured group
// labels and icons, channel icons/banners, avatars and stream badges — all from real server data.
import { $, h, icon, reconcile, setText } from './dom.js';
import { S, isConnected } from './state.js';
import { call } from './core.js';
import { errorText, parseSpacer, pluralMembers } from './text.js';
import { toast } from './toast.js';
import { iconUrl, isBuiltinIcon, channelBannerUrl, avatarUrl } from './media.js';
let hooks = { openPrivate: () => {}, openSettings: () => {}, toggleWatch: () => {}, streamOf: () => null, watchingId: () => null };
let pendingPasswordCid = null;
export function initTree(h0) {
hooks = { ...hooks, ...h0 };
}
function sortClients(a, b) {
if (b.talk_power !== a.talk_power) return b.talk_power - a.talk_power;
return a.nickname.localeCompare(b.nickname, 'ru', { sensitivity: 'base' });
}
export function renderTree() {
const list = $('#tree');
const empty = $('#tree-empty');
if (!isConnected()) {
list.replaceChildren();
empty.hidden = false;
setText(empty, S.conn.state === 'connecting' ? 'Подключение…' : 'Каналы появятся после подключения к серверу.');
pendingPasswordCid = null;
return;
}
empty.hidden = true;
const snap = S.snap;
const byChannel = new Map();
for (const c of snap.clients) {
if (c.client_type === 'query') continue;
if (!byChannel.has(c.channel_id)) byChannel.set(c.channel_id, []);
byChannel.get(c.channel_id).push(c);
}
const items = [];
for (const ch of snap.channels) {
const members = (byChannel.get(ch.id) ?? []).sort(sortClients);
const spacer = ch.parent_id === 0 ? parseSpacer(ch.name) : null;
if (spacer) items.push({ type: 'spacer', ch, spacer });
else items.push({ type: 'channel', ch, count: members.length });
if (pendingPasswordCid === ch.id) items.push({ type: 'password', ch });
for (const cl of members) items.push({ type: 'member', cl, depth: ch.depth + 1 });
}
reconcile(list, items, keyOf, createRow, updateRow);
}
function keyOf(item) {
switch (item.type) {
case 'member': return `u:${item.cl.id}`;
case 'password': return `p:${item.ch.id}`;
case 'spacer': return `s:${item.ch.id}`;
default: return `c:${item.ch.id}`;
}
}
function createRow(item) {
switch (item.type) {
case 'spacer':
return h('li', { class: 'tree-row spacer-row', role: 'presentation' });
case 'password':
return createPasswordRow(item.ch);
case 'member':
return createMemberRow();
default:
return createChannelRow();
}
}
function updateRow(el, item) {
switch (item.type) {
case 'spacer': {
el.style.setProperty('--depth', String(item.ch.depth));
el.dataset.kind = item.spacer.kind;
const text = item.spacer.kind === 'repeat' ? item.spacer.text.repeat(Math.max(1, Math.ceil(60 / Math.max(1, item.spacer.text.length)))) : item.spacer.text;
setText(el, text);
break;
}
case 'password':
el.style.setProperty('--depth', String(item.ch.depth));
break;
case 'member':
updateMemberRow(el, item.cl, item.depth);
break;
default:
updateChannelRow(el, item.ch, item.count);
}
}
// ---------- channels ----------
function createChannelRow() {
const btn = h(
'button',
{ class: 'row-btn', type: 'button' },
icon('channel'),
h('span', { class: 'row-label' }),
h('span', { class: 'channel-icon', 'aria-hidden': 'true' }),
h('span', { class: 'channel-meta' }),
);
const li = h('li', { class: 'tree-row channel-row' }, btn);
btn.addEventListener('click', () => joinChannel(Number(li.dataset.cid)));
return li;
}
function updateChannelRow(li, ch, count) {
li.dataset.cid = String(ch.id);
li.style.setProperty('--depth', String(ch.depth));
const current = ch.id === S.snap.own_channel_id;
li.dataset.current = String(current);
const btn = li.firstElementChild;
const [ic, label, chIcon, meta] = btn.children;
ic.firstElementChild.setAttribute('href', ch.has_password ? '#i-lock' : '#i-channel');
setText(label, ch.name);
const max = ch.max_clients;
setText(meta, max !== null && max !== undefined && max >= 0 && count > 0 ? `${count}/${max}` : max === 0 ? 'закрыт' : '');
const parts = [ch.name];
if (ch.has_password) parts.push('с паролем');
parts.push(pluralMembers(count));
if (current) parts.push('вы здесь');
btn.setAttribute('aria-label', parts.join(', '));
btn.title = ch.topic ? ch.topic : current ? 'Вы в этом канале' : 'Перейти в канал';
if (current) btn.setAttribute('aria-current', 'location');
else btn.removeAttribute('aria-current');
// Channel icon and banner are the server's own files; nothing is drawn when the server has none.
const iconKey = String(ch.icon_id ?? '');
if (chIcon.dataset.sig !== iconKey) {
chIcon.dataset.sig = iconKey;
chIcon.replaceChildren();
iconUrl(ch.icon_id).then((url) => {
if (url && chIcon.dataset.sig === iconKey) chIcon.appendChild(h('img', { src: url, alt: '', draggable: 'false' }));
});
}
const bannerKey = ch.banner_url ?? '';
if (btn.dataset.banner !== bannerKey) {
btn.dataset.banner = bannerKey;
li.classList.remove('has-banner');
btn.style.removeProperty('--banner');
channelBannerUrl(ch).then((url) => {
if (!url || btn.dataset.banner !== bannerKey) return;
btn.style.setProperty('--banner', `url("${url}")`);
li.classList.add('has-banner');
});
}
}
async function joinChannel(cid) {
if (!isConnected() || cid === S.snap.own_channel_id) return;
const ch = S.snap.channels.find((c) => c.id === cid);
if (!ch) return;
if (ch.has_password) {
pendingPasswordCid = pendingPasswordCid === cid ? null : cid;
renderTree();
const input = document.querySelector(`[data-key="p:${cid}"] input`);
if (input) input.focus();
return;
}
try {
await call('join_channel', { channel_id: cid });
} catch (err) {
toast(`Не удалось перейти в «${ch.name}»: ${errorText(err)}`, 'error');
}
}
function createPasswordRow(ch) {
const input = h('input', { type: 'password', autocomplete: 'off', 'aria-label': `Пароль канала ${ch.name}`, placeholder: 'Пароль канала' });
const cancel = h('button', { class: 'btn btn-ghost', type: 'button' }, 'Отмена');
const form = h('form', { novalidate: true }, input, h('button', { class: 'btn btn-primary', type: 'submit' }, 'Войти'), cancel);
const li = h('li', { class: 'tree-row password-row' }, form);
const close = () => {
pendingPasswordCid = null;
renderTree();
};
cancel.addEventListener('click', close);
input.addEventListener('keydown', (e) => {
if (e.key === 'Escape') close();
});
form.addEventListener('submit', async (e) => {
e.preventDefault();
try {
await call('join_channel', { channel_id: ch.id, password: input.value });
close();
} catch (err) {
input.setAttribute('aria-invalid', 'true');
toast(`Не удалось войти в «${ch.name}»: ${errorText(err)}`, 'error');
input.select();
}
});
return li;
}
// ---------- members ----------
function createMemberRow() {
const btn = h(
'button',
{ class: 'row-btn', type: 'button' },
h('span', { class: 'avatar', 'aria-hidden': 'true' }, h('span', { class: 'status-dot' })),
h('span', { class: 'group-label', hidden: true }),
h('span', { class: 'row-label' }),
h('span', { class: 'group-label', hidden: true }),
h('span', { class: 'member-tag' }),
h('span', { class: 'member-flags' }),
h('span', { class: 'member-badges' }),
);
const li = h('li', { class: 'tree-row member-row' }, btn);
btn.addEventListener('click', () => {
const id = Number(li.dataset.clid);
if (li.dataset.self === 'true') hooks.openSettings();
else hooks.openPrivate(id);
});
return li;
}
/** A client's server groups (catalog order) plus its channel group, resolved from the snapshot. */
function groupsOf(cl) {
const ids = new Set(cl.server_groups ?? []);
const server = (S.snap.server_groups ?? []).filter((g) => ids.has(g.id));
const channel = (S.snap.channel_groups ?? []).find((g) => g.id === cl.channel_group_id) ?? null;
return { server, channel };
}
function updateMemberRow(li, cl, depth) {
li.dataset.clid = String(cl.id);
li.style.setProperty('--depth', String(depth));
li.dataset.self = String(cl.is_self);
const talking = cl.is_self ? S.audio.transmitting : S.talking.has(cl.id);
li.dataset.talking = String(talking);
const btn = li.firstElementChild;
const [avatar, before, label, after, tag, flags, badges] = btn.children;
setText(label, cl.nickname);
setText(tag, cl.is_self ? 'вы' : '');
// Group names appear next to the nickname exactly where each group's name_mode puts them.
const { server: groups, channel: cgroup } = groupsOf(cl);
const named = cgroup ? [...groups, cgroup] : groups;
const beforeText = named.filter((g) => g.name_mode === 'before').map((g) => g.name).join(' · ');
const afterText = named.filter((g) => g.name_mode === 'after').map((g) => g.name).join(' · ');
setText(before, beforeText);
before.title = beforeText;
before.hidden = !beforeText;
setText(after, afterText);
after.title = afterText;
after.hidden = !afterText;
const flagIcons = [];
const states = [];
if (cl.output_muted) {
flagIcons.push(['headphones-off', 'flag-muted', 'Звук выключен']);
states.push('звук выключен');
} else if (cl.input_muted) {
flagIcons.push(['mic-off', 'flag-muted', 'Микрофон выключен']);
states.push('микрофон выключен');
}
if (!cl.input_hardware && !cl.input_muted) {
flagIcons.push(['mic-off', '', 'Нет микрофона']);
states.push('нет микрофона');
}
if (cl.away) {
flagIcons.push(['moon', '', cl.away_message ? `Отошёл: ${cl.away_message}` : 'Отошёл']);
states.push(cl.away_message ? `отошёл: ${cl.away_message}` : 'отошёл');
}
if (cl.is_recording) {
flagIcons.push(['record', 'flag-rec', 'Записывает разговор']);
states.push('записывает');
}
const flagKey = flagIcons.map((f) => f.join(':')).join('|');
if (flags.dataset.sig !== flagKey) {
flags.dataset.sig = flagKey;
flags.replaceChildren(...flagIcons.map(([name, cls, title]) => h('span', { title }, icon(name, cls))));
}
// Group icons: custom files from the server; built-in ids have no file, shown as a neutral named badge.
const iconGroups = named.filter((g) => g.icon_id);
const badgeKey = `${iconGroups.map((g) => `${g.id}:${g.icon_id}`).join(',')}|${cl.country ?? ''}`;
if (badges.dataset.sig !== badgeKey) {
badges.dataset.sig = badgeKey;
badges.replaceChildren(
...iconGroups.map((g) => groupBadge(g)),
...(cl.country ? [h('span', { class: 'country', title: `Страна: ${cl.country}`, text: cl.country })] : []),
);
}
const avatarKey = `${cl.avatar_hash ?? ''}|${JSON.stringify(cl.myts_avatars ?? null)}`;
if (avatar.dataset.sig !== avatarKey) {
avatar.dataset.sig = avatarKey;
avatar.querySelector('img')?.remove();
avatar.classList.remove('has-image');
avatarUrl(cl).then((url) => {
if (!url || avatar.dataset.sig !== avatarKey) return;
avatar.prepend(h('img', { src: url, alt: '', draggable: 'false' }));
avatar.classList.add('has-image');
});
}
if (talking) states.unshift('говорит');
const groupNames = groups.map((g) => g.name);
btn.setAttribute('aria-label', `${cl.nickname}${cl.is_self ? ' (вы)' : ''}${groupNames.length ? `, группы: ${groupNames.join(', ')}` : ''}${states.length ? `, ${states.join(', ')}` : ''}${cl.is_self ? '. Открыть настройки профиля' : '. Написать личное сообщение'}`);
btn.title = [cl.description ? `Описание: ${cl.description}` : '', groupNames.length ? `Группы: ${groupNames.join(', ')}` : '', cl.is_self ? 'Настройки профиля' : 'Написать личное сообщение'].filter(Boolean).join('\n');
const stream = hooks.streamOf(cl.id);
let watch = li.querySelector('.watch-btn');
if (stream && !cl.is_self) {
if (!watch) {
watch = h('button', { class: 'watch-btn', type: 'button' }, icon('monitor'), h('span', { text: 'Смотреть' }));
watch.addEventListener('click', () => {
const s = hooks.streamOf(Number(li.dataset.clid));
if (s) hooks.toggleWatch(s);
});
li.appendChild(watch);
}
const watching = hooks.watchingId() === stream.id;
watch.setAttribute('aria-pressed', String(watching));
setText(watch.lastElementChild, watching ? 'Смотрите' : 'Смотреть');
watch.setAttribute('aria-label', `${watching ? 'Прекратить просмотр' : 'Смотреть'} трансляцию ${cl.nickname}${stream.name ? `: ${stream.name}` : ''}`);
watch.title = stream.name || 'Трансляция экрана';
} else if (watch) {
watch.remove();
}
}
function groupBadge(group) {
const el = h('span', { class: 'group-icon', title: group.name, role: 'img', 'aria-label': group.name });
if (isBuiltinIcon(group.icon_id)) {
el.appendChild(icon('shield'));
return el;
}
iconUrl(group.icon_id).then((url) => {
el.appendChild(url ? h('img', { src: url, alt: '', draggable: 'false' }) : icon('shield'));
});
return el;
}
/** Cheap talking update without a full reconcile. */
export function updateTalking(clientId) {
const li = document.querySelector(`#tree [data-key="u:${clientId}"]`);
if (!li || !S.snap) return;
const cl = S.snap.clients.find((c) => c.id === clientId);
if (cl) updateMemberRow(li, cl, Number(li.style.getPropertyValue('--depth')) || 0);
}
-247
View File
@@ -1,247 +0,0 @@
// Voice: microphone capture → core (gated by mute/deafen/PTT/open mic), core mix → speakers,
// device selection and push-to-talk keys.
import { $, setText } from './dom.js';
import { S, isConnected, ownChannel } from './state.js';
import { tp, log } from './core.js';
import { AudioEngine } from './audio/engine.js';
import { toast } from './toast.js';
import { keyLabel } from './text.js';
export const voiceStats = { framesSent: 0, bursts: 0, framesPlayed: 0, level: 0 };
let engine = null;
let sending = false;
let micTest = false;
let meterRaf = 0;
let assigningPtt = null;
let hooks = { onPtt: () => {}, onPttAssigned: () => {}, onTransmitChanged: () => {} };
export function initVoice(h0) {
hooks = { ...hooks, ...h0 };
engine = new AudioEngine({
onFrame,
onError: (e) => toast(e.message, 'error'),
log,
});
tp.onAudio(({ pcm }) => {
voiceStats.framesPlayed += 1;
engine.pushPlayback(pcm);
});
window.addEventListener('keydown', onKeyDown, true);
window.addEventListener('keyup', onKeyUp, true);
window.addEventListener('blur', () => setPtt(false));
navigator.mediaDevices.addEventListener('devicechange', () => refreshDevices());
const btn = $('#btn-ptt');
btn.addEventListener('pointerdown', (e) => {
if (e.button !== 0) return;
btn.setPointerCapture(e.pointerId);
setPtt(true);
});
const release = () => setPtt(false);
btn.addEventListener('pointerup', release);
btn.addEventListener('pointercancel', release);
btn.addEventListener('lostpointercapture', release);
btn.addEventListener('keydown', (e) => {
if ((e.key === ' ' || e.key === 'Enter') && !e.repeat) {
e.preventDefault();
setPtt(true);
}
});
btn.addEventListener('keyup', (e) => {
if (e.key === ' ' || e.key === 'Enter') {
e.preventDefault();
setPtt(false);
}
});
}
/** Creates the AudioContext and applies output prefs; safe to call repeatedly. */
export async function startAudio() {
try {
await engine.init();
engine.setVoiceVolume(S.prefs.voiceVolume);
if (S.prefs.outputDeviceId) await engine.setOutputDevice(S.prefs.outputDeviceId).catch((err) => toast(`Устройство вывода недоступно: ${err.message}`, 'error'));
} catch (err) {
toast(`Звук недоступен: ${err.message}`, 'error');
log('error', `audio init failed: ${err.message}`);
}
}
function channelCanTransmit() {
const ch = ownChannel();
return !ch || ch.codec === null || ch.codec === undefined || ch.codec === 'opus_voice' || ch.codec === 'opus_music';
}
export function shouldTransmit() {
return isConnected()
&& !S.audio.input_muted
&& !S.audio.output_muted
&& (S.prefs.transmitMode === 'open' || S.ptt)
&& channelCanTransmit();
}
function onFrame(pcm, rms, peak) {
voiceStats.level = peak;
if (micTest && !meterRaf) meterRaf = requestAnimationFrame(drawMeter);
if (shouldTransmit()) {
tp.sendAudioFrame(new Uint8Array(pcm));
voiceStats.framesSent += 1;
if (!sending) {
sending = true;
voiceStats.bursts += 1;
hooks.onTransmitChanged();
}
} else if (sending) {
tp.endAudio();
sending = false;
hooks.onTransmitChanged();
}
}
function drawMeter() {
meterRaf = 0;
const db = voiceStats.level > 0 ? 20 * Math.log10(voiceStats.level) : -100;
const pct = Math.max(0, Math.min(100, ((db + 60) / 60) * 100));
$('#mic-meter').style.width = `${pct.toFixed(0)}%`;
}
/** Capture runs while connected (or during the settings mic test). */
export async function syncCapture() {
const want = isConnected() || micTest;
if (want && !engine.capturing) {
try {
await engine.startCapture({
deviceId: S.prefs.inputDeviceId,
echoCancellation: S.prefs.echoCancellation,
noiseSuppression: S.prefs.noiseSuppression,
autoGainControl: S.prefs.autoGainControl,
});
refreshDevices();
} catch (err) {
toast(`Нет доступа к микрофону: ${err.message || err.name}`, 'error');
log('error', `capture failed: ${err.name} ${err.message}`);
}
} else if (!want && engine.capturing) {
engine.stopCapture();
if (sending) {
tp.endAudio();
sending = false;
}
}
}
export async function restartCapture() {
if (!engine.capturing) return;
engine.stopCapture();
await syncCapture();
}
export function setMicTest(on) {
micTest = on;
if (!on) $('#mic-meter').style.width = '0%';
return syncCapture();
}
export function onOutputMuted(muted) {
if (muted) engine.flushPlayback();
}
export function setVoiceVolume(pct) {
engine.setVoiceVolume(pct);
}
export async function setOutputDevice(id) {
await engine.setOutputDevice(id);
}
export function playbackStats() {
return engine.playbackStats();
}
// ---------- devices ----------
export async function refreshDevices() {
let devices = [];
try {
devices = await navigator.mediaDevices.enumerateDevices();
} catch {
return;
}
fillSelect($('#input-device'), devices.filter((d) => d.kind === 'audioinput'), S.prefs.inputDeviceId, 'Микрофон');
fillSelect($('#output-device'), devices.filter((d) => d.kind === 'audiooutput'), S.prefs.outputDeviceId, 'Динамики');
}
function fillSelect(select, list, selected, fallback) {
const options = [{ value: '', label: 'Системное устройство по умолчанию' }];
let n = 0;
for (const d of list) {
if (d.deviceId === 'default' || d.deviceId === 'communications' || d.deviceId === '') continue;
n += 1;
options.push({ value: d.deviceId, label: d.label || `${fallback} ${n}` });
}
if (selected && !options.some((o) => o.value === selected)) options.push({ value: selected, label: 'Выбранное устройство (не подключено)' });
select.replaceChildren(...options.map((o) => {
const opt = document.createElement('option');
opt.value = o.value;
opt.textContent = o.label;
return opt;
}));
select.value = selected || '';
}
// ---------- push-to-talk ----------
function isTextField(el) {
return el instanceof HTMLTextAreaElement || (el instanceof HTMLInputElement && !['checkbox', 'radio', 'range', 'button', 'submit'].includes(el.type)) || el?.isContentEditable;
}
function onKeyDown(e) {
if (assigningPtt) {
e.preventDefault();
e.stopPropagation();
const done = assigningPtt;
assigningPtt = null;
done(e.key === 'Escape' ? null : e.code);
return;
}
if (e.code !== S.prefs?.pttCode || e.repeat) return;
if (S.prefs.transmitMode !== 'ptt') return;
if (isTextField(e.target) && e.key.length === 1) return;
setPtt(true);
}
function onKeyUp(e) {
if (e.code === S.prefs?.pttCode) setPtt(false);
}
export function setPtt(down) {
if (S.ptt === down) return;
S.ptt = down;
const btn = $('#btn-ptt');
btn.setAttribute('aria-pressed', String(down));
setText(btn, down ? 'Говорите…' : 'Удерживайте, чтобы говорить');
hooks.onPtt(down);
}
/** Resolves with a KeyboardEvent.code, or null when cancelled with Escape. */
export function capturePttKey() {
return new Promise((resolve) => {
assigningPtt = resolve;
});
}
export function transmitHint() {
if (!S.prefs) return '';
if (S.prefs.transmitMode === 'open') return 'Открытый микрофон';
return `Клавиша: ${keyLabel(S.prefs.pttCode)}`;
}
export function isSending() {
return sending;
}
export function channelCodecProblem() {
const ch = ownChannel();
if (!ch || channelCanTransmit()) return null;
return ch.codec;
}
-404
View File
@@ -1,404 +0,0 @@
// TS6 screenshare: discovery (stream_list + notifications), one viewing session, the viewer panel.
import { $, setIcon, setText } from './dom.js';
import { S, isConnected, clientById } from './state.js';
import { call, log } from './core.js';
import { StreamDirectory } from './stream/directory.js';
import { StreamViewerSession } from './stream/session.js';
import { toast } from './toast.js';
import { errorText } from './text.js';
// Same public STUN endpoints the official TS6 client ships with (see docs/evidence/ts6-official-client.md).
const ICE_SERVERS = [{ urls: ['stun:turn.teamspeak.com:3478', 'stun:turn2.teamspeak.com:3478'] }];
export const directory = new StreamDirectory();
let session = null;
let current = null; // { id, clientId, name, nickname }
let media = null;
let statsTimer = null;
let attachTimer = null;
let lastCodecLogged = '';
let sfuToastShown = false;
let hooks = { onChange: () => {}, savePrefs: () => {} };
let listTimer = null;
let listFull = false;
const listClients = new Set();
let knownChannelPeers = new Set();
let knownOwnChannel = null;
function emptyStats() {
return {
codec: '', fmtp: '', decoder: '', powerEfficientDecoder: null, width: 0, height: 0, fps: 0,
framesDecoded: 0, videoPackets: 0, videoBytes: 0, packetsLost: 0, keyFrames: 0,
audioTrackPresent: false, streamAdvertisesAudio: null, audioCodec: '', inboundAudioPackets: 0, inboundAudioBytes: 0,
remoteCandidatesAdded: 0, staleCandidates: 0, candidateErrors: 0, offersApplied: 0, answersSent: 0, pair: '',
sinkId: '', sinkError: '',
};
}
export const watchStats = { state: 'idle', ...emptyStats() };
export function initWatch(h0) {
hooks = { ...hooks, ...h0 };
const video = $('#stream-video');
const volume = $('#stream-volume');
volume.addEventListener('input', () => applyVolume());
volume.addEventListener('change', () => hooks.savePrefs({ streamVolume: Number(volume.value) }));
$('#stream-mute').addEventListener('click', () => {
const btn = $('#stream-mute');
btn.setAttribute('aria-pressed', String(btn.getAttribute('aria-pressed') !== 'true'));
applyVolume();
});
$('#stream-fullscreen').addEventListener('click', () => {
const view = $('#stream-view');
if (document.fullscreenElement) document.exitFullscreen();
else view.requestFullscreen().catch((err) => toast(`Полноэкранный режим недоступен: ${err.message}`, 'error'));
});
$('#stream-stop').addEventListener('click', () => stopWatching());
video.addEventListener('resize', () => updateStatsLine());
// The output device is applied to a running player only; an element without media has nothing to route.
video.addEventListener('playing', () => applySink());
}
export function streamOf(clientId) {
return directory.byClient(clientId);
}
export function watchingId() {
return session && !session.closed ? current.id : null;
}
export function toggleWatch(stream) {
if (session && !session.closed && current && current.id === stream.id) {
stopWatching();
return;
}
startWatching(stream);
}
// ---------- discovery ----------
/** Called for every snapshot: asks newly seen channel members whether they stream. */
export function onSnapshot() {
const snap = S.snap;
const present = new Set(snap.clients.map((c) => c.id));
let changed = directory.prune(present);
const peers = new Set(snap.clients.filter((c) => c.channel_id === snap.own_channel_id && !c.is_self && c.client_type !== 'query').map((c) => c.id));
if (knownOwnChannel !== snap.own_channel_id) {
knownOwnChannel = snap.own_channel_id;
scheduleList(null);
} else {
for (const id of peers) if (!knownChannelPeers.has(id)) scheduleList(id);
}
knownChannelPeers = peers;
if (session && !session.closed && current && !present.has(current.clientId)) {
session.terminate('streamer_left');
changed = true;
}
if (changed) hooks.onChange();
}
function scheduleList(clientId) {
if (clientId === null) listFull = true;
else listClients.add(clientId);
if (listTimer) return;
listTimer = setTimeout(runList, 300);
}
async function runList() {
listTimer = null;
if (!isConnected()) return;
const full = listFull;
const ids = Array.from(listClients);
listFull = false;
listClients.clear();
const requests = full ? [undefined] : ids.map((id) => ({ client_id: id }));
for (const args of requests) {
try {
const result = await call('stream_list', args);
let changed = false;
for (const r of result.results ?? []) {
// A client that is not streaming answers requeststreaminfo with an error only.
if (!r.ok && directory.byClient(r.client_id)) {
changed = directory.handle('notifystreamstopped', [{ clid: String(r.client_id) }]) || changed;
}
}
if (changed) hooks.onChange();
} catch (err) {
log('warn', `stream_list failed: ${err.code}`);
}
}
}
/** `stream` event from the core (bridge §5). */
export function onStreamEvent(evt) {
const name = evt.name;
const items = Array.isArray(evt.items) ? evt.items : [];
log('info', `stream event ${name} items=${items.length} keys=${items[0] ? Object.keys(items[0]).sort().join(',') : '-'}`);
if (session && !session.closed) {
for (const item of items) session.handle(name, item);
}
if (name === 'notifysfuaccessinfo' && !sfuToastShown) {
sfuToastShown = true;
toast('Сервер передаёт трансляции через SFU. TeamsPeach поддерживает только прямые (P2P) трансляции TeamSpeak 6.', 'error');
}
if (directory.handle(name, items)) hooks.onChange();
}
export function onDisconnected() {
if (session && !session.closed) session.terminate('disconnected');
directory.clear();
knownChannelPeers = new Set();
knownOwnChannel = null;
sfuToastShown = false;
}
// ---------- viewing ----------
/** Core-backed signaling for a session (bridge §4.12–4.14). */
const coreTransport = {
join: (id, clid, msg) => call('stream_join', { stream_id: id, client_id: clid, message: msg }),
send: (id, clid, json) => call('stream_signal', { stream_id: id, client_id: clid, json }),
leave: (id, clid) => call('stream_leave', { stream_id: id, client_id: clid }),
};
/**
* Starts viewing `stream`. `transport` is the signaling path; production always uses the core.
* Every async continuation below checks that its session is still the current one.
*/
export function startWatching(stream, transport = coreTransport) {
stopWatching();
const streamer = clientById(stream.clientId);
current = { id: stream.id, clientId: stream.clientId, name: stream.name, nickname: streamer?.nickname ?? stream.nickname ?? '?' };
const sessionMedia = new MediaStream();
media = sessionMedia;
const video = $('#stream-video');
applyVolume();
lastCodecLogged = '';
Object.assign(watchStats, emptyStats());
watchStats.streamAdvertisesAudio = stream.fields?.audio === '1' ? true : stream.fields?.audio === '0' ? false : null;
$('#stream-view').hidden = false;
setText($('#stream-title'), current.name ? `${current.nickname} — ${current.name}` : `Трансляция ${current.nickname}`);
setText($('#stream-stats'), '');
const own = new StreamViewerSession({
streamId: stream.id,
clientId: stream.clientId,
ownClientId: S.snap?.own_client_id ?? 0,
message: S.profile?.nickname ?? '',
signal: transport,
createPeerConnection: (config) => new RTCPeerConnection(config),
iceServers: ICE_SERVERS,
onState: (state, detail) => {
if (session === own) onSessionState(state, detail);
},
onTrack: (track) => {
if (session !== own) return;
sessionMedia.addTrack(track);
if (track.kind === 'audio') watchStats.audioTrackPresent = true;
track.addEventListener('ended', () => sessionMedia.removeTrack(track));
// Both tracks of an offer arrive in one setRemoteDescription; attach the stream once after them.
// Later tracks are picked up by the element from the same MediaStream.
if (attachTimer === null && video.srcObject !== sessionMedia) {
attachTimer = setTimeout(() => {
attachTimer = null;
if (session !== own || own.closed || media !== sessionMedia) return;
video.srcObject = sessionMedia;
video.play().catch((err) => log('warn', `watch: play() rejected: ${err.name}`));
}, 0);
}
},
log,
});
session = own;
hooks.onChange();
own.start();
statsTimer = setInterval(pollStats, 1500);
}
export function stopWatching() {
if (session && !session.closed) session.stop();
session = null;
current = null;
teardownMedia();
$('#stream-view').hidden = true;
watchStats.state = 'idle';
hooks.onChange();
}
function teardownMedia() {
clearInterval(statsTimer);
statsTimer = null;
clearTimeout(attachTimer);
attachTimer = null;
const video = $('#stream-video');
video.srcObject = null;
if (media) for (const t of media.getTracks()) t.stop();
media = null;
if (document.fullscreenElement) document.exitFullscreen().catch(() => {});
}
const STATE_TEXT = {
requesting: 'Запрос отправлен. Ждём ответа стримера…',
connecting: 'Соединение со стримером…',
live: '',
unstable: 'Связь со стримером прервалась, ждём восстановления…',
declined: 'Стример отклонил запрос на просмотр.',
removed: 'Стример убрал вас из зрителей.',
stopped: '',
};
function failureText(detail) {
switch (detail) {
case 'no_response': return 'Стример не ответил на запрос за 90 секунд.';
case 'ice_failed': return 'Не удалось установить прямое соединение со стримером. Для просмотра нужен прямой сетевой доступ к его компьютеру (через STUN, без TURN).';
default: return `Ошибка трансляции: ${detail}`;
}
}
function endedText(detail) {
switch (detail) {
case 'stream_stopped': return 'Трансляция завершена.';
case 'streamer_left': return 'Стример покинул сервер.';
case 'disconnected': return 'Соединение с сервером потеряно.';
default: return 'Трансляция завершена.';
}
}
function onSessionState(state, detail) {
watchStats.state = state;
log('info', `watch: state ${state}${detail ? ` (${detail})` : ''}`);
if (state === 'stopped') return;
let text = STATE_TEXT[state];
if (state === 'failed') text = failureText(detail);
else if (state === 'ended') text = endedText(detail);
else if (state === 'unsupported') text = 'Эта трансляция идёт через SFU-сервер TeamSpeak. TeamsPeach поддерживает только прямые (P2P) трансляции.';
else if (state === 'declined' && detail) text = `${STATE_TEXT.declined} ${detail}`;
if (state === 'live' && watchStats.framesDecoded === 0) text = 'Соединение установлено, ждём первый кадр…';
setText($('#stream-overlay'), text ?? '');
const terminal = ['declined', 'ended', 'removed', 'failed', 'unsupported'].includes(state);
setText($('#stream-stop'), terminal ? 'Закрыть' : state === 'requesting' ? 'Отменить' : 'Прекратить просмотр');
if (terminal) {
teardownMedia();
if (state !== 'ended' || detail !== 'disconnected') toast(text, state === 'ended' ? 'info' : 'error');
}
hooks.onChange();
}
async function pollStats() {
const own = session;
const pc = own?.pc;
if (!own || !pc || own.closed) return;
let report;
try {
report = await pc.getStats();
} catch {
return;
}
// The user may have stopped or switched streams while getStats() was pending.
if (session !== own || own.closed) return;
let inbound = null;
let audioIn = null;
let pair = null;
const codecs = new Map();
report.forEach((s) => {
if (s.type === 'inbound-rtp' && s.kind === 'video') inbound = s;
if (s.type === 'inbound-rtp' && s.kind === 'audio') audioIn = s;
if (s.type === 'candidate-pair' && s.nominated && s.state === 'succeeded') pair = s;
if (s.type === 'codec') codecs.set(s.id, s);
});
watchStats.remoteCandidatesAdded = own.remoteCandidatesAdded;
watchStats.staleCandidates = own.staleCandidates;
watchStats.candidateErrors = own.candidateErrors;
watchStats.offersApplied = own.offersApplied;
watchStats.answersSent = own.answersSent;
if (pair) {
const local = report.get(pair.localCandidateId);
const remote = report.get(pair.remoteCandidateId);
watchStats.pair = `${local?.candidateType ?? '?'}/${local?.protocol ?? '?'} → ${remote?.candidateType ?? '?'}`;
}
if (audioIn) {
const ac = codecs.get(audioIn.codecId);
watchStats.audioCodec = ac ? ac.mimeType : '';
watchStats.inboundAudioPackets = audioIn.packetsReceived ?? 0;
watchStats.inboundAudioBytes = audioIn.bytesReceived ?? 0;
}
if (!inbound) return;
watchStats.videoPackets = inbound.packetsReceived ?? 0;
watchStats.videoBytes = inbound.bytesReceived ?? 0;
watchStats.packetsLost = inbound.packetsLost ?? 0;
watchStats.keyFrames = inbound.keyFramesDecoded ?? 0;
const codec = codecs.get(inbound.codecId);
watchStats.codec = codec ? codec.mimeType.replace(/^video\//, '') : '';
watchStats.fmtp = codec?.sdpFmtpLine ?? '';
watchStats.width = inbound.frameWidth ?? 0;
watchStats.height = inbound.frameHeight ?? 0;
watchStats.fps = Math.round(inbound.framesPerSecond ?? 0);
const firstFrame = watchStats.framesDecoded === 0 && (inbound.framesDecoded ?? 0) > 0;
watchStats.framesDecoded = inbound.framesDecoded ?? 0;
watchStats.decoder = inbound.decoderImplementation ?? '';
watchStats.powerEfficientDecoder = typeof inbound.powerEfficientDecoder === 'boolean' ? inbound.powerEfficientDecoder : null;
if (firstFrame && own.state === 'live') setText($('#stream-overlay'), '');
const sig = `${watchStats.codec} ${watchStats.fmtp}`;
if (codec && sig !== lastCodecLogged) {
lastCodecLogged = sig;
log('info', `watch: negotiated ${codec.mimeType} fmtp="${codec.sdpFmtpLine ?? ''}" decoder=${watchStats.decoder}`);
}
updateStatsLine();
}
function updateStatsLine() {
if (!session) return;
const parts = [];
if (watchStats.codec) parts.push(watchStats.codec);
if (watchStats.width) parts.push(`${watchStats.width}×${watchStats.height}`);
if (watchStats.fps) parts.push(`${watchStats.fps} к/с`);
if (session.state === 'live') {
if (watchStats.streamAdvertisesAudio === false) parts.push('стример не передаёт звук');
else if (watchStats.inboundAudioPackets > 0) parts.push('со звуком');
}
setText($('#stream-stats'), parts.join(' · '));
}
export function applyVolume() {
const video = $('#stream-video');
const volume = $('#stream-volume');
const muted = $('#stream-mute').getAttribute('aria-pressed') === 'true';
video.volume = Number(volume.value) / 100;
video.muted = muted || S.audio.output_muted;
setText($('#stream-volume-value'), `${volume.value}%`);
setIcon($('#stream-mute').firstElementChild, muted ? 'speaker-off' : 'speaker');
$('#stream-mute').title = muted ? 'Включить звук трансляции' : 'Выключить звук трансляции';
}
let sinkChain = Promise.resolve();
/**
* Routes stream audio to the selected output device. Calls are serialized and only issued for a
* playing element whose current sink differs; a failure is reported with the device name and the
* element keeps playing on its current device.
*/
export function applySink() {
const video = $('#stream-video');
if (typeof video.setSinkId !== 'function' || !S.prefs) return;
sinkChain = sinkChain.then(async () => {
const own = session;
const target = S.prefs.outputDeviceId || '';
if (!own || !video.srcObject || video.sinkId === target) {
watchStats.sinkId = video.sinkId;
return;
}
try {
await video.setSinkId(target);
if (session !== own) return;
watchStats.sinkId = video.sinkId;
watchStats.sinkError = '';
log('info', `watch: audio output set (${target ? 'selected device' : 'system default'})`);
} catch (err) {
log('warn', `watch: setSinkId failed ${err.name}: ${err.message}`);
if (session !== own) return;
watchStats.sinkError = `${err.name}: ${err.message}`;
const label = Array.from($('#output-device').options).find((o) => o.value === target)?.textContent || 'выбранное устройство';
toast(`Звук трансляции не удалось направить на «${label}» (${err.name}). Он продолжает играть через текущее устройство; выберите другое в Настройки → Звук.`, 'error');
}
});
}
-692
View File
@@ -1,692 +0,0 @@
/* TeamsPeach — restrained working UI: warm neutrals, one peach accent, state colours that mean something. */
:root {
color-scheme: light dark;
--font: system-ui, -apple-system, "Segoe UI", "Noto Sans", Ubuntu, Cantarell, "Helvetica Neue", Arial, sans-serif;
--mono: ui-monospace, "Cascadia Mono", "SFMono-Regular", "DejaVu Sans Mono", Consolas, monospace;
--bg: #f6f3f0;
--surface: #fffdfb;
--sidebar: #eee9e4;
--sunken: #e6e0da;
--hover: rgba(70, 45, 30, 0.07);
--border: #dcd3cb;
--border-strong: #c3b7ad;
--text: #221c18;
--text-2: #5e544d;
--text-3: #776c64;
--accent: #b24f26;
--accent-hover: #9c431e;
--accent-ink: #ffffff;
--accent-soft: #fbe2d4;
--accent-soft-ink: #7c3112;
--peach: #f3a37c;
--talk: #1f8a5a;
--talk-soft: rgba(31, 138, 90, 0.16);
--danger: #b3261e;
--danger-soft: #f9dedc;
--warn-soft: #fbedd0;
--warn-ink: #6b4a00;
--focus: #b24f26;
--shadow: 0 6px 20px rgba(40, 24, 12, 0.14), 0 1px 3px rgba(40, 24, 12, 0.1);
--radius: 8px;
--radius-sm: 6px;
}
@media (prefers-color-scheme: dark) {
:root {
/* Blue-gray surfaces from the owner's settings reference; the peach accent stays the brand colour. */
--bg: #1b2029;
--surface: #242b37;
--sidebar: #1e242e;
--sunken: #171b23;
--hover: rgba(205, 220, 245, 0.07);
--border: #2f3746;
--border-strong: #414b5c;
--text: #e7ebf2;
--text-2: #aab3c2;
--text-3: #8e98aa;
--accent: #f09a6c;
--accent-hover: #f6ae86;
--accent-ink: #2a140a;
--accent-soft: #3a3033;
--accent-soft-ink: #f6c0a2;
--peach: #f3a37c;
--talk: #4fcf8e;
--talk-soft: rgba(79, 207, 142, 0.18);
--danger: #f08b82;
--danger-soft: #42221f;
--warn-soft: #3a2f17;
--warn-ink: #f0d18a;
--focus: #f09a6c;
--shadow: 0 8px 24px rgba(0, 0, 0, 0.45), 0 1px 3px rgba(0, 0, 0, 0.4);
}
}
* { box-sizing: border-box; }
html, body {
margin: 0;
height: 100%;
background: var(--bg);
color: var(--text);
font: 14px/1.45 var(--font);
-webkit-font-smoothing: antialiased;
}
body { overflow: hidden; }
[hidden] { display: none !important; }
::selection { background: var(--accent-soft); color: var(--accent-soft-ink); }
:focus-visible {
outline: 2px solid var(--focus);
outline-offset: 2px;
}
::-webkit-scrollbar { width: 10px; height: 10px; }
::-webkit-scrollbar-track { background: transparent; }
::-webkit-scrollbar-thumb { background: var(--border-strong); border-radius: 8px; border: 2px solid transparent; background-clip: padding-box; }
::-webkit-scrollbar-thumb:hover { background-color: var(--text-3); }
h1, h2, h3 { margin: 0; font-weight: 650; text-wrap: balance; }
h1 { font-size: 20px; line-height: 1.25; }
h2 { font-size: 16px; }
h3 { font-size: 14px; }
p { margin: 0; }
.sprite { position: absolute; width: 0; height: 0; overflow: hidden; }
.icon {
width: 20px;
height: 20px;
flex: none;
fill: none;
stroke: currentColor;
stroke-width: 1.8;
stroke-linecap: round;
stroke-linejoin: round;
}
.brand-mark { width: 40px; height: 40px; stroke: none; }
.brand-mark-large { width: 56px; height: 56px; }
.brand-mark .peach-body, .peach-body { fill: var(--peach); stroke: none; }
.peach-crease { fill: none; stroke: rgba(120, 50, 20, 0.35); stroke-width: 1.2; }
.peach-leaf { fill: #5f9e5a; stroke: none; }
/* ---------- controls ---------- */
.btn {
display: inline-flex;
align-items: center;
justify-content: center;
gap: 6px;
min-height: 34px;
padding: 6px 14px;
border: 1px solid var(--border-strong);
border-radius: var(--radius-sm);
background: var(--surface);
color: var(--text);
font: inherit;
font-weight: 550;
cursor: pointer;
transition: background-color 120ms ease-out, border-color 120ms ease-out;
}
.btn:hover { background: var(--hover); }
.btn:disabled { opacity: 0.55; cursor: not-allowed; }
.btn .icon { width: 18px; height: 18px; }
.btn-primary { background: var(--accent); border-color: var(--accent); color: var(--accent-ink); }
.btn-primary:hover { background: var(--accent-hover); border-color: var(--accent-hover); }
.btn-ghost { background: transparent; border-color: transparent; color: var(--text-2); padding-inline: 8px; }
.btn-ghost:hover { background: var(--hover); color: var(--text); }
.btn-ghost[aria-pressed="true"] { color: var(--accent-soft-ink); background: var(--accent-soft); }
.btn-wide { width: 100%; }
.btn-danger { color: var(--danger); }
.icon-btn {
display: inline-grid;
place-items: center;
width: 34px;
height: 34px;
padding: 0;
border: 0;
border-radius: var(--radius-sm);
background: transparent;
color: var(--text-2);
cursor: pointer;
transition: background-color 120ms ease-out, color 120ms ease-out;
}
.icon-btn:hover { background: var(--hover); color: var(--text); }
.icon-btn:disabled { opacity: 0.45; cursor: not-allowed; }
.icon-btn[aria-pressed="true"] { color: var(--danger); background: var(--danger-soft); }
.icon-btn-accent { color: var(--accent); }
.field { display: flex; flex-direction: column; gap: 6px; }
.field-grow { flex: 1; }
.field-label { font-size: 13px; font-weight: 600; color: var(--text-2); }
.optional { font-weight: 400; color: var(--text-3); }
input[type="text"], input[type="password"], select, textarea {
width: 100%;
min-height: 36px;
padding: 7px 10px;
border: 1px solid var(--border-strong);
border-radius: var(--radius-sm);
background: var(--surface);
color: var(--text);
font: inherit;
caret-color: var(--accent);
}
input::placeholder, textarea::placeholder { color: var(--text-3); }
input:focus-visible, select:focus-visible, textarea:focus-visible { outline: 2px solid var(--focus); outline-offset: 0; border-color: transparent; }
input[aria-invalid="true"] { border-color: var(--danger); }
input[type="checkbox"], input[type="radio"] { accent-color: var(--accent); width: 16px; height: 16px; margin: 0; }
.range { accent-color: var(--accent); width: 100%; }
.range-value { min-width: 3.5ch; font-variant-numeric: tabular-nums; color: var(--text-2); font-size: 12px; }
.fieldset { border: 0; padding: 0; margin: 0; display: flex; flex-direction: column; gap: 8px; }
.fieldset legend { margin-bottom: 8px; padding: 0; }
.choice { display: flex; align-items: center; gap: 8px; cursor: pointer; }
.hint { font-size: 12.5px; color: var(--text-3); max-width: 68ch; }
.lede { color: var(--text-2); max-width: 60ch; }
.form-error { min-height: 1em; color: var(--danger); font-size: 13px; }
.form-error:empty { display: none; }
.form-status { color: var(--text-2); font-size: 13px; }
.form-actions { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; }
.kbd {
display: inline-block;
min-width: 2.4em;
padding: 2px 8px;
border: 1px solid var(--border-strong);
border-bottom-width: 2px;
border-radius: 5px;
background: var(--surface);
font: 12.5px var(--mono);
text-align: center;
}
/* ---------- boot / fatal / onboarding ---------- */
.boot, .fatal, .onboarding {
height: 100%;
display: grid;
place-items: center;
padding: 32px;
}
.boot { gap: 12px; align-content: center; color: var(--text-2); }
.fatal-inner { max-width: 620px; display: flex; flex-direction: column; gap: 14px; }
.fatal-list { margin: 0; padding-left: 18px; font: 12.5px var(--mono); color: var(--text-2); word-break: break-all; }
.fatal-list:empty { display: none; }
.fatal-actions { display: flex; gap: 10px; flex-wrap: wrap; }
.onboarding-form {
width: min(420px, 100%);
display: flex;
flex-direction: column;
gap: 12px;
}
.onboarding-form h1 { font-size: 24px; margin-top: 6px; }
/* ---------- shell ---------- */
.shell {
height: 100%;
display: grid;
grid-template-columns: clamp(280px, 27vw, 390px) 1fr;
}
.sidebar {
display: flex;
flex-direction: column;
min-height: 0;
background: var(--sidebar);
border-right: 1px solid var(--border);
}
.server-head {
display: flex;
align-items: center;
gap: 8px;
padding: 12px 10px 12px 14px;
border-bottom: 1px solid var(--border);
}
.server-title { flex: 1; min-width: 0; display: flex; flex-direction: column; gap: 2px; }
.server-name { font-weight: 650; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.conn-badge { font-size: 12px; color: var(--text-3); display: inline-flex; align-items: center; gap: 6px; }
.conn-badge::before { content: ""; width: 7px; height: 7px; border-radius: 50%; background: var(--text-3); }
.conn-badge[data-state="connected"] { color: var(--talk); }
.conn-badge[data-state="connected"]::before { background: var(--talk); }
.conn-badge[data-state="connecting"]::before, .conn-badge[data-state="disconnecting"]::before { background: var(--peach); }
.tree-empty { padding: 16px 14px; color: var(--text-3); font-size: 13px; }
.tree {
list-style: none;
margin: 0;
padding: 6px 6px 12px;
flex: 1;
min-height: 0;
overflow-y: auto;
}
.tree-row { --indent: calc(var(--depth, 0) * 14px); }
.row-btn {
width: 100%;
display: flex;
align-items: center;
gap: 7px;
min-height: 30px;
padding: 4px 8px 4px calc(8px + var(--indent));
border: 0;
border-radius: var(--radius-sm);
background: transparent;
color: var(--text);
font: inherit;
text-align: left;
cursor: pointer;
}
.row-btn:hover { background: var(--hover); }
.row-btn .icon { width: 17px; height: 17px; color: var(--text-3); }
.row-label { flex: 1; min-width: 0; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.channel-row .row-btn { font-weight: 600; color: var(--text-2); }
.channel-row[data-current="true"] .row-btn { color: var(--text); background: var(--accent-soft); }
.channel-row[data-current="true"] .row-btn .icon { color: var(--accent-soft-ink); }
.channel-meta { font-size: 12px; font-weight: 400; color: var(--text-3); font-variant-numeric: tabular-nums; }
.spacer-row { padding: 8px 8px 4px calc(8px + var(--indent)); font-size: 12px; font-weight: 600; color: var(--text-3); white-space: nowrap; overflow: hidden; text-overflow: clip; }
.spacer-row[data-kind="center"] { text-align: center; }
.spacer-row[data-kind="right"] { text-align: right; }
.member-row { display: flex; align-items: center; gap: 2px; padding-right: 2px; }
.member-row .row-btn { padding-left: calc(24px + var(--indent)); min-height: 28px; font-weight: 450; }
.member-row[data-self="true"] .row-label { font-weight: 650; }
.member-tag { font-size: 12px; color: var(--text-3); }
.member-flags { display: inline-flex; gap: 2px; color: var(--text-3); }
.member-flags .icon { width: 15px; height: 15px; }
.member-flags .flag-muted { color: var(--danger); }
.status-dot {
width: 10px;
height: 10px;
flex: none;
border-radius: 50%;
border: 2px solid var(--border-strong);
transition: background-color 90ms ease-out, border-color 90ms ease-out, box-shadow 90ms ease-out;
}
[data-talking="true"] > .row-btn .status-dot,
.status-dot[data-talking="true"] {
background: var(--talk);
border-color: var(--talk);
box-shadow: 0 0 0 3px var(--talk-soft);
}
.watch-btn {
display: inline-flex;
align-items: center;
gap: 4px;
flex: none;
height: 24px;
padding: 0 8px 0 6px;
border: 1px solid var(--accent);
border-radius: 12px;
background: transparent;
color: var(--accent);
font: 600 12px var(--font);
cursor: pointer;
}
.watch-btn .icon { width: 14px; height: 14px; }
.watch-btn:hover { background: var(--accent-soft); }
.watch-btn[aria-pressed="true"] { background: var(--accent); color: var(--accent-ink); }
.password-row { padding: 4px 6px 8px calc(30px + var(--indent)); }
.password-row form { display: flex; gap: 6px; }
.password-row input { min-height: 30px; padding: 4px 8px; }
.password-row .btn { min-height: 30px; padding: 4px 10px; }
.self {
display: flex;
align-items: center;
gap: 6px;
padding: 10px 8px 10px 14px;
border-top: 1px solid var(--border);
background: var(--sunken);
}
.self-id { flex: 1; min-width: 0; display: flex; align-items: center; gap: 10px; }
.self-text { min-width: 0; }
.self-nick { font-weight: 650; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.self-sub { font-size: 12px; color: var(--text-3); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; font-variant-numeric: tabular-nums; }
.self-actions { display: flex; gap: 2px; }
/* ---------- workspace ---------- */
.workspace { min-width: 0; min-height: 0; display: flex; flex-direction: column; background: var(--surface); }
.connect-view { flex: 1; overflow-y: auto; display: grid; place-items: center; padding: 32px; }
.connect-form { width: min(440px, 100%); display: flex; flex-direction: column; gap: 14px; }
.session-view { flex: 1; min-height: 0; display: flex; flex-direction: column; }
.session-head {
display: flex;
align-items: center;
gap: 16px;
padding: 12px 18px;
border-bottom: 1px solid var(--border);
}
.session-title { flex: 1; min-width: 0; }
.session-title h1 { font-size: 17px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.channel-topic { font-size: 12.5px; color: var(--text-3); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.channel-topic:empty { display: none; }
.transmit { display: flex; align-items: center; gap: 10px; flex: none; }
.transmit-hint { font-size: 12.5px; color: var(--text-3); }
.btn-ptt { user-select: none; touch-action: none; }
.btn-ptt[aria-pressed="true"] { background: var(--talk); border-color: var(--talk); color: #fff; }
.notice {
margin: 10px 18px 0;
padding: 8px 12px;
border-radius: var(--radius-sm);
background: var(--warn-soft);
color: var(--warn-ink);
font-size: 13px;
}
/* stream */
.stream-view {
flex: 0 0 58%;
min-height: 220px;
display: flex;
flex-direction: column;
background: #0d0c0b;
border-bottom: 1px solid var(--border);
}
.stream-stage { position: relative; flex: 1; min-height: 0; }
.stream-stage video { position: absolute; inset: 0; width: 100%; height: 100%; object-fit: contain; background: #0d0c0b; }
.stream-overlay {
position: absolute;
inset: 0;
display: grid;
place-items: center;
padding: 24px;
color: #e9e2dc;
text-align: center;
font-size: 14px;
pointer-events: none;
}
.stream-overlay:empty { display: none; }
.stream-bar {
display: flex;
align-items: center;
gap: 12px;
padding: 8px 12px;
background: #171514;
color: #ede6e0;
}
.stream-bar .icon-btn { color: #c9bfb7; }
.stream-bar .icon-btn:hover { background: rgba(255, 255, 255, 0.08); color: #fff; }
.stream-bar .icon-btn[aria-pressed="true"] { background: rgba(240, 139, 130, 0.18); color: #f4a39b; }
.stream-bar .btn { background: transparent; color: #ede6e0; border-color: #4a433e; }
.stream-bar .btn:hover { background: rgba(255, 255, 255, 0.08); }
.stream-bar .range { width: 120px; accent-color: #f09a6c; }
.stream-bar .range-value { color: #b2a79f; }
.stream-meta { flex: 1; min-width: 0; display: flex; flex-direction: column; }
.stream-title { font-weight: 600; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.stream-stats { font-size: 12px; color: #b2a79f; font-variant-numeric: tabular-nums; }
.stream-controls { display: flex; align-items: center; gap: 6px; }
.stream-view:fullscreen .stream-stage video { object-fit: contain; }
/* chat */
.chat { flex: 1; min-height: 160px; display: flex; flex-direction: column; }
.chat-tabs {
display: flex;
gap: 2px;
padding: 8px 12px 0;
border-bottom: 1px solid var(--border);
overflow-x: auto;
flex: none;
}
.tab-wrap { display: inline-flex; align-items: center; flex: none; }
.chat-tab {
display: inline-flex;
align-items: center;
gap: 6px;
max-width: 220px;
padding: 7px 10px 8px;
border: 0;
border-bottom: 2px solid transparent;
background: transparent;
color: var(--text-2);
font: inherit;
font-weight: 550;
cursor: pointer;
white-space: nowrap;
}
.chat-tab:hover { color: var(--text); }
.chat-tab[aria-selected="true"] { color: var(--text); border-bottom-color: var(--accent); }
.chat-tab .tab-label { overflow: hidden; text-overflow: ellipsis; }
.chat-tab .unread {
min-width: 18px;
padding: 0 5px;
border-radius: 9px;
background: var(--accent);
color: var(--accent-ink);
font-size: 11px;
line-height: 18px;
text-align: center;
font-variant-numeric: tabular-nums;
}
.tab-close {
display: inline-grid;
place-items: center;
width: 18px;
height: 18px;
border-radius: 4px;
color: var(--text-3);
}
.tab-close:hover { background: var(--hover); color: var(--text); }
.tab-close .icon { width: 14px; height: 14px; }
.chat-log {
flex: 1;
min-height: 0;
margin: 0;
padding: 12px 18px;
list-style: none;
overflow-y: auto;
}
.chat-log:focus-visible { outline-offset: -2px; }
.chat-empty { color: var(--text-3); font-size: 13px; padding: 8px 0; }
.msg { padding: 2px 0; max-width: 80ch; }
.msg + .msg[data-head="true"] { margin-top: 10px; }
.msg-head { display: flex; align-items: baseline; gap: 8px; }
.msg-author { font-weight: 650; }
.msg[data-own="true"] .msg-author { color: var(--accent); }
.msg-time { font-size: 11.5px; color: var(--text-3); font-variant-numeric: tabular-nums; }
.msg-body { white-space: pre-wrap; overflow-wrap: anywhere; }
.msg-system { color: var(--text-3); font-size: 13px; padding: 4px 0; }
.msg-system + .msg[data-head="true"], .msg + .msg-system { margin-top: 8px; }
.composer {
display: flex;
align-items: flex-end;
gap: 8px;
margin: 0 18px 14px;
padding: 6px 6px 6px 12px;
border: 1px solid var(--border-strong);
border-radius: var(--radius);
background: var(--surface);
}
.composer:focus-within { border-color: var(--focus); box-shadow: 0 0 0 1px var(--focus); }
.composer textarea {
min-height: 24px;
max-height: 160px;
padding: 5px 0;
border: 0;
background: transparent;
resize: none;
line-height: 1.45;
}
.composer textarea:focus-visible { outline: none; }
/* settings */
.settings-view { flex: 1; min-height: 0; display: flex; flex-direction: column; }
.uid-value {
padding: 6px 10px;
border-radius: var(--radius-sm);
background: var(--sunken);
font: 13px var(--mono);
user-select: all;
overflow-wrap: anywhere;
}
.meter-row { display: flex; align-items: center; gap: 12px; }
.meter { flex: 1; height: 8px; border-radius: 4px; background: var(--sunken); overflow: hidden; }
.meter-fill { height: 100%; width: 0%; background: var(--talk); transition: width 60ms linear; }
.ptt-row { display: flex; align-items: center; gap: 10px; }
.ptt-row .field-label { margin-right: 4px; }
.diag-list { display: grid; grid-template-columns: max-content 1fr; gap: 6px 18px; margin: 0; font-size: 13px; }
.diag-list dt { color: var(--text-3); }
.diag-list dd { margin: 0; font-variant-numeric: tabular-nums; overflow-wrap: anywhere; }
.codec-list { margin: 0; padding: 0; list-style: none; display: flex; flex-direction: column; gap: 4px; font: 12.5px var(--mono); color: var(--text-2); }
/* toasts */
.toasts {
position: fixed;
right: 16px;
bottom: 16px;
display: flex;
flex-direction: column;
gap: 8px;
max-width: min(420px, calc(100vw - 32px));
z-index: 10;
}
.toast {
display: flex;
align-items: flex-start;
gap: 10px;
padding: 10px 8px 10px 14px;
border-radius: var(--radius);
background: var(--surface);
border: 1px solid var(--border);
box-shadow: var(--shadow);
font-size: 13px;
animation: toast-in 180ms cubic-bezier(0.16, 1, 0.3, 1);
}
.toast[data-kind="error"] { border-color: var(--danger); }
.toast-text { flex: 1; padding-top: 2px; }
.toast .icon-btn { width: 26px; height: 26px; }
.toast .icon { width: 16px; height: 16px; }
@keyframes toast-in {
from { transform: translateY(8px); opacity: 0; }
to { transform: none; opacity: 1; }
}
@media (prefers-reduced-motion: reduce) {
*, *::before, *::after { transition: none !important; animation: none !important; }
}
@media (max-width: 1000px) {
.transmit-hint { display: none; }
}
/* ---------- server-provided tree media ---------- */
.avatar { position: relative; width: 22px; height: 22px; flex: none; display: grid; place-items: center; border-radius: 50%; }
.avatar img { width: 22px; height: 22px; border-radius: 50%; object-fit: cover; }
.avatar.has-image .status-dot { position: absolute; right: -2px; bottom: -2px; width: 9px; height: 9px; background: var(--sidebar); }
[data-talking="true"] > .row-btn .avatar.has-image img { box-shadow: 0 0 0 2px var(--talk); }
.member-row .row-btn { padding-left: calc(18px + var(--indent)); }
/* The nickname keeps its width first; group labels and badges shrink and truncate before it. */
.member-row .row-label { flex: 0 0 auto; max-width: 70%; }
.group-label { flex: 0 1 auto; min-width: 2.5em; max-width: 14ch; padding: 0 6px; border-radius: 4px; background: var(--sunken); color: var(--text-2); font-size: 11.5px; line-height: 18px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.member-tag { margin-right: auto; }
.member-badges { display: inline-flex; align-items: center; gap: 3px; flex: 0 1 auto; min-width: 0; overflow: hidden; }
.group-icon { display: inline-grid; place-items: center; width: 16px; height: 16px; color: var(--text-3); }
.group-icon img { width: 16px; height: 16px; object-fit: contain; }
.group-icon .icon { width: 14px; height: 14px; }
.country { padding: 0 4px; border: 1px solid var(--border-strong); border-radius: 3px; font-size: 10.5px; line-height: 14px; color: var(--text-2); font-variant-numeric: tabular-nums; }
.member-flags .flag-rec { color: var(--danger); }
.channel-icon { display: inline-grid; place-items: center; flex: none; }
.channel-icon img { width: 16px; height: 16px; object-fit: contain; }
.channel-row.has-banner .row-btn {
min-height: 36px;
background-image: linear-gradient(90deg, var(--sidebar) 30%, color-mix(in srgb, var(--sidebar) 55%, transparent) 100%), var(--banner);
background-size: cover;
background-position: center;
}
.channel-row.has-banner[data-current="true"] .row-btn {
background-image: linear-gradient(90deg, var(--accent-soft) 30%, color-mix(in srgb, var(--accent-soft) 55%, transparent) 100%), var(--banner);
}
.host-banner { display: block; width: calc(100% - 20px); max-height: 96px; margin: 10px 10px 0; object-fit: contain; border-radius: var(--radius-sm); }
/* The official client highlights only relationships it knows: the own client (and myTS contacts, which need an account). */
.member-row[data-self="true"] .row-label { color: var(--accent); }
/* ---------- settings: category navigation + titled cards (owner's reference) ---------- */
.visually-hidden { position: absolute; width: 1px; height: 1px; margin: -1px; padding: 0; overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; border: 0; }
.room-side { flex: 1; min-height: 0; display: flex; flex-direction: column; }
.room-side[hidden] { display: none; }
.settings-nav { flex: 1; min-height: 0; overflow-y: auto; display: flex; flex-direction: column; gap: 2px; padding: 10px 10px 14px; }
.settings-back { display: inline-flex; align-items: center; gap: 6px; align-self: flex-start; margin-bottom: 6px; padding: 6px 8px; border: 0; border-radius: var(--radius-sm); background: transparent; color: var(--text-2); font: inherit; cursor: pointer; }
.settings-back:hover { background: var(--hover); color: var(--text); }
.settings-back .icon { width: 18px; height: 18px; }
.settings-nav-title { display: flex; align-items: center; gap: 8px; padding: 4px 8px 8px; color: var(--text-2); font-size: 15px; font-weight: 600; }
.nav-group-label { padding: 10px 10px 4px; color: var(--text-3); font-size: 12px; }
.nav-item { position: relative; display: flex; align-items: center; gap: 12px; min-height: 40px; padding: 6px 12px; border: 0; border-radius: var(--radius); background: transparent; color: var(--text); font: inherit; font-weight: 550; text-align: left; cursor: pointer; }
.nav-item .icon { width: 22px; height: 22px; color: var(--text-2); }
.nav-item:hover { background: var(--hover); }
.nav-item[aria-current="page"] { background: var(--accent-soft); }
.nav-item[aria-current="page"] .icon { color: var(--accent); }
.nav-item[aria-current="page"]::before { content: ""; position: absolute; left: -10px; top: 8px; bottom: 8px; width: 3px; border-radius: 0 3px 3px 0; background: var(--accent); }
.settings-view { background: var(--bg); }
.settings-scroll { flex: 1; min-height: 0; overflow-y: auto; padding: 22px 26px 40px; }
.settings-panel { max-width: 880px; display: flex; flex-direction: column; gap: 14px; }
.panel-title { font-size: 20px; margin: 2px 2px 4px; }
.card { display: flex; flex-direction: column; gap: 12px; padding: 18px 20px; border-radius: 12px; background: var(--surface); border: 1px solid var(--border); }
.card-title { font-size: 15px; font-weight: 650; }
.card-divider { height: 1px; background: var(--border); margin: 2px 0; }
.card-row { display: flex; align-items: center; gap: 12px; flex-wrap: wrap; }
.row-name { font-weight: 600; margin-right: auto; }
.card .uid-value { font-size: 12.5px; color: var(--text-2); background: var(--sunken); }
.inline-form { display: flex; align-items: center; gap: 12px; }
.inline-label { font-weight: 600; }
.inline-form input { flex: 1; min-height: 34px; border-radius: 17px; padding: 5px 14px; background: var(--sunken); border-color: transparent; }
.stack-form { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; align-items: end; }
.stack-form .form-actions { grid-column: 1 / -1; }
.btn-small { min-height: 30px; padding: 4px 12px; font-size: 13px; }
/* ---------- saved servers ---------- */
.servers-panel { padding: 8px 8px 6px; border-bottom: 1px solid var(--border); }
.servers-head { display: flex; align-items: center; gap: 8px; padding: 2px 6px 6px; }
.servers-title { flex: 1; font-size: 12px; font-weight: 600; color: var(--text-3); }
.servers-empty { padding: 2px 6px 6px; font-size: 12.5px; color: var(--text-3); }
.servers-list { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 2px; }
.server-item { width: 100%; display: flex; align-items: center; gap: 10px; padding: 6px 8px; border: 0; border-radius: var(--radius-sm); background: transparent; color: var(--text); font: inherit; text-align: left; cursor: pointer; }
.server-item:hover:not(:disabled) { background: var(--hover); }
.server-item:disabled { cursor: default; }
.server-item .icon { width: 16px; height: 16px; color: var(--text-3); }
.server-text { flex: 1; min-width: 0; display: flex; flex-direction: column; }
.server-item-name { font-weight: 600; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.server-item-address { font-size: 12px; color: var(--text-3); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.server-item-action { flex: none; font-size: 12px; font-weight: 600; color: var(--accent); }
.server-item:disabled .server-item-action { color: var(--talk); }
.servers-manage { gap: 0; }
.manage-row { display: flex; align-items: center; gap: 8px; padding: 10px 0; border-top: 1px solid var(--border); }
.manage-row:first-child { border-top: 0; }
.edit-row { flex: 1; display: grid; grid-template-columns: 1fr 1fr auto auto; gap: 8px; }
.row-value { color: var(--text-2); font-size: 13px; }
.card-details { border-top: 1px solid var(--border); padding-top: 10px; }
.card-details > summary { cursor: pointer; font-weight: 600; color: var(--text-2); padding: 4px 0; }
.card-details > summary:hover { color: var(--text); }
.card-details[open] > summary { margin-bottom: 10px; }
.card-details .diag-list { margin-bottom: 12px; }
.details-title { font-size: 13px; font-weight: 600; color: var(--text-2); margin: 10px 0 6px; }
BIN
View File
Binary file not shown.

Before

Width:  |  Height:  |  Size: 37 KiB

After

Width:  |  Height:  |  Size: 57 KiB

BIN
View File
Binary file not shown.

Before

Width:  |  Height:  |  Size: 14 KiB

After

Width:  |  Height:  |  Size: 138 KiB

+15 -4
View File
@@ -1,6 +1,17 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512">
<rect x="24" y="24" width="464" height="464" rx="104" fill="#2a2320"/>
<path d="M256 168c-86-30-150 30-150 112 0 86 67 156 150 156s150-70 150-156c0-82-64-142-150-112z" fill="#f3a37c"/>
<path d="M256 176c-30 47-37 160 0 254" fill="none" stroke="#b9653d" stroke-width="12" stroke-linecap="round"/>
<path d="M261 160c4-50 39-80 96-82-6 52-40 81-96 82z" fill="#6aa864"/>
<defs>
<linearGradient id="peach" x1="108" y1="142" x2="390" y2="432" gradientUnits="userSpaceOnUse">
<stop stop-color="#ffc18c"/>
<stop offset=".48" stop-color="#f3a37c"/>
<stop offset="1" stop-color="#ed776b"/>
</linearGradient>
<linearGradient id="leaf" x1="274" y1="109" x2="368" y2="44" gradientUnits="userSpaceOnUse">
<stop stop-color="#3e8053"/>
<stop offset="1" stop-color="#83b56b"/>
</linearGradient>
</defs>
<path d="M252 151c-7-35-3-68 11-94" fill="none" stroke="#80503b" stroke-width="21" stroke-linecap="round"/>
<path d="M264 119c3-53 43-84 116-78-10 58-47 92-116 78Z" fill="url(#leaf)"/>
<path d="M255 150c-35-26-72-35-106-24C79 148 47 201 53 267c7 85 73 150 167 195 23 11 37 21 44 21s20-12 40-23c96-54 152-120 156-196 4-65-31-119-92-137-43-13-82-4-113 23Z" fill="url(#peach)"/>
<path d="M255 150c-22 36-34 75-35 117-2 66 17 133 44 185" fill="none" stroke="#d97158" stroke-width="13" stroke-linecap="round"/>
</svg>

Before

Width:  |  Height:  |  Size: 445 B

After

Width:  |  Height:  |  Size: 1.0 KiB

+27 -4
View File
@@ -1,6 +1,6 @@
[package]
name = "teamspeach-core"
version = "0.1.0"
version.workspace = true
edition = "2021"
rust-version = "1.89"
description = "TeamsPeach native TeamSpeak protocol core (stdio JSON bridge)"
@@ -19,21 +19,44 @@ audiopus = "0.3.0-rc.0"
base64 = "0.22"
futures = "0.3"
num-traits = "0.2"
# File identity (volume serial + index / dev + inode) for paused partial downloads; already in the lock.
same-file = "1.0.6"
serde = { version = "1", features = ["derive"] }
serde_json = { version = "1", features = ["raw_value", "preserve_order"] }
sha-1 = "0.10"
md-5 = "0.10"
# Same DER decoder tsproto-types uses for keys (already in the lock through it).
simple_asn1 = "0.6"
# Voice activation detector (pure Rust, embedded model; MIT OR Apache-2.0). Pinned: newer releases change the API.
earshot = "=1.2.2"
thiserror = "2"
tokio = { version = "1", features = ["rt", "macros", "io-std", "io-util", "sync", "time"] }
tracing = "0.1"
tracing-subscriber = { version = "0.3", features = ["env-filter", "fmt"] }
[target.'cfg(windows)'.dependencies]
windows-core = "0.62.2"
windows = { version = "0.62.2", features = [
"Win32_Foundation",
"Win32_Media_Audio",
"Win32_Security",
"Win32_System_Com",
"Win32_System_Com_StructuredStorage",
"Win32_System_Diagnostics_ToolHelp",
"Win32_System_SystemInformation",
"Win32_System_Threading",
"Win32_System_Variant",
] }
windows-sys = { version = "0.61", features = [
"Win32_Foundation",
"Win32_Security",
"Win32_Security_Authorization",
"Win32_System_Threading",
"Win32_UI_Input_KeyboardAndMouse",
"Win32_UI_WindowsAndMessaging",
] }
[profile.release]
lto = "thin"
codegen-units = 4
[target.'cfg(target_os = "linux")'.dependencies]
dbus = { version = "0.9", features = ["vendored"] }
x11rb = "0.13"
File diff suppressed because it is too large. Load diff
+1175
View File
File diff suppressed because it is too large. Load diff
+172
View File
@@ -0,0 +1,172 @@
//! Additional ordinary client administration primitives used by JSON snapshots and admin views.
//! Wire declarations: pinned ReSpeak Messages.toml (ClientDb*, LogView, *Group*, ChannelAddPerm, ServerGroupDel /
//! ChannelGroupDel `[sgid|cgid, force]`, ServerGroupDelPerm / ChannelGroupDelPerm / ChannelDelPerm
//! `[sgid|cgid|cid, permid?, permsid?]`). The installed TeamSpeak.dll 6.0.0.5163 carries the same five verbs in its
//! client command string table; official main.js@2408925 `RemovePermissionGroup` → `requestGroupDel(..., force)`
//! (the permission page always passes force=true after a confirmation checkbox, main.js@4606337) and
//! main.js@2410218 `RemovePermissions` → `requestPermissionsDel` (inspector `removePermission`, main.js@4575316).
use serde::Deserialize;
use serde_json::Value;
use tsproto_packets::packets::OutCommand;
use crate::{admin::{Live, Reply}, menu, protocol::{ErrorObj, ErrorCode}};
#[derive(Clone, Copy, Debug, PartialEq, Deserialize)]
#[serde(rename_all="snake_case")]
pub enum GroupKind { Server, Channel }
#[derive(Clone, Debug, PartialEq, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Permission { pub id: String, pub value: i32, #[serde(default)] pub negate: bool, #[serde(default)] pub skip: bool }
#[derive(Clone, Debug, PartialEq, Deserialize)]
#[serde(tag="command", rename_all="snake_case", deny_unknown_fields)]
pub enum Command {
ServerLog { lines: u16, reverse: bool, instance: bool, begin_pos: u64 },
ClientDatabaseList { start: u32, duration: u16 },
ClientDatabaseFind { pattern: String, uid: bool },
ClientDatabaseDelete { generation: u64, client_database_id: u64, confirm: String },
ClientDatabaseId { uid: String },
ServerGroupList {}, ChannelGroupList {}, ChannelList {}, ChannelInfo { channel_id: u64 },
ClientInfo { client_id: u16, uid: String },
GroupAdd { generation: u64, kind: GroupKind, name: String, #[serde(rename="type")] group_type: u8 },
GroupRename { generation: u64, kind: GroupKind, group_id: u64, name: String },
GroupSetPermissions { generation: u64, kind: GroupKind, group_id: u64, permissions: Vec<Permission> },
ChannelSetPermissions { generation: u64, channel_id: u64, permissions: Vec<Permission> },
/// Destructive: `confirm` must be the decimal group ID being deleted.
GroupDelete { generation: u64, kind: GroupKind, group_id: u64, force: bool, confirm: String },
GroupDeletePermissions { generation: u64, kind: GroupKind, group_id: u64, permissions: Vec<String> },
ChannelDeletePermissions { generation: u64, channel_id: u64, permissions: Vec<String> },
ServerGroupAddClient { generation: u64, group_id: u64, client_database_id: u64 },
ServerGroupMemberAddUid { generation: u64, group_id: u64, uid: String },
}
impl Command {
pub fn name(&self) -> &'static str { match self {
Self::ServerLog{..}=>"server_log", Self::ClientDatabaseList{..}=>"client_database_list",
Self::ClientDatabaseFind{..}=>"client_database_find", Self::ClientDatabaseDelete{..}=>"client_database_delete",
Self::ClientDatabaseId{..}=>"client_database_id", Self::ServerGroupList{}=>"server_group_list",
Self::ChannelGroupList{}=>"channel_group_list", Self::ChannelList{}=>"channel_list", Self::ChannelInfo{..}=>"channel_info",
Self::ClientInfo{..}=>"client_info",
Self::GroupAdd{..}=>"group_add", Self::GroupRename{..}=>"group_rename", Self::GroupSetPermissions{..}=>"group_set_permissions",
Self::ChannelSetPermissions{..}=>"channel_set_permissions", Self::ServerGroupAddClient{..}=>"server_group_add_client",
Self::ServerGroupMemberAddUid{..}=>"server_group_member_add_uid", Self::GroupDelete{..}=>"group_delete",
Self::GroupDeletePermissions{..}=>"group_delete_permissions", Self::ChannelDeletePermissions{..}=>"channel_delete_permissions",
}}
pub fn generation(&self) -> Option<u64> { match self {
Self::ServerGroupMemberAddUid{generation,..}=>Some(*generation),
Self::ClientDatabaseDelete{generation,..}|Self::GroupAdd{generation,..}|Self::GroupRename{generation,..}
|Self::GroupSetPermissions{generation,..}|Self::ChannelSetPermissions{generation,..}|Self::ServerGroupAddClient{generation,..}
|Self::GroupDelete{generation,..}|Self::GroupDeletePermissions{generation,..}|Self::ChannelDeletePermissions{generation,..}=>Some(*generation), _=>None,
}}
pub(super) fn validate(&self) -> Result<(),ErrorObj> {
let positive=|id:u64| if id==0 {Err(menu::bad("target ID must be positive"))}else{Ok(())};
let text=|s:&str,max:usize| if s.is_empty()||s.len()>max||s.chars().any(char::is_control){Err(menu::bad("invalid text argument"))}else{Ok(())};
if let Some(g)=self.generation(){positive(g)?;}
match self {
Self::ServerLog{lines,..} if !(1..=1000).contains(lines)=>return Err(menu::bad("lines must be 1..1000")),
Self::ClientDatabaseList{duration,..} if !(1..=200).contains(duration)=>return Err(menu::bad("duration must be 1..200")),
Self::ClientDatabaseFind{pattern,..}=>text(pattern,255)?,
Self::ClientDatabaseId{uid}=>text(uid,128)?,
Self::ClientDatabaseDelete{client_database_id,confirm,..}=>{positive(*client_database_id)?;if confirm!=&client_database_id.to_string(){return Err(menu::bad("confirmation does not match the database ID"));}},
Self::GroupAdd{name,group_type,..}=>{text(name,128)?;if *group_type>2{return Err(menu::bad("type must be 0..2"));}},
Self::GroupRename{group_id,name,..}=>{positive(*group_id)?;text(name,128)?;},
Self::GroupSetPermissions{group_id,permissions,kind,..}=>{positive(*group_id)?;validate_permissions(permissions,*kind==GroupKind::Server)?;},
Self::ChannelSetPermissions{channel_id,permissions,..}=>{positive(*channel_id)?;validate_permissions(permissions,false)?;},
Self::GroupDelete{group_id,confirm,..}=>{positive(*group_id)?;if confirm!=&group_id.to_string(){return Err(menu::bad("confirmation does not match the group ID"));}},
Self::GroupDeletePermissions{group_id,permissions,..}=>{positive(*group_id)?;validate_permission_ids(permissions)?;},
Self::ChannelDeletePermissions{channel_id,permissions,..}=>{positive(*channel_id)?;validate_permission_ids(permissions)?;},
Self::ChannelInfo{channel_id}=>positive(*channel_id)?,
Self::ClientInfo{client_id,uid}=>{positive(u64::from(*client_id))?;text(uid,128)?;},
Self::ServerGroupAddClient{group_id,client_database_id,..}=>{positive(*group_id)?;positive(*client_database_id)?;},
Self::ServerGroupMemberAddUid{group_id,uid,..}=>{positive(*group_id)?;text(uid,128)?;},
_=>{},
} Ok(())
}
pub fn build(&self, live:&Live) -> Result<(OutCommand,Reply),ErrorObj> {
let s=|v:u64|v.to_string(); let flag=|v:bool|u8::from(v).to_string();
Ok(match self {
Self::ServerLog{lines,reverse,instance,begin_pos}=>(menu::command("logview",&[("lines",lines.to_string()),("reverse",flag(*reverse)),("instance",flag(*instance)),("begin_pos",s(*begin_pos))]),Reply::rows("notifyserverlog",None)),
Self::ClientDatabaseList{start,duration}=>(menu::command("clientdblist",&[("start",start.to_string()),("duration",duration.to_string())]),Reply::rows("notifyclientdblist",None)),
Self::ClientDatabaseFind{pattern,uid}=>{let mut c=menu::command("clientdbfind",&[("pattern",pattern.clone()),("-details",String::new())]);if *uid{c.write_arg("-uid",&"");}(c,Reply::rows("notifyclientdbfind",None))},
Self::ClientDatabaseDelete{client_database_id,..}=>(menu::command("clientdbdelete",&[("cldbid",s(*client_database_id))]),Reply::Ack),
Self::ClientDatabaseId{uid}=>(menu::command("clientgetdbidfromuid",&[("cluid",uid.clone())]),Reply::rows("notifyclientdbidfromuid",None)),
Self::ServerGroupList{}=>(menu::command("servergrouplist",&[]),Reply::rows("notifyservergrouplist",None)),
Self::ChannelGroupList{}=>(menu::command("channelgrouplist",&[]),Reply::rows("notifychannelgrouplist",None)),
Self::GroupAdd{kind,name,group_type,..}=>{
let (verb,notify,key)=group_names(*kind,"add");
(menu::command(verb,&[("name",name.clone()),("type",group_type.to_string())]),Reply::GroupCreated{notify,key,name:name.clone(),group_id:None,ambiguous:false})
},
Self::GroupRename{kind,group_id,name,..}=>{let(verb,_,key)=group_names(*kind,"rename");(menu::command(verb,&[(key,s(*group_id)),("name",name.clone())]),Reply::Ack)},
Self::GroupSetPermissions{kind,group_id,permissions,..}=>{let(verb,_,key)=group_names(*kind,"perm");(permission_command(verb,key,*group_id,permissions,*kind==GroupKind::Server),Reply::Ack)},
Self::ChannelSetPermissions{channel_id,permissions,..}=>{
if (live.channel)(*channel_id).is_none(){return Err(ErrorObj::new(ErrorCode::NotFound,"channel is no longer visible"));}
(permission_command("channeladdperm","cid",*channel_id,permissions,false),Reply::Ack)
},
Self::GroupDelete{kind,group_id,force,..}=>{
let key=group_names(*kind,"del").2;
let verb=if *kind==GroupKind::Server {"servergroupdel"}else{"channelgroupdel"};
(menu::command(verb,&[(key,s(*group_id)),("force",flag(*force))]),Reply::Ack)
},
Self::GroupDeletePermissions{kind,group_id,permissions,..}=>{
let (verb,key)=if *kind==GroupKind::Server {("servergroupdelperm","sgid")}else{("channelgroupdelperm","cgid")};
(delete_permission_command(verb,key,*group_id,permissions),Reply::Ack)
},
Self::ChannelDeletePermissions{channel_id,permissions,..}=>{
if (live.channel)(*channel_id).is_none(){return Err(ErrorObj::new(ErrorCode::NotFound,"channel is no longer visible"));}
(delete_permission_command("channeldelperm","cid",*channel_id,permissions),Reply::Ack)
},
Self::ServerGroupAddClient{group_id,client_database_id,..}=>(menu::command("servergroupaddclient",&[("sgid",s(*group_id)),("cldbid",s(*client_database_id))]),Reply::Ack),
Self::ServerGroupMemberAddUid{group_id,uid,..}=>{
// Official TS6 main.js assignServerGroupMembers + TeamSpeak.dll
// constructor 0x1814b8e7d: vsgroupassignbyids json=<versioned JSON>.
let member=if uid.len()>32 {serde_json::json!({"client_uid":uid,"vs_group_id":group_id.to_string()})}else{serde_json::json!({"migration":uid,"vs_group_id":group_id.to_string()})};
let payload=serde_json::json!({"version":1,"add":[member]}).to_string();
(menu::command("vsgroupassignbyids",&[("json",payload)]),Reply::Ack)
},
Self::ChannelInfo{..}|Self::ChannelList{}|Self::ClientInfo{..}=>return Err(ErrorObj::new(ErrorCode::Internal,"object reads are handled by the session")),
})
}
}
fn group_names(kind:GroupKind,op:&str)->(&'static str,&'static str,&'static str){match(kind,op){
(GroupKind::Server,"add")=>("servergroupadd","notifyservergrouplist","sgid"),
(GroupKind::Server,"rename")=>("servergrouprename","notifyservergrouplist","sgid"),
(GroupKind::Server,_)=>("servergroupaddperm","notifyservergrouplist","sgid"),
(GroupKind::Channel,"add")=>("channelgroupadd","notifychannelgrouplist","cgid"),
(GroupKind::Channel,"rename")=>("channelgrouprename","notifychannelgrouplist","cgid"),
(GroupKind::Channel,_)=>("channelgroupaddperm","notifychannelgrouplist","cgid"),
}}
fn validate_permission_id(id:&str)->Result<(),ErrorObj>{
if id.is_empty()||id.len()>128||!id.bytes().all(|b|b.is_ascii_alphanumeric()||b==b'_'){return Err(menu::bad("invalid permission identifier"));}
if id.bytes().all(|b|b.is_ascii_digit())&&id.parse::<u32>().ok().is_none_or(|v|v==0){return Err(menu::bad("invalid numeric permission identifier"));}
Ok(())
}
fn validate_permissions(rows:&[Permission],server:bool)->Result<(),ErrorObj>{
if rows.is_empty()||rows.len()>512{return Err(menu::bad("permissions must contain 1..512 entries"));}
for p in rows {
validate_permission_id(&p.id)?;
if !server&&(p.negate||p.skip){return Err(menu::bad("negate and skip are only available for server groups"));}
} Ok(())
}
fn validate_permission_ids(ids:&[String])->Result<(),ErrorObj>{
if ids.is_empty()||ids.len()>512{return Err(menu::bad("permissions must contain 1..512 entries"));}
ids.iter().map(String::as_str).try_for_each(validate_permission_id)
}
/// `*delperm` (declared `[key, permid?, permsid?]`): one part per explicit permission being removed.
fn delete_permission_command(verb:&'static str,key:&'static str,id:u64,ids:&[String])->OutCommand{
let mut c=menu::command(verb,&[]);
for(i,p)in ids.iter().enumerate(){if i>0{c.start_new_part();}c.write_arg(key,&id);
c.write_arg(if p.bytes().all(|b|b.is_ascii_digit()){"permid"}else{"permsid"},p);}
c
}
fn permission_command(verb:&'static str,key:&'static str,id:u64,rows:&[Permission],server:bool)->OutCommand{
let mut c=menu::command(verb,&[]);
for(i,p)in rows.iter().enumerate(){if i>0{c.start_new_part();}c.write_arg(key,&id);
c.write_arg(if p.id.bytes().all(|b|b.is_ascii_digit()){"permid"}else{"permsid"},&p.id);c.write_arg("permvalue",&p.value);
if server{c.write_arg("permnegated",&u8::from(p.negate));c.write_arg("permskip",&u8::from(p.skip));}
} c
}
pub fn recognizes(name:&str)->bool{matches!(name,"server_log"|"client_database_list"|"client_database_find"|"client_database_delete"|"client_database_id"|"server_group_list"|"channel_group_list"|"channel_list"|"channel_info"|"client_info"|"group_add"|"group_rename"|"group_set_permissions"|"channel_set_permissions"|"server_group_add_client"|"server_group_member_add_uid"|"group_delete"|"group_delete_permissions"|"channel_delete_permissions")}
pub fn parse(name:&str,raw:Option<&serde_json::value::RawValue>)->Result<Command,ErrorObj>{
let mut v:Value=serde_json::from_str(raw.map_or("{}",|r|r.get())).map_err(|e|menu::bad(e.to_string()))?;
let obj=v.as_object_mut().ok_or_else(||menu::bad("args must be an object"))?;
if obj.contains_key("command"){return Err(menu::bad("unexpected command argument"));}
obj.insert("command".into(),Value::String(name.into()));
serde_json::from_value(v).map_err(|e|menu::bad(e.to_string()))
}
+110
View File
@@ -0,0 +1,110 @@
//! Session integration of server/channel administration (`admin.rs`, `docs/bridge.md` §4.6).
use super::*;
impl Session {
pub(super) async fn admin(&mut self, id: &str, cmd: admin::AdminCommand) -> Result<Option<Value>, ErrorObj> {
let c = self.connected_conn()?;
if let Some(generation) = cmd.generation() {
if generation != c.generation {
return Err(ErrorObj::new(ErrorCode::BadRequest, "connection changed; reload and confirm again")
.with_detail(json!({ "generation": c.generation })));
}
}
let book = c.con.get_state().map_err(|e| lib_error(ErrorCode::NotConnected, &e))?;
let (command, reply) = match &cmd {
admin::AdminCommand::Context => (menu::command("permissionlist", &[]), admin::Reply::Context),
admin::AdminCommand::Extra(admin::extra::Command::ChannelList {}) => {
let rows: Vec<_> = snapshot::ordered_channels(&book.channels).into_iter()
.filter_map(|(id, _)| c.extras.channel_properties(id.0).cloned()).collect();
if rows.len() != book.channels.len() {
return Err(ErrorObj::new(ErrorCode::ServerError, "channel properties are incomplete; wait for the server channel list"));
}
return Ok(Some(json!({ "rows": rows })));
}
admin::AdminCommand::Extra(admin::extra::Command::ChannelInfo { channel_id }) => {
if !book.channels.contains_key(&ChannelId(*channel_id)) {
return Err(ErrorObj::new(ErrorCode::NotFound, "channel is no longer visible"));
}
(menu::command("channelgetdescription", &[("cid", channel_id.to_string())]), admin::Reply::ChannelInfo { channel_id: *channel_id })
}
admin::AdminCommand::Extra(admin::extra::Command::ClientInfo { client_id, uid }) => {
if book.clients.get(&ClientId(*client_id)).and_then(|client| client.uid.as_ref()).is_none_or(|current| current.to_string() != *uid) {
return Err(ErrorObj::new(ErrorCode::TargetChanged, "client identity changed; reopen information"));
}
(menu::command("clientgetvariables", &[("clid", client_id.to_string())]), admin::Reply::rows("notifyclientupdated", Some(("clid", u64::from(*client_id)))))
}
admin::AdminCommand::TalkPower { target, grant, .. } => {
let client = book
.clients
.get(&ClientId(target.client_id))
.ok_or_else(|| ErrorObj::new(ErrorCode::NotFound, "client is no longer visible"))?;
if client.uid.as_ref().is_none_or(|uid| uid.to_string() != target.uid) {
return Err(menu::bad("client identity changed; reopen the menu"));
}
(admin::talk_power(target.client_id, *grant), admin::Reply::Ack)
}
other => {
let server_uid = book.server.public_key.get_uid();
let channel = |cid: u64| book.channels.get(&ChannelId(cid)).map(|ch| ch.name.clone());
let live = admin::Live { own_client: book.own_client.0, server_uid: &server_uid, channel: &channel };
admin::build(other, &live)?
}
};
// Rows are matched by notification name, so only one reader per name may be in flight.
if let Some(name) = reply.notification() {
let busy = c.pending.values().any(|p| matches!(p, Pending::Admin { reply, .. } if reply.notification() == Some(name)));
if busy {
return Err(ErrorObj::new(ErrorCode::BadRequest, format!("another request reading {name} is still pending")));
}
}
let handle = c.send(command).map_err(|e| lib_error(ErrorCode::NotConnected, &e))?;
c.pending.insert(handle, Pending::Admin { req: id.to_owned(), reply });
Ok(None)
}
pub(super) async fn admin_result(&mut self, req: String, reply: admin::Reply, res: Result<(), CommandError>) {
let empty = |e: &CommandError| {
matches!(e.error.to_u32(), Some(admin::DATABASE_EMPTY_RESULT | admin::PERMISSION_EMPTY_RESULT))
};
let answer = match (reply, res) {
(admin::Reply::Context, res) => self.admin_context(res),
(admin::Reply::ChannelInfo { channel_id }, Ok(())) => {
self.conn.as_ref().and_then(|c| c.extras.channel_properties(channel_id))
.map(|row| json!({ "rows": [row] }))
.ok_or_else(|| ErrorObj::new(ErrorCode::NotFound, "channel disappeared before its properties were read"))
}
(admin::Reply::Rows { notify: "notifyserverupdated", overflow: false, .. }, Ok(())) => {
self.conn.as_ref().map(|c| json!({ "rows": [c.extras.server_properties()] })).ok_or_else(not_connected)
}
(admin::Reply::Rows { .. }, Err(e)) if empty(&e) => Ok(json!({ "rows": [] })),
(_, Err(e)) => Err(command_error(&e)),
(reply, Ok(())) => admin::finish(reply),
};
match answer {
Ok(v) => self.out.ok(&req, v).await,
Err(e) => self.out.err(&req, e).await,
}
}
/// Generation, server UID and the own permission values the official client checks.
fn admin_context(&self, res: Result<(), CommandError>) -> Result<Value, ErrorObj> {
let c = self.conn.as_ref().filter(|c| c.connected()).ok_or_else(not_connected)?;
let book = c.con.get_state().map_err(|e| lib_error(ErrorCode::NotConnected, &e))?;
let mut permissions = serde_json::Map::new();
for name in admin::HINT_PERMISSIONS {
permissions.insert((*name).to_owned(), json!(c.permissions.named(name)));
}
let mut v = json!({
"generation": c.generation,
"server_uid": book.server.public_key.get_uid(),
"own_client_id": book.own_client.0,
"catalog_received": c.permissions.has_catalog(),
"permissions": permissions,
"permissions_catalog": c.permissions.catalog,
});
if let Err(e) = res {
v["permission_error"] = serde_json::to_value(command_error(&e)).expect("error serializes");
}
Ok(v)
}
}
+249
View File
@@ -0,0 +1,249 @@
//! Profileless selected-application audio. Never substitutes endpoint/system loopback.
//! Native consumers receive bounded PCM directly; only `run` uses the CLI transport.
use std::io::{Read, Write};
use std::process::ExitCode;
use std::sync::{Arc, atomic::{AtomicBool, Ordering}, mpsc};
use std::thread::JoinHandle;
use std::time::Duration;
use base64::{Engine, engine::general_purpose::STANDARD};
use serde_json::{json, Value};
#[cfg(windows)]
#[path = "app_audio_windows.rs"]
mod platform;
#[cfg(target_os = "linux")]
#[path = "app_audio_linux.rs"]
mod platform;
#[cfg(all(test, not(target_os = "linux")))]
#[path = "app_audio_linux.rs"]
#[allow(dead_code)]
mod linux_contract_tests;
pub const PCM_BYTES: usize = 960 * 2 * 2;
const EVENT_CAPACITY: usize = 4;
/// Explicit, clonable cancellation shared by enumeration and capture operations.
#[derive(Clone, Default)]
pub struct Cancellation(Arc<AtomicBool>);
impl Cancellation {
pub fn cancel(&self) { self.0.store(true, Ordering::Release); }
pub fn is_cancelled(&self) -> bool { self.0.load(Ordering::Acquire) }
pub(super) fn check(&self) -> Result<(), String> {
if self.is_cancelled() { Err("Application audio cancelled".into()) } else { Ok(()) }
}
}
/// Fixed 20 ms, 48 kHz stereo signed little-endian PCM. Sequence gaps denote drops.
#[derive(Debug)]
pub enum CaptureEvent {
Format,
Pcm { sequence: u64, bytes: [u8; PCM_BYTES] },
}
#[derive(Clone)]
pub(super) struct Sink(mpsc::SyncSender<CaptureEvent>);
impl Sink {
pub(super) fn format(&self) -> Result<(), String> {
self.0.try_send(CaptureEvent::Format).map_err(|_| "Application audio consumer stopped".into())
}
pub(super) fn pcm(&self, sequence: u64, bytes: [u8; PCM_BYTES]) -> Result<(), String> {
match self.0.try_send(CaptureEvent::Pcm { sequence, bytes }) {
Ok(()) | Err(mpsc::TrySendError::Full(_)) => Ok(()),
Err(mpsc::TrySendError::Disconnected(_)) => Err("Application audio consumer stopped".into()),
}
}
}
/// Owns the capture worker and its bounded output. Drop cancels and joins it.
/// Host callbacks run on the caller, never on a capture or helper-reader thread.
/// Drain continuously; a slow consumer drops new PCM, never blocks capture.
/// The terminal success/error is returned by `join`/`stop`, not a droppable event.
/// `stop`, `join`, and Drop block: use an owner/shutdown worker, never the UI thread.
pub struct Capture {
cancel: Cancellation,
events: mpsc::Receiver<CaptureEvent>,
worker: Option<JoinHandle<Result<(), String>>>,
}
impl Capture {
pub fn cancel(&self) { self.cancel.cancel(); }
pub fn is_finished(&self) -> bool { self.worker.as_ref().is_none_or(JoinHandle::is_finished) }
pub fn recv_timeout(&self, timeout: Duration) -> Result<CaptureEvent, mpsc::RecvTimeoutError> {
if self.cancel.is_cancelled() { return Err(mpsc::RecvTimeoutError::Disconnected); }
let event = self.events.recv_timeout(timeout)?;
if self.cancel.is_cancelled() { return Err(mpsc::RecvTimeoutError::Disconnected); }
Ok(event)
}
/// Dispatch no more than the queue capacity, even while capture produces more.
pub fn dispatch_pending(&self, mut callback: impl FnMut(CaptureEvent)) -> usize {
let mut count = 0;
while count < EVENT_CAPACITY && !self.cancel.is_cancelled() {
let Ok(event) = self.events.try_recv() else { break };
callback(event);
count += 1;
}
count
}
pub fn join(mut self) -> Result<(), String> { self.join_worker() }
pub fn stop(mut self) -> Result<(), String> { self.cancel(); self.join_worker() }
fn join_worker(&mut self) -> Result<(), String> {
self.worker.take().map_or(Ok(()), |worker| worker.join().unwrap_or_else(|_| Err("Application audio worker panicked".into())))
}
}
impl Drop for Capture {
fn drop(&mut self) { self.cancel(); let _ = self.join_worker(); }
}
/// Enumerate without recording. Retains platform capability and isolation metadata.
pub fn list(cancel: &Cancellation) -> Result<Value, String> {
cancel.check()?;
#[cfg(any(windows, target_os = "linux"))]
{ platform::list(cancel) }
#[cfg(not(any(windows, target_os = "linux")))]
{ Ok(json!({"supported":false,"platform":std::env::consts::OS,"reason":unsupported_reason(),"applications":[]})) }
}
#[cfg(not(any(windows, target_os = "linux")))]
fn unsupported_reason() -> &'static str {
if cfg!(target_os = "macos") {
"Selected-application audio requires an implemented Core Audio process-tap or ScreenCaptureKit helper, macOS SDK build, app signing and user audio-recording consent; this build has no macOS application-audio backend."
} else { "This platform has no selected-application audio capture backend." }
}
/// Start only an exact identity returned by `list`; initialization failures are joined.
pub fn capture(id: &str, cancel: Cancellation) -> Result<Capture, String> {
cancel.check()?;
#[cfg(any(windows, target_os = "linux"))]
{
let id = id.to_owned();
spawn_capture(cancel, move |cancel, sink| platform::capture(&id, cancel, sink))
}
#[cfg(not(any(windows, target_os = "linux")))]
{ let _ = id; Err(unsupported_reason().into()) }
}
fn spawn_capture(cancel: Cancellation, run: impl FnOnce(&Cancellation, &Sink) -> Result<(), String> + Send + 'static) -> Result<Capture, String> {
let (tx, events) = mpsc::sync_channel(EVENT_CAPACITY);
let requested = cancel.clone();
let worker = std::thread::Builder::new().name("app-audio-capture".into()).spawn(move || run(&requested, &Sink(tx))).map_err(|e| e.to_string())?;
Ok(Capture { cancel, events, worker: Some(worker) })
}
pub fn run(args: &[String]) -> ExitCode {
match dispatch(args) {
Ok(()) => ExitCode::SUCCESS,
Err(message) => {
eprintln!("{}", json!({"event":"error","code":"application_audio","message":message}));
ExitCode::from(1)
}
}
}
fn dispatch(args: &[String]) -> Result<(), String> {
let cancel = Cancellation::default();
match args {
[command] if command == "list" => {
println!("{}", list(&cancel)?);
Ok(())
},
[command, id] if command == "capture" => {
let capture = capture(id, cancel.clone())?;
// Only the standalone CLI owns this blocking stdin thread; library workers do not.
std::thread::Builder::new().name("app-audio-stop".into()).spawn(move || {
let _ = std::io::stdin().read(&mut [0u8; 1]);
cancel.cancel();
}).map_err(|e| e.to_string())?;
let mut stdout = std::io::stdout().lock();
let mut encoded = String::with_capacity(PCM_BYTES * 4 / 3);
loop {
match capture.recv_timeout(Duration::from_millis(50)) {
Ok(CaptureEvent::Format) => writeln!(stdout, "{{\"event\":\"format\",\"sampleRate\":48000,\"channels\":2,\"format\":\"s16le\",\"frames\":960}}"),
Ok(CaptureEvent::Pcm { sequence, bytes }) => {
encoded.clear(); STANDARD.encode_string(bytes, &mut encoded);
writeln!(stdout, "{{\"event\":\"pcm\",\"sequence\":{sequence},\"pcm\":\"{encoded}\"}}")
},
Err(mpsc::RecvTimeoutError::Timeout) => continue,
Err(mpsc::RecvTimeoutError::Disconnected) => break,
}.and_then(|_| stdout.flush()).map_err(|e| e.to_string())?;
}
capture.join()
},
_ => Err("usage: teamspeach-core app-audio list | app-audio capture <observed-id>".into()),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn bounded_consumer_preserves_format_and_drops_without_blocking() {
let capture = spawn_capture(Cancellation::default(), |_, sink| {
sink.format()?;
for sequence in 0..100 { sink.pcm(sequence, [7; PCM_BYTES])?; }
Ok(())
}).unwrap();
while !capture.is_finished() { std::thread::yield_now(); }
let mut events = Vec::new();
assert_eq!(capture.dispatch_pending(|event| events.push(event)), EVENT_CAPACITY);
assert!(matches!(events[0], CaptureEvent::Format));
assert!(matches!(events[1], CaptureEvent::Pcm { sequence: 0, .. }));
assert_eq!(capture.dispatch_pending(|_| panic!("queue should be empty")), 0);
capture.join().unwrap();
}
#[test]
fn cancellation_discards_queued_pcm_before_host_callback() {
let capture = spawn_capture(Cancellation::default(), |_, sink| {
sink.format()?;
sink.pcm(0, [9; PCM_BYTES])
}).unwrap();
while !capture.is_finished() { std::thread::yield_now(); }
capture.cancel();
assert_eq!(capture.dispatch_pending(|_| panic!("cancelled capture forwarded data")), 0);
assert!(matches!(capture.recv_timeout(Duration::ZERO), Err(mpsc::RecvTimeoutError::Disconnected)));
capture.stop().unwrap();
}
#[test]
fn callback_cancellation_stops_current_dispatch_batch() {
let cancel = Cancellation::default();
let capture = spawn_capture(cancel.clone(), |_, sink| {
sink.format()?;
sink.pcm(0, [9; PCM_BYTES])
}).unwrap();
while !capture.is_finished() { std::thread::yield_now(); }
assert_eq!(capture.dispatch_pending(|_| cancel.cancel()), 1);
capture.join().unwrap();
}
#[test]
fn missing_consumer_fails_without_blocking() {
let (tx, rx) = mpsc::sync_channel(EVENT_CAPACITY);
drop(rx);
let sink = Sink(tx);
assert!(sink.format().is_err());
assert!(sink.pcm(0, [0; PCM_BYTES]).is_err());
}
#[test]
fn drop_cancels_and_joins_worker() {
let finished = Arc::new(AtomicBool::new(false));
let completed = finished.clone();
let capture = spawn_capture(Cancellation::default(), move |cancel, _| {
while !cancel.is_cancelled() { std::thread::sleep(Duration::from_millis(1)); }
completed.store(true, Ordering::Release);
Ok(())
}).unwrap();
drop(capture);
assert!(finished.load(Ordering::Acquire));
}
#[test]
fn worker_errors_and_panics_are_joined() {
let capture = spawn_capture(Cancellation::default(), |_, _| Err("source ended".into())).unwrap();
assert_eq!(capture.join().unwrap_err(), "source ended");
let capture = spawn_capture(Cancellation::default(), |_, _| panic!("fixture")).unwrap();
assert_eq!(capture.join().unwrap_err(), "Application audio worker panicked");
}
#[test]
fn cancelled_enumeration_does_not_access_platform() {
let cancel = Cancellation::default();
cancel.cancel();
assert!(list(&cancel).is_err());
assert!(capture("not-observed", cancel).is_err());
}
}
+321
View File
@@ -0,0 +1,321 @@
//! Linux selected playback-stream capture through PulseAudio / PipeWire-Pulse.
//! Runtime prerequisites: pactl with JSON output and parec with --monitor-stream.
//! No sink moves, volume changes, defaults, modules or persistent graph edits.
use std::io::Read;
use std::process::{Child, Command, Stdio};
use std::sync::{Arc, atomic::{AtomicBool, Ordering}, mpsc};
use std::time::{Duration, Instant};
use super::{Cancellation, Sink};
use serde::Serialize;
use serde_json::{json, Value};
const BYTES: usize = 3840;
const MAX_JSON: u64 = 4 * 1024 * 1024;
const TIMEOUT: Duration = Duration::from_secs(3);
const PREREQUISITE: &str = "Linux application audio requires pactl JSON support, parec --monitor-stream, and an accessible PulseAudio or PipeWire-Pulse user audio server with recording permission; native PipeWire without pipewire-pulse is not supported by this backend";
struct OwnedChild {
child: Child,
readers: Vec<std::thread::JoinHandle<()>>,
}
impl OwnedChild {
fn new(child: Child) -> Self { Self { child, readers: Vec::new() } }
}
impl Drop for OwnedChild {
fn drop(&mut self) {
// Only these exact helper children are terminated. Killing before joining
// releases blocking pipe reads, including early-return and panic paths.
let _ = self.child.kill();
let _ = self.child.wait();
for reader in self.readers.drain(..) { let _ = reader.join(); }
}
}
struct EndForwarding(Arc<AtomicBool>);
impl Drop for EndForwarding {
fn drop(&mut self) { self.0.store(true, Ordering::Release); }
}
fn command(program: &str) -> Command {
let mut command = Command::new(program);
command.stdin(Stdio::null()).stderr(Stdio::null()).stdout(Stdio::piped()).env("LC_ALL", "C");
#[cfg(target_os = "linux")]
{
use std::os::unix::process::CommandExt;
unsafe extern "C" { fn prctl(option: i32, ...) -> i32; fn getppid() -> i32; }
let parent = std::process::id() as i32;
unsafe { command.pre_exec(move || {
// Kill this owned subprocess if its native/CLI host is forcibly terminated.
if prctl(1, 15, 0, 0, 0) != 0 || getppid() != parent { return Err(std::io::Error::last_os_error()); }
Ok(())
}); }
}
command
}
fn output(program: &str, args: &[&str], cancel: &Cancellation) -> Result<Vec<u8>, String> {
cancel.check()?;
let child = OwnedChild::new(command(program).args(args).spawn().map_err(|e| format!("{PREREQUISITE}: {program}: {e}"))?);
collect_output(child, program, cancel)
}
fn collect_output(mut child: OwnedChild, program: &str, cancel: &Cancellation) -> Result<Vec<u8>, String> {
let stdout = child.child.stdout.take().ok_or("Missing command stdout")?;
let (tx, rx) = mpsc::sync_channel(1);
child.readers.push(std::thread::Builder::new().name("app-audio-query".into()).spawn(move || {
let mut bytes = Vec::new();
let result = stdout.take(MAX_JSON + 1).read_to_end(&mut bytes).map(|_| bytes);
let _ = tx.send(result);
}).map_err(|e| e.to_string())?);
let start = Instant::now();
let mut result = None;
loop {
cancel.check()?;
if result.is_none() {
match rx.try_recv() {
Ok(bytes) => {
let bytes = bytes.map_err(|e| e.to_string())?;
if bytes.len() as u64 > MAX_JSON { return Err("Audio server response exceeds limit".into()); }
result = Some(bytes);
},
Err(mpsc::TryRecvError::Empty) => {},
Err(mpsc::TryRecvError::Disconnected) => return Err("Audio server output reader stopped".into()),
}
}
if let Some(status) = child.child.try_wait().map_err(|e| e.to_string())? {
if !status.success() { return Err(format!("{PREREQUISITE}: {program} exited with {status}")); }
if let Some(bytes) = result { return Ok(bytes); }
}
if start.elapsed() >= TIMEOUT { return Err(format!("{program}: audio server timeout")); }
std::thread::sleep(Duration::from_millis(10));
}
}
fn rows(kind: &str, cancel: &Cancellation) -> Result<Vec<Value>, String> {
serde_json::from_slice(&output("pactl", &["--format=json", "list", kind], cancel)?).map_err(|e| format!("pactl JSON: {e}"))
}
fn number(value: &Value) -> Option<u64> { value.as_u64().or_else(|| value.as_str()?.parse().ok()) }
fn process_stat(text: &str) -> Option<(u32, u64)> {
// comm may contain spaces and parentheses; field 3 starts after the final ')'.
let fields: Vec<_> = text.rsplit_once(')')?.1.split_whitespace().collect();
Some((fields.get(1)?.parse().ok()?, fields.get(19)?.parse().ok()?))
}
fn process(pid: u32) -> Result<(u32, u64), String> {
process_stat(&std::fs::read_to_string(format!("/proc/{pid}/stat")).map_err(|e| e.to_string())?).ok_or_else(|| "Malformed process identity".into())
}
#[derive(Serialize)]
struct Application {
id: String,
label: String,
pid: u32,
ancestors: Vec<u32>,
#[serde(skip)] index: u64,
#[serde(skip)] monitor: String,
}
fn application(row: &Value, sinks: &[Value], start_time: u64, ancestors: Vec<u32>) -> Option<Application> {
let index = number(&row["index"])?;
let client = number(&row["client"])?;
let sink = number(&row["sink"])?;
let props = &row["properties"];
let pid = u32::try_from(number(&props["application.process.id"])?).ok()?;
if pid == 0 { return None; }
let serial = number(&props["object.serial"]).unwrap_or(index);
let sink = sinks.iter().find(|s| number(&s["index"]) == Some(sink))?;
let monitor = sink["monitor_source_name"].as_str()?.to_owned();
if monitor.is_empty() || monitor.len() > 1024 || monitor.chars().any(char::is_control) { return None; }
let label = props["application.name"].as_str().or_else(|| props["application.process.binary"].as_str()).unwrap_or("Audio application");
let media = props["media.name"].as_str().unwrap_or("Playback");
Some(Application {
id: format!("pulse:{index}:{client}:{}:{serial}:{pid}:{start_time}", number(&sink["index"])?),
label: format!("{label} — {media}"), pid, ancestors, index, monitor,
})
}
fn applications(cancel: &Cancellation) -> Result<Vec<Application>, String> {
let sinks = rows("sinks", cancel)?;
let streams = rows("sink-inputs", cancel)?;
let mut result = Vec::new();
for row in streams {
let Some(pid) = number(&row["properties"]["application.process.id"]).and_then(|p| u32::try_from(p).ok()) else { continue };
let Ok((mut parent, start_time)) = process(pid) else { continue };
let mut ancestors = Vec::new();
while parent != 0 && parent != pid && !ancestors.contains(&parent) {
ancestors.push(parent);
let Ok((next, _)) = process(parent) else { break };
parent = next;
}
if let Some(app) = application(&row, &sinks, start_time, ancestors) { result.push(app); }
}
Ok(result)
}
fn prerequisites(cancel: &Cancellation) -> Result<(), String> {
let help = output("parec", &["--help"], cancel)?;
if !String::from_utf8_lossy(&help).contains("--monitor-stream") { return Err(PREREQUISITE.into()); }
Ok(())
}
pub fn list(cancel: &Cancellation) -> Result<Value, String> {
let result = prerequisites(cancel).and_then(|_| applications(cancel));
cancel.check()?;
Ok(match result {
Ok(apps) => json!({"supported":true,"platform":"linux","scope":"audio-stream","backend":"pulseaudio-monitor-stream","applications":apps}),
Err(reason) => json!({"supported":false,"platform":"linux","reason":reason,"applications":[]}),
})
}
pub fn capture(id: &str, cancel: &Cancellation, sink: &Sink) -> Result<(), String> {
match capture_inner(id, cancel, sink) {
Err(_) if cancel.is_cancelled() => Ok(()),
result => result,
}
}
fn capture_inner(id: &str, cancel: &Cancellation, sink: &Sink) -> Result<(), String> {
prerequisites(cancel)?;
let app = applications(cancel)?.into_iter().find(|a| a.id == id).ok_or("Selected audio-stream identity is stale; refresh the application list")?;
// Monitor removal/change before starting capture. Any selected-stream change fails closed.
let mut subscription = OwnedChild::new(command("pactl").arg("subscribe").spawn().map_err(|e| e.to_string())?);
let subscription_out = subscription.child.stdout.take().ok_or("Missing subscription stdout")?;
let changed = Arc::new(AtomicBool::new(false));
let changed_reader = changed.clone();
let target = format!("on sink-input #{}", app.index);
subscription.readers.push(std::thread::Builder::new().name("app-audio-subscribe".into()).spawn(move || {
use std::io::BufRead;
let mut reader = std::io::BufReader::new(subscription_out);
loop {
let mut line = String::new();
match reader.by_ref().take(4097).read_line(&mut line) {
Ok(n) if n > 0 && n <= 4096 => {
if line.trim_end().ends_with(&target) { break; }
},
_ => break,
}
}
changed_reader.store(true, Ordering::Release);
}).map_err(|e| e.to_string())?);
let monitor_arg = format!("--device={}", app.monitor);
let index_arg = format!("--monitor-stream={}", app.index);
cancel.check()?;
let mut recorder = OwnedChild::new(command("parec").args(["--raw", "--format=s16le", "--rate=48000", "--channels=2", "--latency-msec=20", &monitor_arg, &index_arg]).spawn().map_err(|e| e.to_string())?);
// Re-enumerate before forwarding anything: never use a recycled or moved stream index.
if !applications(cancel)?.iter().any(|a| a.id == id && a.monitor == app.monitor) || changed.load(Ordering::Acquire) {
return Err("Selected audio stream changed during activation".into());
}
let mut pcm = recorder.child.stdout.take().ok_or("Missing recorder stdout")?;
sink.format()?;
let pcm_sink = sink.clone();
let pcm_changed = changed.clone();
let requested = cancel.clone();
recorder.readers.push(std::thread::Builder::new().name("app-audio-read".into()).spawn(move || {
let mut sequence = 0;
while !requested.is_cancelled() && !pcm_changed.load(Ordering::Acquire) {
let mut block = [0; BYTES];
if pcm.read_exact(&mut block).is_err() { break; }
if requested.is_cancelled() || pcm_changed.load(Ordering::Acquire) { break; }
if pcm_sink.pcm(sequence, block).is_err() { break; }
sequence += 1;
}
}).map_err(|e| e.to_string())?);
let _end_forwarding = EndForwarding(changed.clone());
let mut checked = Instant::now();
while !cancel.is_cancelled() {
if changed.load(Ordering::Acquire) || subscription.readers.iter().any(|reader| reader.is_finished()) { return Err("Selected audio stream changed or disappeared".into()); }
if recorder.child.try_wait().map_err(|e| e.to_string())?.is_some() { return Err("Selected application recorder stopped".into()); }
if checked.elapsed() >= Duration::from_millis(250) {
if !applications(cancel)?.iter().any(|a| a.id == id && a.monitor == app.monitor) { return Err("Selected audio-stream identity changed or disappeared".into()); }
checked = Instant::now();
}
if recorder.readers.iter().any(|reader| reader.is_finished()) { return Err("Selected application PCM transport stopped".into()); }
std::thread::sleep(Duration::from_millis(10));
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
fn blocking_child() -> OwnedChild {
let (program, prefix) = crate::test_exec::self_invocation();
OwnedChild::new(command(&program).args(prefix)
.args(["app_audio_blocking_child_fixture", "--nocapture", "--test-threads=1"])
.env("TEAMSPEACH_APP_AUDIO_CHILD_FIXTURE", "1").spawn().unwrap())
}
#[test]
fn app_audio_blocking_child_fixture() {
if std::env::var_os("TEAMSPEACH_APP_AUDIO_CHILD_FIXTURE").is_none() { return; }
use std::io::Write;
println!("APP_AUDIO_CHILD_READY");
std::io::stdout().flush().unwrap();
std::thread::sleep(Duration::from_secs(30));
}
#[test]
fn dropping_child_unblocks_and_joins_pipe_reader() {
use std::io::BufRead;
let mut child = blocking_child();
let stdout = child.child.stdout.take().unwrap();
let finished = Arc::new(AtomicBool::new(false));
let completed = finished.clone();
let (ready_tx, ready_rx) = mpsc::sync_channel(1);
child.readers.push(std::thread::spawn(move || {
let mut reader = std::io::BufReader::new(stdout);
let mut line = String::new();
while reader.read_line(&mut line).unwrap_or(0) != 0 {
if line.contains("APP_AUDIO_CHILD_READY") { let _ = ready_tx.try_send(()); }
line.clear();
}
completed.store(true, Ordering::Release);
}));
ready_rx.recv_timeout(Duration::from_secs(5)).unwrap();
let start = Instant::now();
drop(child);
assert!(finished.load(Ordering::Acquire));
assert!(start.elapsed() < Duration::from_secs(2));
}
#[test]
fn cancellation_interrupts_blocked_helper_output() {
let child = blocking_child();
let cancel = Cancellation::default();
let requested = cancel.clone();
let canceller = std::thread::spawn(move || {
std::thread::sleep(Duration::from_millis(50));
requested.cancel();
});
let start = Instant::now();
let result = collect_output(child, "fixture", &cancel);
canceller.join().unwrap();
assert_eq!(result.unwrap_err(), "Application audio cancelled");
assert!(start.elapsed() < Duration::from_secs(2));
}
#[test]
fn controlled_executable_output_and_failure() {
let (program, prefix) = crate::test_exec::self_invocation();
let run = |option: &'static str| {
let mut args: Vec<&str> = prefix.iter().map(String::as_str).collect();
args.push(option);
output(&program, &args, &Cancellation::default())
};
let data = run("--list").unwrap();
assert!(String::from_utf8(data).unwrap().contains("identity_uses_start_time_serial_and_exact_monitor"));
assert!(run("--not-a-real-test-option").is_err());
}
#[test]
fn identity_uses_start_time_serial_and_exact_monitor() {
let row = json!({"index":7,"client":4,"sink":2,"properties":{"application.process.id":"99","object.serial":"12345","application.name":"Fixture","media.name":"Generated"}});
let sinks = vec![json!({"index":2,"monitor_source_name":"fixture.monitor"})];
let app = application(&row, &sinks, 987, vec![1]).unwrap();
assert_eq!(app.id, "pulse:7:4:2:12345:99:987");
assert_eq!(app.monitor, "fixture.monitor");
assert_ne!(app.id, application(&row, &sinks, 988, vec![]).unwrap().id);
assert!(application(&row, &[], 987, vec![]).is_none());
}
#[test]
fn proc_stat_handles_parenthesized_names() {
let text = "99 (test (tone)) S 42 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 987 0";
assert_eq!(process_stat(text), Some((42, 987)));
assert_eq!(process_stat("broken"), None);
}
}
+264
View File
@@ -0,0 +1,264 @@
//! WASAPI process-tree loopback (Windows build 20348+), without audio routing changes.
//! Activation follows Microsoft's ApplicationLoopback sample; COM bindings are windows-rs.
use std::collections::{BTreeMap, BTreeSet};
use std::sync::mpsc;
use super::{Cancellation, Sink};
use std::time::{Duration, Instant};
use serde::Serialize;
use serde_json::json;
use windows::core::{implement, Interface, HRESULT, PCWSTR, PWSTR};
use windows::Win32::Foundation::{CloseHandle, FILETIME, HANDLE, WAIT_OBJECT_0, WAIT_TIMEOUT};
use windows::Win32::Media::Audio::*;
use windows::Win32::System::Com::{CoCreateInstance, CoInitializeEx, CoUninitialize, CLSCTX_ALL, COINIT_MULTITHREADED, BLOB};
use windows::Win32::System::Com::StructuredStorage::PROPVARIANT;
use windows::Win32::System::Diagnostics::ToolHelp::*;
use windows::Win32::System::SystemInformation::OSVERSIONINFOW;
use windows::Win32::System::Threading::*;
use windows::Win32::System::Variant::VT_BLOB;
const FRAMES: usize = 960;
const BYTES: usize = FRAMES * 2 * 2;
#[link(name = "ntdll")]
extern "system" { fn RtlGetVersion(version: *mut OSVERSIONINFOW) -> i32; }
struct Com;
impl Com {
fn new() -> Result<Self, String> {
unsafe { CoInitializeEx(None, COINIT_MULTITHREADED).ok() }.map_err(error)?;
Ok(Self)
}
}
impl Drop for Com { fn drop(&mut self) { unsafe { CoUninitialize() }; } }
struct Handle(HANDLE);
impl Drop for Handle { fn drop(&mut self) { unsafe { let _ = CloseHandle(self.0); } } }
struct Started(IAudioClient);
impl Drop for Started { fn drop(&mut self) { unsafe { let _ = self.0.Stop(); } } }
fn error(e: windows::core::Error) -> String { format!("{e}") }
fn supported() -> bool {
let mut v = OSVERSIONINFOW { dwOSVersionInfoSize: std::mem::size_of::<OSVERSIONINFOW>() as u32, ..Default::default() };
unsafe { RtlGetVersion(&mut v) >= 0 && v.dwBuildNumber >= 20348 }
}
#[derive(Serialize)]
struct Application {
id: String,
label: String,
pid: u32,
ancestors: Vec<u32>,
}
fn process(pid: u32) -> Result<(Handle, String, String), String> {
let h = Handle(unsafe { OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION | PROCESS_SYNCHRONIZE, false, pid) }.map_err(error)?);
let mut creation = FILETIME::default();
let mut exit = FILETIME::default();
let mut kernel = FILETIME::default();
let mut user = FILETIME::default();
unsafe { GetProcessTimes(h.0, &mut creation, &mut exit, &mut kernel, &mut user) }.map_err(error)?;
if unsafe { WaitForSingleObject(h.0, 0) } != WAIT_TIMEOUT { return Err("Selected application has exited".into()); }
let mut path = [0u16; 32768];
let mut length = path.len() as u32;
unsafe { QueryFullProcessImageNameW(h.0, PROCESS_NAME_WIN32, PWSTR(path.as_mut_ptr()), &mut length) }.map_err(error)?;
let path = String::from_utf16_lossy(&path[..length as usize]);
let label = path.rsplit(['\\', '/']).next().unwrap_or(&path).to_owned();
let time = (u64::from(creation.dwHighDateTime) << 32) | u64::from(creation.dwLowDateTime);
Ok((h, format!("{pid}:{time:016x}"), label))
}
fn parents(cancel: &Cancellation) -> Result<BTreeMap<u32, u32>, String> {
let snapshot = Handle(unsafe { CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0) }.map_err(error)?);
let mut entry = PROCESSENTRY32W { dwSize: std::mem::size_of::<PROCESSENTRY32W>() as u32, ..Default::default() };
let mut result = BTreeMap::new();
unsafe {
Process32FirstW(snapshot.0, &mut entry).map_err(error)?;
loop {
cancel.check()?;
result.insert(entry.th32ProcessID, entry.th32ParentProcessID);
if Process32NextW(snapshot.0, &mut entry).is_err() { break; }
}
}
Ok(result)
}
fn applications(cancel: &Cancellation) -> Result<Vec<Application>, String> {
let tree = parents(cancel)?;
let mut ids = BTreeSet::new();
unsafe {
let enumerator: IMMDeviceEnumerator = CoCreateInstance(&MMDeviceEnumerator, None, CLSCTX_ALL).map_err(error)?;
let devices = enumerator.EnumAudioEndpoints(eRender, DEVICE_STATE_ACTIVE).map_err(error)?;
for index in 0..devices.GetCount().map_err(error)? {
cancel.check()?;
let device = devices.Item(index).map_err(error)?;
// A disappearing endpoint must not silently turn enumeration into an all-system selection.
let manager: IAudioSessionManager2 = device.Activate(CLSCTX_ALL, None).map_err(error)?;
let sessions = manager.GetSessionEnumerator().map_err(error)?;
for index in 0..sessions.GetCount().map_err(error)? {
cancel.check()?;
let session = sessions.GetSession(index).map_err(error)?;
if session.GetState().map_err(error)? == AudioSessionStateExpired { continue; }
let session: IAudioSessionControl2 = session.cast().map_err(error)?;
let pid = session.GetProcessId().map_err(error)?;
if pid != 0 && pid != std::process::id() { ids.insert(pid); }
}
}
}
let mut result = Vec::new();
for pid in ids {
cancel.check()?;
// Inaccessible/protected/exited processes are not selectable.
let Ok((_handle, id, label)) = process(pid) else { continue };
let mut ancestors = Vec::new();
let mut current = pid;
while let Some(&parent) = tree.get(&current) {
if parent == 0 || parent == pid || ancestors.contains(&parent) { break; }
ancestors.push(parent);
current = parent;
}
result.push(Application { id, label, pid, ancestors });
}
Ok(result)
}
pub fn list(cancel: &Cancellation) -> Result<serde_json::Value, String> {
cancel.check()?;
if !supported() {
return Ok(json!({"supported":false,"platform":"win32","reason":"WASAPI process-loopback requires Windows build 20348 or later","applications":[]}));
}
let _com = Com::new()?;
let tree = parents(cancel)?;
let mut host_ancestors = Vec::new();
let mut current = std::process::id();
while let Some(&parent) = tree.get(&current) {
if parent == 0 || host_ancestors.contains(&parent) { break; }
host_ancestors.push(parent);
current = parent;
}
let apps = applications(cancel)?;
cancel.check()?;
Ok(json!({"supported":true,"platform":"win32","scope":"process-tree","hostAncestors":host_ancestors,"applications":apps}))
}
#[implement(IActivateAudioInterfaceCompletionHandler)]
struct Completion {
tx: mpsc::SyncSender<()>,
// The callback retains activation input even if the caller's bounded wait times out.
_params: Box<AUDIOCLIENT_ACTIVATION_PARAMS>,
}
impl IActivateAudioInterfaceCompletionHandler_Impl for Completion_Impl {
fn ActivateCompleted(&self, _operation: windows::core::Ref<IActivateAudioInterfaceAsyncOperation>) -> windows::core::Result<()> {
let _ = self.tx.try_send(());
Ok(())
}
}
fn activate(pid: u32, cancel: &Cancellation) -> Result<IAudioClient, String> {
let mut params = Box::new(AUDIOCLIENT_ACTIVATION_PARAMS {
ActivationType: AUDIOCLIENT_ACTIVATION_TYPE_PROCESS_LOOPBACK,
Anonymous: AUDIOCLIENT_ACTIVATION_PARAMS_0 { ProcessLoopbackParams: AUDIOCLIENT_PROCESS_LOOPBACK_PARAMS {
TargetProcessId: pid, ProcessLoopbackMode: PROCESS_LOOPBACK_MODE_INCLUDE_TARGET_PROCESS_TREE,
} },
});
// VT_BLOB borrows callback-owned storage; normal Drop would incorrectly CoTaskMemFree it.
let mut variant = std::mem::ManuallyDrop::new(PROPVARIANT::default());
unsafe {
(*variant.Anonymous.Anonymous).vt = VT_BLOB;
(*variant.Anonymous.Anonymous).Anonymous.blob = BLOB {
cbSize: std::mem::size_of::<AUDIOCLIENT_ACTIVATION_PARAMS>() as u32, pBlobData: (&mut *params as *mut AUDIOCLIENT_ACTIVATION_PARAMS).cast(),
};
}
let (tx, rx) = mpsc::sync_channel(1);
let completion: IActivateAudioInterfaceCompletionHandler = Completion { tx, _params: params }.into();
let operation = unsafe { ActivateAudioInterfaceAsync(VIRTUAL_AUDIO_DEVICE_PROCESS_LOOPBACK, &IAudioClient::IID, Some(&*variant), &completion) }.map_err(error)?;
let start = Instant::now();
loop {
cancel.check()?;
match rx.recv_timeout(Duration::from_millis(50)) {
Ok(()) => break,
Err(mpsc::RecvTimeoutError::Timeout) if start.elapsed() < Duration::from_secs(10) => {},
_ => return Err("Application audio activation timed out".into()),
}
}
let mut status = HRESULT(0);
let mut object = None;
unsafe { operation.GetActivateResult(&mut status, &mut object) }.map_err(error)?;
status.ok().map_err(error)?;
object.ok_or("Application audio activation returned no interface")?.cast().map_err(error)
}
pub fn capture(id: &str, cancel: &Cancellation, sink: &Sink) -> Result<(), String> {
match capture_inner(id, cancel, sink) {
Err(_) if cancel.is_cancelled() => Ok(()),
result => result,
}
}
fn capture_inner(id: &str, cancel: &Cancellation, sink: &Sink) -> Result<(), String> {
if cancel.is_cancelled() { return Ok(()); }
if !supported() { return Err("WASAPI process-loopback requires Windows build 20348 or later".into()); }
let _com = Com::new()?;
let app = applications(cancel)?.into_iter().find(|app| app.id == id).ok_or("Selected application identity is stale or no longer has an audio session; refresh the list")?;
let (target, current_id, _) = process(app.pid)?;
if current_id != id { return Err("Selected application identity changed before capture".into()); }
let client = match activate(app.pid, cancel) {
Err(_) if cancel.is_cancelled() => return Ok(()),
result => result?,
};
// Recheck after asynchronous activation; never start an audio client for a recycled PID.
let (_recheck, current_id, _) = process(app.pid)?;
if current_id != id || unsafe { WaitForSingleObject(target.0, 0) } != WAIT_TIMEOUT {
return Err("Selected application exited during activation".into());
}
let format = WAVEFORMATEX { wFormatTag: 1, nChannels: 2, nSamplesPerSec: 48000, nAvgBytesPerSec: 192000, nBlockAlign: 4, wBitsPerSample: 16, cbSize: 0 };
unsafe { client.Initialize(AUDCLNT_SHAREMODE_SHARED, AUDCLNT_STREAMFLAGS_LOOPBACK | AUDCLNT_STREAMFLAGS_EVENTCALLBACK | AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM | AUDCLNT_STREAMFLAGS_SRC_DEFAULT_QUALITY, 0, 0, &format, None) }.map_err(error)?;
let event = Handle(unsafe { CreateEventW(None, false, false, PCWSTR::null()) }.map_err(error)?);
unsafe { client.SetEventHandle(event.0) }.map_err(error)?;
let reader: IAudioCaptureClient = unsafe { client.GetService() }.map_err(error)?;
if cancel.is_cancelled() { return Ok(()); }
unsafe { client.Start() }.map_err(error)?;
let _started = Started(client);
sink.format()?;
let mut block = [0u8; BYTES];
let mut used = 0;
let mut sequence = 0;
while !cancel.is_cancelled() {
if unsafe { WaitForSingleObject(target.0, 0) } != WAIT_TIMEOUT { return Err("Selected application exited".into()); }
let wait = unsafe { WaitForSingleObject(event.0, 50) };
if wait == WAIT_TIMEOUT { continue; }
if wait != WAIT_OBJECT_0 { return Err("Application audio capture event failed".into()); }
while !cancel.is_cancelled() && unsafe { reader.GetNextPacketSize() }.map_err(error)? > 0 {
let mut data = std::ptr::null_mut();
let mut frames = 0;
let mut flags = 0;
unsafe { reader.GetBuffer(&mut data, &mut frames, &mut flags, None, None) }.map_err(error)?;
let length = frames as usize * 4;
let silent = flags & AUDCLNT_BUFFERFLAGS_SILENT.0 as u32 != 0;
if !silent && data.is_null() {
unsafe { reader.ReleaseBuffer(frames) }.map_err(error)?;
return Err("Application audio returned a null PCM buffer".into());
}
if flags & AUDCLNT_BUFFERFLAGS_DATA_DISCONTINUITY.0 as u32 != 0 { used = 0; sequence += 1; }
let mut offset = 0;
while offset < length {
let count = (BYTES - used).min(length - offset);
if silent { block[used..used + count].fill(0); }
else { block[used..used + count].copy_from_slice(unsafe { std::slice::from_raw_parts(data.add(offset), count) }); }
used += count;
offset += count;
if used == BYTES {
if !cancel.is_cancelled() {
if let Err(message) = sink.pcm(sequence, block) {
unsafe { reader.ReleaseBuffer(frames) }.map_err(error)?;
return Err(message);
}
}
used = 0;
sequence += 1;
}
}
unsafe { reader.ReleaseBuffer(frames) }.map_err(error)?;
}
}
Ok(())
}
+608 -43
View File
@@ -4,6 +4,7 @@
use std::collections::{HashSet, VecDeque};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Mutex;
use std::time::{Duration, Instant};
use audiopus::coder::Encoder;
use audiopus::{Application, Bitrate, Channels, SampleRate};
@@ -23,17 +24,38 @@ const MAX_OPUS_PACKET: usize = 1275;
// ---------------------------------------------------------------- input queue
/// A capture-clock-stamped frame. Producers retain these tags through DSP and VAD;
/// a device callback must hand PCM to a worker rather than lock this queue itself.
#[derive(Clone, Debug)]
pub struct CapturedFrame {
pub pcm: Frame,
pub captured_at: Instant,
pub connection_generation: u64,
pub capture_epoch: u64,
/// A whisper frame may only use this registered whisper route, never normal voice.
pub whisper: Option<u32>,
}
pub enum AudioIn {
Frame(Box<Frame>),
Frame(CapturedFrame),
End,
}
/// Bounded single-consumer queue between the stdin reader and the session; drops the oldest
/// frame when full.
impl AudioIn {
fn is_frame(&self) -> bool { matches!(self, AudioIn::Frame(_)) }
}
/// Capture age is checked both on ingress and immediately before encoding/sending.
pub const MAX_CAPTURE_AGE: Duration = Duration::from_millis(200);
/// Bounded single-consumer queue between capture/DSP workers and the session.
/// The mutex also serializes synchronous network enqueue against invalidation.
pub struct AudioInQueue {
items: Mutex<VecDeque<AudioIn>>,
notify: Notify,
dropped: AtomicU64,
capture_epoch: AtomicU64,
connection_generation: AtomicU64,
}
/// Upper bound of queued entries: at most [`TX_QUEUE_FRAMES`] frames, and End markers are never
@@ -46,37 +68,103 @@ impl AudioInQueue {
items: Mutex::new(VecDeque::with_capacity(TX_QUEUE_ENTRIES)),
notify: Notify::new(),
dropped: AtomicU64::new(0),
capture_epoch: AtomicU64::new(1),
connection_generation: AtomicU64::new(0),
}
}
pub fn push(&self, item: AudioIn) {
pub fn epoch(&self) -> u64 { self.capture_epoch.load(Ordering::Acquire) }
pub fn generation(&self) -> u64 { self.connection_generation.load(Ordering::Acquire) }
/// A preliminary check, not a send permit. Use `with_valid_frame` for network enqueue.
pub fn validate(&self, frame: &CapturedFrame) -> bool {
self.validate_at(frame, Instant::now())
}
fn validate_at(&self, frame: &CapturedFrame, now: Instant) -> bool {
frame.capture_epoch == self.epoch()
&& frame.connection_generation == self.generation()
&& now.checked_duration_since(frame.captured_at).is_some_and(|age| age <= MAX_CAPTURE_AGE)
}
/// Execute encoding and synchronous network enqueue while invalidation is excluded.
/// Never await, block on network, or call queue-mutating methods in `send`.
/// Recheck `validate(frame)` after encoding, immediately before network enqueue:
/// encoding can itself exhaust the capture-age limit. Release this guard before
/// asynchronous error reporting. Once invalidation returns no old send can start.
pub fn with_valid_frame<R>(&self, frame: &CapturedFrame, send: impl FnOnce() -> R) -> Option<R> {
let _guard = self.items.lock().expect("audio queue poisoned");
self.validate(frame).then(send)
}
fn invalidate_locked(&self, q: &mut VecDeque<AudioIn>) -> u64 {
let epoch = self.epoch().checked_add(1).expect("capture epoch exhausted");
self.capture_epoch.store(epoch, Ordering::Release);
q.clear();
// The consumer must also stop its encoder/VAD burst, even if no PCM remains.
q.push_back(AudioIn::End);
epoch
}
/// Revoke queued, dequeued and VAD-held frames and ask the consumer to end its burst.
pub fn invalidate(&self) -> u64 {
let epoch = {
let mut q = self.items.lock().expect("audio queue poisoned");
self.invalidate_locked(&mut q)
};
self.notify.notify_one();
epoch
}
/// Every connection boundary revokes capture, including reapplying a generation.
pub fn set_generation(&self, generation: u64) {
{
let mut q = self.items.lock().expect("audio queue poisoned");
match item {
// Consecutive ends carry no extra information.
AudioIn::End if matches!(q.back(), Some(AudioIn::End)) => {}
AudioIn::End => q.push_back(item),
AudioIn::Frame(_) => {
let frames = q.iter().filter(|i| matches!(i, AudioIn::Frame(_))).count();
if frames >= TX_QUEUE_FRAMES {
if let Some(pos) = q.iter().position(|i| matches!(i, AudioIn::Frame(_))) {
q.remove(pos);
self.dropped.fetch_add(1, Ordering::Relaxed);
// Dropping a burst's only frame can leave two ends side by side.
if pos > 0
&& matches!(q.get(pos - 1), Some(AudioIn::End))
&& matches!(q.get(pos), Some(AudioIn::End))
{
q.remove(pos);
}
}
self.connection_generation.store(generation, Ordering::Release);
self.invalidate_locked(&mut q);
}
self.notify.notify_one();
}
/// Reject expired or wrong-boundary frames without ever allocating per frame.
pub fn try_push(&self, frame: CapturedFrame) -> bool {
{
let mut q = self.items.lock().expect("audio queue poisoned");
if !self.validate(&frame) { return false; }
let frames = q.iter().filter(|i| i.is_frame()).count();
if frames >= TX_QUEUE_FRAMES {
if let Some(pos) = q.iter().position(AudioIn::is_frame) {
q.remove(pos);
self.dropped.fetch_add(1, Ordering::Relaxed);
// Removing a burst's only frame can leave adjacent ends.
if pos > 0
&& matches!(q.get(pos - 1), Some(AudioIn::End))
&& matches!(q.get(pos), Some(AudioIn::End))
{
q.remove(pos);
}
q.push_back(item);
}
}
q.push_back(AudioIn::Frame(frame));
debug_assert!(q.len() <= TX_QUEUE_ENTRIES);
}
self.notify.notify_one();
true
}
pub fn push(&self, item: AudioIn) {
match item {
AudioIn::Frame(frame) => { self.try_push(frame); }
AudioIn::End => {
{
let mut q = self.items.lock().expect("audio queue poisoned");
if !matches!(q.back(), Some(AudioIn::End)) { q.push_back(AudioIn::End); }
debug_assert!(q.len() <= TX_QUEUE_ENTRIES);
}
self.notify.notify_one();
}
}
}
#[cfg(test)]
@@ -84,12 +172,33 @@ impl AudioInQueue {
pub fn pop(&self) -> Option<AudioIn> { self.items.lock().expect("audio queue poisoned").pop_front() }
/// Discard queued entries without revoking dequeued frames. Privacy/routing
/// boundaries must use `invalidate` instead. Overflow statistics are unchanged.
pub fn clear(&self) -> usize {
let mut q = self.items.lock().expect("audio queue poisoned");
let frames = q.iter().filter(|i| i.is_frame()).count();
q.clear();
frames
}
pub async fn notified(&self) { self.notify.notified().await }
/// Number of frames dropped since the last call.
pub fn take_dropped(&self) -> u64 { self.dropped.swap(0, Ordering::Relaxed) }
}
impl tsclientlib::AudioSendGuard for AudioInQueue {
fn with_valid_audio(&self, metadata: &tsclientlib::AudioSendMetadata, send: &mut dyn FnMut()) {
let _guard = self.items.lock().expect("audio queue poisoned");
if metadata.capture_epoch == self.epoch()
&& metadata.connection_generation == self.generation()
&& Instant::now().checked_duration_since(metadata.captured_at).is_some_and(|age| age <= MAX_CAPTURE_AGE)
{
send();
}
}
}
// ---------------------------------------------------------------- transmit
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
@@ -166,7 +275,13 @@ impl TxEncoder {
pub fn codec(&self) -> TxCodec { self.codec }
/// Encode one mono frame into a voice packet for the current channel.
pub fn encode(&mut self, frame: &Frame) -> Result<OutPacket, audiopus::Error> {
pub fn encode(&mut self, frame: &Frame) -> Result<OutPacket, audiopus::Error> { self.encode_to(frame, None) }
/// Encode one mono frame: ordinary voice (`C2S`) when `whisper` is `None`, otherwise a whisper
/// packet to that route only (`C2SWhisper`/`C2SWhisperNew`, see [`crate::whisper::packet`]).
pub fn encode_to(
&mut self, frame: &Frame, whisper: Option<&mut crate::whisper::Route>,
) -> Result<OutPacket, audiopus::Error> {
let len = match self.codec {
TxCodec::OpusVoice => self.encoder.encode(&frame[..], &mut self.out[..])?,
TxCodec::OpusMusic => {
@@ -177,7 +292,11 @@ impl TxEncoder {
self.encoder.encode(&self.stereo[..], &mut self.out[..])?
}
};
Ok(OutAudio::new(&AudioData::C2S { id: 0, codec: self.codec.codec_type(), data: &self.out[..len] }))
let codec = self.codec.codec_type();
Ok(match whisper {
None => OutAudio::new(&AudioData::C2S { id: 0, codec, data: &self.out[..len] }),
Some(route) => crate::whisper::packet(route, codec, &self.out[..len]),
})
}
}
@@ -186,6 +305,11 @@ pub fn end_of_voice(codec: TxCodec) -> OutPacket {
OutAudio::new(&AudioData::C2S { id: 0, codec: codec.codec_type(), data: &[] })
}
/// The empty whisper packet that ends a whisper transmission, addressed to the same route as its audio.
pub fn end_of_whisper(codec: TxCodec, route: &mut crate::whisper::Route) -> OutPacket {
crate::whisper::packet(route, codec.codec_type(), &[])
}
// ---------------------------------------------------------------- receive
pub enum RxEvent {
@@ -201,6 +325,16 @@ pub struct Receiver {
mix: Vec<f32>,
speakers: Vec<u16>,
unsupported_reported: HashSet<u16>,
/// Clients whose current talk spurt reaches us as whisper (`S2CWhisper`).
whisperers: HashSet<u16>,
/// Whisper spurts started since the last [`Receiver::take_whisper_starts`] (official `onWhisperStart`).
whisper_starts: Vec<u16>,
/// Official receive mode "Deny All": incoming whisper audio is dropped locally.
deny_whispers: bool,
/// Scratch for [`Receiver::mix_tapped`]: speakers whose queue last decoded a whisper packet.
whispering_now: Vec<u16>,
/// Per-speaker playback AGC (`voice_dsp.rs`).
dsp: crate::voice_dsp::PlaybackDsp,
}
pub struct Mixed<'a> {
@@ -215,23 +349,71 @@ impl Receiver {
mix: vec![0.0; FRAME_SAMPLES * 2],
speakers: Vec::new(),
unsupported_reported: HashSet::new(),
whisperers: HashSet::new(),
whisper_starts: Vec::new(),
deny_whispers: false,
whispering_now: Vec::new(),
dsp: Default::default(),
}
}
/// Per-speaker playback AGC ("Automatically level the volume of other users", voice_dsp.rs).
pub fn set_playback_agc(&mut self, enabled: bool) { self.dsp.set_agc(enabled); }
/// Drop all speaker state (connection or channel context changed). Returns who was talking.
pub fn reset(&mut self) -> Vec<u16> {
let talking: Vec<u16> = self.handler.get_queues().keys().map(|c| c.0).collect();
self.handler.reset();
// Client ids are recycled by the server; report codec problems afresh.
self.unsupported_reported.clear();
self.whisperers.clear();
self.whisper_starts.clear();
self.dsp.reset();
talking
}
/// Discard queued audio before the server can recycle a departed client's numeric ID.
pub fn remove_client(&mut self, client_id: u16) {
self.handler.get_mut_queues().remove(&ClientId(client_id));
self.unsupported_reported.remove(&client_id);
self.whisperers.remove(&client_id);
self.dsp.remove(client_id);
}
/// Applies the incoming whisper policy. Switching to deny also drops whisper audio already queued;
/// returns the speakers whose queue was removed (they stopped talking).
pub fn set_deny_whispers(&mut self, deny: bool) -> Vec<u16> {
if self.deny_whispers == deny {
return Vec::new();
}
self.deny_whispers = deny;
if !deny {
return Vec::new();
}
let removed: Vec<u16> = self.whisperers.drain().collect();
let queues = self.handler.get_mut_queues();
for id in &removed {
queues.remove(&ClientId(*id));
self.dsp.remove(*id);
}
self.whisper_starts.clear();
removed
}
/// Clients who started whispering to us since the last call (deduplicated per talk spurt).
pub fn take_whisper_starts(&mut self) -> std::vec::Drain<'_, u16> { self.whisper_starts.drain(..) }
pub fn handle_packet(&mut self, packet: InAudioBuf) -> RxEvent {
let (from, codec) = match packet.data().data() {
AudioData::S2C { from, codec, .. } | AudioData::S2CWhisper { from, codec, .. } => (*from, *codec),
// tsclientlib's jitter buffer treats a payload of at most one byte as end of stream.
let (from, codec, whisper, end) = match packet.data().data() {
AudioData::S2C { from, codec, data, .. } => (*from, *codec, false, data.len() <= 1),
AudioData::S2CWhisper { from, codec, data, .. } => (*from, *codec, true, data.len() <= 1),
_ => return RxEvent::None,
};
if whisper && self.deny_whispers {
debug!(client = from, "incoming whisper ignored (receive mode: deny all)");
return RxEvent::None;
}
if codec != CodecType::OpusVoice && codec != CodecType::OpusMusic {
return if self.unsupported_reported.insert(from) {
RxEvent::Unsupported { client_id: from, codec }
@@ -239,6 +421,14 @@ impl Receiver {
RxEvent::None
};
}
if whisper && !end {
if self.whisperers.insert(from) {
self.whisper_starts.push(from);
}
} else if whisper || !end {
// An empty whisper packet ends the whisper spurt; ordinary voice ends whispering.
self.whisperers.remove(&from);
}
match self.handler.handle_packet(ClientId(from), packet) {
Ok(Some(id)) => RxEvent::Started(id.0),
Ok(None) => RxEvent::None,
@@ -250,20 +440,51 @@ impl Receiver {
}
}
/// Pull 20 ms from every speaker's jitter buffer, mix, and downmix stereo to mono into `out`.
pub fn mix(&mut self, out: &mut [i16; FRAME_SAMPLES]) -> Mixed<'_> {
/// Pull 20 ms from every speaker's jitter buffer, apply local gains, and mix to mono.
/// Resolve the current client UID in `gain` each tick: recycled client IDs must never
/// inherit a previous occupant's volume. The resolver returns a linear 0..=MAX_USER_GAIN factor
/// (10^(10/20), from the user's dB modifier).
pub fn mix(&mut self, out: &mut [i16; FRAME_SAMPLES], gain: impl FnMut(u16) -> f32) -> Mixed<'_> {
self.mix_tapped(out, gain, |_, _, _| {})
}
/// [`Receiver::mix`] that also hands every speaker's decoded 20 ms to `tap` before local volume is
/// applied: `(client_id, whisper, interleaved stereo f32)`. `whisper` is whether the speaker's queue
/// last decoded a whisper packet (sampled before this tick's decode).
pub fn mix_tapped(
&mut self, out: &mut [i16; FRAME_SAMPLES], mut gain: impl FnMut(u16) -> f32,
mut tap: impl FnMut(u16, bool, &[f32]),
) -> Mixed<'_> {
self.whispering_now.clear();
for (id, queue) in self.handler.get_mut_queues() {
let value = gain(id.0);
// Keep invalid values out of the float sum, even if a caller bypasses IPC validation.
queue.volume = (if value.is_finite() { value.clamp(0.0, crate::voice_dsp::MAX_USER_GAIN) } else { 1.0 })
* self.dsp.speaker_gain(id.0);
if queue.is_whispering() {
self.whispering_now.push(id.0);
}
}
self.mix.iter_mut().for_each(|s| *s = 0.0);
self.speakers.clear();
let speakers = &mut self.speakers;
let whispering = &self.whispering_now;
let dsp = &mut self.dsp;
let stopped = self.handler.fill_buffer_with_proc(&mut self.mix, |id, data| {
if !data.is_empty() {
speakers.push(id.0);
}
dsp.observe(id.0, data);
tap(id.0, whispering.contains(&id.0), data);
});
for (o, lr) in out.iter_mut().zip(self.mix.chunks_exact(2)) {
let m = (lr[0] + lr[1]) * 0.5;
*o = (m.clamp(-1.0, 1.0) * f32::from(i16::MAX)) as i16;
}
for id in &stopped {
self.whisperers.remove(&id.0);
self.dsp.remove(id.0);
}
Mixed { speakers: &self.speakers, stopped: stopped.into_iter().map(|c| c.0).collect() }
}
}
@@ -316,6 +537,113 @@ mod tests {
InAudioBuf::try_new(Direction::S2C, out.into_vec()).unwrap()
}
#[test]
fn generated_whisper_codec_routes_and_incoming_block() {
use crate::whisper::{Route, Whisper};
use tsproto_packets::packets::{InPacket, PacketType};
for codec in [TxCodec::OpusVoice, TxCodec::OpusMusic] {
for group in [false, true] {
let route = if group { Route::Group { whisper_type: 3, target: 6, target_id: 0 } }
else { Route::Ids { channels: vec![12], clients: vec![7], uids: vec![None] } };
let mut state = Whisper::default();
state.start(4, 9, route);
let mut encoder = TxEncoder::new(codec, 6).unwrap();
let mut rx = Receiver::new();
let mut phase = 0.0;
let mut energy = 0u64;
for id in 0..40u16 {
let packet = encoder.encode_to(&sine(&mut phase, 220.0), state.route_mut(4, 9)).unwrap();
let parsed = InPacket::try_new(Direction::C2S, packet.data()).unwrap();
assert_eq!(parsed.header().packet_type(), PacketType::VoiceWhisper);
let audio = parsed.into_audio().unwrap();
let (format, payload) = match audio.data() {
AudioData::C2SWhisper { codec, channels, clients, data, .. } => {
assert!(!group); assert_eq!(channels, &[12]); assert_eq!(clients, &[7]); (*codec, *data)
},
AudioData::C2SWhisperNew { codec, whisper_type, target, data, .. } => {
assert!(group); assert_eq!((*whisper_type, *target), (3, 6)); (*codec, *data)
},
_ => panic!("whisper must never produce ordinary voice"),
};
let incoming = OutAudio::new(&AudioData::S2CWhisper { id, from: 7, codec: format, data: payload });
rx.handle_packet(InAudioBuf::try_new(Direction::S2C, incoming.into_vec()).unwrap());
let mut out = [0; FRAME_SAMPLES];
rx.mix(&mut out, |_| crate::voice_dsp::MAX_USER_GAIN);
energy += out.iter().map(|s| i64::from(*s).pow(2) as u64).sum::<u64>();
}
assert!(energy > 1_000_000, "real Opus whisper decoded no signal");
assert!(state.stop(4));
assert!(state.route_mut(4, 9).is_none(), "released frames have no route");
rx.set_deny_whispers(true);
let mut out = [1; FRAME_SAMPLES];
rx.mix(&mut out, |_| 1.0);
assert_eq!(out, [0; FRAME_SAMPLES], "deny all clears queued whisper samples");
}
}
}
/// Offline real encoder/receiver proof for PCM captured by audit-voice-timed.mjs.
/// Explicit opt-in: no device, socket or playback is opened by this test.
#[test]
#[ignore = "requires TEAMSPEACH_AUDIT_PCM and TEAMSPEACH_AUDIT_OUT"]
fn captured_speech_quality_matrix() {
use std::io::Write;
let input = std::fs::read(std::env::var("TEAMSPEACH_AUDIT_PCM").unwrap()).unwrap();
assert_eq!(input.len() % FRAME_BYTES, 0);
let dir = std::path::PathBuf::from(std::env::var("TEAMSPEACH_AUDIT_OUT").unwrap());
std::fs::create_dir_all(&dir).unwrap();
let mut reports = Vec::new();
for codec in [TxCodec::OpusVoice, TxCodec::OpusMusic] {
for quality in [0, 6, 10] {
let mut enc = TxEncoder::new(codec, quality).unwrap();
let config = serde_json::json!({ "codec": format!("{codec:?}"), "quality": quality,
"bitrate": format!("{:?}", enc.encoder.bitrate().unwrap()), "application": format!("{:?}", enc.encoder.application().unwrap()),
"complexity": enc.encoder.complexity().unwrap(), "lookahead": enc.encoder.lookahead().unwrap(),
"maxBandwidth": format!("{:?}", enc.encoder.max_bandwidth().unwrap()), "signal": format!("{:?}", enc.encoder.signal().unwrap()),
"vbr": enc.encoder.vbr().unwrap(), "constrainedVbr": enc.encoder.vbr_constraint().unwrap(),
"fec": enc.encoder.inband_fec().unwrap(), "dtx": enc.encoder.dtx().unwrap() });
let mut rx = Receiver::new();
let mut file = std::io::BufWriter::new(std::fs::File::create(dir.join(format!("{codec:?}-q{quality}.pcm"))).unwrap());
let mut frame = [0; FRAME_SAMPLES];
let mut decoded = [0; FRAME_SAMPLES];
let mut packets = 0usize;
let mut gate = crate::vad::VoiceGate::new(crate::vad::Sensitivity::Normal);
let mut gate_starts = Vec::new();
let mut gate_sent = 0usize;
for (index, bytes) in input.chunks_exact(FRAME_BYTES).enumerate() {
for (s, b) in frame.iter_mut().zip(bytes.chunks_exact(2)) { *s = i16::from_le_bytes([b[0], b[1]]); }
// Same lifecycle as a channel-context boundary: no preceding speech survives.
if index == 4500 { enc = TxEncoder::new(codec, quality).unwrap(); rx.reset(); gate.reset(); }
match gate.push(&frame) {
crate::vad::Decision::Start => { gate_starts.push(index); gate_sent += 1; }
crate::vad::Decision::Send | crate::vad::Decision::SendAndEnd => gate_sent += 1,
crate::vad::Decision::Hold => {}
}
let packet = enc.encode(&frame).unwrap(); packets += packet.content().len() - 3;
rx.handle_packet(as_s2c(packet, index as u16, 7));
rx.mix(&mut decoded, |_| 1.0);
for sample in decoded { file.write_all(&sample.to_le_bytes()).unwrap(); }
}
file.flush().unwrap();
reports.push(serde_json::json!({ "config": config, "payloadBytes": packets, "frames": input.len()/FRAME_BYTES,
"gateStarts": gate_starts, "gateSentFramesExcludingPreroll": gate_sent, "contextResetFrame": 4500 }));
}
}
std::fs::write(dir.join("codec-matrix.json"), serde_json::to_vec_pretty(&reports).unwrap()).unwrap();
}
#[test]
fn clear_discards_queued_frames_without_counting_drops() {
let q = AudioInQueue::new();
for _ in 0..3 {
q.push(AudioIn::Frame(captured(&q, 1)));
}
q.push(AudioIn::End);
assert_eq!(q.clear(), 3);
assert!(q.pop().is_none());
assert_eq!(q.take_dropped(), 0);
}
#[test]
fn encode_decode_mix_roundtrip_both_codecs() {
for codec in [TxCodec::OpusVoice, TxCodec::OpusMusic] {
@@ -331,7 +659,7 @@ mod tests {
assert_eq!(id, 7);
started = true;
}
let mixed = rx.mix(&mut out);
let mixed = rx.mix(&mut out, |_| 1.0);
if !mixed.speakers.is_empty() {
assert_eq!(mixed.speakers, &[7]);
energy += out.iter().map(|s| f64::from(*s).powi(2)).sum::<f64>();
@@ -343,7 +671,7 @@ mod tests {
rx.handle_packet(as_s2c(end_of_voice(codec), 40, 7));
let mut stopped = false;
for _ in 0..20 {
if rx.mix(&mut out).stopped.contains(&7) {
if rx.mix(&mut out, |_| 1.0).stopped.contains(&7) {
stopped = true;
break;
}
@@ -352,10 +680,138 @@ mod tests {
}
}
fn frame(tag: i16) -> AudioIn {
let mut f = Box::new([0i16; FRAME_SAMPLES]);
f[0] = tag;
AudioIn::Frame(f)
/// Real Opus encoders, S2C packet parsing, jitter buffers and decoders; no PCM echo mock.
#[test]
fn controlled_two_speaker_local_volume() {
for codec in [TxCodec::OpusVoice, TxCodec::OpusMusic] {
let mut enc_a = TxEncoder::new(codec, 6).unwrap();
let mut enc_b = TxEncoder::new(codec, 6).unwrap();
let mut phase_a = 0.0;
let mut phase_b = 0.0;
// Identical packets enter each independent real decoder. Solo references retain
// both queues, so startup buffering and packet-loss concealment match exactly.
let mut receivers: [Receiver; 8] = std::array::from_fn(|_| Receiver::new());
let mut frames = [[0i16; FRAME_SAMPLES]; 8];
let mut energy = [0u64; 8];
let mut saturated = 0usize;
let mut max_error = 0i32;
let mut proof_samples = Vec::new();
for sequence in 0..80u16 {
if sequence == 48 {
for receiver in &mut receivers { receiver.reset(); }
}
for (from, encoder, phase, frequency) in [
(7, &mut enc_a, &mut phase_a, 440.0),
(9, &mut enc_b, &mut phase_b, 730.0),
] {
let mut input = sine(phase, frequency);
if sequence >= 64 { for sample in input.iter_mut() { *sample *= 3; } }
let packet = encoder.encode(&input).unwrap();
let bytes = OutAudio::new(&AudioData::S2C {
id: sequence, from, codec: codec.codec_type(), data: &packet.content()[3..],
}).into_vec();
for receiver in &mut receivers {
receiver.handle_packet(InAudioBuf::try_new(Direction::S2C, bytes.clone()).unwrap());
}
}
let changing_gain = match sequence { 0..=15 => 1.0, 16..=31 => 0.0, 32..=47 => 0.5, _ => 1.0 };
let gains = [(1.0, 1.0), (1.0, 0.0), (0.0, 1.0), (0.5, 1.0),
(2.0, 1.0), (f32::NAN, 1.0), (changing_gain, 1.0), (0.0, 0.0)];
for (index, receiver) in receivers.iter_mut().enumerate() {
let (a, b) = gains[index];
receiver.mix(&mut frames[index], |id| if id == 7 { a } else { b });
energy[index] += frames[index].iter().map(|s| i64::from(*s).pow(2) as u64).sum::<u64>();
}
assert_eq!(frames[5], frames[0], "invalid gain cannot poison the mix");
if changing_gain == 0.0 {
assert_eq!(frames[6], frames[2], "muting target must leave the other peer bit-identical");
} else if changing_gain == 1.0 {
assert_eq!(frames[6], frames[0], "100% and restored volume must be bit-identical");
}
for sample in 0..FRAME_SAMPLES {
let a = f32::from(frames[1][sample]);
let b = f32::from(frames[2][sample]);
for (index, gain) in [(0, 1.0), (3, 0.5), (4, 2.0), (5, 1.0), (6, changing_gain)] {
let expected = (a * gain + b).clamp(-32767.0, 32767.0) as i32;
let error = (i32::from(frames[index][sample]) - expected).abs();
max_error = max_error.max(error);
assert!(error <= 3, "{codec:?} frame={sequence} mix={index} sample={sample}: error={error}");
}
assert_eq!(frames[7][sample], 0, "both peers muted must be digital silence");
if frames[4][sample].abs() == i16::MAX { saturated += 1; }
}
if [12, 24, 40, 56, 72].contains(&sequence) {
proof_samples.push(serde_json::json!({
"frame": sequence, "target_gain": changing_gain,
"target_only": &frames[1][200..208], "other_only": &frames[2][200..208],
"actual_mix": &frames[6][200..208], "both_unity": &frames[0][200..208],
}));
}
}
assert!(energy[1] > 1_000_000_000 && energy[2] > 1_000_000_000);
assert_eq!(energy[7], 0);
assert!(saturated > 0, "high-level sum must saturate, not wrap");
println!("LOCAL_VOLUME_PROOF {}", serde_json::json!({
"codec": format!("{codec:?}"), "frames": 80, "max_sample_error": max_error,
"saturated_samples": saturated, "energy": energy, "samples": proof_samples,
}));
}
}
#[test]
fn local_volume_decode_mix_subprocess_smoke() {
// Exercise the real encode/decode/mix proof in an isolated OS subprocess, not a
// server, live microphone, user profile or running desktop application's core.
let (program, prefix) = crate::test_exec::self_invocation();
let output = std::process::Command::new(program).args(prefix)
.args(["--exact", "audio::tests::controlled_two_speaker_local_volume", "--nocapture"])
.output().unwrap();
let stdout = String::from_utf8(output.stdout).unwrap();
assert!(output.status.success(), "child failed: {stdout}\n{}", String::from_utf8_lossy(&output.stderr));
assert_eq!(stdout.matches("LOCAL_VOLUME_PROOF ").count(), 2);
println!("LOCAL_VOLUME_SUBPROCESS {}\n{stdout}", output.status);
}
#[test]
fn removed_client_discards_queued_audio_before_id_reuse() {
let mut rx = Receiver::new();
let mut encoder = TxEncoder::new(TxCodec::OpusVoice, 6).unwrap();
let mut phase = 0.0;
for sequence in 0..4 {
let packet = encoder.encode(&sine(&mut phase, 440.0)).unwrap();
rx.handle_packet(as_s2c(packet, sequence, 7));
}
assert!(rx.handler.get_queues().contains_key(&ClientId(7)));
rx.remove_client(7);
let mut output = [1i16; FRAME_SAMPLES];
assert!(rx.mix(&mut output, |_| 1.0).speakers.is_empty());
assert_eq!(output, [0; FRAME_SAMPLES]);
// Reused ID starts a fresh decoder; the prior talker's queued tone cannot leak.
let mut replacement = TxEncoder::new(TxCodec::OpusVoice, 6).unwrap();
let packet = replacement.encode(&[0; FRAME_SAMPLES]).unwrap();
let bytes = OutAudio::new(&AudioData::S2C {
id: 0, from: 7, codec: CodecType::OpusVoice, data: &packet.content()[3..],
}).into_vec();
let mut fresh = Receiver::new();
fresh.handle_packet(InAudioBuf::try_new(Direction::S2C, bytes.clone()).unwrap());
assert!(matches!(rx.handle_packet(InAudioBuf::try_new(Direction::S2C, bytes).unwrap()), RxEvent::Started(7)));
rx.mix(&mut output, |_| 1.0);
let mut expected = [0; FRAME_SAMPLES];
fresh.mix(&mut expected, |_| 1.0);
// Lossy Opus silence can contain tiny quantization samples; compare exact real decoding.
assert_eq!(output, expected);
}
fn captured(q: &AudioInQueue, tag: i16) -> CapturedFrame {
let mut pcm = [0i16; FRAME_SAMPLES];
pcm[0] = tag;
CapturedFrame {
pcm,
captured_at: Instant::now(),
connection_generation: q.generation(),
capture_epoch: q.epoch(),
whisper: None,
}
}
#[test]
@@ -365,13 +821,13 @@ mod tests {
q.push(AudioIn::End);
}
assert_eq!(q.len(), 1);
q.push(frame(1));
q.push(AudioIn::Frame(captured(&q, 1)));
for _ in 0..1000 {
q.push(AudioIn::End);
}
assert_eq!(q.len(), 3);
assert!(matches!(q.pop(), Some(AudioIn::End)));
assert!(matches!(q.pop(), Some(AudioIn::Frame(f)) if f[0] == 1));
assert!(matches!(q.pop(), Some(AudioIn::Frame(f)) if f.pcm[0] == 1));
assert!(matches!(q.pop(), Some(AudioIn::End)));
assert!(q.pop().is_none());
}
@@ -380,7 +836,7 @@ mod tests {
fn alternating_bursts_overflow_stays_bounded_and_terminated() {
let q = AudioInQueue::new();
for i in 0..500i16 {
q.push(frame(i));
q.push(AudioIn::Frame(captured(&q, i)));
q.push(AudioIn::End);
q.push(AudioIn::End);
assert!(q.len() <= TX_QUEUE_ENTRIES, "len {}", q.len());
@@ -393,7 +849,7 @@ mod tests {
while let Some(item) = q.pop() {
match item {
AudioIn::Frame(f) => {
frames.push(f[0]);
frames.push(f.pcm[0]);
prev_end = false;
last_is_end = false;
}
@@ -408,6 +864,115 @@ mod tests {
assert_eq!(frames, (490..500).collect::<Vec<i16>>());
}
#[test]
fn capture_age_is_inclusive_and_never_accepts_future_frames() {
let q = AudioInQueue::new();
let mut frame = captured(&q, 1);
let now = frame.captured_at;
assert!(q.validate_at(&frame, now));
assert!(q.validate_at(&frame, now + MAX_CAPTURE_AGE));
// Windows Instant arithmetic rounds to the performance-counter resolution, not nanoseconds.
assert!(!q.validate_at(&frame, now + MAX_CAPTURE_AGE + Duration::from_millis(1)));
assert!(!q.validate_at(&frame, now - Duration::from_millis(1)));
frame.captured_at = Instant::now() - Duration::from_millis(600);
assert!(!q.try_push(frame));
let mut future = captured(&q, 2);
future.captured_at += Duration::from_secs(60);
assert!(!q.try_push(future));
assert!(q.pop().is_none());
assert_eq!(q.take_dropped(), 0);
}
#[test]
fn invalidation_revokes_dequeued_frames_and_preserves_one_end() {
let q = AudioInQueue::new();
let frame = captured(&q, 7);
assert!(q.try_push(frame.clone()));
let Some(AudioIn::Frame(dequeued)) = q.pop() else { panic!("missing frame") };
assert!(q.try_push(captured(&q, 8)));
q.push(AudioIn::End);
let epoch = q.invalidate();
assert_eq!(epoch, frame.capture_epoch + 1);
assert!(!q.validate(&dequeued));
assert!(!q.try_push(frame));
assert!(q.with_valid_frame(&dequeued, || panic!("revoked frame sent")).is_none());
q.invalidate();
q.push(AudioIn::End);
assert_eq!(q.len(), 1);
assert!(matches!(q.pop(), Some(AudioIn::End)));
assert!(q.try_push(captured(&q, 9)));
assert!(matches!(q.pop(), Some(AudioIn::Frame(frame)) if frame.pcm[0] == 9));
assert_eq!(q.take_dropped(), 0);
}
#[test]
fn generation_boundary_revokes_epoch_and_rejects_wrong_tags() {
let q = AudioInQueue::new();
let old = captured(&q, 1);
q.set_generation(7);
assert_eq!(q.generation(), 7);
assert_eq!(q.epoch(), old.capture_epoch + 1);
assert!(!q.validate(&old));
let mut wrong_generation = captured(&q, 2);
wrong_generation.connection_generation = 6;
assert!(!q.try_push(wrong_generation));
let mut wrong_epoch = captured(&q, 3);
wrong_epoch.capture_epoch += 1;
assert!(!q.try_push(wrong_epoch));
let epoch = q.epoch();
q.set_generation(7);
assert_eq!(q.epoch(), epoch + 1);
assert!(matches!(q.pop(), Some(AudioIn::End)));
assert!(q.pop().is_none());
}
#[test]
fn whisper_envelope_survives_queue_without_normal_voice_fallback() {
let q = AudioInQueue::new();
let mut frame = captured(&q, 4);
frame.whisper = Some(42);
let captured_at = frame.captured_at;
assert!(q.try_push(frame));
let Some(AudioIn::Frame(frame)) = q.pop() else { panic!("missing whisper frame") };
assert_eq!(frame.whisper, Some(42));
assert_eq!(frame.captured_at, captured_at);
assert_eq!(frame.pcm[0], 4);
}
#[test]
fn send_guard_serializes_invalidation_and_rechecks_capture_age() {
let q = AudioInQueue::new();
let frame = captured(&q, 1);
let order = AtomicU64::new(0);
std::thread::scope(|scope| {
let q = &q;
let frame = &frame;
let order = &order;
let (entered_tx, entered_rx) = std::sync::mpsc::channel();
let (release_tx, release_rx) = std::sync::mpsc::channel();
let sender = scope.spawn(move || {
q.with_valid_frame(frame, || {
assert!(q.items.try_lock().is_err(), "send must exclude invalidation");
entered_tx.send(()).unwrap();
release_rx.recv().unwrap();
assert_eq!(order.fetch_add(1, Ordering::SeqCst), 0);
})
});
entered_rx.recv().unwrap();
let invalidator = scope.spawn(move || {
q.invalidate();
assert_eq!(order.fetch_add(1, Ordering::SeqCst), 1);
});
release_tx.send(()).unwrap();
assert!(sender.join().unwrap().is_some());
invalidator.join().unwrap();
});
assert!(q.with_valid_frame(&frame, || panic!("old send after invalidation")).is_none());
let mut expired = captured(&q, 2);
expired.captured_at -= Duration::from_millis(600);
assert!(q.with_valid_frame(&expired, || panic!("expired frame encoded")).is_none());
}
#[test]
fn reset_rearms_unsupported_codec_report() {
let mut rx = Receiver::new();
@@ -425,14 +990,14 @@ mod tests {
fn queue_drops_oldest_frames() {
let q = AudioInQueue::new();
for i in 0..(TX_QUEUE_FRAMES + 3) {
let mut f = Box::new([0i16; FRAME_SAMPLES]);
f[0] = i as i16;
q.push(AudioIn::Frame(f));
let mut pcm = [0i16; FRAME_SAMPLES];
pcm[0] = i as i16;
q.try_push(CapturedFrame { pcm, captured_at: Instant::now(), connection_generation: q.generation(), capture_epoch: q.epoch(), whisper: None });
}
q.push(AudioIn::End);
assert_eq!(q.take_dropped(), 3);
match q.pop() {
Some(AudioIn::Frame(f)) => assert_eq!(f[0], 3),
Some(AudioIn::Frame(f)) => assert_eq!(f.pcm[0], 3),
_ => panic!(),
}
let mut n = 1;
+181
View File
@@ -0,0 +1,181 @@
//! `server_event` events: client/channel/server changes with reason and invoker, built from the
//! raw notifications (tsclientlib's book keeps neither kick messages nor invokers of most changes).
//! Used for the official "Server Events" log and notification policies (`docs/bridge.md` §5).
use serde_json::{json, Value};
use crate::rawcmd::RawNotification;
use crate::snapshot::RawExtras;
/// Extra notifications copied raw for events (the others are tapped already for the snapshot).
pub fn tapped(name: &[u8]) -> bool {
matches!(name, b"notifyclientmoved" | b"notifychannelmoved" | b"notifyserveredited")
}
/// Pinned `Enums.toml` `Reason` variants in declaration order (wire value = index).
const REASONS: [&str; 12] = [
"none", "moved", "subscription", "lost_connection", "kick_channel", "kick_server", "ban",
"server_stop", "disconnect", "channel_update", "channel_edit", "server_shutdown",
];
fn num<T: std::str::FromStr>(row: &crate::menu::Row, key: &str) -> Option<T> { row.get(key).and_then(|v| v.parse().ok()) }
fn invoker(row: &crate::menu::Row) -> Value {
match num::<u16>(row, "invokerid") {
Some(id) => json!({
"id": id,
"uid": row.get("invokeruid").filter(|u| !u.is_empty()),
"name": row.get("invokername").cloned().unwrap_or_default(),
}),
None => Value::Null,
}
}
fn reason(row: &crate::menu::Row) -> (Value, Value) {
match num::<usize>(row, "reasonid") {
Some(id) => (json!(id), REASONS.get(id).map_or(Value::Null, |r| json!(r))),
None => (Value::Null, Value::Null),
}
}
fn base(kind: &str, row: &crate::menu::Row) -> Value {
let (reason_id, reason) = reason(row);
json!({
"event": "server_event",
"kind": kind,
"reason_id": reason_id,
"reason": reason,
"invoker": invoker(row),
"message": row.get("reasonmsg").filter(|m| !m.is_empty()),
})
}
/// Events for one tapped notification. Must run BEFORE `extras.apply(raw)` so clients that leave
/// and channels that are deleted still have their last known labels.
pub fn from_raw(raw: &RawNotification, extras: &RawExtras, own_client: Option<u16>) -> Vec<Value> {
let mut out = Vec::new();
// Shared arguments (`ctid`, `reasonid`, invoker…) may only be present in the first entry.
let first = raw.items.first();
let shared = |row: &crate::menu::Row, key: &str| row.get(key).or_else(|| first.and_then(|f| f.get(key))).cloned();
for row in &raw.items {
let mut merged = row.clone();
for key in ["reasonid", "invokerid", "invokername", "invokeruid", "reasonmsg", "ctid", "cfid", "bantime"] {
if let Some(v) = shared(row, key) { merged.entry(key.to_owned()).or_insert(v); }
}
let row = &merged;
let client = |kind: &str, clid: u16| {
let label = extras.client_label(clid);
let mut v = base(kind, row);
v["client_id"] = json!(clid);
v["uid"] = json!(row.get("client_unique_identifier").cloned().or(label.uid));
v["nickname"] = json!(row.get("client_nickname").cloned().or(label.name));
v["is_self"] = json!(own_client == Some(clid));
(v, label.channel)
};
let channel = |kind: &str, cid: u64| {
let label = extras.channel_label(cid);
let mut v = base(kind, row);
v["channel_id"] = json!(cid);
v["name"] = json!(row.get("channel_name").cloned().or(label.name));
v["parent_id"] = json!(num::<u64>(row, "cpid").or(label.channel));
v
};
match raw.name.as_str() {
"notifycliententerview" => {
let Some(clid) = num(row, "clid") else { continue };
let (mut v, _) = client("client_enter", clid);
v["from_channel_id"] = json!(num::<u64>(row, "cfid").filter(|c| *c != 0));
v["to_channel_id"] = json!(num::<u64>(row, "ctid"));
out.push(v);
}
"notifyclientleftview" => {
let Some(clid) = num(row, "clid") else { continue };
let (mut v, last) = client("client_leave", clid);
v["from_channel_id"] = json!(num::<u64>(row, "cfid").filter(|c| *c != 0).or(last));
v["to_channel_id"] = json!(num::<u64>(row, "ctid").filter(|c| *c != 0));
v["ban_time_s"] = json!(num::<u64>(row, "bantime"));
out.push(v);
}
"notifyclientmoved" => {
let Some(clid) = num(row, "clid") else { continue };
let (mut v, last) = client("client_move", clid);
v["from_channel_id"] = json!(last);
v["to_channel_id"] = json!(num::<u64>(row, "ctid"));
out.push(v);
}
"notifyclientupdated" => {
let Some(clid) = num::<u16>(row, "clid") else { continue };
if let Some(flag) = row.get("client_talk_request") {
let (mut v, _) = client("talk_request", clid);
v["requested"] = json!(flag != "0");
v["message"] = json!(row.get("client_talk_request_msg").filter(|m| !m.is_empty()));
out.push(v);
}
if let Some(flag) = row.get("client_is_talker") {
let (mut v, _) = client("talker_changed", clid);
v["is_talker"] = json!(flag == "1");
out.push(v);
}
}
"notifychannelcreated" => if let Some(cid) = num(row, "cid") { out.push(channel("channel_created", cid)) },
// Description replies (`channelgetdescription`) carry no invoker; they are not edits.
"notifychanneledited" if row.contains_key("invokerid") => if let Some(cid) = num(row, "cid") { out.push(channel("channel_edited", cid)) },
"notifychanneldeleted" => if let Some(cid) = num(row, "cid") { out.push(channel("channel_deleted", cid)) },
"notifychannelmoved" => if let Some(cid) = num(row, "cid") {
let mut v = channel("channel_moved", cid);
v["from_parent_id"] = json!(extras.channel_label(cid).channel);
v["order"] = json!(num::<u64>(row, "order"));
out.push(v);
},
"notifyserveredited" => {
out.push(base("server_edited", row));
break;
}
_ => {}
}
}
out
}
#[cfg(test)]
mod tests {
use super::*;
use crate::rawcmd::parse;
#[test]
fn leave_and_kick_keep_last_label_and_reason() {
let mut x = RawExtras::default();
x.apply(&parse(br"notifycliententerview cfid=0 ctid=5 reasonid=0 clid=9 client_nickname=Ann client_unique_identifier=u9=").unwrap());
let enter = from_raw(&parse(br"notifycliententerview cfid=0 ctid=5 reasonid=0 clid=10 client_nickname=Bo").unwrap(), &x, Some(10));
assert_eq!(enter[0]["kind"], "client_enter");
assert_eq!(enter[0]["is_self"], true);
let moved = parse(br"notifyclientmoved ctid=6 reasonid=1 invokerid=3 invokername=Mod invokeruid=m= clid=9").unwrap();
let ev = from_raw(&moved, &x, Some(10));
assert_eq!((ev[0]["from_channel_id"].as_u64(), ev[0]["to_channel_id"].as_u64()), (Some(5), Some(6)));
assert_eq!(ev[0]["reason"], "moved");
assert_eq!(ev[0]["invoker"]["name"], "Mod");
x.apply(&moved);
let kick = parse(br"notifyclientleftview cfid=6 ctid=0 reasonid=5 invokerid=3 invokername=Mod reasonmsg=bye clid=9").unwrap();
let ev = from_raw(&kick, &x, Some(10));
assert_eq!(ev[0]["kind"], "client_leave");
assert_eq!(ev[0]["nickname"], "Ann");
assert_eq!(ev[0]["uid"], "u9=");
assert_eq!(ev[0]["reason"], "kick_server");
assert_eq!(ev[0]["message"], "bye");
assert_eq!(ev[0]["to_channel_id"], Value::Null);
}
#[test]
fn channel_and_talk_events() {
let mut x = RawExtras::default();
x.apply(&parse(br"channellist cid=4 cpid=0 channel_name=Old").unwrap());
let del = from_raw(&parse(br"notifychanneldeleted cid=4 invokerid=1 invokername=A").unwrap(), &x, None);
assert_eq!((del[0]["kind"].as_str(), del[0]["name"].as_str()), (Some("channel_deleted"), Some("Old")));
assert!(from_raw(&parse(br"notifychanneledited cid=4 reasonid=10 channel_description=x").unwrap(), &x, None).is_empty());
let talk = from_raw(&parse(br"notifyclientupdated clid=2 client_talk_request=1 client_talk_request_msg=pls").unwrap(), &x, None);
assert_eq!((talk[0]["kind"].as_str(), talk[0]["requested"].as_bool(), talk[0]["message"].as_str()), (Some("talk_request"), Some(true), Some("pls")));
let granted = from_raw(&parse(br"notifyclientupdated clid=2 client_is_talker=1 invokerid=1 invokername=A").unwrap(), &x, None);
assert_eq!(granted[0]["is_talker"], true);
assert!(from_raw(&parse(br"notifyclientupdated clid=2 client_input_muted=1").unwrap(), &x, None).is_empty());
}
}
File diff suppressed because it is too large. Load diff
+841
View File
@@ -0,0 +1,841 @@
//! Session integration for the channel file browser (`file_transfer`).
//!
//! Hooks called from `session.rs`: `files_request`, `files_result`, `files_raw`,
//! `files_download`, `files_upload`, `files_failed`, `files_fail_all`, `files_tick`.
use super::*;
use std::sync::atomic::{AtomicU64, Ordering};
use futures::FutureExt;
use tsclientlib::{FileDownloadResult, FileUploadResult};
use crate::file_transfer::{self as ft, Direction, Ended, ListJob, Local, Partial, Request, Stage, Tombstone, Transfer};
use crate::rawcmd::RawNotification;
/// Channel passwords travel hashed, like tsclientlib's own `download_file`/`upload_file`.
fn cpw(password: &str) -> String {
if password.is_empty() { String::new() } else { tsproto_types::crypto::encode_password(password.as_bytes()) }
}
fn internal(e: impl std::fmt::Display) -> ErrorObj { ErrorObj::new(ErrorCode::Internal, e.to_string()) }
fn not_active(transfer_id: u32) -> ErrorObj { ErrorObj::new(ErrorCode::NotFound, format!("file transfer {transfer_id} is not active")) }
fn ts_id(e: &tsclientlib::Error) -> Option<u32> {
match e {
tsclientlib::Error::CommandError(ce) => ce.error.to_u32(),
_ => None,
}
}
/// Error of a failed transfer stream/status (`FiletransferFailed`).
fn stream_error(e: &tsclientlib::Error) -> ErrorObj {
match e {
tsclientlib::Error::FiletransferIo(_) => ErrorObj::new(ErrorCode::Io, e.to_string()),
_ => lib_error(ErrorCode::ServerError, e),
}
}
/// Server error for a failed `ftinit*`; "file already exists" becomes `file_exists`.
fn init_error(e: &CommandError, name: &str) -> ErrorObj {
let err = command_error(e);
if e.error.to_u32() == Some(ft::TS_FILE_ALREADY_EXISTS) {
let mut exists = ft::exists_error(name);
exists.ts_error = err.ts_error;
return exists;
}
err
}
fn channel_known(c: &Conn, channel_id: u64) -> Result<(), ErrorObj> {
let book = c.con.get_state().map_err(|e| lib_error(ErrorCode::NotConnected, &e))?;
if !book.channels.contains_key(&ChannelId(channel_id)) {
return Err(ErrorObj::new(ErrorCode::NotFound, format!("channel {channel_id} is not visible")));
}
Ok(())
}
/// `ftstop` for a granted transfer. An aborted upload's partial file is deleted on the server; a
/// paused one (`keep`, official haltTransfer without deleteUnfinishedFile) is kept for resume.
/// Cancelling a transfer that is already paused sends nothing, like the official
/// pauseCancelTransfer for a PAUSED item: its stream is gone, and deleting by path later could
/// remove a file someone else stored there meanwhile, so the server partial stays.
fn send_stop(c: &mut Conn, server_ftid: u16, direction: Direction, keep: bool) {
let delete = if direction == Direction::Upload && !keep { "1" } else { "0" };
let cmd = menu::command("ftstop", &[("serverftfid", server_ftid.to_string()), ("delete", delete.into())]);
match c.send(cmd) {
Ok(handle) => {
c.files.stops.insert(handle, ());
}
Err(e) => warn!(%e, "ftstop could not be sent"),
}
}
/// Retire an ftid: it keeps catching late grants and statuses; a granted one is stopped.
fn release(c: &mut Conn, ftid: u16, server_ftid: Option<u16>, direction: Direction, keep: bool) {
c.files.tombstones.insert(ftid, Tombstone { since: Instant::now(), server_ftid, direction, keep });
if let Some(server_ftid) = server_ftid {
send_stop(c, server_ftid, direction, keep);
}
}
/// Remove a transfer that will not complete. Dropping the record aborts its I/O.
fn retire(c: &mut Conn, t: Transfer) {
if let Some(ftid) = t.ftid() {
release(c, ftid, t.server_ftid, t.direction, false);
}
drop(t);
}
/// Official pauseCancelTransfer(delete=false). A starting transfer, or one whose stream broke and
/// still holds its partial, is paused at once (the ftid is retired with `delete=0`); a running
/// stream is asked to halt at its next chunk and becomes `paused` in `files_tick`. Returns the
/// `paused` event when the pause is immediate.
fn halt(c: &mut Conn, i: usize) -> Option<Value> {
let t = &mut c.files.transfers[i];
match std::mem::replace(&mut t.stage, Stage::Paused) {
Stage::Running { ftid, task, halt } => {
halt.send_replace(true);
t.stage = Stage::Pausing { ftid, task, since: Instant::now() };
None
}
stage @ (Stage::Init { .. } | Stage::Lost { .. }) => {
t.stage = stage;
let ft::Interrupt::PausedNow { ftid } = t.interrupt() else { unreachable!("starting/broken transfers pause at once") };
let (server_ftid, direction) = (t.server_ftid.take(), t.direction);
t.reported = t.progress.load(Ordering::Relaxed);
let event = t.event("paused", None);
release(c, ftid, server_ftid, direction, true);
Some(event)
}
other => {
t.stage = other;
None
}
}
}
/// Send `ftinit*` for transfer `i` now. `resume` continues a paused transfer (official
/// doFileDownload/doFileUpload with resume: download `seekpos` = kept bytes, upload `resume=1`
/// without overwrite). On a send failure the transfer is removed and its `failed` event returned.
fn start(c: &mut Conn, i: usize, resume: bool) -> Result<Value, (Value, ErrorObj)> {
let ftid = c.transfer_id();
let t = &c.files.transfers[i];
let resume_at = t.resume_args(resume);
let cmd = init_command(t.direction, ftid, t.channel_id, &t.path, &t.cpw, t.total, t.overwrite, resume_at);
match c.send(cmd) {
Ok(handle) => {
c.files.inits.insert(handle, ftid);
c.files.start_seq += 1;
let started = c.files.start_seq;
let t = &mut c.files.transfers[i];
t.stage = Stage::Init { ftid, since: Instant::now() };
t.started = started;
t.interrupted = false;
Ok(t.event("starting", None))
}
Err(e) => {
let err = lib_error(ErrorCode::NotConnected, &e);
let t = c.files.transfers.remove(i);
Err((t.event("failed", Some(&err)), err))
}
}
}
/// `ftdeletefile` for validated paths (channel 0: server icons under their classic wire name).
fn delete_command(channel_id: u64, hashed_cpw: &str, paths: &[String]) -> OutCommand {
let mut cmd = menu::command("ftdeletefile", &[("cid", channel_id.to_string()), ("cpw", hashed_cpw.to_owned())]);
for (i, path) in paths.iter().enumerate() {
if i > 0 {
cmd.start_new_part();
}
cmd.write_arg("name", &ft::wire_name(channel_id, path));
}
cmd
}
/// `ftinitdownload` / `ftinitupload` for a queued transfer. Channel 0 icons are listed under
/// `/icons/` but transferred as `/icon_<id>`. `resume` holds a paused download's kept byte count
/// (any value marks an upload resume, which the server answers with its own seek position).
#[allow(clippy::too_many_arguments)]
fn init_command(direction: Direction, ftid: u16, channel_id: u64, path: &str, hashed_cpw: &str, total: u64, overwrite: bool, resume: Option<u64>) -> OutCommand {
let mut args = vec![
("clientftfid", ftid.to_string()),
("name", ft::wire_name(channel_id, path).to_owned()),
("cid", channel_id.to_string()),
("cpw", hashed_cpw.to_owned()),
];
match direction {
Direction::Download => {
args.extend([("seekpos", resume.unwrap_or(0).to_string()), ("proto", "1".to_owned())]);
menu::command("ftinitdownload", &args)
}
Direction::Upload => {
// Overwrite excludes resume (TS error file_overwrite_excludes_resume); the official
// client passes overwrite=!resume.
let (overwrite, resume) = if resume.is_some() { (false, true) } else { (overwrite, false) };
args.extend([
("size", total.to_string()),
("overwrite", if overwrite { "1" } else { "0" }.to_owned()),
("resume", if resume { "1" } else { "0" }.to_owned()),
("proto", "1".to_owned()),
]);
menu::command("ftinitupload", &args)
}
}
}
impl Session {
pub(super) async fn files_request(&mut self, id: &str, request: Request) -> Result<Option<Value>, ErrorObj> {
if !matches!(&request, Request::Cancel { .. } | Request::Pause { .. } | Request::Resume { .. } | Request::Transfers | Request::Config { .. }) {
self.connected_conn()?.files.require_legacy()?;
}
match request {
Request::Config { download_slots, upload_slots, download_limit, upload_limit } => {
let c = self.connected_conn()?;
let changed = c.files.slots != Some([download_slots, upload_slots]);
c.files.slots = Some([download_slots, upload_slots]);
c.files.download_rate.set(download_limit);
c.files.upload_rate.set(upload_limit);
// Official updateConcurrentTransferLimits: a changed limit pauses each channel's
// excess in-progress transfers; they wait for an explicit resume.
let mut events = Vec::new();
if changed {
for transfer_id in c.files.over_limit() {
if let Some(i) = c.files.index_of_id(transfer_id) {
events.extend(halt(c, i));
}
}
}
for e in events {
self.out.json(&e).await;
}
Ok(Some(json!({})))
}
Request::Pause { transfer_id } => {
let c = self.connected_conn()?;
let i = c.files.index_of_id(transfer_id).ok_or_else(|| not_active(transfer_id))?;
let t = &c.files.transfers[i];
if t.channel_id == 0 {
return Err(menu::bad("server icon transfers cannot be paused"));
}
if !matches!(t.stage, Stage::Init { .. } | Stage::Running { .. } | Stage::Lost { .. }) {
return Err(menu::bad("only a starting or running transfer can be paused"));
}
if let Some(e) = halt(c, i) {
self.out.json(&e).await;
}
Ok(Some(json!({ "transfer_id": transfer_id, "pausing": true })))
}
Request::Resume { transfer_id } => self.files_resume(transfer_id).await,
Request::List { channel_id, path, password } => {
let c = self.connected_conn()?;
if channel_id != 0 { channel_known(c, channel_id)?; }
if c.files.list_pending(channel_id, &path) {
return Err(menu::bad("a listing of this folder is already pending"));
}
let cmd = menu::command("ftgetfilelist", &[("cid", channel_id.to_string()), ("cpw", cpw(&password)), ("path", path.clone())]);
let handle = c.send(cmd).map_err(|e| lib_error(ErrorCode::NotConnected, &e))?;
c.files.lists.insert(handle, ListJob {
req: id.into(),
channel_id,
path,
entries: Vec::new(),
malformed: 0,
overflow: false,
finished: false,
result_ok: false,
started: Instant::now(),
});
Ok(None)
}
Request::Mkdir { channel_id, path, password } => {
let cmd = menu::command("ftcreatedir", &[("cid", channel_id.to_string()), ("cpw", cpw(&password)), ("dirname", path)]);
self.files_simple(id, channel_id, cmd)
}
Request::Rename { channel_id, password, from, to, target } => {
let mut args = vec![("cid", channel_id.to_string()), ("cpw", cpw(&password))];
if let Some((tcid, tpw)) = &target {
self.connected_conn().and_then(|c| channel_known(c, *tcid))?;
args.push(("tcid", tcid.to_string()));
args.push(("tcpw", cpw(tpw)));
}
args.push(("oldname", from));
args.push(("newname", to));
self.files_simple(id, channel_id, menu::command("ftrenamefile", &args))
}
Request::Delete { channel_id, password, paths } => {
let cmd = delete_command(channel_id, &cpw(&password), &paths);
self.files_simple(id, channel_id, cmd)
}
Request::Download { channel_id, password, path, dest_dir, subdirs, overwrite } => {
if channel_id != 0 { self.connected_conn().and_then(|c| channel_known(c, channel_id))?; }
let name = ft::file_name(&path).to_owned();
let checked = name.clone();
let dir = tokio::task::spawn_blocking(move || ft::prepare_download(&dest_dir, &subdirs, &checked, overwrite))
.await
.map_err(internal)??;
self.files_enqueue(Direction::Download, channel_id, path, &password, overwrite, Local::Download { dir, name, overwrite, partial: None }, 0)
}
Request::Upload { channel_id, password, path, source, overwrite } => {
if channel_id != 0 { self.connected_conn().and_then(|c| channel_known(c, channel_id))?; }
let (file, size, modified) = tokio::task::spawn_blocking(move || {
ft::prepare_upload(&source).map(|(file, size)| {
let modified = file.metadata().ok().and_then(|m| m.modified().ok());
(file, size, modified)
})
})
.await
.map_err(internal)??;
self.files_enqueue(Direction::Upload, channel_id, path, &password, overwrite, Local::Upload { file: Some(file), size, modified }, size)
}
Request::Cancel { transfer_id } => self.files_cancel(transfer_id).await,
Request::FetchImage { channel_id, path } => {
self.connected_conn().and_then(|c| channel_known(c, channel_id))?;
self.fetch_media(id, MediaKind::ChannelFile { channel_id, path }).await
}
Request::Transfers => {
let c = self.connected_conn()?;
let transfers: Vec<Value> = c.files.transfers.iter().map(|t| t.event(t.state(), None)).collect();
Ok(Some(json!({ "transfers": transfers, "storage": c.files.storage() })))
}
}
}
fn files_simple(&mut self, id: &str, channel_id: u64, cmd: OutCommand) -> Result<Option<Value>, ErrorObj> {
let c = self.connected_conn()?;
// Channel 0 (server icons) is not a tree channel; the parser admitted only icon paths for it.
if channel_id != 0 { channel_known(c, channel_id)?; }
let handle = c.send(cmd).map_err(|e| lib_error(ErrorCode::NotConnected, &e))?;
c.files.simple.insert(handle, id.into());
Ok(None)
}
/// Queue a transfer; it is started by `files_tick`, so the answer precedes its events.
#[allow(clippy::too_many_arguments)]
fn files_enqueue(
&mut self,
direction: Direction,
channel_id: u64,
path: String,
password: &str,
overwrite: bool,
local: Local,
total: u64,
) -> Result<Option<Value>, ErrorObj> {
let c = self.connected_conn()?;
if c.files.transfers.len() >= ft::MAX_TRANSFERS {
return Err(menu::bad("too many file transfers are queued"));
}
let id = c.files.next_transfer_id();
let now = Instant::now();
let t = Transfer {
id,
direction,
channel_id,
path,
cpw: cpw(password),
overwrite,
local,
total,
stage: Stage::Queued,
server_ftid: None,
confirmed: false,
progress: Arc::new(AtomicU64::new(0)),
commit: Arc::default(),
reported: 0,
seen: 0,
last_change: now,
last_emit: now,
started: 0,
interrupted: false,
granted: false,
};
let mut result = t.event("queued", None);
result.as_object_mut().expect("object").remove("event");
c.files.transfers.push(t);
Ok(Some(result))
}
async fn files_cancel(&mut self, transfer_id: u32) -> Result<Option<Value>, ErrorObj> {
let c = self.connected_conn()?;
let i = c
.files
.index_of_id(transfer_id)
.ok_or_else(|| not_active(transfer_id))?;
if matches!(c.files.transfers[i].stage, Stage::Confirming { .. }) {
return Err(menu::bad("the upload is complete and awaiting the server's confirmation"));
}
if !c.files.transfers[i].commit.cancel() {
return Err(menu::bad("the download is being committed and can no longer be cancelled"));
}
let t = c.files.transfers.remove(i);
let event = t.event("cancelled", Some(&ft::cancelled()));
retire(c, t);
self.out.json(&event).await;
Ok(Some(json!({ "transfer_id": transfer_id, "cancelled": true })))
}
/// Official resumeTransfers (paused) / forceStartTransfer (queued): make space in the channel by
/// pausing its earliest-started transfers, then start this one now, outside the queue.
async fn files_resume(&mut self, transfer_id: u32) -> Result<Option<Value>, ErrorObj> {
let c = self.connected_conn()?;
let i = c.files.index_of_id(transfer_id).ok_or_else(|| not_active(transfer_id))?;
let t = &c.files.transfers[i];
if t.channel_id == 0 {
return Err(menu::bad("server icon transfers cannot be resumed"));
}
let resume = match t.stage {
Stage::Paused => true,
Stage::Queued => false,
_ => return Err(menu::bad("only a paused or queued transfer can be started")),
};
c.files.require_legacy()?;
let (direction, channel_id) = (t.direction, t.channel_id);
let mut events = Vec::new();
for other in c.files.make_space(direction, channel_id) {
if let Some(j) = c.files.index_of_id(other) {
events.extend(halt(c, j));
}
}
let i = c.files.index_of_id(transfer_id).expect("halting others keeps this transfer");
let started = start(c, i, resume);
let result = match started {
Ok(event) => {
events.push(event);
Ok(Some(json!({ "transfer_id": transfer_id, "state": "starting" })))
}
Err((event, err)) => {
events.push(event);
Err(err)
}
};
for e in events {
self.out.json(&e).await;
}
result
}
/// Start queued transfers while their channel is below its limit.
async fn files_pump(&mut self) {
let mut events = Vec::new();
if let Some(c) = self.conn.as_mut().filter(|c| c.connected()) {
for direction in [Direction::Download, Direction::Upload] {
while let Some(i) = c.files.next_startable(direction) {
events.push(start(c, i, false).unwrap_or_else(|(event, _)| event));
}
}
}
for e in events {
self.out.json(&e).await;
}
}
async fn files_answer_list(&mut self, handle: u16) {
let Some(c) = &mut self.conn else { return };
let Some(job) = c.files.lists.remove(&handle) else { return };
let hints = c
.con
.get_state()
.ok()
.and_then(|b| b.channels.get(&ChannelId(job.channel_id)))
.and_then(|ch| ch.permission_hints)
.map(|h| h.bits());
let req = job.req.clone();
match ft::list_result(job, ft::capabilities(hints), c.files.storage()) {
Ok(v) => self.out.ok(&req, v).await,
Err(e) => self.out.err(&req, e).await,
}
}
pub(super) async fn files_result(&mut self, handle: u16, res: Result<(), CommandError>) {
let Some(c) = &mut self.conn else { return };
if let Some(job) = c.files.lists.get_mut(&handle) {
match res {
Ok(()) => job.result_ok = true,
// An empty folder is answered with "database empty result set" and no rows.
Err(e) if e.error.to_u32() == Some(ft::TS_DATABASE_EMPTY_RESULT) => {
job.result_ok = true;
job.finished = true;
}
Err(e) => {
let req = c.files.lists.remove(&handle).expect("present").req;
self.out.err(&req, command_error(&e)).await;
return;
}
}
if job.finished {
self.files_answer_list(handle).await;
}
return;
}
if let Some(req) = c.files.simple.remove(&handle) {
match res {
Ok(()) => self.out.ok(&req, json!({})).await,
Err(e) => self.out.err(&req, command_error(&e)).await,
}
return;
}
if let Some(ftid) = c.files.inits.remove(&handle) {
let Err(e) = res else { return };
if c.files.tombstones.remove(&ftid).is_some() {
return;
}
if let Some(i) = c.files.index_of_ftid(ftid) {
let t = c.files.transfers.remove(i);
let event = t.event("failed", Some(&init_error(&e, ft::file_name(&t.path))));
drop(t);
self.out.json(&event).await;
}
return;
}
if c.files.stops.remove(&handle).is_some() {
if let Err(e) = res {
debug!(error = ?e.error, "ftstop rejected");
}
}
}
pub(super) async fn files_raw(&mut self, raw: &RawNotification) {
let Some(c) = &mut self.conn else { return };
for handle in c.files.apply_raw(raw) {
self.files_answer_list(handle).await;
}
}
pub(super) async fn files_download(&mut self, ftid: u16, result: FileDownloadResult) -> Option<FileDownloadResult> {
let Some(c) = &mut self.conn else { return Some(result) };
if let Some(tomb) = c.files.tombstones.remove(&ftid) {
drop(result);
if let Some(server_ftid) = tomb.server_ftid {
send_stop(c, server_ftid, tomb.direction, tomb.keep);
}
return None;
}
let Some(i) = c.files.index_of_ftid(ftid) else { return Some(result) };
let t = &mut c.files.transfers[i];
let (Stage::Init { .. }, Local::Download { dir, name, overwrite, partial }) = (&t.stage, &mut t.local) else {
warn!(ftid, "download grant for a transfer that is not waiting for one");
return self.files_refuse_grant(i, ErrorObj::new(ErrorCode::ServerError, "server granted an unexpected transfer")).await;
};
let resume = partial.take();
if let Some(p) = &resume {
// Taken as the whole file size (the server then sends the bytes after seekpos); not
// verified against a live server. Only a size change is observable: the legacy protocol
// offers no content identity, so a same-size replacement on the server is not detected.
let problem = if result.size != t.total || p.written > result.size {
Some("the server file size changed while the download was paused")
} else if !p.intact() {
Some("the paused download file was changed or removed")
} else {
None
};
if let Some(problem) = problem {
// Dropping `resume` deletes the partial only while it is still our file.
drop(resume);
return self.files_refuse_grant(i, ErrorObj::new(ErrorCode::Io, problem)).await;
}
}
let (dir, name, overwrite) = (dir.clone(), name.clone(), *overwrite);
t.total = result.size;
let (halt, halted) = tokio::sync::watch::channel(false);
let task = tokio::spawn(ft::download(
result.stream,
result.size,
t.id,
dir,
name,
overwrite,
resume,
t.progress.clone(),
t.commit.clone(),
c.files.download_rate.clone(),
halted,
));
t.stage = Stage::Running { ftid, task, halt };
t.granted = true;
t.last_change = Instant::now();
let event = t.event("running", None);
self.out.json(&event).await;
None
}
pub(super) async fn files_upload(&mut self, ftid: u16, result: FileUploadResult) -> Option<FileUploadResult> {
let Some(c) = &mut self.conn else { return Some(result) };
if let Some(tomb) = c.files.tombstones.remove(&ftid) {
drop(result);
if let Some(server_ftid) = tomb.server_ftid {
send_stop(c, server_ftid, tomb.direction, tomb.keep);
}
return None;
}
let Some(i) = c.files.index_of_ftid(ftid) else { return Some(result) };
let t = &mut c.files.transfers[i];
// The open source handle stays with the transfer for a later resume; the stream reads a
// duplicate. Its length and modification time must still be the ones seen when picked.
let file = match (&t.stage, &t.local) {
(Stage::Init { .. }, Local::Upload { file: Some(file), size, modified }) => Some(
ft::upload_source_unchanged(file, *size, *modified).and_then(|()| {
file.try_clone().map_err(|e| ErrorObj::new(ErrorCode::Io, format!("cannot read the file: {e}")))
}),
),
_ => None,
};
let file = match file {
Some(Ok(file)) => file,
Some(Err(e)) => return self.files_refuse_grant(i, e).await,
None => {
warn!(ftid, "upload grant for a transfer that is not waiting for one");
return self.files_refuse_grant(i, ErrorObj::new(ErrorCode::ServerError, "server granted an unexpected transfer")).await;
}
};
let t = &mut c.files.transfers[i];
let (halt, halted) = tokio::sync::watch::channel(false);
let task = tokio::spawn(ft::upload(result.stream, file, t.total, result.seek_position, t.progress.clone(), c.files.upload_rate.clone(), halted));
t.stage = Stage::Running { ftid, task, halt };
t.granted = true;
t.last_change = Instant::now();
let event = t.event("running", None);
self.out.json(&event).await;
None
}
/// Fail transfer `i` whose grant cannot be used; the granted server transfer is stopped. The
/// stream in the grant result was already dropped by the caller or is dropped here.
async fn files_refuse_grant<R>(&mut self, i: usize, error: ErrorObj) -> Option<R> {
let Some(c) = &mut self.conn else { return None };
let t = c.files.transfers.remove(i);
let event = t.event("failed", Some(&error));
retire(c, t);
self.out.json(&event).await;
None
}
pub(super) async fn files_failed(&mut self, ftid: u16, err: tsclientlib::Error) -> Option<tsclientlib::Error> {
let Some(c) = &mut self.conn else { return Some(err) };
if c.files.tombstones.remove(&ftid).is_some() {
return None;
}
let Some(i) = c.files.index_of_ftid(ftid) else { return Some(err) };
if ts_id(&err) == Some(ft::TS_FILE_TRANSFER_INTERRUPTED) {
// Official doFile* callbacks: FileTransferInterrupted pauses the item, keeping its partial.
let t = &mut c.files.transfers[i];
match t.interrupt() {
ft::Interrupt::PausedNow { ftid } => {
let (server_ftid, direction) = (t.server_ftid.take(), t.direction);
t.reported = t.progress.load(Ordering::Relaxed);
let event = t.event("paused", None);
release(c, ftid, server_ftid, direction, true);
self.out.json(&event).await;
return None;
}
ft::Interrupt::Halting | ft::Interrupt::Ignore => return None,
// Server icons cannot be resumed: fail as before pause support.
ft::Interrupt::Fail => {}
}
}
if ts_id(&err) == Some(ft::TS_FILE_TRANSFER_COMPLETE) {
let t = &mut c.files.transfers[i];
t.confirmed = true;
if matches!(t.stage, Stage::Confirming { .. }) {
let t = c.files.transfers.remove(i);
let event = t.event("done", None);
drop(t);
self.out.json(&event).await;
}
return None;
}
let t = c.files.transfers.remove(i);
let event = t.event("failed", Some(&stream_error(&err)));
drop(t);
self.out.json(&event).await;
None
}
/// Answer every file request and fail every transfer of the current connection.
pub(super) async fn files_fail_all(&mut self, why: &str) {
let Some(c) = &mut self.conn else { return };
let f = &mut c.files;
let reqs: Vec<String> = f.lists.drain().map(|(_, j)| j.req).chain(f.simple.drain().map(|(_, r)| r)).collect();
f.inits.clear();
f.stops.clear();
f.tombstones.clear();
let transfers: Vec<Transfer> = f.transfers.drain(..).collect();
let err = ErrorObj::new(ErrorCode::NotConnected, why);
for req in reqs {
self.out.err(&req, err.clone()).await;
}
for t in transfers {
let event = t.event("failed", Some(&err));
drop(t);
self.out.json(&event).await;
}
}
pub(super) async fn files_tick(&mut self) {
let now = Instant::now();
let mut events = Vec::new();
let mut answers = Vec::new();
{
let Some(c) = &mut self.conn else { return };
let late: Vec<u16> = c.files.lists.iter().filter(|(_, j)| now - j.started >= ft::LIST_DEADLINE).map(|(h, _)| *h).collect();
for h in late {
let job = c.files.lists.remove(&h).expect("present");
let msg = if job.result_ok { "server did not finish the file list" } else { "server did not answer the file list request" };
answers.push((job.req, ErrorObj::new(ErrorCode::ServerError, msg)));
}
c.files.tombstones.retain(|_, t| now - t.since < ft::TOMBSTONE_TTL);
let mut i = 0;
while i < c.files.transfers.len() {
let t = &mut c.files.transfers[i];
let bytes = t.progress.load(Ordering::Relaxed);
if bytes != t.seen {
t.seen = bytes;
t.last_change = now;
}
let finished = match &mut t.stage {
Stage::Running { task, .. } | Stage::Pausing { task, .. } if task.is_finished() => {
Some((&mut *task).now_or_never().expect("finished").unwrap_or_else(|e| Err(internal(e))))
}
_ => None,
};
enum Outcome {
Done,
Failed(ErrorObj),
/// Halted (`None`) or broken (`Some`) stream with its kept partial.
Stopped(Option<Partial>, Option<ErrorObj>),
Keep,
}
let outcome = match finished {
Some(Err(e)) => Outcome::Failed(e),
Some(Ok(Ended::Paused(partial))) => Outcome::Stopped(partial, None),
Some(Ok(Ended::Lost { error, partial })) => Outcome::Stopped(partial, Some(error)),
Some(Ok(Ended::Complete { closed })) if t.direction == Direction::Download || closed || t.confirmed => Outcome::Done,
Some(Ok(Ended::Complete { .. })) => {
let ftid = t.ftid().expect("running transfer has an ftid");
t.stage = Stage::Confirming { ftid, since: now };
Outcome::Keep
}
None => match &t.stage {
Stage::Init { since, .. } if now - *since >= ft::GRANT_DEADLINE => {
Outcome::Failed(ErrorObj::new(ErrorCode::ServerError, "server did not start the file transfer"))
}
Stage::Running { .. } if now - t.last_change >= ft::STALL_DEADLINE => {
Outcome::Failed(ErrorObj::new(ErrorCode::Io, "file transfer stalled"))
}
Stage::Pausing { since, .. } if now - *since >= ft::STALL_DEADLINE => {
Outcome::Failed(ErrorObj::new(ErrorCode::Io, "file transfer did not pause"))
}
// No interrupted status arrived for the broken stream: it failed.
Stage::Lost { since, error, .. } if now - *since >= ft::INTERRUPT_GRACE => Outcome::Failed(error.clone()),
Stage::Confirming { .. } if t.confirmed => Outcome::Done,
Stage::Confirming { since, .. } if now - *since >= ft::CONFIRM_DEADLINE => {
Outcome::Failed(ErrorObj::new(ErrorCode::ServerError, "server did not confirm the upload"))
}
_ => Outcome::Keep,
},
};
match outcome {
Outcome::Done => {
let t = c.files.transfers.remove(i);
t.progress.store(t.total, Ordering::Relaxed);
events.push(t.event("done", None));
}
Outcome::Failed(e) => {
let t = c.files.transfers.remove(i);
events.push(t.event("failed", Some(&e)));
let ended = !matches!(t.stage, Stage::Running { .. } | Stage::Pausing { .. } | Stage::Init { .. } | Stage::Lost { .. });
if ended {
drop(t);
} else {
retire(c, t);
}
}
Outcome::Stopped(kept, lost) => {
// A halt stopped at a chunk boundary, or the stream broke after an interrupted
// status: stop the server side with delete=0 and keep the partial file
// (download) / server partial (upload) for resume. A break without that
// status waits in `Lost` for it; a server icon's break fails at once.
let t = &mut c.files.transfers[i];
let ftid = t.ftid().expect("a stream task belongs to an ftid");
match t.stream_stopped(kept, lost, now) {
ft::Stopped::Paused => {
let (server_ftid, direction) = (t.server_ftid.take(), t.direction);
t.reported = t.progress.load(Ordering::Relaxed);
events.push(t.event("paused", None));
release(c, ftid, server_ftid, direction, true);
i += 1;
}
ft::Stopped::Waiting => i += 1,
ft::Stopped::Failed(e) => {
let t = c.files.transfers.remove(i);
events.push(t.event("failed", Some(&e)));
retire(c, t);
}
}
}
Outcome::Keep => {
let t = &mut c.files.transfers[i];
if matches!(t.stage, Stage::Running { .. }) && bytes != t.reported && now - t.last_emit >= ft::PROGRESS_INTERVAL {
t.reported = bytes;
t.last_emit = now;
events.push(t.event("running", None));
}
i += 1;
}
}
}
}
for (req, e) in answers {
self.out.err(&req, e).await;
}
for e in events {
self.out.json(&e).await;
}
self.files_pump().await;
}
}
#[cfg(test)]
mod tests {
use super::*;
fn content(cmd: OutCommand) -> String { String::from_utf8(cmd.into_packet().content().to_vec()).unwrap() }
#[test]
fn server_icons_use_classic_wire_names_and_channels_stay_unchanged() {
let icon = "/icons/icon_3558086607".to_owned();
assert_eq!(
content(init_command(Direction::Upload, 3, 0, &icon, "", 812, false, None)),
"ftinitupload clientftfid=3 name=\\/icon_3558086607 cid=0 cpw size=812 overwrite=0 resume=0 proto=1"
);
assert_eq!(
content(init_command(Direction::Download, 4, 0, &icon, "", 0, false, None)),
"ftinitdownload clientftfid=4 name=\\/icon_3558086607 cid=0 cpw seekpos=0 proto=1"
);
assert_eq!(
content(delete_command(0, "", &[icon.clone(), "/icons/icon_7".into()])),
"ftdeletefile cid=0 cpw name=\\/icon_3558086607|name=\\/icon_7"
);
// Real channels keep their paths, including a folder that happens to be called "icons".
assert_eq!(
content(init_command(Direction::Upload, 5, 9, "/icons/icon_5", "", 1, true, None)),
"ftinitupload clientftfid=5 name=\\/icons\\/icon_5 cid=9 cpw size=1 overwrite=1 resume=0 proto=1"
);
assert_eq!(content(delete_command(9, "", &["/icons/icon_5".into()])), "ftdeletefile cid=9 cpw name=\\/icons\\/icon_5");
}
#[test]
fn resumed_transfers_continue_from_the_kept_offset_without_overwrite() {
// Official doFileDownload(resume=true): seekpos is the kept byte count.
assert_eq!(
content(init_command(Direction::Download, 6, 9, "/a.bin", "", 0, false, Some(65543))),
"ftinitdownload clientftfid=6 name=\\/a.bin cid=9 cpw seekpos=65543 proto=1"
);
// Official doFileUpload(resume=true): overwrite=!resume, the server answers with its seek position.
assert_eq!(
content(init_command(Direction::Upload, 7, 9, "/a.bin", "", 9, true, Some(0))),
"ftinitupload clientftfid=7 name=\\/a.bin cid=9 cpw size=9 overwrite=0 resume=1 proto=1"
);
}
}
+433
View File
@@ -0,0 +1,433 @@
//! Scoped global-shortcut helper. No keyboard hooks or unrestricted key-state scans.
//! Native callback service and CLI adapter (newline-delimited JSON on stdio).
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, HashSet};
use std::error::Error;
use std::io::{self, BufRead, Write};
use std::sync::{atomic::{AtomicBool, Ordering}, mpsc::{self, RecvTimeoutError}, Arc};
use std::thread::JoinHandle;
use std::time::Duration;
mod keys;
#[cfg(target_os = "linux")]
mod portal;
#[cfg(target_os = "linux")]
mod x11;
#[cfg(windows)]
mod windows;
#[cfg(test)]
mod tests;
type Result<T, E = Box<dyn Error>> = std::result::Result<T, E>;
const MAX_LINE: usize = 64 * 1024;
const MAX_BINDINGS: usize = 64;
#[derive(Debug, Deserialize)]
#[serde(tag = "cmd", rename_all = "snake_case", deny_unknown_fields)]
enum Command {
Bind { seq: u32, bindings: Vec<Binding> },
Shutdown {},
}
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Binding {
pub id: String,
pub code: String,
#[serde(default)]
pub ctrl: bool,
#[serde(default)]
pub alt: bool,
#[serde(default)]
pub shift: bool,
#[serde(default)]
pub meta: bool,
#[serde(default)]
pub description: String,
}
impl Binding {
fn modifiers(&self) -> u8 {
u8::from(self.ctrl) | (u8::from(self.alt) << 1)
| (u8::from(self.shift) << 2) | (u8::from(self.meta) << 3)
}
}
#[derive(Debug, Serialize)]
struct BindResult {
id: String,
ok: bool,
#[serde(skip_serializing_if = "Option::is_none")]
error: Option<&'static str>,
trigger: String,
detail: String,
}
impl BindResult {
fn success(binding: &Binding, trigger: String) -> Self {
Self { id: binding.id.clone(), ok: true, error: None, trigger, detail: String::new() }
}
fn failure(binding: &Binding, error: &'static str, detail: impl Into<String>) -> Self {
Self { id: binding.id.clone(), ok: false, error: Some(error), trigger: String::new(), detail: detail.into() }
}
}
enum Event {
Bound { seq: u32, results: Vec<BindResult> },
Rebound { results: Vec<BindResult> },
Key { id: String, down: bool },
}
trait Backend {
fn name(&self) -> &'static str;
fn bind(&mut self, seq: u32, bindings: Vec<Binding>, events: &mut Vec<Event>) -> Result<()>;
fn poll(&mut self, events: &mut Vec<Event>) -> Result<()>;
fn clear(&mut self) -> Result<()>;
}
#[derive(Default)]
struct State {
registered: BTreeMap<String, bool>,
}
impl State {
fn transition(&mut self, id: &str, down: bool) -> bool {
let Some(held) = self.registered.get_mut(id) else { return false };
if *held == down { return false; }
*held = down;
true
}
fn release_all(&mut self, out: &mut impl FnMut(serde_json::Value) -> io::Result<()>) -> io::Result<()> {
// Clear every flag even when the consumer fails; OS cleanup must still run.
let mut failure = None;
for (id, held) in &mut self.registered {
if std::mem::replace(held, false) {
if let Err(error) = out(serde_json::json!({ "event": "release", "id": id, "synthetic": true })) {
failure = Some(error);
}
}
}
self.registered.clear();
failure.map_or(Ok(()), Err)
}
fn event(&mut self, event: Event, out: &mut impl FnMut(serde_json::Value) -> io::Result<()>) -> io::Result<()> {
match event {
Event::Key { id, down } => {
if self.transition(&id, down) {
out(serde_json::json!({ "event": if down { "press" } else { "release" }, "id": id }))?;
}
}
Event::Bound { seq, results } => {
self.release_all(out)?;
self.registered.extend(results.iter().filter(|r| r.ok).map(|r| (r.id.clone(), false)));
out(serde_json::json!({ "event": "bound", "seq": seq, "results": results }))?;
}
Event::Rebound { results } => {
self.release_all(out)?;
self.registered.extend(results.iter().filter(|r| r.ok).map(|r| (r.id.clone(), false)));
out(serde_json::json!({ "event": "rebound", "results": results }))?;
}
}
Ok(())
}
}
fn emit(out: &mut impl Write, value: &impl Serialize) -> io::Result<()> {
serde_json::to_writer(&mut *out, value)?;
out.write_all(b"\n")?;
out.flush()
}
fn validate_bindings(bindings: &[Binding]) -> Result<()> {
if bindings.len() > MAX_BINDINGS { return Err("at most 64 hotkey bindings".into()); }
let mut ids = HashSet::with_capacity(bindings.len());
let mut chords = HashSet::with_capacity(bindings.len());
for b in bindings {
if b.id.is_empty() || b.id.len() > 128 || b.id.chars().any(char::is_control)
|| b.code.is_empty() || b.code.len() > 32 || !b.code.bytes().all(|c| c.is_ascii_alphanumeric())
|| b.description.len() > 256 || b.description.chars().any(char::is_control)
{
return Err("invalid hotkey id, code or description".into());
}
if !ids.insert(&b.id) || !chords.insert((&b.code, b.modifiers())) {
return Err("duplicate hotkey id or chord".into());
}
}
Ok(())
}
fn parse(line: &[u8]) -> Result<Command> {
if line.len() > MAX_LINE { return Err("hotkey input line exceeds 64 KiB".into()); }
let command: Command = serde_json::from_slice(line)?;
if let Command::Bind { bindings, .. } = &command { validate_bindings(bindings)?; }
Ok(command)
}
fn read_line(input: &mut impl BufRead, line: &mut Vec<u8>) -> io::Result<bool> {
line.clear();
loop {
let bytes = input.fill_buf()?;
if bytes.is_empty() { return Ok(!line.is_empty()); }
let end = bytes.iter().position(|&b| b == b'\n').map(|n| n + 1);
let count = end.unwrap_or(bytes.len());
if line.len() + count > MAX_LINE {
return Err(io::Error::new(io::ErrorKind::InvalidData, "hotkey input line exceeds 64 KiB"));
}
line.extend_from_slice(&bytes[..count]);
input.consume(count);
if end.is_some() { return Ok(true); }
}
}
fn open_backend() -> Result<Box<dyn Backend>> {
#[cfg(windows)]
{ return Ok(Box::new(windows::Windows::new())); }
#[cfg(target_os = "linux")]
{
// XWayland grabs are not global to Wayland clients. Never silently claim otherwise.
let wayland = std::env::var_os("WAYLAND_DISPLAY").is_some()
|| std::env::var("XDG_SESSION_TYPE").is_ok_and(|v| v == "wayland");
return if wayland {
Ok(Box::new(portal::Portal::new()?))
} else {
Ok(Box::new(x11::X11::new()?))
};
}
#[cfg(not(any(windows, target_os = "linux")))]
{ Err("global shortcuts are unavailable on this platform".into()) }
}
/// A startup, validation, queue or backend failure. No OS registrations survive stop.
#[derive(Clone, Debug)]
pub struct HotkeyError(String);
impl std::fmt::Display for HotkeyError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str(&self.0) }
}
impl Error for HotkeyError {}
/// Owns a backend thread and bounded ordered events. Drop requests cancellation;
/// call `stop` off the UI thread to wait for OS cleanup, then dispatch final events.
pub struct HotkeyHandle {
commands: mpsc::SyncSender<Result<Command, String>>,
cancelled: Arc<AtomicBool>,
worker: Option<JoinHandle<Result<(), HotkeyError>>>,
events: mpsc::Receiver<serde_json::Value>,
held: std::collections::BTreeSet<String>,
terminal: Option<Result<(), HotkeyError>>,
terminal_delivered: bool,
}
const EVENT_CAPACITY: usize = 256;
impl HotkeyHandle {
/// Replace the complete binding profile. Success means queued; the callback's
/// `bound` event with this sequence carries the actual registration results.
/// A full queue returns an error without replacing any pending profile.
pub fn update(&self, seq: u32, bindings: Vec<Binding>) -> Result<(), HotkeyError> {
validate_bindings(&bindings).map_err(|e| HotkeyError(e.to_string()))?;
if self.cancelled.load(Ordering::Acquire) { return Err(HotkeyError("hotkey service has stopped".into())); }
self.commands.try_send(Ok(Command::Bind { seq, bindings })).map_err(|error| {
HotkeyError(match error {
mpsc::TrySendError::Full(_) => "hotkey command queue is full",
mpsc::TrySendError::Disconnected(_) => "hotkey service has stopped",
}.into())
})
}
/// Cancel pending updates, release held keys, unregister and join the worker.
/// Call off the UI thread; callbacks are never run by the backend worker.
/// Afterwards call `dispatch` to consume final releases/errors.
pub fn stop(&mut self) -> Result<(), HotkeyError> {
self.cancel();
if let Some(worker) = self.worker.take() {
self.terminal = Some(worker.join().unwrap_or_else(|_| Err(HotkeyError("hotkey worker panicked".into()))));
}
self.terminal.clone().unwrap_or(Ok(()))
}
fn cancel(&self) {
self.cancelled.store(true, Ordering::Release);
// Wake an idle worker; cancellation remains effective with a full queue.
let _ = self.commands.try_send(Ok(Command::Shutdown {}));
}
/// Deliver a bounded batch on the calling thread, plus final releases/errors.
/// No callback runs on the OS backend thread, so a stalled consumer cannot
/// prevent unregister. Queue overflow terminates the backend; cancellation
/// discards undelivered events. Every consumer-held key is released before the
/// terminal error, even if the bounded queue had no room for its release.
/// Callback failure cancels the backend; call again to receive final releases.
pub fn dispatch(&mut self, mut callback: impl FnMut(serde_json::Value) -> io::Result<()>) -> Result<usize, HotkeyError> {
let mut delivered = 0;
let mut disconnected = false;
if self.worker.as_ref().is_some_and(|worker| worker.is_finished()) { let _ = self.stop(); }
if matches!(&self.terminal, Some(Err(_))) {
// Failed service events must not reactivate PTT when a stalled host
// resumes. The joined worker cannot refill this bounded queue.
while self.events.try_recv().is_ok() {}
}
for _ in 0..EVENT_CAPACITY {
let value = match self.events.try_recv() {
Ok(value) => value,
Err(mpsc::TryRecvError::Empty) => break,
Err(mpsc::TryRecvError::Disconnected) => { disconnected = true; break; }
};
if self.cancelled.load(Ordering::Acquire) { continue; }
let release_id = if value["event"] == "release" { value["id"].as_str().map(str::to_owned) } else { None };
if value["event"] == "press" {
if let Some(id) = value["id"].as_str() { self.held.insert(id.to_owned()); }
}
if let Err(error) = callback(value) {
self.cancel();
return Err(HotkeyError(error.to_string()));
}
if let Some(id) = release_id { self.held.remove(&id); }
delivered += 1;
}
if self.worker.as_ref().is_some_and(|worker| worker.is_finished()) { let _ = self.stop(); }
if disconnected && self.terminal.is_some() && !self.terminal_delivered {
while let Some(id) = self.held.first().cloned() {
callback(serde_json::json!({ "event": "release", "id": id, "synthetic": true })).map_err(|e| HotkeyError(e.to_string()))?;
self.held.remove(&id);
delivered += 1;
}
if let Some(Err(error)) = &self.terminal {
callback(serde_json::json!({ "event": "error", "detail": error.to_string() })).map_err(|e| HotkeyError(e.to_string()))?;
delivered += 1;
}
self.terminal_delivered = true;
}
Ok(delivered)
}
}
impl Drop for HotkeyHandle {
fn drop(&mut self) { self.cancel(); }
}
/// Explicitly open the platform backend, without registering any bindings.
/// Call off the UI thread: startup waits for backend discovery. `update` is the
/// only registration request. Call `dispatch` regularly to deliver callback
/// events with the CLI JSON shape and no serialization round trip.
pub fn start() -> Result<HotkeyHandle, HotkeyError> {
start_with_backend(open_backend)
}
fn start_with_backend(
factory: impl FnOnce() -> Result<Box<dyn Backend>> + Send + 'static,
) -> Result<HotkeyHandle, HotkeyError> {
let (commands, rx) = mpsc::sync_channel(8);
let (ready_tx, ready_rx) = mpsc::sync_channel(1);
let (events_tx, events) = mpsc::sync_channel(EVENT_CAPACITY);
let cancelled = Arc::new(AtomicBool::new(false));
let stop = Arc::clone(&cancelled);
let worker = std::thread::Builder::new().name("hotkeys".into()).spawn(move || {
let mut out = |value: serde_json::Value| {
// Native errors are delivered once after final held-key releases.
if value["event"] == "error" { return Ok(()); }
events_tx.try_send(value).map_err(|error| io::Error::other(match error {
mpsc::TrySendError::Full(_) => "hotkey event queue overflow",
mpsc::TrySendError::Disconnected(_) => "hotkey event consumer closed",
}))
};
let mut backend = match factory() {
Ok(backend) => backend,
Err(error) => {
let detail = error.to_string();
let _ = out(serde_json::json!({ "event": "ready", "backend": "unavailable", "global": false, "release": false, "detail": detail }));
let _ = ready_tx.send(Err(detail.clone()));
return Err(HotkeyError(detail));
}
};
if let Err(error) = out(serde_json::json!({ "event": "ready", "backend": backend.name(), "global": true, "release": true })) {
let _ = backend.clear();
let _ = ready_tx.send(Err(error.to_string()));
return Err(HotkeyError(error.to_string()));
}
let _ = ready_tx.send(Ok(()));
serve(&mut *backend, rx, &stop, &mut out).map_err(|e| HotkeyError(e.to_string()))
}).map_err(|e| HotkeyError(e.to_string()))?;
let mut handle = HotkeyHandle { commands, cancelled, worker: Some(worker), events,
held: Default::default(), terminal: None, terminal_delivered: false };
match ready_rx.recv() {
Ok(Ok(())) => Ok(handle),
Ok(Err(error)) => { let _ = handle.stop(); Err(HotkeyError(error)) }
Err(_) => { let _ = handle.stop(); Err(HotkeyError("hotkey worker stopped during startup".into())) }
}
}
fn serve(
backend: &mut dyn Backend,
rx: mpsc::Receiver<Result<Command, String>>,
cancelled: &AtomicBool,
out: &mut impl FnMut(serde_json::Value) -> io::Result<()>,
) -> Result<()> {
let mut state = State::default();
let mut events = Vec::with_capacity(MAX_BINDINGS);
let result = (|| -> Result<()> {
while !cancelled.load(Ordering::Acquire) {
let command = rx.recv_timeout(Duration::from_millis(8));
if cancelled.load(Ordering::Acquire) { break; }
match command {
Ok(Ok(Command::Shutdown {})) | Err(RecvTimeoutError::Disconnected) => break,
Ok(Err(error)) => return Err(error.into()),
Ok(Ok(Command::Bind { seq, bindings })) => {
state.release_all(out)?;
backend.clear()?;
backend.bind(seq, bindings, &mut events)?;
}
Err(RecvTimeoutError::Timeout) => {}
}
if cancelled.load(Ordering::Acquire) { break; }
backend.poll(&mut events)?;
for event in events.drain(..) { state.event(event, out)?; }
}
Ok(())
})();
let released = state.release_all(out);
let cleared = backend.clear();
if let Err(error) = &result {
let _ = out(serde_json::json!({ "event": "error", "detail": error.to_string() }));
}
result?;
released?;
cleared
}
/// Runs only when explicitly selected by the `hotkeys` CLI subcommand.
/// Blocking input and stdout serialization belong exclusively to this adapter.
pub fn run() -> std::result::Result<(), Box<dyn std::error::Error>> {
let stdout = io::stdout();
let mut out = stdout.lock();
let mut backend = match open_backend() {
Ok(backend) => backend,
Err(error) => {
emit(&mut out, &serde_json::json!({ "event": "ready", "backend": "unavailable", "global": false, "release": false, "detail": error.to_string() }))?;
return Ok(());
}
};
emit(&mut out, &serde_json::json!({ "event": "ready", "backend": backend.name(), "global": true, "release": true }))?;
let (tx, rx) = mpsc::sync_channel(8);
// A bounded reader keeps backend event handling responsive while stdin is idle.
// It owns no OS registrations; EOF/shutdown closes the receiver on exit.
std::thread::Builder::new().name("hotkey-stdin".into()).spawn(move || {
let stdin = io::stdin();
let mut input = stdin.lock();
let mut line = Vec::with_capacity(4096);
loop {
let item = match read_line(&mut input, &mut line) {
Ok(false) => break,
Ok(true) => parse(&line).map_err(|e| e.to_string()),
Err(error) => Err(error.to_string()),
};
let terminal = item.is_err() || matches!(item, Ok(Command::Shutdown {}));
if tx.send(item).is_err() || terminal { break; }
}
})?;
serve(&mut *backend, rx, &AtomicBool::new(false), &mut |value| emit(&mut out, &value))
}
+76
View File
@@ -0,0 +1,76 @@
//! Explicit key allowlist: unsupported DOM codes are reported, never guessed/scanned.
use super::Binding;
pub(super) struct Key {
pub windows: u32,
pub x11: u32,
pub name: String,
}
pub(super) fn lookup(code: &str) -> Option<Key> {
if let Some(letter) = code.strip_prefix("Key").filter(|s| s.len() == 1 && s.as_bytes()[0].is_ascii_uppercase()) {
let letter = letter.as_bytes()[0];
return Some(Key { windows: u32::from(letter), x11: u32::from(letter.to_ascii_lowercase()), name: char::from(letter.to_ascii_lowercase()).to_string() });
}
if let Some(digit) = code.strip_prefix("Digit").filter(|s| s.len() == 1 && s.as_bytes()[0].is_ascii_digit()) {
return Some(Key { windows: u32::from(digit.as_bytes()[0]), x11: u32::from(digit.as_bytes()[0]), name: digit.into() });
}
if let Some(digit) = code.strip_prefix("Numpad").filter(|s| s.len() == 1 && s.as_bytes()[0].is_ascii_digit()) {
let n = u32::from(digit.as_bytes()[0] - b'0');
return Some(Key { windows: 0x60 + n, x11: 0xffb0 + n, name: format!("KP_{digit}") });
}
if let Some(number) = code.strip_prefix('F').and_then(|n| n.parse::<u32>().ok()).filter(|n| (1..=24).contains(n)) {
if code != format!("F{number}") { return None; }
return Some(Key { windows: 0x70 + number - 1, x11: 0xffbe + number - 1, name: code.into() });
}
let (windows, x11, name) = match code {
"Backspace" => (0x08, 0xff08, "BackSpace"),
"Tab" => (0x09, 0xff09, "Tab"),
"Enter" => (0x0d, 0xff0d, "Return"),
"Pause" => (0x13, 0xff13, "Pause"),
"CapsLock" => (0x14, 0xffe5, "Caps_Lock"),
"Escape" => (0x1b, 0xff1b, "Escape"),
"Space" => (0x20, 0x20, "space"),
"PageUp" => (0x21, 0xff55, "Prior"),
"PageDown" => (0x22, 0xff56, "Next"),
"End" => (0x23, 0xff57, "End"),
"Home" => (0x24, 0xff50, "Home"),
"ArrowLeft" => (0x25, 0xff51, "Left"),
"ArrowUp" => (0x26, 0xff52, "Up"),
"ArrowRight" => (0x27, 0xff53, "Right"),
"ArrowDown" => (0x28, 0xff54, "Down"),
"PrintScreen" => (0x2c, 0xff61, "Print"),
"Insert" => (0x2d, 0xff63, "Insert"),
"Delete" => (0x2e, 0xffff, "Delete"),
"ContextMenu" => (0x5d, 0xff67, "Menu"),
"NumpadMultiply" => (0x6a, 0xffaa, "KP_Multiply"),
"NumpadAdd" => (0x6b, 0xffab, "KP_Add"),
"NumpadSubtract" => (0x6d, 0xffad, "KP_Subtract"),
"NumpadDecimal" => (0x6e, 0xffae, "KP_Decimal"),
"NumpadDivide" => (0x6f, 0xffaf, "KP_Divide"),
"NumLock" => (0x90, 0xff7f, "Num_Lock"),
"ScrollLock" => (0x91, 0xff14, "Scroll_Lock"),
"Semicolon" => (0xba, 0x3b, "semicolon"),
"Equal" => (0xbb, 0x3d, "equal"),
"Comma" => (0xbc, 0x2c, "comma"),
"Minus" => (0xbd, 0x2d, "minus"),
"Period" => (0xbe, 0x2e, "period"),
"Slash" => (0xbf, 0x2f, "slash"),
"Backquote" => (0xc0, 0x60, "grave"),
"BracketLeft" => (0xdb, 0x5b, "bracketleft"),
"Backslash" => (0xdc, 0x5c, "backslash"),
"BracketRight" => (0xdd, 0x5d, "bracketright"),
"Quote" => (0xde, 0x27, "apostrophe"),
_ => return None,
};
Some(Key { windows, x11, name: name.into() })
}
pub(super) fn trigger(binding: &Binding, key: &Key) -> String {
let mut trigger = String::with_capacity(40);
for (enabled, modifier) in [(binding.ctrl, "CTRL+"), (binding.alt, "ALT+"), (binding.shift, "SHIFT+"), (binding.meta, "LOGO+")] {
if enabled { trigger.push_str(modifier); }
}
trigger.push_str(&key.name);
trigger
}
+260
View File
@@ -0,0 +1,260 @@
//! GlobalShortcuts portal, not an XWayland or keyboard-hook fallback.
//! Requests remain asynchronous so rebind/shutdown can close a permission dialog.
use super::{keys, Backend, BindResult, Binding, Event, Result, MAX_BINDINGS};
use dbus::arg::{PropMap, RefArg, Variant};
use dbus::blocking::{stdintf::org_freedesktop_dbus::Properties, Connection};
use dbus::channel::MatchingReceiver;
use dbus::message::MatchRule;
use dbus::{Message, Path};
use std::collections::HashMap;
use std::sync::{atomic::{AtomicBool, Ordering}, mpsc::{self, Receiver}, Arc};
use std::time::{Duration, Instant};
const DEST: &str = "org.freedesktop.portal.Desktop";
const ROOT: &str = "/org/freedesktop/portal/desktop";
const IFACE: &str = "org.freedesktop.portal.GlobalShortcuts";
const REQUEST: &str = "org.freedesktop.portal.Request";
const SESSION: &str = "org.freedesktop.portal.Session";
const CALL_TIMEOUT: Duration = Duration::from_secs(2);
enum Stage { Creating, Binding }
struct Pending { path: Path<'static>, stage: Stage, started: Instant }
pub(super) struct Portal {
connection: Connection,
incoming: Receiver<Message>,
overflow: Arc<AtomicBool>,
owner: String,
generation: u64,
session: Option<Path<'static>>,
pending: Option<Pending>,
bindings: Vec<Binding>,
seq: u32,
bound: bool,
}
fn option(map: &mut PropMap, key: &str, value: String) {
map.insert(key.into(), Variant(Box::new(value)));
}
impl Portal {
pub(super) fn new() -> Result<Self> {
let connection = Connection::new_session()?;
let proxy = connection.with_proxy(DEST, ROOT, CALL_TIMEOUT);
let version: u32 = proxy.get(IFACE, "version")?;
if version < 1 { return Err("GlobalShortcuts portal version is unavailable".into()); }
let (owner,): (String,) = connection.with_proxy("org.freedesktop.DBus", "/org/freedesktop/DBus", CALL_TIMEOUT)
.method_call("org.freedesktop.DBus", "GetNameOwner", (DEST,))?;
let (tx, incoming) = mpsc::sync_channel(256);
let overflow = Arc::new(AtomicBool::new(false));
for (interface, member) in [(REQUEST, "Response"), (IFACE, "Activated"), (IFACE, "Deactivated"),
(IFACE, "ShortcutsChanged"), (SESSION, "Closed"), ("org.freedesktop.DBus", "NameOwnerChanged")] {
let sender = if interface == "org.freedesktop.DBus" { "org.freedesktop.DBus" } else { owner.as_str() };
let rule = MatchRule::new_signal(interface, member).with_strict_sender(sender.to_owned());
connection.add_match_no_cb(&rule.match_str())?;
let tx = tx.clone();
let overflow = Arc::clone(&overflow);
connection.start_receive(rule, Box::new(move |message, _| {
if tx.try_send(message).is_err() { overflow.store(true, Ordering::Relaxed); }
true
}));
}
Ok(Self { connection, incoming, overflow, owner, generation: 0, session: None, pending: None,
bindings: Vec::new(), seq: 0, bound: false })
}
fn token(&self, suffix: &str) -> String { format!("tp_{}_{}_{}", std::process::id(), self.generation, suffix) }
fn create(&mut self) -> Result<()> {
let mut options = PropMap::new();
option(&mut options, "handle_token", self.token("create"));
option(&mut options, "session_handle_token", self.token("session"));
// Predict the session path so even a cancelled CreateSession is closed on shutdown.
let sender = self.connection.unique_name().trim_start_matches(':').replace('.', "_");
self.session = Some(Path::new(format!("/org/freedesktop/portal/desktop/session/{sender}/{}", self.token("session")))?);
let (path,): (Path<'static>,) = self.connection.with_proxy(DEST, ROOT, CALL_TIMEOUT)
.method_call(IFACE, "CreateSession", (options,))?;
self.pending = Some(Pending { path, stage: Stage::Creating, started: Instant::now() });
Ok(())
}
fn request_bind(&mut self) -> Result<()> {
let mut shortcuts = Vec::with_capacity(self.bindings.len());
for binding in &self.bindings {
if let Some(key) = keys::lookup(&binding.code) {
let mut properties = PropMap::new();
option(&mut properties, "description", if binding.description.is_empty() { binding.id.clone() } else { binding.description.clone() });
option(&mut properties, "preferred_trigger", keys::trigger(binding, &key));
shortcuts.push((binding.id.clone(), properties));
}
}
let mut options = PropMap::new();
option(&mut options, "handle_token", self.token("bind"));
let session = self.session.as_ref().ok_or("portal session missing")?;
let (path,): (Path<'static>,) = self.connection.with_proxy(DEST, ROOT, CALL_TIMEOUT)
.method_call(IFACE, "BindShortcuts", (session, shortcuts, "", options))?;
self.pending = Some(Pending { path, stage: Stage::Binding, started: Instant::now() });
Ok(())
}
fn results(&self, shortcuts: &HashMap<String, String>, denied: bool) -> Vec<BindResult> {
self.bindings.iter().map(|binding| {
if keys::lookup(&binding.code).is_none() {
BindResult::failure(binding, "unsupported_key", "DOM code has no portal trigger mapping")
} else if let Some(trigger) = shortcuts.get(&binding.id) {
BindResult::success(binding, trigger.clone())
} else {
BindResult::failure(binding, if denied { "portal_denied" } else { "failed" }, "Shortcut was not granted by the desktop portal")
}
}).collect()
}
fn close(&self, path: &Path<'static>, interface: &str) -> Result<()> {
let _: () = self.connection.with_proxy(DEST, path.clone(), CALL_TIMEOUT).method_call(interface, "Close", ())?;
Ok(())
}
}
// Dynamic a(sa{sv}) decoding: dbus represents nested variants with RefArg, not
// necessarily the concrete Vec/HashMap types used to encode outbound calls.
fn shortcuts(value: &dyn RefArg) -> Result<HashMap<String, String>> {
let mut result = HashMap::new();
let entries = value.as_iter().ok_or("portal shortcuts are not an array")?;
for entry in entries {
if result.len() >= MAX_BINDINGS { return Err("portal returned too many shortcuts".into()); }
let mut fields = entry.as_iter().ok_or("invalid portal shortcut tuple")?;
let id = fields.next().and_then(RefArg::as_str).ok_or("invalid portal shortcut id")?;
if id.len() > 128 { return Err("portal shortcut id exceeds limit".into()); }
let properties = fields.next().ok_or("missing portal shortcut properties")?;
let mut properties = properties.as_iter().ok_or("invalid portal shortcut properties")?;
let mut trigger = String::new();
while let Some(key) = properties.next() {
let value = properties.next().ok_or("invalid portal shortcut property")?;
if key.as_str() == Some("trigger_description") {
let text = value.as_str().or_else(|| value.as_iter()?.next()?.as_str()).unwrap_or("");
trigger = text.chars().take(128).collect();
}
}
result.insert(id.to_owned(), trigger);
}
Ok(result)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn decodes_shortcut_trigger_variants_without_a_bus() {
let mut properties = PropMap::new();
option(&mut properties, "description", "Whisper".into());
option(&mut properties, "trigger_description", "Ctrl+W".into());
let entries = vec![("whisper".to_owned(), properties)];
let decoded = shortcuts(&entries).unwrap();
assert_eq!(decoded.get("whisper").map(String::as_str), Some("Ctrl+W"));
}
#[test]
fn rejects_non_array_and_oversized_shortcut_lists() {
assert!(shortcuts(&17u32).is_err());
let entries: Vec<_> = (0..=MAX_BINDINGS).map(|index| (index.to_string(), PropMap::new())).collect();
assert!(shortcuts(&entries).is_err());
}
}
impl Backend for Portal {
fn name(&self) -> &'static str { "xdg_portal_global_shortcuts" }
fn bind(&mut self, seq: u32, bindings: Vec<Binding>, events: &mut Vec<Event>) -> Result<()> {
self.seq = seq;
self.bindings = bindings;
self.generation = self.generation.checked_add(1).ok_or("portal request generation exhausted")?;
if self.bindings.iter().all(|b| keys::lookup(&b.code).is_none()) {
events.push(Event::Bound { seq, results: self.results(&HashMap::new(), false) });
return Ok(());
}
self.create()
}
fn poll(&mut self, events: &mut Vec<Event>) -> Result<()> {
for _ in 0..256 {
if !self.connection.process(Duration::ZERO)? { break; }
}
if self.overflow.swap(false, Ordering::Relaxed) { return Err("portal signal queue overflow".into()); }
// A pending permission request must not keep a session alive indefinitely.
if self.pending.as_ref().is_some_and(|p| p.started.elapsed() > Duration::from_secs(120)) {
return Err("portal shortcut request timed out".into());
}
while let Ok(message) = self.incoming.try_recv() {
let member = message.member().map(|m| m.to_string()).unwrap_or_default();
if member == "NameOwnerChanged" {
let (name, old, new): (String, String, String) = message.read3()?;
if name == DEST && old == self.owner && new != old { return Err("GlobalShortcuts portal service disappeared".into()); }
continue;
}
if member == "Response" {
if !self.pending.as_ref().is_some_and(|pending| message.path().as_ref() == Some(&pending.path)) { continue; }
let pending = self.pending.take().ok_or("portal request missing")?;
let (response, properties): (u32, PropMap) = message.read2()?;
if response != 0 {
events.push(Event::Bound { seq: self.seq, results: self.results(&HashMap::new(), response == 1) });
self.clear()?;
continue;
}
match pending.stage {
Stage::Creating => {
let path = properties.get("session_handle").and_then(|v| v.0.as_str()).ok_or("portal returned no session handle")?;
// Only accept the session path for this request/connection.
if self.session.as_ref().map(|p| p.to_string()).as_deref() != Some(path) {
return Err("portal returned an unexpected session handle".into());
}
self.request_bind()?;
}
Stage::Binding => {
let granted = shortcuts(properties.get("shortcuts").ok_or("portal returned no shortcuts")?.0.as_ref())?;
events.push(Event::Bound { seq: self.seq, results: self.results(&granted, true) });
self.bound = true;
}
}
} else if member == "Closed" {
if message.path().as_ref() == self.session.as_ref() { return Err("portal shortcut session closed".into()); }
} else if member == "Activated" || member == "Deactivated" {
let (session, id, _, _): (Path<'static>, String, u64, PropMap) = message.read4()?;
if self.bound && Some(&session) == self.session.as_ref() && self.bindings.iter().any(|b| b.id == id) {
events.push(Event::Key { id, down: member == "Activated" });
}
} else if member == "ShortcutsChanged" {
let (session, changed): (Path<'static>, Vec<(String, PropMap)>) = message.read2()?;
if self.bound && Some(&session) == self.session.as_ref() {
if changed.len() > MAX_BINDINGS { return Err("portal returned too many shortcuts".into()); }
let granted = changed.into_iter().map(|(id, properties)| {
let trigger = properties.get("trigger_description").and_then(|v| v.0.as_str()).unwrap_or("").chars().take(128).collect();
(id, trigger)
}).collect();
events.push(Event::Rebound { results: self.results(&granted, true) });
}
}
}
Ok(())
}
fn clear(&mut self) -> Result<()> {
self.bound = false;
self.bindings.clear();
let mut failure = None;
if let Some(pending) = self.pending.take() {
if let Err(error) = self.close(&pending.path, REQUEST) { failure = Some(error); }
}
if let Some(session) = self.session.take() {
// Session may already have been closed by the desktop/user. The
// connection is dropped on any failure, which also revokes its session.
if let Err(error) = self.close(&session, SESSION) { failure = Some(error); }
}
while self.incoming.try_recv().is_ok() {}
match failure { Some(error) => Err(error), None => Ok(()) }
}
}
impl Drop for Portal {
fn drop(&mut self) { let _ = self.clear(); }
}
+294
View File
@@ -0,0 +1,294 @@
//! Pure tests: no platform backend construction, display connection, OS hooks or key polling.
use super::*;
use std::io::{BufReader, Cursor};
fn binding(id: &str, code: &str) -> Binding {
Binding { id: id.into(), code: code.into(), ctrl: false, alt: false, shift: false, meta: false, description: String::new() }
}
#[test]
fn accepts_helper_wire_commands() {
let command = parse(br#"{"cmd":"bind","seq":4294967295,"bindings":[{"id":"a","code":"KeyW","ctrl":true,"alt":false,"shift":false,"meta":false,"description":"whisper_list"}]}"#).unwrap();
let Command::Bind { seq, bindings } = command else { panic!("expected bind") };
assert_eq!(seq, u32::MAX);
assert_eq!(bindings.len(), 1);
assert_eq!(bindings[0].modifiers(), 1);
assert!(matches!(parse(b"{\"cmd\":\"shutdown\"}\r\n").unwrap(), Command::Shutdown {}));
}
#[test]
fn rejects_unknown_fields_wrong_types_and_duplicate_chords() {
for raw in [
r#"{"cmd":"shutdown","bindings":[]}"#,
r#"{"cmd":"bind","seq":-1,"bindings":[]}"#,
r#"{"cmd":"bind","seq":1,"bindings":[{"id":"a","code":"KeyA","ctrl":1}]}"#,
r#"{"cmd":"bind","seq":1,"bindings":[{"id":"a","code":"KeyA","global":true}]}"#,
r#"{"cmd":"bind","seq":1,"bindings":[{"id":"a","code":"KeyA"},{"id":"a","code":"KeyB"}]}"#,
r#"{"cmd":"bind","seq":1,"bindings":[{"id":"a","code":"KeyA"},{"id":"b","code":"KeyA"}]}"#,
r#"{"cmd":"bind","seq":1,"bindings":[{"id":"a","code":"Key-A"}]}"#,
r#"{"cmd":"bind","seq":1,"bindings":[{"id":"a\n","code":"KeyA"}]}"#,
] {
assert!(parse(raw.as_bytes()).is_err(), "accepted {raw}");
}
}
#[test]
fn limits_binding_count_and_text_before_backend_access() {
let bindings: Vec<_> = (0..65).map(|n| serde_json::json!({ "id": n.to_string(), "code": format!("Key{n}") })).collect();
let raw = serde_json::to_vec(&serde_json::json!({ "cmd": "bind", "seq": 1, "bindings": bindings })).unwrap();
assert!(parse(&raw).is_err());
for (field, text) in [("id", "a".repeat(129)), ("code", "A".repeat(33)), ("description", "x".repeat(257))] {
let mut b = serde_json::json!({ "id": "a", "code": "KeyA" });
b[field] = text.into();
let raw = serde_json::to_vec(&serde_json::json!({ "cmd": "bind", "seq": 1, "bindings": [b] })).unwrap();
assert!(parse(&raw).is_err());
}
assert!(parse(&vec![b' '; MAX_LINE + 1]).is_err());
}
#[test]
fn bounded_reader_handles_chunk_boundaries_crlf_and_final_line() {
let mut input = BufReader::with_capacity(3, Cursor::new(b"abc\r\ndef\nxyz"));
let mut line = Vec::new();
for expected in [b"abc\r\n".as_slice(), b"def\n", b"xyz"] {
assert!(read_line(&mut input, &mut line).unwrap());
assert_eq!(line, expected);
}
assert!(!read_line(&mut input, &mut line).unwrap());
}
#[test]
fn oversized_unterminated_input_never_grows_past_limit() {
let mut input = BufReader::with_capacity(1024, Cursor::new(vec![b'x'; MAX_LINE + 100]));
let mut line = Vec::new();
assert_eq!(read_line(&mut input, &mut line).unwrap_err().kind(), io::ErrorKind::InvalidData);
assert!(line.len() <= MAX_LINE);
}
#[test]
fn ignores_unknown_ids_and_repeat_transitions() {
let mut state = State::default();
state.registered.insert("a".into(), false);
assert!(!state.transition("unregistered", true));
assert!(!state.transition("a", false));
assert!(state.transition("a", true));
assert!(!state.transition("a", true));
assert!(state.transition("a", false));
assert!(!state.transition("a", false));
}
#[test]
fn replacement_releases_held_ids_before_new_bound_event() {
let mut state = State::default();
state.registered.insert("old".into(), true);
let mut out = Vec::new();
state.event(Event::Bound { seq: 2, results: vec![BindResult::success(&binding("new", "KeyN"), "n".into()),
BindResult::failure(&binding("bad", "Unknown"), "unsupported_key", "unsupported")] }, &mut |value| emit(&mut out, &value)).unwrap();
let messages: Vec<serde_json::Value> = out.split(|b| *b == b'\n').filter(|b| !b.is_empty())
.map(|b| serde_json::from_slice(b).unwrap()).collect();
assert_eq!(messages[0]["event"], "release");
assert_eq!(messages[0]["id"], "old");
// Replacement is cancellation, not a physical key-up that can trigger a command.
assert_eq!(messages[0]["synthetic"], true);
assert_eq!(messages[1]["event"], "bound");
assert_eq!(messages[1]["seq"], 2);
assert!(state.transition("new", true));
assert!(!state.transition("old", true));
assert!(!state.transition("bad", true));
}
#[test]
fn shutdown_and_failure_release_all_once() {
let mut state = State::default();
state.registered.extend([("a".into(), true), ("b".into(), true), ("c".into(), false)]);
let mut out = Vec::new();
state.release_all(&mut |value| emit(&mut out, &value)).unwrap();
let written = out.len();
state.release_all(&mut |value| emit(&mut out, &value)).unwrap();
assert_eq!(out.len(), written);
assert_eq!(out.iter().filter(|&&b| b == b'\n').count(), 2);
assert!(state.registered.is_empty());
}
#[test]
fn broken_stdout_still_clears_all_held_state() {
struct Broken;
impl Write for Broken {
fn write(&mut self, _: &[u8]) -> io::Result<usize> { Err(io::ErrorKind::BrokenPipe.into()) }
fn flush(&mut self) -> io::Result<()> { Ok(()) }
}
let mut state = State::default();
state.registered.extend([("a".into(), true), ("b".into(), true)]);
assert!(state.release_all(&mut |value| emit(&mut Broken, &value)).is_err());
assert!(state.registered.is_empty());
}
#[test]
fn key_allowlist_and_portal_trigger_are_explicit() {
for code in ["KeyA", "Digit0", "F1", "F24", "Space", "Numpad9", "ArrowLeft"] {
assert!(keys::lookup(code).is_some(), "{code}");
}
for code in ["Keya", "KeyAA", "F0", "F25", "F01", "Mouse1", "ControlLeft", "NumpadEnter", "Unknown"] {
assert!(keys::lookup(code).is_none(), "{code}");
}
let mut b = binding("a", "KeyA");
b.ctrl = true;
b.shift = true;
b.meta = true;
assert_eq!(keys::trigger(&b, &keys::lookup(&b.code).unwrap()), "CTRL+SHIFT+LOGO+a");
}
// The same service factory/loop used by native callers, with no platform access.
struct FakeBackend {
binds: Arc<std::sync::atomic::AtomicUsize>,
clears: Arc<std::sync::atomic::AtomicUsize>,
dropped: Arc<AtomicBool>,
bursts: mpsc::Receiver<usize>,
active: Option<String>,
}
impl Backend for FakeBackend {
fn name(&self) -> &'static str { "test" }
fn bind(&mut self, seq: u32, bindings: Vec<Binding>, events: &mut Vec<Event>) -> Result<()> {
self.binds.fetch_add(1, Ordering::SeqCst);
self.active = bindings.first().map(|b| b.id.clone());
let results = bindings.iter().map(|b| BindResult::success(b, b.code.clone())).collect();
events.push(Event::Bound { seq, results });
if let Some(id) = &self.active { events.push(Event::Key { id: id.clone(), down: true }); }
Ok(())
}
fn poll(&mut self, events: &mut Vec<Event>) -> Result<()> {
if let (Some(id), Ok(count)) = (&self.active, self.bursts.try_recv()) {
for n in 0..count { events.push(Event::Key { id: id.clone(), down: n % 2 != 0 }); }
}
Ok(())
}
fn clear(&mut self) -> Result<()> {
self.clears.fetch_add(1, Ordering::SeqCst);
self.active = None;
Ok(())
}
}
impl Drop for FakeBackend {
fn drop(&mut self) { self.dropped.store(true, Ordering::Release); }
}
struct Fixture {
handle: HotkeyHandle,
binds: Arc<std::sync::atomic::AtomicUsize>,
clears: Arc<std::sync::atomic::AtomicUsize>,
dropped: Arc<AtomicBool>,
bursts: mpsc::SyncSender<usize>,
}
fn fake_service() -> Fixture {
let binds = Arc::new(std::sync::atomic::AtomicUsize::new(0));
let clears = Arc::new(std::sync::atomic::AtomicUsize::new(0));
let dropped = Arc::new(AtomicBool::new(false));
let (bursts, rx) = mpsc::sync_channel(1);
let backend = FakeBackend { binds: binds.clone(), clears: clears.clone(), dropped: dropped.clone(), bursts: rx, active: None };
let handle = start_with_backend(move || Ok(Box::new(backend))).unwrap();
Fixture { handle, binds, clears, dropped, bursts }
}
fn eventually(mut condition: impl FnMut() -> bool) {
let deadline = std::time::Instant::now() + Duration::from_secs(3);
while !condition() {
assert!(std::time::Instant::now() < deadline, "hotkey lifecycle did not complete");
std::thread::sleep(Duration::from_millis(1));
}
}
fn dispatch_until(handle: &mut HotkeyHandle, messages: &mut Vec<serde_json::Value>, event: &str, id: &str) {
let consumer_thread = std::thread::current().id();
eventually(|| {
handle.dispatch(|value| {
assert_eq!(std::thread::current().id(), consumer_thread);
messages.push(value);
Ok(())
}).unwrap();
messages.iter().any(|v| v["event"] == event && v["id"] == id)
});
}
#[test]
fn native_profiles_release_before_replace_and_join_before_restart() {
for _ in 0..100 {
let mut fixture = fake_service();
assert_eq!(fixture.binds.load(Ordering::SeqCst), 0, "startup must not register");
let mut messages = Vec::new();
fixture.handle.update(1, vec![binding("old", "KeyA")]).unwrap();
dispatch_until(&mut fixture.handle, &mut messages, "press", "old");
assert!(fixture.handle.update(2, vec![binding("x", "KeyA"), binding("x", "KeyB")]).is_err());
assert_eq!(fixture.binds.load(Ordering::SeqCst), 1);
fixture.handle.update(3, vec![binding("new", "KeyB")]).unwrap();
dispatch_until(&mut fixture.handle, &mut messages, "press", "new");
let released = messages.iter().position(|v| v["event"] == "release" && v["id"] == "old").unwrap();
let rebound = messages.iter().position(|v| v["event"] == "bound" && v["seq"] == 3).unwrap();
assert!(released < rebound);
fixture.handle.stop().unwrap();
assert!(fixture.dropped.load(Ordering::Acquire), "stop must join backend destruction");
assert_eq!(fixture.clears.load(Ordering::SeqCst), 3);
dispatch_until(&mut fixture.handle, &mut messages, "release", "new");
assert!(fixture.handle.update(4, vec![]).is_err());
let count = messages.len();
fixture.handle.stop().unwrap();
fixture.handle.dispatch(|v| { messages.push(v); Ok(()) }).unwrap();
assert_eq!(messages.len(), count, "stop/release must be idempotent");
}
}
#[test]
fn stalled_event_consumer_unregisters_and_receives_final_release_on_overflow() {
let mut fixture = fake_service();
let mut messages = Vec::new();
fixture.handle.update(1, vec![binding("ptt", "KeyA")]).unwrap();
dispatch_until(&mut fixture.handle, &mut messages, "press", "ptt");
fixture.bursts.send(EVENT_CAPACITY + 1).unwrap();
// Do not dispatch: a backend must terminate independently of the consumer.
eventually(|| fixture.dropped.load(Ordering::Acquire));
assert!(fixture.handle.stop().unwrap_err().to_string().contains("overflow"));
eventually(|| {
fixture.handle.dispatch(|v| { messages.push(v); Ok(()) }).unwrap();
messages.iter().any(|v| v["event"] == "error")
});
let mut held = false;
for message in &messages {
match message["event"].as_str().unwrap() {
"press" => { assert!(!held); held = true; }
"release" => { assert!(held); held = false; }
"error" => assert!(!held, "overflow must release PTT before reporting failure"),
_ => {}
}
}
assert!(!held);
assert_eq!(fixture.clears.load(Ordering::SeqCst), 2);
}
#[test]
fn callback_failure_cancels_without_stranding_consumer_held_key() {
let mut fixture = fake_service();
fixture.handle.update(1, vec![binding("ptt", "KeyA")]).unwrap();
eventually(|| fixture.handle.dispatch(|value| {
if value["event"] == "press" { Err(io::Error::other("consumer failed")) } else { Ok(()) }
}).is_err());
fixture.handle.stop().unwrap();
let mut messages = Vec::new();
dispatch_until(&mut fixture.handle, &mut messages, "release", "ptt");
assert_eq!(messages.iter().filter(|v| v["event"] == "release").count(), 1);
assert!(fixture.dropped.load(Ordering::Acquire));
}
#[test]
fn dropping_service_requests_cleanup_without_dispatch() {
let mut fixture = fake_service();
fixture.handle.update(1, vec![binding("ptt", "KeyA")]).unwrap();
dispatch_until(&mut fixture.handle, &mut Vec::new(), "press", "ptt");
drop(fixture.handle);
eventually(|| fixture.dropped.load(Ordering::Acquire));
assert_eq!(fixture.clears.load(Ordering::SeqCst), 2);
}
+91
View File
@@ -0,0 +1,91 @@
use super::{keys, Backend, BindResult, Binding, Event, Result};
use windows_sys::Win32::UI::Input::KeyboardAndMouse::{GetAsyncKeyState, RegisterHotKey, UnregisterHotKey, MOD_ALT, MOD_CONTROL, MOD_NOREPEAT, MOD_SHIFT, MOD_WIN};
use windows_sys::Win32::UI::WindowsAndMessaging::{PeekMessageW, MSG, PM_REMOVE, WM_HOTKEY};
struct Registered {
token: i32,
id: String,
vk: u32,
held: bool,
}
pub(super) struct Windows {
bindings: Vec<Registered>,
next_token: i32,
}
impl Windows {
pub(super) fn new() -> Self {
Self { bindings: Vec::new(), next_token: 1 }
}
}
impl Backend for Windows {
fn name(&self) -> &'static str { "windows_registerhotkey" }
fn bind(&mut self, seq: u32, bindings: Vec<Binding>, events: &mut Vec<Event>) -> Result<()> {
let mut results = Vec::with_capacity(bindings.len());
for binding in bindings {
let Some(key) = keys::lookup(&binding.code) else {
results.push(BindResult::failure(&binding, "unsupported_key", "DOM code is not supported by RegisterHotKey"));
continue;
};
let mut modifiers = MOD_NOREPEAT;
if binding.ctrl { modifiers |= MOD_CONTROL; }
if binding.alt { modifiers |= MOD_ALT; }
if binding.shift { modifiers |= MOD_SHIFT; }
if binding.meta { modifiers |= MOD_WIN; }
let token = self.next_token;
self.next_token = if token == 0xbfff { 1 } else { token + 1 };
// Registrations and message draining remain on this same helper thread.
if unsafe { RegisterHotKey(std::ptr::null_mut(), token, modifiers, key.windows) } == 0 {
let error = std::io::Error::last_os_error();
let code = if error.raw_os_error() == Some(1409) { "in_use" } else { "failed" };
results.push(BindResult::failure(&binding, code, error.to_string()));
} else {
results.push(BindResult::success(&binding, keys::trigger(&binding, &key)));
self.bindings.push(Registered { token, id: binding.id, vk: key.windows, held: false });
}
}
events.push(Event::Bound { seq, results });
Ok(())
}
fn poll(&mut self, events: &mut Vec<Event>) -> Result<()> {
let mut message: MSG = unsafe { std::mem::zeroed() };
for _ in 0..256 {
if unsafe { PeekMessageW(&mut message, std::ptr::null_mut(), WM_HOTKEY, WM_HOTKEY, PM_REMOVE) } == 0 { break; }
if let Some(binding) = self.bindings.iter_mut().find(|b| b.token as usize == message.wParam) {
if !binding.held {
binding.held = true;
events.push(Event::Key { id: binding.id.clone(), down: true });
}
}
}
// Only query successfully registered keys after their WM_HOTKEY activation.
// No arbitrary key enumeration, modifier polling, low-level hook or raw-input listener.
for binding in &mut self.bindings {
if binding.held && unsafe { GetAsyncKeyState(binding.vk as i32) } >= 0 {
binding.held = false;
events.push(Event::Key { id: binding.id.clone(), down: false });
}
}
Ok(())
}
fn clear(&mut self) -> Result<()> {
let mut error = None;
for binding in self.bindings.drain(..) {
if unsafe { UnregisterHotKey(std::ptr::null_mut(), binding.token) } == 0 {
error = Some(std::io::Error::last_os_error());
}
}
let mut message: MSG = unsafe { std::mem::zeroed() };
while unsafe { PeekMessageW(&mut message, std::ptr::null_mut(), WM_HOTKEY, WM_HOTKEY, PM_REMOVE) } != 0 {}
match error { Some(error) => Err(error.into()), None => Ok(()) }
}
}
impl Drop for Windows {
fn drop(&mut self) { let _ = self.clear(); }
}
+167
View File
@@ -0,0 +1,167 @@
use super::{keys, Backend, BindResult, Binding, Event, Result};
use std::time::{Duration, Instant};
use x11rb::connection::Connection;
use x11rb::protocol::{xproto::{ConnectionExt, GrabMode, ModMask}, Event as XEvent};
use x11rb::rust_connection::RustConnection;
struct Registered {
id: String,
code: u8,
modifiers: u16,
held: bool,
}
pub(super) struct X11 {
connection: RustConnection,
roots: Vec<u32>,
registered: Vec<Registered>,
grabs: Vec<(u32, u8, u16)>,
ignored: u16,
pending_release: Option<(u8, u32, Instant)>,
}
impl X11 {
pub(super) fn new() -> Result<Self> {
let (connection, _) = x11rb::connect(None)?;
let roots = connection.setup().roots.iter().map(|screen| screen.root).collect();
Ok(Self { connection, roots, registered: Vec::new(), grabs: Vec::new(), ignored: 0, pending_release: None })
}
fn release(&mut self, code: u8, events: &mut Vec<Event>) {
for binding in self.registered.iter_mut().filter(|b| b.code == code && b.held) {
binding.held = false;
events.push(Event::Key { id: binding.id.clone(), down: false });
}
}
}
impl Backend for X11 {
fn name(&self) -> &'static str { "x11_xgrabkey" }
fn bind(&mut self, seq: u32, bindings: Vec<Binding>, events: &mut Vec<Event>) -> Result<()> {
let setup = self.connection.setup();
let first = setup.min_keycode;
let count = setup.max_keycode - first + 1;
let mapping = self.connection.get_keyboard_mapping(first, count)?.reply()?;
let width = usize::from(mapping.keysyms_per_keycode);
if width == 0 { return Err("X11 returned an empty keyboard mapping".into()); }
let modifiers = self.connection.get_modifier_mapping()?.reply()?;
let per_modifier = modifiers.keycodes.len() / 8;
self.ignored = 2; // Caps Lock is always the core Lock modifier.
for (index, codes) in modifiers.keycodes.chunks(per_modifier.max(1)).enumerate() {
if codes.iter().any(|code| {
if *code < first { return false; }
let at = usize::from(*code - first) * width;
mapping.keysyms.get(at..at + width).is_some_and(|syms| syms.contains(&0xff7f) || syms.contains(&0xff14))
}) {
self.ignored |= 1 << index;
}
}
// Every lock-state combination, without AnyModifier (which would capture unrelated chords).
let locks: Vec<u16> = (0u16..256).filter(|m| m & !self.ignored == 0).collect();
let mut results = Vec::with_capacity(bindings.len());
for binding in bindings {
let Some(key) = keys::lookup(&binding.code) else {
results.push(BindResult::failure(&binding, "unsupported_key", "DOM code has no X11 keysym mapping"));
continue;
};
let codes: Vec<u8> = mapping.keysyms.chunks(width).enumerate()
.filter(|(_, syms)| syms[0] == key.x11 || (binding.code.starts_with("Numpad") && syms.contains(&key.x11)))
.map(|(index, _)| first + index as u8).collect();
if codes.is_empty() {
results.push(BindResult::failure(&binding, "unsupported_key", "Key is absent from the current X11 base layout"));
continue;
}
let mask = u16::from(binding.shift) | (u16::from(binding.ctrl) << 2)
| (u16::from(binding.alt) << 3) | (u16::from(binding.meta) << 6);
let start = self.grabs.len();
let mut failed = None;
'grabbing: for &root in &self.roots {
for &code in &codes {
for &lock in &locks {
let modifiers = mask | lock;
let reply = self.connection.grab_key(false, root, ModMask::from(modifiers), code, GrabMode::ASYNC, GrabMode::ASYNC)?.check();
if let Err(error) = reply {
failed = Some(error.to_string());
break 'grabbing;
}
self.grabs.push((root, code, modifiers));
}
}
}
if let Some(detail) = failed {
for (root, code, mask) in self.grabs.drain(start..) {
self.connection.ungrab_key(code, root, ModMask::from(mask))?.check()?;
}
results.push(BindResult::failure(&binding, "in_use", detail));
} else {
results.push(BindResult::success(&binding, keys::trigger(&binding, &key)));
for code in codes {
self.registered.push(Registered { id: binding.id.clone(), code, modifiers: mask, held: false });
}
}
}
self.connection.flush()?;
events.push(Event::Bound { seq, results });
Ok(())
}
fn poll(&mut self, events: &mut Vec<Event>) -> Result<()> {
for _ in 0..256 {
let Some(event) = self.connection.poll_for_event()? else { break };
if let Some((code, time, _)) = self.pending_release.take() {
// Core X11 repeat is a release/press pair with identical time and keycode.
if matches!(&event, XEvent::KeyPress(press) if press.detail == code && press.time == time) {
continue;
}
self.release(code, events);
}
match event {
XEvent::KeyPress(press) => {
let mask = u16::from(press.state) & 0xff & !self.ignored;
for binding in &mut self.registered {
if binding.code == press.detail && binding.modifiers == mask && !binding.held {
binding.held = true;
events.push(Event::Key { id: binding.id.clone(), down: true });
}
}
}
XEvent::KeyRelease(release) => {
if self.registered.iter().any(|b| b.code == release.detail && b.held) {
self.pending_release = Some((release.detail, release.time, Instant::now()));
}
}
XEvent::MappingNotify(_) => return Err("X11 keyboard mapping changed; rebind required".into()),
XEvent::Error(error) => return Err(format!("X11 shortcut error: {error:?}").into()),
_ => {} // Never report keys outside the registered set.
}
}
if self.pending_release.as_ref().is_some_and(|(_, _, at)| at.elapsed() >= Duration::from_millis(16)) {
let (code, _, _) = self.pending_release.take().expect("pending release checked");
self.release(code, events);
}
Ok(())
}
fn clear(&mut self) -> Result<()> {
self.registered.clear();
self.pending_release = None;
let mut failure = None;
for (root, code, mask) in self.grabs.drain(..) {
match self.connection.ungrab_key(code, root, ModMask::from(mask)) {
Ok(cookie) => { if let Err(error) = cookie.check() { failure = Some(error.to_string()); } }
Err(error) => failure = Some(error.to_string()),
}
}
// A passive grab becomes an active keyboard grab while its trigger is held.
// Explicitly end that active grab on replacement/shutdown as well.
self.connection.ungrab_keyboard(x11rb::CURRENT_TIME)?.check()?;
self.connection.flush()?;
while self.connection.poll_for_event()?.is_some() {}
match failure { Some(error) => Err(error.into()), None => Ok(()) }
}
}
impl Drop for X11 {
fn drop(&mut self) { let _ = self.clear(); }
}
+96
View File
@@ -0,0 +1,96 @@
//! Disposable identity CLI. Keys never enter stdout or process arguments.
use std::collections::HashMap;
use std::fs::File;
use std::io::{BufRead, Read, Write};
use std::path::{Path, PathBuf};
use std::process::ExitCode;
use std::sync::{Arc, atomic::{AtomicBool, Ordering}};
use std::time::Duration;
use serde_json::{json, Value};
use crate::profile::{Store, store_error};
use crate::protocol::{ErrorCode, ErrorObj};
fn bad(message: impl Into<String>) -> ErrorObj { ErrorObj::new(ErrorCode::BadRequest, message) }
fn required<'a>(args: &'a HashMap<String, String>, name: &str) -> Result<&'a str, ErrorObj> {
args.get(name).map(String::as_str).ok_or_else(|| bad(format!("{name} is required")))
}
pub fn emit(value: &Value) {
let mut out = std::io::stdout().lock();
let _ = writeln!(out, "{value}");
let _ = out.flush();
}
// Only the standalone CLI owns a blocking stdin cancellation reader. The
// embeddable improvement entrypoint never starts or waits for this reader.
fn improve(store: &Store, uid: &str, target: u8, seconds: u64) -> Result<Value, ErrorObj> {
let cancel = Arc::new(AtomicBool::new(false));
let signal = cancel.clone();
std::thread::spawn(move || {
let mut line = String::new();
// Cancel on explicit command, stdin closure or transport failure.
let _ = std::io::stdin().lock().read_line(&mut line);
signal.store(true, Ordering::Relaxed);
});
crate::identity_improve::improve(store, uid, target, Duration::from_secs(seconds), &cancel, |event| emit(&event))
}
fn execute(args: &[String]) -> Result<Value, ErrorObj> {
let action = args.first().ok_or_else(|| bad("identity action required"))?;
let allowed: &[&str] = match action.as_str() {
"list" => &[], "create" => &["--name", "--nickname"],
"update" => &["--uid", "--name", "--nickname"],
"default" => &["--uid"], "delete" => &["--uid", "--confirm-uid"],
"export" => &["--uid", "--out"], "import" => &["--in"],
"improve" => &["--uid", "--target", "--seconds"],
_ => return Err(bad("unknown identity action")),
};
let mut values = HashMap::new();
let mut iter = args[1..].iter();
while let Some(key) = iter.next() {
if key != "--data-dir" && !allowed.contains(&key.as_str()) { return Err(bad("unexpected identity argument")); }
let value = iter.next().ok_or_else(|| bad("missing argument value"))?;
if values.insert(key.clone(), value.clone()).is_some() { return Err(bad("duplicate argument")); }
}
let dir = PathBuf::from(required(&values, "--data-dir")?);
if !dir.is_absolute() { return Err(bad("--data-dir must be absolute")); }
// Atomic vault reads need no profile lock; exports remain available during standalone sessions.
// Mutations share the core lock and Store serializes writers/protects connected identities.
let _guard = if action == "list" || action == "export" { None } else {
Some(crate::locks::lock_dir(&dir, true).map_err(|e| ErrorObj::new(ErrorCode::Io, e))?)
};
let store = Store::new(dir);
let uid = || required(&values, "--uid");
match action.as_str() {
"list" => Ok(json!(store.list().map_err(store_error)?)),
"create" => Ok(json!(store.create_identity(required(&values,"--name")?, required(&values,"--nickname")?).map_err(store_error)?)),
"update" => Ok(json!(store.update_identity(uid()?, values.get("--name").map(String::as_str), values.get("--nickname").map(String::as_str)).map_err(store_error)?)),
"default" => { store.set_default(uid()?).map_err(store_error)?; Ok(json!({"uid":uid()?})) },
"delete" => { store.delete_identity(uid()?, required(&values,"--confirm-uid")?).map_err(store_error)?; Ok(json!({"uid":uid()?})) },
"export" => {
let ini = store.export_ini(uid()?).map_err(store_error)?;
let out = Path::new(required(&values,"--out")?);
if !out.is_absolute() { return Err(bad("--out must be absolute")); }
crate::secure_fs::write_atomic(out, ini.as_bytes(), true).map_err(|e| ErrorObj::new(ErrorCode::Io, e.to_string()))?;
Ok(json!({"uid":uid()?}))
},
"import" => {
let input = Path::new(required(&values,"--in")?);
if !input.is_absolute() { return Err(bad("--in must be absolute")); }
let mut text = String::new();
File::open(input).and_then(|f| f.take(65537).read_to_string(&mut text)).map_err(|e| ErrorObj::new(ErrorCode::Io, e.to_string()))?;
if text.len() > 65536 { return Err(bad("identity file exceeds 64 KiB")); }
Ok(json!(store.import_ini(&[&text]).map_err(store_error)?))
},
"improve" => {
let target = required(&values,"--target")?.parse::<u8>().map_err(|_| bad("invalid target"))?;
let seconds = values.get("--seconds").map(|v| v.parse::<u64>()).transpose().map_err(|_| bad("invalid duration"))?.unwrap_or(30);
if !(1..=crate::profile::MAX_TARGET_LEVEL).contains(&target) || !(1..=60).contains(&seconds) { return Err(bad("target must be 1–100; duration 1–60 seconds")); }
improve(&store, uid()?, target, seconds)
},
_ => unreachable!(),
}
}
pub fn run(args: &[String]) -> ExitCode {
match execute(args) {
Ok(result) => { emit(&json!({"ok":true,"result":result})); ExitCode::SUCCESS },
Err(error) => { emit(&json!({"ok":false,"error":error})); ExitCode::from(1) },
}
}
+168
View File
@@ -0,0 +1,168 @@
//! Bounded, cancellable hash-cash work. One core at <=25% duty cycle for at most 60 seconds.
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::{Duration, Instant};
use sha1::{Digest, Sha1};
use serde_json::{json, Value};
use crate::profile::{Store, store_error};
use crate::protocol::{ErrorCode, ErrorObj};
// TeamSpeak counts trailing bits of each SHA1 byte, starting with the first byte.
// Decimal conversion uses a stack buffer: no allocation per candidate.
fn quality(prefix: &Sha1, mut offset: u64) -> u8 {
let mut digits = [0u8; 20];
let mut pos = digits.len();
loop {
pos -= 1; digits[pos] = b'0' + (offset % 10) as u8; offset /= 10;
if offset == 0 { break; }
}
let mut hash = prefix.clone();
hash.update(&digits[pos..]);
let mut level = 0;
for byte in hash.finalize() {
if byte == 0 { level += 8; } else { level += byte.trailing_zeros() as u8; break; }
}
level
}
/// Improve an identity on the caller's worker, persisting progress before notifying it.
/// Cancellation is caller-owned; this function creates no threads or transport readers.
/// Returning (including cancellation) completes the final durable checkpoint.
pub fn improve(
store: &Store,
uid: &str,
target: u8,
duration: Duration,
cancel: &AtomicBool,
mut progress: impl FnMut(Value),
) -> Result<Value, ErrorObj> {
if !(1..=crate::profile::MAX_TARGET_LEVEL).contains(&target)
|| duration.is_zero() || duration > Duration::from_secs(60)
{
return Err(ErrorObj::new(ErrorCode::BadRequest, "target must be 1–100; duration greater than zero and at most 60 seconds"));
}
let start = store.improve_start(uid).map_err(store_error)?;
let mut prefix = Sha1::new(); prefix.update(start.omega.as_bytes());
let begun = Instant::now();
let mut checkpoint = Instant::now();
let mut next = start.start;
let mut level = start.level;
let mut best = None;
let mut exhausted = false;
while level < target && begun.elapsed() < duration && !cancel.load(Ordering::Relaxed) {
let slice = Instant::now();
while slice.elapsed() < Duration::from_millis(5) && !cancel.load(Ordering::Relaxed) {
let candidate = quality(&prefix, next);
if candidate > level { level = candidate; best = Some(next); }
if next == u64::MAX { exhausted = true; break; }
next += 1;
if level >= target { break; }
}
if checkpoint.elapsed() >= Duration::from_millis(500) || level >= target || exhausted {
level = store.record_improvement(uid, best.take(), next).map_err(store_error)?;
progress(json!({"event":"identity_progress","uid":uid,"level":level,"target":target,"searched":next.to_string(),"elapsed_ms":begun.elapsed().as_millis()}));
checkpoint = Instant::now();
}
if exhausted { break; }
std::thread::sleep(Duration::from_millis(15));
}
level = store.record_improvement(uid, best, next).map_err(store_error)?;
Ok(json!({"uid":uid,"level":level,"target":target,"reached":level>=target,"canceled":cancel.load(Ordering::Relaxed),"bounded":level<target,"exhausted":exhausted,"searched":next.to_string()}))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn known_sha1_vectors_and_decimal_boundaries() {
// SHA1("0")=b6589fc6… -> first byte 0xb6 has one trailing zero bit.
assert_eq!(quality(&Sha1::new(), 0), 1);
// SHA1("1")=356a192b… -> odd first byte gives zero bits.
assert_eq!(quality(&Sha1::new(), 1), 0);
for offset in [0, 1, 9, 10, 99, 100, u64::MAX] {
let mut p = Sha1::new(); p.update(b"public-key");
let raw = Sha1::digest(format!("public-key{offset}").as_bytes());
let expected = raw.iter().take_while(|b| **b == 0).count() as u8 * 8 + raw.iter().find(|b| **b != 0).map(|b| b.trailing_zeros() as u8).unwrap_or(0);
assert_eq!(quality(&p, offset), expected);
}
}
#[test]
fn cancellation_checkpoints_without_changing_identity() {
let dir = crate::profile::tests::TempDir::new("improve-cancel");
let store = Store::new(&dir.0);
let identity = store.create_identity("Temporary", "Temporary").unwrap();
let before = store.export_ini(&identity.uid).unwrap();
let result = std::thread::scope(|scope| {
scope.spawn(|| improve(&store, &identity.uid, 100, Duration::from_secs(1), &AtomicBool::new(true), |_| panic!("pre-canceled work must not report progress")))
.join().expect("native worker joins without a stdin reader").unwrap()
});
assert_eq!(result["canceled"], true);
assert_eq!(before, store.export_ini(&identity.uid).unwrap());
}
#[test]
fn native_bounds_reject_before_touching_identity() {
let dir = crate::profile::tests::TempDir::new("improve-invalid");
let store = Store::new(&dir.0);
let info = store.create_identity("Temporary", "Temporary").unwrap();
let before = store.export_ini(&info.uid).unwrap();
let start = store.improve_start(&info.uid).unwrap().start;
for (target, duration) in [
(0, Duration::from_secs(1)),
(101, Duration::from_secs(1)),
(100, Duration::ZERO),
(100, Duration::from_secs(61)),
] {
let error = improve(&store, &info.uid, target, duration, &AtomicBool::new(false), |_| panic!("invalid work must not report progress")).unwrap_err();
assert_eq!(serde_json::to_value(error).unwrap()["code"], "bad_request");
}
assert_eq!(before, store.export_ini(&info.uid).unwrap());
assert_eq!(start, store.improve_start(&info.uid).unwrap().start);
}
#[test]
fn quality_matches_protocol_identity_and_deadline_resumes() {
let dir = crate::profile::tests::TempDir::new("improve-bound");
let store = Store::new(&dir.0);
let info = store.create_identity("Temporary", "Temporary").unwrap();
let stored = store.load_identity().unwrap().unwrap();
let start = store.improve_start(&info.uid).unwrap();
let mut prefix = Sha1::new(); prefix.update(start.omega.as_bytes());
assert_eq!(quality(&prefix, stored.identity.counter()), stored.identity.level());
let result = improve(&store, &info.uid, 100, Duration::from_millis(20), &AtomicBool::new(false), |_| {}).unwrap();
assert_eq!(result["bounded"], true);
let resumed = store.improve_start(&info.uid).unwrap();
assert!(resumed.start > start.start);
assert!(resumed.level >= start.level);
assert_eq!(store.load_identity().unwrap().unwrap().uid, info.uid);
assert_eq!(resumed.start.to_string(), result["searched"].as_str().unwrap());
}
#[test]
fn cancellation_during_search_preserves_checkpoint_and_resumes() {
let dir = crate::profile::tests::TempDir::new("improve-running-cancel");
let store = Store::new(&dir.0);
let info = store.create_identity("Temporary", "Temporary").unwrap();
let original_key = store.load_identity().unwrap().unwrap().identity.key().to_ts();
let mut previous = store.improve_start(&info.uid).unwrap().start;
for _ in 0..2 {
let cancel = AtomicBool::new(false);
let mut checkpoint = None;
// Cancel synchronously at a durable checkpoint, without a timing race
// against a detached canceller or relying on thread scheduling.
let result = improve(&store, &info.uid, 100, Duration::from_secs(60), &cancel, |event| {
assert_eq!(event["uid"], info.uid);
let persisted = store.improve_start(&info.uid).unwrap();
assert_eq!(event["searched"], persisted.start.to_string());
checkpoint = Some(persisted.start);
cancel.store(true, Ordering::Relaxed);
}).unwrap();
assert_eq!(result["canceled"], true);
let next = checkpoint.expect("search must report a durable checkpoint");
assert!(next > previous);
let persisted = store.improve_start(&info.uid).unwrap();
assert_eq!(persisted.start, next);
assert_eq!(result["searched"], next.to_string());
let loaded = store.load_identity().unwrap().unwrap();
assert_eq!(loaded.uid, info.uid);
assert_eq!(loaded.identity.key().to_ts(), original_key);
let mut prefix = Sha1::new(); prefix.update(persisted.omega.as_bytes());
assert_eq!(quality(&prefix, loaded.identity.counter()), persisted.level);
previous = next;
}
}
}
+175
View File
@@ -0,0 +1,175 @@
//! Decoding of stored TeamSpeak private keys that tolerates leading zero bytes.
//!
//! Upstream `tsproto_types::crypto::EccKeyPrivP256::from_tomcrypt` passes the DER integer's
//! minimal big-endian bytes to `from_short`, which requires exactly 32 bytes. A private scalar
//! whose top byte is 0x00 (about 1 key in 256) is therefore written fine by `to_ts` but can never
//! be read back. `private_key_from_tomcrypt` is upstream's decoder — the same `simple_asn1`
//! parser and the same block positions — with the single difference that the scalar is
//! left-padded to 32 bytes. The stored format is unchanged.
use base64::prelude::*;
use sha1::{Digest, Sha1};
use simple_asn1::{ASN1Block, BigInt};
use tsclientlib::Identity;
use tsproto_types::crypto::EccKeyPrivP256;
/// XOR mask TeamSpeak applies to identities in its settings/export files (same constant as
/// tsproto-types' `IDENTITY_OBFUSCATION`, MIT OR Apache-2.0).
const IDENTITY_OBFUSCATION: &[u8; 128] = b"b9dfaa7bee6ac57ac7b65f1094a1c155\
e747327bc2fe5d51c512023fe54a280201004e90ad1daaae1075d53b7d571c30e063b5a\
62a4a017bb394833aa0983e6e";
/// Private key from libtomcrypt DER: `SEQUENCE { BIT STRING flags, INTEGER size, INTEGER x,
/// INTEGER y, INTEGER priv }`, or the 2-bit variant `{ BIT STRING, INTEGER size, INTEGER priv }`.
pub fn private_key_from_tomcrypt(der: &[u8]) -> Result<EccKeyPrivP256, String> {
let blocks = simple_asn1::from_der(der).map_err(|e| format!("invalid DER: {e}"))?;
let [ASN1Block::Sequence(_, items)] = blocks.as_slice() else {
return Err("expected a single DER SEQUENCE".into());
};
let Some(ASN1Block::BitString(_, bit_count, flags)) = items.first() else {
return Err("expected BIT STRING".into());
};
if !flags.first().is_some_and(|f| f & 0x80 != 0) {
return Err("key has no private part".into());
}
let priv_index = match bit_count {
1 => 4,
2 => 2,
n => return Err(format!("unexpected flag bit count {n}")),
};
let Some(ASN1Block::Integer(_, scalar)) = items.get(priv_index) else {
return Err("missing private INTEGER".into());
};
if *scalar < BigInt::default() {
return Err("negative private scalar".into());
}
let (_, digits) = scalar.to_bytes_be();
if digits.len() > 32 {
return Err("private scalar longer than 32 bytes".into());
}
let mut short = [0u8; 32];
short[32 - digits.len()..].copy_from_slice(&digits);
EccKeyPrivP256::from_short(&short).map_err(|e| e.to_string())
}
/// Base64 libtomcrypt key as stored in `identity.json` (`EccKeyPrivP256::to_ts` output).
pub fn private_key_from_ts(b64: &str) -> Result<EccKeyPrivP256, String> {
let der = BASE64_STANDARD.decode(b64).map_err(|e| format!("not base64: {e}"))?;
private_key_from_tomcrypt(&der)
}
/// Reverse of `EccKeyPrivP256::to_ts_obfuscated`.
fn deobfuscate(b64: &str) -> Result<String, String> {
let mut data = BASE64_STANDARD.decode(b64).map_err(|e| format!("not base64: {e}"))?;
if data.len() < 20 {
return Err("obfuscated key too short".into());
}
let pos = data[20..].iter().position(|b| *b == 0).unwrap_or(data.len() - 20);
let hash = Sha1::digest(&data[20..20 + pos]);
for (d, h) in data.iter_mut().zip(hash.iter()).take(20) {
*d ^= h;
}
for (d, m) in data.iter_mut().zip(IDENTITY_OBFUSCATION.iter()).take(100) {
*d ^= m;
}
String::from_utf8(data).map_err(|_| "deobfuscated key is not text".into())
}
/// TeamSpeak identity string `<offset>V<key>` where `<key>` is the obfuscated form (TS client
/// exports) or plain base64 libtomcrypt DER.
pub fn identity_from_ts_str(value: &str) -> Result<Identity, String> {
let (counter, key) = value.split_once('V').ok_or("missing 'V' separator")?;
let counter: u64 = counter.parse().map_err(|_| "invalid key offset")?;
let key = private_key_from_ts(key)
.or_else(|plain_err| deobfuscate(key).and_then(|t| private_key_from_ts(&t)).map_err(|e| format!("{e} (as plain key: {plain_err})")))?;
Ok(Identity::new(key, counter))
}
#[cfg(test)]
pub mod tests {
use super::*;
use simple_asn1::{to_der, ASN1Block::*};
/// Valid P-256 scalars (non-zero, below the group order) covering every DER length case.
pub const ONE_LEADING_ZERO: [u8; 32] = scalar(1, 0x5a);
const THREE_LEADING_ZEROS: [u8; 32] = scalar(3, 0x5a);
/// Top bit set: DER needs a 0x00 sign byte (33 content bytes).
const SIGN_PADDED: [u8; 32] = scalar(0, 0x80);
/// Full width without sign byte (32 content bytes).
const FULL_WIDTH: [u8; 32] = scalar(0, 0x7f);
const fn scalar(zeros: usize, first: u8) -> [u8; 32] {
let mut s = [0x5au8; 32];
let mut i = 0;
while i < zeros {
s[i] = 0;
i += 1;
}
s[zeros] = first;
s
}
pub fn key(s: &[u8; 32]) -> EccKeyPrivP256 { EccKeyPrivP256::from_short(s).unwrap() }
#[test]
fn fixed_scalars_roundtrip_in_every_stored_form() {
for s in [ONE_LEADING_ZERO, THREE_LEADING_ZEROS, SIGN_PADDED, FULL_WIDTH] {
let k = key(&s);
let ts = k.to_ts();
assert_eq!(private_key_from_ts(&ts).unwrap().to_short().as_slice(), s.as_slice());
let id = identity_from_ts_str(&format!("42V{}", k.to_ts_obfuscated())).unwrap();
assert_eq!(id.key().to_short().as_slice(), s.as_slice());
assert_eq!(id.counter(), 42);
assert_eq!(identity_from_ts_str(&format!("7V{ts}")).unwrap().key().to_short().as_slice(), s.as_slice());
}
}
#[test]
fn upstream_test_vector_and_garbage() {
// Vector from tsproto's own tests (TS client identity), UID known.
const KEY: &str = "MG8DAgeAAgEgAiEA6rtKxDn/o/Bo50rNtAE5Ph3h2RKLHQ0gbFkvm2yA79kCIQCrfzAZts/vHP+3MOetKLjNnpZXt4c6U3UB4gWLKR4H9AIgYTyJofmztcTBjq3KZcDdxu+G4RPVwE5vg8VaN2jbQao=";
let k = private_key_from_ts(KEY).unwrap();
assert_eq!(k.to_pub().get_uid(), "test/9PZ9vww/Bpf5vJxtJhpz80=");
for bad in ["", "AAAA", "MAA=", "not base64!"] {
assert!(private_key_from_ts(bad).is_err(), "{bad}");
}
assert!(identity_from_ts_str("xVabc").is_err());
assert!(identity_from_ts_str("1Vgarbage").is_err());
}
fn int(v: &[u8]) -> ASN1Block { Integer(0, BigInt::from_signed_bytes_be(v)) }
/// libtomcrypt layout with a 1-bit flag string; `priv_value` goes into the private slot.
fn der_with(flags: ASN1Block, priv_value: ASN1Block) -> Vec<u8> {
to_der(&Sequence(0, vec![flags, int(&[32]), int(&[1]), int(&[2]), priv_value])).unwrap()
}
#[test]
fn malformed_keys_are_errors_not_panics() {
let good = key(&ONE_LEADING_ZERO).to_tomcrypt();
assert!(private_key_from_tomcrypt(&good).is_ok());
let private_flag = || BitString(0, 1, vec![0x80]);
let mut cases: Vec<(&str, Vec<u8>)> = vec![
("truncated", good[..good.len() - 1].to_vec()),
("trailing block", [good.clone(), vec![0x05, 0x00]].concat()),
("not a sequence", to_der(&int(&[1])).unwrap()),
("empty sequence", to_der(&Sequence(0, vec![])).unwrap()),
("first item not a BIT STRING", to_der(&Sequence(0, vec![int(&[1]), int(&[1])])).unwrap()),
("public-only flag", der_with(BitString(0, 1, vec![0x00]), int(&ONE_LEADING_ZERO))),
("empty BIT STRING", der_with(BitString(0, 0, vec![]), int(&ONE_LEADING_ZERO))),
("3-bit flags", der_with(BitString(0, 3, vec![0x80]), int(&ONE_LEADING_ZERO))),
("private slot missing", to_der(&Sequence(0, vec![private_flag(), int(&[32])])).unwrap()),
("private slot not INTEGER", der_with(private_flag(), OctetString(0, ONE_LEADING_ZERO.to_vec()))),
("negative scalar", der_with(private_flag(), int(&[0xff]))),
("zero scalar", der_with(private_flag(), int(&[0]))),
("scalar above the group order", der_with(private_flag(), int(&[[0u8].as_slice(), &[0xff; 32]].concat()))),
("33-byte scalar", der_with(private_flag(), int(&[[0x01u8].as_slice(), &[0x5a; 32]].concat()))),
];
// Raw BIT STRING whose unused-bit count exceeds its length, and one with an empty INTEGER.
cases.push(("unused bits > length", vec![0x30, 0x04, 0x03, 0x02, 0x09, 0x80]));
cases.push(("empty INTEGER", vec![0x30, 0x0f, 0x03, 0x02, 0x07, 0x80, 0x02, 0x01, 0x20, 0x02, 0x01, 0x01, 0x02, 0x01, 0x02, 0x02, 0x00]));
for (name, der) in cases {
assert!(private_key_from_tomcrypt(&der).is_err(), "{name}");
}
}
}
+28
View File
@@ -0,0 +1,28 @@
//! Embedded TeamSpeak domain services and the independent diagnostic CLI adapters.
pub mod admin;
pub mod app_audio;
pub mod audio;
mod events;
pub mod file_transfer;
pub mod hotkeys;
mod keyfmt;
pub mod identity_cli;
pub mod identity_improve;
pub mod locks;
pub mod media;
pub mod menu;
pub mod output;
pub mod profile;
pub mod protocol;
pub mod recording;
mod rawcmd;
pub mod runtime;
pub mod secure_fs;
pub mod session;
mod snapshot;
pub mod stdio;
#[cfg(test)]
mod test_exec;
pub mod vad;
pub mod voice_dsp;
pub mod whisper;
+23
View File
@@ -0,0 +1,23 @@
use std::fs::{File, OpenOptions, TryLockError};
use std::path::Path;
use crate::secure_fs;
/// Cooperates with diagnostic CLI and embedded sessions without copying private identity keys.
pub fn lock_dir(dir: &Path, shared: bool) -> Result<File, String> {
secure_fs::ensure_private_dir(dir).map_err(|e| format!("cannot create data dir {}: {e}", dir.display()))?;
let path = dir.join("core.lock");
let file = OpenOptions::new().create(true).truncate(false).write(true).open(&path)
.map_err(|e| format!("cannot open {}: {e}", path.display()))?;
match if shared { file.try_lock_shared() } else { file.try_lock() } {
Ok(()) => Ok(file),
Err(TryLockError::WouldBlock) => Err(format!("data dir {} is in use by another teamspeach-core", dir.display())),
Err(TryLockError::Error(e)) => Err(format!("cannot lock {}: {e}", path.display())),
}
}
pub fn lock_run(data_dir: &Path, connection_dir: Option<&Path>) -> Result<Vec<File>, String> {
match connection_dir {
None => Ok(vec![lock_dir(data_dir, false)?]),
Some(conn) => Ok(vec![lock_dir(data_dir, true)?, lock_dir(conn, false)?]),
}
}
+41 -98
View File
@@ -1,18 +1,7 @@
//! TeamsPeach core: TeamSpeak protocol backend speaking newline-delimited JSON on stdio.
//! Contract: `docs/bridge.md`.
mod audio;
mod media;
mod profile;
mod protocol;
mod rawcmd;
mod secure_fs;
mod session;
mod snapshot;
mod stdio;
use std::fs::{File, OpenOptions, TryLockError};
use std::io::{Read, Write};
use teamspeach_core::{app_audio, audio, hotkeys, identity_cli, locks, output, profile, protocol, session, stdio};
use std::path::{Path, PathBuf};
use std::process::ExitCode;
use std::sync::Arc;
@@ -22,107 +11,56 @@ use serde_json::json;
use tokio::sync::mpsc;
use tracing::{error, info};
use crate::audio::AudioInQueue;
use crate::profile::Store;
use crate::protocol::{ErrorObj, PROTOCOL_VERSION};
use crate::stdio::Out;
use audio::AudioInQueue;
use profile::Store;
use protocol::PROTOCOL_VERSION;
use output::Out;
const EXIT_FATAL: u8 = 1;
const EXIT_USAGE: u8 = 2;
const EXIT_DATA_DIR: u8 = 3;
const MAX_IMPORT_BYTES: u64 = 64 * 1024;
const USAGE: &str = "usage:
teamspeach-core --data-dir <ABSOLUTE_DIR>
teamspeach-core identity export --data-dir <ABSOLUTE_DIR> --out <FILE>
teamspeach-core identity import --data-dir <ABSOLUTE_DIR> --in <FILE> [--replace]";
teamspeach-core --data-dir <ABSOLUTE_DIR> [--connection-dir <ABSOLUTE_DIR>]
teamspeach-core identity <list|create|update|default|delete|export|import|improve> --data-dir <ABSOLUTE_DIR> [options]
teamspeach-core hotkeys";
enum Mode {
Run { data_dir: PathBuf },
Export { data_dir: PathBuf, out: PathBuf },
Import { data_dir: PathBuf, input: PathBuf, replace: bool },
/// `connection_dir`: one of several simultaneous cores sharing the profile in `data_dir`.
Run { data_dir: PathBuf, connection_dir: Option<PathBuf> },
}
fn parse_args(args: &[String]) -> Result<Mode, String> {
let (sub, rest) = match args {
[a, b, rest @ ..] if a == "identity" && (b == "export" || b == "import") => (Some(b.as_str()), rest),
rest => (None, rest),
};
let rest = args;
let mut data_dir = None;
let mut out = None;
let mut input = None;
let mut replace = false;
let mut connection_dir = None;
let mut it = rest.iter();
while let Some(a) = it.next() {
let mut value = |name: &str| it.next().cloned().ok_or_else(|| format!("{name} needs a value"));
match a.as_str() {
"--data-dir" => data_dir = Some(PathBuf::from(value("--data-dir")?)),
"--out" if sub == Some("export") => out = Some(PathBuf::from(value("--out")?)),
"--in" if sub == Some("import") => input = Some(PathBuf::from(value("--in")?)),
"--replace" if sub == Some("import") => replace = true,
other => return Err(format!("unexpected argument {other:?}")),
"--connection-dir" => connection_dir = Some(PathBuf::from(value("--connection-dir")?)),
other => return Err(format!("unexpected argument {other:?}")),
}
}
let data_dir = data_dir.ok_or("--data-dir is required")?;
if !data_dir.is_absolute() {
return Err("--data-dir must be an absolute path".into());
}
Ok(match sub {
None => Mode::Run { data_dir },
Some("export") => Mode::Export { data_dir, out: out.ok_or("--out is required")? },
Some(_) => Mode::Import { data_dir, input: input.ok_or("--in is required")?, replace },
})
}
/// Exclusive lock on `<data-dir>/core.lock`, held for the process lifetime.
fn lock_data_dir(dir: &Path) -> Result<File, String> {
secure_fs::ensure_private_dir(dir).map_err(|e| format!("cannot create data dir {}: {e}", dir.display()))?;
let path = dir.join("core.lock");
let file = OpenOptions::new()
.create(true)
.truncate(false)
.write(true)
.open(&path)
.map_err(|e| format!("cannot open {}: {e}", path.display()))?;
match file.try_lock() {
Ok(()) => Ok(file),
Err(TryLockError::WouldBlock) => Err(format!("data dir {} is in use by another teamspeach-core", dir.display())),
Err(TryLockError::Error(e)) => Err(format!("cannot lock {}: {e}", path.display())),
if let Some(dir) = &connection_dir {
if !dir.is_absolute() {
return Err("--connection-dir must be an absolute path".into());
}
if dir == &data_dir {
return Err("--connection-dir must differ from --data-dir".into());
}
}
Ok(Mode::Run { data_dir, connection_dir })
}
fn print_cli_result(result: Result<String, ErrorObj>) -> ExitCode {
let (line, code) = match result {
Ok(uid) => (json!({ "ok": true, "uid": uid }), ExitCode::SUCCESS),
Err(e) => (json!({ "ok": false, "error": e }), ExitCode::from(EXIT_FATAL)),
};
let mut stdout = std::io::stdout().lock();
let _ = writeln!(stdout, "{line}");
let _ = stdout.flush();
code
}
fn export(data_dir: &Path, out: &Path) -> Result<String, ErrorObj> {
// Unlocked read-only access is safe: identity.json/profile.json are only ever replaced by
// atomic rename (key-offset upgrade, rename, import --replace), so a concurrent reader sees
// one complete version, and load_identity verifies it.
let (ini, uid) = Store::new(data_dir).export_ts_ini().map_err(session::store_error)?;
secure_fs::write_atomic(out, ini.as_bytes(), true)
.map_err(|e| ErrorObj::new(protocol::ErrorCode::Io, format!("writing {}: {e}", out.display())))?;
Ok(uid)
}
fn import(data_dir: &Path, input: &Path, replace: bool) -> Result<String, ErrorObj> {
let io = |e: std::io::Error| ErrorObj::new(protocol::ErrorCode::Io, format!("reading {}: {e}", input.display()));
let mut text = String::new();
File::open(input).map_err(io)?.take(MAX_IMPORT_BYTES + 1).read_to_string(&mut text).map_err(io)?;
if text.len() as u64 > MAX_IMPORT_BYTES {
return Err(ErrorObj::new(protocol::ErrorCode::BadRequest, "identity file is too large"));
}
Store::new(data_dir).import_ts_ini(&text, replace).map_err(session::store_error)
}
fn run(data_dir: PathBuf) -> ExitCode {
let _lock = match lock_data_dir(&data_dir) {
fn run(data_dir: PathBuf, connection_dir: Option<PathBuf>) -> ExitCode {
let _locks = match locks::lock_run(&data_dir, connection_dir.as_deref()) {
Ok(l) => l,
Err(e) => {
error!("{e}");
@@ -137,8 +75,8 @@ fn run(data_dir: PathBuf) -> ExitCode {
}
};
rt.block_on(async move {
let (out, out_rx) = Out::new();
let writer = tokio::spawn(stdio::run_writer(out_rx));
let (out, out_rx, playback_rx) = Out::new();
let writer = tokio::spawn(stdio::run_writer(out_rx, playback_rx));
let audio_in = Arc::new(AudioInQueue::new());
let (cmd_tx, cmd_rx) = mpsc::channel(64);
{
@@ -150,7 +88,7 @@ fn run(data_dir: PathBuf) -> ExitCode {
}
out.json(&json!({ "event": "ready", "protocol": PROTOCOL_VERSION, "core_version": env!("CARGO_PKG_VERSION") }))
.await;
info!(data_dir = %data_dir.display(), "teamspeach-core ready");
info!(data_dir = %data_dir.display(), connection_dir = ?connection_dir.as_deref().map(Path::display), "teamspeach-core ready");
session::Session::new(Store::new(&data_dir), out, audio_in).run(cmd_rx).await;
// All `Out` senders are gone once the session is dropped; the writer drains and exits.
let _ = writer.await;
@@ -171,6 +109,19 @@ fn main() -> ExitCode {
.init();
let args: Vec<String> = std::env::args().skip(1).collect();
if args.first().is_some_and(|arg| arg == "app-audio") {
return app_audio::run(&args[1..]);
}
if args.first().is_some_and(|arg| arg == "identity") {
return identity_cli::run(&args[1..]);
}
if args.first().is_some_and(|arg| arg == "hotkeys") {
if args.len() != 1 { eprintln!("hotkeys takes no arguments"); return ExitCode::from(EXIT_USAGE); }
return match hotkeys::run() {
Ok(()) => ExitCode::SUCCESS,
Err(e) => { eprintln!("hotkeys: {e}"); ExitCode::from(EXIT_FATAL) }
};
}
let mode = match parse_args(&args) {
Ok(m) => m,
Err(e) => {
@@ -179,14 +130,6 @@ fn main() -> ExitCode {
}
};
match mode {
Mode::Run { data_dir } => run(data_dir),
Mode::Export { data_dir, out } => print_cli_result(export(&data_dir, &out)),
Mode::Import { data_dir, input, replace } => match lock_data_dir(&data_dir) {
Ok(_lock) => print_cli_result(import(&data_dir, &input, replace)),
Err(e) => {
eprintln!("error: {e}");
ExitCode::from(EXIT_DATA_DIR)
}
},
Mode::Run { data_dir, connection_dir } => run(data_dir, connection_dir),
}
}
+299
View File
@@ -0,0 +1,299 @@
//! Target-bound user actions. Protocol names/fields follow pinned ReSpeak Messages.toml.
//! Permission hints come from the server; role names are never authorization evidence.
use std::collections::{BTreeMap, HashMap};
use base64::prelude::*;
use serde::Deserialize;
use serde_json::{json, Value};
use tsclientlib::{ClientId, GroupType};
use tsproto_packets::packets::{Direction, Flags, OutCommand, PacketType};
use crate::protocol::{ErrorCode, ErrorObj};
use crate::rawcmd::RawNotification;
pub type Row = BTreeMap<String, String>;
/// Live per-connection volume changes from the client menu: (dB modifier, muted) by raw UID. Without a
/// live entry the persisted modifier applies (unmuted); mute is never persisted. See voice_dsp.rs.
#[derive(Default)]
pub struct LocalVolumes(HashMap<Vec<u8>, (f32, bool)>);
impl LocalVolumes {
pub fn set(&mut self, uid: &[u8], db: f32, muted: bool) { self.0.insert(uid.to_vec(), (db, muted)); }
pub fn get(&self, uid: &[u8], persisted: &HashMap<Vec<u8>, f32>) -> (f32, bool) {
self.0.get(uid).copied().unwrap_or_else(|| (persisted.get(uid).copied().unwrap_or(0.0), false))
}
/// Linear gain for the mixer (0 when muted or at -200 dB).
pub fn gain(&self, uid: &[u8], persisted: &HashMap<Vec<u8>, f32>) -> f32 {
let (db, muted)=self.get(uid, persisted); if muted {0.0} else {crate::voice_dsp::db_to_gain(db)}
}
pub fn clear(&mut self) { self.0.clear(); }
}
#[derive(Clone, Debug, PartialEq, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Target { pub client_id: u16, pub uid: String }
#[derive(Clone, Debug, PartialEq)]
pub struct ActionRequest { pub target: Target, pub generation: u64, pub action: Action }
#[derive(Clone, Debug, PartialEq, Deserialize)]
#[serde(tag="action", rename_all="snake_case", deny_unknown_fields)]
pub enum Action {
Poke { message: String }, ConnectionInfo {}, Commander { enabled: bool },
ServerGroup { group_id: u64, enabled: bool }, ChannelGroup { group_id: u64, channel_id: u64 },
ClientPermissions {}, ChannelPermissions { channel_id: u64 },
SetClientPermission { permission_id: u32, value: Option<i32>, skip: bool },
SetChannelPermission { channel_id: u64, permission_id: u32, value: Option<i32> },
KickChannel { reason: String }, KickServer { reason: String }, Ban { reason: String, duration: u32 },
Volume { db: f32, muted: bool }, Avatar { data: String },
MoveToOwnChannel { #[serde(default)] password: Option<String>, expected_channel_id: u64 }, DeleteAvatar {},
}
impl Action {
pub fn key(&self) -> &'static str { match self {
Self::Poke{..}=>"poke",Self::ConnectionInfo{}=>"connection_info",Self::Commander{..}=>"commander",
Self::ServerGroup{..}=>"server_group",Self::ChannelGroup{..}=>"channel_group",
Self::ClientPermissions{}=>"client_permissions",Self::ChannelPermissions{..}=>"channel_permissions",
Self::SetClientPermission{..}=>"set_client_permission",Self::SetChannelPermission{..}=>"set_channel_permission",
Self::KickChannel{..}=>"kick_channel",Self::KickServer{..}=>"kick_server",Self::Ban{..}=>"ban",
Self::Volume{..}=>"volume",Self::Avatar{..}=>"avatar",
Self::MoveToOwnChannel{..}=>"move_to_own_channel",Self::DeleteAvatar{}=>"delete_avatar",
}}
pub fn response(&self) -> Option<&'static str> { match self {
Self::ConnectionInfo{}=>Some("notifyconnectioninfo"), Self::ClientPermissions{}=>Some("notifyclientpermlist"),
Self::ChannelPermissions{..}=>Some("notifychannelclientpermlist"), _=>None,
}}
}
pub fn bad(message: impl Into<String>) -> ErrorObj { ErrorObj::new(ErrorCode::BadRequest,message) }
pub fn validate_target(t: &Target) -> Result<(), ErrorObj> {
if t.client_id == 0 || t.uid.is_empty() || t.uid.len()>128 || t.uid.chars().any(char::is_control) { return Err(bad("invalid client target")); }
Ok(())
}
pub fn parse_action(mut value: Value) -> Result<ActionRequest, ErrorObj> {
let obj=value.as_object_mut().ok_or_else(||bad("args must be an object"))?;
let target=serde_json::from_value::<Target>(json!({"client_id":obj.remove("client_id"),"uid":obj.remove("uid")})).map_err(|e|bad(e.to_string()))?;
let generation=obj.remove("generation").and_then(|v|v.as_u64()).filter(|v|*v>0).ok_or_else(||bad("generation is required"))?;
if matches!(obj.get("action").and_then(Value::as_str),Some("set_client_permission"|"set_channel_permission")) && !obj.contains_key("value") { return Err(bad("value is required; use null explicitly to remove a permission")); }
let action:Action=serde_json::from_value(value).map_err(|e|bad(e.to_string()))?;
Ok(ActionRequest { target, generation, action })
}
pub(crate) fn validate_action(request: &ActionRequest) -> Result<(), ErrorObj> {
validate_target(&request.target)?;
if request.generation == 0 { return Err(bad("generation is required")); }
match &request.action {
Action::Poke{message} if message.is_empty() || message.len()>1024 || message.chars().any(char::is_control) =>return Err(bad("poke message must be 1..1024 bytes without controls")),
Action::KickChannel{reason}|Action::KickServer{reason}|Action::Ban{reason,..} if reason.len()>1024 || reason.chars().any(char::is_control)=>return Err(bad("reason must be at most 1024 bytes without controls")),
Action::Volume{db,..} if !crate::voice_dsp::valid_modifier_db(*db)=>return Err(bad("volume must be -200..10 dB in 0.5 dB steps")),
Action::ServerGroup{group_id,..}|Action::ChannelGroup{group_id,..} if *group_id==0=>return Err(bad("group_id must be positive")),
Action::ChannelGroup{channel_id,..}|Action::ChannelPermissions{channel_id}|Action::SetChannelPermission{channel_id,..} if *channel_id==0=>return Err(bad("channel_id must be positive")),
Action::SetClientPermission{permission_id,..}|Action::SetChannelPermission{permission_id,..} if *permission_id==0=>return Err(bad("permission_id must be positive")),
Action::MoveToOwnChannel{expected_channel_id:0,..}=>return Err(bad("expected_channel_id must be positive")),
Action::MoveToOwnChannel{password:Some(p),..} if p.len()>1024 || p.chars().any(char::is_control)=>return Err(bad("invalid channel password")),
Action::Avatar{data}=>{avatar_bytes(data)?;},
_=>{},
}
Ok(())
}
pub fn avatar_bytes(data:&str)->Result<Vec<u8>,ErrorObj>{
if data.len()>174_764 { return Err(bad("avatar exceeds 128 KiB")); }
let bytes=BASE64_STANDARD.decode(data).map_err(|_|bad("avatar is not base64"))?;
if bytes.len()>128*1024 || !(bytes.starts_with(b"\x89PNG\r\n\x1a\n") || bytes.starts_with(&[0xff,0xd8,0xff])) {return Err(bad("avatar must be PNG or JPEG, at most 128 KiB"));}
Ok(bytes)
}
pub fn command(name:&'static str,args:&[(&str,String)])->OutCommand {
let mut cmd=OutCommand::new(Direction::C2S,Flags::empty(),PacketType::Command,name);
for (key,value) in args {cmd.write_arg(key,value);}
cmd
}
pub fn action_command(action:&Action,client_id:u16,dbid:u64)->Option<OutCommand>{
let clid=client_id.to_string(); let dbid=dbid.to_string();
let (name,args)=match action {
Action::Poke{message}=>("clientpoke",vec![("clid",clid),("msg",message.clone())]),
Action::ConnectionInfo{}=>("getconnectioninfo",vec![("clid",clid)]),
Action::Commander{enabled}=>("clientupdate",vec![("client_is_channel_commander",u8::from(*enabled).to_string())]),
Action::ServerGroup{group_id,enabled}=>(if *enabled {"servergroupaddclient"} else {"servergroupdelclient"},vec![("sgid",group_id.to_string()),("cldbid",dbid)]),
Action::ChannelGroup{group_id,channel_id}=>("setclientchannelgroup",vec![("cgid",group_id.to_string()),("cid",channel_id.to_string()),("cldbid",dbid)]),
Action::ClientPermissions{}=>("clientpermlist",vec![("cldbid",dbid)]),
Action::ChannelPermissions{channel_id}=>("channelclientpermlist",vec![("cid",channel_id.to_string()),("cldbid",dbid)]),
Action::SetClientPermission{permission_id,value,skip}=>{
let mut args=vec![("cldbid",dbid),("permid",permission_id.to_string())];
if let Some(v)=value {args.extend([("permvalue",v.to_string()),("permskip",u8::from(*skip).to_string())]);}
(if value.is_some(){"clientaddperm"}else{"clientdelperm"},args)
},
Action::SetChannelPermission{channel_id,permission_id,value}=>{
let mut args=vec![("cid",channel_id.to_string()),("cldbid",dbid),("permid",permission_id.to_string())];
if let Some(v)=value {args.push(("permvalue",v.to_string()));}
(if value.is_some(){"channelclientaddperm"}else{"channelclientdelperm"},args)
},
Action::KickChannel{reason}|Action::KickServer{reason}=>("clientkick",vec![("clid",clid),("reasonid",if matches!(action,Action::KickChannel{..}){"4"}else{"5"}.into()),("reasonmsg",reason.clone())]),
Action::Ban{reason,duration}=>("banclient",vec![("clid",clid),("time",duration.to_string()),("banreason",reason.clone())]),
_=>return None,
};
Some(command(name,&args))
}
#[derive(Default)]
pub struct Permissions { pub catalog: Vec<Value>, values: HashMap<u32,i32> }
impl Permissions {
pub fn apply(&mut self,raw:&RawNotification){
match raw.name.as_str(){
"notifypermissionlist"=>{
self.catalog.clear();
for row in &raw.items { if let Some(name)=row.get("permname") {
let id=row.get("permid").and_then(|v|v.parse::<u32>().ok()).unwrap_or(self.catalog.len() as u32+1);
self.catalog.push(json!({"id":id,"name":name,"description":row.get("permdesc")}));
}}
},
"notifyclientneededpermissions"=>for row in &raw.items {
if let Some(id)=row.get("permid").and_then(|v|v.parse().ok()) {
if let Some(value)=row.get("permvalue").and_then(|v|v.parse().ok()){self.values.insert(id,value);}else{self.values.remove(&id);}
}
},
_=>{},
}
}
fn value(&self,name:&str)->Option<i32>{self.catalog.iter().find(|p|p["name"]==name).and_then(|p|p["id"].as_u64()).and_then(|id|self.values.get(&(id as u32)).copied())}
/// Own effective value of a named permission (`None` = unknown: not in the catalog or not granted).
pub fn named(&self,name:&str)->Option<i32>{self.value(name)}
/// Whether the permission catalog (`permissionlist`) has been received.
pub fn has_catalog(&self)->bool{!self.catalog.is_empty()}
fn power(&self,name:&str,needed:Option<i32>)->Value {cap(self.value(name).zip(needed).map(|(p,n)|p>=n),"effective_permission")}
pub fn context(&self,book:&tsclientlib::data::Connection,target:&Target,generation:u64)->Result<Value,ErrorObj>{
let client=book.clients.get(&ClientId(target.client_id)).ok_or_else(||ErrorObj::new(ErrorCode::NotFound,"client is no longer visible"))?;
validate_live_identity(target,client.id.0,client.uid.as_ref())?;
let own=book.own_client==client.id;
let hints=client.permission_hints.map(|h|h.bits());
let mut capabilities=serde_json::Map::new();
for (key,bit) in [("poke",32),("kick_channel",2),("kick_server",1),("ban",4),("set_client_permission",256),("set_channel_permission",256)] {
capabilities.insert(key.into(),target_hint(own,key,hints,bit));
}
for (key,perm) in [("commander","b_client_use_channel_commander"),("avatar","i_client_max_avatar_filesize")] {
capabilities.insert(key.into(),if own{cap(self.value(perm).map(|v|v!=0),"effective_permission")}else{json!({"allowed":false,"reason":"self_only","source":"target"})});
}
for key in ["connection_info","client_permissions","channel_permissions","server_group","channel_group"] {capabilities.insert(key.into(),cap(None,"server"));}
for (key,perm) in [("connection_info","b_client_info_view"),("client_permissions","b_virtualserver_client_permission_list"),("channel_permissions","b_virtualserver_channelclient_permission_list")] {
capabilities.insert(key.into(),cap(self.value(perm).map(|v|v!=0),"effective_permission"));
}
capabilities.insert("volume".into(),json!({"allowed":!own,"reason":if own{"other_only"}else{"local"},"source":"local"}));
let own_channel=book.clients.get(&book.own_client).map(|c|c.channel);
capabilities.insert("move_to_own_channel".into(),if own||own_channel==Some(client.channel){json!({"allowed":false,"reason":"same_channel","source":"target"})}else{cap(None,"server")});
capabilities.insert("delete_avatar".into(),if own{cap(Some(true),"self")}else{cap(self.value("b_client_avatar_delete_other").map(|v|v!=0),"effective_permission")});
let mut server_groups:Vec<Value>=book.server_groups.values().filter(|g|g.group_type==GroupType::Regular).map(|g|json!({"id":g.id.0,"name":g.name,"member":client.server_groups.contains(&g.id),"can_add":self.power("i_group_member_add_power",Some(g.needed_member_add_power)),"can_remove":self.power("i_group_member_remove_power",g.needed_member_remove_power)})).collect();
server_groups.sort_by_key(|g|g["id"].as_u64());
let mut channel_groups:Vec<Value>=book.channel_groups.values().filter(|g|g.group_type==GroupType::Regular).map(|g|json!({"id":g.id.0,"name":g.name,"member":client.channel_group==g.id,"can_add":self.power("i_group_member_add_power",Some(g.needed_member_add_power)),"can_remove":self.power("i_group_member_remove_power",g.needed_member_remove_power)})).collect();
channel_groups.sort_by_key(|g|g["id"].as_u64());
let remove=channel_groups.iter().find(|g|g["member"]==true).and_then(|g|g["can_remove"]["allowed"].as_bool());
for group in &mut channel_groups {
let add=group["can_add"]["allowed"].as_bool();
let allowed=if group["member"]==true {Some(true)} else if add==Some(false)||remove==Some(false){Some(false)}else{add.zip(remove).map(|(a,r)|a&&r)};
group["can_set"]=cap(allowed,"effective_permission");
}
Ok(json!({"generation":generation,"client_id":target.client_id,"uid":target.uid,"is_self":own,"channel_id":client.channel.0,"is_channel_commander":client.is_channel_commander,"capabilities":capabilities,"server_groups":server_groups,"channel_groups":channel_groups,"permissions":self.catalog}))
}
}
fn cap(allowed:Option<bool>,source:&str)->Value {json!({"allowed":allowed,"reason":match allowed{Some(true)=>"server_hint",Some(false)=>"permission_denied",None=>"server_decides"},"source":source})}
pub fn tapped(name:&[u8])->bool{matches!(name,b"notifypermissionlist"|b"notifyclientneededpermissions"|b"notifyconnectioninfo"|b"notifyclientpermlist"|b"notifychannelclientpermlist")}
fn validate_live_identity(target:&Target,client_id:u16,uid:Option<&tsclientlib::UidBuf>)->Result<(),ErrorObj>{
if target.client_id!=client_id || uid.is_none_or(|uid|uid.to_string()!=target.uid){return Err(bad("client identity changed; reopen the menu"));}
Ok(())
}
fn target_hint(own:bool,key:&str,hints:Option<u64>,bit:u64)->Value {
if own && matches!(key,"poke"|"kick_channel"|"kick_server"|"ban") {json!({"allowed":false,"reason":"other_only","source":"target"})}
else {cap(hints.map(|h|h&bit!=0),"server_hint")}
}
pub fn response_matches(row:&Row,response:&str,client_id:u16,dbid:u64,channel:Option<u64>)->bool {
let number=|key:&str|row.get(key).and_then(|v|v.parse::<u64>().ok());
match response {
"notifyconnectioninfo"=>number("clid")==Some(u64::from(client_id)),
"notifyclientpermlist"=>number("cldbid")==Some(dbid),
"notifychannelclientpermlist"=>number("cldbid")==Some(dbid)&&number("cid")==channel,
_=>false,
}
}
#[cfg(test)]
mod tests {
use super::*;
fn parse_action(value: Value) -> Result<ActionRequest, ErrorObj> {
let request = super::parse_action(value)?;
validate_action(&request)?;
Ok(request)
}
#[test] fn command_fixture_escapes_and_uses_real_protocol_fields(){
let action=Action::KickChannel{reason:"a b|c".into()};
let packet=action_command(&action,42,9).unwrap().into_packet();
let raw=crate::rawcmd::parse(packet.content()).unwrap();
assert_eq!(raw.name,"clientkick"); assert_eq!(raw.items[0]["reasonid"],"4"); assert_eq!(raw.items[0]["reasonmsg"],"a b|c");
let p=action_command(&Action::SetChannelPermission{channel_id:7,permission_id:99,value:None},42,9).unwrap().into_packet();
let r=crate::rawcmd::parse(p.content()).unwrap(); assert_eq!(r.name,"channelclientdelperm"); assert_eq!(r.items[0]["cldbid"],"9");
}
#[test] fn effective_permissions_are_server_data_not_group_names(){
let mut p=Permissions::default();
p.apply(&crate::rawcmd::parse(b"notifypermissionlist group_id_end=1|permname=i_group_member_add_power permdesc=power").unwrap());
assert_eq!(p.power("i_group_member_add_power",Some(50))["allowed"],Value::Null);
p.apply(&crate::rawcmd::parse(b"notifyclientneededpermissions permid=1 permvalue=25").unwrap());
assert_eq!(p.power("i_group_member_add_power",Some(50))["allowed"],false);
p.apply(&crate::rawcmd::parse(b"notifyclientneededpermissions permid=1 permvalue=75").unwrap());
assert_eq!(p.power("i_group_member_add_power",Some(50))["allowed"],true);
}
#[test] fn target_and_action_validation_rejects_injection_and_nonfinite_gain(){
let base=json!({"client_id":42,"uid":"fixture","generation":1,"action":"poke","message":"hello","unexpected":true});
assert!(parse_action(base).is_err());
assert!(parse_action(json!({"client_id":0,"uid":"x","generation":1,"action":"connection_info"})).is_err());
assert!(parse_action(json!({"client_id":42,"uid":"x","generation":1,"action":"volume","db":10.5,"muted":false})).is_err());
assert!(parse_action(json!({"client_id":42,"uid":"x","generation":1,"action":"volume","db":-3.25,"muted":false})).is_err());
assert!(parse_action(json!({"client_id":42,"uid":"x","generation":1,"action":"volume","value":1.0,"muted":false})).is_err());
}
#[test] fn read_notifications_cannot_cross_targets_or_channels(){
let row=crate::rawcmd::parse(b"notifychannelclientpermlist cldbid=8 cid=3 permid=42 permvalue=75").unwrap().items.remove(0);
assert!(response_matches(&row,"notifychannelclientpermlist",2,8,Some(3)));
assert!(!response_matches(&row,"notifychannelclientpermlist",2,9,Some(3)));
assert!(!response_matches(&row,"notifychannelclientpermlist",2,8,Some(4)));
assert!(!response_matches(&row,"notifyconnectioninfo",2,8,None));
}
#[test] fn all_mutation_fixtures_build_expected_wire_verbs(){
for (action,verb) in [
(Action::Poke{message:"hi".into()},"clientpoke"),
(Action::Commander{enabled:true},"clientupdate"),
(Action::ServerGroup{group_id:6,enabled:true},"servergroupaddclient"),
(Action::ServerGroup{group_id:6,enabled:false},"servergroupdelclient"),
(Action::ChannelGroup{group_id:7,channel_id:1},"setclientchannelgroup"),
(Action::SetClientPermission{permission_id:42,value:Some(75),skip:true},"clientaddperm"),
(Action::SetClientPermission{permission_id:42,value:None,skip:false},"clientdelperm"),
(Action::SetChannelPermission{channel_id:1,permission_id:42,value:Some(25)},"channelclientaddperm"),
(Action::KickServer{reason:"fixture".into()},"clientkick"),
(Action::Ban{reason:"fixture".into(),duration:60},"banclient"),
] {
let packet=action_command(&action,2,8).unwrap().into_packet();
let raw=crate::rawcmd::parse(packet.content()).unwrap();
assert_eq!(raw.name,verb);
assert!(!raw.items[0].contains_key("return_code"),"result tracking belongs to connection transport");
}
}
#[test] fn volume_request_retains_db_and_mute_atomically(){
let parsed=parse_action(json!({"client_id":42,"uid":"fixture","generation":1,"action":"volume","db":-12.5,"muted":true})).unwrap();
assert_eq!(parsed.action,Action::Volume{db:-12.5,muted:true});
assert!(parse_action(json!({"client_id":42,"uid":"fixture","generation":1,"action":"volume","db":-200,"muted":false})).is_ok());
assert!(parse_action(json!({"client_id":42,"uid":"fixture","generation":1,"action":"set_client_permission","permission_id":1,"skip":false})).is_err());
}
#[test] fn self_other_and_permission_denials_do_not_depend_on_role_labels(){
assert_eq!(target_hint(true,"kick_server",Some(u64::MAX),1)["allowed"],false);
assert_eq!(target_hint(false,"kick_server",Some(0),1)["allowed"],false);
assert_eq!(target_hint(false,"kick_server",Some(1),1)["allowed"],true);
assert_eq!(target_hint(false,"kick_server",None,1)["allowed"],Value::Null);
assert_eq!(target_hint(true,"set_client_permission",Some(256),256)["allowed"],true);
}
#[test] fn recycled_client_id_cannot_reuse_identity_or_local_gain(){
let first=tsclientlib::UidBuf(vec![1;20]); let second=tsclientlib::UidBuf(vec![2;20]);
let target=Target{client_id:42,uid:first.to_string()};
assert!(validate_live_identity(&target,42,Some(&first)).is_ok());
assert!(validate_live_identity(&target,42,Some(&second)).is_err());
assert!(validate_live_identity(&target,43,Some(&first)).is_err());
assert!(validate_live_identity(&target,42,None).is_err());
let mut persisted=HashMap::new(); persisted.insert(second.0.clone(),-6.0);
let mut volumes=LocalVolumes::default(); volumes.set(&first.0,-8.0,true);
assert_eq!(volumes.get(&first.0,&persisted),(-8.0,true)); assert_eq!(volumes.gain(&first.0,&persisted),0.0);
assert!((volumes.gain(&second.0,&persisted)-0.501_187).abs()<1e-5,"persisted modifier applies without a live entry");
volumes.set(&first.0,-200.0,false); assert_eq!(volumes.gain(&first.0,&persisted),0.0);
volumes.set(&first.0,0.0,false); assert_eq!(volumes.gain(&first.0,&persisted),1.0);
volumes.set(&second.0,10.0,false); assert!((volumes.gain(&second.0,&persisted)-crate::voice_dsp::MAX_USER_GAIN).abs()<1e-5,"live entry wins");
volumes.clear(); assert_eq!(volumes.get(&first.0,&persisted),(0.0,false)); assert_eq!(volumes.get(&second.0,&persisted),(-6.0,false));
}
}
+95
View File
@@ -0,0 +1,95 @@
//! Session integration for target-bound client menu actions.
use super::*;
impl Session {
pub(super) fn client_context(&mut self, id: &str, target: Target) -> Result<Option<Value>, ErrorObj> {
let c = self.connected_conn()?;
let book = c.con.get_state().map_err(|e|lib_error(ErrorCode::NotConnected,&e))?;
c.permissions.context(book,&target,c.generation)?;
let handle = c.send(menu::command("permissionlist",&[])).map_err(|e|lib_error(ErrorCode::ServerError,&e))?;
c.pending.insert(handle,Pending::MenuContext{req:id.into(),target});
Ok(None)
}
pub(super) async fn client_action(&mut self, id: &str, request: ActionRequest) -> Result<Option<Value>, ErrorObj> {
let c=self.connected_conn()?;
if request.generation!=c.generation{return Err(menu::bad("connection changed; reopen the menu"));}
let book=c.con.get_state().map_err(|e|lib_error(ErrorCode::NotConnected,&e))?;
let context=c.permissions.context(book,&request.target,c.generation)?;
let key=request.action.key();
if context["capabilities"][key]["allowed"]==false{return Err(ErrorObj::new(ErrorCode::ServerError,"server permission hint denies this action").with_detail(context["capabilities"][key].clone()));}
let client=&book.clients[&ClientId(request.target.client_id)];
let dbid=client.database_id.0;
match &request.action {
MenuAction::MoveToOwnChannel{password,expected_channel_id}=>{
let own_channel=book.clients.get(&book.own_client).ok_or_else(||menu::bad("own channel unavailable"))?.channel;
if own_channel.0!=*expected_channel_id{return Err(ErrorObj::new(ErrorCode::TargetChanged,"own channel changed; reopen the move action"));}
if own_channel==client.channel{return Err(menu::bad("client is already in your channel"));}
let pw=password.as_ref().filter(|p|!p.is_empty()).map(|p|tsproto_types::crypto::encode_password(p.as_bytes())).unwrap_or_default();
let command=menu::command("clientmove",&[("clid",client.id.0.to_string()),("cid",own_channel.0.to_string()),("cpw",pw)]);
let handle=c.send(command).map_err(|e|lib_error(ErrorCode::ServerError,&e))?;
c.pending.insert(handle,Pending::Simple{req:id.into()});return Ok(None);
},
MenuAction::DeleteAvatar{}=>{
// Official TeamSpeak.dll 6.0.0.5163: constructor VA 0x1814bddd0 emits
// clientavatardeleted with each raw UID under cluid (not clientedit).
let command=menu::command("clientavatardeleted",&[("cluid",request.target.uid.clone())]);
let handle=c.send(command).map_err(|e|lib_error(ErrorCode::ServerError,&e))?;
c.pending.insert(handle,Pending::Simple{req:id.into()});return Ok(None);
},
MenuAction::Volume{db,muted}=>{
let uid=client.uid.as_ref().ok_or_else(||menu::bad("client UID is unavailable"))?;
c.gains.set(&uid.0,*db,*muted);
return Ok(Some(json!({"volume_db":db,"volume_muted":muted})));
},
MenuAction::Avatar{data}=>{
if c.avatar.is_some(){return Err(menu::bad("an avatar upload is already pending"));}
let data=menu::avatar_bytes(data)?;
let hash=format!("{:x}",Md5::digest(&data));
let ftid=c.transfer_id();
let command=menu::command("ftinitupload",&[("clientftfid",ftid.to_string()),("name","/avatar".into()),("cid","0".into()),("cpw",String::new()),("size",data.len().to_string()),("overwrite","1".into()),("resume","0".into()),("proto","1".into())]);
let handle=c.send(command).map_err(|e|lib_error(ErrorCode::ServerError,&e))?;
c.pending.insert(handle,Pending::AvatarInit{ftid});
c.avatar=Some(AvatarUpload{req:id.into(),handle:ftid,data,hash,started:Instant::now(),task:None});
return Ok(None);
},
MenuAction::ServerGroup{group_id,enabled}=>{
let group=context["server_groups"].as_array().unwrap().iter().find(|g|g["id"].as_u64()==Some(*group_id)).ok_or_else(||menu::bad("server group is not available"))?;
if group[if *enabled{"can_add"}else{"can_remove"}]["allowed"]==false{return Err(menu::bad("insufficient group membership power"));}
},
MenuAction::ChannelGroup{group_id,channel_id}=>{
if *channel_id!=client.channel.0{return Err(menu::bad("target channel changed; reopen the menu"));}
let group=context["channel_groups"].as_array().unwrap().iter().find(|g|g["id"].as_u64()==Some(*group_id)).ok_or_else(||menu::bad("channel group is not available"))?;
if group["can_set"]["allowed"]==false{return Err(menu::bad("insufficient channel group membership power"));}
},
MenuAction::ChannelPermissions{channel_id}|MenuAction::SetChannelPermission{channel_id,..}=>{
if *channel_id!=client.channel.0{return Err(menu::bad("target channel changed; reopen the menu"));}
},
_=>{},
}
if let MenuAction::SetClientPermission{permission_id,..}|MenuAction::SetChannelPermission{permission_id,..}=&request.action {
if !c.permissions.catalog.iter().any(|p|p["id"].as_u64()==Some(u64::from(*permission_id))){return Err(menu::bad("permission is not in the server catalog"));}
}
let response=request.action.response();
let channel=match request.action {MenuAction::ChannelPermissions{channel_id}=>Some(channel_id),_=>None};
if response.is_some() && c.pending.values().any(|p|matches!(p,Pending::MenuRead{..})){return Err(menu::bad("another client information request is pending"));}
let command=menu::action_command(&request.action,request.target.client_id,dbid).ok_or_else(||ErrorObj::new(ErrorCode::Internal,"local action reached server dispatch"))?;
let handle=c.send(command).map_err(|e|lib_error(ErrorCode::ServerError,&e))?;
c.pending.insert(handle,match response {
Some(response)=>Pending::MenuRead{req:id.into(),target:request.target,dbid,channel,response,rows:Vec::new()},
None=>Pending::Simple{req:id.into()},
});
Ok(None)
}
pub(super) async fn avatar_finished(&mut self,generation:u64,result:Result<(),String>){
let Some(c)=self.conn.as_mut().filter(|c|c.generation==generation) else{return};
let Some(job)=c.avatar.take() else{return};
if let Err(error)=result{self.out.err(&job.req,ErrorObj::new(ErrorCode::Io,error)).await;return;}
let command=menu::command("clientupdate",&[("client_flag_avatar",job.hash.clone())]);
match c.send(command){
Ok(handle)=>{c.pending.insert(handle,Pending::Simple{req:job.req.clone()});},
Err(e)=>self.out.err(&job.req,lib_error(ErrorCode::ServerError,&e)).await,
}
}
}
+152
View File
@@ -0,0 +1,152 @@
//! Transport-neutral control output and bounded native playback PCM.
use std::{collections::VecDeque, sync::{Arc, Mutex, atomic::{AtomicU64, Ordering}}};
use serde::Serialize;
use serde_json::{json, Value};
use tokio::sync::{mpsc, Notify};
use crate::protocol::{ErrorObj, Frame};
const CONTROL_CAPACITY: usize = 1024;
const PCM_CAPACITY: usize = 10;
pub struct PlaybackFrame {
pub pcm: Frame,
pub speakers: Vec<u16>,
pub generation: u64,
pub emitted_at: std::time::Instant,
recycled: Arc<Mutex<Vec<Vec<u16>>>>,
}
impl Drop for PlaybackFrame {
fn drop(&mut self) {
let mut speakers = std::mem::take(&mut self.speakers);
speakers.clear();
self.recycled.lock().unwrap_or_else(std::sync::PoisonError::into_inner).push(speakers);
}
}
struct PlaybackInner {
frames: VecDeque<PlaybackFrame>,
closed: bool,
}
struct PlaybackShared {
inner: Mutex<PlaybackInner>,
ready: Notify,
recycled: Arc<Mutex<Vec<Vec<u16>>>>,
}
pub struct PlaybackReceiver { shared: Arc<PlaybackShared> }
impl PlaybackReceiver {
pub async fn recv(&mut self) -> Option<PlaybackFrame> {
loop {
let notified = self.shared.ready.notified();
{
let mut inner = self.shared.inner.lock().expect("playback queue poisoned");
if let Some(frame) = inner.frames.pop_front() { return Some(frame); }
if inner.closed { return None; }
}
notified.await;
}
}
}
impl Drop for PlaybackReceiver {
fn drop(&mut self) {
let mut inner = self.shared.inner.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
inner.closed = true;
inner.frames.clear();
}
}
struct OutputInner {
control: mpsc::Sender<Value>,
playback: Arc<PlaybackShared>,
generation: AtomicU64,
}
impl Drop for OutputInner {
fn drop(&mut self) {
self.playback.inner.lock().expect("playback queue poisoned").closed = true;
self.playback.ready.notify_one();
}
}
#[derive(Clone)]
pub struct Out { inner: Arc<OutputInner> }
impl Out {
pub fn new() -> (Self, mpsc::Receiver<Value>, PlaybackReceiver) {
let (control, receiver) = mpsc::channel(CONTROL_CAPACITY);
let playback = Arc::new(PlaybackShared {
inner: Mutex::new(PlaybackInner { frames: VecDeque::with_capacity(PCM_CAPACITY), closed: false }),
ready: Notify::new(),
recycled: Arc::new(Mutex::new((0..PCM_CAPACITY + 2).map(|_| Vec::with_capacity(16)).collect())),
});
(Self { inner: Arc::new(OutputInner { control, playback: playback.clone(), generation: AtomicU64::new(0) }) }, receiver, PlaybackReceiver { shared: playback })
}
pub fn set_generation(&self, generation: u64) { self.inner.generation.store(generation, Ordering::Release); }
pub async fn control(&self, mut value: Value) {
if let Some(object) = value.as_object_mut().filter(|o| o.contains_key("event")) {
object.insert("generation".into(), Value::from(self.inner.generation.load(Ordering::Acquire)));
}
let _ = self.inner.control.send(value).await;
}
pub async fn json<T: Serialize>(&self, value: &T) {
match serde_json::to_value(value) {
Ok(value) => self.control(value).await,
Err(error) => tracing::error!(%error, "could not construct core output"),
}
}
/// Drops oldest playback under congestion; never waits for an audio device.
pub fn playback(&self, pcm: &Frame, speakers: &[u16]) -> bool {
let mut inner = self.inner.playback.inner.lock().expect("playback queue poisoned");
if inner.closed { return false; }
let retained = inner.frames.len() < PCM_CAPACITY;
if !retained { inner.frames.pop_front(); }
let Some(mut speaker_buffer) = self.inner.playback.recycled.lock().expect("playback pool poisoned").pop() else { return false; };
speaker_buffer.extend_from_slice(speakers);
inner.frames.push_back(PlaybackFrame { pcm: *pcm, speakers: speaker_buffer, generation: self.inner.generation.load(Ordering::Acquire), emitted_at: std::time::Instant::now(), recycled: self.inner.playback.recycled.clone() });
drop(inner);
self.inner.playback.ready.notify_one();
retained
}
pub async fn ok(&self, id: &str, result: Value) {
self.control(json!({"id":id,"ok":true,"result":result})).await;
}
pub async fn err(&self, id: &str, error: ErrorObj) {
self.control(json!({"id":id,"ok":false,"error":error})).await;
}
pub async fn error_event(&self, error: ErrorObj) {
self.control(json!({"event":"error","error":error})).await;
}
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test(flavor = "current_thread")]
async fn playback_discards_oldest_without_relabeling_reconnected_frames() {
let (out, _control, mut playback) = Out::new();
out.set_generation(7);
for value in 0..12 { out.playback(&[value; crate::protocol::FRAME_SAMPLES], &[4, 9]); }
out.set_generation(8);
for expected in 2..12 {
let frame = playback.recv().await.unwrap();
assert_eq!(frame.pcm[0], expected);
assert_eq!(frame.generation, 7);
assert_eq!(frame.speakers, [4, 9]);
}
assert!(out.playback(&[12; crate::protocol::FRAME_SAMPLES], &[2]));
let frame = playback.recv().await.unwrap();
assert_eq!(frame.generation, 8);
assert_eq!(frame.speakers, [2]);
drop(frame);
drop(out);
assert!(playback.recv().await.is_none());
}
#[test]
fn missing_playback_consumer_refuses_new_audio() {
let (out, _control, playback) = Out::new();
drop(playback);
assert!(!out.playback(&[1; crate::protocol::FRAME_SAMPLES], &[2]));
}
}
+1225 -126
View File
File diff suppressed because it is too large. Load diff
+376 -48
View File
@@ -1,4 +1,9 @@
//! Bridge protocol v1 (see `docs/bridge.md`): request parsing and error objects.
//! Bridge protocol v1 (see `docs/bridge.md`): transport shape parsing and shared typed validation.
//!
//! Both CLI parsing and embedded requests enter through `validate_command` before
//! becoming `Input::Request`. Family parsers decode only transport shapes; their
//! semantic validators are dispatched here. Live generation/identity/permission
//! checks remain in the session because argument validation cannot replace them.
use std::borrow::Cow;
@@ -8,6 +13,9 @@ use serde::{Deserialize, Serialize};
use serde_json::value::RawValue;
use serde_json::Value;
use crate::vad::GateMode;
use crate::voice_dsp::LocalVolumesUpdate;
pub const PROTOCOL_VERSION: u32 = 1;
/// Maximum accepted stdin line (bytes, without the newline).
pub const MAX_LINE_BYTES: usize = 256 * 1024;
@@ -24,7 +32,7 @@ const MAX_FIELD_CHARS: usize = 1024;
pub type Frame = [i16; FRAME_SAMPLES];
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ErrorCode {
BadRequest,
@@ -46,15 +54,21 @@ pub enum ErrorCode {
AudioCodecUnsupported,
RenameNotPersisted,
NotFound,
TargetChanged,
MediaTooLarge,
MediaUnsupported,
ExternalMedia,
Io,
Internal,
FileExists,
TransferCancelled,
RecordingFailed,
IdentityInUse,
IdentityBusy,
}
/// TeamSpeak server error attached to an [`ErrorObj`].
#[derive(Clone, Debug, PartialEq, Serialize)]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct TsErrorInfo {
/// Numeric TeamSpeak error id (e.g. 513 = nickname in use).
pub id: u32,
@@ -64,7 +78,7 @@ pub struct TsErrorInfo {
pub missing_permission: Option<u32>,
}
#[derive(Clone, Debug, PartialEq, Serialize)]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ErrorObj {
pub code: ErrorCode,
pub message: String,
@@ -106,17 +120,34 @@ pub enum Command {
Connect(ConnectArgs),
Disconnect { message: Option<String> },
JoinChannel { channel_id: u64, password: Option<String> },
SendText { target: TextTarget, client_id: Option<u16>, message: String },
SendText { target: TextTarget, client_id: Option<u16>, expected_client_uid: Option<String>, message: String },
SetAudio { input_muted: Option<bool>, output_muted: Option<bool> },
/// `None` = direct transmission (push-to-talk / open microphone decided by the caller).
SetTransmit { vad: Option<GateMode> },
/// Persisted per-user volume modifiers (replace or upsert).
SetLocalVolumes(LocalVolumesUpdate),
/// Playback DSP of the current output device profile.
SetPlaybackDsp { agc: bool },
StreamList { client_id: Option<u16> },
StreamJoin { stream_id: String, client_id: u16, message: Option<String> },
/// `json` is already compact-serialized and size checked.
/// JSON text; `validate_command` requires an object, compacts it and checks its byte size.
StreamSignal { stream_id: String, client_id: u16, json: String },
StreamLeave { stream_id: String, client_id: u16 },
StreamSetup(StreamPublishArgs),
StreamUpdate(StreamPublishArgs),
StreamStop { stream_id: String },
StreamRespond { stream_id: String, client_id: u16, decision: bool, offer: String, message: String },
StreamRemove { stream_id: String, client_id: u16 },
FetchIcon { icon_id: u32 },
FetchAvatar { client_id: u16 },
FetchBanner { channel_id: u64 },
FetchServerBanner,
ClientContext(crate::menu::Target),
ClientAction(crate::menu::ActionRequest),
Admin(crate::admin::AdminCommand),
Files(crate::file_transfer::Request),
Recording(crate::recording::RecCommand),
Whisper(crate::whisper::WhisperCommand),
Shutdown,
}
@@ -131,19 +162,43 @@ impl Command {
Command::JoinChannel { .. } => "join_channel",
Command::SendText { .. } => "send_text",
Command::SetAudio { .. } => "set_audio",
Command::SetTransmit { .. } => "set_transmit",
Command::SetLocalVolumes(_) => "set_local_volumes",
Command::SetPlaybackDsp { .. } => "set_playback_dsp",
Command::StreamList { .. } => "stream_list",
Command::StreamJoin { .. } => "stream_join",
Command::StreamSignal { .. } => "stream_signal",
Command::StreamLeave { .. } => "stream_leave",
Command::StreamSetup(_) => "stream_setup",
Command::StreamUpdate(_) => "stream_update",
Command::StreamStop { .. } => "stream_stop",
Command::StreamRespond { .. } => "stream_respond",
Command::StreamRemove { .. } => "stream_remove",
Command::FetchIcon { .. } => "fetch_icon",
Command::FetchAvatar { .. } => "fetch_avatar",
Command::FetchBanner { .. } => "fetch_banner",
Command::FetchServerBanner => "fetch_server_banner",
Command::ClientContext(_) => "client_context",
Command::ClientAction(_) => "client_action",
Command::Admin(c) => c.name(),
Command::Files(r) => r.name(),
Command::Recording(c) => c.name(),
Command::Whisper(c) => c.name(),
Command::Shutdown => "shutdown",
}
}
}
/// A command whose transport-independent arguments have been checked and normalized.
/// Only the core can unwrap it; callers must use [`validate_command`].
#[derive(Clone, Debug, PartialEq)]
pub struct ValidatedCommand(Command);
impl ValidatedCommand {
pub fn name(&self) -> &'static str { self.0.name() }
pub(crate) fn into_inner(self) -> Command { self.0 }
}
#[derive(Clone, Debug, PartialEq, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ConnectArgs {
@@ -154,18 +209,32 @@ pub struct ConnectArgs {
pub channel: Option<String>,
#[serde(default)]
pub channel_password: Option<String>,
#[serde(default)]
pub identity_id: Option<String>,
/// Nickname for this connection only (bookmark override); absent: the identity's
/// nickname/name. Validated by `Store::open_for_connect`; the identity is never changed.
#[serde(default)]
pub nickname: Option<String>,
}
/// One parsed stdin line.
#[derive(Debug)]
pub enum Input {
Request { id: String, cmd: Command },
AudioFrame(Box<Frame>),
Request { id: String, cmd: ValidatedCommand },
AudioFrame(TaggedFrame),
AudioEnd,
/// The line could not be turned into a command. `id` is set if it could be recovered.
Invalid { id: Option<String>, error: ErrorObj },
}
/// One captured frame and the route it was captured for.
#[derive(Debug)]
pub struct TaggedFrame {
pub pcm: Box<Frame>,
/// Whisper epoch (`audio_frame.whisper`) while a whisper key was held; `None` = ordinary voice.
pub whisper: Option<u32>,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Envelope<'a> {
@@ -208,6 +277,8 @@ struct SendTextArgs {
target: TextTarget,
#[serde(default)]
client_id: Option<u16>,
#[serde(default)]
expected_client_uid: Option<String>,
message: String,
}
@@ -270,11 +341,42 @@ struct StreamLeaveArgs {
client_id: u16,
}
#[derive(Clone, Debug, PartialEq, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct StreamPublishArgs {
#[serde(default)]
pub stream_id: Option<String>,
pub name: String,
#[serde(rename = "type")]
pub stream_type: u8,
pub accessibility: u8,
pub mode: u8,
pub bitrate: u32,
pub viewer_limit: u16,
pub audio: bool,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct StreamStopArgs { stream_id: String }
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct StreamRespondArgs {
stream_id: String,
client_id: u16,
decision: bool,
offer: String,
message: String,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct AudioFrameArgs<'a> {
#[serde(borrow)]
pcm: Cow<'a, str>,
#[serde(default)]
whisper: Option<u32>,
}
fn args<'a, T: Deserialize<'a>>(raw: Option<&'a RawValue>) -> Result<T, ErrorObj> {
@@ -349,7 +451,12 @@ pub fn parse_line(line: &str) -> Input {
// High-rate audio commands carry no id and get no response.
match env.cmd.as_ref() {
"audio_frame" => {
return match args::<AudioFrameArgs>(env.args).and_then(|a| decode_frame(&a.pcm)) {
return match args::<AudioFrameArgs>(env.args).and_then(|a| {
if a.whisper == Some(0) {
return Err(bad("audio_frame: whisper epoch must be at least 1"));
}
Ok(TaggedFrame { pcm: decode_frame(&a.pcm)?, whisper: a.whisper })
}) {
Ok(frame) => Input::AudioFrame(frame),
Err(error) => Input::Invalid { id: None, error },
};
@@ -370,7 +477,7 @@ pub fn parse_line(line: &str) -> Input {
}
None => return Input::Invalid { id: None, error: bad("missing id") },
};
match parse_command(&env.cmd, env.args) {
match parse_command(&env.cmd, env.args).and_then(validate_command) {
Ok(cmd) => Input::Request { id, cmd },
Err(error) => Input::Invalid { id: Some(id), error },
}
@@ -391,71 +498,58 @@ fn parse_command(cmd: &str, raw: Option<&RawValue>) -> Result<Command, ErrorObj>
"rename" => Command::Rename { nickname: args_owned::<NicknameArgs>(raw)?.nickname },
"connect" => {
let a: ConnectArgs = args_owned(raw)?;
check_text("address", &a.address, 255, false)?;
check_opt("server_password", &a.server_password)?;
check_opt("channel", &a.channel)?;
check_opt("channel_password", &a.channel_password)?;
Command::Connect(a)
}
"disconnect" => {
let a: DisconnectArgs = args_owned(raw)?;
check_opt("message", &a.message)?;
Command::Disconnect { message: a.message }
}
"join_channel" => {
let a: JoinChannelArgs = args_owned(raw)?;
check_opt("password", &a.password)?;
Command::JoinChannel { channel_id: a.channel_id, password: a.password }
}
"send_text" => {
let a: SendTextArgs = args_owned(raw)?;
if a.message.is_empty() || a.message.len() > MAX_TEXT_BYTES {
return Err(bad(format!("message must be 1-{MAX_TEXT_BYTES} bytes")));
}
match (a.target, a.client_id) {
(TextTarget::Client, None) => return Err(bad("client_id is required for target client")),
(TextTarget::Channel | TextTarget::Server, Some(_)) => {
return Err(bad("client_id is only allowed for target client"));
}
_ => {}
}
Command::SendText { target: a.target, client_id: a.client_id, message: a.message }
Command::SendText { target: a.target, client_id: a.client_id, expected_client_uid: a.expected_client_uid, message: a.message }
}
"set_audio" => {
let a: SetAudioArgs = args_owned(raw)?;
Command::SetAudio { input_muted: a.input_muted, output_muted: a.output_muted }
}
"set_transmit" => Command::SetTransmit { vad: crate::voice_dsp::parse_transmit(raw)? },
"set_local_volumes" => Command::SetLocalVolumes(crate::voice_dsp::parse_local_volumes(raw)?),
"set_playback_dsp" => Command::SetPlaybackDsp { agc: crate::voice_dsp::parse_playback_dsp(raw)? },
"stream_list" => Command::StreamList { client_id: args_owned::<StreamListArgs>(raw)?.client_id },
"stream_join" => {
let a: StreamJoinArgs = args_owned(raw)?;
check_stream_id(&a.stream_id)?;
check_opt("message", &a.message)?;
Command::StreamJoin { stream_id: a.stream_id, client_id: a.client_id, message: a.message }
}
"stream_signal" => {
let a: StreamSignalArgs = args(raw)?;
check_stream_id(&a.stream_id)?;
let value: Value = serde_json::from_str(a.json.get())
.map_err(|e| bad(format!("json is not valid JSON: {e}")))?;
if !value.is_object() {
return Err(bad("json must be an object"));
}
let json = serde_json::to_string(&value).map_err(|e| bad(format!("json: {e}")))?;
if json.len() > MAX_SIGNAL_JSON_BYTES {
return Err(bad(format!("json larger than {MAX_SIGNAL_JSON_BYTES} bytes")));
}
Command::StreamSignal { stream_id: a.stream_id, client_id: a.client_id, json }
Command::StreamSignal { stream_id: a.stream_id, client_id: a.client_id, json: a.json.get().to_owned() }
}
"stream_leave" => {
let a: StreamLeaveArgs = args_owned(raw)?;
check_stream_id(&a.stream_id)?;
Command::StreamLeave { stream_id: a.stream_id, client_id: a.client_id }
}
"stream_setup" | "stream_update" => {
let a: StreamPublishArgs = args_owned(raw)?;
if cmd == "stream_setup" { Command::StreamSetup(a) } else { Command::StreamUpdate(a) }
}
"stream_stop" => {
let a: StreamStopArgs = args_owned(raw)?;
Command::StreamStop { stream_id: a.stream_id }
}
"stream_respond" => {
let a: StreamRespondArgs = args_owned(raw)?;
Command::StreamRespond { stream_id: a.stream_id, client_id: a.client_id, decision: a.decision, offer: a.offer, message: a.message }
}
"stream_remove" => {
let a: StreamLeaveArgs = args_owned(raw)?;
Command::StreamRemove { stream_id: a.stream_id, client_id: a.client_id }
}
"fetch_icon" => {
let a: FetchIconArgs = args_owned(raw)?;
if a.icon_id == 0 {
return Err(bad("icon_id 0 means no icon"));
}
Command::FetchIcon { icon_id: a.icon_id }
}
"fetch_avatar" => Command::FetchAvatar { client_id: args_owned::<FetchAvatarArgs>(raw)?.client_id },
@@ -464,6 +558,15 @@ fn parse_command(cmd: &str, raw: Option<&RawValue>) -> Result<Command, ErrorObj>
args::<Empty>(raw)?;
Command::FetchServerBanner
}
"client_context" => {
let target = args_owned(raw)?;
Command::ClientContext(target)
},
"client_action" => Command::ClientAction(crate::menu::parse_action(args_owned(raw)?)?),
n if crate::admin::is_admin(n) => Command::Admin(crate::admin::parse(n, raw)?),
n if n.starts_with("file_") => Command::Files(crate::file_transfer::parse(n, raw)?),
n if n.starts_with("recording_") => Command::Recording(crate::recording::parse(n, raw)?),
n @ ("whisper_start" | "whisper_stop" | "set_whisper_receive") => Command::Whisper(crate::whisper::parse(n, raw)?),
"shutdown" => {
args::<Empty>(raw)?;
Command::Shutdown
@@ -474,6 +577,81 @@ fn parse_command(cmd: &str, raw: Option<&RawValue>) -> Result<Command, ErrorObj>
})
}
/// Validate and normalize typed requests, without serializing commands to JSON.
/// Signaling JSON is itself a protocol payload and is compacted for both transports.
pub fn validate_command(mut command: Command) -> Result<ValidatedCommand, ErrorObj> {
let update = matches!(&command, Command::StreamUpdate(_));
match &mut command {
Command::Connect(a) => {
check_text("address", &a.address, 255, false)?;
check_opt("server_password", &a.server_password)?;
check_opt("channel", &a.channel)?;
check_opt("channel_password", &a.channel_password)?;
check_opt("identity_id", &a.identity_id)?;
}
Command::Disconnect { message } => check_opt("message", message)?,
Command::JoinChannel { password, .. } => check_opt("password", password)?,
Command::SendText { target, client_id, expected_client_uid, message } => {
if message.is_empty() || message.len() > MAX_TEXT_BYTES { return Err(bad(format!("message must be 1-{MAX_TEXT_BYTES} bytes"))); }
match (*target, *client_id) {
(TextTarget::Client, None) => return Err(bad("client_id is required for target client")),
(TextTarget::Channel | TextTarget::Server, Some(_)) => return Err(bad("client_id is only allowed for target client")),
_ => {}
}
if *target == TextTarget::Client {
if *client_id == Some(0) { return Err(bad("client_id must be positive")); }
let uid = expected_client_uid.as_deref().ok_or_else(|| bad("expected_client_uid is required for target client"))?;
check_text("expected_client_uid", uid, 128, false)?;
} else if expected_client_uid.is_some() { return Err(bad("expected_client_uid is only allowed for target client")); }
}
Command::SetTransmit { vad } => crate::voice_dsp::validate_transmit(*vad)?,
Command::SetLocalVolumes(a) => crate::voice_dsp::validate_local_volumes(a)?,
Command::StreamJoin { stream_id, message, .. } => { check_stream_id(stream_id)?; check_opt("message", message)?; }
Command::StreamSignal { stream_id, json, .. } => {
check_stream_id(stream_id)?;
let value: Value = serde_json::from_str(json).map_err(|e| bad(format!("json is not valid JSON: {e}")))?;
if !value.is_object() { return Err(bad("json must be an object")); }
let compact = serde_json::to_string(&value).map_err(|e| bad(format!("json: {e}")))?;
if compact.len() > MAX_SIGNAL_JSON_BYTES { return Err(bad(format!("json larger than {MAX_SIGNAL_JSON_BYTES} bytes"))); }
*json = compact;
}
Command::StreamLeave { stream_id, .. } | Command::StreamStop { stream_id } => check_stream_id(stream_id)?,
Command::StreamSetup(a) | Command::StreamUpdate(a) => {
if update != a.stream_id.is_some() { return Err(bad("stream_id is required only for stream_update")); }
if let Some(id) = &a.stream_id { check_stream_id(id)?; }
check_text("name", &a.name, 200, false)?;
if a.name.chars().any(char::is_control) || !(1..=3).contains(&a.stream_type)
|| !(1..=3).contains(&a.accessibility) || a.mode != 1 || !(100..=100000).contains(&a.bitrate) {
return Err(bad("invalid stream metadata (only P2P is supported)"));
}
}
Command::StreamRespond { stream_id, client_id, decision, offer, message } => {
check_stream_id(stream_id)?;
check_text("message", message, 200, true)?;
if *client_id == 0 || *decision == offer.is_empty() || offer.len() > 60000
|| offer.chars().any(|c| c.is_control() && !matches!(c, '\r' | '\n' | '\t')) || message.chars().any(char::is_control) {
return Err(bad("invalid stream join response"));
}
}
Command::StreamRemove { stream_id, client_id } => {
check_stream_id(stream_id)?;
if *client_id == 0 { return Err(bad("client_id must be nonzero")); }
}
Command::FetchIcon { icon_id: 0 } => return Err(bad("icon_id 0 means no icon")),
Command::ClientContext(a) => crate::menu::validate_target(a)?,
Command::ClientAction(a) => crate::menu::validate_action(a)?,
Command::Admin(a) => crate::admin::validate(a)?,
Command::Files(a) => crate::file_transfer::validate(a)?,
Command::Recording(a) => crate::recording::validate(a)?,
Command::Whisper(a) => crate::whisper::validate(a)?,
Command::ProfileGet | Command::ProfileCreate { .. } | Command::Rename { .. }
| Command::SetAudio { .. } | Command::SetPlaybackDsp { .. } | Command::StreamList { .. }
| Command::FetchIcon { .. } | Command::FetchAvatar { .. } | Command::FetchBanner { .. }
| Command::FetchServerBanner | Command::Shutdown => {}
}
Ok(ValidatedCommand(command))
}
#[cfg(test)]
mod tests {
use super::*;
@@ -491,13 +669,29 @@ mod tests {
let line = format!(r#"{{"cmd":"audio_frame","args":{{"pcm":"{}"}}}}"#, frame_b64(|i| i as i16 - 480));
match parse_line(&line) {
Input::AudioFrame(f) => {
assert_eq!(f[0], -480);
assert_eq!(f[959], 479);
assert_eq!(f.pcm[0], -480);
assert_eq!(f.pcm[959], 479);
assert_eq!(f.whisper, None);
}
other => panic!("{other:?}"),
}
}
#[test]
fn audio_frame_carries_its_whisper_epoch() {
let pcm = frame_b64(|_| 0);
match parse_line(&format!(r#"{{"cmd":"audio_frame","args":{{"pcm":"{pcm}","whisper":7}}}}"#)) {
Input::AudioFrame(f) => assert_eq!(f.whisper, Some(7)),
other => panic!("{other:?}"),
}
for bad in [r#""whisper":0"#, r#""whisper":-1"#, r#""whisper":"7""#, r#""route":1"#] {
match parse_line(&format!(r#"{{"cmd":"audio_frame","args":{{"pcm":"{pcm}",{bad}}}}}"#)) {
Input::Invalid { id: None, .. } => {}
other => panic!("{bad}: {other:?}"),
}
}
}
#[test]
fn audio_frame_wrong_size_is_rejected() {
let short = BASE64_STANDARD.encode([0u8; 1918]);
@@ -511,11 +705,27 @@ mod tests {
}
}
#[test]
fn set_transmit_modes_and_sensitivities() {
let parse = |args: &str| parse_line(&format!(r#"{{"id":"t","cmd":"set_transmit","args":{args}}}"#));
assert!(matches!(parse(r#"{"mode":"direct"}"#), Input::Request { cmd: ValidatedCommand(Command::SetTransmit { vad: None }), .. }));
use crate::vad::Sensitivity;
assert!(matches!(parse(r#"{"mode":"vad"}"#), Input::Request { cmd: ValidatedCommand(Command::SetTransmit { vad: Some(GateMode::Automatic(Sensitivity::Normal)) }), .. }));
assert!(matches!(parse(r#"{"mode":"vad","sensitivity":"high"}"#), Input::Request { cmd: ValidatedCommand(Command::SetTransmit { vad: Some(GateMode::Automatic(Sensitivity::High)) }), .. }));
assert!(matches!(parse(r#"{"mode":"vad","sensitivity":"low"}"#), Input::Request { cmd: ValidatedCommand(Command::SetTransmit { vad: Some(GateMode::Automatic(Sensitivity::Low)) }), .. }));
for bad in [r#"{"mode":"open"}"#, r#"{"mode":"direct","sensitivity":"low"}"#, r#"{"mode":"vad","sensitivity":"max"}"#, r#"{"mode":"vad","threshold":0.1}"#, r#"{}"#] {
match parse(bad) {
Input::Invalid { error, .. } => assert_eq!(error.code, ErrorCode::BadRequest, "{bad}"),
other => panic!("{bad}: {other:?}"),
}
}
}
#[test]
fn requests_need_valid_id_and_known_args() {
assert!(matches!(
parse_line(r#"{"id":"a","cmd":"profile_get"}"#),
Input::Request { cmd: Command::ProfileGet, .. }
Input::Request { cmd: ValidatedCommand(Command::ProfileGet), .. }
));
match parse_line(r#"{"cmd":"profile_get"}"#) {
Input::Invalid { id: None, error } => assert_eq!(error.code, ErrorCode::BadRequest),
@@ -538,11 +748,43 @@ mod tests {
}
}
#[test]
fn connect_rejects_non_string_nickname_overrides() {
let parse = |args: Value| parse_line(&serde_json::json!({"id":"c","cmd":"connect","args":args}).to_string());
for bad in [serde_json::json!(5), serde_json::json!(["Guest"]), serde_json::json!({"name":"Guest"})] {
match parse(serde_json::json!({"address":"ts.example","nickname":bad})) {
Input::Invalid { id: Some(_), error } => assert_eq!(error.code, ErrorCode::BadRequest, "{bad}"),
other => panic!("{bad}: {other:?}"),
}
}
}
#[test]
fn publisher_metadata_and_responses_are_strict() {
let metadata = serde_json::json!({"name":"QA | stream", "type":3,"accessibility":3,"mode":1,"bitrate":4500,"viewer_limit":0,"audio":false});
let parse = |cmd: &str, args: Value| parse_line(&serde_json::json!({"id":"p","cmd":cmd,"args":args}).to_string());
assert!(matches!(parse("stream_setup", metadata.clone()), Input::Request { cmd: ValidatedCommand(Command::StreamSetup(_)), .. }));
assert!(matches!(parse("stream_update", metadata.clone()), Input::Invalid { .. }));
let mut updated = metadata.clone(); updated["stream_id"] = serde_json::json!("s1");
assert!(matches!(parse("stream_update", updated.clone()), Input::Request { cmd: ValidatedCommand(Command::StreamUpdate(_)), .. }));
assert!(matches!(parse("stream_setup", updated), Input::Invalid { .. }));
for (key, value) in [("type", 4), ("accessibility", 0), ("mode", 2), ("bitrate", 99), ("viewer_limit", -1)] {
let mut invalid = metadata.clone(); invalid[key] = serde_json::json!(value);
assert!(matches!(parse("stream_setup", invalid), Input::Invalid { .. }), "{key}");
}
let response = serde_json::json!({"stream_id":"s1","client_id":5,"decision":true,"offer":"v=0\r\n","message":""});
assert!(matches!(parse("stream_respond", response.clone()), Input::Request { cmd: ValidatedCommand(Command::StreamRespond { decision:true, .. }), .. }));
let mut invalid = response; invalid["offer"] = serde_json::json!("");
assert!(matches!(parse("stream_respond", invalid), Input::Invalid { .. }));
assert!(matches!(parse("stream_remove", serde_json::json!({"stream_id":"s1","client_id":0})), Input::Invalid { .. }));
assert!(matches!(parse("stream_remove", serde_json::json!({"stream_id":"s1","client_id":5,"reason":5})), Input::Invalid { .. }));
}
#[test]
fn stream_signal_json_is_compacted_object() {
let line = r#"{"id":"s","cmd":"stream_signal","args":{"stream_id":"7","client_id":5,"json":{ "cmd" : "answer", "args": {"answer":"v=0\r\no=- 1 2 IN IP4 0.0.0.0"} }}}"#;
match parse_line(line) {
Input::Request { cmd: Command::StreamSignal { json, client_id, .. }, .. } => {
Input::Request { cmd: ValidatedCommand(Command::StreamSignal { json, client_id, .. }), .. } => {
assert_eq!(client_id, 5);
assert_eq!(json, r#"{"cmd":"answer","args":{"answer":"v=0\r\no=- 1 2 IN IP4 0.0.0.0"}}"#);
}
@@ -551,4 +793,90 @@ mod tests {
let arr = r#"{"id":"s","cmd":"stream_signal","args":{"stream_id":"7","client_id":5,"json":[1]}}"#;
assert!(matches!(parse_line(arr), Input::Invalid { .. }));
}
fn assert_bad(command: Command) {
assert_eq!(validate_command(command).unwrap_err().code, ErrorCode::BadRequest);
}
#[test]
fn direct_private_text_requires_exact_target_and_uid() {
let private = |client_id, expected_client_uid| Command::SendText {
target: TextTarget::Client, client_id, expected_client_uid, message: "hello".into(),
};
assert_bad(private(None, Some("uid".into())));
assert_bad(private(Some(0), Some("uid".into())));
assert_bad(private(Some(7), None));
assert_bad(private(Some(7), Some(String::new())));
assert_bad(private(Some(7), Some("x".repeat(129))));
let valid = validate_command(private(Some(7), Some("uid".into()))).unwrap();
assert_eq!(valid.name(), "send_text");
assert_eq!(valid.into_inner(), private(Some(7), Some("uid".into())));
for target in [TextTarget::Channel, TextTarget::Server] {
assert_bad(Command::SendText { target, client_id: Some(7), expected_client_uid: None, message: "hello".into() });
assert_bad(Command::SendText { target, client_id: None, expected_client_uid: Some("uid".into()), message: "hello".into() });
for message in [String::new(), "я".repeat(MAX_TEXT_BYTES / 2 + 1)] {
assert_bad(Command::SendText { target, client_id: None, expected_client_uid: None, message });
}
}
let Input::Invalid { error, .. } = parse_line(r#"{"id":"t","cmd":"send_text","args":{"target":"client","client_id":7,"message":"hello"}}"#) else { panic!() };
assert_eq!(error, validate_command(private(Some(7), None)).unwrap_err());
}
#[test]
fn direct_signaling_checks_objects_and_compact_byte_limit() {
let signal = |json| Command::StreamSignal { stream_id: "s1".into(), client_id: 7, json };
for json in ["[]", "null", "42", "\"string\"", "{"] { assert_bad(signal(json.into())); }
let compact = format!(r#"{{"x":"{}"}}"#, "x".repeat(MAX_SIGNAL_JSON_BYTES - 8));
let padded = format!(" {compact}{}", " ".repeat(MAX_SIGNAL_JSON_BYTES));
assert_eq!(validate_command(signal(padded)).unwrap().into_inner(), signal(compact));
assert_bad(signal(format!(r#"{{"x":"{}"}}"#, "x".repeat(MAX_SIGNAL_JSON_BYTES - 7))));
assert_bad(Command::StreamSignal { stream_id: "bad\n".into(), client_id: 7, json: "{}".into() });
}
#[test]
fn direct_publisher_metadata_and_join_response_are_validated() {
let args = StreamPublishArgs { stream_id: None, name: "Screen".into(), stream_type: 3,
accessibility: 3, mode: 1, bitrate: 4500, viewer_limit: 0, audio: false };
assert!(validate_command(Command::StreamSetup(args.clone())).is_ok());
assert_bad(Command::StreamUpdate(args.clone()));
let mut update = args.clone(); update.stream_id = Some("s1".into());
assert!(validate_command(Command::StreamUpdate(update.clone())).is_ok());
assert_bad(Command::StreamSetup(update));
for invalid in [
StreamPublishArgs { mode: 2, ..args.clone() },
StreamPublishArgs { accessibility: 0, ..args.clone() },
StreamPublishArgs { stream_type: 4, ..args.clone() },
StreamPublishArgs { bitrate: 99, ..args.clone() },
StreamPublishArgs { bitrate: 100001, ..args.clone() },
StreamPublishArgs { name: "Screen\n".into(), ..args.clone() },
StreamPublishArgs { name: String::new(), ..args },
] { assert_bad(Command::StreamSetup(invalid)); }
for (client_id, decision, offer, message) in [(0, true, "v=0", ""), (7, true, "", ""),
(7, false, "v=0", ""), (7, true, "v=0\0", ""), (7, true, "v=0", "bad\n")] {
assert_bad(Command::StreamRespond { stream_id: "s1".into(), client_id, decision, offer: offer.into(), message: message.into() });
}
}
#[test]
fn direct_family_commands_cannot_bypass_semantic_checks() {
use crate::{admin, file_transfer as files, menu, recording, whisper};
let invalid = [
Command::Admin(admin::AdminCommand::ChannelMove { generation: 1, channel_id: 7, parent_id: 7, order: None }),
Command::Admin(admin::AdminCommand::BanAdd { generation: 1, ip: None, name: None, uid: None, duration_s: 0, reason: None }),
Command::Admin(admin::AdminCommand::TempPasswordAdd { generation: 1, password: "pw".into(), description: String::new(), duration_s: 0, channel_id: 0, channel_password: String::new() }),
Command::Admin(admin::AdminCommand::Extra(admin::extra::Command::ServerLog { lines: 0, reverse: false, instance: false, begin_pos: 0 })),
Command::ClientAction(menu::ActionRequest { target: menu::Target { client_id: 7, uid: "uid".into() }, generation: 1, action: menu::Action::Volume { db: f32::NAN, muted: false } }),
Command::Files(files::Request::Config { download_slots: usize::MAX, upload_slots: usize::MAX, download_limit: 0, upload_limit: 0 }),
Command::Files(files::Request::Mkdir { channel_id: 7, path: "/../bad".into(), password: String::new() }),
Command::Files(files::Request::List { channel_id: 0, path: "/private".into(), password: String::new() }),
Command::Files(files::Request::Upload { channel_id: 7, path: "/file".into(), password: String::new(), source: "relative".into(), overwrite: false }),
Command::Recording(recording::RecCommand::Start { directory: "relative".into(), mode: recording::Mode::Master, label: None }),
Command::Whisper(whisper::WhisperCommand::Stop { epoch: 0 }),
Command::SetTransmit { vad: Some(GateMode::VolumeGate { level_db: f32::NAN }) },
Command::SetLocalVolumes(LocalVolumesUpdate { replace: false, volumes: vec![(vec![1], f32::INFINITY)] }),
];
for command in invalid { assert_bad(command); }
let validated = validate_command(Command::Files(files::Request::List { channel_id: 7, path: "/folder".into(), password: String::new() })).unwrap();
assert_eq!(validated.into_inner(), Command::Files(files::Request::List { channel_id: 7, path: "/folder/".into(), password: String::new() }));
}
}
+74 -2
View File
@@ -15,6 +15,11 @@ pub enum StreamVerb {
RequestStreamInfo,
JoinStreamRequest,
StreamSignaling,
SetupStream,
UpdateStream,
StopStream,
RespondJoinStreamRequest,
RemoveClientFromStream,
}
impl StreamVerb {
@@ -23,6 +28,11 @@ impl StreamVerb {
StreamVerb::RequestStreamInfo => "requeststreaminfo",
StreamVerb::JoinStreamRequest => "joinstreamrequest",
StreamVerb::StreamSignaling => "streamsignaling",
StreamVerb::SetupStream => "setupstream",
StreamVerb::UpdateStream => "updatestream",
StreamVerb::StopStream => "stopstream",
StreamVerb::RespondJoinStreamRequest => "respondjoinstreamrequest",
StreamVerb::RemoveClientFromStream => "removeclientfromstream",
}
}
}
@@ -54,11 +64,51 @@ pub fn stream_signaling(stream_id: &str, client_id: u16, json: &str) -> OutComma
build(StreamVerb::StreamSignaling, &[("id", stream_id), ("clid", &client_id.to_string()), ("json", json)])
}
/// Legacy text schema recovered from the installed official client; see evidence notes.
pub fn publish_stream(a: &crate::protocol::StreamPublishArgs) -> OutCommand {
let verb = if a.stream_id.is_some() { StreamVerb::UpdateStream } else { StreamVerb::SetupStream };
let mut cmd = OutCommand::new(Direction::C2S, Flags::empty(), PacketType::Command, verb.name());
if let Some(id) = &a.stream_id { cmd.write_arg("id", id); }
cmd.write_arg("name", &a.name);
cmd.write_arg("type", &a.stream_type);
cmd.write_arg("bitrate", &a.bitrate);
cmd.write_arg("accessibility", &a.accessibility);
cmd.write_arg("mode", &a.mode);
cmd.write_arg("viewer_limit", &a.viewer_limit);
cmd.write_arg("audio", &u8::from(a.audio));
cmd
}
pub fn stop_stream(stream_id: &str) -> OutCommand {
build(StreamVerb::StopStream, &[("id", stream_id)])
}
pub fn respond_stream(stream_id: &str, client_id: u16, decision: bool, offer: &str, message: &str) -> OutCommand {
let mut cmd = build(StreamVerb::RespondJoinStreamRequest, &[("id", stream_id)]);
cmd.write_arg("clid", &client_id);
cmd.write_arg("decision", &u8::from(decision));
cmd.write_arg("offer", &offer);
cmd.write_arg("msg", &message);
cmd
}
pub fn remove_stream_client(stream_id: &str, client_id: u16) -> OutCommand {
// Official UI CloseReason.KICKED = 4. No caller-specified protocol reason codes.
let mut cmd = build(StreamVerb::RemoveClientFromStream, &[("id", stream_id)]);
cmd.write_arg("clid", &client_id);
cmd.write_arg("reason", &4u8);
cmd
}
/// Known commands copied raw (vendored `raw_command_tap`) because tsclientlib's book drops some
/// of their arguments: channel banners and the TeamSpeak 6 `client_is_streaming` flag. The
/// leave/delete notifications are tapped so those copied values follow the objects' lifecycle.
pub fn tap(name: &[u8]) -> bool {
matches!(
crate::menu::tapped(name)
|| crate::admin::tapped(name)
|| crate::events::tapped(name)
|| crate::file_transfer::tapped(name)
|| matches!(
name,
b"channellist"
| b"notifychannelcreated"
@@ -73,7 +123,7 @@ pub fn tap(name: &[u8]) -> bool {
/// Incoming notification names forwarded as `stream` events.
pub fn is_stream_notification(name: &str) -> bool {
name.starts_with("notifystream")
|| matches!(name, "notifyjoinstreamrequest" | "notifyrespondjoinstreamrequest" | "notifysfuaccessinfo")
|| matches!(name, "notifyjoinstreamrequest" | "notifyrespondjoinstreamrequest" | "notifyremovedfromstream" | "notifysfuaccessinfo")
}
/// A parsed raw command: name plus one unescaped key/value map per `|`-separated entry.
@@ -150,6 +200,27 @@ mod tests {
assert_eq!(parsed.items[1]["clid"], "6");
}
#[test]
fn publisher_legacy_wire_schema_and_escaping() {
let mut args = crate::protocol::StreamPublishArgs { stream_id: None, name: "QA | share".into(), stream_type: 3,
accessibility: 3, mode: 1, bitrate: 4500, viewer_limit: 0, audio: false };
assert_eq!(std::str::from_utf8(&content(publish_stream(&args))).unwrap(),
r"setupstream name=QA\s\p\sshare type=3 bitrate=4500 accessibility=3 mode=1 viewer_limit=0 audio=0");
args.stream_id = Some("stream 7".into()); args.audio = true; args.viewer_limit = 5;
let update = parse(&content(publish_stream(&args))).unwrap();
assert_eq!(update.name, "updatestream"); assert_eq!(update.items[0]["id"], "stream 7");
assert_eq!(update.items[0]["viewer_limit"], "5"); assert_eq!(update.items[0]["audio"], "1");
assert_eq!(update.items[0].len(), 8);
let sdp = "v=0\r\na=msid:outgoing_video track|test\\id\r\n";
let accepted = parse(&content(respond_stream("7", 4, true, sdp, ""))).unwrap();
assert_eq!(accepted.name, "respondjoinstreamrequest");
assert_eq!(accepted.items[0]["offer"], sdp); assert_eq!(accepted.items[0]["decision"], "1");
assert_eq!(std::str::from_utf8(&content(respond_stream("7", 4, false, "", "not_authorized"))).unwrap(),
"respondjoinstreamrequest id=7 clid=4 decision=0 offer msg=not_authorized");
assert_eq!(std::str::from_utf8(&content(remove_stream_client("7", 4))).unwrap(), "removeclientfromstream id=7 clid=4 reason=4");
assert_eq!(std::str::from_utf8(&content(stop_stream("7"))).unwrap(), "stopstream id=7");
}
#[test]
fn allowlist() {
for ok in [
@@ -159,6 +230,7 @@ mod tests {
"notifyjoinstreamrequest",
"notifyrespondjoinstreamrequest",
"notifysfuaccessinfo",
"notifyremovedfromstream",
] {
assert!(is_stream_notification(ok), "{ok}");
}
File diff suppressed because it is too large. Load diff
+599
View File
@@ -0,0 +1,599 @@
//! Recording tests: real speech (LibriVox fixture) through the real Opus encoder, S2C packet parsing,
//! jitter buffer and decoder (`audio::Receiver::mix_tapped`), then the real writer thread and files.
//! No device, socket, server or playback is opened.
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU32, Ordering};
use std::time::{Duration, Instant};
use tsproto_packets::packets::{AudioData, Direction, InAudioBuf, OutAudio};
use super::*;
use crate::audio::{Receiver as AudioReceiver, TxCodec, TxEncoder};
use crate::vad::tests::speech_frames;
fn parse(name: &str, raw: Option<&RawValue>) -> Result<RecCommand, ErrorObj> {
let command = super::parse(name, raw)?;
validate(&command)?;
Ok(command)
}
const ALICE_UID: &[u8] = b"alice-uid-0123456789";
const BOB_UID: &[u8] = b"bob-uid-0123456789ab";
const CAROL_UID: &[u8] = b"carol-uid-0123456789";
fn temp_dir(name: &str) -> PathBuf {
static N: AtomicU32 = AtomicU32::new(0);
let dir = std::env::temp_dir().join(format!(
"teamspeach-rec-{}-{}-{name}",
std::process::id(),
N.fetch_add(1, Ordering::Relaxed)
));
let _ = fs::remove_dir_all(&dir);
fs::create_dir_all(&dir).unwrap();
dir
}
fn start(dir: &Path, mode: Mode, cfg: Config) -> Recorder {
Recorder::start(
dir,
Some("2026-11-01_12-00-00"),
mode,
StartInfo {
server_name: "Fixture Server".into(),
server_address: "fixture.invalid".into(),
own_uid: Some(b"self-uid-0123456789a".to_vec()),
own_nickname: "Me".into(),
},
cfg,
)
.unwrap()
}
struct Wav {
samples: Vec<i16>,
}
/// Strict reader for the files we write: canonical 44-byte header, sizes consistent with the file.
fn read_wav(path: &Path) -> Wav {
let b = fs::read(path).unwrap_or_else(|e| panic!("{}: {e}", path.display()));
assert!(b.len() >= 44, "{}: too short", path.display());
assert_eq!(&b[0..4], b"RIFF");
assert_eq!(u32::from_le_bytes(b[4..8].try_into().unwrap()) as usize, b.len() - 8, "RIFF size finalized");
assert_eq!(&b[8..16], b"WAVEfmt ");
assert_eq!(u16::from_le_bytes([b[20], b[21]]), 1, "PCM");
assert_eq!(u16::from_le_bytes([b[22], b[23]]), 1, "mono");
assert_eq!(u32::from_le_bytes(b[24..28].try_into().unwrap()), 48_000);
assert_eq!(u16::from_le_bytes([b[34], b[35]]), 16);
assert_eq!(&b[36..40], b"data");
assert_eq!(u32::from_le_bytes(b[40..44].try_into().unwrap()) as usize, b.len() - 44, "data size finalized");
Wav { samples: b[44..].chunks_exact(2).map(|c| i16::from_le_bytes([c[0], c[1]])).collect() }
}
fn manifest(dir: &Path) -> Value { serde_json::from_slice(&fs::read(dir.join("session.json")).unwrap()).unwrap() }
fn session_dir(base: &Path) -> PathBuf { base.join("2026-11-01_12-00-00") }
fn s2c(packet: &tsproto_packets::packets::OutPacket, id: u16, from: u16, codec: TxCodec) -> InAudioBuf {
let codec = match codec {
TxCodec::OpusVoice => tsproto_packets::packets::CodecType::OpusVoice,
TxCodec::OpusMusic => tsproto_packets::packets::CodecType::OpusMusic,
};
let bytes = OutAudio::new(&AudioData::S2C { id, from, codec, data: &packet.content()[3..] }).into_vec();
InAudioBuf::try_new(Direction::S2C, bytes).unwrap()
}
fn whisper(packet: &tsproto_packets::packets::OutPacket, id: u16, from: u16) -> InAudioBuf {
let bytes = OutAudio::new(&AudioData::S2CWhisper {
id,
from,
codec: tsproto_packets::packets::CodecType::OpusVoice,
data: &packet.content()[3..],
})
.into_vec();
InAudioBuf::try_new(Direction::S2C, bytes).unwrap()
}
fn ident(cid: u16) -> Option<Ident<'static>> {
match cid {
7 => Some(Ident { uid: Some(ALICE_UID), nickname: "Alice" }),
9 => Some(Ident { uid: Some(BOB_UID), nickname: "Bob/Builder:?" }),
_ => None,
}
}
const LOBBY: ChannelCtx<'static> = ChannelCtx { channel_id: 5, channel_name: "Lobby" };
fn finish_wait(rec: Recorder, reason: &str) -> FinishResult { rec.finish(reason).wait() }
fn energy(s: &[i16]) -> f64 { s.iter().map(|v| f64::from(*v).powi(2)).sum::<f64>() }
/// Two remote speakers (real speech, real Opus) + own transmitted capture; Multitrack + Master.
#[test]
fn speech_multitrack_and_master_are_exact() {
let speech = speech_frames();
assert!(speech.len() >= 150);
let base = temp_dir("speech");
let mut rec = start(&base, Mode::Both, Config::default());
let mut rx = AudioReceiver::new();
let mut enc_a = TxEncoder::new(TxCodec::OpusVoice, 6).unwrap();
let mut enc_b = TxEncoder::new(TxCodec::OpusMusic, 6).unwrap();
let mut out = [0i16; FRAME_SAMPLES];
// Expected per-speaker decoded audio (pre-volume, same downmix), placed on the session timeline.
let mut expect_a: Vec<(u64, Frame)> = Vec::new();
let mut expect_b: Vec<(u64, Frame)> = Vec::new();
let mut expect_master: Vec<i16> = Vec::new();
let mut expect_capture: Vec<(u64, Frame)> = Vec::new();
const TICKS: u64 = 160;
const B_START: u64 = 40;
for tick in 0..TICKS {
if tick < 120 {
let p = enc_a.encode(&speech[tick as usize]).unwrap();
rx.handle_packet(s2c(&p, tick as u16, 7, TxCodec::OpusVoice));
}
if (B_START..B_START + 80).contains(&tick) {
let p = enc_b.encode(&speech[(tick - B_START) as usize + 30]).unwrap();
rx.handle_packet(s2c(&p, (tick - B_START) as u16, 9, TxCodec::OpusMusic));
}
// Own capture actually sent on this connection during ticks 100..130.
let cap = (100..130).contains(&tick).then(|| speech[tick as usize - 60]);
if let Some(c) = &cap {
rec.capture(c);
}
let mut tapped: Vec<(u16, Frame)> = Vec::new();
let gain = |id: u16| if id == 9 { 0.5 } else { 1.0 };
rx.mix_tapped(&mut out, gain, |id, w, data| {
assert!(!w);
if data.is_empty() {
return;
}
let mut f = [0i16; FRAME_SAMPLES];
downmix(data, &mut f);
tapped.push((id, f));
rec.speaker(id, w, data);
});
for (id, f) in tapped {
match id {
7 => expect_a.push((tick, f)),
9 => expect_b.push((tick, f)),
_ => unreachable!(),
}
}
for (i, m) in out.iter().enumerate() {
expect_master.push(m.saturating_add(cap.map_or(0, |c| c[i])));
}
if let Some(c) = cap {
expect_capture.push((tick, c));
}
assert_eq!(rec.end_tick(&out, ident, &LOBBY), TickOutcome::Ok);
}
let info = rec.info();
assert_eq!(info["timelineFrames"], json!(TICKS * 960));
let result = finish_wait(rec, "stopped");
assert!(result.ok, "{result:?}");
let dir = session_dir(&base);
assert_eq!(result.output_path, dir);
let m = manifest(&dir);
assert_eq!(m["finalized"], json!(true));
assert_eq!(m["endReason"], json!("stopped"));
assert_eq!(m["droppedChunks"], json!(0));
assert_eq!(m["mode"], json!(3));
let tracks = m["tracks"].as_array().unwrap();
let by_kind = |k: &str, name: &str| tracks.iter().find(|t| t["kind"] == json!(k) && t["name"] == json!(name)).unwrap().clone();
let master = by_kind("master", "Master");
let alice = by_kind("client", "Alice");
let bob = by_kind("client", "Bob/Builder:?");
let me = by_kind("capture", "Me");
assert_eq!(alice["uid"], json!(BASE64_STANDARD.encode(ALICE_UID)));
assert_eq!(bob["files"], json!(["02 Bob_Builder__.wav"]), "file names are sanitized");
assert_eq!(master["files"], json!(["00 master.wav"]));
// Master: full timeline, exactly what was played (local volume applied) plus the transmitted capture.
let wm = read_wav(&dir.join("00 master.wav"));
assert_eq!(wm.samples.len() as u64, TICKS * 960, "duration = ticks x 20 ms");
assert_eq!(wm.samples, expect_master);
assert_eq!(master["timelineFrames"], json!(TICKS * 960));
// Client tracks: untouched (pre-volume) decoded audio, aligned at startOffsetFrames.
for (track, expect) in [(&alice, &expect_a), (&bob, &expect_b)] {
let file = track["files"][0].as_str().unwrap();
let w = read_wav(&dir.join(file));
let start = expect[0].0;
assert_eq!(track["startOffsetFrames"], json!(start * 960));
let last = expect.last().unwrap().0;
assert_eq!(w.samples.len() as u64, (last + 1 - start) * 960);
for (tick, f) in expect {
let at = ((tick - start) * 960) as usize;
assert_eq!(&w.samples[at..at + 960], &f[..], "{file} tick {tick}");
}
assert!(energy(&w.samples) > 1e9, "decoded speech has energy");
assert_eq!(track["audioFrames"], json!(expect.len() as u64 * 960));
let seg = &track["segments"][0];
assert_eq!(seg["channelName"], json!("Lobby"));
assert_eq!(seg["channelId"], json!(5));
assert_eq!(seg["startFrame"], json!(start * 960));
assert!(seg["startEpochMs"].as_u64().unwrap() > 1_700_000_000_000);
}
assert!(expect_b[0].0 >= B_START, "Bob's track starts when Bob's audio is first decoded");
// Capture: exactly the frames sent, placed on the ticks they were mixed.
let wc = read_wav(&dir.join(me["files"][0].as_str().unwrap()));
assert_eq!(me["startOffsetFrames"], json!(100 * 960));
assert_eq!(wc.samples.len(), 30 * 960);
for (i, (_, f)) in expect_capture.iter().enumerate() {
assert_eq!(&wc.samples[i * 960..(i + 1) * 960], &f[..]);
}
assert_eq!(m["totalBytes"], json!(result.total_bytes));
let sum: u64 = tracks.iter().map(|t| t["bytes"].as_u64().unwrap()).sum();
assert_eq!(sum, result.total_bytes);
let _ = fs::remove_dir_all(&base);
}
#[test]
fn master_only_records_no_tracks_and_silence_keeps_duration() {
let base = temp_dir("silence");
let mut rec = start(&base, Mode::Master, Config::default());
assert!(!rec.wants_speakers(), "master-only never taps speakers");
let silent = [0i16; FRAME_SAMPLES];
for _ in 0..75 {
assert_eq!(rec.end_tick(&silent, ident, &LOBBY), TickOutcome::Ok);
}
let r = finish_wait(rec, "stopped");
assert!(r.ok);
let dir = session_dir(&base);
let w = read_wav(&dir.join("00 master.wav"));
assert_eq!(w.samples.len(), 75 * 960, "1.5 s of silence");
assert!(w.samples.iter().all(|s| *s == 0));
let m = manifest(&dir);
assert_eq!(m["tracks"].as_array().unwrap().len(), 1);
assert_eq!(m["tracks"][0]["audioFrames"], json!(0));
let names: Vec<_> = fs::read_dir(&dir).unwrap().map(|e| e.unwrap().file_name().into_string().unwrap()).collect();
assert_eq!(names.len(), 2, "{names:?}");
let _ = fs::remove_dir_all(&base);
}
#[test]
fn multitrack_only_has_no_master_and_whisper_is_flagged() {
let speech = speech_frames();
let base = temp_dir("whisper");
let mut rec = start(&base, Mode::Multitrack, Config::default());
let mut rx = AudioReceiver::new();
let mut enc = TxEncoder::new(TxCodec::OpusVoice, 6).unwrap();
let mut out = [0i16; FRAME_SAMPLES];
for tick in 0..40u16 {
let p = enc.encode(&speech[tick as usize]).unwrap();
rx.handle_packet(whisper(&p, tick, 7));
rx.mix_tapped(&mut out, |_| 1.0, |id, w, d| rec.speaker(id, w, d));
rec.end_tick(&out, ident, &LOBBY);
}
assert!(finish_wait(rec, "stopped").ok);
let m = manifest(&session_dir(&base));
let tracks = m["tracks"].as_array().unwrap();
assert!(tracks.iter().all(|t| t["kind"] != json!("master")));
assert_eq!(tracks[0]["name"], json!("Alice"));
assert_eq!(tracks[0]["segments"][0]["whisper"], json!(true));
assert!(!session_dir(&base).join("00 master.wav").exists());
let _ = fs::remove_dir_all(&base);
}
#[test]
fn pause_excludes_audio_and_time_and_splits_segments() {
let speech = speech_frames();
let base = temp_dir("pause");
let mut rec = start(&base, Mode::Both, Config::default());
let mut rx = AudioReceiver::new();
let mut enc = TxEncoder::new(TxCodec::OpusVoice, 6).unwrap();
let mut out = [0i16; FRAME_SAMPLES];
let mut recorded_ticks = 0u64;
for tick in 0..90u16 {
if tick == 30 {
assert!(rec.pause());
assert!(!rec.pause());
}
if tick == 60 {
assert!(rec.resume());
}
let p = enc.encode(&speech[tick as usize]).unwrap();
rx.handle_packet(s2c(&p, tick, 7, TxCodec::OpusVoice));
if rec.is_paused() {
rec.capture(&speech[0]);
}
if rec.wants_speakers() {
rx.mix_tapped(&mut out, |_| 1.0, |id, w, d| rec.speaker(id, w, d));
} else {
rx.mix(&mut out, |_| 1.0);
}
if !rec.is_paused() {
recorded_ticks += 1;
}
rec.end_tick(&out, ident, &LOBBY);
}
assert_eq!(recorded_ticks, 60);
let info = rec.info();
assert_eq!(info["timelineFrames"], json!(60 * 960), "paused time is not on the timeline");
assert!(finish_wait(rec, "stopped").ok);
let dir = session_dir(&base);
let m = manifest(&dir);
assert_eq!(read_wav(&dir.join("00 master.wav")).samples.len(), 60 * 960);
assert_eq!(m["pauses"].as_array().unwrap().len(), 1);
assert_eq!(m["pauses"][0]["atFrame"], json!(30 * 960));
let alice = m["tracks"].as_array().unwrap().iter().find(|t| t["name"] == json!("Alice")).unwrap().clone();
assert_eq!(alice["segments"].as_array().unwrap().len(), 2, "pause splits the segment");
assert_eq!(alice["segments"][1]["startFrame"], json!(30 * 960));
assert!(m["tracks"].as_array().unwrap().iter().all(|t| t["kind"] != json!("capture")), "capture while paused is discarded");
let _ = fs::remove_dir_all(&base);
}
#[test]
fn disconnect_mid_speech_finalizes_playable_files() {
let speech = speech_frames();
let base = temp_dir("disconnect");
let mut rec = start(&base, Mode::Both, Config::default());
let mut rx = AudioReceiver::new();
let mut enc = TxEncoder::new(TxCodec::OpusVoice, 6).unwrap();
let mut out = [0i16; FRAME_SAMPLES];
for tick in 0..37u16 {
let p = enc.encode(&speech[tick as usize]).unwrap();
rx.handle_packet(s2c(&p, tick, 7, TxCodec::OpusVoice));
rx.mix_tapped(&mut out, |_| 1.0, |id, w, d| rec.speaker(id, w, d));
rec.end_tick(&out, ident, &LOBBY);
}
let r = finish_wait(rec, "disconnected");
assert!(r.ok);
let dir = session_dir(&base);
assert_eq!(read_wav(&dir.join("00 master.wav")).samples.len(), 37 * 960);
assert!(read_wav(&dir.join("01 Alice.wav")).samples.len() > 0);
assert_eq!(manifest(&dir)["endReason"], json!("disconnected"));
assert!(!dir.join("session.json.tmp").exists());
let _ = fs::remove_dir_all(&base);
}
#[test]
fn write_error_is_reported_and_files_stay_consistent() {
let base = temp_dir("ioerror");
let cfg = Config { fail_after_bytes: Some(44 * 2 + 960 * 2 * 20), ..Config::default() };
let mut rec = start(&base, Mode::Master, cfg);
let tone: Frame = std::array::from_fn(|i| ((i as f32 * 0.05).sin() * 8000.0) as i16);
let deadline = Instant::now() + Duration::from_secs(10);
let failure = loop {
match rec.end_tick(&tone, ident, &LOBBY) {
TickOutcome::Failed(e) => break e,
_ => std::thread::sleep(Duration::from_millis(2)),
}
assert!(Instant::now() < deadline, "writer failure never surfaced");
};
assert!(failure.contains("injected write failure"), "{failure}");
assert!(rec.info()["error"].as_str().unwrap().contains("injected"));
let r = finish_wait(rec, "write_failed");
assert!(!r.ok);
assert!(r.error.unwrap().contains("injected"));
let dir = session_dir(&base);
let w = read_wav(&dir.join("00 master.wav"));
assert!(!w.samples.is_empty() && w.samples.len() % 960 == 0, "complete frames before the failure");
let m = manifest(&dir);
assert_eq!(m["endReason"], json!("write_failed"));
assert!(m["errors"][0].as_str().unwrap().contains("injected"));
let _ = fs::remove_dir_all(&base);
}
#[test]
fn slow_disk_drops_whole_ticks_truthfully_and_keeps_alignment() {
let base = temp_dir("backpressure");
let cfg = Config { queue_ticks: 2, write_delay: Duration::from_millis(15), ..Config::default() };
let mut rec = start(&base, Mode::Master, cfg);
let mut dropped_reports = 0;
const TICKS: u64 = 60;
for tick in 0..TICKS {
let f: Frame = [(tick as i16) + 1; FRAME_SAMPLES];
match rec.end_tick(&f, ident, &LOBBY) {
TickOutcome::Overflow { .. } => dropped_reports += 1,
TickOutcome::Ok => {}
TickOutcome::Failed(e) => panic!("{e}"),
}
}
let dropped = rec.info()["droppedChunks"].as_u64().unwrap();
assert!(dropped > 0 && dropped < TICKS, "dropped={dropped}");
assert!(dropped_reports >= 1);
assert!(finish_wait(rec, "stopped").ok);
let dir = session_dir(&base);
let m = manifest(&dir);
assert_eq!(m["droppedChunks"], json!(dropped));
let w = read_wav(&dir.join("00 master.wav"));
let ranges: Vec<(u64, u64)> = m["droppedRanges"]
.as_array()
.unwrap()
.iter()
.map(|r| (r[0].as_u64().unwrap() / 960, r[1].as_u64().unwrap() / 960))
.collect();
assert_eq!(ranges.iter().map(|(a, b)| b - a).sum::<u64>(), dropped);
// Even a dropped tail retains the declared duration and is represented by silence.
let ticks = w.samples.len() as u64 / 960;
assert_eq!(ticks, TICKS);
for t in 0..ticks {
let v = w.samples[(t * 960) as usize];
let was_dropped = ranges.iter().any(|(a, b)| (*a..*b).contains(&t));
assert_eq!(v, if was_dropped { 0 } else { t as i16 + 1 }, "tick {t}");
}
let _ = fs::remove_dir_all(&base);
}
#[test]
fn riff_limit_rolls_over_to_numbered_parts() {
let base = temp_dir("rollover");
let cfg = Config { max_wav_data: 960 * 2 * 3, ..Config::default() };
let mut rec = start(&base, Mode::Master, cfg);
for tick in 0..10i16 {
rec.end_tick(&[tick + 1; FRAME_SAMPLES], ident, &LOBBY);
}
assert!(finish_wait(rec, "stopped").ok);
let dir = session_dir(&base);
let m = manifest(&dir);
let files: Vec<String> = serde_json::from_value(m["tracks"][0]["files"].clone()).unwrap();
assert_eq!(files, ["00 master.wav", "00 master (part 2).wav", "00 master (part 3).wav", "00 master (part 4).wav"]);
let all: Vec<i16> = files.iter().flat_map(|f| read_wav(&dir.join(f)).samples).collect();
assert_eq!(all.len(), 10 * 960);
assert!((0..10).all(|t| all[t * 960] == t as i16 + 1));
let _ = fs::remove_dir_all(&base);
}
#[test]
fn recycled_ids_and_reconnects_keep_identity() {
let base = temp_dir("identity");
let mut rec = start(&base, Mode::Multitrack, Config::default());
let stereo = vec![0.25f32; FRAME_SAMPLES * 2];
let silent = [0i16; FRAME_SAMPLES];
// tick 0: Alice as 7. tick 1: id 7 recycled by Carol. tick 2: Alice back as 12.
let who = |tick: u32| {
move |cid: u16| match (tick, cid) {
(0, 7) | (2, 12) => Some(Ident { uid: Some(ALICE_UID), nickname: "Alice" }),
(1, 7) => Some(Ident { uid: Some(CAROL_UID), nickname: "Carol" }),
_ => None,
}
};
for (tick, cid) in [(0u32, 7u16), (1, 7), (2, 12)] {
rec.speaker(cid, false, &stereo);
rec.end_tick(&silent, who(tick), &LOBBY);
}
// Unknown client (no identity yet) still gets a track.
rec.speaker(40, false, &stereo);
rec.end_tick(&silent, |_| None, &LOBBY);
assert!(finish_wait(rec, "stopped").ok);
let m = manifest(&session_dir(&base));
let tracks = m["tracks"].as_array().unwrap();
let names: Vec<_> = tracks.iter().map(|t| (t["name"].as_str().unwrap().to_owned(), t["instance"].as_u64().unwrap())).collect();
assert_eq!(names, [("Alice".into(), 1), ("Carol".into(), 1), ("Client 40".into(), 1)]);
let alice = &tracks[0];
assert_eq!(alice["segments"].as_array().unwrap().len(), 2);
assert_eq!(alice["segments"][1]["clientId"], json!(12));
assert_eq!(alice["timelineFrames"], json!(3 * 960), "gap at tick 1 padded");
let _ = fs::remove_dir_all(&base);
}
#[test]
fn dropping_without_finish_still_finalizes() {
let base = temp_dir("drop");
{
let mut rec = start(&base, Mode::Master, Config::default());
for _ in 0..10 {
rec.end_tick(&[100; FRAME_SAMPLES], ident, &LOBBY);
}
}
let dir = session_dir(&base);
assert_eq!(read_wav(&dir.join("00 master.wav")).samples.len(), 10 * 960);
let m = manifest(&dir);
assert_eq!(m["endReason"], json!("dropped"));
assert_eq!(m["finalized"], json!(true));
let _ = fs::remove_dir_all(&base);
}
#[test]
fn headers_are_refreshed_while_recording() {
let base = temp_dir("refresh");
let (refreshed_tx, refreshed_rx) = mpsc::channel();
let cfg = Config {
queue_ticks: HEADER_REFRESH_TICKS as usize,
header_refreshed: Some(refreshed_tx),
..Config::default()
};
let mut rec = start(&base, Mode::Master, cfg);
for _ in 0..HEADER_REFRESH_TICKS {
assert_eq!(rec.end_tick(&[7; FRAME_SAMPLES], ident, &LOBBY), TickOutcome::Ok);
}
// Wait for the writer's completed header refresh, not file creation or buffered byte count.
// No further frames are queued, so the file is stable while inspected (recorder remains active).
refreshed_rx.recv_timeout(Duration::from_secs(10)).expect("writer never completed its periodic header refresh");
let path = session_dir(&base).join("00 master.wav");
let wav = read_wav(&path);
assert_eq!(wav.samples.len(), HEADER_REFRESH_TICKS as usize * FRAME_SAMPLES);
assert!(wav.samples.iter().all(|sample| *sample == 7));
assert_eq!(manifest(&session_dir(&base))["finalized"], json!(false), "crash marker until finished");
assert!(finish_wait(rec, "stopped").ok);
let _ = fs::remove_dir_all(&base);
}
#[test]
fn start_never_reuses_a_folder_and_creates_missing_output_dir() {
let base = temp_dir("folders").join("missing").join("deeper");
let a = start(&base, Mode::Master, Config::default());
let b = start(&base, Mode::Master, Config::default());
assert_eq!(a.output_path(), base.join("2026-11-01_12-00-00"));
assert_eq!(b.output_path(), base.join("2026-11-01_12-00-00_2"));
assert!(finish_wait(a, "stopped").ok && finish_wait(b, "stopped").ok);
let _ = fs::remove_dir_all(base.parent().unwrap().parent().unwrap());
}
#[test]
fn parse_validates_arguments() {
let raw = |s: &str| RawValue::from_string(s.to_owned()).unwrap();
let abs = if cfg!(windows) { r#"C:\\rec"# } else { "/rec" };
let ok = parse("recording_start", Some(&raw(&format!(r#"{{"directory":"{abs}","mode":3,"label":"2026-11-01_09-05-07"}}"#)))).unwrap();
assert!(matches!(ok, RecCommand::Start { mode: Mode::Both, .. }));
for bad_args in [
r#"{"directory":"relative","mode":1}"#.to_owned(),
format!(r#"{{"directory":"{abs}","mode":4}}"#),
format!(r#"{{"directory":"{abs}","mode":1,"label":"../x"}}"#),
format!(r#"{{"directory":"{abs}","mode":1,"extra":true}}"#),
r#"{"directory":"","mode":1}"#.to_owned(),
] {
assert_eq!(parse("recording_start", Some(&raw(&bad_args))).unwrap_err().code, ErrorCode::BadRequest, "{bad_args}");
}
assert_eq!(parse("recording_stop", None).unwrap(), RecCommand::Stop);
assert!(parse("recording_stop", Some(&raw(r#"{"x":1}"#))).is_err());
assert_eq!(parse("recording_waveform", Some(&raw(r#"{"track_id":1,"from_bucket":0}"#))).unwrap(), RecCommand::Waveform { track_id: 1, from_bucket: 0 });
assert_eq!(parse("recording_nope", None).unwrap_err().code, ErrorCode::UnknownCommand);
}
#[test]
fn helpers() {
assert_eq!(utc_label(0), "1970-01-01_00-00-00");
assert_eq!(utc_label(1_793_525_045_000), "2026-11-01_09-24-05");
assert_eq!(sanitize(" a/b\\c:d*e?f\"g<h>i|j. "), "a_b_c_d_e_f_g_h_i_j");
assert_eq!(sanitize("..."), "client");
assert_eq!(sanitize("Ёжик 🦔"), "Ёжик _");
assert!(valid_label("2026-11-01_09-05-07") && !valid_label("2026-11-01 09-05-07"));
let mut f = [0i16; FRAME_SAMPLES];
downmix(&[2.0, 2.0].repeat(FRAME_SAMPLES), &mut f);
assert!(f.iter().all(|s| *s == i16::MAX), "clamped like playback");
assert_eq!(peak_of(&[i16::MIN; FRAME_SAMPLES]), 1000);
}
#[test]
fn waveform_reports_peaks_per_tick() {
let base = temp_dir("waveform");
let mut rec = start(&base, Mode::Master, Config::default());
for t in 0..5i16 {
rec.end_tick(&[t * 8191; FRAME_SAMPLES], ident, &LOBBY);
}
let w = rec.waveform(0, 2).unwrap();
assert_eq!(w["fromBucket"], json!(2));
assert_eq!(w["nextBucket"], json!(5));
assert_eq!(w["peaks"], json!([500, 750, 1000]));
assert_eq!(rec.waveform(99, 0).unwrap_err().code, ErrorCode::NotFound);
assert!(finish_wait(rec, "stopped").ok);
let _ = fs::remove_dir_all(&base);
}
#[test]
fn immediate_stop_creates_empty_playable_master() {
let base = temp_dir("immediate-stop");
let rec = start(&base, Mode::Master, Config::default());
assert!(finish_wait(rec, "stopped").ok);
assert!(read_wav(&session_dir(&base).join("00 master.wav")).samples.is_empty());
let _ = fs::remove_dir_all(&base);
}
#[test]
fn queued_capture_is_reported_when_pause_or_stop_discards_it() {
let base = temp_dir("capture-cancel");
let mut rec = start(&base, Mode::Both, Config::default());
rec.capture(&[100; FRAME_SAMPLES]);
rec.capture(&[100; FRAME_SAMPLES]);
rec.pause();
assert_eq!(rec.info()["droppedCaptureFrames"], json!(2));
rec.resume();
rec.capture(&[100; FRAME_SAMPLES]);
assert!(finish_wait(rec, "stopped").ok);
assert_eq!(manifest(&session_dir(&base))["droppedCaptureFrames"], json!(3));
let _ = fs::remove_dir_all(&base);
}
+159
View File
@@ -0,0 +1,159 @@
//! Session side of local recording (`recording_*` commands, tick hook, finalization events).
//! The recorder belongs to one connection and only exists between an explicit `recording_start`
//! and stop/disconnect/write failure; nothing is recorded before that.
use super::*;
use crate::recording::{ChannelCtx, Config, Ident, RecCommand, Recorder, StartInfo, TickOutcome};
fn not_recording() -> ErrorObj { ErrorObj::new(ErrorCode::BadRequest, "not recording") }
impl Session {
pub(super) async fn recording(&mut self, _id: &str, cmd: RecCommand) -> Result<Option<Value>, ErrorObj> {
match cmd {
RecCommand::Start { directory, mode, label } => {
if self.rec.is_some() {
return Err(ErrorObj::new(ErrorCode::BadRequest, "already recording"));
}
if !self.rec_finishing.is_empty() {
return Err(ErrorObj::new(ErrorCode::BadRequest, "previous recording is still finalizing"));
}
let c = self.connected_conn()?;
let info = {
let book = c.con.get_state().map_err(|e| lib_error(ErrorCode::NotConnected, &e))?;
let me = book.clients.get(&book.own_client);
StartInfo {
server_name: book.server.name.clone(),
server_address: c.address.clone(),
own_uid: me.and_then(|m| m.uid.as_ref()).map(|u| u.0.clone()),
own_nickname: me.map(|m| m.name.clone()).unwrap_or_default(),
}
};
let rec = Recorder::start(&directory, label.as_deref(), mode, info, Config::default())?;
self.rec = Some(rec);
self.announce_recording(true);
self.emit_recording_state(None, None).await;
Ok(Some(self.rec.as_ref().map_or(Value::Null, Recorder::info)))
}
RecCommand::Stop => {
if self.rec.is_none() {
return Err(not_recording());
}
let path = self.recording_finish("stopped", None).await;
Ok(Some(json!({ "outputPath": path, "finalizing": true })))
}
RecCommand::Pause | RecCommand::Resume => {
let rec = self.rec.as_mut().ok_or_else(not_recording)?;
let changed = if cmd == RecCommand::Pause { rec.pause() } else { rec.resume() };
let paused = rec.is_paused();
if changed {
self.emit_recording_state(None, None).await;
}
Ok(Some(json!({ "isRecording": true, "isPaused": paused })))
}
RecCommand::Status => Ok(Some(json!({
"isRecording": self.rec.is_some(),
"isPaused": self.rec.as_ref().is_some_and(Recorder::is_paused),
}))),
RecCommand::Info => Ok(Some(self.rec.as_ref().map_or_else(|| json!({ "isRecording": false }), Recorder::info))),
RecCommand::Waveform { track_id, from_bucket } => {
self.rec.as_ref().ok_or_else(not_recording)?.waveform(track_id, from_bucket).map(Some)
}
}
}
/// Tell the server (`client_is_recording`) so others see the REC indicator, like the official client.
fn announce_recording(&mut self, on: bool) {
let Some(c) = self.conn.as_mut().filter(|c| c.connected()) else { return };
let Ok(book) = c.con.get_state() else { return };
let part = book.client_update().set_is_recording(on);
match c.send(part) {
Ok(handle) => {
c.pending.insert(handle, Pending::Internal { what: "client_is_recording" });
}
Err(e) => warn!(%e, "announcing recording state failed"),
}
}
async fn emit_recording_state(&self, reason: Option<&str>, error: Option<&str>) {
let mut v = json!({
"event": "recording_state",
"isRecording": self.rec.is_some(),
"isPaused": self.rec.as_ref().is_some_and(Recorder::is_paused),
"outputDirectory": self.rec.as_ref().map(|r| r.output_path().to_string_lossy().into_owned()),
"mode": self.rec.as_ref().map(|r| r.mode() as u8),
});
if let Some(r) = reason {
v["reason"] = json!(r);
}
if let Some(e) = error {
v["error"] = json!(e);
}
self.out.json(&v).await;
}
/// Stops the active recording (if any) and starts finalization; returns its folder. `reason`:
/// `stopped`, `disconnected`, `write_failed`.
pub(super) async fn recording_finish(&mut self, reason: &str, error: Option<String>) -> Option<String> {
let rec = self.rec.take()?;
let path = rec.output_path().to_string_lossy().into_owned();
self.rec_finishing.push(rec.finish(reason));
self.announce_recording(false);
// The state event carries the failure; no separate `error` event, so the UI reports it once.
self.emit_recording_state(Some(reason), error.as_deref()).await;
Some(path)
}
/// Every tick, connected or not: report recordings whose files are finalized.
pub(super) async fn recording_poll(&mut self) {
if self.rec_finishing.is_empty() {
return;
}
let mut done = Vec::new();
self.rec_finishing.retain_mut(|f| match f.poll() {
Some(r) => {
done.push(r);
false
}
None => true,
});
for r in done {
self.out
.json(&json!({
"event": "recording_finalized",
"outputPath": r.output_path.to_string_lossy(),
"ok": r.ok,
"error": r.error,
"totalBytes": r.total_bytes,
}))
.await;
}
}
/// After `rx.mix_tapped` filled `self.pcm` (and fed speakers into the recorder): close the tick.
pub(super) async fn recording_after_mix(&mut self) {
let Some(rec) = self.rec.as_mut() else { return };
let book = self.conn.as_ref().and_then(|c| c.con.get_state().ok());
let (channel_id, channel_name) = book
.and_then(|b| b.clients.get(&b.own_client))
.and_then(|me| book.and_then(|b| b.channels.get(&me.channel)).map(|ch| (me.channel.0, ch.name.as_str())))
.unwrap_or((0, ""));
let ctx = ChannelCtx { channel_id, channel_name };
let outcome = rec.end_tick(
&self.pcm,
|id| {
book.and_then(|b| b.clients.get(&ClientId(id)))
.map(|cl| Ident { uid: cl.uid.as_ref().map(|u| u.0.as_slice()), nickname: cl.name.as_str() })
},
&ctx,
);
match outcome {
TickOutcome::Ok => {}
TickOutcome::Overflow { dropped_chunks } => {
self.out.json(&json!({ "event": "recording_dropped", "droppedChunks": dropped_chunks })).await;
}
TickOutcome::Failed(e) => {
self.recording_finish("write_failed", Some(e)).await;
}
}
}
}
+170
View File
@@ -0,0 +1,170 @@
//! Embedded session lifetime. The host owns one handle per server; no stdio or UI loop is required.
use std::{collections::HashMap, path::PathBuf, sync::{Arc, Mutex, atomic::{AtomicU64, Ordering}}, thread};
use serde_json::Value;
use tokio::sync::{mpsc, oneshot};
use crate::{audio::{AudioIn, AudioInQueue, CapturedFrame}, locks, output::{Out, PlaybackReceiver}, profile::Store, protocol::{validate_command, Command, ErrorCode, ErrorObj, Input}, session::Session};
pub struct CoreConfig { pub data_dir: PathBuf, pub connection_dir: PathBuf }
#[derive(Debug, thiserror::Error)]
#[error("core startup or shutdown failed: {0}")]
pub struct CoreStartError(pub String);
type Pending = Arc<Mutex<HashMap<String, oneshot::Sender<Result<Value, ErrorObj>>>>>;
pub struct CoreEvents {
pub control: mpsc::Receiver<Value>,
pub playback: PlaybackReceiver,
}
pub struct CoreHandle {
commands: Option<mpsc::Sender<Input>>,
pending: Pending,
next_request: AtomicU64,
audio: Arc<AudioInQueue>,
cancel: Option<oneshot::Sender<()>>,
finished: Option<oneshot::Receiver<()>>,
worker: Option<thread::JoinHandle<()>>,
}
fn stopped() -> ErrorObj { ErrorObj::new(ErrorCode::NotConnected, "core session stopped") }
fn fail_pending(pending: &Pending) {
let mut requests = pending.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
for (_, reply) in requests.drain() { let _ = reply.send(Err(stopped())); }
}
struct WorkerCleanup(Pending);
impl Drop for WorkerCleanup {
fn drop(&mut self) { fail_pending(&self.0); }
}
struct PendingRequest { id: String, pending: Pending }
impl Drop for PendingRequest {
fn drop(&mut self) { self.pending.lock().unwrap_or_else(std::sync::PoisonError::into_inner).remove(&self.id); }
}
impl CoreHandle {
pub async fn request(&self, command: Command) -> Result<Value, ErrorObj> {
let command = validate_command(command)?;
let commands = self.commands.as_ref().ok_or_else(stopped)?;
let id = self.next_request.fetch_add(1, Ordering::Relaxed).to_string();
let (reply, receiver) = oneshot::channel();
self.pending.lock().expect("pending requests poisoned").insert(id.clone(), reply);
let _guard = PendingRequest { id: id.clone(), pending: self.pending.clone() };
commands.send(Input::Request { id, cmd: command }).await.map_err(|_| stopped())?;
receiver.await.unwrap_or_else(|_| Err(stopped()))
}
pub fn push_audio(&self, frame: CapturedFrame) -> bool { self.audio.try_push(frame) }
pub fn invalidate_audio(&self) -> u64 { self.audio.invalidate() }
pub fn audio_epoch(&self) -> u64 { self.audio.epoch() }
pub fn connection_generation(&self) -> u64 { self.audio.generation() }
pub fn end_audio(&self) { self.audio.push(AudioIn::End); }
pub async fn shutdown(mut self) -> Result<(), CoreStartError> {
self.audio.invalidate();
self.commands.take();
if let Some(cancel) = self.cancel.take() { let _ = cancel.send(()); }
if let Some(finished) = self.finished.take() { let _ = finished.await; }
if let Some(worker) = self.worker.take() {
worker.join().map_err(|_| CoreStartError("core worker panicked".into()))?;
}
Ok(())
}
}
impl Drop for CoreHandle {
fn drop(&mut self) {
self.audio.invalidate();
self.commands.take();
if let Some(cancel) = self.cancel.take() { let _ = cancel.send(()); }
fail_pending(&self.pending);
// Explicit shutdown awaits completion. Drop signals cancellation without blocking a UI thread.
}
}
pub fn spawn(config: CoreConfig) -> Result<(CoreHandle, CoreEvents), CoreStartError> {
if !config.data_dir.is_absolute() || !config.connection_dir.is_absolute() || config.data_dir == config.connection_dir {
return Err(CoreStartError("data and connection directories must be distinct absolute paths".into()));
}
let locks = locks::lock_run(&config.data_dir, Some(&config.connection_dir)).map_err(CoreStartError)?;
let runtime = tokio::runtime::Builder::new_current_thread().enable_all().build().map_err(|e| CoreStartError(e.to_string()))?;
let (commands, command_rx) = mpsc::channel(64);
let (cancel, cancel_rx) = oneshot::channel();
let (finished_tx, finished) = oneshot::channel();
let (events, control) = mpsc::channel(1024);
let (out, mut out_rx, playback) = Out::new();
let pending: Pending = Arc::new(Mutex::new(HashMap::new()));
let worker_pending = pending.clone();
let audio = Arc::new(AudioInQueue::new());
let worker_audio = audio.clone();
let worker = thread::Builder::new().name("teamspeach-core".into()).spawn(move || {
let _locks = locks;
let _cleanup = WorkerCleanup(worker_pending.clone());
runtime.block_on(async move {
let (failure_tx, failure_rx) = oneshot::channel::<()>();
let mut failure_tx = Some(failure_tx);
let cancel = async { tokio::select! { _ = cancel_rx => {}, _ = failure_rx => {} } };
let mut session = Box::pin(Session::new(Store::new(&config.data_dir), out, worker_audio).run_with_cancel(command_rx, cancel));
let mut session_finished = false;
loop {
tokio::select! {
_ = &mut session, if !session_finished => { session_finished = true; },
value = out_rx.recv() => {
let Some(value) = value else { break };
if let Some(id) = value.get("id").and_then(Value::as_str) {
let reply = worker_pending.lock().expect("pending requests poisoned").remove(id);
if let Some(reply) = reply {
let result = if value.get("ok").and_then(Value::as_bool) == Some(true) {
Ok(value.get("result").cloned().unwrap_or(Value::Null))
} else {
Err(serde_json::from_value(value.get("error").cloned().unwrap_or(Value::Null))
.unwrap_or_else(|_| ErrorObj::new(ErrorCode::Internal, "invalid core error response")))
};
let _ = reply.send(result);
}
} else {
// A stalled/dead host cannot stall network polling or command replies.
if failure_tx.is_some() && events.try_send(value).is_err() {
if let Some(cancel) = failure_tx.take() { let _ = cancel.send(()); }
fail_pending(&worker_pending);
}
}
}
}
}
fail_pending(&worker_pending);
});
drop(runtime);
drop(_locks);
let _ = finished_tx.send(());
}).map_err(|e| CoreStartError(e.to_string()))?;
Ok((CoreHandle { commands: Some(commands), pending, next_request: AtomicU64::new(1), audio,
cancel: Some(cancel), finished: Some(finished), worker: Some(worker) }, CoreEvents { control, playback }))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn worker_unwind_completes_retained_requests_even_with_poisoned_map() {
let pending: Pending = Arc::new(Mutex::new(HashMap::new()));
let (reply, mut receiver) = oneshot::channel();
pending.lock().unwrap().insert("pending".into(), reply);
let captured = pending.clone();
let result = std::panic::catch_unwind(move || {
let _cleanup = WorkerCleanup(captured.clone());
let _held = captured.lock().unwrap();
panic!("controlled worker failure");
});
assert!(result.is_err());
assert_eq!(receiver.try_recv().unwrap().unwrap_err().code, ErrorCode::NotConnected);
assert!(pending.lock().unwrap_or_else(std::sync::PoisonError::into_inner).is_empty());
}
#[test]
fn cancelled_waiter_releases_its_pending_sender() {
let pending: Pending = Arc::new(Mutex::new(HashMap::new()));
let (reply, mut receiver) = oneshot::channel();
pending.lock().unwrap().insert("cancelled".into(), reply);
drop(PendingRequest { id: "cancelled".into(), pending: pending.clone() });
assert!(matches!(receiver.try_recv(), Err(oneshot::error::TryRecvError::Closed)));
assert!(pending.lock().unwrap().is_empty());
}
}
+2 -1
View File
@@ -32,7 +32,8 @@ fn create_file(path: &Path, private: bool) -> io::Result<File> {
/// Write `data` to `path` atomically: temp file (owner-only if `private`) + fsync + rename.
///
/// The caller must hold the data-dir lock, so a leftover temp file can only stem from a crash.
/// The caller must exclude concurrent writers of `path` (profile files: `profile.lock`, see
/// `profile::Store`), so a leftover temp file can only stem from a crash.
pub fn write_atomic(path: &Path, data: &[u8], private: bool) -> io::Result<()> {
let tmp = tmp_path(path);
match fs::remove_file(&tmp) {
+486 -107
View File
@@ -1,6 +1,7 @@
//! The session: owns the tsclientlib connection and maps bridge commands/events onto it.
use std::collections::{HashMap, VecDeque};
use std::future::Future;
use std::net::{IpAddr, SocketAddr};
use std::sync::Arc;
use std::time::{Duration, Instant};
@@ -20,12 +21,30 @@ use tsclientlib::messages::c2s::{OutInitDownloadMessage, OutInitDownloadPart};
use tsproto_packets::packets::OutCommand;
use crate::audio::{self, AudioIn, AudioInQueue, Receiver, RxEvent, TxCodec, TxEncoder};
use crate::vad::{Decision, VoiceGate, MAX_PREROLL_FRAMES};
use crate::media::{self, MediaKind};
use crate::profile::{validate_nickname, Store, StoreError, StoredIdentity};
use crate::protocol::{Command, ConnectArgs, ErrorCode, ErrorObj, Frame, Input, TextTarget, TsErrorInfo, FRAME_SAMPLES};
use crate::menu::{self, Action as MenuAction, ActionRequest, Target};
use tokio::io::AsyncWriteExt;
use md5::{Digest, Md5};
use crate::profile::{store_error, validate_nickname, Store, StoreError, StoredIdentity};
use crate::protocol::{Command, ConnectArgs, ErrorCode, ErrorObj, Input, TextTarget, TsErrorInfo, FRAME_SAMPLES};
use crate::admin;
#[path = "menu_session.rs"]
mod menu_session;
#[path = "admin_session.rs"]
mod admin_session;
#[path = "files_session.rs"]
mod files_session;
#[path = "recording_session.rs"]
mod recording_session;
#[path = "whisper_session.rs"]
mod whisper_session;
#[path = "voice_dsp_session.rs"]
mod voice_dsp_session;
use crate::rawcmd;
use crate::snapshot::{self, RawExtras};
use crate::stdio::Out;
use crate::output::Out;
use crate::audio::CapturedFrame;
const DEFAULT_PORT: u16 = 9987;
const SNAPSHOT_MIN_INTERVAL: Duration = Duration::from_millis(50);
@@ -34,19 +53,6 @@ const DISCONNECT_TIMEOUT: Duration = Duration::from_secs(3);
const OVERFLOW_REPORT_INTERVAL: Duration = Duration::from_secs(1);
const DEFAULT_CODEC_QUALITY: u8 = 6;
pub fn store_error(e: StoreError) -> ErrorObj {
let code = match &e {
StoreError::Missing => ErrorCode::ProfileMissing,
StoreError::Exists => ErrorCode::ProfileExists,
StoreError::IdentityCorrupt { .. } => ErrorCode::IdentityCorrupt,
StoreError::ProfileCorrupt { .. } => ErrorCode::ProfileCorrupt,
StoreError::InvalidNickname(_) => ErrorCode::InvalidNickname,
StoreError::ImportInvalid(_) => ErrorCode::BadRequest,
StoreError::Io { .. } => ErrorCode::Io,
};
ErrorObj::new(code, e.to_string())
}
fn ts_info(error: TsError, missing: Option<tsclientlib::Permission>) -> TsErrorInfo {
TsErrorInfo {
id: error.to_u32().unwrap_or(u32::MAX),
@@ -65,6 +71,10 @@ fn lib_error(code: ErrorCode, e: &tsclientlib::Error) -> ErrorObj {
match e {
tsclientlib::Error::CommandError(ce) => obj.with_ts(ts_info(ce.error, ce.missing_permission)),
tsclientlib::Error::ConnectTs(te) => obj.with_ts(ts_info(*te, None)),
tsclientlib::Error::IdentityLevel(level) => obj.with_detail(json!({ "required_security_level": level })),
tsclientlib::Error::IdentityLevelCorrupted { needed, have } => {
obj.with_detail(json!({ "required_security_level": needed, "security_level": have }))
}
_ => obj,
}
}
@@ -107,14 +117,19 @@ enum Phase {
enum Pending {
Simple { req: String },
MenuContext { req: String, target: Target },
MenuRead { req: String, target: Target, dbid: u64, channel: Option<u64>, response: &'static str, rows: Vec<menu::Row> },
SetAudio { req: String },
Rename { req: String, nickname: String, saved: Option<String> },
Rename { req: String, nickname: String, saved: Option<String>, identity_id: String },
RenameRevert { req: String, attempted: String, saved: String, save_error: String },
StreamInfo { batch: u64, client_id: u16 },
/// Core-initiated command; failures become `error` events.
Internal { what: &'static str },
/// `ftinitdownload` for the media job with this `clientftfid`.
FtInit { ftid: u16 },
AvatarInit { ftid: u16 },
/// Server/channel administration request (`admin.rs`); `reply` assembles the answer.
Admin { req: String, reply: admin::Reply },
}
struct StreamBatch {
@@ -145,6 +160,22 @@ struct Conn {
next_ftid: u16,
/// Port of the connected server if known from the address (checks `ts3image://` banners).
server_port: Option<u16>,
permissions: menu::Permissions,
gains: menu::LocalVolumes,
avatar: Option<AvatarUpload>,
files: crate::file_transfer::Files,
}
struct AvatarUpload {
req: String,
handle: u16,
data: Vec<u8>,
hash: String,
started: Instant,
task: Option<tokio::task::JoinHandle<()>>,
}
impl Drop for AvatarUpload {
fn drop(&mut self) { if let Some(task) = self.task.take() { task.abort(); } }
}
struct FtJob {
@@ -155,12 +186,20 @@ struct FtJob {
impl Conn {
fn connected(&self) -> bool { matches!(self.phase, Phase::Connected) }
fn transfer_id(&mut self) -> u16 {
loop {
let id = self.next_ftid;
self.next_ftid = self.next_ftid.wrapping_add(1).max(1);
if !self.ft_active.contains_key(&id) && self.avatar.as_ref().is_none_or(|j| j.handle != id) && !self.files.owns_ftid(id) { return id; }
}
}
fn own_channel_codec(&self) -> Option<(tsclientlib::Codec, u8)> {
/// Own channel id, codec and codec quality.
fn own_channel_codec(&self) -> Option<(u64, tsclientlib::Codec, u8)> {
let book = self.con.get_state().ok()?;
let me = book.clients.get(&book.own_client)?;
let ch = book.channels.get(&me.channel)?;
Some((ch.codec, ch.codec_quality.unwrap_or(DEFAULT_CODEC_QUALITY)))
Some((me.channel.0, ch.codec, ch.codec_quality.unwrap_or(DEFAULT_CODEC_QUALITY)))
}
fn send(&mut self, cmd: impl OutCommandExt) -> Result<u16, tsclientlib::Error> {
@@ -178,6 +217,14 @@ struct Tx {
last_overflow_report: Option<Instant>,
}
/// Voice activation state; present only in the "vad" transmit mode.
struct VadState {
gate: VoiceGate,
/// Channel and codec the gate's audio belongs to; a change resets the gate so nothing heard before
/// it is sent afterwards.
route: Option<(u64, TxCodec, u8)>,
}
enum Exit {
Running,
Requested { req: Option<String> },
@@ -191,6 +238,13 @@ pub struct Session {
flags: AudioFlags,
conn: Option<Conn>,
tx: Tx,
/// `None` = direct transmission: every frame the renderer forwards is sent.
vad: Option<Box<VadState>>,
/// Whisper send route (one per session) and incoming whisper policy.
whisper: crate::whisper::Whisper,
/// Persisted per-user volumes and playback DSP flags pushed by the app (outlive connections).
voice: crate::voice_dsp::VoiceSettings,
preroll_buf: Box<[Option<CapturedFrame>; MAX_PREROLL_FRAMES]>,
pcm: Box<[i16; FRAME_SAMPLES]>,
rev: u64,
exit: Exit,
@@ -199,6 +253,11 @@ pub struct Session {
generation: u64,
ft_done_tx: mpsc::UnboundedSender<u64>,
ft_done_rx: mpsc::UnboundedReceiver<u64>,
avatar_tx: mpsc::UnboundedSender<(u64, Result<(), String>)>,
avatar_rx: mpsc::UnboundedReceiver<(u64, Result<(), String>)>,
/// Local recording of this connection (`recording.rs`).
rec: Option<crate::recording::Recorder>,
rec_finishing: Vec<crate::recording::Finishing>,
}
async fn next_event(conn: &mut Option<Conn>) -> Option<Result<StreamItem, tsclientlib::Error>> {
@@ -211,6 +270,7 @@ async fn next_event(conn: &mut Option<Conn>) -> Option<Result<StreamItem, tsclie
impl Session {
pub fn new(store: Store, out: Out, audio_in: Arc<AudioInQueue>) -> Self {
let (ft_done_tx, ft_done_rx) = mpsc::unbounded_channel();
let (avatar_tx, avatar_rx) = mpsc::unbounded_channel();
Self {
store,
out,
@@ -218,6 +278,10 @@ impl Session {
flags: AudioFlags::default(),
conn: None,
tx: Tx::default(),
vad: None,
whisper: Default::default(),
voice: Default::default(),
preroll_buf: Box::new(std::array::from_fn(|_| None)),
pcm: Box::new([0; FRAME_SAMPLES]),
rev: 0,
exit: Exit::Running,
@@ -226,17 +290,38 @@ impl Session {
generation: 0,
ft_done_tx,
ft_done_rx,
avatar_tx,
avatar_rx,
rec: None,
rec_finishing: Vec::new(),
}
}
pub async fn run(mut self, mut cmds: mpsc::Receiver<Input>) {
let mut tick = tokio::time::interval(Duration::from_millis(20));
loop {
pub async fn run(self, cmds: mpsc::Receiver<Input>) {
self.run_with_cancel(cmds, std::future::pending()).await;
}
pub async fn run_embedded(self, cmds: mpsc::Receiver<Input>, cancel: tokio::sync::oneshot::Receiver<()>) {
self.run_with_cancel(cmds, async { let _ = cancel.await; }).await;
}
pub(crate) async fn run_with_cancel(mut self, mut cmds: mpsc::Receiver<Input>, cancel: impl Future<Output = ()>) {
tokio::pin!(cancel);
let mut cancelled = false;
let mut tick = tokio::time::interval(Duration::from_millis(20));
loop {
self.check_exit().await;
if matches!(self.exit, Exit::Done) {
break;
}
tokio::select! {
_ = &mut cancel, if !cancelled => {
cancelled = true;
self.audio_in.invalidate();
self.stdin_closed = true;
cmds.close();
self.begin_exit(None).await;
},
ev = next_event(&mut self.conn) => self.on_conn_event(ev).await,
input = cmds.recv(), if !self.stdin_closed => match input {
Some(input) => self.on_input(input).await,
@@ -249,6 +334,7 @@ impl Session {
_ = self.audio_in.notified() => self.drain_audio().await,
_ = tick.tick() => self.on_tick().await,
Some(generation) = self.ft_done_rx.recv() => self.on_ft_done(generation).await,
Some((generation, result)) = self.avatar_rx.recv() => self.avatar_finished(generation, result).await,
}
}
}
@@ -269,20 +355,7 @@ impl Session {
self.out.json(&v).await;
}
fn profile_value(&self) -> Result<Value, StoreError> {
Ok(match self.store.load_identity()? {
None => json!({ "exists": false, "uid": null, "nickname": null, "security_level": null }),
Some(si) => {
let nickname = self.store.load_nickname()?;
json!({
"exists": true,
"uid": si.uid,
"nickname": nickname,
"security_level": si.security_level(),
})
}
})
}
fn profile_value(&self) -> Result<Value, StoreError> { self.store.profile_json(None) }
async fn emit_profile(&self, profile: &Value) {
let mut v = profile.clone();
@@ -292,6 +365,9 @@ impl Session {
async fn emit_state(&self, state: &str, address: Option<&str>, reason: Option<ErrorObj>) {
let mut v = json!({ "event": "state", "state": state, "address": address });
if let Some(c) = &self.conn {
v["identity_id"] = json!(c.identity.uid);
}
if let Some(r) = reason {
v["reason"] = serde_json::to_value(r).expect("error serializes");
}
@@ -303,7 +379,9 @@ impl Session {
let Ok(book) = c.con.get_state() else { return };
self.rev += 1;
c.extras.prune(book);
let v = snapshot::build(book, self.rev, &c.extras);
let mut v = snapshot::build(book, self.rev, &c.extras);
// Mutating admin/menu requests must carry this value (`docs/bridge.md` §4.6).
v["generation"] = json!(c.generation);
c.dirty = false;
c.last_snapshot = Some(Instant::now());
self.out.json(&v).await;
@@ -327,7 +405,7 @@ impl Session {
return;
}
debug!(cmd = cmd.name(), "request");
self.handle(id, cmd).await;
self.handle(id, cmd.into_inner()).await;
}
Input::Invalid { id: Some(id), error } => self.out.err(&id, error).await,
Input::Invalid { id: None, error } => self.out.error_event(error).await,
@@ -344,8 +422,11 @@ impl Session {
Command::Connect(args) => self.connect(&id, args).await,
Command::Disconnect { message } => self.disconnect(Some(id.clone()), message).await,
Command::JoinChannel { channel_id, password } => self.join_channel(&id, channel_id, password),
Command::SendText { target, client_id, message } => self.send_text(&id, target, client_id, &message),
Command::SendText { target, client_id, expected_client_uid, message } => self.send_text(&id, target, client_id, expected_client_uid.as_deref(), &message),
Command::SetAudio { input_muted, output_muted } => self.set_audio(&id, input_muted, output_muted).await,
Command::SetTransmit { vad } => self.set_transmit(vad).await.map(Some),
Command::SetLocalVolumes(update) => self.set_local_volumes(update).map(Some),
Command::SetPlaybackDsp { agc } => self.set_playback_dsp(agc).map(Some),
Command::StreamList { client_id } => self.stream_list(&id, client_id).await,
Command::StreamJoin { stream_id, client_id, message } => {
self.stream_join(&id, &stream_id, client_id, message)
@@ -358,10 +439,22 @@ impl Session {
let cmd = rawcmd::join_stream(&stream_id, client_id, "", true);
self.send_simple(&id, cmd)
}
Command::StreamSetup(args) | Command::StreamUpdate(args) => self.send_simple(&id, rawcmd::publish_stream(&args)),
Command::StreamStop { stream_id } => self.send_simple(&id, rawcmd::stop_stream(&stream_id)),
Command::StreamRespond { stream_id, client_id, decision, offer, message } => {
self.send_simple(&id, rawcmd::respond_stream(&stream_id, client_id, decision, &offer, &message))
}
Command::StreamRemove { stream_id, client_id } => self.send_simple(&id, rawcmd::remove_stream_client(&stream_id, client_id)),
Command::FetchIcon { icon_id } => self.fetch_icon(&id, icon_id).await,
Command::FetchBanner { channel_id } => self.fetch_banner(&id, Some(channel_id)).await,
Command::FetchServerBanner => self.fetch_banner(&id, None).await,
Command::FetchAvatar { client_id } => self.fetch_avatar(&id, client_id).await,
Command::ClientContext(target) => self.client_context(&id, target),
Command::ClientAction(request) => self.client_action(&id, request).await,
Command::Admin(cmd) => self.admin(&id, cmd).await,
Command::Files(r) => self.files_request(&id, r).await,
Command::Recording(cmd) => self.recording(&id, cmd).await,
Command::Whisper(c) => self.whisper_command(&id, c).await,
Command::Shutdown => {
self.begin_exit(Some(id.clone())).await;
Ok(None)
@@ -394,11 +487,12 @@ impl Session {
Ok(Some(profile))
}
Some(c) if c.connected() => {
let saved = self.store.load_nickname().map_err(store_error)?;
let saved = self.store.nickname_of(&c.identity.uid).map_err(store_error)?;
let book = c.con.get_state().map_err(|e| lib_error(ErrorCode::NotConnected, &e))?;
let cmd = book.client_update().set_name(&nickname);
let handle = c.send(cmd).map_err(|e| lib_error(ErrorCode::NotConnected, &e))?;
c.pending.insert(handle, Pending::Rename { req: id.to_owned(), nickname, saved });
let identity_id = c.identity.uid.clone();
c.pending.insert(handle, Pending::Rename { req: id.to_owned(), nickname, saved, identity_id });
Ok(None)
}
Some(_) => Err(ErrorObj::new(
@@ -412,13 +506,14 @@ impl Session {
if self.conn.is_some() {
return Err(ErrorObj::new(ErrorCode::AlreadyConnected, "already connected or connecting"));
}
let identity = self.store.load_identity().map_err(store_error)?.ok_or_else(|| store_error(StoreError::Missing))?;
let nickname = self.store.load_nickname().map_err(store_error)?.ok_or_else(|| {
ErrorObj::new(ErrorCode::NicknameRequired, "no nickname saved; call rename first")
})?;
let (identity, nickname) = self
.store
.open_for_connect(args.identity_id.as_deref(), args.nickname.as_deref())
.map_err(store_error)?;
let mut options = Connection::build(parse_address(&args.address))
.identity(identity.identity.clone())
.automatic_identity_level(false)
.name(nickname)
.input_muted(self.flags.input_muted)
.output_muted(self.flags.output_muted)
@@ -452,6 +547,8 @@ impl Session {
let con = options.connect().map_err(|e| lib_error(ErrorCode::ConnectFailed, &e))?;
info!(uid = %identity.uid, address = %args.address, "connecting");
self.generation += 1;
self.audio_in.set_generation(self.generation);
self.out.set_generation(self.generation);
self.conn = Some(Conn {
con,
address: args.address.clone(),
@@ -463,9 +560,17 @@ impl Session {
dirty: false,
last_snapshot: None,
leave_reason: None,
rx: Receiver::new(),
rx: {
let mut rx = Receiver::new();
rx.set_playback_agc(self.voice.playback_agc);
rx
},
extras: RawExtras::default(),
generation: self.generation,
permissions: menu::Permissions::default(),
gains: menu::LocalVolumes::default(),
avatar: None,
files: Default::default(),
ft_waiting: VecDeque::new(),
ft_active: HashMap::new(),
ft_in_flight: 0,
@@ -527,7 +632,7 @@ impl Session {
Ok(None)
}
fn send_text(&mut self, id: &str, target: TextTarget, client_id: Option<u16>, message: &str) -> Result<Option<Value>, ErrorObj> {
fn send_text(&mut self, id: &str, target: TextTarget, client_id: Option<u16>, expected_client_uid: Option<&str>, message: &str) -> Result<Option<Value>, ErrorObj> {
let target = match (target, client_id) {
(TextTarget::Server, _) => MessageTarget::Server,
(TextTarget::Channel, _) => MessageTarget::Channel,
@@ -535,13 +640,21 @@ impl Session {
(TextTarget::Client, None) => unreachable!("validated by the parser"),
};
let c = self.connected_conn()?;
let cmd: OutCommand = c.con.get_state().map_err(|e| lib_error(ErrorCode::NotConnected, &e))?.send_message(target, message);
let book = c.con.get_state().map_err(|e| lib_error(ErrorCode::NotConnected, &e))?;
if let Some(cid) = client_id {
let current = book.clients.get(&ClientId(cid)).and_then(|client| client.uid.as_ref());
if current.is_none_or(|uid| Some(uid.to_string()).as_deref() != expected_client_uid) {
return Err(ErrorObj::new(ErrorCode::TargetChanged, "private message target left or its identity changed"));
}
}
let cmd: OutCommand = book.send_message(target, message);
let handle = c.send(cmd).map_err(|e| lib_error(ErrorCode::NotConnected, &e))?;
c.pending.insert(handle, Pending::Simple { req: id.to_owned() });
Ok(None)
}
async fn set_audio(&mut self, id: &str, input_muted: Option<bool>, output_muted: Option<bool>) -> Result<Option<Value>, ErrorObj> {
if input_muted.is_some() || output_muted.is_some() { self.audio_in.invalidate(); }
if let Some(m) = input_muted {
self.flags.input_muted = m;
}
@@ -550,6 +663,9 @@ impl Session {
}
if self.flags.input_muted || self.flags.output_muted {
self.tx_end().await;
// A held whisper does not survive a mute or deafen: frames tagged with it are dropped until
// the key is pressed again.
self.whisper_cleared(if self.flags.output_muted { "deafened" } else { "muted" }).await;
}
if self.flags.output_muted {
self.rx_reset().await;
@@ -708,8 +824,7 @@ impl Session {
if let Some(c) = self.conn.as_mut().filter(|c| c.connected()) {
while c.ft_in_flight < media::MAX_IN_FLIGHT {
let Some(mut job) = c.ft_waiting.pop_front() else { break };
let ftid = c.next_ftid;
c.next_ftid = c.next_ftid.wrapping_add(1).max(1);
let ftid = c.transfer_id();
let path = job.kind.path();
let cmd = OutInitDownloadMessage::new(&mut std::iter::once(OutInitDownloadPart {
client_filetransfer_id: ftid,
@@ -803,6 +918,7 @@ impl Session {
// ------------------------------------------------------------ exit
async fn begin_exit(&mut self, req: Option<String>) {
self.audio_in.invalidate();
if !matches!(self.exit, Exit::Running) {
if let Some(r) = req {
self.out.err(&r, ErrorObj::new(ErrorCode::BadRequest, "already shutting down")).await;
@@ -845,7 +961,17 @@ impl Session {
if self.flags.output_muted {
return;
}
match c.rx.handle_packet(packet) {
let ignored = c.rx.set_deny_whispers(self.whisper.deny_incoming);
let event = c.rx.handle_packet(packet);
let whisper_starts: Vec<u16> = c.rx.take_whisper_starts().collect();
for cid in ignored {
self.out.json(&json!({ "event": "talking", "client_id": cid, "talking": false })).await;
}
for cid in whisper_starts {
// Official `onWhisperStart`: feeds the reply history and the whisper notification.
self.out.json(&json!({ "event": "whisper_received", "client_id": cid })).await;
}
match event {
RxEvent::None => {}
RxEvent::Started(cid) => {
self.out.json(&json!({ "event": "talking", "client_id": cid, "talking": true })).await
@@ -865,15 +991,59 @@ impl Session {
}
StreamItem::RawCommandCopy(content) => {
let Some(c) = &mut self.conn else { return };
if let Some(raw) = rawcmd::parse(&content) {
if c.extras.apply(&raw) {
c.dirty = true;
let Some(raw) = rawcmd::parse(&content) else { return };
c.permissions.apply(&raw);
for pending in c.pending.values_mut() {
match pending {
Pending::MenuRead { target, dbid, channel, response, rows, .. } if *response == raw.name => {
for row in &raw.items {
if menu::response_matches(row, *response, target.client_id, *dbid, *channel) && rows.len() <= 4096 { rows.push(row.clone()); }
}
}
Pending::Admin { reply, .. } => reply.collect(&raw),
_ => {}
}
}
// Before `extras.apply`: leaving clients / deleted channels still have their labels.
let own = c.con.get_state().ok().map(|b| b.own_client.0);
let events = crate::events::from_raw(&raw, &c.extras, own);
if c.extras.apply(&raw) {
c.dirty = true;
}
self.files_raw(&raw).await;
for event in events {
self.out.json(&event).await;
}
}
StreamItem::FileDownload(handle, result) => {
if let Some(result) = self.files_download(handle.0, result).await {
self.on_ft_granted(handle.0, result).await;
}
}
StreamItem::FileUpload(handle, result) => {
let Some(result) = self.files_upload(handle.0, result).await else { return };
let Some(c) = &mut self.conn else { return };
let Some(job) = c.avatar.as_mut().filter(|j| j.handle == handle.0) else { return };
let data = std::mem::take(&mut job.data);
let generation = c.generation;
let tx = self.avatar_tx.clone();
job.task = Some(tokio::spawn(async move {
let mut stream = result.stream;
let result = tokio::time::timeout(Duration::from_secs(10), async {
stream.write_all(&data).await?;
stream.shutdown().await
}).await.map_err(|_| "avatar transfer timed out".to_owned()).and_then(|r|r.map_err(|e|e.to_string()));
let _ = tx.send((generation, result));
}));
}
StreamItem::FileDownload(handle, result) => self.on_ft_granted(handle.0, result).await,
StreamItem::FiletransferFailed(handle, e) => {
let Some(e) = self.files_failed(handle.0, e).await else { return };
let err = lib_error(ErrorCode::ServerError, &e);
if self.conn.as_ref().and_then(|c|c.avatar.as_ref()).is_some_and(|j|j.handle==handle.0) {
let job = self.conn.as_mut().unwrap().avatar.take().unwrap();
self.out.err(&job.req, err).await;
return;
}
self.ft_finish(handle.0, err).await;
}
StreamItem::UnknownCommand(cmd) => {
@@ -893,6 +1063,12 @@ impl Session {
self.tx_end().await;
self.rx_reset().await;
if let Some(c) = &mut self.conn {
self.generation += 1;
self.audio_in.set_generation(self.generation);
self.out.set_generation(self.generation);
c.generation = self.generation;
c.permissions = menu::Permissions::default();
c.gains.clear();
c.phase = Phase::Connecting { req: None };
let address = c.address.clone();
let msg = match reason {
@@ -905,12 +1081,12 @@ impl Session {
}
StreamItem::IdentityLevelIncreasing(level) => {
info!(level, "server requires a higher identity security level, computing");
self.out.json(&json!({ "event": "identity_level_increasing", "required_security_level": level })).await;
}
StreamItem::IdentityLevelIncreased => self.persist_upgraded_identity().await,
StreamItem::MessageEvent(_)
| StreamItem::AudioChange(_)
| StreamItem::NetworkStatsUpdated
| StreamItem::FileUpload(..) => {}
| StreamItem::NetworkStatsUpdated => {}
}
}
@@ -933,8 +1109,9 @@ impl Session {
for e in &events {
match e {
Event::Message { target, invoker, message } => texts.push(text_event(*target, invoker, message)),
Event::PropertyRemoved { id: PropertyId::Client(cid), extra, .. } if Some(*cid) == own => {
c.leave_reason = extra.reason;
Event::PropertyRemoved { id: PropertyId::Client(cid), extra, .. } => {
c.rx.remove_client(cid.0);
if Some(*cid) == own { c.leave_reason = extra.reason; }
}
_ => {}
}
@@ -968,12 +1145,46 @@ impl Session {
}
async fn on_result(&mut self, handle: u16, res: Result<(), CommandError>) {
if self.conn.as_ref().is_some_and(|c| c.files.owns_handle(handle)) {
self.files_result(handle, res).await;
return;
}
let Some(c) = &mut self.conn else { return };
let Some(p) = c.pending.remove(&handle) else {
debug!(handle, "result for unknown handle");
return;
};
match p {
Pending::Admin { req, reply } => self.admin_result(req, reply, res).await,
Pending::AvatarInit { ftid } => {
if let Err(e) = res {
if c.avatar.as_ref().is_some_and(|j|j.handle==ftid) {
let job=c.avatar.take().unwrap();
self.out.err(&job.req,command_error(&e)).await;
}
}
},
Pending::MenuContext { req, target } => {
let result = c.con.get_state().map_err(|e|lib_error(ErrorCode::NotConnected,&e)).and_then(|book|c.permissions.context(book,&target,c.generation));
match result {
Ok(mut value) => {
let gain=c.con.get_state().ok().and_then(|b|b.clients.get(&ClientId(target.client_id))).and_then(|client|client.uid.as_ref()).map_or((0.0,false),|uid|c.gains.get(&uid.0,&self.voice.volumes));
value["volume_db"] = json!(gain.0);
value["volume_muted"] = json!(gain.1);
if let Err(e)=res { value["permission_error"]=serde_json::to_value(command_error(&e)).unwrap(); }
self.out.ok(&req,value).await;
},
Err(e)=>self.out.err(&req,e).await,
}
},
Pending::MenuRead { req, target, rows, .. } => match res {
Err(e)=>self.out.err(&req,command_error(&e)).await,
Ok(())=>match c.con.get_state().map_err(|e|lib_error(ErrorCode::NotConnected,&e)).and_then(|b|c.permissions.context(b,&target,c.generation)) {
Ok(_) if rows.len()>4096=>self.out.err(&req,ErrorObj::new(ErrorCode::ServerError,"server returned too many permission rows; result not complete")).await,
Ok(_)=>self.out.ok(&req,json!({"rows":rows})).await,
Err(e)=>self.out.err(&req,e).await,
},
},
Pending::Simple { req } => match res {
Ok(()) => self.out.ok(&req, json!({})).await,
Err(e) => self.out.err(&req, command_error(&e)).await,
@@ -994,12 +1205,14 @@ impl Session {
self.out.error_event(err).await;
}
}
Pending::Rename { req, nickname, saved } => match res {
Pending::Rename { req, nickname, saved, identity_id } => match res {
Err(e) => self.out.err(&req, command_error(&e)).await,
Ok(()) => match self.store.save_nickname(&nickname) {
Ok(()) => match self.profile_value() {
Ok(()) => match self.store.save_nickname_of(&identity_id, &nickname) {
Ok(()) => match self.store.profile_json(Some(&identity_id)) {
Ok(profile) => {
self.emit_profile(&profile).await;
if profile["is_default"] == true {
self.emit_profile(&profile).await;
}
self.out.ok(&req, profile).await;
}
Err(e) => self.out.err(&req, store_error(e)).await,
@@ -1069,12 +1282,14 @@ impl Session {
/// Answer every outstanding request of the current connection with an error.
async fn fail_pending(&mut self, why: &str) {
self.files_fail_all(why).await;
let Some(c) = &mut self.conn else { return };
let pending: Vec<Pending> = c.pending.drain().map(|(_, p)| p).collect();
let batches: Vec<StreamBatch> = c.batches.drain().map(|(_, b)| b).collect();
if let Some(job)=c.avatar.take(){self.out.err(&job.req,ErrorObj::new(ErrorCode::NotConnected,why)).await;}
for p in pending {
match p {
Pending::Simple { req } | Pending::SetAudio { req } | Pending::Rename { req, .. } => {
Pending::Simple { req } | Pending::SetAudio { req } | Pending::Rename { req, .. } | Pending::MenuContext { req, .. } | Pending::MenuRead { req, .. } | Pending::Admin { req, .. } => {
self.out.err(&req, ErrorObj::new(ErrorCode::NotConnected, why)).await
}
Pending::RenameRevert { req, attempted, saved, save_error } => {
@@ -1085,7 +1300,7 @@ impl Session {
.with_detail(json!({ "saved_nickname": saved, "server_nickname": attempted, "reverted": false }));
self.out.err(&req, err).await
}
Pending::StreamInfo { .. } | Pending::Internal { .. } | Pending::FtInit { .. } => {}
Pending::StreamInfo { .. } | Pending::Internal { .. } | Pending::FtInit { .. } | Pending::AvatarInit { .. } => {}
}
}
for b in batches {
@@ -1095,6 +1310,8 @@ impl Session {
/// Drop the connection and emit `state: disconnected`. `respond` answers a disconnect request.
async fn close_conn(&mut self, reason: Option<ErrorObj>, respond: Option<(String, Value)>) {
self.audio_in.invalidate();
self.recording_finish("disconnected", None).await;
self.fail_pending("connection closed before the server answered").await;
self.fail_media("connection closed before the download finished").await;
self.tx_end().await;
@@ -1152,7 +1369,10 @@ impl Session {
// ------------------------------------------------------------ audio
/// Drops all received speaker state (deafen, connection closed or lost). A held whisper belongs to the
/// connection it was resolved on and is cleared with it.
async fn rx_reset(&mut self) {
self.whisper_cleared("connection").await;
let Some(c) = &mut self.conn else { return };
let talking = c.rx.reset();
for cid in talking {
@@ -1176,7 +1396,7 @@ impl Session {
}
while let Some(item) = self.audio_in.pop() {
match item {
AudioIn::Frame(f) => self.tx_frame(&f).await,
AudioIn::Frame(f) => self.tx_frame(&f).await,
AudioIn::End => self.tx_end().await,
}
}
@@ -1189,81 +1409,223 @@ impl Session {
}
}
async fn tx_frame(&mut self, frame: &Frame) {
self.tx.burst_open = true;
self.tx.last_frame = Some(Instant::now());
/// Checks every condition for sending voice right now and returns the own channel id, codec and
/// quality; reports the first failing condition once per burst.
async fn tx_route(&mut self) -> Option<(u64, TxCodec, u8)> {
let flags = self.flags;
let Some(c) = self.conn.as_mut().filter(|c| c.connected()) else {
return self.report_once(ErrorObj::new(ErrorCode::NotConnected, "audio_frame while not connected; frames dropped")).await;
self.report_once(ErrorObj::new(ErrorCode::NotConnected, "audio_frame while not connected; frames dropped")).await;
return None;
};
if flags.input_muted || flags.output_muted {
return self.report_once(ErrorObj::new(ErrorCode::AudioMuted, "audio_frame while muted or deafened; frames dropped")).await;
self.report_once(ErrorObj::new(ErrorCode::AudioMuted, "audio_frame while muted or deafened; frames dropped")).await;
return None;
}
let Some((codec, quality)) = c.own_channel_codec() else {
return self.report_once(ErrorObj::new(ErrorCode::Internal, "own channel is unknown")).await;
let Some((channel, codec, quality)) = c.own_channel_codec() else {
self.report_once(ErrorObj::new(ErrorCode::Internal, "own channel is unknown")).await;
return None;
};
let Some(tx_codec) = TxCodec::for_channel(codec) else {
return self
.report_once(
ErrorObj::new(
ErrorCode::AudioCodecUnsupported,
format!("channel codec {} is not supported for sending (Opus only)", audio::codec_name(codec)),
)
.with_detail(json!({ "codec": audio::codec_name(codec) })),
self.report_once(
ErrorObj::new(
ErrorCode::AudioCodecUnsupported,
format!("channel codec {} is not supported for sending (Opus only)", audio::codec_name(codec)),
)
.await;
.with_detail(json!({ "codec": audio::codec_name(codec) })),
)
.await;
return None;
};
if !c.con.can_send_audio() {
return self
.report_once(ErrorObj::new(
ErrorCode::AudioMuted,
"the server does not let this client talk here (talk power, away or server mute); frames dropped",
))
.await;
self.report_once(ErrorObj::new(
ErrorCode::AudioMuted,
"the server does not let this client talk here (talk power, away or server mute); frames dropped",
))
.await;
return None;
}
Some((channel, tx_codec, quality))
}
/// One captured frame. `whisper` is the epoch the renderer tagged it with while a whisper key was held:
/// such a frame goes only to that whisper route (or nowhere); an untagged frame is ordinary voice.
async fn tx_frame(&mut self, frame: &CapturedFrame) {
if !self.audio_in.validate(frame) { return; }
let whisper = frame.whisper;
// Capture queued before push-to-whisper must not escape to the ordinary channel.
if whisper.is_none() && self.whisper.active_epoch().is_some() {
return;
}
self.tx.burst_open = true;
self.tx.last_frame = Some(frame.captured_at);
let Some(route) = self.tx_route().await else {
// Nothing may be sent now; forget what voice activation heard so it is never sent later.
self.vad_reset();
self.end_spurt().await;
return;
};
let (_, tx_codec, quality) = route;
if let Some(epoch) = whisper {
// Push-to-whisper is held explicitly, so voice activation does not gate it; and nothing voice
// activation heard before may follow the whisper as ordinary voice.
self.vad_reset();
self.tx_send(frame, tx_codec, quality, Some(epoch)).await;
return;
}
if self.whisper.spurt().is_some() {
// Ordinary voice after a whisper: the whisper transmission ends (at its targets) first.
self.end_spurt().await;
}
let Some(vad) = self.vad.as_mut() else {
self.tx_send(frame, tx_codec, quality, None).await;
return;
};
if vad.route != Some(route) {
vad.gate.reset();
vad.route = Some(route);
}
let decision = vad.gate.push_captured(frame);
let held = if decision == Decision::Start { vad.gate.take_captured_preroll(&mut self.preroll_buf) } else { 0 };
match decision {
Decision::Hold => {}
Decision::Start => {
for i in 0..held {
let Some(earlier) = self.preroll_buf[i].take() else { continue; };
if earlier.capture_epoch != self.audio_in.epoch() || earlier.connection_generation != self.audio_in.generation() { return; }
if !self.audio_in.validate(&earlier) { continue; }
if !self.tx_send(&earlier, tx_codec, quality, None).await {
return;
}
}
self.tx_send(frame, tx_codec, quality, None).await;
}
Decision::Send => {
self.tx_send(frame, tx_codec, quality, None).await;
}
Decision::SendAndEnd => {
if self.tx_send(frame, tx_codec, quality, None).await {
self.end_spurt().await;
}
}
}
}
/// Encodes and sends one frame as ordinary voice (`whisper` = `None`) or to the whisper route of that
/// epoch; returns false if it could not be sent (reported once per burst; whisper drops are silent).
async fn tx_send(&mut self, frame: &CapturedFrame, tx_codec: TxCodec, quality: u8, whisper: Option<u32>) -> bool {
if !self.audio_in.validate(frame) { return false; }
if self.tx.transmitting && self.whisper.spurt() != whisper {
// The open transmission belongs to another route and ends there before this one starts.
self.end_spurt().await;
}
let Some(c) = self.conn.as_mut().filter(|c| c.connected()) else { return false };
let generation = c.generation;
if let Some(epoch) = whisper {
let usable = c.con.get_state().is_ok_and(|book| self.whisper.route_for_send(epoch, generation, book).is_some());
if !usable {
// Released, replaced, cleared, other connection, or every target left: dropped, never
// sent anywhere else.
debug!(epoch, "whisper frame without an active route dropped");
self.end_spurt().await;
return false;
}
}
if !self.tx.encoder.as_ref().is_some_and(|e| e.matches(tx_codec, quality)) {
if let (true, Some(old)) = (self.tx.transmitting, &self.tx.encoder) {
let _ = c.con.send_audio(audio::end_of_voice(old.codec()));
let end = match self.whisper.spurt() {
None => Some(audio::end_of_voice(old.codec())),
Some(epoch) => self
.whisper
.route_mut(epoch, generation)
.filter(|r| !r.is_empty())
.map(|r| audio::end_of_whisper(old.codec(), r)),
};
if let Some(end) = end {
let _ = c.con.send_audio(end);
}
}
match TxEncoder::new(tx_codec, quality) {
Ok(e) => self.tx.encoder = Some(e),
Err(e) => {
return self.report_once(ErrorObj::new(ErrorCode::AudioCodec, format!("creating Opus encoder: {e}"))).await;
self.report_once(ErrorObj::new(ErrorCode::AudioCodec, format!("creating Opus encoder: {e}"))).await;
return false;
}
}
}
let encoder = self.tx.encoder.as_mut().expect("set above");
let packet = match encoder.encode(frame) {
Ok(p) => p,
Err(e) => return self.report_once(ErrorObj::new(ErrorCode::AudioCodec, format!("Opus encode failed: {e}"))).await,
};
if let Err(e) = c.con.send_audio(packet) {
return self.report_once(lib_error(ErrorCode::Io, &e)).await;
let route = whisper.and_then(|epoch| self.whisper.route_mut(epoch, generation));
let sent = self.audio_in.with_valid_frame(frame, || {
let packet = encoder.encode_to(&frame.pcm, route)
.map_err(|e| ErrorObj::new(ErrorCode::AudioCodec, format!("Opus encode failed: {e}")))?;
if !self.audio_in.validate(frame) { return Ok(false); }
let metadata = tsclientlib::AudioSendMetadata { captured_at: frame.captured_at,
connection_generation: frame.connection_generation, capture_epoch: frame.capture_epoch };
c.con.send_audio_guarded(packet, metadata, self.audio_in.clone()).map_err(|e| lib_error(ErrorCode::Io, &e))?;
Ok(true)
});
match sent {
Some(Ok(true)) => {},
Some(Err(error)) => { self.report_once(error).await; return false; },
_ => return false,
}
if let Some(r) = self.rec.as_mut() {
r.capture(&frame.pcm);
}
if !self.tx.transmitting {
self.tx.transmitting = true;
self.whisper.set_spurt(whisper);
self.emit_audio_state().await;
}
true
}
fn vad_reset(&mut self) {
if let Some(state) = self.vad.as_mut() {
state.gate.reset();
state.route = None;
}
}
async fn tx_end(&mut self) {
self.tx.burst_open = false;
self.tx.reported = false;
/// Ends the current talk spurt (end-of-voice packet, `transmitting: false`) if one is open. A whisper
/// spurt ends with an empty whisper packet to the same targets, never with ordinary voice.
async fn end_spurt(&mut self) {
if !self.tx.transmitting {
return;
}
self.tx.transmitting = false;
let spurt = self.whisper.take_spurt();
if let (Some(c), Some(enc)) = (self.conn.as_mut(), &self.tx.encoder) {
if c.connected() {
if let Err(e) = c.con.send_audio(audio::end_of_voice(enc.codec())) {
warn!(%e, "sending end of voice failed");
let end = match spurt {
None => Some(audio::end_of_voice(enc.codec())),
// A cleared route has nobody left to tell.
Some(epoch) => self
.whisper
.route_mut(epoch, c.generation)
.filter(|r| !r.is_empty())
.map(|r| audio::end_of_whisper(enc.codec(), r)),
};
if let Some(end) = end {
if let Err(e) = c.con.send_audio(end) {
warn!(%e, "sending end of voice failed");
}
}
}
}
self.emit_audio_state().await;
}
/// The renderer stopped sending (audio_end, mute, deafen, disconnect, capture stopped, timeout).
async fn tx_end(&mut self) {
self.tx.burst_open = false;
self.tx.reported = false;
self.vad_reset();
self.end_spurt().await;
}
async fn on_tick(&mut self) {
// Recording writer state is polled even while disconnected (finishing files).
self.recording_poll().await;
let now = Instant::now();
if self.tx.burst_open && self.tx.last_frame.is_some_and(|t| now - t > BURST_TIMEOUT) {
debug!("audio burst timed out without audio_end");
@@ -1282,30 +1644,47 @@ impl Session {
if !c.connected() {
return;
}
if c.avatar.as_ref().is_some_and(|j| now-j.started>=Duration::from_secs(15)) {
let job=c.avatar.take().unwrap();
self.out.err(&job.req,ErrorObj::new(ErrorCode::Io,"avatar transfer timed out")).await;
}
let expired: Vec<u16> =
c.ft_active.iter().filter(|(_, j)| now - j.started >= media::DEADLINE).map(|(id, _)| *id).collect();
for ftid in expired {
self.ft_finish(ftid, ErrorObj::new(ErrorCode::Io, "file transfer timed out")).await;
}
self.files_tick().await;
let Some(c) = &mut self.conn else { return };
if c.dirty && c.last_snapshot.is_none_or(|t| now - t >= SNAPSHOT_MIN_INTERVAL) {
self.emit_snapshot().await;
}
let Some(c) = &mut self.conn else { return };
let mixed = c.rx.mix(&mut self.pcm);
let book = c.con.get_state().ok();
let gains = &c.gains;
let persisted = &self.voice.volumes;
let gain = |id: u16| {
book.and_then(|b| b.clients.get(&ClientId(id)))
.and_then(|client| client.uid.as_ref())
.map_or(1.0, |uid| gains.gain(&uid.0, persisted))
};
let mixed = match self.rec.as_mut().filter(|r| r.wants_speakers()) {
Some(rec) => c.rx.mix_tapped(&mut self.pcm, gain, |id, whisper, data| rec.speaker(id, whisper, data)),
None => c.rx.mix(&mut self.pcm, gain),
};
let stopped = mixed.stopped;
let line = (!mixed.speakers.is_empty() && !self.flags.output_muted)
.then(|| audio::audio_event_line(&self.pcm, mixed.speakers));
let playback = (!mixed.speakers.is_empty() && !self.flags.output_muted)
.then(|| self.out.playback(&self.pcm, mixed.speakers));
for cid in stopped {
self.out.json(&json!({ "event": "talking", "client_id": cid, "talking": false })).await;
}
if let Some(line) = line {
if !self.out.try_line(line) && self.audio_drop_warned.is_none_or(|t| now - t >= Duration::from_secs(5)) {
self.audio_drop_warned = Some(now);
warn!("stdout is congested, dropping playback audio");
if let Some(retained) = playback {
if !retained && self.audio_drop_warned.is_none_or(|t| now - t >= Duration::from_secs(5)) {
self.audio_drop_warned = Some(now);
warn!("playback consumer is congested, dropping oldest audio");
}
}
self.recording_after_mix().await;
}
}
+147 -1
View File
@@ -5,7 +5,16 @@ use std::collections::{BTreeMap, HashMap, HashSet};
use serde_json::{json, Value};
use tsclientlib::data::{Channel, ChannelGroup, Client, Connection, ServerGroup};
use tsclientlib::{ChannelId, ClientType, GroupNamingMode, GroupType, HostBannerMode, IconId, MaxClients};
use tsclientlib::{ChannelId, ChannelType, ClientType, GroupNamingMode, GroupType, HostBannerMode, IconId, MaxClients};
fn limit(m: Option<MaxClients>) -> Value {
match m {
Some(MaxClients::Limited(n)) => Value::from(n),
Some(MaxClients::Unlimited) => json!("unlimited"),
Some(MaxClients::Inherited) => json!("inherited"),
None => Value::Null,
}
}
use crate::audio::codec_name;
use crate::rawcmd::RawNotification;
@@ -21,22 +30,61 @@ use crate::rawcmd::RawNotification;
pub struct RawExtras {
channels: HashMap<u64, ChannelExtra>,
clients: HashMap<u16, ClientExtra>,
server_properties: BTreeMap<String, String>,
/// Raw `virtualserver_capability_extensions` of `initserver`; `None` = not announced.
capability_extensions: Option<String>,
}
/// Server features exactly as the official client derives them (`hasFeature`, installed
/// `client_ui/main.js` col 2420657): a case-sensitive substring test on the raw
/// `capabilityExtensions` string. The separator is not known, so the string is never split.
const FEATURE_MARKERS: [(&str, &str); 5] = [
("chat", "MATRIXCHAT"),
("file_transfer_http", "HTTPFT"),
("file_transfer_s3", "s3"),
("stream_p2p", "STREAM_P2P"),
("stream_sfu", "STREAM_SFU"),
];
fn server_features(raw: Option<&str>) -> Value {
let mut map = serde_json::Map::new();
for (key, marker) in FEATURE_MARKERS {
map.insert(key.into(), raw.map_or(Value::Null, |r| Value::Bool(r.contains(marker))));
}
Value::Object(map)
}
#[derive(Default)]
struct ChannelExtra {
properties: BTreeMap<String, String>,
banner_url: Option<String>,
banner_mode: Option<String>,
/// Last known name and parent, kept so `server_event`s can name deleted/moved channels.
name: Option<String>,
parent: Option<u64>,
}
impl ChannelExtra {
fn merge(&mut self, item: &BTreeMap<String, String>) {
for (key, value) in item {
if key.starts_with("channel_") || matches!(key.as_str(), "cid" | "cpid") {
self.properties.insert(key.clone(), value.clone());
} else if key == "order" {
self.properties.insert("channel_order".into(), value.clone());
}
}
if let Some(u) = item.get("channel_banner_gfx_url") {
self.banner_url = non_empty(u);
}
if let Some(m) = item.get("channel_banner_mode") {
self.banner_mode = non_empty(m);
}
if let Some(n) = item.get("channel_name") {
self.name = Some(n.clone());
}
if let Some(p) = item.get("cpid").and_then(|p| p.parse().ok()) {
self.parent = Some(p);
}
}
}
@@ -48,6 +96,10 @@ struct ClientExtra {
/// Raw value when it was non-empty but no pair could be parsed.
myts_avatar_unparsed: Option<String>,
has_myts: Option<bool>,
/// Last known identity and channel, kept so `server_event`s can name clients that left.
nickname: Option<String>,
uid: Option<String>,
channel: Option<u64>,
}
impl ClientExtra {
@@ -62,9 +114,27 @@ impl ClientExtra {
if let Some(v) = item.get("client_myteamspeak_id") {
self.has_myts = Some(!v.is_empty());
}
if let Some(v) = item.get("client_nickname") {
self.nickname = Some(v.clone());
}
if let Some(v) = item.get("client_unique_identifier") {
self.uid = non_empty(v);
}
if let Some(v) = item.get("ctid").and_then(|v| v.parse().ok()) {
self.channel = Some(v);
}
}
}
/// Last known label of a client or channel (for `server_event`s).
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Label {
pub name: Option<String>,
pub uid: Option<String>,
/// Client: channel; channel: parent.
pub channel: Option<u64>,
}
const MAX_AVATAR_URL: usize = 2048;
/// Parse `client_myteamspeak_avatar`. Observed live (TS6 6.0.0-beta13.1):
@@ -88,6 +158,11 @@ pub fn parse_myts_avatar(raw: &str) -> Vec<(u32, String)> {
fn non_empty(s: &str) -> Option<String> { (!s.is_empty()).then(|| s.to_owned()) }
impl RawExtras {
pub fn server_properties(&self) -> &BTreeMap<String, String> { &self.server_properties }
/// Ordinary channel fields observed on this connection, not a ServerQuery snapshot.
pub fn channel_properties(&self, channel_id: u64) -> Option<&BTreeMap<String, String>> {
self.channels.get(&channel_id).map(|c| &c.properties)
}
/// myTeamSpeak avatar URLs of a client (`(variant, url)`), empty if none.
pub fn client_myts_avatars(&self, client_id: u16) -> &[(u32, String)] {
self.clients.get(&client_id).map_or(&[], |e| e.myts_avatars.as_slice())
@@ -98,12 +173,41 @@ impl RawExtras {
self.channels.get(&channel_id).and_then(|e| e.banner_url.as_deref())
}
/// Last known nickname/UID/channel of a client (also right before it leaves the view).
pub fn client_label(&self, client_id: u16) -> Label {
self.clients.get(&client_id).map_or_else(Label::default, |e| Label {
name: e.nickname.clone(),
uid: e.uid.clone(),
channel: e.channel,
})
}
/// Last known name/parent of a channel (also right before it is deleted).
pub fn channel_label(&self, channel_id: u64) -> Label {
self.channels.get(&channel_id).map_or_else(Label::default, |e| Label {
name: e.name.clone(),
uid: None,
channel: e.parent,
})
}
/// Apply a tapped command. Returns true if it concerned tracked objects.
pub fn apply(&mut self, raw: &RawNotification) -> bool {
let cids = || raw.items.iter().filter_map(|i| Some((i.get("cid")?.parse::<u64>().ok()?, i)));
let clids = || raw.items.iter().filter_map(|i| Some((i.get("clid")?.parse::<u16>().ok()?, i)));
let mut changed = false;
match raw.name.as_str() {
"initserver" | "notifyserverupdated" | "notifyserveredited" => {
for item in &raw.items {
for (key, value) in item {
if key.starts_with("virtualserver_") { self.server_properties.insert(key.clone(), value.clone()); }
}
if let Some(value) = item.get("virtualserver_capability_extensions") {
self.capability_extensions = Some(value.clone());
}
}
changed = true;
}
"channellist" | "notifychannelcreated" => {
for (cid, item) in cids() {
let mut e = ChannelExtra::default();
@@ -142,6 +246,23 @@ impl RawExtras {
changed |= self.clients.remove(&clid).is_some();
}
}
"notifyclientmoved" => {
// `ctid` is a shared argument: it may only be in the first entry.
let target = raw.items.first().and_then(|i| i.get("ctid")).and_then(|v| v.parse().ok());
for (clid, item) in clids() {
let to = item.get("ctid").and_then(|v| v.parse().ok()).or(target);
if let (Some(e), Some(to)) = (self.clients.get_mut(&clid), to) {
e.channel = Some(to);
}
}
}
"notifychannelmoved" => {
for (cid, item) in cids() {
if let Some(e) = self.channels.get_mut(&cid) {
e.merge(item);
}
}
}
_ => {}
}
changed
@@ -222,6 +343,20 @@ fn channel_json(c: &Channel, depth: usize, extras: &RawExtras) -> Value {
"banner_url": extra.and_then(|e| e.banner_url.clone()),
"banner_mode": extra.and_then(|e| e.banner_mode.as_deref()).and_then(|m| m.parse::<i64>().ok()),
"depth": depth,
// Edit-dialog state (book values; null = not sent by the server).
"channel_type": match c.channel_type {
ChannelType::Permanent => "permanent",
ChannelType::SemiPermanent => "semi_permanent",
ChannelType::Temporary => "temporary",
},
"max_clients_limit": limit(c.max_clients),
"max_family_clients_limit": limit(c.max_family_clients),
"codec_latency_factor": c.codec_latency_factor,
"is_unencrypted": c.is_unencrypted,
"delete_delay_s": c.delete_delay.map(|d| d.whole_seconds()),
"phonetic_name": c.phonetic_name,
"forced_silence": c.forced_silence,
"subscribed": c.subscribed,
})
}
@@ -244,6 +379,10 @@ fn client_json(c: &Client, own: u16, extras: &RawExtras) -> Value {
"away_message": c.away_message,
"talk_power": c.talk_power,
"is_talker": c.talk_power_granted,
"talk_request": c.talk_power_request.as_ref().map(|r| json!({
"time_unix": r.time.unix_timestamp(),
"message": non_empty(&r.message),
})),
"is_channel_commander": c.is_channel_commander,
"is_priority_speaker": c.is_priority_speaker,
"is_recording": c.is_recording,
@@ -343,6 +482,8 @@ pub fn build(book: &Connection, rev: u64, extras: &RawExtras) -> Value {
"event": "snapshot",
"rev": rev,
"server": {
// Virtual server unique identifier (base64 of the server key hash, like client UIDs).
"uid": s.public_key.get_uid(),
"name": s.name,
"welcome_message": s.welcome_message,
"platform": s.platform,
@@ -357,6 +498,11 @@ pub fn build(book: &Connection, rev: u64, extras: &RawExtras) -> Value {
"hostbutton_tooltip": non_empty(&s.hostbutton_tooltip),
"default_server_group": s.default_server_group.0,
"default_channel_group": s.default_channel_group.0,
"default_channel_admin_group": extras.server_properties.get("virtualserver_default_channel_admin_group").and_then(|value| value.parse::<u64>().ok()),
// Raw string or null when the server did not announce it; features are null then too
// (unknown), never false.
"capability_extensions": extras.capability_extensions,
"features": server_features(extras.capability_extensions.as_deref()),
},
"own_client_id": own,
"own_channel_id": own_channel,
+38 -62
View File
@@ -3,73 +3,41 @@
use std::io::{BufRead, BufReader, Read};
use std::sync::Arc;
use serde::Serialize;
use tokio::io::{AsyncWriteExt, BufWriter};
use tokio::sync::mpsc;
use tracing::{error, warn};
use crate::audio::{AudioIn, AudioInQueue};
use crate::audio::{AudioIn, AudioInQueue, CapturedFrame};
use crate::protocol::{self, ErrorCode, ErrorObj, Input, MAX_LINE_BYTES};
use crate::output::PlaybackReceiver;
/// Control lines (responses/events) are awaited; audio lines are dropped when the pipe is full.
const OUT_QUEUE: usize = 1024;
#[derive(Clone)]
pub struct Out {
tx: mpsc::Sender<String>,
}
impl Out {
pub fn new() -> (Self, mpsc::Receiver<String>) {
let (tx, rx) = mpsc::channel(OUT_QUEUE);
(Self { tx }, rx)
}
pub async fn line(&self, line: String) {
if self.tx.send(line).await.is_err() {
error!("stdout writer is gone");
}
}
pub async fn json<T: Serialize>(&self, value: &T) {
match serde_json::to_string(value) {
Ok(s) => self.line(s).await,
Err(e) => error!(%e, "failed to serialize output"),
}
}
/// Non-blocking send for high-rate audio. Returns false if dropped.
pub fn try_line(&self, line: String) -> bool { self.tx.try_send(line).is_ok() }
pub async fn ok(&self, id: &str, result: serde_json::Value) {
self.json(&serde_json::json!({ "id": id, "ok": true, "result": result })).await
}
pub async fn err(&self, id: &str, error: ErrorObj) {
self.json(&serde_json::json!({ "id": id, "ok": false, "error": error })).await
}
pub async fn error_event(&self, error: ErrorObj) {
self.json(&serde_json::json!({ "event": "error", "error": error })).await
}
}
pub async fn run_writer(mut rx: mpsc::Receiver<String>) {
let mut out = BufWriter::new(tokio::io::stdout());
while let Some(first) = rx.recv().await {
let mut line = Some(first);
while let Some(l) = line {
if out.write_all(l.as_bytes()).await.is_err() || out.write_all(b"\n").await.is_err() {
error!("stdout closed");
return;
}
line = rx.try_recv().ok();
}
if out.flush().await.is_err() {
error!("stdout closed");
return;
}
}
/// The diagnostic CLI alone serializes native events and PCM onto stdout.
pub async fn run_writer(mut rx: mpsc::Receiver<serde_json::Value>, mut playback: PlaybackReceiver) {
let mut out = BufWriter::new(tokio::io::stdout());
let mut control_open = true;
let mut audio_open = true;
while control_open || audio_open {
let line = tokio::select! {
biased;
value = rx.recv(), if control_open => match value {
Some(value) => match serde_json::to_string(&value) {
Ok(line) => Some(line),
Err(error) => { error!(%error, "cannot serialize CLI output"); None }
},
None => { control_open = false; None }
},
frame = playback.recv(), if audio_open => match frame {
Some(frame) => Some(crate::audio::audio_event_line(&frame.pcm, &frame.speakers)),
None => { audio_open = false; None }
},
};
if let Some(line) = line {
if out.write_all(line.as_bytes()).await.is_err() || out.write_all(b"\n").await.is_err() || out.flush().await.is_err() {
error!("stdout closed");
return;
}
}
}
}
/// Blocking stdin reader (runs on its own thread). Lines longer than [`MAX_LINE_BYTES`] are
@@ -131,7 +99,15 @@ pub fn run_reader(input: impl Read, cmds: mpsc::Sender<Input>, audio: Arc<AudioI
input
};
match input {
Input::AudioFrame(frame) => audio.push(AudioIn::Frame(frame)),
Input::AudioFrame(f) => {
audio.try_push(CapturedFrame {
pcm: *f.pcm,
captured_at: std::time::Instant::now(),
capture_epoch: audio.epoch(),
connection_generation: audio.generation(),
whisper: f.whisper,
});
},
Input::AudioEnd => audio.push(AudioIn::End),
other => {
if cmds.blocking_send(other).is_err() {
+21
View File
@@ -0,0 +1,21 @@
//! Test-only: run the current test binary again as a child process.
//!
//! Cross-target unit tests run under user-mode qemu without binfmt (CI), where the kernel cannot execute
//! the target ELF directly. There the emulator and the target sysroot are named explicitly by
//! `TEAMSPEACH_TEST_QEMU` and `TEAMSPEACH_TEST_QEMU_SYSROOT`, and the child runs as
//! `<qemu> -L <sysroot> <test binary> <args>`. Without `TEAMSPEACH_TEST_QEMU` the binary runs directly.
/// Program and leading arguments that execute the current test binary; append the test arguments.
pub fn self_invocation() -> (String, Vec<String>) {
let exe = std::env::current_exe().expect("current test executable")
.into_os_string().into_string().expect("UTF-8 test executable path");
match std::env::var("TEAMSPEACH_TEST_QEMU") {
Ok(qemu) => {
let sysroot = std::env::var("TEAMSPEACH_TEST_QEMU_SYSROOT")
.expect("TEAMSPEACH_TEST_QEMU_SYSROOT must name the target sysroot when TEAMSPEACH_TEST_QEMU is set");
(qemu, vec!["-L".into(), sysroot, exe])
}
Err(std::env::VarError::NotPresent) => (exe, Vec::new()),
Err(e) => panic!("TEAMSPEACH_TEST_QEMU: {e}"),
}
}
+996
View File
@@ -0,0 +1,996 @@
//! Voice activation: decides which captured 20 ms frames are sent when the user chose "voice activation".
//!
//! Three detectors follow the official TS6 VAD modes (client_ui/main.js `vadModesForSelect`):
//! - Automatic (TS6 `Likelihood`): earshot (pure Rust, MIT OR Apache-2.0), a small embedded neural network
//! that returns a voice probability for every 16 ms window of 16 kHz mono audio. It is a statistical
//! detector, not a speech recogniser: loud speech-like noise can open the gate and quiet speech under
//! heavy noise can be missed.
//! - Volume gate (TS6 `Power`): the frame's RMS level against the user's level in dB (-50..=+50).
//! - Hybrid (TS6 `LikelihoodAndPower`): speech must be detected AND loud enough.
//! TS6's detectors are native code that is not visible; these are our own implementations with the same
//! modes and level range, not bit-identical ones. The level is measured as frame RMS in dBFS (full-scale
//! sine ≈ -3 dB), so levels above 0 dB can never open the gate; TS6's native level reference is unknown.
//! The input has already passed Chromium's WebRTC capture processing (noise suppression, echo
//! cancellation, gain control as configured by the user) and TeamsPeach's typing attenuation.
//!
//! All buffers are fixed-size and allocated once when the gate is created; processing a frame does not
//! allocate.
use earshot::Detector;
use crate::audio::CapturedFrame;
use crate::protocol::{Frame, FRAME_SAMPLES};
/// Frames kept from before the onset so the start of a word is not cut off (5 × 20 ms = 100 ms).
pub const PREROLL_FRAMES: usize = 5;
/// Frames sent after the last voiced frame so word endings and short pauses are kept (400 ms).
pub const HANGOVER_FRAMES: u32 = 20;
/// While a spurt is open, a window keeps it open at this much below the opening threshold.
pub const RELEASE_MARGIN: f32 = 0.15;
/// Consecutive voiced detector windows (16 ms each) needed to open the gate.
pub const ONSET_WINDOWS: u32 = 3;
/// While a spurt is open, the volume gate keeps it open down to this much below the level (hysteresis).
pub const LEVEL_RELEASE_MARGIN_DB: f32 = 3.0;
/// Official TS6 VAD level range (slider min/max) and default.
pub const MIN_LEVEL_DB: f32 = -50.0;
pub const MAX_LEVEL_DB: f32 = 50.0;
pub const DEFAULT_LEVEL_DB: f32 = -30.0;
/// Frames after a reset during which the gate cannot open: a freshly reset network scores the first
/// ~150 ms of any input (noise, clicks) higher than it settles to. Startup audio is
/// held, but the capture-age limit still applies before network transmission.
pub const WARMUP_FRAMES: u32 = 10;
/// Frames held at most: the whole warm-up plus the normal preroll (300 ms).
/// The consumer must reject expired held frames, including this first spurt.
pub const MAX_PREROLL_FRAMES: usize = WARMUP_FRAMES as usize + PREROLL_FRAMES;
/// Detector input: 16 ms at 16 kHz.
const WINDOW: usize = 256;
/// 48 kHz → 16 kHz.
const DECIMATION: usize = 3;
const OUT_PER_FRAME: usize = FRAME_SAMPLES / DECIMATION;
/// Anti-aliasing low-pass in front of the decimation (odd length, linear phase).
const TAPS: usize = 63;
const HISTORY: usize = TAPS - 1;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Sensitivity {
High,
Normal,
Low,
}
impl Sensitivity {
/// Voice probability a detector window needs to count as voiced.
pub fn threshold(self) -> f32 {
match self {
Sensitivity::High => 0.45,
Sensitivity::Normal => 0.6,
Sensitivity::Low => 0.75,
}
}
pub fn name(self) -> &'static str {
match self {
Sensitivity::High => "high",
Sensitivity::Normal => "normal",
Sensitivity::Low => "low",
}
}
}
/// Which detector decides (TS6 VadMode; `LikelihoodAndPowerFuzzy` exists in the official enum but is not
/// offered by its UI and is not implemented here).
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum GateMode {
Automatic(Sensitivity),
VolumeGate { level_db: f32 },
Hybrid { sensitivity: Sensitivity, level_db: f32 },
}
impl From<Sensitivity> for GateMode {
fn from(s: Sensitivity) -> Self { GateMode::Automatic(s) }
}
impl GateMode {
pub fn detector_name(self) -> &'static str {
match self {
GateMode::Automatic(_) => "automatic",
GateMode::VolumeGate { .. } => "volume_gate",
GateMode::Hybrid { .. } => "hybrid",
}
}
fn sensitivity(self) -> Option<Sensitivity> {
match self {
GateMode::Automatic(s) | GateMode::Hybrid { sensitivity: s, .. } => Some(s),
GateMode::VolumeGate { .. } => None,
}
}
fn level_db(self) -> Option<f32> {
match self {
GateMode::VolumeGate { level_db } | GateMode::Hybrid { level_db, .. } => Some(level_db),
GateMode::Automatic(_) => None,
}
}
/// Frames after a reset during which the gate cannot open (detector warm-up; none for level only).
fn warmup(self) -> u32 {
if self.sensitivity().is_some() { WARMUP_FRAMES } else { 0 }
}
}
/// RMS level of a frame in dBFS (-inf for digital silence).
pub fn frame_level_db(frame: &Frame) -> f32 {
let sum: f64 = frame.iter().map(|s| {
let x = f64::from(*s) / 32_768.0;
x * x
}).sum();
(10.0 * (sum / FRAME_SAMPLES as f64).log10()) as f32
}
/// What to do with the frame just pushed.
#[derive(Debug, PartialEq, Eq)]
pub enum Decision {
/// Not speech: keep it only as possible preroll.
Hold,
/// Speech starts: send the returned preroll frames (oldest first), then the current frame.
Start,
/// Inside a talk spurt: send the current frame.
Send,
/// Send the current frame, then end the talk spurt (hangover ran out).
SendAndEnd,
}
/// 48 kHz → 16 kHz decimator whose filter history carries over between 960-sample frames.
struct Decimator {
coeffs: [f32; TAPS],
/// The last `HISTORY` input samples of the previous frame, then the current frame.
buf: [f32; HISTORY + FRAME_SAMPLES],
}
impl Decimator {
fn new() -> Self {
// Windowed sinc (Blackman), cut-off 7 kHz at 48 kHz, unity gain at DC.
let fc = 7_000.0_f64 / 48_000.0;
let m = (TAPS - 1) as f64;
let mut c = [0.0_f64; TAPS];
for (i, v) in c.iter_mut().enumerate() {
let x = i as f64 - m / 2.0;
let sinc = if x == 0.0 { 2.0 * fc } else { (2.0 * std::f64::consts::PI * fc * x).sin() / (std::f64::consts::PI * x) };
let w = 0.42 - 0.5 * (2.0 * std::f64::consts::PI * i as f64 / m).cos() + 0.08 * (4.0 * std::f64::consts::PI * i as f64 / m).cos();
*v = sinc * w;
}
let sum: f64 = c.iter().sum();
let mut coeffs = [0.0_f32; TAPS];
for (o, v) in coeffs.iter_mut().zip(c) {
*o = (v / sum) as f32;
}
Self { coeffs, buf: [0.0; HISTORY + FRAME_SAMPLES] }
}
fn reset(&mut self) { self.buf = [0.0; HISTORY + FRAME_SAMPLES]; }
/// Decimates one 20 ms frame into `out` (320 samples). The low-pass can overshoot full-scale input
/// slightly (ringing), so outputs are clamped to [-1, 1], the range the detector expects.
fn process(&mut self, frame: &Frame, out: &mut [f32; OUT_PER_FRAME]) {
for (dst, s) in self.buf[HISTORY..].iter_mut().zip(frame.iter()) {
*dst = f32::from(*s) / 32_768.0;
}
// Output k uses the TAPS inputs ending at input sample 3k (+2 to stay causal within the frame).
for (k, o) in out.iter_mut().enumerate() {
let end = HISTORY + k * DECIMATION + (DECIMATION - 1);
let window = &self.buf[end + 1 - TAPS..=end];
let y: f32 = window.iter().zip(self.coeffs.iter()).map(|(x, c)| x * c).sum();
*o = y.clamp(-1.0, 1.0);
}
self.buf.copy_within(FRAME_SAMPLES.., 0);
}
}
#[derive(Clone, Copy)]
struct CaptureMetadata {
captured_at: std::time::Instant,
connection_generation: u64,
capture_epoch: u64,
whisper: Option<u32>,
}
pub struct VoiceGate {
detector: Box<Detector>,
decimator: Decimator,
threshold: f32,
mode: GateMode,
/// 16 kHz samples waiting for a full detector window.
pending: [f32; WINDOW],
pending_len: usize,
resampled: [f32; OUT_PER_FRAME],
voiced_run: u32,
/// Frames left before the spurt ends; 0 = idle.
hangover: u32,
preroll: [Frame; MAX_PREROLL_FRAMES],
preroll_metadata: [Option<CaptureMetadata>; MAX_PREROLL_FRAMES],
capture_context: Option<(u64, u64, Option<u32>)>,
preroll_start: usize,
preroll_len: usize,
/// Frames left in the post-reset warm-up.
warmup: u32,
/// True from a reset until the first spurt opens: that spurt gets every frame held since the reset.
since_reset: bool,
}
impl VoiceGate {
pub fn new(mode: impl Into<GateMode>) -> Self {
let mode = mode.into();
let mut gate = Self {
detector: Detector::default_boxed(),
decimator: Decimator::new(),
threshold: mode.sensitivity().unwrap_or(Sensitivity::Normal).threshold(),
mode,
pending: [0.0; WINDOW],
pending_len: 0,
resampled: [0.0; OUT_PER_FRAME],
voiced_run: 0,
hangover: 0,
preroll: [[0; FRAME_SAMPLES]; MAX_PREROLL_FRAMES],
preroll_metadata: [None; MAX_PREROLL_FRAMES],
capture_context: None,
preroll_start: 0,
preroll_len: 0,
warmup: WARMUP_FRAMES,
since_reset: true,
};
gate.reset();
gate
}
#[cfg(test)]
pub fn sensitivity(&self) -> Sensitivity { self.mode.sensitivity().unwrap_or(Sensitivity::Normal) }
pub fn mode(&self) -> GateMode { self.mode }
/// Changes the detector or its parameters. A change of detector kind resets the gate (its held audio
/// was judged by another rule); a changed sensitivity or level applies from the next frame.
pub fn set_mode(&mut self, mode: GateMode) {
let kind_changed = std::mem::discriminant(&mode) != std::mem::discriminant(&self.mode);
self.mode = mode;
if let Some(s) = mode.sensitivity() {
self.threshold = s.threshold();
}
if kind_changed {
self.reset();
}
}
#[cfg(test)]
pub fn is_active(&self) -> bool { self.hangover > 0 }
/// Forgets everything heard so far: detector state, filter history, preroll and any open spurt.
/// Called at privacy and routing boundaries only (mode change, mute/deafen, capture end, disconnect,
/// channel/codec/permission change), never at the natural end of a spurt.
pub fn reset(&mut self) {
self.detector.reset();
self.warmup = self.mode.warmup();
self.since_reset = true;
self.decimator.reset();
self.pending_len = 0;
self.voiced_run = 0;
self.hangover = 0;
self.preroll_len = 0;
self.preroll_start = 0;
self.preroll_metadata.fill(None);
self.capture_context = None;
}
/// Runs the detector over one frame and returns whether any 16 ms window in it was voiced and
/// whether the onset condition is met. While a spurt is open, windows count as voiced down to
/// [`RELEASE_MARGIN`] below the threshold (hysteresis), so quieter syllables do not end it.
fn detect(&mut self, frame: &Frame) -> (bool, bool) {
if self.mode.sensitivity().is_none() {
return (false, false);
}
self.decimator.process(frame, &mut self.resampled);
let keep = if self.hangover > 0 { self.threshold - RELEASE_MARGIN } else { self.threshold };
let mut voiced = false;
let mut onset = false;
let mut i = 0;
while i < OUT_PER_FRAME {
let take = (WINDOW - self.pending_len).min(OUT_PER_FRAME - i);
self.pending[self.pending_len..self.pending_len + take].copy_from_slice(&self.resampled[i..i + take]);
self.pending_len += take;
i += take;
if self.pending_len == WINDOW {
self.pending_len = 0;
let score = self.detector.predict_f32(&self.pending);
if score >= keep {
voiced = true;
}
if score >= self.threshold {
self.voiced_run = (self.voiced_run + 1).min(ONSET_WINDOWS);
if self.voiced_run >= ONSET_WINDOWS {
onset = true;
}
} else {
self.voiced_run = 0;
}
}
}
(voiced, onset)
}
/// Level-gate verdict for a frame: (keeps an open spurt, may open one).
fn level(&self, frame: &Frame) -> (bool, bool) {
let Some(level) = self.mode.level_db() else { return (true, true) };
let db = frame_level_db(frame);
(db >= level - LEVEL_RELEASE_MARGIN_DB, db >= level)
}
/// Classifies `frame`. On [`Decision::Start`], the caller sends [`VoiceGate::take_preroll`] and then
/// `frame`; the current frame is never part of the preroll.
pub fn push(&mut self, frame: &Frame) -> Decision {
// Raw PCM is for detector analysis, never a replacement for capture tags.
if self.capture_context.is_some() { self.reset(); }
self.classify(frame)
}
/// Classify captured PCM without losing its original timestamp or routing tags.
/// A new boundary resets detector state as well as its held frames. Validation
/// remains the consumer's responsibility, both here and before every actual send.
pub fn push_captured(&mut self, frame: &CapturedFrame) -> Decision {
let context = (frame.connection_generation, frame.capture_epoch, frame.whisper);
if self.capture_context != Some(context) { self.reset(); }
self.capture_context = Some(context);
let slot = (self.preroll_start + self.preroll_len) % MAX_PREROLL_FRAMES;
let decision = self.classify(&frame.pcm);
if decision == Decision::Hold {
self.preroll_metadata[slot] = Some(CaptureMetadata {
captured_at: frame.captured_at,
connection_generation: frame.connection_generation,
capture_epoch: frame.capture_epoch,
whisper: frame.whisper,
});
}
decision
}
fn classify(&mut self, frame: &Frame) -> Decision {
let (keep_level, open_level) = self.level(frame);
let (voiced, onset) = match self.mode {
GateMode::VolumeGate { .. } => (keep_level, open_level),
GateMode::Automatic(_) => self.detect(frame),
GateMode::Hybrid { .. } => {
let (voiced, onset) = self.detect(frame);
(voiced && keep_level, onset && open_level)
}
};
if self.hangover > 0 {
if voiced {
self.hangover = HANGOVER_FRAMES;
return Decision::Send;
}
self.hangover -= 1;
return if self.hangover == 0 { Decision::SendAndEnd } else { Decision::Send };
}
if self.warmup > 0 {
self.warmup -= 1;
} else if onset {
self.hangover = HANGOVER_FRAMES;
return Decision::Start;
}
self.remember(frame);
Decision::Hold
}
fn remember(&mut self, frame: &Frame) {
let slot = (self.preroll_start + self.preroll_len) % MAX_PREROLL_FRAMES;
self.preroll[slot] = *frame;
self.preroll_metadata[slot] = None;
if self.preroll_len < MAX_PREROLL_FRAMES {
self.preroll_len += 1;
} else {
self.preroll_start = (self.preroll_start + 1) % MAX_PREROLL_FRAMES;
}
}
/// Copies the frames to send before the current one into `out`, oldest first, and empties the
/// preroll: everything since the reset for the first spurt after it (at most 300 ms), otherwise the
/// last [`PREROLL_FRAMES`]. Returns how many were copied.
pub fn take_preroll(&mut self, out: &mut [Frame; MAX_PREROLL_FRAMES]) -> usize {
let keep = if self.since_reset { self.preroll_len } else { self.preroll_len.min(PREROLL_FRAMES) };
let skip = self.preroll_len - keep;
for (i, dst) in out.iter_mut().take(keep).enumerate() {
*dst = self.preroll[(self.preroll_start + skip + i) % MAX_PREROLL_FRAMES];
}
self.preroll_start = 0;
self.preroll_len = 0;
self.preroll_metadata.fill(None);
self.since_reset = false;
keep
}
/// Drain original capture envelopes, oldest first, without per-frame allocation.
/// Output entries beyond the returned length are cleared. Even a valid current
/// frame does not authorize these frames: check each one's age/epoch/generation
/// with the input queue immediately before encoding and network enqueue.
pub fn take_captured_preroll(&mut self, out: &mut [Option<CapturedFrame>; MAX_PREROLL_FRAMES]) -> usize {
let keep = if self.since_reset { self.preroll_len } else { self.preroll_len.min(PREROLL_FRAMES) };
let skip = self.preroll_len - keep;
out.fill(None);
let mut written = 0;
for i in 0..keep {
let slot = (self.preroll_start + skip + i) % MAX_PREROLL_FRAMES;
if let Some(metadata) = self.preroll_metadata[slot].take() {
out[written] = Some(CapturedFrame {
pcm: self.preroll[slot],
captured_at: metadata.captured_at,
connection_generation: metadata.connection_generation,
capture_epoch: metadata.capture_epoch,
whisper: metadata.whisper,
});
written += 1;
}
}
self.preroll_start = 0;
self.preroll_len = 0;
self.preroll_metadata.fill(None);
self.since_reset = false;
written
}
}
#[cfg(test)]
pub mod tests {
use super::*;
fn captured_frame(queue: &crate::audio::AudioInQueue, sample: i16) -> CapturedFrame {
CapturedFrame {
pcm: [sample; FRAME_SAMPLES],
captured_at: std::time::Instant::now(),
connection_generation: queue.generation(),
capture_epoch: queue.epoch(),
whisper: None,
}
}
#[test]
fn captured_preroll_preserves_original_age_and_routing() {
let queue = crate::audio::AudioInQueue::new();
queue.set_generation(9);
let mut gate = VoiceGate::new(GateMode::VolumeGate { level_db: -30.0 });
let mut old = captured_frame(&queue, 1);
old.captured_at -= std::time::Duration::from_millis(600);
old.whisper = Some(7);
assert_eq!(gate.push_captured(&old), Decision::Hold);
let mut onset = captured_frame(&queue, 20_000);
onset.whisper = Some(7);
assert_eq!(gate.push_captured(&onset), Decision::Start);
let mut held = std::array::from_fn(|_| None);
assert_eq!(gate.take_captured_preroll(&mut held), 1);
let earlier = held[0].as_ref().unwrap();
assert_eq!(earlier.pcm, old.pcm);
assert_eq!(earlier.captured_at, old.captured_at);
assert_eq!(earlier.connection_generation, old.connection_generation);
assert_eq!(earlier.capture_epoch, old.capture_epoch);
assert_eq!(earlier.whisper, Some(7));
assert!(!queue.validate(earlier), "opening VAD cannot renew an expired capture");
assert!(held[1..].iter().all(Option::is_none));
assert_eq!(gate.take_captured_preroll(&mut held), 0);
assert!(held.iter().all(Option::is_none));
}
#[test]
fn captured_preroll_is_revoked_by_every_routing_boundary() {
let queue = crate::audio::AudioInQueue::new();
for boundary in 0..3 {
let mut gate = VoiceGate::new(GateMode::VolumeGate { level_db: -30.0 });
let old = captured_frame(&queue, 1);
assert_eq!(gate.push_captured(&old), Decision::Hold);
let mut next = captured_frame(&queue, 20_000);
match boundary {
0 => next.capture_epoch += 1,
1 => next.connection_generation += 1,
_ => next.whisper = Some(3),
}
assert_eq!(gate.push_captured(&next), Decision::Start);
let mut held = std::array::from_fn(|_| None);
assert_eq!(gate.take_captured_preroll(&mut held), 0);
gate.reset();
assert!(gate.capture_context.is_none());
assert!(gate.preroll_metadata.iter().all(Option::is_none));
}
}
#[test]
fn captured_preroll_ring_keeps_metadata_with_its_pcm() {
let queue = crate::audio::AudioInQueue::new();
let mut gate = VoiceGate::new(GateMode::VolumeGate { level_db: -30.0 });
let start = std::time::Instant::now();
for i in 0..MAX_PREROLL_FRAMES + 5 {
let mut frame = captured_frame(&queue, i as i16);
frame.captured_at = start + std::time::Duration::from_millis(i as u64 * 20);
assert_eq!(gate.push_captured(&frame), Decision::Hold);
}
assert_eq!(gate.push_captured(&captured_frame(&queue, 20_000)), Decision::Start);
let mut held = std::array::from_fn(|_| None);
assert_eq!(gate.take_captured_preroll(&mut held), MAX_PREROLL_FRAMES);
for (i, frame) in held.iter().enumerate() {
let frame = frame.as_ref().unwrap();
assert_eq!(frame.pcm[0], (i + 5) as i16);
assert_eq!(frame.captured_at, start + std::time::Duration::from_millis((i + 5) as u64 * 20));
}
queue.invalidate();
assert!(held.iter().all(|frame| !queue.validate(frame.as_ref().unwrap())));
}
#[test]
fn raw_analysis_frames_cannot_inherit_capture_authorization() {
let queue = crate::audio::AudioInQueue::new();
let mut gate = VoiceGate::new(GateMode::VolumeGate { level_db: -30.0 });
assert_eq!(gate.push_captured(&captured_frame(&queue, 1)), Decision::Hold);
assert_eq!(gate.push(&[2; FRAME_SAMPLES]), Decision::Hold);
assert_eq!(gate.push(&[20_000; FRAME_SAMPLES]), Decision::Start);
let mut held = std::array::from_fn(|_| None);
assert_eq!(gate.take_captured_preroll(&mut held), 0);
}
/// Real speech: 4 s of a public-domain LibriVox reading (see tests/fixtures/README.md), 48 kHz mono s16le WAV.
pub fn speech_frames() -> Vec<Frame> {
let wav = include_bytes!("../tests/fixtures/speech-librivox-48k.wav");
let data = wav_data(wav);
data.chunks_exact(FRAME_SAMPLES * 2)
.map(|c| {
let mut f = [0i16; FRAME_SAMPLES];
for (s, b) in f.iter_mut().zip(c.chunks_exact(2)) {
*s = i16::from_le_bytes([b[0], b[1]]);
}
f
})
.collect()
}
fn wav_data(wav: &[u8]) -> &[u8] {
assert_eq!(&wav[0..4], b"RIFF");
assert_eq!(&wav[8..12], b"WAVE");
let mut i = 12;
while i + 8 <= wav.len() {
let id = &wav[i..i + 4];
let len = u32::from_le_bytes([wav[i + 4], wav[i + 5], wav[i + 6], wav[i + 7]]) as usize;
if id == b"fmt " {
let fmt = &wav[i + 8..i + 8 + len];
assert_eq!(u16::from_le_bytes([fmt[0], fmt[1]]), 1, "PCM");
assert_eq!(u16::from_le_bytes([fmt[2], fmt[3]]), 1, "mono");
assert_eq!(u32::from_le_bytes([fmt[4], fmt[5], fmt[6], fmt[7]]), 48_000, "48 kHz");
assert_eq!(u16::from_le_bytes([fmt[14], fmt[15]]), 16, "16 bit");
}
if id == b"data" {
return &wav[i + 8..i + 8 + len];
}
i += 8 + len + (len & 1);
}
panic!("no data chunk");
}
/// Deterministic pseudo-random generator (xorshift) for synthetic noise.
struct Rng(u32);
impl Rng {
fn next(&mut self) -> f32 {
self.0 ^= self.0 << 13;
self.0 ^= self.0 >> 17;
self.0 ^= self.0 << 5;
(self.0 as f32 / u32::MAX as f32) * 2.0 - 1.0
}
}
fn silence(n: usize) -> Vec<Frame> { vec![[0i16; FRAME_SAMPLES]; n] }
/// Synthetic steady broadband noise (fan/hiss-like) at roughly -30 dBFS RMS.
fn steady_noise(n: usize) -> Vec<Frame> {
let mut rng = Rng(0x1234_5678);
let mut low = 0.0_f32;
(0..n)
.map(|_| {
let mut f = [0i16; FRAME_SAMPLES];
for s in f.iter_mut() {
low = 0.97 * low + 0.03 * rng.next();
*s = ((rng.next() * 0.03 + low * 0.3) * 32_767.0) as i16;
}
f
})
.collect()
}
/// Synthetic transients: a 3 ms click (keyboard/mouse-like) every 200 ms over near-silence.
fn clicks(n: usize) -> Vec<Frame> {
let mut rng = Rng(0x0bad_cafe);
(0..n)
.map(|i| {
let mut f = [0i16; FRAME_SAMPLES];
if i % 10 == 0 {
for (j, s) in f.iter_mut().take(144).enumerate() {
let env = 1.0 - j as f32 / 144.0;
*s = (rng.next() * env * 0.6 * 32_767.0) as i16;
}
}
f
})
.collect()
}
/// Runs frames through a gate and returns, per frame, whether it would have been sent, plus the
/// total number of frames sent (preroll included).
fn run(gate: &mut VoiceGate, frames: &[Frame]) -> (Vec<bool>, usize) {
let mut sent = Vec::with_capacity(frames.len());
let mut total = 0;
for f in frames {
match gate.push(f) {
Decision::Hold => sent.push(false),
Decision::Start => {
let mut pre = [[0i16; FRAME_SAMPLES]; MAX_PREROLL_FRAMES];
total += gate.take_preroll(&mut pre) + 1;
sent.push(true);
}
Decision::Send | Decision::SendAndEnd => {
total += 1;
sent.push(true);
}
}
}
(sent, total)
}
#[test]
fn decimator_keeps_history_across_frames() {
// A 1 kHz tone split into frames must decimate exactly like one long block would: compare the
// frame-wise output with a direct convolution over the concatenated input.
let mut d = Decimator::new();
let input: Vec<i16> = (0..FRAME_SAMPLES * 3).map(|n| ((n as f32 * 2.0 * std::f32::consts::PI * 1_000.0 / 48_000.0).sin() * 10_000.0) as i16).collect();
let mut framewise = Vec::new();
for chunk in input.chunks_exact(FRAME_SAMPLES) {
let mut f = [0i16; FRAME_SAMPLES];
f.copy_from_slice(chunk);
let mut out = [0.0; OUT_PER_FRAME];
d.process(&f, &mut out);
framewise.extend_from_slice(&out);
}
let reference = Decimator::new();
let padded: Vec<f32> = std::iter::repeat_n(0.0, HISTORY).chain(input.iter().map(|s| f32::from(*s) / 32_768.0)).collect();
for (k, got) in framewise.iter().enumerate() {
let end = HISTORY + k * DECIMATION + (DECIMATION - 1);
let want: f32 = padded[end + 1 - TAPS..=end].iter().zip(reference.coeffs.iter()).map(|(x, c)| x * c).sum();
assert!((got - want).abs() < 1e-6, "sample {k}: {got} vs {want}");
}
// A 1 kHz tone passes, a 12 kHz tone (above the new Nyquist) is suppressed.
let rms = |hz: f32| {
let mut d = Decimator::new();
let mut acc = 0.0;
for i in 0..4 {
let mut f = [0i16; FRAME_SAMPLES];
for (n, s) in f.iter_mut().enumerate() {
let t = (i * FRAME_SAMPLES + n) as f32;
*s = ((t * 2.0 * std::f32::consts::PI * hz / 48_000.0).sin() * 16_000.0) as i16;
}
let mut out = [0.0; OUT_PER_FRAME];
d.process(&f, &mut out);
if i > 0 {
acc += out.iter().map(|x| x * x).sum::<f32>();
}
}
(acc / (3 * OUT_PER_FRAME) as f32).sqrt()
};
assert!(rms(1_000.0) > 0.3, "pass band {}", rms(1_000.0));
assert!(rms(12_000.0) < 0.003, "stop band {}", rms(12_000.0));
}
#[test]
fn detector_windows_cross_frame_boundaries() {
// 320 new samples per frame against 256-sample windows: the remainder after each frame walks
// 64, 128, 192, 0 and repeats, so samples carry across frames and none is lost or duplicated
// (a remainder reset every frame would stay at 64).
let mut gate = VoiceGate::new(Sensitivity::Normal);
for n in 1..=8 {
gate.detect(&[0i16; FRAME_SAMPLES]);
assert_eq!(gate.pending_len, (n * OUT_PER_FRAME) % WINDOW, "after frame {n}");
}
}
fn rms_dbfs(f: &Frame) -> f32 {
let p = f.iter().map(|s| (f32::from(*s) / 32_768.0).powi(2)).sum::<f32>() / FRAME_SAMPLES as f32;
10.0 * p.max(1e-18).log10()
}
/// Index of the first clearly voiced frame of the fixture. The recording's own noise floor is about
/// -30 dBFS; voiced speech is above -24 dBFS.
fn first_loud(frames: &[Frame]) -> usize { frames.iter().position(|f| rms_dbfs(f) >= -24.0).expect("loud frame") }
#[test]
fn speech_opens_the_gate_with_preroll_and_no_duplicate() {
let speech = speech_frames();
let lead = 10;
let mut frames = silence(lead);
frames.extend_from_slice(&speech);
frames.extend(silence(60));
let speech_start = lead + first_loud(&speech);
let mut gate = VoiceGate::new(Sensitivity::Normal);
let mut first_onset = None;
let mut first_held = 0;
let mut since_end = 0; // frames held since the last spurt ended
let mut open = false;
let mut ended_at = None;
for (i, f) in frames.iter().enumerate() {
match gate.push(f) {
Decision::Start => {
assert!(!open);
let mut buf = [[0i16; FRAME_SAMPLES]; MAX_PREROLL_FRAMES];
let n = gate.take_preroll(&mut buf);
// First spurt after the reset: everything held since it (bounded); later spurts: the
// normal preroll. Oldest first, never the current frame.
let expected = if first_onset.is_none() { i.min(MAX_PREROLL_FRAMES) } else { PREROLL_FRAMES.min(since_end) };
assert_eq!(n, expected, "spurt at {i}");
for (k, p) in buf[..n].iter().enumerate() {
assert_eq!(p, &frames[i - n + k]);
}
if first_onset.is_none() {
first_onset = Some(i);
first_held = n;
}
open = true;
}
Decision::Send => assert!(open),
Decision::SendAndEnd => {
assert!(open);
open = false;
since_end = 0;
if i >= lead + speech.len() {
ended_at.get_or_insert(i);
}
}
Decision::Hold => {
assert!(!open);
since_end += 1;
}
}
}
let onset = first_onset.expect("speech must open the gate");
// The gate decides within 3 frames (60 ms) of the first loud frame, and what it sends reaches back
// before it, so the onset is not clipped.
assert!(onset >= speech_start && onset <= speech_start + 3, "onset at {onset}, loud speech at {speech_start}");
assert!(onset - first_held <= speech_start, "first sent frame {} after the loud start {speech_start}", onset - first_held);
// The last spurt ends in the trailing silence: after at least the hangover, and not much later.
let speech_end = lead + speech.len();
let ended = ended_at.expect("the spurt must end in the trailing silence");
assert!(ended >= speech_end + HANGOVER_FRAMES as usize - 1 && ended <= speech_end + HANGOVER_FRAMES as usize + 15, "ended at {ended}, speech ended at {speech_end}");
}
/// First spurt of `frames` fed to `gate`: (index of the Start, frames sent before the current one).
fn first_spurt(gate: &mut VoiceGate, frames: &[Frame]) -> Option<(usize, usize)> {
for (i, f) in frames.iter().enumerate() {
if gate.push(f) == Decision::Start {
let mut buf = [[0i16; FRAME_SAMPLES]; MAX_PREROLL_FRAMES];
let n = gate.take_preroll(&mut buf);
for (k, p) in buf[..n].iter().enumerate() {
assert_eq!(p, &frames[i - n + k], "sent frames are the held ones, in order");
}
return Some((i, n));
}
}
None
}
#[test]
fn speech_from_the_first_frame_is_sent_in_full() {
// Loud speech starting at frame 0 of a fresh gate (connect, unmute, mode change while talking).
let speech = speech_frames();
let from_loud = &speech[first_loud(&speech)..];
for s in [Sensitivity::High, Sensitivity::Normal, Sensitivity::Low] {
let mut gate = VoiceGate::new(s);
let (onset, held) = first_spurt(&mut gate, from_loud).expect("speech must open the gate");
// The warm-up delays the decision (measured: at most 3 frames past it), but every frame from
// frame 0 is sent: nothing of the first word is lost, it just arrives up to ~260 ms later.
assert!(onset <= WARMUP_FRAMES as usize + 3, "{s:?}: opened at frame {onset}");
assert_eq!(held, onset, "{s:?}: frames 0..{onset} must all be sent before frame {onset}");
}
}
#[test]
fn speech_right_after_a_reset_is_sent_in_full() {
// Talking through an unmute: the gate is reset at the mute; the first frame after it must be sent.
let speech = speech_frames();
let mut gate = VoiceGate::new(Sensitivity::Normal);
run(&mut gate, &speech[..60]);
gate.reset();
let after = &speech[60..];
let (onset, held) = first_spurt(&mut gate, after).expect("speech must open the gate");
assert_eq!(held, onset, "frames since the reset are all sent");
assert!(onset <= WARMUP_FRAMES as usize + 3);
}
#[test]
fn the_natural_end_of_a_spurt_does_not_reset_the_detector() {
let speech = speech_frames();
let mut frames = speech.clone();
frames.extend(silence(HANGOVER_FRAMES as usize + 10));
frames.extend_from_slice(&speech);
let mut gate = VoiceGate::new(Sensitivity::Normal);
let mut starts = Vec::new();
for f in &frames {
if gate.push(f) == Decision::Start {
let mut buf = [[0i16; FRAME_SAMPLES]; MAX_PREROLL_FRAMES];
starts.push(gate.take_preroll(&mut buf));
}
}
assert!(starts.len() >= 2, "{starts:?}");
// Only the first spurt after the reset carries the startup buffer; later ones the normal preroll,
// and no warm-up was re-armed in between.
assert!(starts[1..].iter().all(|n| *n <= PREROLL_FRAMES), "{starts:?}");
assert_eq!(gate.warmup, 0);
}
#[test]
fn decimator_output_stays_in_the_detector_range() {
// Full-scale square wave: the low-pass rings above full scale; the detector input is clamped.
let mut d = Decimator::new();
let mut peak = 0.0f32;
for _ in 0..3 {
let mut f = [0i16; FRAME_SAMPLES];
for (n, s) in f.iter_mut().enumerate() {
*s = if (n / 48) % 2 == 0 { i16::MAX } else { i16::MIN };
}
let mut out = [0.0; OUT_PER_FRAME];
d.process(&f, &mut out);
peak = out.iter().fold(peak, |m, x| m.max(x.abs()));
}
assert!(peak <= 1.0 && peak > 0.9, "peak {peak}");
}
#[test]
fn silence_steady_noise_and_clicks_stay_closed() {
// Synthetic, deterministic noise (not recordings): the detector is statistical, so this checks the
// chosen thresholds keep these inputs closed, not that every real noise does.
for (name, frames) in [("silence", silence(250)), ("steady noise", steady_noise(250)), ("clicks", clicks(250))] {
for s in [Sensitivity::High, Sensitivity::Normal, Sensitivity::Low] {
let mut gate = VoiceGate::new(s);
let (_, total) = run(&mut gate, &frames);
assert_eq!(total, 0, "{name} opened the gate at {s:?}");
}
}
}
#[test]
fn hangover_keeps_short_pauses_and_ends_after_it() {
let speech = speech_frames();
// A continuously voiced stretch of the fixture, a 160 ms pause, the same stretch again, then silence.
let voiced = &speech[60..90];
let mut frames = voiced.to_vec();
frames.extend(silence(8));
frames.extend_from_slice(voiced);
let speech_end = frames.len();
frames.extend(silence(60));
let mut gate = VoiceGate::new(Sensitivity::Normal);
let (sent, _) = run(&mut gate, &frames);
let starts = sent.windows(2).filter(|w| !w[0] && w[1]).count() + usize::from(sent[0]);
assert_eq!(starts, 1, "a short pause must not split the spurt");
let last_sent = sent.iter().rposition(|s| *s).expect("sent");
assert!(last_sent >= speech_end + HANGOVER_FRAMES as usize - 1, "closed at {last_sent} before the hangover ran out");
assert!(!sent[sent.len() - 1], "gate must be closed after the hangover");
}
#[test]
fn reset_forgets_preroll_and_open_spurt() {
let speech = speech_frames();
let mut gate = VoiceGate::new(Sensitivity::Normal);
run(&mut gate, &speech[..40]);
assert!(gate.is_active());
gate.reset();
assert!(!gate.is_active());
let mut buf = [[0i16; FRAME_SAMPLES]; MAX_PREROLL_FRAMES];
assert_eq!(gate.take_preroll(&mut buf), 0);
// After a reset only new audio is considered: silence keeps it closed.
let (_, total) = run(&mut gate, &silence(30));
assert_eq!(total, 0);
}
#[test]
fn sensitivity_changes_what_is_sent() {
// The same speech at each sensitivity: a lower probability threshold counts more windows as
// voiced, so more of it is sent; changing the sensitivity of an existing gate decides exactly
// like a gate created with it.
let mut frames = silence(10);
frames.extend_from_slice(&speech_frames());
frames.extend(silence(60));
let decide = |s| run(&mut VoiceGate::new(s), &frames);
let (high, normal, low) = (decide(Sensitivity::High), decide(Sensitivity::Normal), decide(Sensitivity::Low));
assert!(high.1 > normal.1 && normal.1 > low.1, "sent frames high {} normal {} low {}", high.1, normal.1, low.1);
let mut switched = VoiceGate::new(Sensitivity::Low);
switched.set_mode(GateMode::Automatic(Sensitivity::High));
assert_eq!(run(&mut switched, &frames), high);
}
/// A frame of a 440 Hz sine with the given RMS level in dBFS.
fn tone_frames(rms_db: f32, n: usize) -> Vec<Frame> {
let amp = 10f32.powf(rms_db / 20.0) * std::f32::consts::SQRT_2;
let mut phase = 0usize;
(0..n)
.map(|_| {
let mut f = [0i16; FRAME_SAMPLES];
for s in f.iter_mut() {
*s = (amp * (phase as f32 * 2.0 * std::f32::consts::PI * 440.0 / 48_000.0).sin() * 32_767.0) as i16;
phase += 1;
}
f
})
.collect()
}
#[test]
fn frame_level_matches_rms_dbfs() {
assert!(frame_level_db(&[0; FRAME_SAMPLES]).is_infinite());
for db in [-60.0, -30.0, -6.0] {
let got = frame_level_db(&tone_frames(db, 1)[0]);
assert!((got - db).abs() < 0.1, "{db}: {got}");
}
}
#[test]
fn volume_gate_opens_at_level_with_preroll_hangover_and_hysteresis() {
let mut gate = VoiceGate::new(GateMode::VolumeGate { level_db: -30.0 });
// Below the level: never opens, no warm-up needed.
let (_, total) = run(&mut gate, &tone_frames(-33.0, 50));
assert_eq!(total, 0);
// At/above the level: opens on the first loud frame and sends the held preroll (5 frames).
let mut pre = [[0i16; FRAME_SAMPLES]; MAX_PREROLL_FRAMES];
assert_eq!(gate.push(&tone_frames(-29.0, 1)[0]), Decision::Start);
assert_eq!(gate.take_preroll(&mut pre), MAX_PREROLL_FRAMES, "first spurt after a reset gets everything held");
// Hysteresis: -32 dB (within 3 dB below the level) keeps it open indefinitely.
for f in tone_frames(-32.0, 100) {
assert_eq!(gate.push(&f), Decision::Send);
}
// Below level - margin: exactly HANGOVER_FRAMES more frames, the last one ends the spurt.
let quiet = tone_frames(-40.0, HANGOVER_FRAMES as usize);
for (i, f) in quiet.iter().enumerate() {
let d = gate.push(f);
if i + 1 == HANGOVER_FRAMES as usize {
assert_eq!(d, Decision::SendAndEnd);
} else {
assert_eq!(d, Decision::Send, "frame {i}");
}
}
assert!(!gate.is_active());
// Later spurts send only the last PREROLL_FRAMES.
run(&mut gate, &silence(20));
assert_eq!(gate.push(&tone_frames(-20.0, 1)[0]), Decision::Start);
assert_eq!(gate.take_preroll(&mut pre), PREROLL_FRAMES);
}
#[test]
fn volume_gate_level_change_applies_without_reset_and_kind_change_resets() {
let mut gate = VoiceGate::new(GateMode::VolumeGate { level_db: -30.0 });
assert_eq!(gate.push(&tone_frames(-20.0, 1)[0]), Decision::Start);
gate.set_mode(GateMode::VolumeGate { level_db: 0.0 });
assert!(gate.is_active(), "a level change keeps the open spurt");
gate.set_mode(GateMode::Automatic(Sensitivity::Normal));
assert!(!gate.is_active(), "a detector change resets");
assert_eq!(gate.warmup, WARMUP_FRAMES);
// Positive levels cannot be reached by any 16-bit frame (documented limit).
let mut gate = VoiceGate::new(GateMode::VolumeGate { level_db: 1.0 });
let full: Frame = std::array::from_fn(|i| if i % 2 == 0 { i16::MAX } else { i16::MIN });
assert_eq!(run(&mut gate, &[full; 10]).1, 0);
}
#[test]
fn hybrid_needs_speech_and_level() {
let mut frames = silence(10);
frames.extend_from_slice(&speech_frames());
frames.extend(silence(60));
let automatic = run(&mut VoiceGate::new(Sensitivity::Normal), &frames).1;
let hybrid_low = run(&mut VoiceGate::new(GateMode::Hybrid { sensitivity: Sensitivity::Normal, level_db: -50.0 }), &frames).1;
let hybrid_high = run(&mut VoiceGate::new(GateMode::Hybrid { sensitivity: Sensitivity::Normal, level_db: -3.0 }), &frames).1;
assert!(automatic > 0);
assert!(hybrid_low > 0 && hybrid_low <= automatic, "hybrid {hybrid_low} vs automatic {automatic}");
assert_eq!(hybrid_high, 0, "speech below the level must not open the hybrid gate");
// A loud non-speech tone opens the volume gate but not hybrid.
let tone = tone_frames(-10.0, 60);
assert!(run(&mut VoiceGate::new(GateMode::VolumeGate { level_db: -30.0 }), &tone).1 > 0);
assert_eq!(run(&mut VoiceGate::new(GateMode::Hybrid { sensitivity: Sensitivity::Normal, level_db: -30.0 }), &tone).1, 0);
}
}
+472
View File
@@ -0,0 +1,472 @@
//! Local voice settings and processing owned by TeamsPeach (not a port of TeamSpeak's native DSP, whose
//! code is not visible): per-user volume modifiers in dB, playback automatic gain control per speaker
//! ("Automatically level the volume of other users"), and the bridge arguments that configure them and
//! the voice-activation detectors ([`crate::vad::GateMode`]).
//!
//! Modifier range and resolution follow the official TS6 fader (client_ui/main.js `audio-fader-taper`):
//! -200..=+10 dB in 0.5 dB steps, -200 dB being silence. The AGC target and limits below are our own
//! choices; the official native AGC parameters are not observable, so no bit-exact behaviour is claimed.
//! The mix is still hard-clipped at full scale exactly as before (no limiter): a +10 dB modifier on a
//! loud speaker can clip, as the bridge's clipping metrics show.
//!
//! AGC state is fixed-size per speaker; a tick does not allocate except when a new speaker's state is
//! first inserted.
use std::collections::HashMap;
use base64::prelude::*;
use serde::Deserialize;
use serde_json::value::RawValue;
use serde_json::{json, Value};
use crate::protocol::{ErrorCode, ErrorObj};
use crate::vad::{GateMode, Sensitivity, MAX_LEVEL_DB, MIN_LEVEL_DB};
/// Lowest modifier; treated as silence.
pub const MIN_DB: f32 = -200.0;
/// Highest modifier.
pub const MAX_DB: f32 = 10.0;
/// Linear gain of [`MAX_DB`] (10^(10/20)).
pub const MAX_USER_GAIN: f32 = 3.162_277_7;
/// Persisted modifiers accepted in one `set_local_volumes` (fits the 256 KiB line limit).
pub const MAX_LOCAL_VOLUMES: usize = 4096;
/// A storable per-user modifier: finite, within [-200, +10], on the 0.5 dB grid.
pub fn valid_modifier_db(db: f32) -> bool {
db.is_finite() && (MIN_DB..=MAX_DB).contains(&db) && (db * 2.0).fract() == 0.0
}
/// Linear factor for a modifier; -200 dB (or anything not above it, NaN included) is exactly 0.
pub fn db_to_gain(db: f32) -> f32 {
if db.is_nan() || db <= MIN_DB {
return 0.0;
}
10f32.powf(db.min(MAX_DB) / 20.0)
}
/// Session-wide voice settings pushed by the desktop app (they outlive single connections).
#[derive(Default)]
pub struct VoiceSettings {
/// Persisted per-user modifiers by raw UID bytes (0 dB entries are not stored).
pub volumes: HashMap<Vec<u8>, f32>,
/// Playback AGC for the current output device profile.
pub playback_agc: bool,
}
// ---------------------------------------------------------------- bridge arguments
fn bad(msg: impl Into<String>) -> ErrorObj { ErrorObj::new(ErrorCode::BadRequest, msg) }
fn parse<T: for<'de> Deserialize<'de>>(raw: Option<&RawValue>) -> Result<T, ErrorObj> {
serde_json::from_str(raw.map(RawValue::get).unwrap_or("{}")).map_err(|e| bad(format!("invalid args: {e}")))
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct TransmitArgs {
mode: String,
#[serde(default)]
detector: Option<String>,
#[serde(default)]
sensitivity: Option<String>,
#[serde(default)]
level_db: Option<f32>,
}
/// `set_transmit`: `{mode:"direct"}` or `{mode:"vad", detector?: "automatic"|"volume_gate"|"hybrid",
/// sensitivity?: "high"|"normal"|"low" (automatic/hybrid), level_db: -50..=50 (volume_gate/hybrid)}`.
/// `None` = direct transmission.
pub fn parse_transmit(raw: Option<&RawValue>) -> Result<Option<GateMode>, ErrorObj> {
let a: TransmitArgs = parse(raw)?;
if a.mode == "direct" {
if a.detector.is_some() || a.sensitivity.is_some() || a.level_db.is_some() {
return Err(bad("set_transmit: detector, sensitivity and level_db apply to mode 'vad' only"));
}
return Ok(None);
}
if a.mode != "vad" {
return Err(bad("set_transmit: mode must be 'direct' or 'vad'"));
}
let sensitivity = match a.sensitivity.as_deref() {
None | Some("normal") => Sensitivity::Normal,
Some("high") => Sensitivity::High,
Some("low") => Sensitivity::Low,
Some(_) => return Err(bad("set_transmit: sensitivity must be 'high', 'normal' or 'low'")),
};
let level = || match a.level_db {
Some(l) => Ok(l),
None => Err(bad("set_transmit: level_db is required for this detector")),
};
match a.detector.as_deref() {
None | Some("automatic") => {
if a.level_db.is_some() {
return Err(bad("set_transmit: level_db applies to 'volume_gate' and 'hybrid' only"));
}
Ok(Some(GateMode::Automatic(sensitivity)))
}
Some("volume_gate") => {
if a.sensitivity.is_some() {
return Err(bad("set_transmit: sensitivity does not apply to 'volume_gate'"));
}
Ok(Some(GateMode::VolumeGate { level_db: level()? }))
}
Some("hybrid") => Ok(Some(GateMode::Hybrid { sensitivity, level_db: level()? })),
Some(_) => Err(bad("set_transmit: detector must be 'automatic', 'volume_gate' or 'hybrid'")),
}
}
pub(crate) fn validate_transmit(mode: Option<GateMode>) -> Result<(), ErrorObj> {
if let Some(GateMode::VolumeGate { level_db } | GateMode::Hybrid { level_db, .. }) = mode {
if !level_db.is_finite() || !(MIN_LEVEL_DB..=MAX_LEVEL_DB).contains(&level_db) {
return Err(bad("set_transmit: level_db must be between -50 and 50"));
}
}
Ok(())
}
/// The `set_transmit` answer for an applied mode.
pub fn transmit_result(mode: Option<GateMode>) -> Value {
match mode {
None => json!({ "mode": "direct" }),
Some(GateMode::Automatic(s)) => json!({ "mode": "vad", "detector": "automatic", "sensitivity": s.name() }),
Some(GateMode::VolumeGate { level_db }) => json!({ "mode": "vad", "detector": "volume_gate", "level_db": level_db }),
Some(GateMode::Hybrid { sensitivity, level_db }) => {
json!({ "mode": "vad", "detector": "hybrid", "sensitivity": sensitivity.name(), "level_db": level_db })
}
}
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct VolumeEntry {
uid: String,
db: f32,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct LocalVolumesArgs {
replace: bool,
volumes: Vec<VolumeEntry>,
}
/// Parsed `set_local_volumes`: `replace` swaps the whole map, otherwise entries are upserted; a 0 dB
/// entry removes the UID.
#[derive(Clone, Debug, PartialEq)]
pub struct LocalVolumesUpdate {
pub replace: bool,
pub volumes: Vec<(Vec<u8>, f32)>,
}
/// `set_local_volumes {replace: bool, volumes: [{uid: base64 client UID, db}]}`.
pub fn parse_local_volumes(raw: Option<&RawValue>) -> Result<LocalVolumesUpdate, ErrorObj> {
let a: LocalVolumesArgs = parse(raw)?;
if a.volumes.len() > MAX_LOCAL_VOLUMES {
return Err(bad(format!("set_local_volumes: at most {MAX_LOCAL_VOLUMES} entries")));
}
let mut volumes = Vec::with_capacity(a.volumes.len());
for e in a.volumes {
if e.uid.is_empty() || e.uid.len() > 128 {
return Err(bad("set_local_volumes: uid must be 1..128 characters"));
}
let uid = BASE64_STANDARD.decode(&e.uid).map_err(|_| bad("set_local_volumes: uid is not base64"))?;
volumes.push((uid, e.db));
}
let update = LocalVolumesUpdate { replace: a.replace, volumes };
Ok(update)
}
pub(crate) fn validate_local_volumes(update: &LocalVolumesUpdate) -> Result<(), ErrorObj> {
if update.volumes.len() > MAX_LOCAL_VOLUMES {
return Err(bad(format!("set_local_volumes: at most {MAX_LOCAL_VOLUMES} entries")));
}
for (uid, db) in &update.volumes {
// The wire representation is a nonempty base64 string of at most 128 bytes.
if uid.is_empty() || uid.len() > 96 { return Err(bad("set_local_volumes: uid must be 1..128 characters")); }
if !valid_modifier_db(*db) { return Err(bad("set_local_volumes: db must be -200..10 in 0.5 steps")); }
}
Ok(())
}
impl VoiceSettings {
pub fn apply_volumes(&mut self, update: LocalVolumesUpdate) {
if update.replace {
self.volumes.clear();
}
for (uid, db) in update.volumes {
if db == 0.0 {
self.volumes.remove(&uid);
} else {
self.volumes.insert(uid, db);
}
}
}
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct PlaybackDspArgs {
agc: bool,
}
/// `set_playback_dsp {agc: bool}`.
pub fn parse_playback_dsp(raw: Option<&RawValue>) -> Result<bool, ErrorObj> {
Ok(parse::<PlaybackDspArgs>(raw)?.agc)
}
// ---------------------------------------------------------------- playback AGC
/// Speech level the AGC aims for (20 ms RMS, dBFS).
pub const AGC_TARGET_DBFS: f32 = -20.0;
/// Most boost/cut applied to one speaker.
pub const AGC_MAX_BOOST_DB: f32 = 12.0;
pub const AGC_MAX_CUT_DB: f32 = 12.0;
/// Frames quieter than this do not update a speaker's level (pauses, background).
pub const AGC_SPEECH_FLOOR_DBFS: f32 = -50.0;
/// Gain slew per 20 ms tick: rises slowly (pauses and noise are not pumped up), falls quickly.
pub const AGC_RISE_DB_PER_TICK: f32 = 0.25;
pub const AGC_FALL_DB_PER_TICK: f32 = 3.0;
/// Level tracker smoothing: louder frames are followed faster than quieter ones.
const LEVEL_UP: f32 = 0.35;
const LEVEL_DOWN: f32 = 0.06;
#[derive(Clone, Copy, Debug)]
struct SpeakerAgc {
/// Smoothed speech level in dBFS; None until the first speech frame.
level: Option<f32>,
/// Gain applied on the next tick, dB.
gain_db: f32,
}
impl SpeakerAgc {
const fn new() -> Self { Self { level: None, gain_db: 0.0 } }
fn observe(&mut self, rms_dbfs: f32) {
if rms_dbfs < AGC_SPEECH_FLOOR_DBFS {
return;
}
let level = match self.level {
None => rms_dbfs,
Some(l) => l + (rms_dbfs - l) * if rms_dbfs > l { LEVEL_UP } else { LEVEL_DOWN },
};
self.level = Some(level);
let want = (AGC_TARGET_DBFS - level).clamp(-AGC_MAX_CUT_DB, AGC_MAX_BOOST_DB);
self.gain_db += (want - self.gain_db).clamp(-AGC_FALL_DB_PER_TICK, AGC_RISE_DB_PER_TICK);
}
}
/// RMS of interleaved samples in dBFS (-inf for silence).
pub fn rms_dbfs(samples: &[f32]) -> f32 {
if samples.is_empty() {
return f32::NEG_INFINITY;
}
let sum: f32 = samples.iter().map(|s| s * s).sum();
10.0 * (sum / samples.len() as f32).log10()
}
/// Per-speaker playback AGC. Measures each speaker's decoded (pre-volume) samples of a tick and applies
/// the resulting gain from the next tick, multiplied with the user's modifier.
#[derive(Default)]
pub struct PlaybackDsp {
agc_enabled: bool,
agc: HashMap<u16, SpeakerAgc>,
}
impl PlaybackDsp {
pub fn set_agc(&mut self, enabled: bool) {
if !enabled {
self.agc.clear();
}
self.agc_enabled = enabled;
}
pub fn agc_enabled(&self) -> bool { self.agc_enabled }
pub fn observe(&mut self, client_id: u16, samples: &[f32]) {
if !self.agc_enabled || samples.is_empty() {
return;
}
let level = rms_dbfs(samples);
self.agc.entry(client_id).or_insert_with(SpeakerAgc::new).observe(level);
}
/// AGC factor for a speaker (1.0 when disabled or not yet measured).
pub fn speaker_gain(&self, client_id: u16) -> f32 {
if !self.agc_enabled {
return 1.0;
}
self.agc.get(&client_id).map_or(1.0, |s| 10f32.powf(s.gain_db / 20.0))
}
pub fn remove(&mut self, client_id: u16) { self.agc.remove(&client_id); }
pub fn reset(&mut self) { self.agc.clear(); }
}
#[cfg(test)]
mod tests {
use super::*;
fn parse_transmit(raw: Option<&RawValue>) -> Result<Option<GateMode>, ErrorObj> {
let mode = super::parse_transmit(raw)?;
validate_transmit(mode)?;
Ok(mode)
}
fn parse_local_volumes(raw: Option<&RawValue>) -> Result<LocalVolumesUpdate, ErrorObj> {
let update = super::parse_local_volumes(raw)?;
validate_local_volumes(&update)?;
Ok(update)
}
#[test]
fn typed_dsp_commands_enforce_finite_levels_and_decoded_uid_limits() {
use crate::protocol::{validate_command, Command};
for level_db in [f32::NAN, f32::INFINITY, -51.0, 51.0] {
for mode in [GateMode::VolumeGate { level_db }, GateMode::Hybrid { sensitivity: Sensitivity::Normal, level_db }] {
assert_eq!(validate_command(Command::SetTransmit { vad: Some(mode) }).unwrap_err().code, ErrorCode::BadRequest);
}
}
for volumes in [vec![(vec![], 0.0)], vec![(vec![1; 97], 0.0)], vec![(vec![1], -3.25)],
vec![(vec![1], 0.0); MAX_LOCAL_VOLUMES + 1]] {
assert_eq!(validate_command(Command::SetLocalVolumes(LocalVolumesUpdate { replace: true, volumes })).unwrap_err().code, ErrorCode::BadRequest);
}
let valid = LocalVolumesUpdate { replace: true, volumes: vec![(vec![1; 96], -200.0), (vec![2], 10.0)] };
assert_eq!(validate_command(Command::SetLocalVolumes(valid.clone())).unwrap().into_inner(), Command::SetLocalVolumes(valid));
}
fn raw(s: &str) -> Box<RawValue> { RawValue::from_string(s.to_owned()).unwrap() }
#[test]
fn modifier_grid_and_gain() {
for ok in [-200.0, -199.5, -60.0, -0.5, 0.0, 9.5, 10.0] {
assert!(valid_modifier_db(ok), "{ok}");
}
for bad in [-200.5, 10.5, 0.25, f32::NAN, f32::INFINITY, -f32::INFINITY] {
assert!(!valid_modifier_db(bad), "{bad}");
}
assert_eq!(db_to_gain(-200.0), 0.0);
assert_eq!(db_to_gain(f32::NAN), 0.0);
assert_eq!(db_to_gain(0.0), 1.0);
assert!((db_to_gain(10.0) - MAX_USER_GAIN).abs() < 1e-5);
assert!((db_to_gain(-6.0) - 0.501_187).abs() < 1e-5);
assert!((db_to_gain(50.0) - MAX_USER_GAIN).abs() < 1e-5, "clamped to +10");
}
#[test]
fn transmit_arguments() {
let p = |s: &str| parse_transmit(Some(&raw(s)));
assert_eq!(p(r#"{"mode":"direct"}"#).unwrap(), None);
assert_eq!(p(r#"{"mode":"vad"}"#).unwrap(), Some(GateMode::Automatic(Sensitivity::Normal)));
assert_eq!(p(r#"{"mode":"vad","sensitivity":"high"}"#).unwrap(), Some(GateMode::Automatic(Sensitivity::High)));
assert_eq!(p(r#"{"mode":"vad","detector":"volume_gate","level_db":-30}"#).unwrap(), Some(GateMode::VolumeGate { level_db: -30.0 }));
assert_eq!(
p(r#"{"mode":"vad","detector":"hybrid","sensitivity":"low","level_db":12.5}"#).unwrap(),
Some(GateMode::Hybrid { sensitivity: Sensitivity::Low, level_db: 12.5 })
);
for bad in [
r#"{"mode":"open"}"#,
r#"{"mode":"direct","sensitivity":"low"}"#,
r#"{"mode":"direct","level_db":0}"#,
r#"{"mode":"vad","sensitivity":"max"}"#,
r#"{"mode":"vad","threshold":0.1}"#,
r#"{"mode":"vad","level_db":-30}"#,
r#"{"mode":"vad","detector":"volume_gate"}"#,
r#"{"mode":"vad","detector":"volume_gate","level_db":-51}"#,
r#"{"mode":"vad","detector":"volume_gate","level_db":50.5}"#,
r#"{"mode":"vad","detector":"volume_gate","level_db":-30,"sensitivity":"high"}"#,
r#"{"mode":"vad","detector":"fuzzy","level_db":0}"#,
r#"{}"#,
] {
assert_eq!(p(bad).unwrap_err().code, ErrorCode::BadRequest, "{bad}");
}
assert_eq!(transmit_result(Some(GateMode::VolumeGate { level_db: -30.0 })), json!({"mode":"vad","detector":"volume_gate","level_db":-30.0}));
assert_eq!(transmit_result(None), json!({"mode":"direct"}));
}
#[test]
fn local_volume_updates() {
let mut s = VoiceSettings::default();
let p = |t: &str| parse_local_volumes(Some(&raw(t)));
s.apply_volumes(p(r#"{"replace":true,"volumes":[{"uid":"AQID","db":-6},{"uid":"BAUG","db":10}]}"#).unwrap());
assert_eq!(s.volumes.get(&vec![1, 2, 3]), Some(&-6.0));
s.apply_volumes(p(r#"{"replace":false,"volumes":[{"uid":"AQID","db":0},{"uid":"BwgJ","db":-200}]}"#).unwrap());
assert_eq!(s.volumes.get(&vec![1, 2, 3]), None, "0 dB removes");
assert_eq!(s.volumes.len(), 2);
s.apply_volumes(p(r#"{"replace":true,"volumes":[]}"#).unwrap());
assert!(s.volumes.is_empty());
for bad in [
r#"{"replace":true,"volumes":[{"uid":"AQID","db":10.5}]}"#,
r#"{"replace":true,"volumes":[{"uid":"AQID","db":0.25}]}"#,
r#"{"replace":true,"volumes":[{"uid":"not base64!","db":0}]}"#,
r#"{"replace":true,"volumes":[{"uid":"","db":0}]}"#,
r#"{"volumes":[]}"#,
] {
assert!(p(bad).is_err(), "{bad}");
}
assert!(parse_playback_dsp(Some(&raw(r#"{"agc":true}"#))).unwrap());
assert!(parse_playback_dsp(Some(&raw(r#"{"agc":1}"#))).is_err());
}
fn tone(amplitude: f32, n: usize) -> Vec<f32> {
(0..n).map(|i| amplitude * (i as f32 * 2.0 * std::f32::consts::PI * 220.0 / 48_000.0).sin()).collect()
}
#[test]
fn agc_levels_quiet_and_loud_speakers_towards_target_within_limits() {
let mut dsp = PlaybackDsp::default();
dsp.set_agc(true);
let quiet = tone(0.02, 1920); // ≈ -37 dBFS RMS
let loud = tone(0.7, 1920); // ≈ -6 dBFS RMS
for _ in 0..200 {
dsp.observe(1, &quiet);
dsp.observe(2, &loud);
}
let gq = 20.0 * dsp.speaker_gain(1).log10();
let gl = 20.0 * dsp.speaker_gain(2).log10();
assert!((gq - AGC_MAX_BOOST_DB).abs() < 0.01, "quiet boosted to the cap: {gq}");
assert!((gl + AGC_MAX_CUT_DB).abs() < 0.01, "loud cut to the cap: {gl}");
let mid = tone(0.05, 1920); // ≈ -29 dBFS: within reach, lands on the target
let mut dsp = PlaybackDsp::default();
dsp.set_agc(true);
for _ in 0..200 {
dsp.observe(3, &mid);
}
let g = 20.0 * dsp.speaker_gain(3).log10();
assert!((rms_dbfs(&mid) + g - AGC_TARGET_DBFS).abs() < 0.1, "{g}");
// Silence never changes the gain (no boosting of pauses).
let before = dsp.speaker_gain(3);
for _ in 0..100 {
dsp.observe(3, &[0.0; 1920]);
}
assert_eq!(dsp.speaker_gain(3), before);
}
#[test]
fn agc_cuts_fast_and_boosts_slowly() {
let mut dsp = PlaybackDsp::default();
dsp.set_agc(true);
dsp.observe(7, &tone(0.9, 1920));
let g = 20.0 * dsp.speaker_gain(7).log10();
assert!((g + AGC_FALL_DB_PER_TICK).abs() < 1e-4, "first loud frame cuts by one fast step: {g}");
let mut dsp = PlaybackDsp::default();
dsp.set_agc(true);
dsp.observe(7, &tone(0.01, 1920));
let g = 20.0 * dsp.speaker_gain(7).log10();
assert!((g - AGC_RISE_DB_PER_TICK).abs() < 1e-4, "first quiet frame boosts by one slow step: {g}");
}
#[test]
fn agc_disabled_is_unity_and_forgets() {
let mut dsp = PlaybackDsp::default();
dsp.observe(1, &tone(0.01, 1920));
assert_eq!(dsp.speaker_gain(1), 1.0);
dsp.set_agc(true);
dsp.observe(1, &tone(0.01, 1920));
assert!(dsp.speaker_gain(1) > 1.0);
dsp.set_agc(false);
assert_eq!(dsp.speaker_gain(1), 1.0);
dsp.set_agc(true);
assert_eq!(dsp.speaker_gain(1), 1.0, "state was dropped");
}
}
+48
View File
@@ -0,0 +1,48 @@
//! Session integration for transmit detectors, persisted per-user volumes and playback DSP
//! (bridge commands `set_transmit`, `set_local_volumes`, `set_playback_dsp`; see voice_dsp.rs).
use super::*;
use crate::vad::GateMode;
use crate::voice_dsp;
impl Session {
/// Applies the transmit mode. A change between direct and voice activation, or to another detector,
/// discards frames still queued and ends any open burst before the answer, so nothing captured under
/// the old mode is sent under the new one. A changed sensitivity or level of the same detector (the
/// user moving the VAD level slider) applies from the next frame without interrupting speech.
pub(super) async fn set_transmit(&mut self, mode: Option<GateMode>) -> Result<Value, ErrorObj> {
let same_detector = matches!((mode, self.vad.as_ref()), (Some(new), Some(state))
if std::mem::discriminant(&new) == std::mem::discriminant(&state.gate.mode()));
if same_detector {
let state = self.vad.as_mut().expect("checked above");
state.gate.set_mode(mode.expect("checked above"));
} else {
let epoch = self.audio_in.invalidate();
self.tx_end().await;
match (mode, self.vad.as_mut()) {
(None, _) => self.vad = None,
(Some(m), Some(state)) => state.gate.set_mode(m),
(Some(m), None) => self.vad = Some(Box::new(VadState { gate: VoiceGate::new(m), route: None })),
}
info!(epoch, "transmit queue invalidated for a mode change");
}
let result = voice_dsp::transmit_result(mode);
info!(mode = %result["mode"], detector = %result["detector"], sensitivity = %result["sensitivity"], level_db = %result["level_db"], "transmit mode applied");
Ok(result)
}
/// Persisted per-user modifiers (by UID) pushed by the desktop app; live menu changes of the current
/// connection (`client_action volume`) still take precedence until disconnect.
pub(super) fn set_local_volumes(&mut self, update: voice_dsp::LocalVolumesUpdate) -> Result<Value, ErrorObj> {
self.voice.apply_volumes(update);
Ok(json!({ "count": self.voice.volumes.len() }))
}
/// Playback DSP of the current output device profile; applies to the running and later connections.
pub(super) fn set_playback_dsp(&mut self, agc: bool) -> Result<Value, ErrorObj> {
self.voice.playback_agc = agc;
if let Some(c) = self.conn.as_mut() {
c.rx.set_playback_agc(agc);
}
Ok(json!({ "agc": agc }))
}
}
Loaded 100 of 1600 files, more files were not shown because too many files have changed in this diff. Show more