diff --git a/.github/actions/system-deps/action.yml b/.github/actions/system-deps/action.yml new file mode 100644 index 0000000..0d3b031 --- /dev/null +++ b/.github/actions/system-deps/action.yml @@ -0,0 +1,82 @@ +name: System dependencies +description: > + Native libraries and tools the workspace builds against: apt packages on + Linux; NASM and libvpx (vcpkg, cached) on Windows, exporting VPX_LIB_DIR, + VPX_INCLUDE_DIR, VPX_VERSION and VPX_STATIC for libvpx-native-sys. + +inputs: + vpx-triplet: + description: vcpkg triplet for libvpx on Windows (static library, dynamic CRT like Rust's default) + default: x64-windows-static-md + +runs: + using: composite + steps: + - name: apt packages + if: runner.os == 'Linux' + shell: bash + # ALSA (audio devices), fontconfig + xkbcommon (UI), libvpx + dav1d + # (video codecs), PipeWire + SPA (screen and audio capture), libclang + # (bindgen), Xvfb (X11 tests). + run: | + sudo apt-get update + sudo apt-get install -y --no-install-recommends \ + libasound2-dev libfontconfig1-dev libxkbcommon-dev \ + libvpx-dev libdav1d-dev libpipewire-0.3-dev libspa-0.2-dev libclang-dev \ + xvfb + + # aws-lc-sys (WebRTC DTLS through str0m) assembles with NASM on Windows. + - name: NASM + if: runner.os == 'Windows' + uses: ilammy/setup-nasm@v1 + + - name: vcpkg revision + if: runner.os == 'Windows' + id: vcpkg + shell: pwsh + run: | + "commit=$(git -C "$env:VCPKG_INSTALLATION_ROOT" rev-parse HEAD)" >> $env:GITHUB_OUTPUT + + - name: Cache vcpkg packages + if: runner.os == 'Windows' + uses: actions/cache@v4 + with: + path: ${{ runner.temp }}\vcpkg-archives + key: vcpkg-libvpx-${{ inputs.vpx-triplet }}-${{ steps.vcpkg.outputs.commit }} + restore-keys: vcpkg-libvpx-${{ inputs.vpx-triplet }}- + + - name: libvpx + if: runner.os == 'Windows' + shell: pwsh + env: + TRIPLET: ${{ inputs.vpx-triplet }} + VCPKG_BINARY_SOURCES: clear;files,${{ runner.temp }}\vcpkg-archives,readwrite + run: | + $ErrorActionPreference = 'Stop' + $vcpkg = Join-Path $env:VCPKG_INSTALLATION_ROOT 'vcpkg.exe' + New-Item -ItemType Directory -Force (Join-Path $env:RUNNER_TEMP 'vcpkg-archives') | Out-Null + & $vcpkg install "libvpx:$env:TRIPLET" + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + + # "libvpx:x64-windows-static-md 1.15.2#1 The reference ..." + $line = (& $vcpkg list libvpx | Select-String -Pattern "^libvpx:$env:TRIPLET\s").Line + if (-not $line) { throw "vcpkg list does not show libvpx:$env:TRIPLET" } + $version = (($line -split '\s+')[1] -split '#')[0] + + $root = Join-Path $env:VCPKG_INSTALLATION_ROOT "installed\$env:TRIPLET" + $libdir = Join-Path $root 'lib' + # libvpx-native-sys links "vpx"; libvpx's own MSVC build names the + # library vpxmd.lib / vpxmt.lib, so provide vpx.lib if needed. + if (-not (Test-Path (Join-Path $libdir 'vpx.lib'))) { + $lib = Get-ChildItem $libdir -Filter 'vpx*.lib' | Select-Object -First 1 + if (-not $lib) { Get-ChildItem $libdir; throw "no vpx library in $libdir" } + $libdir = Join-Path $env:RUNNER_TEMP 'vpx-lib' + New-Item -ItemType Directory -Force $libdir | Out-Null + Copy-Item $lib.FullName (Join-Path $libdir 'vpx.lib') + } + + "VPX_LIB_DIR=$libdir" >> $env:GITHUB_ENV + "VPX_INCLUDE_DIR=$(Join-Path $root 'include')" >> $env:GITHUB_ENV + "VPX_VERSION=$version" >> $env:GITHUB_ENV + "VPX_STATIC=1" >> $env:GITHUB_ENV + Write-Host "libvpx $version from $libdir" diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 8f19f8d..9101adc 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -20,8 +20,7 @@ jobs: runs-on: ubuntu-24.04 steps: - uses: actions/checkout@v4 - - name: Install system dependencies - run: sudo apt-get update && sudo apt-get install -y libasound2-dev libfontconfig1-dev libxkbcommon-dev + - uses: ./.github/actions/system-deps - name: Install toolchain (rust-toolchain.toml) run: rustup toolchain install - uses: Swatinem/rust-cache@v2 @@ -44,17 +43,73 @@ jobs: runs-on: ${{ matrix.os }} steps: - uses: actions/checkout@v4 - - name: Install system dependencies - if: runner.os == 'Linux' - run: sudo apt-get update && sudo apt-get install -y libasound2-dev libfontconfig1-dev libxkbcommon-dev + - uses: ./.github/actions/system-deps - name: Install toolchain (rust-toolchain.toml) run: rustup toolchain install - uses: Swatinem/rust-cache@v2 - name: Build run: cargo build --workspace --all-targets --locked + # Under Xvfb, so X11 tests (screen capture, global hotkeys through + # XTEST input) run instead of skipping. + - name: Test (Linux, Xvfb) + if: runner.os == 'Linux' + run: xvfb-run -a bash -c 'TSC_X11_TEST_DISPLAY="$DISPLAY" cargo test --workspace --locked' - name: Test + if: runner.os != 'Linux' run: cargo test --workspace --locked + release-build: + name: release build (${{ matrix.os }}) + strategy: + fail-fast: false + matrix: + include: + - os: ubuntu-24.04 + artifact: tsc-desktop-linux-x86_64 + - os: windows-2025 + artifact: tsc-desktop-windows-x86_64 + runs-on: ${{ matrix.os }} + steps: + - uses: actions/checkout@v4 + - uses: ./.github/actions/system-deps + - name: Install toolchain (rust-toolchain.toml) + run: rustup toolchain install + - uses: Swatinem/rust-cache@v2 + with: + key: release + - name: Build tsc-desktop + run: cargo build --release --locked -p tsc-ui + - name: Stage (Linux) + if: runner.os == 'Linux' + run: | + mkdir -p dist + cp target/release/tsc-desktop dist/ + cp packaging/linux/* dist/ + # The installer is built when NSIS is on the runner; unsigned. + - name: Stage (Windows) + if: runner.os == 'Windows' + shell: pwsh + run: | + New-Item -ItemType Directory -Force dist | Out-Null + Copy-Item target\release\tsc-desktop.exe dist\ + $makensis = (Get-Command makensis -ErrorAction SilentlyContinue).Source + if (-not $makensis) { + $makensis = "${env:ProgramFiles(x86)}\NSIS\makensis.exe" + } + if (Test-Path $makensis) { + $version = (cargo metadata --no-deps --format-version 1 | ConvertFrom-Json).packages | + Where-Object name -eq 'tsc-ui' | Select-Object -ExpandProperty version + & $makensis "/DVERSION=$version" "/DOUTDIR=$PWD\dist" packaging\windows\installer.nsi + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + } else { + Write-Host "::notice::NSIS not found, uploading the executable only" + } + - uses: actions/upload-artifact@v4 + with: + name: ${{ matrix.artifact }} + path: dist/ + if-no-files-found: error + deny: name: cargo-deny runs-on: ubuntu-24.04 @@ -72,8 +127,7 @@ jobs: needs: test steps: - uses: actions/checkout@v4 - - name: Install system dependencies - run: sudo apt-get update && sudo apt-get install -y libasound2-dev libfontconfig1-dev libxkbcommon-dev + - uses: ./.github/actions/system-deps - name: Install toolchain (rust-toolchain.toml) run: rustup toolchain install - uses: Swatinem/rust-cache@v2 diff --git a/Cargo.lock b/Cargo.lock index ee8cf6a..cf5d08e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -107,8 +107,8 @@ dependencies = [ "accesskit_consumer", "hashbrown 0.16.1", "static_assertions", - "windows", - "windows-core", + "windows 0.62.2", + "windows-core 0.62.2", ] [[package]] @@ -1240,7 +1240,7 @@ dependencies = [ "js-sys", "num-traits", "wasm-bindgen", - "windows-link", + "windows-link 0.2.1", ] [[package]] @@ -1577,8 +1577,8 @@ dependencies = [ "objc2-core-foundation", "objc2-foundation 0.3.2", "web-sys", - "windows", - "windows-core", + "windows 0.62.2", + "windows-core 0.62.2", ] [[package]] @@ -2660,8 +2660,8 @@ dependencies = [ "read-fonts", "roxmltree", "smallvec", - "windows", - "windows-core", + "windows 0.62.2", + "windows-core 0.62.2", "yeslogic-fontconfig-sys", ] @@ -2859,7 +2859,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1bd49230192a3797a9a4d6abe9b3eed6f7fa4c8a8a4947977c6f80025f92cbd8" dependencies = [ "rustix 1.1.5", - "windows-link", + "windows-link 0.2.1", ] [[package]] @@ -3059,7 +3059,7 @@ dependencies = [ "log", "presser", "thiserror 2.0.21", - "windows", + "windows 0.62.2", ] [[package]] @@ -3556,7 +3556,7 @@ dependencies = [ "wasm-bindgen", "web-sys", "webbrowser", - "windows", + "windows 0.62.2", "winit", "zbus", ] @@ -3664,7 +3664,7 @@ dependencies = [ "web-sys", "web-time", "wgpu", - "windows", + "windows 0.62.2", ] [[package]] @@ -3733,8 +3733,8 @@ dependencies = [ "vtable", "wgpu", "wgpu-hal", - "windows", - "windows-core", + "windows 0.62.2", + "windows-core 0.62.2", "write-fonts", ] @@ -3769,7 +3769,7 @@ dependencies = [ "js-sys", "log", "wasm-bindgen", - "windows-core", + "windows-core 0.62.2", ] [[package]] @@ -4077,7 +4077,7 @@ dependencies = [ "socket2", "widestring", "windows-registry", - "windows-result", + "windows-result 0.4.1", "windows-sys 0.61.2", ] @@ -4172,7 +4172,7 @@ dependencies = [ "simd_cesu8", "thiserror 2.0.21", "walkdir", - "windows-link", + "windows-link 0.2.1", ] [[package]] @@ -4350,7 +4350,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d7c4b02199fee7c5d21a5ae7d8cfa79a6ef5bb2fc834d6e9058e89c825efdc55" dependencies = [ "cfg-if", - "windows-link", + "windows-link 0.2.1", ] [[package]] @@ -4558,6 +4558,20 @@ dependencies = [ "num-traits", ] +[[package]] +name = "mac-notification-sys" +version = "0.6.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd604973958ddcc11b561193c0fb96ba146506ef2f231ef2e7c35fd2cbc9beca" +dependencies = [ + "cc", + "log", + "objc2 0.6.4", + "objc2-foundation 0.3.2", + "time", + "uuid", +] + [[package]] name = "mach2" version = "0.6.0" @@ -4857,6 +4871,20 @@ dependencies = [ "memchr", ] +[[package]] +name = "notify-rust" +version = "4.18.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c5b4c1b4f2aa9f25f63a7a49d3dd0ed567b3670da15330a66b29434be899b891" +dependencies = [ + "futures-lite", + "log", + "mac-notification-sys", + "serde", + "tauri-winrt-notification", + "zbus", +] + [[package]] name = "nu-ansi-term" version = "0.50.3" @@ -5573,8 +5601,8 @@ dependencies = [ "sha2 0.11.0", "thiserror 2.0.21", "tokio", - "windows", - "windows-strings", + "windows 0.62.2", + "windows-strings 0.5.1", ] [[package]] @@ -5603,7 +5631,7 @@ dependencies = [ "libc", "redox_syscall 0.5.18", "smallvec", - "windows-link", + "windows-link 0.2.1", ] [[package]] @@ -7484,7 +7512,7 @@ checksum = "c61cb643dac43067f3eb76c866635a74377ac0abca0ff2590674e1e295514c3d" dependencies = [ "bitflags 2.13.2", "skia-bindings", - "windows", + "windows 0.62.2", ] [[package]] @@ -7672,6 +7700,79 @@ dependencies = [ "x11rb", ] +[[package]] +name = "sonora" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e1ce442ab5cb392c4067b8f2cced20be4cf12e479f6dfbf44acbe9b14ac9250" +dependencies = [ + "sonora-aec3", + "sonora-agc2", + "sonora-common-audio", + "sonora-ns", + "sonora-simd", + "tracing", +] + +[[package]] +name = "sonora-aec3" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "50280e31256d09f7838aff6715ed4b7640e514dc1092a1e14013c01e552380db" +dependencies = [ + "sonora-common-audio", + "sonora-fft", + "sonora-simd", +] + +[[package]] +name = "sonora-agc2" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a93a9fa8373a33e61a7fb441d8a9e725ac6024079d2c77a845cf6abe1790b9f" +dependencies = [ + "bytemuck", + "derive_more", + "sonora-common-audio", + "sonora-fft", + "sonora-simd", + "tracing", +] + +[[package]] +name = "sonora-common-audio" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6635bc61b24807ceac93ad0807b1292b6b0620caa6cd360d3be89fc616b833cc" +dependencies = [ + "derive_more", + "sonora-simd", +] + +[[package]] +name = "sonora-fft" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27e272c70f34363afb5382dd1818c05f8f63ef6785635736a14e9ccbbb5ba012" + +[[package]] +name = "sonora-ns" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d511feef19302c716d245c4555087d161ba91c178735ea11107dcce0d0b7a86f" +dependencies = [ + "sonora-fft", +] + +[[package]] +name = "sonora-simd" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7cf0804e4752a5562262e143014f53043080ead4cd5a98f9278d3ceaf32d868" +dependencies = [ + "cpufeatures 0.3.1", +] + [[package]] name = "spin_on" version = "0.1.1" @@ -8070,6 +8171,17 @@ dependencies = [ "pin-project-lite", ] +[[package]] +name = "tauri-winrt-notification" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed071c670382e85fc2f48ae706492d8c338f4f89bf72520d32f8abfe880aade" +dependencies = [ + "thiserror 2.0.21", + "windows 0.61.3", + "windows-version", +] + [[package]] name = "tempfile" version = "3.27.0" @@ -8582,6 +8694,11 @@ dependencies = [ "opus2", "rtrb", "rubato", + "serde", + "serde_json", + "sonora", + "sonora-agc2", + "sonora-simd", "thiserror 2.0.21", "tracing", "tsclientlib", @@ -8604,6 +8721,7 @@ dependencies = [ "tsc-model", "tsc-observer", "tsc-query", + "tsc-stream", "tsclientlib", "tsproto-packets", ] @@ -8692,6 +8810,23 @@ dependencies = [ "tsc-query", ] +[[package]] +name = "tsc-platform" +version = "0.1.0" +dependencies = [ + "ashpd", + "dirs", + "futures-util", + "notify-rust", + "serde", + "serde_json", + "thiserror 2.0.21", + "tokio", + "tracing", + "windows 0.62.2", + "x11rb", +] + [[package]] name = "tsc-query" version = "0.1.0" @@ -8808,6 +8943,7 @@ dependencies = [ "tsc-model", "tsc-observer", "tsc-query", + "tsc-stream", "tsclientlib", "tsproto-packets", ] @@ -9214,8 +9350,8 @@ dependencies = [ "log", "num-integer", "thiserror 2.0.21", - "windows", - "windows-core", + "windows 0.62.2", + "windows-core 0.62.2", ] [[package]] @@ -9567,8 +9703,8 @@ dependencies = [ "thiserror 2.0.21", "wgpu-naga-bridge", "wgpu-types", - "windows", - "windows-core", + "windows 0.62.2", + "windows-core 0.62.2", ] [[package]] @@ -9651,16 +9787,29 @@ dependencies = [ "num-traits", ] +[[package]] +name = "windows" +version = "0.61.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9babd3a767a4c1aef6900409f85f5d53ce2544ccdfaa86dad48c91782c6d6893" +dependencies = [ + "windows-collections 0.2.0", + "windows-core 0.61.2", + "windows-future 0.2.1", + "windows-link 0.1.3", + "windows-numerics 0.2.0", +] + [[package]] name = "windows" version = "0.62.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "527fadee13e0c05939a6a05d5bd6eec6cd2e3dbd648b9f8e447c6518133d8580" dependencies = [ - "windows-collections", - "windows-core", - "windows-future", - "windows-numerics", + "windows-collections 0.3.2", + "windows-core 0.62.2", + "windows-future 0.3.2", + "windows-numerics 0.3.1", ] [[package]] @@ -9672,8 +9821,17 @@ dependencies = [ "parking_lot", "rayon", "thiserror 2.0.21", - "windows", - "windows-future", + "windows 0.62.2", + "windows-future 0.3.2", +] + +[[package]] +name = "windows-collections" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3beeceb5e5cfd9eb1d76b381630e82c4241ccd0d27f1a39ed41b2760b255c5e8" +dependencies = [ + "windows-core 0.61.2", ] [[package]] @@ -9682,7 +9840,20 @@ version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "23b2d95af1a8a14a3c7367e1ed4fc9c20e0a26e79551b1454d72583c97cc6610" dependencies = [ - "windows-core", + "windows-core 0.62.2", +] + +[[package]] +name = "windows-core" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0fdd3ddb90610c7638aa2b3a3ab2904fb9e5cdbecc643ddb3647212781c4ae3" +dependencies = [ + "windows-implement", + "windows-interface", + "windows-link 0.1.3", + "windows-result 0.3.4", + "windows-strings 0.4.2", ] [[package]] @@ -9693,9 +9864,20 @@ checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb" dependencies = [ "windows-implement", "windows-interface", - "windows-link", - "windows-result", - "windows-strings", + "windows-link 0.2.1", + "windows-result 0.4.1", + "windows-strings 0.5.1", +] + +[[package]] +name = "windows-future" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc6a41e98427b19fe4b73c550f060b59fa592d7d686537eebf9385621bfbad8e" +dependencies = [ + "windows-core 0.61.2", + "windows-link 0.1.3", + "windows-threading 0.1.0", ] [[package]] @@ -9704,9 +9886,9 @@ version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e1d6f90251fe18a279739e78025bd6ddc52a7e22f921070ccdc67dde84c605cb" dependencies = [ - "windows-core", - "windows-link", - "windows-threading", + "windows-core 0.62.2", + "windows-link 0.2.1", + "windows-threading 0.2.1", ] [[package]] @@ -9731,6 +9913,12 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "windows-link" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e6ad25900d524eaabdbbb96d20b4311e1e7ae1699af4fb28c17ae66c80d798a" + [[package]] name = "windows-link" version = "0.2.1" @@ -9750,14 +9938,24 @@ dependencies = [ "zeroize", ] +[[package]] +name = "windows-numerics" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9150af68066c4c5c07ddc0ce30421554771e528bde427614c61038bc2c92c2b1" +dependencies = [ + "windows-core 0.61.2", + "windows-link 0.1.3", +] + [[package]] name = "windows-numerics" version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6e2e40844ac143cdb44aead537bbf727de9b044e107a0f1220392177d15b0f26" dependencies = [ - "windows-core", - "windows-link", + "windows-core 0.62.2", + "windows-link 0.2.1", ] [[package]] @@ -9766,9 +9964,18 @@ version = "0.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "02752bf7fbdcce7f2a27a742f798510f3e5ad88dbe84871e5168e2120c3d5720" dependencies = [ - "windows-link", - "windows-result", - "windows-strings", + "windows-link 0.2.1", + "windows-result 0.4.1", + "windows-strings 0.5.1", +] + +[[package]] +name = "windows-result" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "56f42bd332cc6c8eac5af113fc0c1fd6a8fd2aa08a0119358686e5160d0586c6" +dependencies = [ + "windows-link 0.1.3", ] [[package]] @@ -9777,7 +9984,16 @@ version = "0.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" dependencies = [ - "windows-link", + "windows-link 0.2.1", +] + +[[package]] +name = "windows-strings" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "56e6c93f3a0c3b36176cb1327a4958a0353d5d166c2a35cb268ace15e91d3b57" +dependencies = [ + "windows-link 0.1.3", ] [[package]] @@ -9786,7 +10002,7 @@ version = "0.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" dependencies = [ - "windows-link", + "windows-link 0.2.1", ] [[package]] @@ -9822,7 +10038,7 @@ version = "0.61.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" dependencies = [ - "windows-link", + "windows-link 0.2.1", ] [[package]] @@ -9871,13 +10087,31 @@ dependencies = [ "windows_x86_64_msvc 0.52.6", ] +[[package]] +name = "windows-threading" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b66463ad2e0ea3bbf808b7f1d371311c80e115c0b71d60efc142cafbcfb057a6" +dependencies = [ + "windows-link 0.1.3", +] + [[package]] name = "windows-threading" version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3949bd5b99cafdf1c7ca86b43ca564028dfe27d66958f2470940f73d86d75b37" dependencies = [ - "windows-link", + "windows-link 0.2.1", +] + +[[package]] +name = "windows-version" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e4060a1da109b9d0326b7262c8e12c84df67cc0dbc9e33cf49e01ccc2eb63631" +dependencies = [ + "windows-link 0.2.1", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index 24749c4..7359176 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -16,6 +16,7 @@ members = [ "crates/tsc-media", "crates/tsc-model", "crates/tsc-observer", + "crates/tsc-platform", "crates/tsc-query", "crates/tsc-store", "crates/tsc-stream", @@ -35,6 +36,7 @@ default-members = [ "crates/tsc-gateway-proto", "crates/tsc-model", "crates/tsc-observer", + "crates/tsc-platform", "crates/tsc-query", "crates/tsc-store", "crates/tsc-stream", @@ -61,6 +63,23 @@ all = { level = "warn", priority = -1 } # it takes seconds. opt-level = 3 +# Audio processing (echo cancellation, noise suppression) runs in real time on +# every 10 ms of microphone audio; unoptimized it needs about a third of a core. +[profile.dev.package.sonora] +opt-level = 3 +[profile.dev.package.sonora-aec3] +opt-level = 3 +[profile.dev.package.sonora-agc2] +opt-level = 3 +[profile.dev.package.sonora-common-audio] +opt-level = 3 +[profile.dev.package.sonora-fft] +opt-level = 3 +[profile.dev.package.sonora-ns] +opt-level = 3 +[profile.dev.package.sonora-simd] +opt-level = 3 + [profile.dev] # Line tables (for backtraces) for workspace crates, no debug info for # dependencies: keeps target/ several times smaller. Override locally for diff --git a/crates/tsc-audio/Cargo.toml b/crates/tsc-audio/Cargo.toml index 6991483..44bb56f 100644 --- a/crates/tsc-audio/Cargo.toml +++ b/crates/tsc-audio/Cargo.toml @@ -19,10 +19,17 @@ hound = "3.5.1" opus2 = "0.4" rtrb = { version = "0.4.0", optional = true } rubato = "5.0.0" +serde = { version = "1.0.228", features = ["derive"] } +sonora = "0.2" +sonora-agc2 = "0.2" +sonora-simd = "0.2" thiserror = "2.0.21" tracing = "0.1.44" tsclientlib = { path = "../proto/tsclientlib" } tsproto-packets = { path = "../proto/tsproto-packets" } +[dev-dependencies] +serde_json = "1" + [lints] workspace = true diff --git a/crates/tsc-audio/src/device.rs b/crates/tsc-audio/src/device.rs index 5b0ad81..69ecb94 100644 --- a/crates/tsc-audio/src/device.rs +++ b/crates/tsc-audio/src/device.rs @@ -2,42 +2,140 @@ //! //! The device callbacks only move samples through lock-free ring buffers; all //! processing happens on the caller's side. +//! +//! Devices are identified by cpal's stable device id (`host:device`, e.g. +//! `alsa:hw:1,0`), which survives restarts and replugging. A stream notices +//! when its device goes away through cpal's error callback +//! ([`Capture::is_lost`]); [`Managed`] reopens it, on the default device when +//! the selected one is gone, and moves back when it returns. + +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::time::{Duration, Instant}; use cpal::traits::{DeviceTrait, HostTrait, StreamTrait}; +use cpal::{ErrorKind, SampleFormat}; use rtrb::{Consumer, Producer, RingBuffer}; -use tracing::warn; +use tracing::{debug, warn}; use crate::{Error, Result}; /// A device as shown in settings. -#[derive(Clone, Debug)] +#[derive(Clone, Debug, PartialEq, Eq)] pub struct DeviceInfo { + /// Stable id to store in settings (`AudioSettings::input_device`). + pub id: String, + /// Human-readable name. pub name: String, pub input: bool, pub output: bool, + /// The system's default input device. + pub default_input: bool, + /// The system's default output device. + pub default_output: bool, } fn device_error(e: impl std::fmt::Display) -> Error { Error::Device(e.to_string()) } +fn device_name(device: &cpal::Device) -> String { + device.description().map(|d| d.name().to_string()).unwrap_or_else(|_| device.to_string()) +} + +fn device_id(device: &cpal::Device) -> Option { + device.id().ok().map(|id| id.to_string()) +} + /// All devices of the default host. pub fn list_devices() -> Result> { let host = cpal::default_host(); + let default_input = host.default_input_device().and_then(|d| device_id(&d)); + let default_output = host.default_output_device().and_then(|d| device_id(&d)); let devices = host.devices().map_err(device_error)?; Ok(devices - .map(|d| DeviceInfo { - name: d.description().map(|d| d.name().to_string()).unwrap_or_default(), - input: d.supports_input(), - output: d.supports_output(), + .filter_map(|d| { + let id = device_id(&d)?; + Some(DeviceInfo { + name: device_name(&d), + input: d.supports_input(), + output: d.supports_output(), + default_input: default_input.as_deref() == Some(id.as_str()), + default_output: default_output.as_deref() == Some(id.as_str()), + id, + }) }) .collect()) } +/// Devices that can record. +pub fn input_devices() -> Result> { + Ok(list_devices()?.into_iter().filter(|d| d.input).collect()) +} + +/// Devices that can play. +pub fn output_devices() -> Result> { + Ok(list_devices()?.into_iter().filter(|d| d.output).collect()) +} + +/// The device with this id, or the default one for `None`. +fn find_device(id: Option<&str>, input: bool) -> Result { + let host = cpal::default_host(); + let kind = if input { "input" } else { "output" }; + let Some(id) = id else { + let device = if input { host.default_input_device() } else { host.default_output_device() }; + return device.ok_or_else(|| Error::Device(format!("no {kind} device"))); + }; + let parsed = id.parse().map_err(device_error)?; + host.device_by_id(&parsed).ok_or_else(|| Error::Device(format!("{kind} device {id} not found"))) +} + +/// Whether a device with this id is present. +pub fn device_exists(id: &str) -> bool { + id.parse().ok().and_then(|id| cpal::default_host().device_by_id(&id)).is_some() +} + +/// Errors after which a stream will not recover by itself. +fn is_fatal(kind: ErrorKind) -> bool { + !matches!(kind, ErrorKind::DeviceChanged | ErrorKind::Xrun | ErrorKind::RealtimeDenied) +} + +/// The error callback: log, and flag the stream lost on fatal errors. +fn error_callback(what: &'static str, lost: Arc) -> impl FnMut(cpal::Error) + Send { + move |error| { + if is_fatal(error.kind()) { + warn!(%error, "{what} stream lost"); + lost.store(true, Ordering::Relaxed); + } else { + debug!(%error, "{what} stream"); + } + } +} + +/// The default config, but with f32 samples if the device offers them at the +/// same rate (streams here are f32 only). +fn f32_config( + default: cpal::SupportedStreamConfig, + supported: impl Iterator, +) -> cpal::StreamConfig { + if default.sample_format() == SampleFormat::F32 { + return default.config(); + } + let rate = default.sample_rate(); + supported + .filter(|r| r.sample_format() == SampleFormat::F32) + .find_map(|r| r.try_with_sample_rate(rate)) + .map(|c| c.config()) + .unwrap_or_else(|| default.config()) +} + /// Running capture stream. Samples are interleaved at the device's rate. pub struct Capture { _stream: cpal::Stream, consumer: Consumer, + lost: Arc, + id: Option, + name: String, pub channels: usize, pub rate: u32, } @@ -45,14 +143,21 @@ pub struct Capture { impl Capture { /// Open the default input device, buffering up to `buffer_ms` of audio. pub fn open_default(buffer_ms: u32) -> Result { - let device = cpal::default_host() - .default_input_device() - .ok_or_else(|| Error::Device("no input device".into()))?; - let config = device.default_input_config().map_err(device_error)?.config(); + Self::open(None, buffer_ms) + } + + /// Open the input device with this id (see [`DeviceInfo::id`]), or the + /// default one for `None`. + pub fn open(id: Option<&str>, buffer_ms: u32) -> Result { + let device = find_device(id, true)?; + let default = device.default_input_config().map_err(device_error)?; + let supported = device.supported_input_configs().map_err(device_error)?; + let config = f32_config(default, supported); let channels = config.channels as usize; let rate = config.sample_rate; let (mut producer, consumer) = RingBuffer::new((rate * buffer_ms / 1000) as usize * channels); + let lost = Arc::new(AtomicBool::new(false)); let stream = device .build_input_stream( config, @@ -62,12 +167,20 @@ impl Capture { chunk.fill_from_iter(data[..n].iter().copied()); } }, - |error| warn!(%error, "capture stream error"), + error_callback("capture", lost.clone()), None, ) .map_err(device_error)?; stream.play().map_err(device_error)?; - Ok(Self { _stream: stream, consumer, channels, rate }) + Ok(Self { + _stream: stream, + consumer, + lost, + id: device_id(&device), + name: device_name(&device), + channels, + rate, + }) } /// Move everything captured so far into `out`. @@ -77,26 +190,45 @@ impl Capture { out.extend(chunk); } } + + /// The device went away or the stream broke; reopen it. + pub fn is_lost(&self) -> bool { + self.lost.load(Ordering::Relaxed) + } + + pub fn name(&self) -> &str { + &self.name + } } /// Running playback stream. Write interleaved samples at the device's rate. pub struct Playback { _stream: cpal::Stream, producer: Producer, + lost: Arc, + id: Option, + name: String, + capacity: usize, pub channels: usize, pub rate: u32, } impl Playback { pub fn open_default(buffer_ms: u32) -> Result { - let device = cpal::default_host() - .default_output_device() - .ok_or_else(|| Error::Device("no output device".into()))?; - let config = device.default_output_config().map_err(device_error)?.config(); + Self::open(None, buffer_ms) + } + + /// Open the output device with this id, or the default one for `None`. + pub fn open(id: Option<&str>, buffer_ms: u32) -> Result { + let device = find_device(id, false)?; + let default = device.default_output_config().map_err(device_error)?; + let supported = device.supported_output_configs().map_err(device_error)?; + let config = f32_config(default, supported); let channels = config.channels as usize; let rate = config.sample_rate; - let (producer, mut consumer) = - RingBuffer::::new((rate * buffer_ms / 1000) as usize * channels); + let capacity = (rate * buffer_ms / 1000) as usize * channels; + let (producer, mut consumer) = RingBuffer::::new(capacity); + let lost = Arc::new(AtomicBool::new(false)); let stream = device .build_output_stream( config, @@ -110,12 +242,21 @@ impl Playback { // Underrun: play silence. data[n..].fill(0.0); }, - |error| warn!(%error, "playback stream error"), + error_callback("playback", lost.clone()), None, ) .map_err(device_error)?; stream.play().map_err(device_error)?; - Ok(Self { _stream: stream, producer, channels, rate }) + Ok(Self { + _stream: stream, + producer, + lost, + id: device_id(&device), + name: device_name(&device), + capacity, + channels, + rate, + }) } /// Queue samples; returns how many fit into the buffer. @@ -131,4 +272,299 @@ impl Playback { pub fn free(&self) -> usize { self.producer.slots() } + + /// Samples (all channels) queued and not yet handed to the device. + pub fn queued(&self) -> usize { + self.capacity - self.producer.slots() + } + + /// Queued audio in milliseconds. + pub fn queued_ms(&self) -> u32 { + (self.queued() / self.channels.max(1)) as u32 * 1000 / self.rate.max(1) + } + + /// The device went away or the stream broke; reopen it. + pub fn is_lost(&self) -> bool { + self.lost.load(Ordering::Relaxed) + } + + pub fn name(&self) -> &str { + &self.name + } +} + +/// What [`Managed`] needs from a stream; implemented by [`Capture`] and +/// [`Playback`]. +pub trait DeviceStream: Sized { + fn open(id: Option<&str>, buffer_ms: u32) -> Result; + fn is_lost(&self) -> bool; + /// Id of the device actually opened. + fn device_id(&self) -> Option<&str>; + fn name(&self) -> &str; + fn device_exists(id: &str) -> bool; +} + +impl DeviceStream for Capture { + fn open(id: Option<&str>, buffer_ms: u32) -> Result { + Capture::open(id, buffer_ms) + } + fn is_lost(&self) -> bool { + Capture::is_lost(self) + } + fn device_id(&self) -> Option<&str> { + self.id.as_deref() + } + fn name(&self) -> &str { + &self.name + } + fn device_exists(id: &str) -> bool { + device_exists(id) + } +} + +impl DeviceStream for Playback { + fn open(id: Option<&str>, buffer_ms: u32) -> Result { + Playback::open(id, buffer_ms) + } + fn is_lost(&self) -> bool { + Playback::is_lost(self) + } + fn device_id(&self) -> Option<&str> { + self.id.as_deref() + } + fn name(&self) -> &str { + &self.name + } + fn device_exists(id: &str) -> bool { + device_exists(id) + } +} + +/// What happened to a [`Managed`] stream, for the user. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum DeviceEvent { + /// Opened a device. `fallback` is set when it is the default device + /// because the selected one is missing. + Opened { name: String, fallback: bool }, + /// The open device went away. + Lost { name: String }, + /// No device could be opened; retrying in the background. Reported once + /// until a device opens again. + Unavailable(String), +} + +/// Retry opening a device this often while none is open. +pub const RETRY_INTERVAL: Duration = Duration::from_secs(2); +/// While on the default device instead of the selected one, look for the +/// selected one this often. +pub const RETURN_INTERVAL: Duration = Duration::from_secs(5); + +/// Keeps a stream open across device loss and selection changes. Call +/// [`poll`](Self::poll) regularly from the audio loop. +pub struct Managed { + stream: Option, + wanted: Option, + buffer_ms: u32, + retry_at: Instant, + return_at: Instant, + failing: bool, +} + +impl Managed { + /// Nothing is opened until the first [`poll`](Self::poll). + pub fn new(wanted: Option, buffer_ms: u32) -> Self { + let now = Instant::now(); + Self { stream: None, wanted, buffer_ms, retry_at: now, return_at: now, failing: false } + } + + /// Select another device (`None`: the default); reopens on the next poll. + pub fn select(&mut self, wanted: Option) { + if wanted != self.wanted { + self.wanted = wanted; + self.stream = None; + self.retry_at = Instant::now(); + } + } + + pub fn wanted(&self) -> Option<&str> { + self.wanted.as_deref() + } + + pub fn stream(&mut self) -> Option<&mut S> { + self.stream.as_mut() + } + + /// Whether the stream was replaced since the caller last saw it matters + /// for resamplers; callers compare [`DeviceEvent::Opened`]. + pub fn poll(&mut self) -> Option { + self.poll_at(Instant::now()) + } + + fn poll_at(&mut self, now: Instant) -> Option { + if let Some(stream) = &self.stream { + if stream.is_lost() { + let name = stream.name().to_string(); + self.stream = None; + self.retry_at = now; + return Some(DeviceEvent::Lost { name }); + } + // On the default device although another one is selected: move + // back once it is present again. + let on_fallback = self.wanted.is_some() && stream.device_id() != self.wanted.as_deref(); + if !on_fallback || now < self.return_at { + return None; + } + self.return_at = now + RETURN_INTERVAL; + match self.wanted.as_deref() { + Some(id) if S::device_exists(id) => self.stream = None, + _ => return None, + } + } + if now < self.retry_at { + return None; + } + let wanted = self.wanted.clone(); + let opened = match S::open(wanted.as_deref(), self.buffer_ms) { + Ok(s) => Ok((s, false)), + Err(e) if wanted.is_some() => { + S::open(None, self.buffer_ms).map(|s| (s, true)).map_err(|default_error| { + Error::Device(format!("{e}; default device: {default_error}")) + }) + } + Err(e) => Err(e), + }; + match opened { + Ok((stream, fallback)) => { + let name = stream.name().to_string(); + self.stream = Some(stream); + self.failing = false; + self.return_at = now + RETURN_INTERVAL; + Some(DeviceEvent::Opened { name, fallback }) + } + Err(e) => { + self.retry_at = now + RETRY_INTERVAL; + let first = !self.failing; + self.failing = true; + first.then(|| DeviceEvent::Unavailable(e.to_string())) + } + } + } +} + +#[cfg(test)] +mod tests { + use std::cell::RefCell; + use std::collections::HashSet; + + use super::*; + + thread_local! { + /// Plugged-in fake devices; "default" is the system default. + static PLUGGED: RefCell> = RefCell::new(HashSet::new()); + } + + fn plug(id: &str, on: bool) { + PLUGGED.with(|p| { + let mut p = p.borrow_mut(); + if on { p.insert(id.into()) } else { p.remove(id) } + }); + } + + fn plugged(id: &str) -> bool { + PLUGGED.with(|p| p.borrow().contains(id)) + } + + struct Fake { + id: String, + } + + impl DeviceStream for Fake { + fn open(id: Option<&str>, _: u32) -> Result { + let id = id.unwrap_or("default"); + if plugged(id) { + Ok(Fake { id: id.into() }) + } else { + Err(Error::Device(format!("{id} not found"))) + } + } + fn is_lost(&self) -> bool { + !plugged(&self.id) + } + fn device_id(&self) -> Option<&str> { + Some(&self.id) + } + fn name(&self) -> &str { + &self.id + } + fn device_exists(id: &str) -> bool { + plugged(id) + } + } + + fn opened(name: &str, fallback: bool) -> Option { + Some(DeviceEvent::Opened { name: name.into(), fallback }) + } + + #[test] + fn fatal_errors() { + assert!(is_fatal(ErrorKind::DeviceNotAvailable)); + assert!(is_fatal(ErrorKind::StreamInvalidated)); + assert!(!is_fatal(ErrorKind::Xrun)); + assert!(!is_fatal(ErrorKind::DeviceChanged)); + } + + /// Headset selected, unplugged mid-call, plugged back in. + #[test] + fn reopens_and_falls_back() { + plug("default", true); + plug("headset", true); + let mut m = Managed::::new(Some("headset".into()), 100); + let t0 = Instant::now(); + assert_eq!(m.poll_at(t0), opened("headset", false)); + assert_eq!(m.poll_at(t0), None); + + plug("headset", false); + assert_eq!(m.poll_at(t0), Some(DeviceEvent::Lost { name: "headset".into() })); + assert_eq!(m.poll_at(t0), opened("default", true)); + assert_eq!(m.stream().unwrap().id, "default"); + + // Back only after the return interval. + plug("headset", true); + assert_eq!(m.poll_at(t0 + Duration::from_secs(1)), None); + assert_eq!(m.poll_at(t0 + RETURN_INTERVAL), opened("headset", false)); + + // Selecting the default device switches right away. + m.select(None); + assert_eq!(m.poll_at(t0 + RETURN_INTERVAL), opened("default", false)); + } + + /// Nothing plugged in: one report, retries every interval, recovers. + #[test] + fn retries_when_unavailable() { + plug("default", false); + let mut m = Managed::::new(None, 100); + let t0 = Instant::now(); + assert!(matches!(m.poll_at(t0), Some(DeviceEvent::Unavailable(_)))); + assert!(m.stream().is_none()); + plug("default", true); + // Not before the retry interval, and no repeated report. + assert_eq!(m.poll_at(t0 + Duration::from_millis(500)), None); + assert_eq!(m.poll_at(t0 + RETRY_INTERVAL), opened("default", false)); + plug("default", false); + assert!(matches!(m.poll_at(t0 + RETRY_INTERVAL), Some(DeviceEvent::Lost { .. }))); + assert!(matches!(m.poll_at(t0 + RETRY_INTERVAL), Some(DeviceEvent::Unavailable(_)))); + assert_eq!(m.poll_at(t0 + RETRY_INTERVAL * 2), None); + } + + /// Opening real devices needs hardware; just make sure enumeration does + /// not fail or panic without any. + #[test] + fn enumeration_without_hardware() { + if let Ok(devices) = list_devices() { + for d in devices { + assert!(!d.id.is_empty()); + } + } + assert!(!device_exists("no-such-host:nothing")); + } } diff --git a/crates/tsc-audio/src/lib.rs b/crates/tsc-audio/src/lib.rs index 9d71539..80693e8 100644 --- a/crates/tsc-audio/src/lib.rs +++ b/crates/tsc-audio/src/lib.rs @@ -5,14 +5,22 @@ //! - [`framer`]: slice an arbitrary sample stream into codec frames //! - [`resample`]: sample-rate conversion to the 48 kHz the codec uses //! - [`wav`]: WAV file input/output -//! - [`Mixer`]: per-client jitter buffer, decoder and mixer (from the vendored -//! `tsclientlib::audio::AudioHandler`) -//! - `device` (feature `device`): capture and playback through cpal +//! - [`process`]: echo cancellation, noise suppression and gain control +//! - [`vad`]: voice activity detection +//! - [`mixer`]: per-client jitter buffer, decoder, volume and mixing (on the +//! vendored `tsclientlib::audio::AudioHandler`) +//! - [`settings`]: all user audio settings in one serde struct +//! - `device` (feature `device`): capture and playback through cpal, device +//! lists and loss detection pub mod encode; pub mod framer; +pub mod mixer; pub mod pcm; +pub mod process; pub mod resample; +pub mod settings; +pub mod vad; pub mod wav; #[cfg(feature = "device")] @@ -20,10 +28,11 @@ pub mod device; pub use encode::{VoiceCodec, VoiceEncoder}; pub use framer::Framer; +pub use mixer::Mixer; +pub use process::{ProcessingSettings, Processor}; +pub use settings::AudioSettings; pub use tsclientlib::audio::AudioHandler; - -/// Jitter buffer, decoder and mixer for incoming voice, keyed by sender. -pub type Mixer = AudioHandler; +pub use vad::{Vad, VadSettings}; #[derive(Debug, thiserror::Error)] pub enum Error { diff --git a/crates/tsc-audio/src/mixer.rs b/crates/tsc-audio/src/mixer.rs new file mode 100644 index 0000000..1b56142 --- /dev/null +++ b/crates/tsc-audio/src/mixer.rs @@ -0,0 +1,219 @@ +//! Incoming voice: per-client jitter buffer, decoder and mixer, with a +//! volume and mute per client. +//! +//! The jitter buffer is the vendored `tsclientlib::audio::AudioHandler`. Per +//! sender it keeps a queue of Opus packets and adapts its length: +//! +//! - a new talker starts after a pre-buffer derived from the queue lengths of +//! the other talkers (none for the first one); +//! - a queue that underruns plays Opus packet-loss concealment for the +//! missing packet (one inserted frame) and drops the talker after three +//! frames in a row without data, so a slow sender never lets latency grow; +//! - when the smallest queue length over the last 255 decoded packets exceeds +//! its spread (a fast sender, or a jitter spike that passed), every 100th +//! sample of the decoded frame is dropped (1 % faster playback) until the +//! surplus is gone; above 0.5 s the queue is truncated outright. +//! +//! So sender clock drift is absorbed by occasional 1 % speed-ups (fast +//! sender) or concealment frames (slow sender) and latency stays bounded; the +//! `drift` integration test simulates an hour at ±200 ppm to check that. + +use std::collections::{HashMap, HashSet}; + +use tsclientlib::ClientId; +use tsclientlib::audio::{AudioHandler, Error as QueueError}; +use tsproto_packets::packets::InAudioBuf; + +/// Loudest per-client volume: +12 dB. +pub const MAX_CLIENT_VOLUME: f32 = 4.0; + +/// Jitter buffer, decoder and mixer for incoming voice, keyed by sender. +/// Output is interleaved stereo at 48 kHz. +#[derive(Default)] +pub struct Mixer { + handler: AudioHandler, + volumes: HashMap, + muted: HashSet, +} + +impl Mixer { + pub fn new() -> Self { + Self::default() + } + + /// Queue a voice packet from `id`. Returns `Some(id)` when this client + /// just started talking. Late, duplicate and malformed packets are + /// errors; on UDP they are expected and can be ignored. + pub fn handle_packet( + &mut self, + id: ClientId, + packet: InAudioBuf, + ) -> Result, QueueError> { + self.handler.handle_packet(id, packet) + } + + /// Add the next `buf.len() / 2` stereo frames of all talkers to `buf` + /// (not cleared first), each scaled by its volume. Returns the clients + /// that stopped talking. + pub fn fill_buffer(&mut self, buf: &mut [f32]) -> Vec { + for (id, queue) in self.handler.get_mut_queues() { + queue.volume = if self.muted.contains(id) { + 0.0 + } else { + self.volumes.get(id).copied().unwrap_or(1.0) + }; + } + // Muted talkers are still decoded so their queues stay in sync. + self.handler.fill_buffer(buf) + } + + /// Linear gain for one client, clamped to `0..=`[`MAX_CLIENT_VOLUME`]. + /// Kept when the client stops and starts talking again. + pub fn set_volume(&mut self, id: ClientId, volume: f32) { + let volume = if volume.is_finite() { volume.clamp(0.0, MAX_CLIENT_VOLUME) } else { 1.0 }; + if volume == 1.0 { + self.volumes.remove(&id); + } else { + self.volumes.insert(id, volume); + } + } + + /// Like [`set_volume`](Self::set_volume), in dB (0 dB = unchanged). + pub fn set_volume_db(&mut self, id: ClientId, db: f32) { + self.set_volume(id, 10f32.powf(db / 20.0)); + } + + pub fn volume(&self, id: ClientId) -> f32 { + self.volumes.get(&id).copied().unwrap_or(1.0) + } + + pub fn set_muted(&mut self, id: ClientId, muted: bool) { + if muted { + self.muted.insert(id); + } else { + self.muted.remove(&id); + } + } + + pub fn is_muted(&self, id: ClientId) -> bool { + self.muted.contains(&id) + } + + /// Forget volume and mute of a client (e.g. it left the server; client + /// ids are reused). + pub fn forget(&mut self, id: ClientId) { + self.volumes.remove(&id); + self.muted.remove(&id); + self.handler.get_mut_queues().remove(&id); + } + + /// Clients with a queue, i.e. currently talking or buffering. + pub fn talkers(&self) -> impl Iterator + '_ { + self.handler.get_queues().keys().copied() + } + + /// Drop all queues; volumes and mutes are kept. + pub fn reset(&mut self) { + self.handler.reset(); + } + + /// The underlying jitter buffer. + pub fn handler(&self) -> &AudioHandler { + &self.handler + } +} + +impl std::fmt::Debug for Mixer { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("Mixer") + .field("talkers", &self.handler.get_queues().len()) + .field("volumes", &self.volumes) + .field("muted", &self.muted) + .finish() + } +} + +#[cfg(test)] +mod tests { + use tsproto_packets::packets::{AudioData, CodecType, Direction, OutAudio}; + + use super::*; + use crate::VoiceEncoder; + use crate::encode::VoiceCodec; + use crate::pcm::{self, FRAME_SAMPLES, SAMPLE_RATE}; + + fn packet(from: u16, id: u16, data: &[u8]) -> InAudioBuf { + let packet = OutAudio::new(&AudioData::S2C { id, codec: CodecType::OpusVoice, from, data }); + InAudioBuf::try_new(Direction::S2C, packet.into_vec()).unwrap() + } + + /// Two clients send tones at the same level; after setting volumes the + /// mix carries each at its own gain, and a muted one not at all. + #[test] + fn volume_per_client() { + let (a, b) = (ClientId(3), ClientId(4)); + let mut enc_a = VoiceEncoder::new(VoiceCodec::Voice).unwrap(); + let mut enc_b = VoiceEncoder::new(VoiceCodec::Voice).unwrap(); + let tone_a = pcm::sine(500.0, 2.0, 0.2); + let tone_b = pcm::sine(1300.0, 2.0, 0.2); + + let mut mixer = Mixer::new(); + mixer.set_volume(a, 0.25); + mixer.set_volume_db(b, 6.0); + assert!((mixer.volume(b) - 1.995).abs() < 0.01); + let mut out = Vec::new(); + let frames = tone_a.chunks_exact(FRAME_SAMPLES).zip(tone_b.chunks_exact(FRAME_SAMPLES)); + for (i, (fa, fb)) in frames.enumerate() { + let id = i as u16; + let started = mixer.handle_packet(a, packet(3, id, enc_a.encode_to_bytes(fa).unwrap())); + if i == 0 { + assert_eq!(started.unwrap(), Some(a)); + } + mixer.handle_packet(b, packet(4, id, enc_b.encode_to_bytes(fb).unwrap())).unwrap(); + let mut buf = vec![0.0; FRAME_SAMPLES * 2]; + mixer.fill_buffer(&mut buf); + out.extend(pcm::to_mono(&buf, 2)); + } + assert_eq!(mixer.talkers().count(), 2); + let tail = &out[out.len() / 2..]; + let power = |f| pcm::goertzel_power(tail, f, SAMPLE_RATE); + // Amplitude ratio 0.25 / 2 = 1/8, power ratio 1/64 (-18 dB). + let ratio_db = 10.0 * (power(500.0) / power(1300.0)).log10(); + assert!((ratio_db + 18.0).abs() < 1.5, "ratio {ratio_db} dB"); + + // Mute b: only a remains. + mixer.set_muted(b, true); + let mut out = Vec::new(); + for i in 0..20u16 { + let id = 100 + i; + let fa = &tone_a[..FRAME_SAMPLES]; + let fb = &tone_b[..FRAME_SAMPLES]; + let _ = mixer.handle_packet(a, packet(3, id, enc_a.encode_to_bytes(fa).unwrap())); + let _ = mixer.handle_packet(b, packet(4, id, enc_b.encode_to_bytes(fb).unwrap())); + let mut buf = vec![0.0; FRAME_SAMPLES * 2]; + mixer.fill_buffer(&mut buf); + out.extend(pcm::to_mono(&buf, 2)); + } + let tail = &out[out.len() / 2..]; + assert!(pcm::goertzel_power(tail, 1300.0, SAMPLE_RATE) < 1e-6); + assert!(pcm::goertzel_power(tail, 500.0, SAMPLE_RATE) > 1e-4); + } + + #[test] + fn volume_bounds_and_forget() { + let mut mixer = Mixer::new(); + let id = ClientId(9); + mixer.set_volume(id, 100.0); + assert_eq!(mixer.volume(id), MAX_CLIENT_VOLUME); + mixer.set_volume(id, -1.0); + assert_eq!(mixer.volume(id), 0.0); + mixer.set_volume(id, f32::NAN); + assert_eq!(mixer.volume(id), 1.0); + mixer.set_volume(id, 0.5); + mixer.set_muted(id, true); + assert!(mixer.is_muted(id)); + mixer.forget(id); + assert!(!mixer.is_muted(id)); + assert_eq!(mixer.volume(id), 1.0); + } +} diff --git a/crates/tsc-audio/src/pcm.rs b/crates/tsc-audio/src/pcm.rs index ade1a22..15b1c64 100644 --- a/crates/tsc-audio/src/pcm.rs +++ b/crates/tsc-audio/src/pcm.rs @@ -13,6 +13,20 @@ pub fn sine(freq: f32, seconds: f32, amplitude: f32) -> Vec { (0..n).map(|i| amplitude * (TAU * freq * i as f32 / SAMPLE_RATE as f32).sin()).collect() } +/// Deterministic white noise, uniform in `[-amplitude, amplitude]`, for tests +/// and calibration. +pub fn white_noise(n: usize, amplitude: f32, seed: u64) -> Vec { + // PCG-style LCG; the top 24 bits are uniform enough. + let mut state = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + (0..n) + .map(|_| { + state = state.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + let x = (state >> 40) as f32 / (1u64 << 24) as f32; + amplitude * (2.0 * x - 1.0) + }) + .collect() +} + /// Average interleaved channels into mono. pub fn to_mono(interleaved: &[f32], channels: usize) -> Vec { if channels <= 1 { @@ -93,6 +107,17 @@ mod tests { assert_eq!(voiced_tone_ratio(&[0.0; 48_000], 1000.0, SAMPLE_RATE), 0.0); } + #[test] + fn noise_is_white_and_deterministic() { + let n = white_noise(48_000, 0.5, 1); + assert_eq!(n, white_noise(48_000, 0.5, 1)); + assert_ne!(n, white_noise(48_000, 0.5, 2)); + assert!(n.iter().all(|s| s.abs() <= 0.5)); + // Uniform in ±a has energy a²/3. + assert!((energy(&n) - 0.25 / 3.0).abs() < 0.005); + assert!(tone_ratio(&n, 1000.0, SAMPLE_RATE) < 0.01); + } + #[test] fn channel_conversion() { assert_eq!(to_mono(&[1.0, 3.0, 2.0, 4.0], 2), vec![2.0, 3.0]); diff --git a/crates/tsc-audio/src/process.rs b/crates/tsc-audio/src/process.rs new file mode 100644 index 0000000..ee36b09 --- /dev/null +++ b/crates/tsc-audio/src/process.rs @@ -0,0 +1,363 @@ +//! Microphone processing: echo cancellation, noise suppression and automatic +//! gain control. +//! +//! Backed by [sonora](https://crates.io/crates/sonora) (BSD-3-Clause), a pure +//! Rust port of the WebRTC audio processing module (AEC3, NS, AGC2): no C++ +//! toolchain or system library needed, so it builds the same on Linux, +//! Windows and Android. +//! +//! The [`Processor`] runs on 10 ms mono frames at 48 kHz. The far end, i.e. +//! exactly what goes to the speakers (the mixer output after per-client volume +//! and output mute), is fed through [`Processor::render`]; the microphone +//! through [`Processor::capture`]. Both accept any length and frame internally. + +use serde::{Deserialize, Serialize}; +use sonora::config::{ + AdaptiveDigital, CaptureLevelAdjustment, EchoCanceller, GainController2, HighPassFilter, + MaxProcessingRate, NoiseSuppression, NoiseSuppressionLevel, Pipeline, +}; +use sonora::{AudioProcessing, Config, StreamConfig}; + +use crate::Framer; +use crate::pcm::SAMPLE_RATE; + +/// Samples in one 10 ms processing frame (mono, 48 kHz). +pub const PROCESS_FRAME: usize = SAMPLE_RATE as usize / 100; + +/// How hard noise suppression works. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum NoiseLevel { + /// About 6 dB. + Low, + /// About 12 dB. + #[default] + Moderate, + /// About 18 dB. + High, + /// About 21 dB. + VeryHigh, +} + +impl From for NoiseSuppressionLevel { + fn from(level: NoiseLevel) -> Self { + match level { + NoiseLevel::Low => Self::Low, + NoiseLevel::Moderate => Self::Moderate, + NoiseLevel::High => Self::High, + NoiseLevel::VeryHigh => Self::VeryHigh, + } + } +} + +/// User settings for microphone processing. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct ProcessingSettings { + /// Remove what the speakers play from the microphone signal. + pub echo_cancellation: bool, + /// Remove steady background noise (fans, hum, hiss). + pub noise_suppression: bool, + pub noise_level: NoiseLevel, + /// Bring speech to a steady level (adaptive digital gain and limiter). + pub auto_gain: bool, + /// Manual microphone gain in dB, applied before everything else. + /// Clamped to ±[`MAX_INPUT_GAIN_DB`]. + pub input_gain_db: f32, + /// Remove rumble below ~80 Hz. Always on while echo cancellation is. + pub high_pass: bool, +} + +/// Limit of [`ProcessingSettings::input_gain_db`]. +pub const MAX_INPUT_GAIN_DB: f32 = 30.0; + +impl Default for ProcessingSettings { + fn default() -> Self { + Self { + echo_cancellation: true, + noise_suppression: true, + noise_level: NoiseLevel::Moderate, + auto_gain: true, + input_gain_db: 0.0, + high_pass: true, + } + } +} + +impl ProcessingSettings { + /// Everything off: the processor passes audio through untouched. + pub fn off() -> Self { + Self { + echo_cancellation: false, + noise_suppression: false, + noise_level: NoiseLevel::Moderate, + auto_gain: false, + input_gain_db: 0.0, + high_pass: false, + } + } + + fn input_gain(&self) -> f32 { + let db = if self.input_gain_db.is_finite() { self.input_gain_db } else { 0.0 }; + 10f32.powf(db.clamp(-MAX_INPUT_GAIN_DB, MAX_INPUT_GAIN_DB) / 20.0) + } + + fn is_passthrough(&self) -> bool { + !self.echo_cancellation + && !self.noise_suppression + && !self.auto_gain + && !self.high_pass + && self.input_gain() == 1.0 + } + + fn to_config(&self) -> Config { + let gain = self.input_gain(); + Config { + pipeline: Pipeline { + // Full band: voice is Opus at 48 kHz. + maximum_internal_processing_rate: MaxProcessingRate::Rate48kHz, + ..Default::default() + }, + capture_level_adjustment: (gain != 1.0) + .then(|| CaptureLevelAdjustment { pre_gain_factor: gain, ..Default::default() }), + high_pass_filter: self.high_pass.then(HighPassFilter::default), + echo_canceller: self.echo_cancellation.then(EchoCanceller::default), + noise_suppression: self + .noise_suppression + .then(|| NoiseSuppression { level: self.noise_level.into(), ..Default::default() }), + gain_controller2: self.auto_gain.then(|| GainController2 { + adaptive_digital: Some(AdaptiveDigital::default()), + ..Default::default() + }), + ..Default::default() + } + } +} + +/// Echo canceller statistics, for diagnostics. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct ProcessingStats { + /// Echo return loss enhancement in dB: how much echo the canceller removes. + pub erle_db: Option, + /// Render-to-capture delay the canceller estimated. + pub delay_ms: Option, +} + +/// Microphone processing pipeline stage. See the [module docs](self). +pub struct Processor { + apm: AudioProcessing, + settings: ProcessingSettings, + passthrough: bool, + delay_ms: u32, + render_framer: Framer, + capture_framer: Framer, + frame: Vec, +} + +impl Processor { + pub fn new(settings: &ProcessingSettings) -> Self { + let stream = StreamConfig::new(SAMPLE_RATE, 1); + let apm = AudioProcessing::builder() + .config(settings.to_config()) + .capture_config(stream) + .render_config(stream) + .build(); + Self { + apm, + settings: settings.clone(), + passthrough: settings.is_passthrough(), + delay_ms: 0, + render_framer: Framer::new(PROCESS_FRAME), + capture_framer: Framer::new(PROCESS_FRAME), + frame: vec![0.0; PROCESS_FRAME], + } + } + + pub fn settings(&self) -> &ProcessingSettings { + &self.settings + } + + /// Change settings. Only reconfigures when something changed, since that + /// resets the adaptive filters. + pub fn apply(&mut self, settings: &ProcessingSettings) { + if *settings == self.settings { + return; + } + self.apm.apply_config(settings.to_config()); + self.settings = settings.clone(); + self.passthrough = settings.is_passthrough(); + } + + /// Hint for the echo canceller: time from handing a frame to + /// [`render`](Self::render) until it is heard, plus time from the + /// microphone picking a sample up until it reaches + /// [`capture`](Self::capture). The canceller estimates the rest itself. + pub fn set_delay_ms(&mut self, delay_ms: u32) { + if delay_ms != self.delay_ms { + self.delay_ms = delay_ms; + // Values above 500 ms are clamped, which is fine for a hint. + let _ = self.apm.set_stream_delay_ms(delay_ms.min(500) as i32); + } + } + + /// Feed far-end audio: mono 48 kHz, exactly as played. + pub fn render(&mut self, samples: &[f32]) { + if !self.settings.echo_cancellation { + return; + } + let Self { apm, render_framer, frame, .. } = self; + render_framer.push(samples, |f| { + // Render output is not used: no render-side processing is enabled. + let _ = apm.process_render_f32(&[f], &mut [frame.as_mut_slice()]); + }); + } + + /// Process microphone audio (mono 48 kHz), appending the result to `out`. + /// Output comes in whole 10 ms frames, so up to 10 ms stay buffered. + pub fn capture(&mut self, samples: &[f32], out: &mut Vec) { + if self.passthrough && self.capture_framer.buffered() == 0 { + out.extend_from_slice(samples); + return; + } + let Self { apm, capture_framer, frame, passthrough, .. } = self; + capture_framer.push(samples, |f| { + if *passthrough { + out.extend_from_slice(f); + } else if apm.process_capture_f32(&[f], &mut [frame.as_mut_slice()]).is_ok() { + out.extend_from_slice(frame); + } else { + out.extend_from_slice(f); + } + }); + } + + pub fn stats(&self) -> ProcessingStats { + let stats = self.apm.statistics(); + ProcessingStats { erle_db: stats.echo_return_loss_enhancement, delay_ms: stats.delay_ms } + } +} + +impl std::fmt::Debug for Processor { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("Processor").field("settings", &self.settings).finish_non_exhaustive() + } +} + +#[cfg(test)] +mod tests { + use std::f32::consts::TAU; + + use super::*; + use crate::pcm::{self, energy, white_noise as noise}; + + fn db(ratio: f32) -> f32 { + 10.0 * ratio.max(1e-20).log10() + } + + #[test] + fn passthrough_when_off() { + let mut p = Processor::new(&ProcessingSettings::off()); + let input = pcm::sine(440.0, 0.05, 0.3); + let mut out = Vec::new(); + p.capture(&input[..100], &mut out); + p.capture(&input[100..], &mut out); + assert_eq!(out, input); + } + + #[test] + fn input_gain_is_clamped() { + let s = ProcessingSettings { input_gain_db: 1000.0, ..ProcessingSettings::off() }; + assert!((s.input_gain() - 10f32.powf(1.5)).abs() < 1e-3); + let s = ProcessingSettings { input_gain_db: f32::NAN, ..ProcessingSettings::off() }; + assert_eq!(s.input_gain(), 1.0); + let s = ProcessingSettings { input_gain_db: 6.0, ..ProcessingSettings::off() }; + assert!(!s.is_passthrough()); + } + + #[test] + fn settings_serde_defaults() { + let s: ProcessingSettings = serde_json::from_str(r#"{"noise_level":"very_high"}"#).unwrap(); + assert_eq!(s.noise_level, NoiseLevel::VeryHigh); + assert!(s.echo_cancellation); + } + + /// The far end leaks into the microphone 40 ms later at -6 dB; after the + /// canceller converged the echo must be at least 10 dB quieter. + #[test] + fn cancels_synthetic_echo() { + let settings = ProcessingSettings { + echo_cancellation: true, + high_pass: true, + ..ProcessingSettings::off() + }; + let mut p = Processor::new(&settings); + p.set_delay_ms(40); + let seconds = 6; + let delay = 40 * PROCESS_FRAME / 10; + // Speech-like far end: noise with a syllable-rate envelope. + let far: Vec = noise(SAMPLE_RATE as usize * seconds, 0.4, 1) + .into_iter() + .enumerate() + .map(|(i, s)| s * (0.6 + 0.4 * (i as f32 * 4.0 / SAMPLE_RATE as f32 * TAU).sin())) + .collect(); + let mut near = vec![0.0; delay]; + near.extend(far.iter().map(|s| s * 0.5)); + near.truncate(far.len()); + + let mut out = Vec::new(); + for (f, n) in far.chunks(PROCESS_FRAME).zip(near.chunks(PROCESS_FRAME)) { + p.render(f); + p.capture(n, &mut out); + } + assert_eq!(out.len(), near.len()); + let tail = SAMPLE_RATE as usize * 2; + let before = energy(&near[near.len() - tail..]); + let after = energy(&out[out.len() - tail..]); + let attenuation = db(before / after); + assert!(attenuation >= 10.0, "echo attenuated by {attenuation:.1} dB"); + } + + /// White noise gets quieter while a tone on top of it survives. The tone + /// comes in 200 ms bursts like syllables: a steady tone is stationary and + /// a noise suppressor rightly learns it as noise. + #[test] + fn suppresses_noise_keeps_tone() { + let settings = ProcessingSettings { + noise_suppression: true, + noise_level: NoiseLevel::High, + ..ProcessingSettings::off() + }; + let seconds = 4; + let n = SAMPLE_RATE as usize * seconds; + let hiss = noise(n, 0.05, 7); + + let mut p = Processor::new(&settings); + let mut out = Vec::new(); + p.capture(&hiss, &mut out); + let tail = SAMPLE_RATE as usize; + let reduction = db(energy(&hiss[n - tail..]) / energy(&out[n - tail..])); + assert!(reduction >= 10.0, "noise reduced by {reduction:.1} dB"); + + let ms = |ms: usize| ms * SAMPLE_RATE as usize / 1000; + let tone: Vec = pcm::sine(600.0, seconds as f32, 0.3) + .into_iter() + .enumerate() + .map(|(i, s)| if i % ms(400) < ms(200) { s } else { 0.0 }) + .collect(); + let mixed: Vec = tone.iter().zip(&hiss).map(|(a, b)| a + b).collect(); + let mut p = Processor::new(&settings); + let mut out = Vec::new(); + p.capture(&mixed, &mut out); + // The last two seconds, away from the burst edges. + for start in (n - ms(2000)..n).step_by(ms(400)) { + let on = start + ms(40)..start + ms(160); + let tone_in = pcm::goertzel_power(&tone[on.clone()], 600.0, SAMPLE_RATE); + let tone_out = pcm::goertzel_power(&out[on], 600.0, SAMPLE_RATE); + let loss = db(tone_in / tone_out); + assert!(loss.abs() < 3.0, "tone changed by {loss:.1} dB"); + let off = start + ms(240)..start + ms(360); + let reduction = db(energy(&hiss[off.clone()]) / energy(&out[off])); + assert!(reduction >= 6.0, "noise between bursts reduced by {reduction:.1} dB"); + } + } +} diff --git a/crates/tsc-audio/src/settings.rs b/crates/tsc-audio/src/settings.rs new file mode 100644 index 0000000..450195a --- /dev/null +++ b/crates/tsc-audio/src/settings.rs @@ -0,0 +1,80 @@ +//! All user audio settings in one serde struct, e.g. for +//! `tsc_store::Store::set_setting("audio", &settings)`. Missing fields take +//! their defaults, so stored settings survive new options. + +use serde::{Deserialize, Serialize}; + +use crate::process::ProcessingSettings; +use crate::vad::VadSettings; + +/// When the microphone is sent. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum TransmitMode { + /// While the push-to-talk key or button is held. + #[default] + PushToTalk, + /// While the voice activity detector hears speech. + VoiceActivation, + /// Always (unless muted). + Continuous, +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct AudioSettings { + pub transmit: TransmitMode, + pub processing: ProcessingSettings, + pub vad: VadSettings, + /// Microphone by device id (`device::DeviceInfo::id`); `None` follows + /// the system default. + pub input_device: Option, + /// Speakers by device id; `None` follows the system default. + pub output_device: Option, + /// Output volume for everyone, linear (1 = unchanged), applied before + /// the echo canceller sees the signal. + pub output_volume: f32, + /// Audio kept queued for the speakers. Lower is snappier, higher + /// survives scheduling hiccups. + pub playback_buffer_ms: u32, +} + +impl Default for AudioSettings { + fn default() -> Self { + Self { + transmit: TransmitMode::PushToTalk, + processing: ProcessingSettings::default(), + vad: VadSettings::default(), + input_device: None, + output_device: None, + output_volume: 1.0, + playback_buffer_ms: 60, + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn json_roundtrip_and_defaults() { + let mut s = AudioSettings { + transmit: TransmitMode::VoiceActivation, + input_device: Some("alsa:hw:1,0".into()), + ..Default::default() + }; + s.processing.echo_cancellation = false; + s.vad.threshold_db = -35.0; + let json = serde_json::to_string(&s).unwrap(); + assert_eq!(serde_json::from_str::(&json).unwrap(), s); + + // Older or partial settings fill in defaults. + let partial: AudioSettings = + serde_json::from_str(r#"{"transmit":"continuous","vad":{"hangover_ms":100}}"#).unwrap(); + assert_eq!(partial.transmit, TransmitMode::Continuous); + assert_eq!(partial.vad.hangover_ms, 100); + assert_eq!(partial.vad.threshold_db, VadSettings::default().threshold_db); + assert_eq!(partial.processing, ProcessingSettings::default()); + } +} diff --git a/crates/tsc-audio/src/vad.rs b/crates/tsc-audio/src/vad.rs new file mode 100644 index 0000000..1f1dc43 --- /dev/null +++ b/crates/tsc-audio/src/vad.rs @@ -0,0 +1,250 @@ +//! Voice activity detection for voice-activated transmission. +//! +//! A level gate with hangover, optionally combined with the RNN speech +//! detector of WebRTC's AGC2 (through sonora), which ignores noise such as +//! typing, fans or breathing that is loud enough to pass the level gate. +//! Works on 10 ms mono frames at 48 kHz, after [`Processor`](crate::process::Processor). + +use serde::{Deserialize, Serialize}; +use sonora_agc2::vad_wrapper::VoiceActivityDetectorWrapper; + +use crate::pcm::SAMPLE_RATE; +use crate::process::PROCESS_FRAME; + +/// What opens the gate. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum VadMode { + /// The level is above the threshold. + #[default] + Level, + /// The level is above the threshold and the frame sounds like speech. + Speech, +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct VadSettings { + pub mode: VadMode, + /// Level in dBFS (RMS of a 10 ms frame; a full-scale sine is -3 dBFS) + /// that opens the gate. + pub threshold_db: f32, + /// Keep transmitting this long after the last active frame, so word + /// endings and short pauses are not cut. + pub hangover_ms: u32, + /// Speech probability (0 to 1) needed in [`VadMode::Speech`]. + pub speech_probability: f32, +} + +impl Default for VadSettings { + fn default() -> Self { + // Speech after automatic gain control sits around -20 dBFS and the + // controller keeps noise below -50 dBFS. + Self { + mode: VadMode::Level, + threshold_db: -40.0, + hangover_ms: 300, + speech_probability: 0.6, + } + } +} + +/// Level of silence, so the meter has a floor. +pub const SILENCE_DB: f32 = -100.0; + +/// RMS level in dBFS. +pub fn level_db(samples: &[f32]) -> f32 { + let e = crate::pcm::energy(samples); + if e > 0.0 { (10.0 * e.log10()).max(SILENCE_DB) } else { SILENCE_DB } +} + +/// Voice activity detector. See the [module docs](self). +pub struct Vad { + settings: VadSettings, + rnn: Option, + scaled: Vec, + hang_remaining_ms: u32, + level_db: f32, + probability: f32, +} + +impl Vad { + pub fn new(settings: &VadSettings) -> Self { + let mut vad = Self { + settings: settings.clone(), + rnn: None, + scaled: vec![0.0; PROCESS_FRAME], + hang_remaining_ms: 0, + level_db: SILENCE_DB, + probability: 0.0, + }; + vad.apply(settings); + vad + } + + pub fn settings(&self) -> &VadSettings { + &self.settings + } + + pub fn apply(&mut self, settings: &VadSettings) { + if settings.mode == VadMode::Speech && self.rnn.is_none() { + self.rnn = Some(VoiceActivityDetectorWrapper::new( + sonora_simd::detect_backend(), + SAMPLE_RATE as i32, + )); + } else if settings.mode != VadMode::Speech { + self.rnn = None; + self.probability = 0.0; + } + self.settings = settings.clone(); + } + + /// Analyse mono 48 kHz audio, a whole number of 10 ms frames (a + /// trailing partial frame is ignored). Returns whether to transmit. + pub fn process(&mut self, samples: &[f32]) -> bool { + for frame in samples.chunks_exact(PROCESS_FRAME) { + self.level_db = level_db(frame); + let mut active = self.level_db >= self.settings.threshold_db; + if let Some(rnn) = &mut self.rnn { + // The detector works on 16-bit scale floats. + for (dst, src) in self.scaled.iter_mut().zip(frame) { + *dst = src * 32768.0; + } + self.probability = rnn.analyze(&self.scaled); + active &= self.probability >= self.settings.speech_probability; + } + if active { + // Plus this frame itself. + self.hang_remaining_ms = self.settings.hangover_ms + 10; + } else { + self.hang_remaining_ms = self.hang_remaining_ms.saturating_sub(10); + } + } + self.is_active() + } + + /// Whether the gate is open after the last frame. + pub fn is_active(&self) -> bool { + self.hang_remaining_ms > 0 + } + + /// Level of the last frame in dBFS, for a microphone meter. + pub fn level_db(&self) -> f32 { + self.level_db + } + + /// Speech probability of the last frame, 0 unless in [`VadMode::Speech`]. + pub fn speech_probability(&self) -> f32 { + self.probability + } + + /// Close the gate immediately (e.g. when switching to push-to-talk). + pub fn reset(&mut self) { + self.hang_remaining_ms = 0; + } +} + +impl std::fmt::Debug for Vad { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("Vad") + .field("settings", &self.settings) + .field("level_db", &self.level_db) + .field("active", &self.is_active()) + .finish_non_exhaustive() + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::pcm::{self, white_noise as noise}; + + /// A voiced sound: a 120 Hz pulse train through three vowel formants, + /// scaled to `amplitude` peak. + pub(crate) fn vowel(seconds: f32, amplitude: f32) -> Vec { + let n = (seconds * SAMPLE_RATE as f32) as usize; + let pulses: Vec = + (0..n).map(|i| if i % (SAMPLE_RATE as usize / 120) == 0 { 1.0 } else { 0.0 }).collect(); + let resonate = |freq: f32, bandwidth: f32| -> Vec { + let r = (-std::f32::consts::PI * bandwidth / SAMPLE_RATE as f32).exp(); + let c = 2.0 * r * (std::f32::consts::TAU * freq / SAMPLE_RATE as f32).cos(); + let (mut y1, mut y2) = (0.0f32, 0.0f32); + pulses + .iter() + .map(|&x| { + let y = x * (1.0 - r) + c * y1 - r * r * y2; + (y2, y1) = (y1, y); + y + }) + .collect() + }; + let (f1, f2, f3) = (resonate(700.0, 80.0), resonate(1200.0, 90.0), resonate(2600.0, 120.0)); + let mix: Vec = (0..n).map(|i| f1[i] + 0.6 * f2[i] + 0.3 * f3[i]).collect(); + let peak = mix.iter().fold(0.0f32, |m, s| m.max(s.abs())); + mix.iter().map(|s| s / peak * amplitude).collect() + } + + fn active_fraction(vad: &mut Vad, signal: &[f32]) -> f32 { + let frames: Vec = + signal.chunks_exact(PROCESS_FRAME).map(|f| vad.process(f)).collect(); + frames.iter().filter(|&&a| a).count() as f32 / frames.len() as f32 + } + + #[test] + fn level() { + assert_eq!(level_db(&[0.0; 480]), SILENCE_DB); + assert!((level_db(&pcm::sine(1000.0, 0.01, 1.0)) + 3.01).abs() < 0.1); + assert!((level_db(&[0.1; 480]) + 20.0).abs() < 0.01); + } + + #[test] + fn gate_and_hangover() { + let settings = VadSettings { hangover_ms: 50, ..Default::default() }; + let mut vad = Vad::new(&settings); + let loud = pcm::sine(300.0, 0.01, 0.1); + let quiet = vec![0.001; PROCESS_FRAME]; + assert!(!vad.process(&quiet)); + assert!(vad.process(&loud)); + // 50 ms of hangover after the last loud frame, then closed. + for _ in 0..5 { + assert!(vad.process(&quiet)); + } + assert!(!vad.process(&quiet)); + // A 20 ms frame is analysed as two 10 ms frames. + assert!(vad.process(&[loud.clone(), loud].concat())); + vad.reset(); + assert!(!vad.is_active()); + } + + #[test] + fn threshold_is_respected() { + let mut vad = + Vad::new(&VadSettings { threshold_db: -30.0, hangover_ms: 0, ..Default::default() }); + // -33 dBFS stays closed, -23 dBFS opens. + assert!(!vad.process(&pcm::sine(300.0, 0.01, 0.0316))); + assert!(vad.process(&pcm::sine(300.0, 0.01, 0.1))); + } + + /// In speech mode, noise loud enough for the level gate stays out, a + /// voiced sound gets through. + #[test] + fn speech_mode_rejects_noise() { + let settings = VadSettings { mode: VadMode::Speech, hangover_ms: 0, ..Default::default() }; + let hiss = noise(SAMPLE_RATE as usize * 2, 0.05, 3); + assert!(level_db(&hiss) > settings.threshold_db); + let mut level_only = Vad::new(&VadSettings { mode: VadMode::Level, ..settings.clone() }); + assert!(active_fraction(&mut level_only, &hiss) > 0.99); + let mut vad = Vad::new(&settings); + let noise_active = active_fraction(&mut vad, &hiss); + assert!(noise_active < 0.1, "noise active {noise_active}"); + + let mut vad = Vad::new(&settings); + let voice_active = active_fraction(&mut vad, &vowel(2.0, 0.3)); + assert!(voice_active > 0.8, "voice active {voice_active}"); + assert!(vad.speech_probability() > 0.5); + + // Switching back to level mode drops the detector. + vad.apply(&VadSettings::default()); + assert_eq!(vad.speech_probability(), 0.0); + } +} diff --git a/crates/tsc-audio/tests/drift.rs b/crates/tsc-audio/tests/drift.rs new file mode 100644 index 0000000..306c5d6 --- /dev/null +++ b/crates/tsc-audio/tests/drift.rs @@ -0,0 +1,129 @@ +//! A one-hour call with a sender whose clock runs ±200 ppm off ours: the +//! jitter buffer must keep the latency bounded instead of drifting by the +//! 720 ms the clocks disagree over an hour. +//! +//! The sender transmits continuously (the worst case: talk spurts would reset +//! the queue) over a network with 20–60 ms of jitter, reordering and 0.5 % +//! loss. Every 30 s it sends a loud marker frame instead of the quiet one; +//! the latency is the time from generating a marker to it leaving the mixer. + +use tsc_audio::pcm::{FRAME_SAMPLES, SAMPLE_RATE, energy, sine, white_noise}; +use tsc_audio::{Mixer, VoiceCodec, VoiceEncoder}; +use tsclientlib::ClientId; +use tsproto_packets::packets::{AudioData, CodecType, Direction, InAudioBuf, OutAudio}; + +/// The receiver pulls 10 ms at a time, like a playback loop. +const PULL: usize = SAMPLE_RATE as usize / 100; +const MARKER_EVERY: u64 = 1500; + +struct Rng(u64); + +impl Rng { + fn next(&mut self) -> f64 { + self.0 = self.0.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + (self.0 >> 11) as f64 / (1u64 << 53) as f64 + } +} + +/// Returns the latency of each marker in ms, in order. +fn simulate(ppm: f64, hours: f64) -> Vec { + let mut encoder = VoiceEncoder::new(VoiceCodec::Voice).unwrap(); + // A quiet frame (-65 dBFS noise) and a loud marker, encoded once. + let quiet = white_noise(FRAME_SAMPLES, 0.001, 1); + for _ in 0..5 { + encoder.encode_to_bytes(&quiet).unwrap(); + } + let quiet = encoder.encode_to_bytes(&quiet).unwrap().to_vec(); + let marker = encoder.encode_to_bytes(&sine(1000.0, 0.02, 0.5)).unwrap().to_vec(); + + let mut rng = Rng(ppm.to_bits()); + let mut mixer = Mixer::new(); + let client = ClientId(5); + let total = (hours * 3600.0 * SAMPLE_RATE as f64) as u64; + // Sender frame n is made at n * 20 ms of the sender's clock. + let frame_time = |n: u64| n as f64 * FRAME_SAMPLES as f64 / (1.0 + ppm * 1e-6); + + // (arrival time, packet id), kept sorted by arrival. + let mut in_flight: Vec<(f64, u64)> = Vec::new(); + let mut next_frame = 0u64; + let mut markers_sent = Vec::new(); + let mut latencies = Vec::new(); + let mut out = vec![0.0f32; PULL * 2]; + let mut now = 0u64; + while now < total { + // Everything the sender produced up to now goes on the wire. + while frame_time(next_frame) <= now as f64 { + let is_marker = next_frame % MARKER_EVERY == MARKER_EVERY / 2; + if is_marker { + markers_sent.push(frame_time(next_frame)); + } + // Markers are never lost, so each one can be matched. + if is_marker || rng.next() >= 0.005 { + let jitter = (0.02 + 0.04 * rng.next()) * SAMPLE_RATE as f64; + in_flight.push((frame_time(next_frame) + jitter, next_frame)); + } + next_frame += 1; + } + in_flight.sort_by(|a, b| a.0.total_cmp(&b.0)); + let arrived = in_flight.partition_point(|&(t, _)| t <= now as f64); + for (_, n) in in_flight.drain(..arrived) { + let data = if n % MARKER_EVERY == MARKER_EVERY / 2 { &marker } else { &quiet }; + let packet = OutAudio::new(&AudioData::S2C { + id: n as u16, + codec: CodecType::OpusVoice, + from: 5, + data, + }); + let packet = InAudioBuf::try_new(Direction::S2C, packet.into_vec()).unwrap(); + // Late packets are dropped by the jitter buffer, as on a real network. + let _ = mixer.handle_packet(client, packet); + } + + out.fill(0.0); + mixer.fill_buffer(&mut out); + let left: Vec = out.iter().step_by(2).copied().collect(); + if energy(&left) > 1e-3 { + // The latest marker made before now; they are 30 s apart. + let sent = markers_sent.iter().rev().find(|&&t| t <= now as f64).copied(); + if let Some(sent) = sent { + let latency = (now as f64 - sent) * 1000.0 / SAMPLE_RATE as f64; + // One detection per marker (it spans two 10 ms pulls). + if latencies.len() < markers_sent.len() && latency < 5000.0 { + let index = markers_sent.iter().position(|&t| t == sent).unwrap(); + if index == latencies.len() { + latencies.push(latency); + } + } + } + } + now += PULL as u64; + } + assert_eq!(latencies.len(), markers_sent.len(), "every marker must come out (ppm {ppm})"); + latencies +} + +fn check(ppm: f64) { + let latencies = simulate(ppm, 1.0); + assert_eq!(latencies.len(), 120); + let max = latencies.iter().copied().fold(0.0, f64::max); + let min = latencies.iter().copied().fold(f64::MAX, f64::min); + let first: f64 = latencies[..20].iter().sum::() / 20.0; + let last: f64 = latencies[latencies.len() - 20..].iter().sum::() / 20.0; + println!( + "{ppm:+} ppm: latency min {min:.0} ms, max {max:.0} ms, first 10 min avg {first:.0} ms, last 10 min avg {last:.0} ms" + ); + // The network alone adds 20-60 ms; unchecked drift would add 720 ms. + assert!(min >= 20.0, "latency {min} ms is below the network delay"); + assert!(max < 250.0, "latency grew to {max} ms"); + assert!((last - first).abs() < 60.0, "latency drifted from {first} ms to {last} ms"); +} + +#[test] +fn fast_sender_one_hour() { + check(200.0); +} + +#[test] +fn slow_sender_one_hour() { + check(-200.0); +} diff --git a/crates/tsc-core/Cargo.toml b/crates/tsc-core/Cargo.toml index c6a4644..fa9195b 100644 --- a/crates/tsc-core/Cargo.toml +++ b/crates/tsc-core/Cargo.toml @@ -26,6 +26,7 @@ tsc-gateway-proto = { path = "../tsc-gateway-proto" } tsc-model = { path = "../tsc-model" } tsc-observer = { path = "../tsc-observer" } tsc-query = { path = "../tsc-query" } +tsc-stream = { path = "../tsc-stream" } tsclientlib = { path = "../proto/tsclientlib" } tsproto-packets = { path = "../proto/tsproto-packets" } diff --git a/crates/tsc-core/src/audio.rs b/crates/tsc-core/src/audio.rs index 0fac225..cf97582 100644 --- a/crates/tsc-core/src/audio.rs +++ b/crates/tsc-core/src/audio.rs @@ -1,18 +1,23 @@ -//! Audio thread: capture → encode → voice connection, and incoming voice → -//! jitter buffer/mixer → playback. +//! Audio thread: capture → processing (echo cancellation, noise suppression, +//! gain) → voice activity / push-to-talk → encode → voice connection, and +//! incoming voice → jitter buffer/mixer (per-client volume) → playback, with +//! what is played fed back to the echo canceller as its reference. //! //! Devices live on their own OS thread (cpal streams are not `Send` on every -//! platform); the connection task talks to it through channels. +//! platform); the connection task talks to it through channels. The device +//! independent part is [`Pipeline`]; the thread loop only moves samples +//! between it and the devices, reopening devices that go away. +use std::collections::VecDeque; use std::sync::mpsc as std_mpsc; use std::thread; -use std::time::Duration; +use std::time::{Duration, Instant}; use tokio::sync::mpsc; use tracing::{debug, warn}; -use tsc_audio::pcm::{self, FRAME_SAMPLES, SAMPLE_RATE}; -use tsc_audio::resample::Linear; -use tsc_audio::{Framer, Mixer, VoiceCodec, VoiceEncoder}; +use tsc_audio::pcm::{self, FRAME_SAMPLES}; +use tsc_audio::settings::TransmitMode; +use tsc_audio::{AudioSettings, Framer, Mixer, Processor, Vad, VoiceCodec, VoiceEncoder}; use tsclientlib::ClientId; use tsproto_packets::packets::{AudioData, InAudioBuf, OutPacket}; @@ -21,6 +26,23 @@ pub(crate) enum AudioIn { Transmit(bool), InputMuted(bool), OutputMuted(bool), + /// Devices, processing, voice activation and transmit mode. + #[allow(dead_code, reason = "sent once the session exposes audio settings")] + Settings(Box), + /// Playback volume of one client, linear (1 = unchanged, up to 4). + #[allow(dead_code, reason = "sent once the session exposes client volumes")] + ClientVolume { + client: ClientId, + volume: f32, + }, + #[allow(dead_code, reason = "sent once the session exposes client volumes")] + ClientMuted { + client: ClientId, + muted: bool, + }, + /// The client left; client ids are reused, so forget its volume. + #[allow(dead_code, reason = "sent once the session exposes client volumes")] + ClientLeft(ClientId), } pub(crate) struct AudioHandle { @@ -33,24 +55,19 @@ impl AudioHandle { } } -/// Voice activity: transmit while the level is above the threshold, with a -/// short hang time so word endings are not cut. -struct Vad { - threshold: f32, - hang_frames: u32, - remaining: u32, -} - -impl Vad { - fn active(&mut self, frame: &[f32]) -> bool { - if pcm::energy(frame) > self.threshold { - self.remaining = self.hang_frames; - } else if self.remaining > 0 { - self.remaining -= 1; - } - self.remaining > 0 - } -} +/// With voice activation, also send this many 20 ms frames from before the +/// detector opened, so word onsets are not cut. +const PRE_ROLL_FRAMES: usize = 2; +/// Capacity of the speaker queue; [`AudioSettings::playback_buffer_ms`] is +/// clamped below it. +#[cfg(feature = "audio-device")] +const PLAYBACK_CAPACITY_MS: u32 = 200; +/// Latency of the devices beyond our queues, as a hint for the echo +/// canceller (it estimates the actual delay itself). +#[cfg(feature = "audio-device")] +const DEVICE_LATENCY_MS: u32 = 20; +/// How long the loop sleeps between rounds. +const TICK: Duration = Duration::from_millis(5); /// Start the audio thread. Encoded packets go to `outgoing`; problems (e.g. /// no device) are reported through `errors`. @@ -59,141 +76,464 @@ pub(crate) fn spawn( errors: mpsc::UnboundedSender, voice_activation: bool, ) -> AudioHandle { + let transmit = + if voice_activation { TransmitMode::VoiceActivation } else { TransmitMode::PushToTalk }; + let settings = AudioSettings { transmit, ..Default::default() }; let (tx, rx) = std_mpsc::channel(); thread::Builder::new() .name("tsc-audio".into()) - .spawn(move || run(rx, outgoing, errors, voice_activation)) + .spawn(move || run(rx, outgoing, errors, settings)) .expect("spawn audio thread"); AudioHandle { tx } } +/// Everything between the devices and the connection. +struct Pipeline { + settings: AudioSettings, + encoder: VoiceEncoder, + mixer: Mixer, + processor: Processor, + vad: Vad, + framer: Framer, + processed: Vec, + pre_roll: VecDeque>, + ptt: bool, + input_muted: bool, + output_muted: bool, + was_sending: bool, + /// Processed microphone audio, for tests. + #[cfg(test)] + tap: Vec, +} + +impl Pipeline { + fn new(settings: AudioSettings) -> tsc_audio::Result { + let settings = sanitize(settings); + Ok(Self { + encoder: VoiceEncoder::new(VoiceCodec::Voice)?, + mixer: Mixer::new(), + processor: Processor::new(&settings.processing), + vad: Vad::new(&settings.vad), + framer: Framer::new(FRAME_SAMPLES), + processed: Vec::new(), + pre_roll: VecDeque::new(), + ptt: false, + input_muted: false, + output_muted: false, + was_sending: false, + settings, + #[cfg(test)] + tap: Vec::new(), + }) + } + + fn handle(&mut self, msg: AudioIn) { + match msg { + AudioIn::Packet(packet) => { + let from = match packet.data().data() { + AudioData::S2C { from, .. } | AudioData::S2CWhisper { from, .. } => *from, + _ => return, + }; + if let Err(error) = self.mixer.handle_packet(ClientId(from), packet) { + debug!(%error, "dropped voice packet"); + } + } + AudioIn::Transmit(on) => self.ptt = on, + AudioIn::InputMuted(m) => self.input_muted = m, + AudioIn::OutputMuted(m) => self.output_muted = m, + AudioIn::Settings(settings) => { + let settings = sanitize(*settings); + self.processor.apply(&settings.processing); + self.vad.apply(&settings.vad); + if settings.transmit != TransmitMode::VoiceActivation { + self.vad.reset(); + self.pre_roll.clear(); + } + self.settings = settings; + } + AudioIn::ClientVolume { client, volume } => self.mixer.set_volume(client, volume), + AudioIn::ClientMuted { client, muted } => self.mixer.set_muted(client, muted), + AudioIn::ClientLeft(client) => self.mixer.forget(client), + } + } + + /// Microphone audio in (mono, 48 kHz, any length); voice packets out. + /// `delay_ms` is the playback-to-capture delay hint for the echo canceller. + fn capture(&mut self, samples: &[f32], delay_ms: u32, send: &mut impl FnMut(OutPacket)) { + self.processor.set_delay_ms(delay_ms); + self.processed.clear(); + self.processor.capture(samples, &mut self.processed); + #[cfg(test)] + self.tap.extend_from_slice(&self.processed); + let mut frames = Vec::new(); + self.framer.push(&self.processed, |f| frames.push(f.to_vec())); + for frame in frames { + self.transmit(frame, send); + } + } + + fn transmit(&mut self, frame: Vec, send: &mut impl FnMut(OutPacket)) { + // Always analysed, so the detector's state is current when needed. + let voice = self.vad.process(&frame); + let wanted = match self.settings.transmit { + TransmitMode::PushToTalk => self.ptt, + TransmitMode::VoiceActivation => voice, + TransmitMode::Continuous => true, + }; + let sending = wanted && !self.input_muted; + if sending { + let pre_roll: Vec<_> = self.pre_roll.drain(..).collect(); + for f in pre_roll.iter().chain([&frame]) { + match self.encoder.encode(f) { + Ok(packet) => send(packet), + Err(e) => warn!(%e, "encoding failed"), + } + } + } else { + if self.was_sending { + send(self.encoder.end_of_stream()); + } + if self.settings.transmit == TransmitMode::VoiceActivation { + self.pre_roll.push_back(frame); + if self.pre_roll.len() > PRE_ROLL_FRAMES { + self.pre_roll.pop_front(); + } + } + } + self.was_sending = sending; + } + + /// The next 20 ms for the speakers (mono, 48 kHz), which also becomes + /// the echo canceller's reference. + fn playback_frame(&mut self) -> Vec { + let mut stereo = vec![0.0; FRAME_SAMPLES * 2]; + self.mixer.fill_buffer(&mut stereo); + let gain = if self.output_muted { 0.0 } else { self.settings.output_volume }; + let mut mono = pcm::to_mono(&stereo, 2); + for s in &mut mono { + *s = (*s * gain).clamp(-1.0, 1.0); + } + self.processor.render(&mono); + mono + } +} + +fn sanitize(mut settings: AudioSettings) -> AudioSettings { + let volume = settings.output_volume; + settings.output_volume = if volume.is_finite() { volume.clamp(0.0, 4.0) } else { 1.0 }; + #[cfg(feature = "audio-device")] + { + settings.playback_buffer_ms = + settings.playback_buffer_ms.clamp(20, PLAYBACK_CAPACITY_MS - 20); + } + settings +} + fn run( rx: std_mpsc::Receiver, outgoing: mpsc::UnboundedSender, errors: mpsc::UnboundedSender, - voice_activation: bool, + settings: AudioSettings, ) { #[cfg(feature = "audio-device")] - let mut capture = match tsc_audio::device::Capture::open_default(500) { - Ok(c) => Some(c), - Err(e) => { - let _ = errors.send(format!("no microphone: {e}")); - None - } - }; - #[cfg(feature = "audio-device")] - let mut playback = match tsc_audio::device::Playback::open_default(200) { - Ok(p) => Some(p), - Err(e) => { - let _ = errors.send(format!("no speakers: {e}")); - None - } - }; + let mut devices = devices::Devices::new(&settings); #[cfg(not(feature = "audio-device"))] let _ = errors.send("built without audio device support".to_string()); - let mut encoder = match VoiceEncoder::new(VoiceCodec::Voice) { - Ok(e) => e, + let mut pipeline = match Pipeline::new(settings) { + Ok(p) => p, Err(e) => { let _ = errors.send(e.to_string()); return; } }; - let mut mixer = Mixer::new(); - let mut framer = Framer::new(FRAME_SAMPLES); - let mut vad = Vad { threshold: 1e-4, hang_frames: 15, remaining: 0 }; - let (mut ptt, mut input_muted, mut output_muted) = (false, false, false); - let mut was_sending = false; - - #[cfg(feature = "audio-device")] - let mut capture_resampler = capture.as_ref().map(|c| Linear::new(c.rate, SAMPLE_RATE)); - #[cfg(feature = "audio-device")] - let mut playback_resampler = playback.as_ref().map(|p| Linear::new(SAMPLE_RATE, p.rate)); - let mut captured = Vec::new(); - let mut resampled = Vec::new(); + let mut send = |packet| { + let _ = outgoing.send(packet); + }; + // Without speakers the mixer is drained at real time, so queues do not + // fill up and talkers still end. + let mut idle_clock = Instant::now(); loop { // Control messages and incoming voice. loop { match rx.try_recv() { - Ok(AudioIn::Packet(packet)) => { - let from = match packet.data().data() { - AudioData::S2C { from, .. } | AudioData::S2CWhisper { from, .. } => *from, - _ => continue, - }; - if let Err(error) = mixer.handle_packet(ClientId(from), packet) { - debug!(%error, "dropped voice packet"); + Ok(msg) => { + #[cfg(feature = "audio-device")] + if let AudioIn::Settings(s) = &msg { + devices.select(s); } + pipeline.handle(msg); } - Ok(AudioIn::Transmit(on)) => ptt = on, - Ok(AudioIn::InputMuted(m)) => input_muted = m, - Ok(AudioIn::OutputMuted(m)) => output_muted = m, Err(std_mpsc::TryRecvError::Empty) => break, Err(std_mpsc::TryRecvError::Disconnected) => return, } } - // Capture → 48 kHz mono → 20 ms frames → Opus. - captured.clear(); - resampled.clear(); #[cfg(feature = "audio-device")] - if let (Some(c), Some(r)) = (&mut capture, &mut capture_resampler) { - c.read_available(&mut captured); - let mono = pcm::to_mono(&captured, c.channels); - r.process(&mono, &mut resampled); - } - let mut frames = Vec::new(); - framer.push(&resampled, |f| frames.push(f.to_vec())); - for frame in frames { - let send = !input_muted && if voice_activation { vad.active(&frame) } else { ptt }; - if send { - match encoder.encode(&frame) { - Ok(packet) => { - let _ = outgoing.send(packet); - } - Err(e) => warn!(%e, "encoding failed"), - } - } else if was_sending { - let _ = outgoing.send(encoder.end_of_stream()); - } - was_sending = send; - } - - // Mixer → device rate/channels → playback. - #[cfg(feature = "audio-device")] - if let (Some(p), Some(r)) = (&mut playback, &mut playback_resampler) { - let needed_48k = (p.free() / p.channels) as u64 * SAMPLE_RATE as u64 / p.rate as u64; - if needed_48k as usize >= FRAME_SAMPLES { - let mut stereo = vec![0.0; FRAME_SAMPLES * 2]; - mixer.fill_buffer(&mut stereo); - if output_muted { - stereo.fill(0.0); - } - let mono = pcm::to_mono(&stereo, 2); - let mut out = Vec::with_capacity(mono.len()); - r.process(&mono, &mut out); - p.write(&pcm::from_mono(&out, p.channels)); - } - } + let playing = devices.step(&mut pipeline, &mut send, &errors); #[cfg(not(feature = "audio-device"))] - let _ = (output_muted, &mut mixer); + let playing = { + // No microphone: nothing to process, but keep the path alive. + pipeline.capture(&[], 0, &mut send); + false + }; - thread::sleep(Duration::from_millis(5)); + if playing { + idle_clock = Instant::now(); + } else { + let frame = Duration::from_millis(20); + while idle_clock + frame <= Instant::now() { + pipeline.playback_frame(); + idle_clock += frame; + } + } + + thread::sleep(TICK); + } +} + +#[cfg(feature = "audio-device")] +mod devices { + use tokio::sync::mpsc; + use tracing::debug; + use tsc_audio::AudioSettings; + use tsc_audio::device::{Capture, DeviceEvent, Managed, Playback}; + use tsc_audio::pcm::{self, FRAME_SAMPLES, SAMPLE_RATE}; + use tsc_audio::resample::Linear; + use tsproto_packets::packets::OutPacket; + + use super::{DEVICE_LATENCY_MS, PLAYBACK_CAPACITY_MS, Pipeline}; + + /// The microphone and speakers, reopened when they go away. + pub(super) struct Devices { + capture: Managed, + playback: Managed, + capture_resampler: Option<(u32, Linear)>, + playback_resampler: Option<(u32, Linear)>, + captured: Vec, + resampled: Vec, + } + + /// A resampler for this device rate, recreated when the rate changes + /// (another device was opened). + fn resampler(slot: &mut Option<(u32, Linear)>, from: u32, to: u32, rate: u32) -> &mut Linear { + if slot.as_ref().is_none_or(|(r, _)| *r != rate) { + *slot = Some((rate, Linear::new(from, to))); + } + &mut slot.as_mut().expect("just set").1 + } + + fn report(errors: &mpsc::UnboundedSender, what: &str, event: DeviceEvent) { + let message = match event { + DeviceEvent::Opened { name, fallback: false } => { + debug!(%name, "{what} opened"); + return; + } + DeviceEvent::Opened { name, fallback: true } => { + format!("selected {what} not found, using {name}") + } + DeviceEvent::Lost { name } => format!("{what} disconnected: {name}"), + DeviceEvent::Unavailable(e) => format!("no {what}: {e}"), + }; + let _ = errors.send(message); + } + + impl Devices { + pub fn new(settings: &AudioSettings) -> Self { + Self { + capture: Managed::new(settings.input_device.clone(), 500), + playback: Managed::new(settings.output_device.clone(), PLAYBACK_CAPACITY_MS), + capture_resampler: None, + playback_resampler: None, + captured: Vec::new(), + resampled: Vec::new(), + } + } + + pub fn select(&mut self, settings: &AudioSettings) { + self.capture.select(settings.input_device.clone()); + self.playback.select(settings.output_device.clone()); + } + + /// One round: top up the speakers, then process what the microphone + /// recorded. Returns whether speakers are open. + pub fn step( + &mut self, + pipeline: &mut Pipeline, + send: &mut impl FnMut(OutPacket), + errors: &mpsc::UnboundedSender, + ) -> bool { + if let Some(event) = self.playback.poll() { + report(errors, "speakers", event); + } + if let Some(event) = self.capture.poll() { + report(errors, "microphone", event); + } + + // Mixer → speakers, keeping the configured amount queued. + let mut delay_ms = DEVICE_LATENCY_MS; + let playing = if let Some(p) = self.playback.stream() { + let r = resampler(&mut self.playback_resampler, SAMPLE_RATE, p.rate, p.rate); + let frame_len = + (FRAME_SAMPLES * p.rate as usize).div_ceil(SAMPLE_RATE as usize) + 1; + while p.queued_ms() < pipeline.settings.playback_buffer_ms + && p.free() >= frame_len * p.channels + { + let mono = pipeline.playback_frame(); + let mut out = Vec::with_capacity(frame_len); + r.process(&mono, &mut out); + p.write(&pcm::from_mono(&out, p.channels)); + } + delay_ms += p.queued_ms(); + true + } else { + false + }; + + // Microphone → 48 kHz mono → pipeline. + if let Some(c) = self.capture.stream() { + self.captured.clear(); + self.resampled.clear(); + c.read_available(&mut self.captured); + let mono = pcm::to_mono(&self.captured, c.channels); + let r = resampler(&mut self.capture_resampler, c.rate, SAMPLE_RATE, c.rate); + r.process(&mono, &mut self.resampled); + pipeline.capture(&self.resampled, delay_ms, send); + } + playing + } } } #[cfg(test)] mod tests { + use tsc_audio::pcm::{SAMPLE_RATE, energy, sine, white_noise}; + use tsc_audio::{ProcessingSettings, VadSettings}; + use tsproto_packets::packets::{CodecType, Direction, OutAudio}; + use super::*; + fn pipeline(transmit: TransmitMode) -> Pipeline { + Pipeline::new(AudioSettings { + transmit, + processing: ProcessingSettings::off(), + vad: VadSettings { hangover_ms: 40, ..Default::default() }, + ..Default::default() + }) + .unwrap() + } + + /// Run `samples` through the capture side; returns (voice packets, + /// end-of-stream packets). + fn capture(p: &mut Pipeline, samples: &[f32]) -> (usize, usize) { + let (mut voice, mut end) = (0, 0); + p.capture(samples, 0, &mut |packet: OutPacket| { + // Header of 3 bytes (id + codec) for C2S audio. + if packet.content().len() > 3 { voice += 1 } else { end += 1 } + }); + (voice, end) + } + + fn incoming(from: u16, id: u16, data: &[u8]) -> AudioIn { + let packet = OutAudio::new(&AudioData::S2C { id, codec: CodecType::OpusVoice, from, data }); + AudioIn::Packet(InAudioBuf::try_new(Direction::S2C, packet.into_vec()).unwrap()) + } + #[test] - fn vad_hangs_after_speech() { - let mut vad = Vad { threshold: 1e-3, hang_frames: 2, remaining: 0 }; - let loud = vec![0.5; 960]; - let quiet = vec![0.0; 960]; - assert!(!vad.active(&quiet)); - assert!(vad.active(&loud)); - assert!(vad.active(&quiet)); - assert!(!vad.active(&quiet)); + fn push_to_talk_and_mute() { + let mut p = pipeline(TransmitMode::PushToTalk); + let tone = sine(440.0, 0.2, 0.3); + assert_eq!(capture(&mut p, &tone), (0, 0)); + p.handle(AudioIn::Transmit(true)); + assert_eq!(capture(&mut p, &tone), (10, 0)); + p.handle(AudioIn::InputMuted(true)); + assert_eq!(capture(&mut p, &tone), (0, 1)); + p.handle(AudioIn::InputMuted(false)); + p.handle(AudioIn::Transmit(false)); + assert_eq!(capture(&mut p, &tone), (0, 0)); + } + + #[test] + fn voice_activation_with_pre_roll() { + let mut p = pipeline(TransmitMode::VoiceActivation); + let quiet = vec![0.0; FRAME_SAMPLES * 5]; + assert_eq!(capture(&mut p, &quiet), (0, 0)); + // Speech opens the gate: the frame itself plus the pre-roll. + assert_eq!(capture(&mut p, &sine(440.0, 0.02, 0.3)), (1 + PRE_ROLL_FRAMES, 0)); + // 40 ms of hangover, then the stream ends. + assert_eq!(capture(&mut p, &quiet), (2, 1)); + + // Switching modes through settings. + let settings = AudioSettings { transmit: TransmitMode::Continuous, ..p.settings.clone() }; + p.handle(AudioIn::Settings(Box::new(settings))); + assert_eq!(capture(&mut p, &quiet), (5, 0)); + } + + /// Two talkers; one turned down, one muted, then forgotten. + #[test] + fn client_volume() { + let mut p = pipeline(TransmitMode::PushToTalk); + let mut encoder = VoiceEncoder::new(VoiceCodec::Voice).unwrap(); + let tone = sine(700.0, 1.0, 0.4); + let mut play = |p: &mut Pipeline, from: u16| -> f32 { + let mut out = Vec::new(); + for (i, frame) in tone.chunks_exact(FRAME_SAMPLES).enumerate() { + p.handle(incoming(from, i as u16, encoder.encode_to_bytes(frame).unwrap())); + out.extend(p.playback_frame()); + } + energy(&out[out.len() / 2..]) + }; + let full = play(&mut p, 1); + p.handle(AudioIn::ClientVolume { client: ClientId(2), volume: 0.5 }); + let half = play(&mut p, 2); + let ratio_db = 10.0 * (half / full).log10(); + assert!((ratio_db + 6.0).abs() < 1.0, "volume 0.5 gave {ratio_db} dB"); + p.handle(AudioIn::ClientMuted { client: ClientId(3), muted: true }); + assert!(play(&mut p, 3) < 1e-8); + p.handle(AudioIn::ClientLeft(ClientId(3))); + assert!(!p.mixer.is_muted(ClientId(3))); + } + + /// End to end: a remote talker is played, the speakers leak into the + /// microphone 30 ms later, and the echo canceller (fed with what was + /// played) removes it from what we would send. + #[test] + fn echo_of_playback_is_cancelled() { + let mut p = Pipeline::new(AudioSettings { + transmit: TransmitMode::Continuous, + processing: ProcessingSettings { echo_cancellation: true, ..ProcessingSettings::off() }, + ..Default::default() + }) + .unwrap(); + let mut encoder = VoiceEncoder::new(VoiceCodec::Voice).unwrap(); + let far = white_noise(SAMPLE_RATE as usize * 6, 0.3, 11); + let delay = SAMPLE_RATE as usize * 30 / 1000; + let mut played = vec![0.0; delay]; + let mut echo = Vec::new(); + for (i, frame) in far.chunks_exact(FRAME_SAMPLES).enumerate() { + p.handle(incoming(9, i as u16, encoder.encode_to_bytes(frame).unwrap())); + played.extend(p.playback_frame()); + let mic: Vec = played[played.len() - delay - FRAME_SAMPLES..played.len() - delay] + .iter() + .map(|s| s * 0.5) + .collect(); + p.capture(&mic, 30, &mut |_| {}); + echo.extend(mic); + } + let tail = SAMPLE_RATE as usize * 2; + let before = energy(&echo[echo.len() - tail..]); + let after = energy(&p.tap[p.tap.len() - tail..]); + let attenuation = 10.0 * (before / after).log10(); + assert!(before > 1e-3, "the echo must be audible"); + assert!(attenuation >= 10.0, "echo attenuated by {attenuation:.1} dB"); + } + + #[test] + fn settings_are_sanitized() { + let mut p = pipeline(TransmitMode::PushToTalk); + let settings = AudioSettings { output_volume: f32::INFINITY, ..Default::default() }; + p.handle(AudioIn::Settings(Box::new(settings))); + assert_eq!(p.settings.output_volume, 1.0); } } diff --git a/crates/tsc-core/src/lib.rs b/crates/tsc-core/src/lib.rs index c9a155f..4226b28 100644 --- a/crates/tsc-core/src/lib.rs +++ b/crates/tsc-core/src/lib.rs @@ -10,12 +10,17 @@ //! Presence comes from the most authoritative connected source //! (voice > gateway > query). Channel chat goes through the voice connection //! when the user is in that channel, otherwise through a relay. +//! +//! On TeamSpeak 6 servers the voice connection also carries streams (screen +//! sharing): see the `*Stream*` commands and events, and +//! [`Engine::subscribe_frames`] for the frames of watched streams. mod audio; mod gateway; mod query; mod route; mod session; +pub mod stream; mod voice; use std::collections::HashMap; @@ -25,6 +30,8 @@ use tokio::sync::{broadcast, mpsc}; use tsc_model::{Capabilities, ChannelId, ChatMessage, ChatTarget, Presence, ServerFlavor}; pub use route::{ChatRoute, Dedup, route_chat}; +pub use stream::{StreamFrame, StreamSink, StreamState, WatchState}; +use tsc_stream::{EncodedFrame, StreamInfo, StreamSetup, ViewerInfo}; pub use voice::VoiceOptions; pub type SessionId = u64; @@ -84,6 +91,49 @@ pub enum Command { session: SessionId, on: bool, }, + /// Start streaming in our channel (TeamSpeak 6 only). Progress comes as + /// [`Event::StreamState`]; frames go in through the sink of + /// [`StreamState::Live`] or [`Command::SendStreamFrame`]. + StartStream { + session: SessionId, + setup: StreamSetup, + /// Accept every viewer instead of asking with [`Event::StreamViewerRequest`]. + auto_accept: bool, + }, + StopStream { + session: SessionId, + }, + /// Answer an [`Event::StreamViewerRequest`]. + AcceptViewer { + session: SessionId, + viewer: u16, + accept: bool, + }, + /// Remove a viewer from our stream. + KickViewer { + session: SessionId, + viewer: u16, + }, + /// An encoded frame for our stream. + SendStreamFrame { + session: SessionId, + frame: EncodedFrame, + }, + /// Watch a stream from [`Event::StreamsChanged`]. Frames arrive through + /// [`Engine::subscribe_frames`]. + WatchStream { + session: SessionId, + stream_id: String, + }, + LeaveStream { + session: SessionId, + stream_id: String, + }, + /// Ask the streamer of a watched stream for a keyframe. + RequestStreamKeyframe { + session: SessionId, + stream_id: String, + }, /// Close everything of a session. CloseSession { session: SessionId, @@ -159,6 +209,37 @@ pub enum Event { session: SessionId, message: String, }, + /// The streams in our channel (TeamSpeak 6), full list. + StreamsChanged { + session: SessionId, + streams: Vec, + }, + /// Our own stream. + StreamState { + session: SessionId, + state: StreamState, + }, + /// Someone asks to watch our stream; answer with [`Command::AcceptViewer`]. + StreamViewerRequest { + session: SessionId, + viewer: u16, + message: String, + }, + /// The viewers of our stream and their state, full list. + StreamViewers { + session: SessionId, + viewers: Vec, + }, + /// A viewer needs a keyframe (also flagged on the [`StreamSink`]). + StreamKeyframeRequest { + session: SessionId, + }, + /// A stream we watch. + WatchState { + session: SessionId, + stream_id: String, + state: WatchState, + }, } /// Handle to the engine. Cheap to clone; all methods are non-blocking. @@ -166,6 +247,7 @@ pub enum Event { pub struct Engine { commands: mpsc::UnboundedSender, events: broadcast::Sender, + frames: broadcast::Sender, } impl Engine { @@ -173,8 +255,10 @@ impl Engine { pub fn start() -> Self { let (commands, rx) = mpsc::unbounded_channel(); let (events, _) = broadcast::channel(4096); - tokio::spawn(run(rx, events.clone())); - Self { commands, events } + // About a minute of one watched stream. + let (frames, _) = broadcast::channel(4096); + tokio::spawn(run(rx, events.clone(), frames.clone())); + Self { commands, events, frames } } pub fn send(&self, command: Command) { @@ -184,9 +268,18 @@ impl Engine { pub fn subscribe(&self) -> broadcast::Receiver { self.events.subscribe() } + + /// Encoded frames of the streams we watch (kept off the event bus). + pub fn subscribe_frames(&self) -> broadcast::Receiver { + self.frames.subscribe() + } } -async fn run(mut commands: mpsc::UnboundedReceiver, events: broadcast::Sender) { +async fn run( + mut commands: mpsc::UnboundedReceiver, + events: broadcast::Sender, + frames: broadcast::Sender, +) { let mut sessions: HashMap = HashMap::new(); while let Some(command) = commands.recv().await { let id = command_session(&command); @@ -198,7 +291,7 @@ async fn run(mut commands: mpsc::UnboundedReceiver, events: broadcast:: } sessions .entry(id) - .or_insert_with(|| session::SessionHandle::spawn(id, events.clone())) + .or_insert_with(|| session::SessionHandle::spawn(id, events.clone(), frames.clone())) .send(command); } } @@ -217,6 +310,14 @@ fn command_session(command: &Command) -> SessionId { | Command::SetInputMuted { session, .. } | Command::SetOutputMuted { session, .. } | Command::SetTransmitting { session, .. } + | Command::StartStream { session, .. } + | Command::StopStream { session } + | Command::AcceptViewer { session, .. } + | Command::KickViewer { session, .. } + | Command::SendStreamFrame { session, .. } + | Command::WatchStream { session, .. } + | Command::LeaveStream { session, .. } + | Command::RequestStreamKeyframe { session, .. } | Command::CloseSession { session } => *session, } } diff --git a/crates/tsc-core/src/session.rs b/crates/tsc-core/src/session.rs index bcb638c..93b748a 100644 --- a/crates/tsc-core/src/session.rs +++ b/crates/tsc-core/src/session.rs @@ -1,6 +1,6 @@ //! One server session: merges its sources and routes commands. -use std::collections::HashSet; +use std::collections::{BTreeMap, HashSet}; use std::sync::Arc; use tokio::sync::{broadcast, mpsc}; @@ -11,6 +11,7 @@ use crate::audio::{self, AudioHandle, AudioIn}; use crate::gateway::{self, GatewayCmd, GatewayEvent}; use crate::query::{self, QueryCmd, QueryEvent}; use crate::route::{ChatRoute, Dedup, route_chat}; +use crate::stream::{PeerConfig, StreamFrame, StreamHandle, StreamInput}; use crate::voice::{self, VoiceCmd, VoiceEvent}; use crate::{Command, Event, ObserveState, SessionId, SessionState, Source, VoiceState}; @@ -19,9 +20,13 @@ pub(crate) struct SessionHandle { } impl SessionHandle { - pub fn spawn(id: SessionId, events: broadcast::Sender) -> Self { + pub fn spawn( + id: SessionId, + events: broadcast::Sender, + frames: broadcast::Sender, + ) -> Self { let (tx, rx) = mpsc::unbounded_channel(); - tokio::spawn(Session::new(id, events).run(rx)); + tokio::spawn(Session::new(id, events, frames).run(rx)); Self { tx } } @@ -53,6 +58,12 @@ struct Session { query: Option<(u64, mpsc::UnboundedSender)>, query_presence: Option, audio: Option, + /// Streams of the voice connection (TeamSpeak 6 only). + streams: Option, + stream_peer: PeerConfig, + frames: broadcast::Sender, + /// `client_is_streaming` of the voice presence, as last told to the streams. + streaming_clients: BTreeMap>, open_chats: HashSet, dedup: Dedup, sources_tx: mpsc::UnboundedSender, @@ -60,7 +71,11 @@ struct Session { } impl Session { - fn new(id: SessionId, events: broadcast::Sender) -> Self { + fn new( + id: SessionId, + events: broadcast::Sender, + frames: broadcast::Sender, + ) -> Self { let (sources_tx, sources_rx) = mpsc::unbounded_channel(); Self { id, @@ -75,6 +90,10 @@ impl Session { query: None, query_presence: None, audio: None, + streams: None, + stream_peer: PeerConfig::default(), + frames, + streaming_clients: BTreeMap::new(), open_chats: HashSet::new(), dedup: Dedup::default(), sources_tx, @@ -135,8 +154,10 @@ impl Session { if let Some((_, tx)) = self.voice.take() { let _ = tx.send(VoiceCmd::Disconnect); } + self.stop_streams("voice reconnecting"); let generation = self.next_generation(); self.nickname = options.nickname.clone(); + self.stream_peer = options.stream_peer.clone(); let (cmd_tx, cmd_rx) = mpsc::unbounded_channel(); let (ev_tx, ev_rx) = mpsc::unbounded_channel(); if options.audio { @@ -243,10 +264,50 @@ impl Session { } self.emit_state(); } + Command::StartStream { setup, auto_accept, .. } => { + self.stream_input(StreamInput::Start { setup, auto_accept }); + } + Command::StopStream { .. } => self.stream_input(StreamInput::Stop), + Command::AcceptViewer { viewer, accept, .. } => { + self.stream_input(StreamInput::Respond { viewer, accept }); + } + Command::KickViewer { viewer, .. } => self.stream_input(StreamInput::Kick { viewer }), + Command::SendStreamFrame { frame, .. } => { + // Frames without a stream are dropped silently. + if let Some(s) = &self.streams { + s.send(StreamInput::Frame(frame)); + } + } + Command::WatchStream { stream_id, .. } => { + self.stream_input(StreamInput::Watch { stream_id }); + } + Command::LeaveStream { stream_id, .. } => { + self.stream_input(StreamInput::Leave { stream_id }); + } + Command::RequestStreamKeyframe { stream_id, .. } => { + self.stream_input(StreamInput::RequestKeyframe { stream_id }); + } Command::CloseSession { .. } => {} } } + fn stream_input(&self, input: StreamInput) { + match &self.streams { + Some(s) => s.send(input), + None if self.state.voice == VoiceState::Connected => { + self.error("streams need a TeamSpeak 6 server"); + } + None => self.error("not connected with voice"), + } + } + + fn stop_streams(&mut self, reason: &str) { + if let Some(s) = self.streams.take() { + s.send(StreamInput::Shutdown(reason.into())); + } + self.streaming_clients.clear(); + } + fn voice_cmd(&self, cmd: VoiceCmd) { match &self.voice { Some((_, tx)) => { @@ -299,6 +360,7 @@ impl Session { } fn stop_all(&mut self) { + self.stop_streams("session closed"); if let Some((_, tx)) = self.voice.take() { let _ = tx.send(VoiceCmd::Disconnect); } @@ -334,17 +396,47 @@ impl Session { fn voice_event(&mut self, e: VoiceEvent) { match e { - VoiceEvent::Connected { name, flavor } => { + VoiceEvent::Connected { name, flavor, own_client } => { self.state.voice = VoiceState::Connected; self.emit_state(); let capabilities = flavor.capabilities(); + if capabilities.streams + && let Some((_, voice)) = &self.voice + { + self.streams = Some(StreamHandle::spawn( + self.id, + own_client, + self.stream_peer.clone(), + voice.clone(), + self.events.clone(), + self.frames.clone(), + )); + } self.emit(Event::ServerInfo { session: self.id, name, flavor, capabilities }); self.reopen_relayed_chats(); } VoiceEvent::Presence(p) => { + if let Some(s) = &self.streams { + let clients: BTreeMap<_, _> = + p.clients.values().map(|c| (c.id, c.streaming)).collect(); + if clients != self.streaming_clients { + self.streaming_clients = clients.clone(); + s.send(StreamInput::Clients(clients)); + } + } self.voice_presence = Some(p); self.publish_presence(); } + VoiceEvent::Stream(n) => { + if let Some(s) = &self.streams { + s.send(StreamInput::Notification(n)); + } + } + VoiceEvent::StreamRequestFailed(request, error) => { + if let Some(s) = &self.streams { + s.send(StreamInput::RequestFailed(request, error)); + } + } VoiceEvent::OwnChannel(cid) => { if self.state.own_channel != Some(cid) { self.state.own_channel = Some(cid); @@ -361,6 +453,7 @@ impl Session { self.emit(Event::Talking { session: self.id, client, talking }); } VoiceEvent::Disconnected(reason) => { + self.stop_streams("voice disconnected"); self.voice = None; self.voice_presence = None; self.audio = None; diff --git a/crates/tsc-core/src/stream.rs b/crates/tsc-core/src/stream.rs new file mode 100644 index 0000000..80ed3a2 --- /dev/null +++ b/crates/tsc-core/src/stream.rs @@ -0,0 +1,530 @@ +//! TeamSpeak 6 streams of a session: a task that runs the stream sessions +//! ([`tsc_stream::Streams`]) of the voice connection. +//! +//! The voice task forwards stream notifications here and sends the resulting +//! commands. Only started for TeamSpeak 6 servers. + +use std::collections::BTreeMap; +use std::fmt; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; + +use tokio::sync::{broadcast, mpsc}; +use tracing::debug; +pub use tsc_stream::{ + Codec, EncodedFrame, EndReason, FrameSource, Frequency, LeaveReason, MediaFrame, MediaKind, + MediaTime, PeerConfig, StreamInfo, StreamKind, StreamSetup, SyntheticSource, VideoCodec, + ViewerInfo, ViewerState, +}; +use tsc_stream::{ + Output, Request, StreamEvent, StreamNotification, StreamerEvent, StreamerOptions, Streams, + WatchEvent, +}; +use tsclientlib::ClientId; + +use crate::voice::VoiceCmd; +use crate::{Event, SessionId}; + +/// Our own stream. +#[derive(Clone, Debug, PartialEq)] +pub enum StreamState { + /// `setupstream` sent. + Starting, + /// Live: frames given to `sink` (or [`crate::Command::SendStreamFrame`]) + /// reach every connected viewer. + Live { + id: String, + sink: StreamSink, + }, + Ended(EndReason), +} + +/// A stream we watch. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum WatchState { + /// Join request sent; waiting for the streamer. + Requested, + /// Accepted; connecting to the streamer. + Connecting, + /// Frames arrive through [`crate::Engine::subscribe_frames`]. + Connected, + Ended(EndReason), +} + +/// A received frame of a watched stream. +#[derive(Clone, Debug)] +pub struct StreamFrame { + pub session: SessionId, + pub stream_id: String, + pub frame: MediaFrame, +} + +/// Hands encoded frames of our stream to the engine, e.g. from an encoder thread. +#[derive(Clone)] +pub struct StreamSink { + tx: mpsc::UnboundedSender, + live: Arc, + keyframe: Arc, +} + +impl StreamSink { + /// Send one frame; `false` once the stream has ended. + pub fn send(&self, frame: EncodedFrame) -> bool { + self.live.load(Ordering::Relaxed) && self.tx.send(StreamInput::Frame(frame)).is_ok() + } + + /// Whether a viewer asked for a keyframe since the last call. + pub fn take_keyframe_request(&self) -> bool { + self.keyframe.swap(false, Ordering::Relaxed) + } + + pub fn is_live(&self) -> bool { + self.live.load(Ordering::Relaxed) + } +} + +impl fmt::Debug for StreamSink { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("StreamSink").field("live", &self.is_live()).finish() + } +} + +impl PartialEq for StreamSink { + fn eq(&self, other: &Self) -> bool { + Arc::ptr_eq(&self.live, &other.live) + } +} + +pub(crate) enum StreamInput { + Start { + setup: StreamSetup, + auto_accept: bool, + }, + Stop, + Respond { + viewer: u16, + accept: bool, + }, + Kick { + viewer: u16, + }, + Watch { + stream_id: String, + }, + Leave { + stream_id: String, + }, + RequestKeyframe { + stream_id: String, + }, + Frame(EncodedFrame), + Notification(StreamNotification), + RequestFailed(Request, String), + /// Clients on the server with their `client_is_streaming`. + Clients(BTreeMap>), + /// The voice connection is gone. + Shutdown(String), +} + +pub(crate) struct StreamHandle { + tx: mpsc::UnboundedSender, +} + +impl StreamHandle { + pub fn spawn( + session: SessionId, + own_client: u16, + config: PeerConfig, + voice: mpsc::UnboundedSender, + events: broadcast::Sender, + frames: broadcast::Sender, + ) -> Self { + let (tx, rx) = mpsc::unbounded_channel(); + let task = StreamTask { + session, + streams: Streams::new(ClientId(own_client), config), + voice, + events, + frames, + tx: tx.clone(), + sink: None, + clients: BTreeMap::new(), + }; + tokio::spawn(task.run(rx)); + Self { tx } + } + + pub fn send(&self, input: StreamInput) { + let _ = self.tx.send(input); + } +} + +struct StreamTask { + session: SessionId, + streams: Streams, + voice: mpsc::UnboundedSender, + events: broadcast::Sender, + frames: broadcast::Sender, + /// For the sinks handed out. + tx: mpsc::UnboundedSender, + /// The sink of our live stream. + sink: Option, + /// Clients on the server and their `client_is_streaming`. + clients: BTreeMap>, +} + +impl StreamTask { + async fn run(mut self, mut rx: mpsc::UnboundedReceiver) { + loop { + tokio::select! { + input = rx.recv() => match input { + None => break, + Some(StreamInput::Shutdown(reason)) => { + self.shutdown(reason); + break; + } + Some(input) => self.input(input).await, + }, + () = self.streams.wait_peers() => {} + } + self.flush(); + } + debug!(session = self.session, "stream task ended"); + } + + fn emit(&self, event: Event) { + let _ = self.events.send(event); + } + + async fn input(&mut self, input: StreamInput) { + let session = self.session; + let result = match input { + StreamInput::Start { setup, auto_accept } => { + self.streams.start(StreamerOptions { setup, auto_accept }).map(|()| { + self.emit(Event::StreamState { session, state: StreamState::Starting }); + }) + } + StreamInput::Stop => self.streams.stop(), + StreamInput::Respond { viewer, accept } => { + self.streams.respond(ClientId(viewer), accept).await + } + StreamInput::Kick { viewer } => self.streams.kick(ClientId(viewer)), + StreamInput::Watch { stream_id } => self.streams.watch(&stream_id, "").map(|()| { + self.emit(Event::WatchState { session, stream_id, state: WatchState::Requested }); + }), + StreamInput::Leave { stream_id } => self.streams.leave(&stream_id), + StreamInput::RequestKeyframe { stream_id } => { + self.streams.request_keyframe(&stream_id); + Ok(()) + } + StreamInput::Frame(frame) => { + self.streams.write_frame(&frame); + Ok(()) + } + StreamInput::Notification(n) => { + self.streams.handle_notification(n).await; + Ok(()) + } + StreamInput::RequestFailed(request, error) => { + self.streams.request_failed(&request, &error); + Ok(()) + } + StreamInput::Clients(clients) => { + // Streams of clients that left or stopped streaming are gone. + // Only changes count: a snapshot may predate the streaming flag + // of a stream that was just announced. + for (client, streaming) in &clients { + let was = self.clients.get(client).copied().flatten(); + if let (Some(was), Some(now)) = (was, *streaming) + && was != now + { + self.streams.set_client_streaming(ClientId(*client), now); + } + } + self.streams.retain_streamers(|c| clients.contains_key(&c.0)); + self.clients = clients; + Ok(()) + } + StreamInput::Shutdown(_) => Ok(()), + }; + if let Err(e) = result { + self.emit(Event::Error { session, message: format!("stream: {e}") }); + } + } + + /// Send the requests on the connection and report the events. + fn flush(&mut self) { + while let Some(output) = self.streams.poll_output() { + match output { + Output::Request(request) => { + let _ = self.voice.send(VoiceCmd::Stream(request)); + } + Output::Event(event) => self.event(event), + } + } + } + + fn event(&mut self, event: StreamEvent) { + let session = self.session; + match event { + StreamEvent::Streams(streams) => self.emit(Event::StreamsChanged { session, streams }), + StreamEvent::Streamer(StreamerEvent::Live { id }) => { + let sink = StreamSink { + tx: self.tx.clone(), + live: Arc::new(AtomicBool::new(true)), + keyframe: Arc::new(AtomicBool::new(true)), + }; + self.sink = Some(sink.clone()); + self.emit(Event::StreamState { session, state: StreamState::Live { id, sink } }); + } + StreamEvent::Streamer(StreamerEvent::Request { viewer, message }) => { + self.emit(Event::StreamViewerRequest { session, viewer: viewer.0, message }); + } + StreamEvent::Streamer(StreamerEvent::Viewers(viewers)) => { + self.emit(Event::StreamViewers { session, viewers }); + } + StreamEvent::Streamer(StreamerEvent::KeyframeRequest) => { + if let Some(sink) = &self.sink { + sink.keyframe.store(true, Ordering::Relaxed); + } + self.emit(Event::StreamKeyframeRequest { session }); + } + StreamEvent::Streamer(StreamerEvent::Ended(reason)) => { + if let Some(sink) = self.sink.take() { + sink.live.store(false, Ordering::Relaxed); + } + self.emit(Event::StreamState { session, state: StreamState::Ended(reason) }); + } + StreamEvent::Watch { id, event } => { + let state = match event { + WatchEvent::Accepted => WatchState::Connecting, + WatchEvent::Connected => WatchState::Connected, + WatchEvent::Ended(reason) => WatchState::Ended(reason), + WatchEvent::Frame(frame) => { + let _ = self.frames.send(StreamFrame { session, stream_id: id, frame }); + return; + } + }; + self.emit(Event::WatchState { session, stream_id: id, state }); + } + } + } + + /// The connection is gone: report our stream and watched streams as ended. + fn shutdown(&mut self, reason: String) { + let session = self.session; + let ended = || EndReason::Failed(reason.clone()); + if self.streams.streamer().is_some() { + self.emit(Event::StreamState { session, state: StreamState::Ended(ended()) }); + } + if let Some(sink) = self.sink.take() { + sink.live.store(false, Ordering::Relaxed); + } + for watched in self.streams.watching() { + let stream_id = watched.id().to_owned(); + self.emit(Event::WatchState { session, stream_id, state: WatchState::Ended(ended()) }); + } + if self.streams.directory().iter().next().is_some() { + self.emit(Event::StreamsChanged { session, streams: Vec::new() }); + } + } +} + +#[cfg(test)] +mod tests { + use std::time::{Duration, Instant}; + + use tokio::time::timeout; + use tsc_stream::{FrameSource, SyntheticSource}; + + use super::*; + + const CLIENTS: [u16; 2] = [5, 6]; + + /// The notifications the server sends for `request` from `from`, per receiver. + fn relay(from: u16, request: Request) -> Vec<(u16, StreamNotification)> { + let both = |n: StreamNotification| CLIENTS.map(|c| (c, n.clone())).to_vec(); + match request { + Request::Setup(setup) => CLIENTS + .map(|c| { + let info = StreamInfo { + id: "s-1".into(), + streamer: ClientId(from), + name: setup.name.clone(), + kind: setup.kind, + bitrate: setup.bitrate, + viewer_limit: setup.viewer_limit, + audio: setup.audio, + }; + let return_code = (c == from).then(|| "1".to_owned()); + (c, StreamNotification::Started { info, return_code }) + }) + .to_vec(), + Request::Stop { id } => { + both(StreamNotification::Stopped { id, streamer: None, reason: None }) + } + Request::Join { id, streamer, message } => vec![( + streamer.0, + StreamNotification::JoinRequest { + id, + viewer: ClientId(from), + message, + remove: false, + }, + )], + Request::Leave { id, streamer } => vec![( + streamer.0, + StreamNotification::JoinRequest { + id, + viewer: ClientId(from), + message: String::new(), + remove: true, + }, + )], + Request::Respond { id, viewer, offer, accept } => vec![( + viewer.0, + StreamNotification::JoinResponse { + id, + streamer: Some(ClientId(from)), + accepted: accept, + offer, + message: String::new(), + }, + )], + Request::Signal { id, peer, signal } => vec![( + peer.0, + StreamNotification::Signaling { id, peer: ClientId(from), json: signal.to_json() }, + )], + Request::RemoveViewer { id, viewer, reason } => { + both(StreamNotification::ViewerLeft { id, viewer, reason: Some(reason) }) + } + } + } + + async fn wait( + rx: &mut broadcast::Receiver, + mut f: impl FnMut(Event) -> Option, + ) -> T { + timeout(Duration::from_secs(10), async { + loop { + if let Some(t) = f(rx.recv().await.unwrap()) { + return t; + } + } + }) + .await + .expect("timed out") + } + + /// Two stream tasks (sessions 1 and 2) whose commands go through a fake server. + #[tokio::test(flavor = "multi_thread")] + async fn stream_tasks_through_fake_server() { + let (events, mut rx) = broadcast::channel(4096); + let (frames, mut frames_rx) = broadcast::channel(4096); + let mut voices = Vec::new(); + let mut handles = Vec::new(); + for (i, clid) in CLIENTS.into_iter().enumerate() { + let (voice, voice_rx) = mpsc::unbounded_channel(); + let config = PeerConfig::loopback(); + let session = i as u64 + 1; + handles.push(StreamHandle::spawn( + session, + clid, + config, + voice, + events.clone(), + frames.clone(), + )); + voices.push(voice_rx); + } + let handles = Arc::new(handles); + // The server: relays requests from one task as notifications to the others. + for (i, mut voice_rx) in voices.into_iter().enumerate() { + let handles = handles.clone(); + tokio::spawn(async move { + while let Some(cmd) = voice_rx.recv().await { + if let VoiceCmd::Stream(request) = cmd { + for (to, n) in relay(CLIENTS[i], request) { + let index = CLIENTS.iter().position(|c| *c == to).unwrap(); + handles[index].send(StreamInput::Notification(n)); + } + } + } + }); + } + + let setup = StreamSetup { name: "t".into(), ..Default::default() }; + handles[0].send(StreamInput::Start { setup, auto_accept: true }); + // Live for the streamer and listed for the viewer, in either order. + let (mut sink, mut listed) = (None, false); + wait(&mut rx, |e| { + match e { + Event::StreamState { session: 1, state: StreamState::Live { sink: s, .. } } => { + sink = Some(s); + } + Event::StreamsChanged { session: 2, streams } => listed = streams.len() == 1, + _ => {} + } + (sink.is_some() && listed).then_some(()) + }) + .await; + let sink = sink.unwrap(); + handles[1].send(StreamInput::Watch { stream_id: "s-1".into() }); + wait(&mut rx, |e| match e { + Event::WatchState { session: 2, state: WatchState::Connected, .. } => Some(()), + _ => None, + }) + .await; + + // Frames from the sink reach the viewer's frame bus. + let feeder = tokio::spawn({ + let sink = sink.clone(); + async move { + let mut source = SyntheticSource::new(30, 2000, true); + let mut out = Vec::new(); + while sink.is_live() { + source.poll_frames(Instant::now(), &mut out); + for f in out.drain(..) { + sink.send(f); + } + tokio::time::sleep(Duration::from_millis(10)).await; + } + } + }); + let (mut video, mut audio) = (0, 0); + timeout(Duration::from_secs(10), async { + while video < 10 || audio < 10 { + let f = frames_rx.recv().await.unwrap(); + assert_eq!((f.session, f.stream_id.as_str()), (2, "s-1")); + match f.frame.kind { + MediaKind::Video => video += 1, + MediaKind::Audio => audio += 1, + } + } + }) + .await + .expect("no frames"); + assert!(sink.take_keyframe_request()); + + // Stopping ends the sink and tells the viewer. + handles[0].send(StreamInput::Stop); + wait(&mut rx, |e| match e { + Event::WatchState { + session: 2, state: WatchState::Ended(EndReason::Stopped), .. + } => Some(()), + _ => None, + }) + .await; + assert!(!sink.is_live()); + feeder.await.unwrap(); + + // Errors surface as events. + handles[1].send(StreamInput::Leave { stream_id: "s-1".into() }); + wait(&mut rx, |e| match e { + Event::Error { session: 2, message } if message.contains("not watching") => Some(()), + _ => None, + }) + .await; + handles[1].send(StreamInput::Shutdown("bye".into())); + } +} diff --git a/crates/tsc-core/src/voice.rs b/crates/tsc-core/src/voice.rs index 7b848c2..c1c1723 100644 --- a/crates/tsc-core/src/voice.rs +++ b/crates/tsc-core/src/voice.rs @@ -1,5 +1,6 @@ //! The voice source: a normal client connection. +use std::collections::HashMap; use std::time::Duration; use futures::prelude::*; @@ -9,12 +10,13 @@ use tracing::{info, warn}; use tsc_model::{ ChannelId, ChannelInfo, ChatMessage, ChatTarget, ClientInfo, Presence, ServerFlavor, }; +use tsc_stream::{PeerConfig, Request, StreamNotification}; use tsclientlib::data; use tsclientlib::events::Event as BookEvent; use tsclientlib::prelude::*; use tsclientlib::{ - ClientType, Connection, DisconnectOptions, Identity, MaxClients, MessageTarget, StreamItem, - Version, + ClientType, Connection, DisconnectOptions, Identity, MaxClients, MessageHandle, MessageTarget, + StreamItem, Version, }; use tsproto_packets::packets::{AudioData, InAudioBuf, OutPacket}; @@ -30,6 +32,8 @@ pub struct VoiceOptions { pub channel: Option, /// Open the audio devices (capture and playback). pub audio: bool, + /// Network settings for stream peer connections (TeamSpeak 6). + pub stream_peer: PeerConfig, } impl VoiceOptions { @@ -42,6 +46,7 @@ impl VoiceOptions { server_password: None, channel: None, audio: false, + stream_peer: PeerConfig::default(), } } } @@ -53,6 +58,8 @@ pub(crate) enum VoiceCmd { SetOutputMuted(bool), /// An encoded voice packet from the audio thread. Audio(OutPacket), + /// A stream command; failures come back as [`VoiceEvent::StreamRequestFailed`]. + Stream(Request), Disconnect, } @@ -60,6 +67,7 @@ pub(crate) enum VoiceEvent { Connected { name: String, flavor: ServerFlavor, + own_client: u16, }, Presence(Presence), OwnChannel(ChannelId), @@ -70,6 +78,8 @@ pub(crate) enum VoiceEvent { client: u16, talking: bool, }, + Stream(StreamNotification), + StreamRequestFailed(Request, String), Disconnected(Option), } @@ -192,7 +202,11 @@ async fn run_inner( let state = con.get_state()?; let flavor = ServerFlavor::from_version_string(&state.server.version); info!(server = %state.server.name, ?flavor, "voice connected"); - let _ = events.send(VoiceEvent::Connected { name: state.server.name.clone(), flavor }); + let _ = events.send(VoiceEvent::Connected { + name: state.server.name.clone(), + flavor, + own_client: state.own_client.0, + }); } // Subscribe to all channels to see everyone. let cmd = con.get_state()?.server.set_subscribed(true); @@ -202,6 +216,8 @@ async fn run_inner( // Who is talking: last voice packet per client. let mut talking: std::collections::HashMap = Default::default(); let mut tick = tokio::time::interval(Duration::from_millis(250)); + // Stream commands waiting for the server's answer. + let mut stream_requests: HashMap = HashMap::new(); loop { let input = { @@ -258,12 +274,27 @@ async fn run_inner( } let _ = events.send(VoiceEvent::Audio(packet)); } + StreamItem::MessageEvent(msg) => { + for n in StreamNotification::from_message(&msg) { + let _ = events.send(VoiceEvent::Stream(n)); + } + } + StreamItem::MessageResult(handle, result) => { + if let (Some(request), Err(e)) = (stream_requests.remove(&handle), result) { + let _ = + events.send(VoiceEvent::StreamRequestFailed(request, e.to_string())); + } + } StreamItem::DisconnectedTemporarily(reason) => { warn!(?reason, "voice connection interrupted, reconnecting"); } _ => {} }, Input::Cmd(None) | Input::Cmd(Some(VoiceCmd::Disconnect)) => break, + Input::Cmd(Some(VoiceCmd::Stream(request))) => { + let handle = request.to_command().send_with_result(&mut con)?; + stream_requests.insert(handle, request); + } Input::Cmd(Some(cmd)) => handle_command(&mut con, cmd)?, Input::Tick => { talking.retain(|client, last| { @@ -336,6 +367,9 @@ fn handle_command(con: &mut Connection, cmd: VoiceCmd) -> anyhow::Result<()> { VoiceCmd::Audio(packet) => { con.send_audio(packet)?; } + VoiceCmd::Stream(request) => { + request.to_command().send(con)?; + } VoiceCmd::Disconnect => {} } Ok(()) diff --git a/crates/tsc-core/tests/stream_live.rs b/crates/tsc-core/tests/stream_live.rs new file mode 100644 index 0000000..25e1824 --- /dev/null +++ b/crates/tsc-core/tests/stream_live.rs @@ -0,0 +1,257 @@ +//! Streams through the engine against the development servers +//! (dev/docker-compose.yml): one session streams synthetic frames, another +//! watches. Runs only with `TSC_LIVE=1`. + +use std::time::{Duration, Instant}; + +use tokio::sync::broadcast::Receiver; +use tokio::time::timeout; +use tsc_core::stream::{ + EndReason, FrameSource, LeaveReason, MediaKind, PeerConfig, StreamSetup, SyntheticSource, + ViewerState, +}; +use tsc_core::{Command, Engine, Event, StreamState, VoiceOptions, VoiceState, WatchState}; + +fn live() -> bool { + std::env::var("TSC_LIVE").is_ok_and(|v| v == "1") +} + +/// Wait for an event matching `f`, failing after 20 s. +async fn wait_for( + rx: &mut Receiver, + what: &str, + mut f: impl FnMut(&Event) -> Option, +) -> T { + timeout(Duration::from_secs(20), async { + loop { + match rx.recv().await { + Ok(e) => { + if let Some(t) = f(&e) { + return t; + } + if let Event::Error { session, message } = e { + eprintln!("engine error (session {session}): {message}"); + } + } + Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => {} + Err(e) => panic!("event bus closed: {e}"), + } + } + }) + .await + .unwrap_or_else(|_| panic!("timed out waiting for {what}")) +} + +/// Wait until both `f` and `g` matched an event, in either order. Events of +/// the two sessions race, so waiting for them one after the other can drop one. +async fn wait_both( + rx: &mut Receiver, + what: &str, + mut f: impl FnMut(&Event) -> Option, + mut g: impl FnMut(&Event) -> Option, +) -> (A, B) { + let (mut a, mut b) = (None, None); + wait_for(rx, what, |e| { + if a.is_none() { + a = f(e); + } + if b.is_none() { + b = g(e); + } + (a.is_some() && b.is_some()).then_some(()) + }) + .await; + (a.unwrap(), b.unwrap()) +} + +async fn connect( + engine: &Engine, + events: &mut Receiver, + session: u64, + addr: &str, + nick: &str, +) { + let mut options = VoiceOptions::new(addr, nick); + options.stream_peer = PeerConfig::loopback(); + engine.send(Command::ConnectVoice { session, options: Box::new(options) }); + wait_for(events, "voice connected", |e| match e { + Event::State { session: s, state } + if *s == session + && state.voice == VoiceState::Connected + && state.own_channel.is_some() => + { + Some(()) + } + _ => None, + }) + .await; +} + +#[tokio::test(flavor = "multi_thread")] +async fn ts6_stream_between_sessions() { + if !live() { + eprintln!("skipped: set TSC_LIVE=1 with the dev servers running"); + return; + } + let engine = Engine::start(); + let mut events = engine.subscribe(); + let mut frames = engine.subscribe_frames(); + let tag = std::process::id() % 10_000; + connect(&engine, &mut events, 1, "127.0.0.1:9988", &format!("e-streamer-{tag}")).await; + connect(&engine, &mut events, 2, "127.0.0.1:9988", &format!("e-viewer-{tag}")).await; + + // Stream, asking for each viewer. + let setup = StreamSetup { name: format!("engine {tag}"), ..Default::default() }; + engine.send(Command::StartStream { session: 1, setup, auto_accept: false }); + // The viewer's list often updates before the streamer goes live, so wait + // for both at once and remember the latest list. + let mut live = None; + let mut listed = Vec::new(); + let (id, sink) = wait_for(&mut events, "stream live and in the viewer's list", |e| { + match e { + Event::StreamState { session: 1, state: StreamState::Live { id, sink } } => { + live = Some((id.clone(), sink.clone())); + } + Event::StreamState { session: 1, state: StreamState::Ended(reason) } => { + panic!("stream ended: {reason:?}") + } + Event::StreamsChanged { session: 2, streams } => { + listed = streams.iter().map(|s| s.id.clone()).collect(); + } + _ => {} + } + live.clone().filter(|(id, _)| listed.contains(id)) + }) + .await; + + // Synthetic frames through the sink, as an encoder would send them. + let feeder = tokio::spawn({ + let sink = sink.clone(); + async move { + let mut source = SyntheticSource::new(30, 3000, true); + let mut out = Vec::new(); + while sink.is_live() { + source.poll_frames(Instant::now(), &mut out); + for frame in out.drain(..) { + sink.send(frame); + } + tokio::time::sleep(Duration::from_millis(10)).await; + } + } + }); + + engine.send(Command::WatchStream { session: 2, stream_id: id.clone() }); + let viewer = wait_for(&mut events, "viewer request", |e| match e { + Event::StreamViewerRequest { session: 1, viewer, .. } => Some(*viewer), + _ => None, + }) + .await; + engine.send(Command::AcceptViewer { session: 1, viewer, accept: true }); + wait_both( + &mut events, + "watching and viewer connected", + |e| match e { + Event::WatchState { session: 2, stream_id, state: WatchState::Connected } + if *stream_id == id => + { + Some(()) + } + Event::WatchState { session: 2, state: WatchState::Ended(reason), .. } => { + panic!("watching ended: {reason:?}") + } + _ => None, + }, + |e| match e { + Event::StreamViewers { session: 1, viewers } + if viewers + .iter() + .any(|v| v.client.0 == viewer && v.state == ViewerState::Connected) => + { + Some(()) + } + _ => None, + }, + ) + .await; + assert!(sink.take_keyframe_request(), "a new viewer asks for a keyframe"); + + let (mut video, mut audio) = (0, 0); + let _ = timeout(Duration::from_secs(10), async { + while video < 60 || audio < 60 { + match frames.recv().await { + Ok(f) if f.session == 2 && f.stream_id == id => match f.frame.kind { + MediaKind::Video => video += 1, + MediaKind::Audio => audio += 1, + }, + Ok(_) | Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => {} + Err(_) => break, + } + } + }) + .await; + assert!(video >= 60 && audio >= 60, "viewer got {video} video / {audio} audio frames"); + + // The streamer removes the viewer, then ends the stream. + engine.send(Command::KickViewer { session: 1, viewer }); + wait_for(&mut events, "kicked", |e| match e { + Event::WatchState { + session: 2, + state: WatchState::Ended(EndReason::Removed(Some(LeaveReason::Kicked))), + .. + } => Some(()), + _ => None, + }) + .await; + engine.send(Command::StopStream { session: 1 }); + wait_both( + &mut events, + "stream ended and gone from the viewer's list", + |e| match e { + Event::StreamState { session: 1, state: StreamState::Ended(EndReason::Local) } => { + Some(()) + } + _ => None, + }, + |e| match e { + Event::StreamsChanged { session: 2, streams } if streams.iter().all(|s| s.id != id) => { + Some(()) + } + _ => None, + }, + ) + .await; + assert!(!sink.send(tsc_core::stream::EncodedFrame { + kind: MediaKind::Audio, + time: tsc_core::stream::MediaTime::from_90khz(0), + data: vec![0].into(), + })); + feeder.await.unwrap(); + + engine.send(Command::CloseSession { session: 1 }); + engine.send(Command::CloseSession { session: 2 }); + tokio::time::sleep(Duration::from_millis(500)).await; +} + +#[tokio::test(flavor = "multi_thread")] +async fn ts3_has_no_streams() { + if !live() { + return; + } + let engine = Engine::start(); + let mut events = engine.subscribe(); + let nick = format!("e-nostream-{}", std::process::id() % 10_000); + connect(&engine, &mut events, 1, "127.0.0.1:9987", &nick).await; + engine.send(Command::StartStream { + session: 1, + setup: StreamSetup::default(), + auto_accept: true, + }); + let message = wait_for(&mut events, "error", |e| match e { + Event::Error { session: 1, message } => Some(message.clone()), + _ => None, + }) + .await; + assert!(message.contains("TeamSpeak 6"), "{message}"); + engine.send(Command::CloseSession { session: 1 }); + tokio::time::sleep(Duration::from_millis(500)).await; +} diff --git a/crates/tsc-platform/Cargo.toml b/crates/tsc-platform/Cargo.toml new file mode 100644 index 0000000..09091b9 --- /dev/null +++ b/crates/tsc-platform/Cargo.toml @@ -0,0 +1,49 @@ +[package] +name = "tsc-platform" +version = "0.1.0" +description = "Desktop integration: global push-to-talk hotkeys, notifications and app directories." +edition.workspace = true +rust-version.workspace = true +license.workspace = true +repository.workspace = true +publish.workspace = true + +[features] +default = ["portal", "x11"] +# Wayland global shortcuts through xdg-desktop-portal (Linux). +portal = ["dep:ashpd", "dep:futures-util"] +# X11 global hotkeys through XInput2 raw events (Linux). +x11 = ["dep:x11rb"] + +[dependencies] +dirs = "6" +serde = { version = "1.0.228", features = ["derive"] } +thiserror = "2" +tokio = { version = "1", features = ["rt", "sync"] } +tracing = "0.1" + +[target.'cfg(all(unix, not(target_os = "macos")))'.dependencies] +ashpd = { version = "0.13", default-features = false, features = ["tokio", "global_shortcuts"], optional = true } +futures-util = { version = "0.3", optional = true } +notify-rust = { version = "4.18", default-features = false, features = ["z-with-tokio"] } +x11rb = { version = "0.13", features = ["xinput"], optional = true } + +[target.'cfg(windows)'.dependencies] +notify-rust = { version = "4.18", default-features = false } +windows = { version = "0.62", features = [ + "Win32_Foundation", + "Win32_System_LibraryLoader", + "Win32_System_Threading", + "Win32_UI_Input_KeyboardAndMouse", + "Win32_UI_WindowsAndMessaging", +] } + +[dev-dependencies] +serde_json = "1" +tokio = { version = "1", features = ["macros", "rt-multi-thread", "time"] } + +[target.'cfg(all(unix, not(target_os = "macos")))'.dev-dependencies] +x11rb = { version = "0.13", features = ["xinput", "xtest"] } + +[lints] +workspace = true diff --git a/crates/tsc-platform/src/hotkey/key.rs b/crates/tsc-platform/src/hotkey/key.rs new file mode 100644 index 0000000..70d3b80 --- /dev/null +++ b/crates/tsc-platform/src/hotkey/key.rs @@ -0,0 +1,456 @@ +//! Keys and key combinations, with their X11 keysyms, Windows virtual-key +//! codes and xdg "shortcuts" names. + +use std::fmt; +use std::str::FromStr; + +use serde::{Deserialize, Serialize}; + +use crate::Error; + +macro_rules! named_keys { + ($($variant:ident $name:literal $keysym:literal $vk:literal $xdg:literal;)*) => { + /// Keys that are not letters, digits, function or keypad digit keys. + #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] + pub enum NamedKey { + $($variant,)* + } + + impl NamedKey { + pub const ALL: &[NamedKey] = &[$(NamedKey::$variant,)*]; + + pub fn name(self) -> &'static str { + match self { + $(NamedKey::$variant => $name,)* + } + } + + fn keysym(self) -> u32 { + match self { + $(NamedKey::$variant => $keysym,)* + } + } + + fn vk(self) -> u16 { + match self { + $(NamedKey::$variant => $vk,)* + } + } + + fn xdg(self) -> &'static str { + match self { + $(NamedKey::$variant => $xdg,)* + } + } + } + }; +} + +// Mouse buttons have no keysym (0) and no xdg name (""); their codes are +// handled by the backends. +named_keys! { + Space "Space" 0x0020 0x20 "space"; + Tab "Tab" 0xff09 0x09 "Tab"; + CapsLock "CapsLock" 0xffe5 0x14 "Caps_Lock"; + Backquote "Backquote" 0x0060 0xc0 "grave"; + Minus "Minus" 0x002d 0xbd "minus"; + Equal "Equal" 0x003d 0xbb "equal"; + BracketLeft "BracketLeft" 0x005b 0xdb "bracketleft"; + BracketRight "BracketRight" 0x005d 0xdd "bracketright"; + Backslash "Backslash" 0x005c 0xdc "backslash"; + Semicolon "Semicolon" 0x003b 0xba "semicolon"; + Quote "Quote" 0x0027 0xde "apostrophe"; + Comma "Comma" 0x002c 0xbc "comma"; + Period "Period" 0x002e 0xbe "period"; + Slash "Slash" 0x002f 0xbf "slash"; + Enter "Enter" 0xff0d 0x0d "Return"; + Escape "Escape" 0xff1b 0x1b "Escape"; + Backspace "Backspace" 0xff08 0x08 "BackSpace"; + Insert "Insert" 0xff63 0x2d "Insert"; + Delete "Delete" 0xffff 0x2e "Delete"; + Home "Home" 0xff50 0x24 "Home"; + End "End" 0xff57 0x23 "End"; + PageUp "PageUp" 0xff55 0x21 "Prior"; + PageDown "PageDown" 0xff56 0x22 "Next"; + Left "Left" 0xff51 0x25 "Left"; + Up "Up" 0xff52 0x26 "Up"; + Right "Right" 0xff53 0x27 "Right"; + Down "Down" 0xff54 0x28 "Down"; + Pause "Pause" 0xff13 0x13 "Pause"; + ScrollLock "ScrollLock" 0xff14 0x91 "Scroll_Lock"; + PrintScreen "PrintScreen" 0xff61 0x2c "Print"; + NumLock "NumLock" 0xff7f 0x90 "Num_Lock"; + NumpadAdd "NumpadAdd" 0xffab 0x6b "KP_Add"; + NumpadSubtract "NumpadSubtract" 0xffad 0x6d "KP_Subtract"; + NumpadMultiply "NumpadMultiply" 0xffaa 0x6a "KP_Multiply"; + NumpadDivide "NumpadDivide" 0xffaf 0x6f "KP_Divide"; + NumpadDecimal "NumpadDecimal" 0xffae 0x6e "KP_Decimal"; + // Windows reports it as Enter with the extended flag. + NumpadEnter "NumpadEnter" 0xff8d 0x0d "KP_Enter"; + Menu "Menu" 0xff67 0x5d "Menu"; + LeftCtrl "LeftCtrl" 0xffe3 0xa2 "Control_L"; + RightCtrl "RightCtrl" 0xffe4 0xa3 "Control_R"; + LeftShift "LeftShift" 0xffe1 0xa0 "Shift_L"; + RightShift "RightShift" 0xffe2 0xa1 "Shift_R"; + LeftAlt "LeftAlt" 0xffe9 0xa4 "Alt_L"; + RightAlt "RightAlt" 0xffea 0xa5 "Alt_R"; + LeftSuper "LeftSuper" 0xffeb 0x5b "Super_L"; + RightSuper "RightSuper" 0xffec 0x5c "Super_R"; + MouseMiddle "MouseMiddle" 0 0x04 ""; + MouseBack "MouseBack" 0 0x05 ""; + MouseForward "MouseForward" 0 0x06 ""; +} + +/// X11 keysym of AltGr on most layouts, sitting on the right Alt key. +const XK_ISO_LEVEL3_SHIFT: u32 = 0xfe03; + +/// A physical key (or mouse side button) as a hotkey trigger. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum Key { + /// `'A'..='Z'`. + Letter(char), + /// 0 to 9 on the main keyboard. + Digit(u8), + /// F1 to F24. + F(u8), + /// 0 to 9 on the keypad. + Numpad(u8), + Named(NamedKey), +} + +/// Which modifier a key is, if it is one. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum ModifierKind { + Ctrl, + Shift, + Alt, + Super, +} + +impl Key { + fn validate(self) -> Result { + let ok = match self { + Key::Letter(c) => c.is_ascii_uppercase(), + Key::Digit(d) | Key::Numpad(d) => d <= 9, + Key::F(n) => (1..=24).contains(&n), + Key::Named(_) => true, + }; + if ok { Ok(self) } else { Err(Error::InvalidHotkey(format!("{self:?}"))) } + } + + pub fn is_mouse(self) -> bool { + matches!( + self, + Key::Named(NamedKey::MouseMiddle | NamedKey::MouseBack | NamedKey::MouseForward) + ) + } + + #[cfg(any(test, windows, all(unix, not(target_os = "macos"), feature = "x11")))] + pub(crate) fn modifier(self) -> Option { + match self { + Key::Named(NamedKey::LeftCtrl | NamedKey::RightCtrl) => Some(ModifierKind::Ctrl), + Key::Named(NamedKey::LeftShift | NamedKey::RightShift) => Some(ModifierKind::Shift), + Key::Named(NamedKey::LeftAlt | NamedKey::RightAlt) => Some(ModifierKind::Alt), + Key::Named(NamedKey::LeftSuper | NamedKey::RightSuper) => Some(ModifierKind::Super), + _ => None, + } + } + + /// X11 keysym (for letters the lowercase one). 0 for mouse buttons. + pub fn x11_keysym(self) -> u32 { + match self { + Key::Letter(c) => c.to_ascii_lowercase() as u32, + Key::Digit(d) => 0x30 + d as u32, + Key::F(n) => 0xffbe + n as u32 - 1, + Key::Numpad(d) => 0xffb0 + d as u32, + Key::Named(k) => k.keysym(), + } + } + + /// The key an X11 keysym belongs to (any shift level). + pub fn from_x11_keysym(keysym: u32) -> Option { + match keysym { + 0x61..=0x7a => Some(Key::Letter((keysym as u8 - 0x20) as char)), + 0x41..=0x5a => Some(Key::Letter(keysym as u8 as char)), + 0x30..=0x39 => Some(Key::Digit((keysym - 0x30) as u8)), + 0xffbe..=0xffd5 => Some(Key::F((keysym - 0xffbe + 1) as u8)), + 0xffb0..=0xffb9 => Some(Key::Numpad((keysym - 0xffb0) as u8)), + XK_ISO_LEVEL3_SHIFT => Some(Key::Named(NamedKey::RightAlt)), + 0 => None, + _ => NamedKey::ALL.iter().find(|k| k.keysym() == keysym).map(|&k| Key::Named(k)), + } + } + + /// Windows virtual-key code. Mouse buttons use VK_MBUTTON/VK_XBUTTON1/2. + pub fn windows_vk(self) -> u16 { + match self { + Key::Letter(c) => c as u16, + Key::Digit(d) => 0x30 + d as u16, + Key::F(n) => 0x70 + n as u16 - 1, + Key::Numpad(d) => 0x60 + d as u16, + Key::Named(k) => k.vk(), + } + } + + /// The key for a Windows virtual-key code; `extended` is the + /// low-level hook's extended-key flag (tells keypad Enter apart). + pub fn from_windows_vk(vk: u16, extended: bool) -> Option { + match vk { + 0x0d if extended => Some(Key::Named(NamedKey::NumpadEnter)), + 0x41..=0x5a => Some(Key::Letter(vk as u8 as char)), + 0x30..=0x39 => Some(Key::Digit((vk - 0x30) as u8)), + 0x70..=0x87 => Some(Key::F((vk - 0x70 + 1) as u8)), + 0x60..=0x69 => Some(Key::Numpad((vk - 0x60) as u8)), + // Generic Ctrl/Shift/Alt (never sent to low-level hooks, but cheap). + 0x10 => Some(Key::Named(NamedKey::LeftShift)), + 0x11 => Some(Key::Named(NamedKey::LeftCtrl)), + 0x12 => Some(Key::Named(NamedKey::LeftAlt)), + _ => NamedKey::ALL + .iter() + .find(|k| k.vk() == vk && **k != NamedKey::NumpadEnter) + .map(|&k| Key::Named(k)), + } + } + + /// Keysym name as used by the xdg "shortcuts" specification (portal + /// preferred triggers). `None` for mouse buttons. + pub fn xdg_name(self) -> Option { + let name = match self { + Key::Letter(c) => c.to_ascii_lowercase().to_string(), + Key::Digit(d) => d.to_string(), + Key::F(n) => format!("F{n}"), + Key::Numpad(d) => format!("KP_{d}"), + Key::Named(k) => k.xdg().to_string(), + }; + (!name.is_empty()).then_some(name) + } +} + +impl fmt::Display for Key { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Key::Letter(c) => write!(f, "{c}"), + Key::Digit(d) => write!(f, "{d}"), + Key::F(n) => write!(f, "F{n}"), + Key::Numpad(d) => write!(f, "Numpad{d}"), + Key::Named(k) => f.write_str(k.name()), + } + } +} + +impl FromStr for Key { + type Err = Error; + + fn from_str(s: &str) -> Result { + let invalid = || Error::InvalidHotkey(s.to_string()); + let key = if s.len() == 1 { + let c = s.chars().next().ok_or_else(invalid)?; + match c { + 'a'..='z' | 'A'..='Z' => Key::Letter(c.to_ascii_uppercase()), + '0'..='9' => Key::Digit(c as u8 - b'0'), + _ => return Err(invalid()), + } + } else if let Some(d) = s.strip_prefix("Numpad").and_then(|d| d.parse().ok()) { + Key::Numpad(d) + } else if let Some(n) = s.strip_prefix(['F', 'f']).and_then(|n| n.parse().ok()) { + Key::F(n) + } else { + let named = NamedKey::ALL.iter().find(|k| k.name().eq_ignore_ascii_case(s)); + Key::Named(*named.ok_or_else(invalid)?) + }; + key.validate().map_err(|_| invalid()) + } +} + +/// Modifiers that must be held with a hotkey's key. Either side counts. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +pub struct Modifiers { + pub ctrl: bool, + pub shift: bool, + pub alt: bool, + /// The Windows / Command / "logo" key. + pub logo: bool, +} + +impl Modifiers { + pub const NONE: Modifiers = Modifiers { ctrl: false, shift: false, alt: false, logo: false }; + + /// Every modifier in `self` is also in `held`. + pub fn is_subset_of(self, held: Modifiers) -> bool { + (!self.ctrl || held.ctrl) + && (!self.shift || held.shift) + && (!self.alt || held.alt) + && (!self.logo || held.logo) + } + + pub(crate) fn add(&mut self, kind: ModifierKind) { + match kind { + ModifierKind::Ctrl => self.ctrl = true, + ModifierKind::Shift => self.shift = true, + ModifierKind::Alt => self.alt = true, + ModifierKind::Super => self.logo = true, + } + } + + fn names(self) -> impl Iterator { + [ + (self.ctrl, "Ctrl", "CTRL"), + (self.shift, "Shift", "SHIFT"), + (self.alt, "Alt", "ALT"), + (self.logo, "Super", "LOGO"), + ] + .into_iter() + .filter(|(on, ..)| *on) + .map(|(_, name, xdg)| (name, xdg)) + } +} + +/// A key plus required modifiers, e.g. `Ctrl+Shift+T`, `F13`, `RightCtrl` +/// or `MouseBack`. +/// +/// Fires when the key goes down while at least these modifiers are held +/// (extra modifiers do not prevent it, so push-to-talk keeps working while +/// typing with Shift), and releases when the key goes up. Serialized as +/// that string. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(try_from = "String", into = "String")] +pub struct Hotkey { + pub modifiers: Modifiers, + pub key: Key, +} + +impl Hotkey { + pub fn new(key: Key) -> Self { + Self { modifiers: Modifiers::NONE, key } + } + + pub fn with(mut self, modifiers: Modifiers) -> Self { + self.modifiers = modifiers; + self + } + + /// Trigger in the xdg "shortcuts" format (`CTRL+SHIFT+t`), as the + /// portal's preferred trigger. `None` for mouse buttons. + pub fn xdg_trigger(&self) -> Option { + let key = self.key.xdg_name()?; + let mut parts: Vec = self.modifiers.names().map(|(_, x)| x.to_string()).collect(); + parts.push(key); + Some(parts.join("+")) + } +} + +impl fmt::Display for Hotkey { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + for (name, _) in self.modifiers.names() { + write!(f, "{name}+")?; + } + write!(f, "{}", self.key) + } +} + +impl FromStr for Hotkey { + type Err = Error; + + fn from_str(s: &str) -> Result { + let mut parts: Vec<&str> = s.split('+').map(str::trim).collect(); + // "Ctrl++" is not supported; Plus is not a key here. + let key = parts.pop().filter(|k| !k.is_empty()); + let key: Key = key.ok_or_else(|| Error::InvalidHotkey(s.to_string()))?.parse()?; + let mut modifiers = Modifiers::NONE; + for part in parts { + let kind = match part.to_ascii_lowercase().as_str() { + "ctrl" | "control" => ModifierKind::Ctrl, + "shift" => ModifierKind::Shift, + "alt" => ModifierKind::Alt, + "super" | "logo" | "win" | "meta" => ModifierKind::Super, + _ => return Err(Error::InvalidHotkey(s.to_string())), + }; + modifiers.add(kind); + } + Ok(Hotkey { modifiers, key }) + } +} + +impl TryFrom for Hotkey { + type Error = Error; + + fn try_from(s: String) -> Result { + s.parse() + } +} + +impl From for String { + fn from(h: Hotkey) -> String { + h.to_string() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn parse_and_display() { + for s in + ["Ctrl+Shift+T", "F13", "RightCtrl", "MouseBack", "Alt+Numpad5", "Super+Space", "7"] + { + let h: Hotkey = s.parse().unwrap(); + assert_eq!(h.to_string(), s); + } + let h: Hotkey = "control + shift + t".parse().unwrap(); + assert_eq!(h.to_string(), "Ctrl+Shift+T"); + assert_eq!("win+f1".parse::().unwrap().to_string(), "Super+F1"); + for bad in ["", "Ctrl+", "Hyper+A", "F25", "F0", "Numpad10", "NoSuchKey", "Ctrl+Shift"] { + assert!(bad.parse::().is_err(), "{bad} should not parse"); + } + } + + #[test] + fn serde_as_string() { + let h: Hotkey = "Ctrl+F13".parse().unwrap(); + let json = serde_json::to_string(&h).unwrap(); + assert_eq!(json, r#""Ctrl+F13""#); + assert_eq!(serde_json::from_str::(&json).unwrap(), h); + assert!(serde_json::from_str::(r#""Ctrl+Nope""#).is_err()); + } + + #[test] + fn platform_codes_roundtrip() { + let mut keys: Vec = NamedKey::ALL.iter().map(|&k| Key::Named(k)).collect(); + keys.extend(('A'..='Z').map(Key::Letter)); + keys.extend((0..=9).map(Key::Digit)); + keys.extend((0..=9).map(Key::Numpad)); + keys.extend((1..=24).map(Key::F)); + for key in keys { + let extended = key == Key::Named(NamedKey::NumpadEnter); + assert_eq!(Key::from_windows_vk(key.windows_vk(), extended), Some(key), "{key}"); + if !key.is_mouse() { + assert_eq!(Key::from_x11_keysym(key.x11_keysym()), Some(key), "{key}"); + assert!(key.xdg_name().is_some()); + } + assert_eq!(key.to_string().parse::().unwrap(), key); + } + // Shifted letters and AltGr. + assert_eq!(Key::from_x11_keysym(0x41), Some(Key::Letter('A'))); + assert_eq!(Key::from_x11_keysym(0xfe03), Some(Key::Named(NamedKey::RightAlt))); + assert_eq!(Key::from_x11_keysym(0x1234), None); + } + + #[test] + fn xdg_triggers() { + let h: Hotkey = "Ctrl+Shift+T".parse().unwrap(); + assert_eq!(h.xdg_trigger().as_deref(), Some("CTRL+SHIFT+t")); + let h: Hotkey = "Super+PageUp".parse().unwrap(); + assert_eq!(h.xdg_trigger().as_deref(), Some("LOGO+Prior")); + assert_eq!("MouseBack".parse::().unwrap().xdg_trigger(), None); + } + + #[test] + fn modifier_subsets() { + let ctrl = Modifiers { ctrl: true, ..Modifiers::NONE }; + let ctrl_shift = Modifiers { shift: true, ..ctrl }; + assert!(Modifiers::NONE.is_subset_of(ctrl)); + assert!(ctrl.is_subset_of(ctrl_shift)); + assert!(!ctrl_shift.is_subset_of(ctrl)); + } +} diff --git a/crates/tsc-platform/src/hotkey/mod.rs b/crates/tsc-platform/src/hotkey/mod.rs new file mode 100644 index 0000000..434e6df --- /dev/null +++ b/crates/tsc-platform/src/hotkey/mod.rs @@ -0,0 +1,216 @@ +//! Global hotkeys with press and release events, for push-to-talk. +//! +//! Backends, picked by [`HotkeyManager::new`]: +//! +//! - **Portal** (Wayland): the xdg-desktop-portal `GlobalShortcuts` +//! interface. The compositor owns the binding: our [`Hotkey`] is only the +//! preferred trigger, the user confirms or changes it in a system dialog, +//! and the portal reports `Activated` / `Deactivated`. Needs KDE Plasma +//! 5.27+, GNOME 48+ or another desktop implementing it. +//! - **X11**: XInput2 raw key and button events on the root window. They are +//! delivered whatever window has focus and nothing is grabbed, so the key +//! still reaches the focused application. Under Wayland this only sees keys +//! while an X11 (XWayland) window has focus. +//! - **Windows**: a low-level keyboard and mouse hook (`WH_KEYBOARD_LL`, +//! `WH_MOUSE_LL`) on its own thread. `RegisterHotKey` would only report +//! presses and swallow the key. + +// Builds without a backend (other platforms, or Linux without both +// features) compile, but have nothing to register with. +#![cfg_attr( + not(any( + windows, + all(unix, not(target_os = "macos"), any(feature = "portal", feature = "x11")) + )), + allow(unused_variables, unreachable_code) +)] + +mod key; +#[cfg(any(test, windows, all(unix, not(target_os = "macos"), feature = "x11")))] +mod tracker; + +#[cfg(all(unix, not(target_os = "macos"), feature = "portal"))] +mod portal; +#[cfg(windows)] +mod windows; +#[cfg(all(unix, not(target_os = "macos"), feature = "x11"))] +mod x11; + +pub use key::{Hotkey, Key, Modifiers, NamedKey}; +use tokio::sync::mpsc; + +use crate::{Error, Result}; + +/// A registered hotkey went down or up. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum HotkeyEvent { + Pressed, + Released, +} + +/// Events of one registration; dropping it unregisters the hotkey on the +/// next key event (X11, Windows) or on [`HotkeyManager::unregister`]. +pub type HotkeyEvents = mpsc::UnboundedReceiver; + +/// How hotkeys are captured. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum BackendKind { + Portal, + X11, + WindowsHook, +} + +enum Backend { + #[cfg(all(unix, not(target_os = "macos"), feature = "portal"))] + Portal(portal::PortalBackend), + #[cfg(all(unix, not(target_os = "macos"), feature = "x11"))] + X11(x11::X11Backend), + #[cfg(windows)] + Windows(windows::HookBackend), + /// Keeps matches exhaustive on platforms without any backend. + #[allow(dead_code)] + None(std::convert::Infallible), +} + +/// Registers global hotkeys. See the [module docs](self) for the backends. +pub struct HotkeyManager { + backend: Backend, +} + +impl HotkeyManager { + /// The best backend for this desktop session: the portal on Wayland + /// (falling back to X11 when the desktop does not offer it), X11 on X11, + /// the hook on Windows. Must be called within a Tokio runtime (the portal + /// listens for its signals on a task). + pub async fn new() -> Result { + let mut errors = Vec::new(); + for kind in preferred_backends() { + match Self::with_backend(kind).await { + Ok(manager) => return Ok(manager), + Err(e) => { + tracing::debug!(?kind, %e, "hotkey backend unavailable"); + errors.push(format!("{kind:?}: {e}")); + } + } + } + Err(Error::Unsupported(if errors.is_empty() { + "no hotkey backend for this platform".into() + } else { + errors.join("; ") + })) + } + + /// Use a specific backend. + pub async fn with_backend(kind: BackendKind) -> Result { + let backend = match kind { + #[cfg(all(unix, not(target_os = "macos"), feature = "portal"))] + BackendKind::Portal => Backend::Portal(portal::PortalBackend::new().await?), + #[cfg(all(unix, not(target_os = "macos"), feature = "x11"))] + BackendKind::X11 => Backend::X11(x11::X11Backend::connect(None)?), + #[cfg(windows)] + BackendKind::WindowsHook => Backend::Windows(windows::HookBackend::start()?), + #[allow(unreachable_patterns)] + _ => return Err(Error::Unsupported(format!("{kind:?} is not available in this build"))), + }; + Ok(Self { backend }) + } + + /// X11 on a specific display (e.g. `":1"`), mainly for tests. + #[cfg(all(unix, not(target_os = "macos"), feature = "x11"))] + pub fn x11(display: &str) -> Result { + Ok(Self { backend: Backend::X11(x11::X11Backend::connect(Some(display))?) }) + } + + pub fn backend(&self) -> BackendKind { + match &self.backend { + #[cfg(all(unix, not(target_os = "macos"), feature = "portal"))] + Backend::Portal(_) => BackendKind::Portal, + #[cfg(all(unix, not(target_os = "macos"), feature = "x11"))] + Backend::X11(_) => BackendKind::X11, + #[cfg(windows)] + Backend::Windows(_) => BackendKind::WindowsHook, + Backend::None(never) => match *never {}, + } + } + + /// Register `hotkey` under a stable `id` (the portal remembers the + /// user's choice by it); `description` is shown in the portal's dialog. + /// Registering an id again replaces it. + /// + /// With the portal this may show a dialog and waits for the user. + pub async fn register( + &mut self, + id: &str, + description: &str, + hotkey: Hotkey, + ) -> Result { + let _ = description; + match &mut self.backend { + #[cfg(all(unix, not(target_os = "macos"), feature = "portal"))] + Backend::Portal(p) => p.register(id, description, hotkey).await, + #[cfg(all(unix, not(target_os = "macos"), feature = "x11"))] + Backend::X11(x) => Ok(x.register(id, hotkey)), + #[cfg(windows)] + Backend::Windows(w) => Ok(w.register(id, hotkey)), + Backend::None(never) => match *never {}, + } + } + + pub async fn unregister(&mut self, id: &str) -> Result<()> { + match &mut self.backend { + #[cfg(all(unix, not(target_os = "macos"), feature = "portal"))] + Backend::Portal(p) => p.unregister(id).await, + #[cfg(all(unix, not(target_os = "macos"), feature = "x11"))] + Backend::X11(x) => { + x.unregister(id); + Ok(()) + } + #[cfg(windows)] + Backend::Windows(w) => { + w.unregister(id); + Ok(()) + } + Backend::None(never) => match *never {}, + } + } + + /// What actually triggers `id`, as the desktop describes it (portal + /// only: the user may have picked another key). Other backends return + /// `None`; the registered [`Hotkey`] is the trigger. + pub fn trigger_description(&self, id: &str) -> Option { + match &self.backend { + #[cfg(all(unix, not(target_os = "macos"), feature = "portal"))] + Backend::Portal(p) => p.trigger_description(id), + #[allow(unreachable_patterns)] + _ => { + let _ = id; + None + } + } + } +} + +/// Backends to try, best first. +fn preferred_backends() -> Vec { + if cfg!(windows) { + return vec![BackendKind::WindowsHook]; + } + if !cfg!(all(unix, not(target_os = "macos"))) { + return Vec::new(); + } + let wayland = std::env::var_os("WAYLAND_DISPLAY").is_some() + || std::env::var("XDG_SESSION_TYPE").is_ok_and(|t| t == "wayland"); + let x11 = std::env::var_os("DISPLAY").is_some(); + let mut kinds = Vec::new(); + if wayland { + kinds.push(BackendKind::Portal); + } + if x11 { + kinds.push(BackendKind::X11); + } + if !wayland { + // E.g. a portal without a Wayland session, or no display variables. + kinds.push(BackendKind::Portal); + } + kinds +} diff --git a/crates/tsc-platform/src/hotkey/portal.rs b/crates/tsc-platform/src/hotkey/portal.rs new file mode 100644 index 0000000..66f0706 --- /dev/null +++ b/crates/tsc-platform/src/hotkey/portal.rs @@ -0,0 +1,162 @@ +//! Wayland backend: xdg-desktop-portal `GlobalShortcuts`. +//! +//! The portal binds all shortcuts of a session at once, so every change +//! closes the session and binds the full list in a new one. Shortcuts the +//! user already confirmed are remembered by id and do not ask again. + +use std::collections::HashMap; +use std::sync::{Arc, Mutex, PoisonError}; + +use ashpd::desktop::global_shortcuts::{ + Activated, BindShortcutsOptions, Deactivated, GlobalShortcuts, NewShortcut, +}; +use ashpd::desktop::{CreateSessionOptions, Session}; +use futures_util::{Stream, StreamExt}; +use tokio::sync::mpsc; +use tracing::debug; + +use super::{Hotkey, HotkeyEvent, HotkeyEvents}; +use crate::{APP_ID, Error, Result}; + +type Senders = Arc>>>; + +fn portal_error(e: ashpd::Error) -> Error { + Error::Backend(format!("portal: {e}")) +} + +struct Shortcut { + id: String, + description: String, + hotkey: Hotkey, +} + +pub(crate) struct PortalBackend { + portal: GlobalShortcuts, + session: Option>, + shortcuts: Vec, + senders: Senders, + triggers: HashMap, + listener: tokio::task::JoinHandle<()>, +} + +impl PortalBackend { + pub async fn new() -> Result { + // Outside a sandbox the portal learns our app id this way (newer + // portals need it for global shortcuts); older ones lack the call. + if let Ok(app_id) = APP_ID.parse() + && let Err(e) = ashpd::register_host_app(app_id).await + { + debug!(%e, "portal host app registration"); + } + let portal = GlobalShortcuts::new().await.map_err(portal_error)?; + let activated = portal.receive_activated().await.map_err(portal_error)?; + let deactivated = portal.receive_deactivated().await.map_err(portal_error)?; + let senders = Senders::default(); + let listener = tokio::spawn(listen(activated, deactivated, senders.clone())); + Ok(Self { + portal, + session: None, + shortcuts: Vec::new(), + senders, + triggers: HashMap::new(), + listener, + }) + } + + fn senders( + &self, + ) -> std::sync::MutexGuard<'_, HashMap>> { + self.senders.lock().unwrap_or_else(PoisonError::into_inner) + } + + pub async fn register( + &mut self, + id: &str, + description: &str, + hotkey: Hotkey, + ) -> Result { + if hotkey.key.is_mouse() { + return Err(Error::Unsupported("the portal does not bind mouse buttons".into())); + } + self.shortcuts.retain(|s| s.id != id); + self.shortcuts.push(Shortcut { id: id.into(), description: description.into(), hotkey }); + if let Err(e) = self.rebind().await { + self.shortcuts.retain(|s| s.id != id); + return Err(e); + } + let (tx, rx) = mpsc::unbounded_channel(); + self.senders().insert(id.into(), tx); + Ok(rx) + } + + pub async fn unregister(&mut self, id: &str) -> Result<()> { + self.senders().remove(id); + self.shortcuts.retain(|s| s.id != id); + self.rebind().await + } + + pub fn trigger_description(&self, id: &str) -> Option { + self.triggers.get(id).cloned() + } + + async fn rebind(&mut self) -> Result<()> { + if let Some(old) = self.session.take() { + let _ = old.close().await; + } + self.triggers.clear(); + if self.shortcuts.is_empty() { + return Ok(()); + } + let session = self + .portal + .create_session(CreateSessionOptions::default()) + .await + .map_err(portal_error)?; + let new: Vec = self + .shortcuts + .iter() + .map(|s| { + let trigger = s.hotkey.xdg_trigger(); + NewShortcut::new(&s.id, &s.description).preferred_trigger(trigger.as_deref()) + }) + .collect(); + let request = self + .portal + .bind_shortcuts(&session, &new, None, BindShortcutsOptions::default()) + .await + .map_err(portal_error)?; + let bound = request.response().map_err(portal_error)?; + self.triggers = bound + .shortcuts() + .iter() + .map(|s| (s.id().to_string(), s.trigger_description().to_string())) + .collect(); + self.session = Some(session); + Ok(()) + } +} + +impl Drop for PortalBackend { + fn drop(&mut self) { + // Closing the session needs an await; the portal closes it when our + // D-Bus connection goes away. + self.listener.abort(); + } +} + +/// Forward `Activated` / `Deactivated` to the registration with that id. +async fn listen( + activated: impl Stream, + deactivated: impl Stream, + senders: Senders, +) { + let activated = activated.map(|a| (a.shortcut_id().to_string(), HotkeyEvent::Pressed)); + let deactivated = deactivated.map(|d| (d.shortcut_id().to_string(), HotkeyEvent::Released)); + let mut events = std::pin::pin!(futures_util::stream::select(activated, deactivated)); + while let Some((id, event)) = events.next().await { + let senders = senders.lock().unwrap_or_else(PoisonError::into_inner); + if let Some(tx) = senders.get(&id) { + let _ = tx.send(event); + } + } +} diff --git a/crates/tsc-platform/src/hotkey/tracker.rs b/crates/tsc-platform/src/hotkey/tracker.rs new file mode 100644 index 0000000..f92cf9e --- /dev/null +++ b/crates/tsc-platform/src/hotkey/tracker.rs @@ -0,0 +1,147 @@ +//! Turns raw key presses and releases into hotkey events. Used by the +//! backends that see every key (X11 raw events, the Windows keyboard hook); +//! the portal does its own matching. + +use std::collections::HashSet; + +use tokio::sync::mpsc; + +use super::{Hotkey, HotkeyEvent, HotkeyEvents, Key, Modifiers}; + +struct Registration { + id: String, + hotkey: Hotkey, + events: mpsc::UnboundedSender, + active: bool, +} + +#[derive(Default)] +pub(crate) struct Tracker { + registrations: Vec, + held: HashSet, +} + +impl Tracker { + /// Register (or replace) `id`. + pub fn add(&mut self, id: &str, hotkey: Hotkey) -> HotkeyEvents { + self.remove(id); + let (tx, rx) = mpsc::unbounded_channel(); + self.registrations.push(Registration { id: id.into(), hotkey, events: tx, active: false }); + rx + } + + pub fn remove(&mut self, id: &str) -> bool { + let before = self.registrations.len(); + self.registrations.retain(|r| r.id != id); + self.registrations.len() != before + } + + #[cfg(test)] + pub fn is_empty(&self) -> bool { + self.registrations.is_empty() + } + + fn held_modifiers(&self) -> Modifiers { + let mut m = Modifiers::NONE; + for kind in self.held.iter().filter_map(|k| k.modifier()) { + m.add(kind); + } + m + } + + /// A key went down (`pressed`) or up. Auto-repeat presses are ignored. + pub fn key(&mut self, key: Key, pressed: bool) { + if pressed { + self.held.insert(key); + let held = self.held_modifiers(); + for r in &mut self.registrations { + if !r.active && r.hotkey.key == key && r.hotkey.modifiers.is_subset_of(held) { + r.active = true; + let _ = r.events.send(HotkeyEvent::Pressed); + } + } + } else { + self.held.remove(&key); + for r in &mut self.registrations { + if r.active && r.hotkey.key == key { + r.active = false; + let _ = r.events.send(HotkeyEvent::Released); + } + } + } + // Receivers that were dropped unregister themselves. + self.registrations.retain(|r| !r.events.is_closed()); + } + + /// Release everything (e.g. the keyboard state was lost). + pub fn release_all(&mut self) { + self.held.clear(); + for r in &mut self.registrations { + if r.active { + r.active = false; + let _ = r.events.send(HotkeyEvent::Released); + } + } + } +} + +#[cfg(test)] +mod tests { + use super::super::NamedKey; + use super::*; + + fn drain(rx: &mut HotkeyEvents) -> Vec { + std::iter::from_fn(|| rx.try_recv().ok()).collect() + } + + #[test] + fn press_release_with_modifiers() { + use HotkeyEvent::*; + let mut t = Tracker::default(); + let mut ptt = t.add("ptt", "Ctrl+F13".parse().unwrap()); + let mut plain = t.add("mute", "M".parse().unwrap()); + let ctrl = Key::Named(NamedKey::RightCtrl); + + // Without Ctrl nothing happens for Ctrl+F13. + t.key(Key::F(13), true); + t.key(Key::F(13), false); + assert!(drain(&mut ptt).is_empty()); + + t.key(ctrl, true); + t.key(Key::F(13), true); + t.key(Key::F(13), true); // auto-repeat + // Letting go of Ctrl first keeps it pressed until F13 is released. + t.key(ctrl, false); + assert_eq!(drain(&mut ptt), vec![Pressed]); + t.key(Key::F(13), false); + assert_eq!(drain(&mut ptt), vec![Released]); + + // Extra modifiers do not block a plain hotkey. + t.key(Key::Named(NamedKey::LeftShift), true); + t.key(Key::Letter('M'), true); + t.key(Key::Letter('M'), false); + assert_eq!(drain(&mut plain), vec![Pressed, Released]); + } + + #[test] + fn modifier_alone_and_unregister() { + use HotkeyEvent::*; + let mut t = Tracker::default(); + let mut rx = t.add("ptt", "RightCtrl".parse().unwrap()); + let key = Key::Named(NamedKey::RightCtrl); + t.key(key, true); + t.release_all(); + assert_eq!(drain(&mut rx), vec![Pressed, Released]); + + assert!(t.remove("ptt")); + assert!(!t.remove("ptt")); + t.key(key, true); + assert!(rx.try_recv().is_err()); + + // A dropped receiver unregisters on the next key. + let rx = t.add("x", "A".parse().unwrap()); + drop(rx); + t.key(Key::Letter('B'), true); + assert!(t.is_empty()); + } +} diff --git a/crates/tsc-platform/src/hotkey/windows.rs b/crates/tsc-platform/src/hotkey/windows.rs new file mode 100644 index 0000000..4ec8591 --- /dev/null +++ b/crates/tsc-platform/src/hotkey/windows.rs @@ -0,0 +1,179 @@ +//! Windows backend: low-level keyboard and mouse hooks. +//! +//! `RegisterHotKey` only reports presses and takes the key away from other +//! applications, so push-to-talk uses `WH_KEYBOARD_LL` / `WH_MOUSE_LL` +//! instead. The hooks run on a dedicated thread with a message loop (Windows +//! calls low-level hooks on the installing thread) and always pass events +//! on. Hook procedures get no user data, so the thread's tracker lives in a +//! thread local. +//! +//! This is the crate's only unsafe code: the Win32 calls and reading the +//! hook structs Windows hands to the callbacks. +#![allow(unsafe_code)] + +use std::cell::RefCell; +use std::sync::{Arc, Mutex, PoisonError, mpsc as std_mpsc}; +use std::thread; + +use windows::Win32::Foundation::{HINSTANCE, LPARAM, LRESULT, WPARAM}; +use windows::Win32::System::LibraryLoader::GetModuleHandleW; +use windows::Win32::System::Threading::GetCurrentThreadId; +use windows::Win32::UI::WindowsAndMessaging::{ + CallNextHookEx, DispatchMessageW, GetMessageW, HC_ACTION, HHOOK, KBDLLHOOKSTRUCT, + LLKHF_EXTENDED, MSG, MSLLHOOKSTRUCT, PostThreadMessageW, SetWindowsHookExW, TranslateMessage, + UnhookWindowsHookEx, WH_KEYBOARD_LL, WH_MOUSE_LL, WM_KEYDOWN, WM_KEYUP, WM_MBUTTONDOWN, + WM_MBUTTONUP, WM_QUIT, WM_SYSKEYDOWN, WM_SYSKEYUP, WM_XBUTTONDOWN, WM_XBUTTONUP, +}; +use windows::core::PCWSTR; + +use super::tracker::Tracker; +use super::{Hotkey, HotkeyEvents, Key, NamedKey}; +use crate::{Error, Result}; + +thread_local! { + /// The tracker of the hook thread this runs on. + static TRACKER: RefCell>>> = const { RefCell::new(None) }; +} + +fn with_tracker(f: impl FnOnce(&mut Tracker)) { + TRACKER.with(|t| { + if let Some(tracker) = &*t.borrow() { + f(&mut tracker.lock().unwrap_or_else(PoisonError::into_inner)); + } + }); +} + +/// Keyboard hook procedure. +unsafe extern "system" fn keyboard_proc(code: i32, wparam: WPARAM, lparam: LPARAM) -> LRESULT { + if code == HC_ACTION as i32 { + // SAFETY: for WH_KEYBOARD_LL with HC_ACTION, lparam points to a + // KBDLLHOOKSTRUCT that is valid for the duration of this call. + let info = unsafe { &*(lparam.0 as *const KBDLLHOOKSTRUCT) }; + let pressed = match wparam.0 as u32 { + WM_KEYDOWN | WM_SYSKEYDOWN => Some(true), + WM_KEYUP | WM_SYSKEYUP => Some(false), + _ => None, + }; + let extended = info.flags.contains(LLKHF_EXTENDED); + if let (Some(pressed), Some(key)) = + (pressed, Key::from_windows_vk(info.vkCode as u16, extended)) + { + with_tracker(|t| t.key(key, pressed)); + } + } + // SAFETY: passing the unchanged arguments on to the next hook. + unsafe { CallNextHookEx(None, code, wparam, lparam) } +} + +/// Mouse hook procedure: middle and side buttons. +unsafe extern "system" fn mouse_proc(code: i32, wparam: WPARAM, lparam: LPARAM) -> LRESULT { + if code == HC_ACTION as i32 { + // SAFETY: for WH_MOUSE_LL with HC_ACTION, lparam points to a + // MSLLHOOKSTRUCT that is valid for the duration of this call. + let info = unsafe { &*(lparam.0 as *const MSLLHOOKSTRUCT) }; + let side = |pressed| { + // The high word of mouseData: 1 = XBUTTON1 (back), 2 = forward. + let key = match info.mouseData >> 16 { + 1 => NamedKey::MouseBack, + 2 => NamedKey::MouseForward, + _ => return None, + }; + Some((Key::Named(key), pressed)) + }; + let event = match wparam.0 as u32 { + WM_MBUTTONDOWN => Some((Key::Named(NamedKey::MouseMiddle), true)), + WM_MBUTTONUP => Some((Key::Named(NamedKey::MouseMiddle), false)), + WM_XBUTTONDOWN => side(true), + WM_XBUTTONUP => side(false), + _ => None, + }; + if let Some((key, pressed)) = event { + with_tracker(|t| t.key(key, pressed)); + } + } + // SAFETY: passing the unchanged arguments on to the next hook. + unsafe { CallNextHookEx(None, code, wparam, lparam) } +} + +/// Install both hooks on this thread. +fn install() -> windows::core::Result<(HHOOK, HHOOK)> { + // SAFETY: plain Win32 calls with valid arguments; the hook procedures + // have the HOOKPROC signature and live for the whole program. + unsafe { + let module = HINSTANCE::from(GetModuleHandleW(PCWSTR::null())?); + let keyboard = SetWindowsHookExW(WH_KEYBOARD_LL, Some(keyboard_proc), Some(module), 0)?; + match SetWindowsHookExW(WH_MOUSE_LL, Some(mouse_proc), Some(module), 0) { + Ok(mouse) => Ok((keyboard, mouse)), + Err(e) => { + let _ = UnhookWindowsHookEx(keyboard); + Err(e) + } + } + } +} + +fn hook_thread(tracker: Arc>, ready: std_mpsc::Sender>) { + TRACKER.with(|t| *t.borrow_mut() = Some(tracker.clone())); + let hooks = match install() { + Ok(hooks) => hooks, + Err(e) => { + let _ = ready.send(Err(Error::Backend(format!("keyboard hook: {e}")))); + return; + } + }; + // SAFETY: returns the id of the calling thread. + let _ = ready.send(Ok(unsafe { GetCurrentThreadId() })); + let mut msg = MSG::default(); + // SAFETY: standard message loop on this thread's queue; `msg` is valid. + // GetMessageW returns 0 for WM_QUIT and -1 on errors. + unsafe { + while GetMessageW(&mut msg, None, 0, 0).0 > 0 { + let _ = TranslateMessage(&msg); + DispatchMessageW(&msg); + } + let _ = UnhookWindowsHookEx(hooks.0); + let _ = UnhookWindowsHookEx(hooks.1); + } + tracker.lock().unwrap_or_else(PoisonError::into_inner).release_all(); +} + +pub(crate) struct HookBackend { + tracker: Arc>, + thread_id: u32, +} + +impl HookBackend { + pub fn start() -> Result { + let tracker = Arc::new(Mutex::new(Tracker::default())); + let (ready_tx, ready_rx) = std_mpsc::channel(); + { + let tracker = tracker.clone(); + thread::Builder::new() + .name("tsc-hotkeys-hook".into()) + .spawn(move || hook_thread(tracker, ready_tx)) + .map_err(|e| Error::Backend(format!("keyboard hook: {e}")))?; + } + let thread_id = + ready_rx.recv().map_err(|_| Error::Backend("keyboard hook thread ended".into()))??; + Ok(Self { tracker, thread_id }) + } + + fn tracker(&self) -> std::sync::MutexGuard<'_, Tracker> { + self.tracker.lock().unwrap_or_else(PoisonError::into_inner) + } + + pub fn register(&mut self, id: &str, hotkey: Hotkey) -> HotkeyEvents { + self.tracker().add(id, hotkey) + } + + pub fn unregister(&mut self, id: &str) { + self.tracker().remove(id); + } +} + +impl Drop for HookBackend { + fn drop(&mut self) { + // SAFETY: posting WM_QUIT to our hook thread's queue ends its loop. + let _ = unsafe { PostThreadMessageW(self.thread_id, WM_QUIT, WPARAM(0), LPARAM(0)) }; + } +} diff --git a/crates/tsc-platform/src/hotkey/x11.rs b/crates/tsc-platform/src/hotkey/x11.rs new file mode 100644 index 0000000..e587ae4 --- /dev/null +++ b/crates/tsc-platform/src/hotkey/x11.rs @@ -0,0 +1,193 @@ +//! X11 backend: XInput2 raw key and button events on the root window. +//! +//! Raw events reach us whichever window has focus, and nothing is grabbed, +//! so the key also reaches the focused application. A thread blocks on the +//! connection; dropping the backend wakes it with a client message to a +//! private input-only window. + +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, Mutex, PoisonError}; +use std::thread; + +use tracing::{debug, warn}; +use x11rb::connection::Connection; +use x11rb::protocol::Event; +use x11rb::protocol::xinput::{self, ConnectionExt as _, XIEventMask}; +use x11rb::protocol::xproto::{ + AtomEnum, ClientMessageEvent, ConnectionExt as _, CreateWindowAux, EventMask, Window, + WindowClass, +}; +use x11rb::rust_connection::RustConnection; + +use super::tracker::Tracker; +use super::{Hotkey, HotkeyEvents, Key, NamedKey}; +use crate::{Error, Result}; + +fn x11_error(e: impl std::fmt::Display) -> Error { + Error::Backend(format!("X11: {e}")) +} + +/// Keycode to keysyms, from the server's keyboard mapping. +struct Keymap { + min_keycode: u8, + per_keycode: usize, + keysyms: Vec, +} + +impl Keymap { + fn load(conn: &RustConnection) -> Result { + let setup = conn.setup(); + let (min, max) = (setup.min_keycode, setup.max_keycode); + let reply = conn + .get_keyboard_mapping(min, max - min + 1) + .map_err(x11_error)? + .reply() + .map_err(x11_error)?; + Ok(Self { + min_keycode: min, + per_keycode: reply.keysyms_per_keycode as usize, + keysyms: reply.keysyms, + }) + } + + /// The key on this keycode, by the first of its keysyms we know. + fn key(&self, keycode: u32) -> Option { + let index = (keycode.checked_sub(self.min_keycode as u32)? as usize) * self.per_keycode; + let syms = self.keysyms.get(index..index + self.per_keycode)?; + syms.iter().find_map(|&s| Key::from_x11_keysym(s)) + } +} + +/// Raw (physical) button numbers: 2 middle, 8 back, 9 forward. +fn button_key(button: u32) -> Option { + match button { + 2 => Some(Key::Named(NamedKey::MouseMiddle)), + 8 => Some(Key::Named(NamedKey::MouseBack)), + 9 => Some(Key::Named(NamedKey::MouseForward)), + _ => None, + } +} + +pub(crate) struct X11Backend { + conn: Arc, + wake_window: Window, + tracker: Arc>, + stop: Arc, +} + +impl X11Backend { + /// Connect to `display`, or `$DISPLAY` for `None`. + pub fn connect(display: Option<&str>) -> Result { + let (conn, screen) = x11rb::connect(display).map_err(x11_error)?; + let root = conn.setup().roots[screen].root; + + let version = + conn.xinput_xi_query_version(2, 0).map_err(x11_error)?.reply().map_err(x11_error)?; + if version.major_version < 2 { + return Err(Error::Backend("X11: XInput 2 is not available".into())); + } + let mask = XIEventMask::RAW_KEY_PRESS + | XIEventMask::RAW_KEY_RELEASE + | XIEventMask::RAW_BUTTON_PRESS + | XIEventMask::RAW_BUTTON_RELEASE; + let masks = + [xinput::EventMask { deviceid: xinput::Device::ALL_MASTER.into(), mask: vec![mask] }]; + conn.xinput_xi_select_events(root, &masks) + .map_err(x11_error)? + .check() + .map_err(x11_error)?; + + let wake_window = conn.generate_id().map_err(x11_error)?; + conn.create_window( + 0, + wake_window, + root, + 0, + 0, + 1, + 1, + 0, + WindowClass::INPUT_ONLY, + 0, + &CreateWindowAux::new(), + ) + .map_err(x11_error)? + .check() + .map_err(x11_error)?; + + let keymap = Keymap::load(&conn)?; + let conn = Arc::new(conn); + let tracker = Arc::new(Mutex::new(Tracker::default())); + let stop = Arc::new(AtomicBool::new(false)); + { + let (conn, tracker, stop) = (conn.clone(), tracker.clone(), stop.clone()); + thread::Builder::new() + .name("tsc-hotkeys-x11".into()) + .spawn(move || event_loop(&conn, keymap, &tracker, &stop)) + .map_err(|e| Error::Backend(format!("X11: {e}")))?; + } + Ok(Self { conn, wake_window, tracker, stop }) + } + + fn tracker(&self) -> std::sync::MutexGuard<'_, Tracker> { + self.tracker.lock().unwrap_or_else(PoisonError::into_inner) + } + + pub fn register(&mut self, id: &str, hotkey: Hotkey) -> HotkeyEvents { + self.tracker().add(id, hotkey) + } + + pub fn unregister(&mut self, id: &str) { + self.tracker().remove(id); + } +} + +impl Drop for X11Backend { + fn drop(&mut self) { + self.stop.store(true, Ordering::Relaxed); + // With an empty event mask the event goes to the window's creator: us. + let wake = ClientMessageEvent::new(32, self.wake_window, AtomEnum::NONE, [0u32; 5]); + let _ = self.conn.send_event(false, self.wake_window, EventMask::NO_EVENT, wake); + let _ = self.conn.flush(); + } +} + +fn event_loop( + conn: &RustConnection, + mut keymap: Keymap, + tracker: &Mutex, + stop: &AtomicBool, +) { + let lock = || tracker.lock().unwrap_or_else(PoisonError::into_inner); + loop { + let event = match conn.wait_for_event() { + Ok(event) => event, + Err(error) => { + warn!(%error, "X11 hotkey connection lost"); + lock().release_all(); + return; + } + }; + if stop.load(Ordering::Relaxed) { + lock().release_all(); + return; + } + let (key, pressed) = match event { + Event::XinputRawKeyPress(e) => (keymap.key(e.detail), true), + Event::XinputRawKeyRelease(e) => (keymap.key(e.detail), false), + Event::XinputRawButtonPress(e) => (button_key(e.detail), true), + Event::XinputRawButtonRelease(e) => (button_key(e.detail), false), + Event::MappingNotify(_) => { + match Keymap::load(conn) { + Ok(k) => keymap = k, + Err(error) => debug!(%error, "keeping the old keymap"), + } + continue; + } + _ => continue, + }; + if let Some(key) = key { + lock().key(key, pressed); + } + } +} diff --git a/crates/tsc-platform/src/lib.rs b/crates/tsc-platform/src/lib.rs new file mode 100644 index 0000000..1edf2e4 --- /dev/null +++ b/crates/tsc-platform/src/lib.rs @@ -0,0 +1,34 @@ +//! Desktop integration. +//! +//! - [`hotkey`]: global push-to-talk hotkeys with press and release events +//! (xdg-desktop-portal on Wayland, XInput2 on X11, a keyboard hook on +//! Windows) +//! - [`notify`]: desktop notifications +//! - [`paths`]: data, config, cache and state directories + +pub mod hotkey; +pub mod notify; +pub mod paths; + +pub use hotkey::{BackendKind, Hotkey, HotkeyEvent, HotkeyEvents, HotkeyManager, Key, Modifiers}; +pub use notify::{Notification, notify}; + +/// Application id: desktop file, icon, portal registrations. A placeholder +/// until the product has a name. +pub const APP_ID: &str = "io.github.faumaray.TsClient"; +/// Name shown in notifications. A placeholder until the product has a name. +pub const APP_NAME: &str = "TS Client"; + +#[derive(Debug, thiserror::Error)] +pub enum Error { + #[error("invalid hotkey: {0}")] + InvalidHotkey(String), + #[error("not supported: {0}")] + Unsupported(String), + #[error("{0}")] + Backend(String), + #[error("notification: {0}")] + Notification(String), +} + +pub type Result = std::result::Result; diff --git a/crates/tsc-platform/src/notify.rs b/crates/tsc-platform/src/notify.rs new file mode 100644 index 0000000..15eec0b --- /dev/null +++ b/crates/tsc-platform/src/notify.rs @@ -0,0 +1,75 @@ +//! Desktop notifications through notify-rust: the freedesktop notification +//! service over D-Bus on Linux (works from Flatpak too), toasts on Windows. + +use std::time::Duration; + +use crate::{APP_NAME, Error, Result}; + +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct Notification { + pub title: String, + pub body: String, + /// How long it stays; `None` for the desktop's default. + pub timeout: Option, + /// Urgent (a poke, a private message): kept until dismissed where the + /// desktop supports that. + pub urgent: bool, +} + +impl Notification { + pub fn new(title: impl Into, body: impl Into) -> Self { + Self { title: title.into(), body: body.into(), ..Default::default() } + } +} + +#[cfg(any(windows, all(unix, not(target_os = "macos"))))] +fn native(n: &Notification) -> notify_rust::Notification { + let mut native = notify_rust::Notification::new(); + native.summary(&n.title).body(&n.body).appname(APP_NAME); + if let Some(timeout) = n.timeout { + native.timeout(notify_rust::Timeout::Milliseconds(timeout.as_millis() as u32)); + } + #[cfg(all(unix, not(target_os = "macos")))] + { + // The desktop file and icon are installed under the app id. + native.icon(crate::APP_ID).hint(notify_rust::Hint::DesktopEntry(crate::APP_ID.into())); + if n.urgent { + native.urgency(notify_rust::Urgency::Critical); + } + } + native +} + +/// Show a notification. Fails when there is no notification service (e.g. no +/// D-Bus session); callers usually just log that. +pub async fn notify(n: &Notification) -> Result<()> { + #[cfg(all(unix, not(target_os = "macos")))] + { + native(n).show_async().await.map_err(|e| Error::Notification(e.to_string()))?; + Ok(()) + } + #[cfg(windows)] + { + native(n).show().map_err(|e| Error::Notification(e.to_string()))?; + Ok(()) + } + #[cfg(not(any(windows, all(unix, not(target_os = "macos")))))] + { + let _ = (n, APP_NAME); + Err(Error::Unsupported("notifications".into())) + } +} + +// On Windows a toast would really show, so Linux only. +#[cfg(all(test, unix, not(target_os = "macos")))] +mod tests { + use super::*; + + /// Without a notification service this must fail, not hang or panic. + #[tokio::test] + async fn notify_returns() { + let n = Notification { urgent: true, ..Notification::new("Poke", "from a test") }; + let result = tokio::time::timeout(Duration::from_secs(10), notify(&n)).await; + assert!(result.is_ok(), "notify hung"); + } +} diff --git a/crates/tsc-platform/src/paths.rs b/crates/tsc-platform/src/paths.rs new file mode 100644 index 0000000..1ceac52 --- /dev/null +++ b/crates/tsc-platform/src/paths.rs @@ -0,0 +1,106 @@ +//! Where the app keeps its files. +//! +//! `/tsc` for the platform's data, config, cache and state bases (XDG +//! on Linux, where Flatpak points them into `~/.var/app//`; Known +//! Folders on Windows: `%APPDATA%` for data and config, `%LOCALAPPDATA%` for +//! cache and state). Each can be overridden with an environment variable, +//! e.g. for portable installs or tests. + +use std::path::{Path, PathBuf}; + +/// Directory name under each base; the desktop app's store already lives in +/// `/tsc`. +pub const APP_DIR: &str = "tsc"; + +fn resolve(var: &str, base: Option) -> PathBuf { + match std::env::var_os(var).filter(|v| !v.is_empty()) { + Some(dir) => dir.into(), + None => base.unwrap_or_else(|| PathBuf::from(".")).join(APP_DIR), + } +} + +/// Identities, bookmarks, chat history. `TSC_DATA_DIR` overrides. +pub fn data_dir() -> PathBuf { + resolve("TSC_DATA_DIR", dirs::data_dir()) +} + +/// Settings files. `TSC_CONFIG_DIR` overrides. +pub fn config_dir() -> PathBuf { + resolve("TSC_CONFIG_DIR", dirs::config_dir()) +} + +/// Disposable files (avatars, downloaded codecs). `TSC_CACHE_DIR` overrides. +pub fn cache_dir() -> PathBuf { + resolve("TSC_CACHE_DIR", dirs::cache_dir()) +} + +/// Logs and crash reports. `TSC_STATE_DIR` overrides. +pub fn state_dir() -> PathBuf { + resolve("TSC_STATE_DIR", dirs::state_dir().or_else(dirs::data_local_dir)) +} + +/// Create `dir` and its parents if needed. +pub fn ensure(dir: &Path) -> std::io::Result<&Path> { + std::fs::create_dir_all(dir)?; + Ok(dir) +} + +/// Running inside a Flatpak sandbox. +pub fn is_flatpak() -> bool { + cfg!(target_os = "linux") && Path::new("/.flatpak-info").exists() +} + +/// The display server of this session, as far as the environment tells. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum DisplayServer { + Wayland, + X11, + Windows, + MacOs, + Unknown, +} + +pub fn display_server() -> DisplayServer { + if cfg!(windows) { + DisplayServer::Windows + } else if cfg!(target_os = "macos") { + DisplayServer::MacOs + } else if std::env::var_os("WAYLAND_DISPLAY").is_some() + || std::env::var("XDG_SESSION_TYPE").is_ok_and(|t| t == "wayland") + { + DisplayServer::Wayland + } else if std::env::var_os("DISPLAY").is_some() { + DisplayServer::X11 + } else { + DisplayServer::Unknown + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn dirs_end_in_app_dir_or_override() { + for dir in [data_dir(), config_dir(), cache_dir(), state_dir()] { + assert!(dir.is_absolute() || dir.starts_with("."), "{}", dir.display()); + } + assert_eq!( + resolve("TSC_TEST_UNSET_VARIABLE", Some("/base".into())), + Path::new("/base/tsc") + ); + assert_eq!(resolve("TSC_TEST_UNSET_VARIABLE", None), Path::new("./tsc")); + // PATH is always set: stands in for an override. + let path = std::env::var_os("PATH").unwrap(); + assert_eq!(resolve("PATH", Some("/base".into())), PathBuf::from(path)); + } + + #[test] + fn ensure_creates() { + let dir = + std::env::temp_dir().join(format!("tsc-platform-{}", std::process::id())).join("a"); + assert_eq!(ensure(&dir).unwrap(), dir); + assert!(dir.is_dir()); + std::fs::remove_dir_all(dir.parent().unwrap()).unwrap(); + } +} diff --git a/crates/tsc-platform/tests/x11.rs b/crates/tsc-platform/tests/x11.rs new file mode 100644 index 0000000..15d12d9 --- /dev/null +++ b/crates/tsc-platform/tests/x11.rs @@ -0,0 +1,115 @@ +//! Global hotkeys against a real X server, typing through XTEST. +//! +//! Needs `TSC_X11_TEST_DISPLAY` naming a display to use (e.g. an Xvfb +//! started for the test, as CI does); skipped otherwise. + +#![cfg(all(unix, not(target_os = "macos"), feature = "x11"))] + +use std::time::Duration; + +use tokio::time::timeout; +use tsc_platform::{HotkeyEvent, HotkeyEvents, HotkeyManager}; +use x11rb::connection::Connection; +use x11rb::protocol::xproto::{ + BUTTON_PRESS_EVENT, BUTTON_RELEASE_EVENT, ConnectionExt as _, KEY_PRESS_EVENT, + KEY_RELEASE_EVENT, +}; +use x11rb::protocol::xtest::ConnectionExt as _; +use x11rb::rust_connection::RustConnection; +use x11rb::wrapper::ConnectionExt as _; + +struct Typist { + conn: RustConnection, + root: u32, +} + +impl Typist { + fn new(display: &str) -> Self { + let (conn, screen) = x11rb::connect(Some(display)).unwrap(); + let root = conn.setup().roots[screen].root; + Self { conn, root } + } + + fn keycode(&self, keysym: u32) -> u8 { + let setup = self.conn.setup(); + let (min, max) = (setup.min_keycode, setup.max_keycode); + let map = self.conn.get_keyboard_mapping(min, max - min + 1).unwrap().reply().unwrap(); + let per = map.keysyms_per_keycode as usize; + let index = map.keysyms.iter().position(|&s| s == keysym).expect("keysym in keymap"); + min + (index / per) as u8 + } + + fn fake(&self, kind: u8, detail: u8) { + self.conn.xtest_fake_input(kind, detail, 0, self.root, 0, 0, 0).unwrap(); + self.conn.sync().unwrap(); + } + + fn key(&self, keysym: u32, down: bool) { + let kind = if down { KEY_PRESS_EVENT } else { KEY_RELEASE_EVENT }; + self.fake(kind, self.keycode(keysym)); + } + + fn button(&self, button: u8, down: bool) { + self.fake(if down { BUTTON_PRESS_EVENT } else { BUTTON_RELEASE_EVENT }, button); + } +} + +async fn next(events: &mut HotkeyEvents) -> Option { + timeout(Duration::from_secs(2), events.recv()).await.ok().flatten() +} + +async fn nothing(events: &mut HotkeyEvents) -> bool { + timeout(Duration::from_millis(300), events.recv()).await.is_err() +} + +const XK_CONTROL_L: u32 = 0xffe3; +const XK_F9: u32 = 0xffc6; +const XK_A: u32 = 0x61; + +#[tokio::test] +async fn xinput2_press_and_release() { + let Ok(display) = std::env::var("TSC_X11_TEST_DISPLAY") else { + eprintln!("TSC_X11_TEST_DISPLAY not set, skipping"); + return; + }; + let mut manager = HotkeyManager::x11(&display).unwrap(); + let mut ptt = + manager.register("ptt", "Push to talk", "Ctrl+F9".parse().unwrap()).await.unwrap(); + let mut plain = manager.register("a", "Plain key", "A".parse().unwrap()).await.unwrap(); + let mut back = manager.register("back", "Mouse", "MouseBack".parse().unwrap()).await.unwrap(); + let typist = Typist::new(&display); + + // F9 alone does not trigger Ctrl+F9. + typist.key(XK_F9, true); + typist.key(XK_F9, false); + assert!(nothing(&mut ptt).await); + + typist.key(XK_CONTROL_L, true); + typist.key(XK_F9, true); + assert_eq!(next(&mut ptt).await, Some(HotkeyEvent::Pressed)); + // Still held while Ctrl goes up first. + typist.key(XK_CONTROL_L, false); + assert!(nothing(&mut ptt).await); + typist.key(XK_F9, false); + assert_eq!(next(&mut ptt).await, Some(HotkeyEvent::Released)); + + typist.key(XK_A, true); + typist.key(XK_A, false); + assert_eq!(next(&mut plain).await, Some(HotkeyEvent::Pressed)); + assert_eq!(next(&mut plain).await, Some(HotkeyEvent::Released)); + + typist.button(8, true); + typist.button(8, false); + assert_eq!(next(&mut back).await, Some(HotkeyEvent::Pressed)); + assert_eq!(next(&mut back).await, Some(HotkeyEvent::Released)); + + manager.unregister("a").await.unwrap(); + typist.key(XK_A, true); + typist.key(XK_A, false); + // The sender is gone: the channel ends. + assert_eq!(next(&mut plain).await, None); + + // Dropping the manager stops its thread and closes the channels. + drop(manager); + assert_eq!(next(&mut ptt).await, None); +} diff --git a/crates/tsc-stream/Cargo.toml b/crates/tsc-stream/Cargo.toml index 7574ae1..1464d8b 100644 --- a/crates/tsc-stream/Cargo.toml +++ b/crates/tsc-stream/Cargo.toml @@ -21,7 +21,7 @@ tsproto-packets = { path = "../proto/tsproto-packets" } [dev-dependencies] anyhow = "1" futures = "0.3" -tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "sync", "time"] } +tokio = { version = "1", features = ["io-util", "macros", "net", "process", "rt-multi-thread", "sync", "time"] } tracing-subscriber = { version = "0.3", features = ["env-filter"] } [lints] diff --git a/crates/tsc-stream/src/lib.rs b/crates/tsc-stream/src/lib.rs index fad7a83..d6fef35 100644 --- a/crates/tsc-stream/src/lib.rs +++ b/crates/tsc-stream/src/lib.rs @@ -4,14 +4,25 @@ //! Only TeamSpeak 6 servers support streams. Media flows peer to peer; the //! server only forwards `respondjoinstreamrequest` (the streamer's offer) and //! `streamsignaling` (answer and ICE candidates). +//! +//! [`Streams`] (module [`session`]) ties it together for one connection: the +//! streams in our channel, our own stream with a peer per viewer, and the +//! streams we watch. [`FrameSource`] is where a streamer's encoded frames come from. pub mod peer; pub mod proto; +pub mod session; pub mod signal; +pub mod source; pub mod stun; pub use peer::{MediaFrame, Peer, PeerConfig, PeerError, PeerEvent, VideoCodec}; pub use proto::{LeaveReason, StreamInfo, StreamKind, StreamNotification, StreamSetup}; +pub use session::{ + EndReason, Output, Request, SessionError, StreamDirectory, StreamEvent, StreamerEvent, + StreamerOptions, Streams, ViewerInfo, ViewerState, WatchEvent, WatchState, +}; pub use signal::{Signal, SignalError}; +pub use source::{EncodedFrame, FrameSource, SyntheticSource}; pub use str0m::format::Codec; pub use str0m::media::{Frequency, MediaKind, MediaTime}; diff --git a/crates/tsc-stream/src/peer.rs b/crates/tsc-stream/src/peer.rs index 90f6e95..32f50f5 100644 --- a/crates/tsc-stream/src/peer.rs +++ b/crates/tsc-stream/src/peer.rs @@ -9,6 +9,7 @@ use std::collections::HashMap; use std::hash::{BuildHasher, RandomState}; use std::net::{IpAddr, Ipv4Addr, SocketAddr}; use std::sync::Arc; +use std::task::{Context, Poll}; use std::time::{Duration, Instant}; use str0m::change::{SdpAnswer, SdpOffer, SdpPendingOffer}; @@ -32,6 +33,8 @@ pub enum VideoCodec { } impl VideoCodec { + pub const ALL: [Self; 4] = [Self::Vp8, Self::Vp9, Self::H264, Self::Av1]; + pub fn from_codec(c: Codec) -> Option { match c { Codec::Vp8 => Some(Self::Vp8), @@ -41,6 +44,20 @@ impl VideoCodec { _ => None, } } + + /// From an SDP encoding name (`a=rtpmap: VP8/90000`). + pub fn from_sdp_name(name: &str) -> Option { + Self::ALL.into_iter().find(|c| c.sdp_name().eq_ignore_ascii_case(name)) + } + + pub fn sdp_name(self) -> &'static str { + match self { + Self::Vp8 => "VP8", + Self::Vp9 => "VP9", + Self::H264 => "H264", + Self::Av1 => "AV1", + } + } } #[derive(Clone, Debug)] @@ -49,8 +66,12 @@ pub struct PeerConfig { pub hosts: Vec, /// STUN servers (`host:port`) for a server-reflexive candidate. pub stun_servers: Vec, - /// Video codecs, used for the streamer's offer; a viewer accepts all it knows. + /// Video codecs a streamer offers, in order of preference. Frames are sent + /// with the codec the viewer picks, so offer only what the encoder produces. pub video_codecs: Vec, + /// Video codecs a viewer accepts (what it can decode). The answer keeps + /// the order of the streamer's offer, so the streamer's preference wins. + pub accept_video_codecs: Vec, pub video: bool, pub audio: bool, } @@ -60,7 +81,8 @@ impl Default for PeerConfig { Self { hosts: Vec::new(), stun_servers: stun::TEAMSPEAK_STUN.iter().map(|s| (*s).to_owned()).collect(), - video_codecs: vec![VideoCodec::Vp8, VideoCodec::H264], + video_codecs: vec![VideoCodec::Vp8], + accept_video_codecs: VideoCodec::ALL.to_vec(), video: true, audio: true, } @@ -100,8 +122,9 @@ pub enum PeerEvent { /// ICE and DTLS are up; media can flow. Connected, /// A candidate found after the SDP was sent (server reflexive), as an SDP - /// `candidate:` line for [`crate::Signal::IceCandidate`]. - LocalCandidate(String), + /// `candidate:` line for [`crate::Signal::IceCandidate`], with the mid of + /// the first (bundled) media line. + LocalCandidate { candidate: String, mid: Option }, /// A received frame (depacketized). Media(MediaFrame), /// The viewer asks for a keyframe. @@ -140,7 +163,7 @@ impl Peer { /// Streamer side: create a connection that sends our media; returns the SDP /// offer for `respondjoinstreamrequest`. pub async fn offer(config: &PeerConfig, stream_id: &str) -> Result<(Self, String), PeerError> { - let mut rtc = build_rtc(config, true); + let mut rtc = build_rtc(config, &config.video_codecs); let net = Net::bind(config, &mut rtc).await?; let mut api = rtc.sdp_api(); let msid = Some(stream_id.to_owned()); @@ -161,8 +184,18 @@ impl Peer { /// Viewer side: accept the streamer's offer; returns our SDP answer. pub async fn answer(config: &PeerConfig, offer: &str) -> Result<(Self, String), PeerError> { + // Our codecs in the order of the offer, then the rest. + let mut codecs: Vec<_> = offered_video_codecs(offer) + .into_iter() + .filter(|c| config.accept_video_codecs.contains(c)) + .collect(); + for c in &config.accept_video_codecs { + if !codecs.contains(c) { + codecs.push(*c); + } + } let offer = SdpOffer::from_sdp_string(offer).map_err(|e| PeerError::Sdp(e.to_string()))?; - let mut rtc = build_rtc(config, false); + let mut rtc = build_rtc(config, &codecs); let net = Net::bind(config, &mut rtc).await?; let answer = rtc.sdp_api().accept_offer(offer)?; Ok((Self::spawn(rtc, net, config, None, Vec::new()), answer.to_sdp_string())) @@ -225,6 +258,11 @@ impl Peer { pub fn try_next_event(&mut self) -> Option { self.events.try_recv().ok() } + + /// Poll for the next event, for driving many peers from one task. + pub fn poll_event(&mut self, cx: &mut Context<'_>) -> Poll> { + self.events.poll_recv(cx) + } } impl Drop for Peer { @@ -233,24 +271,66 @@ impl Drop for Peer { } } -fn build_rtc(config: &PeerConfig, offering: bool) -> Rtc { - let mut rtc_config = - RtcConfig::new().set_crypto_provider(Arc::new(str0m::crypto::from_feature_flags())); - if offering { - // Offer only the codecs we can encode, in our order of preference. - rtc_config = rtc_config.clear_codecs().enable_opus(config.audio); - for codec in &config.video_codecs { - rtc_config = match codec { - VideoCodec::Vp8 => rtc_config.enable_vp8(true), - VideoCodec::Vp9 => rtc_config.enable_vp9(true), - VideoCodec::H264 => rtc_config.enable_h264(true), - VideoCodec::Av1 => rtc_config.enable_av1(true), - }; - } +/// H.264 Constrained High, level 3.1: reportedly the only H.264 profile the +/// TeamSpeak client decodes; str0m's defaults lack it. +const H264_CONSTRAINED_HIGH: u32 = 0x640c1f; + +/// An RTC with Opus and `video` codecs, in this order of preference. +fn build_rtc(config: &PeerConfig, video: &[VideoCodec]) -> Rtc { + let mut rtc_config = RtcConfig::new() + .set_crypto_provider(Arc::new(str0m::crypto::from_feature_flags())) + .clear_codecs() + .enable_opus(config.audio); + for codec in video { + rtc_config = match codec { + VideoCodec::Vp8 => rtc_config.enable_vp8(true), + VideoCodec::Vp9 => rtc_config.enable_vp9(true), + VideoCodec::H264 => { + let mut c = rtc_config.enable_h264(true); + c.codec_config().add_h264( + 112.into(), + Some(113.into()), + true, + H264_CONSTRAINED_HIGH, + ); + c + } + VideoCodec::Av1 => rtc_config.enable_av1(true), + }; } rtc_config.build(Instant::now()) } +/// The video codecs of the first video media line of `sdp`, in offered order. +fn offered_video_codecs(sdp: &str) -> Vec { + let mut pts: Vec<&str> = Vec::new(); + let mut names: Vec<(&str, VideoCodec)> = Vec::new(); + let mut in_video = false; + for line in sdp.lines().map(str::trim) { + if let Some(media) = line.strip_prefix("m=") { + in_video = pts.is_empty() && media.starts_with("video "); + if in_video { + pts = media.split_whitespace().skip(3).collect(); + } + } else if in_video + && let Some((pt, encoding)) = + line.strip_prefix("a=rtpmap:").and_then(|r| r.split_once(' ')) + && let Some(codec) = encoding.split('/').next().and_then(VideoCodec::from_sdp_name) + { + names.push((pt, codec)); + } + } + let mut codecs = Vec::new(); + for pt in pts { + if let Some((_, codec)) = names.iter().find(|(p, _)| *p == pt) + && !codecs.contains(codec) + { + codecs.push(*codec); + } + } + codecs +} + /// The primary local IPv4 address (the one used for the default route). fn primary_ipv4() -> Option { let socket = std::net::UdpSocket::bind("0.0.0.0:0").ok()?; @@ -420,9 +500,10 @@ impl Task { } match Candidate::server_reflexive(mapped, pending.base, "udp") { Ok(c) => { - let line = c.to_sdp_string(); + let candidate = c.to_sdp_string(); + let mid = self.mids.first().map(|(mid, _)| mid.to_string()); if self.rtc.add_local_candidate(c).is_some() { - let _ = self.events.send(PeerEvent::LocalCandidate(line)); + let _ = self.events.send(PeerEvent::LocalCandidate { candidate, mid }); } } Err(e) => debug!("bad reflexive candidate {mapped}: {e}"), @@ -583,3 +664,45 @@ impl Task { Some((mid, pt)) } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn offered_codec_order() { + let sdp = "v=0\r\n\ + m=audio 9 UDP/TLS/RTP/SAVPF 111\r\n\ + a=rtpmap:111 opus/48000/2\r\n\ + m=video 9 UDP/TLS/RTP/SAVPF 98 99 96 97 45 102\r\n\ + a=rtpmap:96 VP8/90000\r\n\ + a=rtpmap:97 rtx/90000\r\n\ + a=rtpmap:98 VP9/90000\r\n\ + a=rtpmap:99 rtx/90000\r\n\ + a=rtpmap:45 AV1/90000\r\n\ + a=rtpmap:102 H264/90000\r\n\ + m=video 9 UDP/TLS/RTP/SAVPF 96\r\n\ + a=rtpmap:96 H264/90000\r\n"; + assert_eq!( + offered_video_codecs(sdp), + [VideoCodec::Vp9, VideoCodec::Vp8, VideoCodec::Av1, VideoCodec::H264] + ); + assert!(offered_video_codecs("v=0\r\n").is_empty()); + } + + #[tokio::test] + async fn answer_follows_offer_order() { + let streamer = PeerConfig { + video_codecs: vec![VideoCodec::H264, VideoCodec::Vp8], + ..PeerConfig::loopback() + }; + let (_peer, offer) = Peer::offer(&streamer, "s").await.unwrap(); + assert!(offer.contains("profile-level-id=640c1f"), "{offer}"); + let (_peer, answer) = Peer::answer(&PeerConfig::loopback(), &offer).await.unwrap(); + assert_eq!(offered_video_codecs(&answer)[0], VideoCodec::H264, "{answer}"); + let vp8_only = + PeerConfig { accept_video_codecs: vec![VideoCodec::Vp8], ..PeerConfig::loopback() }; + let (_peer, answer) = Peer::answer(&vp8_only, &offer).await.unwrap(); + assert_eq!(offered_video_codecs(&answer), [VideoCodec::Vp8], "{answer}"); + } +} diff --git a/crates/tsc-stream/src/session.rs b/crates/tsc-stream/src/session.rs new file mode 100644 index 0000000..9f2a1e1 --- /dev/null +++ b/crates/tsc-stream/src/session.rs @@ -0,0 +1,1539 @@ +//! Stream sessions: the streamer's and the viewer's side of TeamSpeak 6 +//! streams as state machines, and the list of streams in our channel. +//! +//! The sessions do no connection IO. They are fed the stream notifications of +//! one server connection and the app's decisions, and queue [`Output`]s: a +//! [`Request`] to send on the connection or a [`StreamEvent`] for the app. +//! They own the WebRTC [`Peer`]s (one per viewer on the streamer's side, one +//! per watched stream on the viewer's side). [`Streams::wait_peers`] handles +//! peer events and is cancel safe, so it can sit in a `select!` next to the +//! connection: +//! +//! ```ignore +//! loop { +//! tokio::select! { +//! msg = messages.next() => { +//! for n in StreamNotification::from_message(&msg) { +//! streams.handle_notification(n).await; +//! } +//! } +//! () = streams.wait_peers() => {} +//! } +//! while let Some(output) = streams.poll_output() { +//! // Output::Request: send `request.to_command()`, report failures +//! // with `streams.request_failed`. Output::Event: tell the app. +//! } +//! } +//! ``` + +use std::collections::{BTreeMap, BTreeSet, VecDeque}; +use std::sync::Arc; +use std::task::{Context, Poll}; +use std::time::{Duration, Instant}; + +use str0m::media::{MediaKind, MediaTime}; +use tracing::{debug, warn}; +use tsclientlib::ClientId; +use tsproto_packets::packets::OutCommand; + +use crate::peer::{MediaFrame, Peer, PeerConfig, PeerEvent}; +use crate::proto::{self, LeaveReason, StreamInfo, StreamNotification, StreamSetup}; +use crate::signal::Signal; +use crate::source::EncodedFrame; + +/// Keyframe requests closer together than this are merged into one event. +const KEYFRAME_INTERVAL: Duration = Duration::from_millis(250); +/// How often a viewer asks for a new offer after its connection failed. +const MAX_RECONNECTS: u32 = 3; +/// Peer events handled per peer and poll, so one busy peer cannot starve the rest. +const EVENTS_PER_POLL: usize = 64; + +/// A command for the server. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Request { + /// `setupstream`: start our stream. + Setup(StreamSetup), + /// `stopstream`: end our stream. + Stop { id: String }, + /// `joinstreamrequest ... is_remove=0`: ask to watch. + Join { id: String, streamer: ClientId, message: String }, + /// `joinstreamrequest ... is_remove=1`: withdraw the request or stop watching. + Leave { id: String, streamer: ClientId }, + /// `respondjoinstreamrequest`: accept a viewer with our offer, or deny. + Respond { id: String, viewer: ClientId, offer: Option, accept: bool }, + /// `streamsignaling` + Signal { id: String, peer: ClientId, signal: Signal }, + /// `removeclientfromstream` + RemoveViewer { id: String, viewer: ClientId, reason: LeaveReason }, +} + +impl Request { + pub fn to_command(&self) -> OutCommand { + match self { + Self::Setup(setup) => proto::setup(setup), + Self::Stop { id } => proto::stop(id), + Self::Join { id, streamer, message } => { + proto::join_request(id, *streamer, message, false) + } + Self::Leave { id, streamer } => proto::join_request(id, *streamer, "", true), + Self::Respond { id, viewer, offer, accept } => { + proto::respond(id, *viewer, offer.as_deref(), *accept) + } + Self::Signal { id, peer, signal } => proto::signaling(id, *peer, &signal.to_json()), + Self::RemoveViewer { id, viewer, reason } => proto::remove_viewer(id, *viewer, *reason), + } + } +} + +/// Why a stream ended for us. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum EndReason { + /// We stopped streaming or watching. + Local, + /// The streamer denied our join request. + Denied, + /// The stream was stopped (or its streamer disconnected). + Stopped, + /// The streamer or the server ended our viewing session. + Removed(Option), + /// A command failed or no connection could be established. + Failed(String), +} + +/// A viewer of our stream, as the streamer sees it. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ViewerState { + /// Asked to watch, waiting for our decision. + Requested, + /// Offer sent; waiting for the answer and the connection. + Connecting, + Connected, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ViewerInfo { + pub client: ClientId, + pub state: ViewerState, + /// The message of the join request. + pub message: String, +} + +/// What happens to our own stream. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum StreamerEvent { + /// The server confirmed `setupstream`: the stream is live under `id`. + Live { + id: String, + }, + /// A viewer asks to watch (without auto-accept); answer with [`Streams::respond`]. + Request { + viewer: ClientId, + message: String, + }, + /// The viewers or their states changed (full list). + Viewers(Vec), + /// A viewer connected or lost a frame: the encoder should send a keyframe. + KeyframeRequest, + Ended(EndReason), +} + +/// What happens to a stream we watch. +#[derive(Clone, Debug)] +pub enum WatchEvent { + /// The streamer accepted our join request; connecting. + Accepted, + Connected, + /// An encoded video or audio frame. + Frame(MediaFrame), + Ended(EndReason), +} + +#[derive(Clone, Debug)] +pub enum StreamEvent { + /// The streams in our channel changed (full list). + Streams(Vec), + /// Our own stream. + Streamer(StreamerEvent), + /// A stream we watch. + Watch { id: String, event: WatchEvent }, +} + +#[derive(Clone, Debug)] +pub enum Output { + /// Send `request.to_command()` on the connection. + Request(Request), + Event(StreamEvent), +} + +/// Queue of [`Output`]s the sessions append to. +#[derive(Debug, Default)] +pub struct Outbox(VecDeque); + +impl Outbox { + pub fn request(&mut self, request: Request) { + self.0.push_back(Output::Request(request)); + } + + pub fn event(&mut self, event: StreamEvent) { + self.0.push_back(Output::Event(event)); + } + + pub fn pop(&mut self) -> Option { + self.0.pop_front() + } + + pub fn is_empty(&self) -> bool { + self.0.is_empty() + } +} + +/// A call the sessions cannot carry out. +#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)] +pub enum SessionError { + #[error("already streaming")] + AlreadyStreaming, + #[error("not streaming")] + NotStreaming, + #[error("the stream is not live yet")] + NotLive, + #[error("client {0} has not asked to watch")] + NoRequest(u16), + #[error("client {0} is not a viewer")] + UnknownViewer(u16), + #[error("unknown stream {0}")] + UnknownStream(String), + #[error("already watching stream {0}")] + AlreadyWatching(String), + #[error("not watching stream {0}")] + NotWatching(String), + #[error("cannot watch our own stream")] + OwnStream, +} + +/// The streams in our channel, from `notifystreamstarted`/`notifystreaminfo`/ +/// `notifystreamstopped` and the clients' `client_is_streaming`. +#[derive(Clone, Debug, Default)] +pub struct StreamDirectory { + streams: BTreeMap, + /// Clients with `client_is_streaming=1`. + streaming: BTreeSet, +} + +impl StreamDirectory { + /// Apply a notification; `true` if the list of streams changed. + pub fn apply(&mut self, n: &StreamNotification) -> bool { + match n { + StreamNotification::Started { info, .. } | StreamNotification::Info(info) => { + self.streaming.insert(info.streamer.0); + self.streams.insert(info.id.clone(), info.clone()).as_ref() != Some(info) + } + StreamNotification::Stopped { id, .. } => self.streams.remove(id).is_some(), + _ => false, + } + } + + /// `client_is_streaming` of a client changed. When it stops, its streams + /// are dropped; returns `true` if the list of streams changed. + pub fn set_streaming(&mut self, client: ClientId, streaming: bool) -> bool { + if streaming { + self.streaming.insert(client.0); + false + } else { + self.streaming.remove(&client.0); + self.retain_streamers(|c| c != client) + } + } + + /// Drop the streams of streamers `keep` rejects (e.g. clients that left). + pub fn retain_streamers(&mut self, mut keep: impl FnMut(ClientId) -> bool) -> bool { + let before = self.streams.len(); + self.streams.retain(|_, s| keep(s.streamer)); + self.streaming.retain(|c| keep(ClientId(*c))); + self.streams.len() != before + } + + pub fn get(&self, id: &str) -> Option<&StreamInfo> { + self.streams.get(id) + } + + pub fn by_streamer(&self, client: ClientId) -> Option<&StreamInfo> { + self.streams.values().find(|s| s.streamer == client) + } + + pub fn iter(&self) -> impl Iterator { + self.streams.values() + } + + pub fn to_vec(&self) -> Vec { + self.streams.values().cloned().collect() + } + + /// Clients that stream, but whose stream id we have not been told. + pub fn unannounced_streamers(&self) -> impl Iterator + '_ { + self.streaming + .iter() + .filter(|c| !self.streams.values().any(|s| s.streamer.0 == **c)) + .map(|c| ClientId(*c)) + } +} + +/// Options for our own stream. +#[derive(Clone, Debug, Default)] +pub struct StreamerOptions { + pub setup: StreamSetup, + /// Accept every join request. Otherwise each one is reported as + /// [`StreamerEvent::Request`] and answered with [`Streams::respond`]. + pub auto_accept: bool, +} + +struct ViewerSlot { + state: ViewerState, + message: String, + /// `None` while the viewer waits for our decision or after its connection closed. + peer: Option, +} + +/// Our own stream: `setupstream`, one peer connection per accepted viewer. +pub struct StreamerSession { + own: ClientId, + options: StreamerOptions, + config: PeerConfig, + id: Option, + ended: bool, + /// Stopped before the server confirmed the setup: stop once it does. + stop_when_live: bool, + viewers: BTreeMap, + last_keyframe_request: Option, +} + +impl StreamerSession { + /// Start streaming: queues `setupstream`. + pub fn start( + own: ClientId, + options: StreamerOptions, + config: PeerConfig, + out: &mut Outbox, + ) -> Self { + out.request(Request::Setup(options.setup.clone())); + Self { + own, + options, + config, + id: None, + ended: false, + stop_when_live: false, + viewers: BTreeMap::new(), + last_keyframe_request: None, + } + } + + /// The stream id, once the server confirmed the setup. + pub fn id(&self) -> Option<&str> { + self.id.as_deref() + } + + pub fn is_ended(&self) -> bool { + self.ended + } + + /// Ended and nothing left to send. + fn is_finished(&self) -> bool { + self.ended && !self.stop_when_live + } + + pub fn viewers(&self) -> Vec { + self.viewers + .iter() + .map(|(clid, v)| ViewerInfo { + client: ClientId(*clid), + state: v.state, + message: v.message.clone(), + }) + .collect() + } + + /// Whether `n` is about this stream. + pub fn wants(&self, n: &StreamNotification) -> bool { + match (&self.id, n) { + (None, StreamNotification::Started { info, .. }) => info.streamer == self.own, + // Responses to join requests are for viewers. + (Some(_), StreamNotification::JoinResponse { .. }) => false, + (Some(id), n) => n.stream_id() == id, + (None, _) => false, + } + } + + pub async fn handle(&mut self, n: &StreamNotification, out: &mut Outbox) { + match n { + StreamNotification::Started { info, .. } if self.id.is_none() => { + self.id = Some(info.id.clone()); + if self.stop_when_live { + self.stop_when_live = false; + out.request(Request::Stop { id: info.id.clone() }); + } else if !self.ended { + out.event(StreamEvent::Streamer(StreamerEvent::Live { id: info.id.clone() })); + } + } + _ if self.ended => {} + StreamNotification::Stopped { .. } => self.end(EndReason::Stopped, out), + StreamNotification::JoinRequest { viewer, message, remove: false, .. } => { + let slot = ViewerSlot { + state: ViewerState::Requested, + message: message.clone(), + peer: None, + }; + self.viewers.insert(viewer.0, slot); + if self.options.auto_accept { + self.offer(*viewer, false, out).await; + } else { + out.event(StreamEvent::Streamer(StreamerEvent::Request { + viewer: *viewer, + message: message.clone(), + })); + self.emit_viewers(out); + } + } + StreamNotification::JoinRequest { viewer, remove: true, .. } + | StreamNotification::ViewerLeft { viewer, .. } => { + if self.viewers.remove(&viewer.0).is_some() { + self.emit_viewers(out); + } + } + StreamNotification::Signaling { peer, json, .. } => { + self.signal(*peer, json, out).await; + } + StreamNotification::ViewerJoined { viewer, .. } => { + debug!(viewer = viewer.0, "viewer joined the stream"); + } + _ => {} + } + } + + async fn signal(&mut self, viewer: ClientId, json: &str, out: &mut Outbox) { + let signal = match Signal::parse(json) { + Ok(s) => s, + Err(e) => { + warn!(viewer = viewer.0, "bad signalling message: {e}"); + return; + } + }; + let Some(slot) = self.viewers.get(&viewer.0) else { + debug!(viewer = viewer.0, "signal from a client that is not a viewer"); + return; + }; + match signal { + Signal::Answer { sdp } => { + let Some(peer) = &slot.peer else { return }; + if let Err(e) = peer.accept_answer(&sdp).await { + warn!(viewer = viewer.0, "cannot apply the viewer's answer: {e}"); + self.remove(viewer, LeaveReason::Failed, out); + } + } + Signal::IceCandidate { candidate, .. } => { + if let Some(peer) = &slot.peer { + peer.add_remote_candidate(&candidate); + } + } + Signal::Reconnect => { + if slot.state != ViewerState::Requested { + self.offer(viewer, true, out).await; + } + } + other => debug!(viewer = viewer.0, "ignoring signal {other:?}"), + } + } + + /// Create a peer for `viewer` and send our offer: in `respondjoinstreamrequest`, + /// or as `reconnectOffer` for a viewer that lost its connection. + async fn offer(&mut self, viewer: ClientId, reconnect: bool, out: &mut Outbox) { + let Some(id) = self.id.clone() else { return }; + match Peer::offer(&self.config, &id).await { + Ok((peer, sdp)) => { + if let Some(slot) = self.viewers.get_mut(&viewer.0) { + slot.peer = Some(peer); + slot.state = ViewerState::Connecting; + } + out.request(if reconnect { + Request::Signal { id, peer: viewer, signal: Signal::Offer { sdp, reconnect } } + } else { + Request::Respond { id, viewer, offer: Some(sdp), accept: true } + }); + } + Err(e) => { + warn!(viewer = viewer.0, "cannot create a peer connection: {e}"); + self.viewers.remove(&viewer.0); + out.request(if reconnect { + Request::RemoveViewer { id, viewer, reason: LeaveReason::Failed } + } else { + Request::Respond { id, viewer, offer: None, accept: false } + }); + } + } + self.emit_viewers(out); + } + + /// Accept or deny a pending join request. + pub async fn respond( + &mut self, + viewer: ClientId, + accept: bool, + out: &mut Outbox, + ) -> Result<(), SessionError> { + let id = self.id.clone().ok_or(SessionError::NotLive)?; + match self.viewers.get(&viewer.0) { + Some(slot) if slot.state == ViewerState::Requested => {} + _ => return Err(SessionError::NoRequest(viewer.0)), + } + if accept { + self.offer(viewer, false, out).await; + } else { + self.viewers.remove(&viewer.0); + out.request(Request::Respond { id, viewer, offer: None, accept: false }); + self.emit_viewers(out); + } + Ok(()) + } + + /// End a viewer's session (`removeclientfromstream` with reason kicked). + pub fn kick(&mut self, viewer: ClientId, out: &mut Outbox) -> Result<(), SessionError> { + if self.id.is_none() { + return Err(SessionError::NotLive); + } + if !self.viewers.contains_key(&viewer.0) { + return Err(SessionError::UnknownViewer(viewer.0)); + } + self.remove(viewer, LeaveReason::Kicked, out); + Ok(()) + } + + fn remove(&mut self, viewer: ClientId, reason: LeaveReason, out: &mut Outbox) { + self.viewers.remove(&viewer.0); + if let Some(id) = &self.id { + out.request(Request::RemoveViewer { id: id.clone(), viewer, reason }); + } + self.emit_viewers(out); + } + + /// End the stream (`stopstream`). + pub fn stop(&mut self, out: &mut Outbox) { + if self.ended { + return; + } + match &self.id { + Some(id) => out.request(Request::Stop { id: id.clone() }), + None => self.stop_when_live = true, + } + self.end(EndReason::Local, out); + } + + fn end(&mut self, reason: EndReason, out: &mut Outbox) { + self.ended = true; + self.viewers.clear(); + out.event(StreamEvent::Streamer(StreamerEvent::Ended(reason))); + } + + /// Send an encoded frame to every connected viewer. + pub fn write(&self, kind: MediaKind, time: MediaTime, data: Arc<[u8]>) { + for slot in self.viewers.values() { + if let (ViewerState::Connected, Some(peer)) = (slot.state, &slot.peer) { + peer.write(kind, time, data.clone()); + } + } + } + + /// Whether any viewer is connected (frames are dropped otherwise). + pub fn has_connected_viewers(&self) -> bool { + self.viewers.values().any(|v| v.state == ViewerState::Connected) + } + + /// A command of this session failed on the server. + pub fn request_failed(&mut self, request: &Request, error: &str, out: &mut Outbox) { + match request { + Request::Setup(_) if self.id.is_none() => { + self.stop_when_live = false; + if !self.ended { + self.end(EndReason::Failed(format!("setupstream: {error}")), out); + } + } + Request::Respond { viewer, accept: true, .. } => { + if self.viewers.remove(&viewer.0).is_some() { + self.emit_viewers(out); + } + } + other => debug!(?other, "stream command failed: {error}"), + } + } + + /// Handle ready peer events; `Pending` if there were none. + pub fn poll_peers(&mut self, cx: &mut Context<'_>, out: &mut Outbox) -> Poll<()> { + let mut events = Vec::new(); + for (clid, slot) in &mut self.viewers { + let Some(peer) = &mut slot.peer else { continue }; + for _ in 0..EVENTS_PER_POLL { + match peer.poll_event(cx) { + Poll::Ready(Some(e)) => events.push((ClientId(*clid), e)), + Poll::Ready(None) => { + events.push((ClientId(*clid), PeerEvent::Closed)); + break; + } + Poll::Pending => break, + } + } + } + if events.is_empty() { + return Poll::Pending; + } + for (viewer, event) in events { + self.peer_event(viewer, event, out); + } + Poll::Ready(()) + } + + fn peer_event(&mut self, viewer: ClientId, event: PeerEvent, out: &mut Outbox) { + let Some(id) = self.id.clone() else { return }; + let Some(slot) = self.viewers.get_mut(&viewer.0) else { return }; + match event { + PeerEvent::Connected => { + slot.state = ViewerState::Connected; + self.emit_viewers(out); + self.keyframe_request(out); + } + PeerEvent::LocalCandidate { candidate, mid } => out.request(Request::Signal { + id, + peer: viewer, + signal: Signal::IceCandidate { candidate, mid, mline_index: Some(0) }, + }), + PeerEvent::KeyframeRequest => self.keyframe_request(out), + PeerEvent::Media(_) => {} + PeerEvent::Closed => { + // The viewer may ask for a new offer (`reconnect`); it stays + // until it leaves. + if slot.peer.take().is_some() { + debug!(viewer = viewer.0, "viewer connection closed"); + slot.state = ViewerState::Connecting; + self.emit_viewers(out); + } + } + } + } + + fn keyframe_request(&mut self, out: &mut Outbox) { + let now = Instant::now(); + if self.last_keyframe_request.is_some_and(|t| now.duration_since(t) < KEYFRAME_INTERVAL) { + return; + } + self.last_keyframe_request = Some(now); + out.event(StreamEvent::Streamer(StreamerEvent::KeyframeRequest)); + } + + fn emit_viewers(&self, out: &mut Outbox) { + out.event(StreamEvent::Streamer(StreamerEvent::Viewers(self.viewers()))); + } +} + +/// State of a stream we watch. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum WatchState { + /// Join request sent. + Requested, + /// Accepted; connecting to the streamer. + Connecting, + Connected, + Ended, +} + +/// Watching one stream: `joinstreamrequest`, answer the streamer's offer, receive media. +pub struct ViewerSession { + id: String, + streamer: ClientId, + own: ClientId, + config: PeerConfig, + state: WatchState, + peer: Option, + reconnects: u32, +} + +impl ViewerSession { + /// Ask `streamer` to let us watch stream `id`: queues `joinstreamrequest`. + pub fn join( + own: ClientId, + id: &str, + streamer: ClientId, + message: &str, + config: PeerConfig, + out: &mut Outbox, + ) -> Self { + out.request(Request::Join { id: id.to_owned(), streamer, message: message.to_owned() }); + Self { + id: id.to_owned(), + streamer, + own, + config, + state: WatchState::Requested, + peer: None, + reconnects: 0, + } + } + + pub fn id(&self) -> &str { + &self.id + } + + pub fn streamer(&self) -> ClientId { + self.streamer + } + + pub fn state(&self) -> WatchState { + self.state + } + + /// Whether `n` is for this viewing session. + pub fn wants(&self, n: &StreamNotification) -> bool { + if n.stream_id() != self.id { + return false; + } + match n { + StreamNotification::JoinRequest { .. } => false, + StreamNotification::Signaling { peer, .. } => *peer == self.streamer, + StreamNotification::ViewerJoined { viewer, .. } + | StreamNotification::ViewerLeft { viewer, .. } => *viewer == self.own, + _ => true, + } + } + + pub async fn handle(&mut self, n: &StreamNotification, out: &mut Outbox) { + if self.state == WatchState::Ended { + return; + } + match n { + StreamNotification::JoinResponse { accepted: false, .. } => { + self.end(EndReason::Denied, out); + } + StreamNotification::JoinResponse { accepted: true, offer, .. } => { + self.state = WatchState::Connecting; + self.event(WatchEvent::Accepted, out); + // Without an offer in the response, it follows as an `offer` signal. + if let Some(offer) = offer { + self.answer(offer, out).await; + } + } + StreamNotification::Signaling { json, .. } => match Signal::parse(json) { + Ok(Signal::Offer { sdp, .. }) => self.answer(&sdp, out).await, + Ok(Signal::IceCandidate { candidate, .. }) => { + if let Some(peer) = &self.peer { + peer.add_remote_candidate(&candidate); + } + } + Ok(other) => debug!(stream = self.id, "ignoring signal {other:?}"), + Err(e) => warn!(stream = self.id, "bad signalling message: {e}"), + }, + StreamNotification::Stopped { .. } => self.end(EndReason::Stopped, out), + StreamNotification::ViewerLeft { reason, .. } => { + self.end(EndReason::Removed(*reason), out); + } + _ => {} + } + } + + /// Answer an offer (the first one or a `reconnectOffer`) with a new peer. + async fn answer(&mut self, offer: &str, out: &mut Outbox) { + match Peer::answer(&self.config, offer).await { + Ok((peer, sdp)) => { + self.peer = Some(peer); + self.state = WatchState::Connecting; + self.signal(Signal::Answer { sdp }, out); + } + Err(e) => self.fail(format!("cannot answer the streamer's offer: {e}"), out), + } + } + + fn signal(&self, signal: Signal, out: &mut Outbox) { + out.request(Request::Signal { id: self.id.clone(), peer: self.streamer, signal }); + } + + /// Stop watching (or withdraw the request). + pub fn leave(&mut self, out: &mut Outbox) { + if self.state == WatchState::Ended { + return; + } + out.request(Request::Leave { id: self.id.clone(), streamer: self.streamer }); + self.end(EndReason::Local, out); + } + + /// Ask the streamer for a keyframe (RTCP PLI). + pub fn request_keyframe(&self) { + if let Some(peer) = &self.peer { + peer.request_keyframe(); + } + } + + /// Drop the connection and ask the streamer for a new offer (`reconnect`). + pub fn reconnect(&mut self, out: &mut Outbox) { + if matches!(self.state, WatchState::Connecting | WatchState::Connected) { + self.peer = None; + self.state = WatchState::Connecting; + self.signal(Signal::Reconnect, out); + } + } + + fn fail(&mut self, error: String, out: &mut Outbox) { + warn!(stream = self.id, "{error}"); + out.request(Request::Leave { id: self.id.clone(), streamer: self.streamer }); + self.end(EndReason::Failed(error), out); + } + + fn end(&mut self, reason: EndReason, out: &mut Outbox) { + self.state = WatchState::Ended; + self.peer = None; + self.event(WatchEvent::Ended(reason), out); + } + + fn event(&self, event: WatchEvent, out: &mut Outbox) { + out.event(StreamEvent::Watch { id: self.id.clone(), event }); + } + + /// A command of this session failed on the server. + pub fn request_failed(&mut self, request: &Request, error: &str, out: &mut Outbox) { + match request { + Request::Join { .. } if self.state != WatchState::Ended => { + self.end(EndReason::Failed(format!("joinstreamrequest: {error}")), out); + } + other => debug!(?other, "stream command failed: {error}"), + } + } + + /// Handle ready peer events; `Pending` if there were none. + pub fn poll_peer(&mut self, cx: &mut Context<'_>, out: &mut Outbox) -> Poll<()> { + let mut events = Vec::new(); + if let Some(peer) = &mut self.peer { + for _ in 0..EVENTS_PER_POLL { + match peer.poll_event(cx) { + Poll::Ready(Some(e)) => events.push(e), + Poll::Ready(None) => { + events.push(PeerEvent::Closed); + break; + } + Poll::Pending => break, + } + } + } + if events.is_empty() { + return Poll::Pending; + } + for event in events { + self.peer_event(event, out); + } + Poll::Ready(()) + } + + fn peer_event(&mut self, event: PeerEvent, out: &mut Outbox) { + if self.state == WatchState::Ended { + return; + } + match event { + PeerEvent::Connected => { + self.state = WatchState::Connected; + self.reconnects = 0; + self.event(WatchEvent::Connected, out); + } + PeerEvent::LocalCandidate { candidate, mid } => { + self.signal(Signal::IceCandidate { candidate, mid, mline_index: Some(0) }, out); + } + PeerEvent::Media(frame) => self.event(WatchEvent::Frame(frame), out), + PeerEvent::KeyframeRequest => {} + PeerEvent::Closed => { + if self.peer.take().is_none() { + return; + } + if self.reconnects < MAX_RECONNECTS { + self.reconnects += 1; + debug!( + stream = self.id, + attempt = self.reconnects, + "connection lost, reconnecting" + ); + self.state = WatchState::Connecting; + self.signal(Signal::Reconnect, out); + } else { + self.fail("connection to the streamer lost".into(), out); + } + } + } + } +} + +/// All stream sessions of one server connection: the directory of streams in +/// our channel, our own stream, and the streams we watch. +pub struct Streams { + own: ClientId, + config: PeerConfig, + directory: StreamDirectory, + streamer: Option, + viewers: BTreeMap, + out: Outbox, +} + +impl Streams { + /// `own` is our client id on the connection; `config` is used for every peer. + pub fn new(own: ClientId, config: PeerConfig) -> Self { + Self { + own, + config, + directory: StreamDirectory::default(), + streamer: None, + viewers: BTreeMap::new(), + out: Outbox::default(), + } + } + + pub fn own_client(&self) -> ClientId { + self.own + } + + pub fn directory(&self) -> &StreamDirectory { + &self.directory + } + + /// Our stream, while it has not ended. + pub fn streamer(&self) -> Option<&StreamerSession> { + self.streamer.as_ref().filter(|s| !s.is_ended()) + } + + pub fn watching(&self) -> impl Iterator { + self.viewers.values() + } + + /// The next request or event; call until `None` after every input. + pub fn poll_output(&mut self) -> Option { + self.out.pop() + } + + /// Start our stream (`setupstream`). + pub fn start(&mut self, options: StreamerOptions) -> Result<(), SessionError> { + // Also while a stream stopped before it went live waits for its id. + if self.streamer.is_some() { + return Err(SessionError::AlreadyStreaming); + } + let session = StreamerSession::start(self.own, options, self.config.clone(), &mut self.out); + self.streamer = Some(session); + Ok(()) + } + + /// Stop our stream. + pub fn stop(&mut self) -> Result<(), SessionError> { + let streamer = self.streamer.as_mut().filter(|s| !s.is_ended()); + streamer.ok_or(SessionError::NotStreaming)?.stop(&mut self.out); + self.cleanup(); + Ok(()) + } + + /// Accept or deny a viewer's join request. + pub async fn respond(&mut self, viewer: ClientId, accept: bool) -> Result<(), SessionError> { + let streamer = self.streamer.as_mut().filter(|s| !s.is_ended()); + streamer.ok_or(SessionError::NotStreaming)?.respond(viewer, accept, &mut self.out).await + } + + /// Remove a viewer from our stream. + pub fn kick(&mut self, viewer: ClientId) -> Result<(), SessionError> { + let streamer = self.streamer.as_mut().filter(|s| !s.is_ended()); + streamer.ok_or(SessionError::NotStreaming)?.kick(viewer, &mut self.out) + } + + /// Send an encoded frame of our stream to all connected viewers. + pub fn write(&self, kind: MediaKind, time: MediaTime, data: impl Into>) { + if let Some(s) = self.streamer() { + s.write(kind, time, data.into()); + } + } + + pub fn write_frame(&self, frame: &EncodedFrame) { + self.write(frame.kind, frame.time, frame.data.clone()); + } + + /// Watch a stream from the directory. + pub fn watch(&mut self, id: &str, message: &str) -> Result<(), SessionError> { + let info = self.directory.get(id).ok_or_else(|| SessionError::UnknownStream(id.into()))?; + let streamer = info.streamer; + self.watch_from(id, streamer, message) + } + + /// Watch stream `id` of `streamer`, also if it is not in the directory. + pub fn watch_from( + &mut self, + id: &str, + streamer: ClientId, + message: &str, + ) -> Result<(), SessionError> { + if streamer == self.own || self.streamer().is_some_and(|s| s.id() == Some(id)) { + return Err(SessionError::OwnStream); + } + if self.viewers.get(id).is_some_and(|v| v.state() != WatchState::Ended) { + return Err(SessionError::AlreadyWatching(id.into())); + } + let session = ViewerSession::join( + self.own, + id, + streamer, + message, + self.config.clone(), + &mut self.out, + ); + self.viewers.insert(id.to_owned(), session); + Ok(()) + } + + /// Stop watching a stream. + pub fn leave(&mut self, id: &str) -> Result<(), SessionError> { + let viewer = + self.viewers.get_mut(id).ok_or_else(|| SessionError::NotWatching(id.into()))?; + viewer.leave(&mut self.out); + self.cleanup(); + Ok(()) + } + + /// Ask the streamer of a watched stream for a keyframe. + pub fn request_keyframe(&self, id: &str) { + if let Some(v) = self.viewers.get(id) { + v.request_keyframe(); + } + } + + /// Reconnect to a watched stream: the streamer sends a new offer. + pub fn reconnect(&mut self, id: &str) -> Result<(), SessionError> { + let viewer = + self.viewers.get_mut(id).ok_or_else(|| SessionError::NotWatching(id.into()))?; + viewer.reconnect(&mut self.out); + Ok(()) + } + + /// Stop streaming and watching, e.g. before disconnecting. + pub fn close(&mut self) { + if let Some(s) = &mut self.streamer { + s.stop(&mut self.out); + } + for v in self.viewers.values_mut() { + v.leave(&mut self.out); + } + self.cleanup(); + } + + /// Feed a stream notification from the connection. + pub async fn handle_notification(&mut self, n: StreamNotification) { + if self.directory.apply(&n) { + self.emit_streams(); + } + if let Some(s) = &mut self.streamer + && s.wants(&n) + { + s.handle(&n, &mut self.out).await; + } + if let Some(v) = self.viewers.get_mut(n.stream_id()) + && v.wants(&n) + { + v.handle(&n, &mut self.out).await; + } + self.cleanup(); + } + + /// `client_is_streaming` of a client changed. + pub fn set_client_streaming(&mut self, client: ClientId, streaming: bool) { + if self.directory.set_streaming(client, streaming) { + self.emit_streams(); + } + } + + /// Drop the streams of streamers `keep` rejects (clients that left or stopped). + pub fn retain_streamers(&mut self, keep: impl FnMut(ClientId) -> bool) { + if self.directory.retain_streamers(keep) { + self.emit_streams(); + } + } + + /// A request from [`Output::Request`] failed on the server. + pub fn request_failed(&mut self, request: &Request, error: &str) { + let watched = match request { + Request::Join { id, .. } | Request::Leave { id, .. } | Request::Signal { id, .. } => { + self.viewers.get_mut(id) + } + _ => None, + }; + if let Some(v) = watched { + v.request_failed(request, error, &mut self.out); + } else if let Some(s) = &mut self.streamer { + s.request_failed(request, error, &mut self.out); + } + self.cleanup(); + } + + /// Wait for peer events and handle them. Cancel safe; never returns while + /// there are no peers. + pub async fn wait_peers(&mut self) { + std::future::poll_fn(|cx| self.poll_peers(cx)).await + } + + /// Handle ready peer events; `Pending` if there were none. + pub fn poll_peers(&mut self, cx: &mut Context<'_>) -> Poll<()> { + let mut ready = false; + if let Some(s) = &mut self.streamer { + ready |= s.poll_peers(cx, &mut self.out).is_ready(); + } + for v in self.viewers.values_mut() { + ready |= v.poll_peer(cx, &mut self.out).is_ready(); + } + if ready { + self.cleanup(); + Poll::Ready(()) + } else { + Poll::Pending + } + } + + fn emit_streams(&mut self) { + self.out.event(StreamEvent::Streams(self.directory.to_vec())); + } + + /// Forget sessions that ended. + fn cleanup(&mut self) { + if self.streamer.as_ref().is_some_and(StreamerSession::is_finished) { + self.streamer = None; + } + self.viewers.retain(|_, v| v.state() != WatchState::Ended); + } +} + +#[cfg(test)] +mod tests { + use std::time::Duration; + + use tokio::time::timeout; + + use super::*; + use crate::proto::StreamKind; + use crate::{Frequency, SyntheticSource}; + + const OWN: ClientId = ClientId(10); + const OTHER: ClientId = ClientId(20); + + fn text(request: &Request) -> String { + String::from_utf8(request.to_command().0.content().to_vec()).unwrap() + } + + fn texts(requests: &[Request]) -> Vec { + requests.iter().map(text).collect() + } + + fn drain(s: &mut Streams) -> (Vec, Vec) { + let (mut requests, mut events) = (Vec::new(), Vec::new()); + while let Some(o) = s.poll_output() { + match o { + Output::Request(r) => requests.push(r), + Output::Event(e) => events.push(e), + } + } + (requests, events) + } + + fn info(id: &str, streamer: ClientId) -> StreamInfo { + StreamInfo { + id: id.into(), + streamer, + name: "screen".into(), + kind: StreamKind::Screen, + bitrate: 4608, + viewer_limit: 0, + audio: true, + } + } + + fn started(id: &str, streamer: ClientId, own: bool) -> StreamNotification { + StreamNotification::Started { + info: info(id, streamer), + return_code: own.then(|| "1".to_owned()), + } + } + + fn stopped(id: &str) -> StreamNotification { + StreamNotification::Stopped { id: id.into(), streamer: None, reason: None } + } + + fn join(viewer: ClientId, remove: bool) -> StreamNotification { + StreamNotification::JoinRequest { id: "s-1".into(), viewer, message: "hi".into(), remove } + } + + fn signaling(peer: ClientId, signal: &Signal) -> StreamNotification { + StreamNotification::Signaling { id: "s-1".into(), peer, json: signal.to_json() } + } + + fn response(accepted: bool, offer: Option) -> StreamNotification { + StreamNotification::JoinResponse { + id: "s-1".into(), + streamer: Some(OTHER), + accepted, + offer, + message: String::new(), + } + } + + /// The last viewer list in `events`. + fn viewers(events: &[StreamEvent]) -> Option> { + events.iter().rev().find_map(|e| match e { + StreamEvent::Streamer(StreamerEvent::Viewers(v)) => { + Some(v.iter().map(|v| (v.client.0, v.state)).collect()) + } + _ => None, + }) + } + + /// Handle peer events until `f` accepts the collected events. + async fn until(s: &mut Streams, mut f: impl FnMut(&[StreamEvent]) -> bool) -> Vec { + let mut events = Vec::new(); + timeout(Duration::from_secs(10), async { + loop { + events.extend(drain(s).1); + if f(&events) { + return; + } + s.wait_peers().await; + } + }) + .await + .expect("timed out"); + events + } + + #[tokio::test] + async fn streamer_transcript() { + let config = PeerConfig::loopback(); + let mut s = Streams::new(OWN, config.clone()); + let setup = StreamSetup { name: "t".into(), ..Default::default() }; + s.start(StreamerOptions { setup, auto_accept: false }).unwrap(); + assert_eq!(s.start(StreamerOptions::default()), Err(SessionError::AlreadyStreaming)); + let (requests, _) = drain(&mut s); + assert_eq!( + texts(&requests), + [ + "setupstream name=t type=3 bitrate=4608 accessibility=1 mode=1 viewer_limit=0 audio=1" + ] + ); + + // Someone else's stream only goes into the directory. + s.handle_notification(started("x-1", OTHER, false)).await; + let (requests, events) = drain(&mut s); + assert!(requests.is_empty()); + assert!(matches!(&events[..], [StreamEvent::Streams(l)] if l.len() == 1)); + assert_eq!(s.streamer().unwrap().id(), None); + + s.handle_notification(started("s-1", OWN, true)).await; + let (_, events) = drain(&mut s); + assert!(matches!( + &events[..], + [StreamEvent::Streams(l), StreamEvent::Streamer(StreamerEvent::Live { id })] + if l.len() == 2 && id == "s-1" + )); + + // A join request waits for our decision. + s.handle_notification(join(OTHER, false)).await; + let (requests, events) = drain(&mut s); + assert!(requests.is_empty()); + assert!(matches!( + &events[0], + StreamEvent::Streamer(StreamerEvent::Request { viewer: OTHER, message }) if message == "hi" + )); + assert_eq!(viewers(&events), Some(vec![(20, ViewerState::Requested)])); + assert_eq!(s.respond(ClientId(99), true).await, Err(SessionError::NoRequest(99))); + + // Accept: the offer goes into respondjoinstreamrequest. + s.respond(OTHER, true).await.unwrap(); + let (requests, events) = drain(&mut s); + let [Request::Respond { id, viewer: OTHER, offer: Some(offer), accept: true }] = + &requests[..] + else { + panic!("{requests:?}") + }; + assert_eq!(id, "s-1"); + assert!(offer.contains("m=video") && offer.contains("VP8"), "{offer}"); + let command = text(&requests[0]); + assert!( + command.starts_with("respondjoinstreamrequest id=s-1 clid=20 msg offer="), + "{command}" + ); + assert!(command.ends_with("decision=1"), "{command}"); + assert_eq!(viewers(&events), Some(vec![(20, ViewerState::Connecting)])); + + // The viewer's answer arrives through notifystreamsignaling. + let (mut viewer_peer, answer) = Peer::answer(&config, offer).await.unwrap(); + s.handle_notification(signaling(OTHER, &Signal::Answer { sdp: answer })).await; + let events = + until(&mut s, |e| viewers(e) == Some(vec![(20, ViewerState::Connected)])).await; + assert!( + events + .iter() + .any(|e| matches!(e, StreamEvent::Streamer(StreamerEvent::KeyframeRequest))), + "a new viewer needs a keyframe" + ); + // Frames reach the viewer. + timeout(Duration::from_secs(5), async { + loop { + let time = MediaTime::new(0, Frequency::FORTY_EIGHT_KHZ); + s.write(MediaKind::Audio, time, &crate::source::OPUS_SILENCE[..]); + tokio::select! { + e = viewer_peer.next_event() => if let Some(PeerEvent::Media(_)) = e { break }, + () = tokio::time::sleep(Duration::from_millis(20)) => {} + } + } + }) + .await + .expect("no media at the viewer"); + + // Withdrawal. + s.handle_notification(join(OTHER, true)).await; + let (requests, events) = drain(&mut s); + assert!(requests.is_empty()); + assert_eq!(viewers(&events), Some(vec![])); + + // Deny. + s.handle_notification(join(ClientId(21), false)).await; + s.respond(ClientId(21), false).await.unwrap(); + let (requests, _) = drain(&mut s); + assert_eq!(texts(&requests), ["respondjoinstreamrequest id=s-1 clid=21 msg decision=0"]); + + // Kick. + s.handle_notification(join(ClientId(22), false)).await; + s.respond(ClientId(22), true).await.unwrap(); + let _ = drain(&mut s); + s.kick(ClientId(22)).unwrap(); + assert_eq!(s.kick(ClientId(22)), Err(SessionError::UnknownViewer(22))); + let (requests, events) = drain(&mut s); + assert_eq!(texts(&requests), ["removeclientfromstream id=s-1 clid=22 reason=5"]); + assert_eq!(viewers(&events), Some(vec![])); + + // A viewer that asks to reconnect gets a new offer. + s.handle_notification(join(ClientId(23), false)).await; + s.respond(ClientId(23), true).await.unwrap(); + let _ = drain(&mut s); + s.handle_notification(signaling(ClientId(23), &Signal::Reconnect)).await; + let (requests, _) = drain(&mut s); + assert!(matches!( + &requests[..], + [Request::Signal { + peer: ClientId(23), + signal: Signal::Offer { reconnect: true, .. }, + .. + }] + )); + assert!(text(&requests[0]).contains("reconnectOffer")); + + // Stop. + s.stop().unwrap(); + let (requests, events) = drain(&mut s); + assert_eq!(texts(&requests), ["stopstream id=s-1 reason=1"]); + assert!(matches!( + &events[..], + [StreamEvent::Streamer(StreamerEvent::Ended(EndReason::Local))] + )); + assert!(s.streamer().is_none()); + assert_eq!(s.stop(), Err(SessionError::NotStreaming)); + // The server tells everyone. + s.handle_notification(stopped("s-1")).await; + let (requests, events) = drain(&mut s); + assert!(requests.is_empty()); + assert!(matches!(&events[..], [StreamEvent::Streams(l)] if l.len() == 1)); + } + + #[tokio::test] + async fn auto_accept_and_failures() { + let mut s = Streams::new(OWN, PeerConfig::loopback()); + s.start(StreamerOptions { auto_accept: true, ..Default::default() }).unwrap(); + let (requests, _) = drain(&mut s); + s.request_failed(&requests[0], "insufficient client permissions (2568)"); + let (_, events) = drain(&mut s); + assert!(matches!( + &events[..], + [StreamEvent::Streamer(StreamerEvent::Ended(EndReason::Failed(m)))] if m.contains("2568") + )); + assert!(s.streamer().is_none()); + + s.start(StreamerOptions { auto_accept: true, ..Default::default() }).unwrap(); + s.handle_notification(started("s-1", OWN, true)).await; + s.handle_notification(join(OTHER, false)).await; + let (requests, events) = drain(&mut s); + assert!(matches!( + &requests[..], + [Request::Setup(_), Request::Respond { offer: Some(_), accept: true, .. }] + )); + assert!( + !events + .iter() + .any(|e| matches!(e, StreamEvent::Streamer(StreamerEvent::Request { .. }))) + ); + // The server refuses the response: the viewer is dropped. + s.request_failed(&requests[1], "invalid client id"); + let (_, events) = drain(&mut s); + assert_eq!(viewers(&events), Some(vec![])); + // The server ends the stream. + s.handle_notification(stopped("s-1")).await; + let (_, events) = drain(&mut s); + assert!( + events.iter().any(|e| matches!( + e, + StreamEvent::Streamer(StreamerEvent::Ended(EndReason::Stopped)) + )) + ); + assert!(s.streamer().is_none()); + } + + #[tokio::test] + async fn stop_before_live() { + let mut s = Streams::new(OWN, PeerConfig::loopback()); + s.start(StreamerOptions::default()).unwrap(); + s.stop().unwrap(); + let _ = drain(&mut s); + // The stream still needs its id to be stopped. + assert_eq!(s.start(StreamerOptions::default()), Err(SessionError::AlreadyStreaming)); + s.handle_notification(started("s-1", OWN, true)).await; + let (requests, events) = drain(&mut s); + assert_eq!(texts(&requests), ["stopstream id=s-1 reason=1"]); + assert!(!events.iter().any(|e| matches!(e, StreamEvent::Streamer(_)))); + s.start(StreamerOptions::default()).unwrap(); + } + + #[tokio::test] + async fn viewer_transcript() { + let config = PeerConfig::loopback(); + let mut s = Streams::new(OWN, config.clone()); + assert_eq!(s.watch("s-1", ""), Err(SessionError::UnknownStream("s-1".into()))); + s.handle_notification(started("s-1", OTHER, false)).await; + let _ = drain(&mut s); + + // Denied. + s.watch("s-1", "please").unwrap(); + assert_eq!(s.watch("s-1", ""), Err(SessionError::AlreadyWatching("s-1".into()))); + let (requests, _) = drain(&mut s); + assert_eq!(texts(&requests), ["joinstreamrequest id=s-1 clid=20 msg=please is_remove=0"]); + s.handle_notification(response(false, None)).await; + let (_, events) = drain(&mut s); + assert!(matches!( + &events[..], + [StreamEvent::Watch { event: WatchEvent::Ended(EndReason::Denied), .. }] + )); + assert_eq!(s.watching().count(), 0); + + // Accepted: our answer goes back through streamsignaling. + s.watch("s-1", "").unwrap(); + let (mut streamer_peer, offer) = Peer::offer(&config, "s-1").await.unwrap(); + s.handle_notification(response(true, Some(offer))).await; + let (requests, events) = drain(&mut s); + assert_eq!(text(&requests[0]), "joinstreamrequest id=s-1 clid=20 msg is_remove=0"); + let Request::Signal { peer: OTHER, signal: Signal::Answer { sdp }, .. } = &requests[1] + else { + panic!("{requests:?}") + }; + assert!(text(&requests[1]).starts_with("streamsignaling id=s-1 clid=20 json={")); + assert!(matches!(&events[..], [StreamEvent::Watch { event: WatchEvent::Accepted, .. }])); + streamer_peer.accept_answer(sdp).await.unwrap(); + + // Media arrives as frames. + let events = until(&mut s, |e| { + e.iter().any(|e| matches!(e, StreamEvent::Watch { event: WatchEvent::Connected, .. })) + }) + .await; + assert!(events.iter().all(|e| matches!(e, StreamEvent::Watch { .. }))); + timeout(Duration::from_secs(5), async { + while !matches!(streamer_peer.next_event().await, Some(PeerEvent::Connected)) {} + }) + .await + .unwrap(); + let frame: Arc<[u8]> = SyntheticSource::video_frame(0, 2000).into(); + let video = until(&mut s, |e| { + streamer_peer.write(MediaKind::Video, MediaTime::from_90khz(0), frame.clone()); + e.iter().any(|e| matches!(e, StreamEvent::Watch { event: WatchEvent::Frame(_), .. })) + }) + .await; + assert!(video.iter().any(|e| matches!( + e, + StreamEvent::Watch { event: WatchEvent::Frame(f), .. } if f.data.len() == 2000 + ))); + + // The streamer's ICE candidates are added; unknown signals are ignored. + let candidate = Signal::IceCandidate { + candidate: "candidate:1 1 udp 2130706431 127.0.0.1 9 typ host".into(), + mid: Some("0".into()), + mline_index: Some(0), + }; + let unknown = Signal::Unknown { cmd: "future".into(), args: serde_json::json!({}) }; + for signal in [candidate, unknown] { + s.handle_notification(signaling(OTHER, &signal)).await; + } + assert!(drain(&mut s).0.is_empty()); + + // Leave. + s.leave("s-1").unwrap(); + let (requests, events) = drain(&mut s); + assert_eq!(texts(&requests), ["joinstreamrequest id=s-1 clid=20 msg is_remove=1"]); + assert!(matches!( + &events[..], + [StreamEvent::Watch { event: WatchEvent::Ended(EndReason::Local), .. }] + )); + assert_eq!(s.leave("s-1"), Err(SessionError::NotWatching("s-1".into()))); + + // Kicked. + s.watch("s-1", "").unwrap(); + s.handle_notification(StreamNotification::ViewerLeft { + id: "s-1".into(), + viewer: OWN, + reason: Some(LeaveReason::Kicked), + }) + .await; + let (_, events) = drain(&mut s); + assert!(matches!( + &events[..], + [StreamEvent::Watch { + event: WatchEvent::Ended(EndReason::Removed(Some(LeaveReason::Kicked))), + .. + }] + )); + + // The stream stops. + s.watch("s-1", "").unwrap(); + s.handle_notification(stopped("s-1")).await; + let (_, events) = drain(&mut s); + assert!(events.iter().any(|e| matches!( + e, + StreamEvent::Watch { event: WatchEvent::Ended(EndReason::Stopped), .. } + ))); + assert!(events.iter().any(|e| matches!(e, StreamEvent::Streams(l) if l.is_empty()))); + assert_eq!(s.watch("s-1", ""), Err(SessionError::UnknownStream("s-1".into()))); + assert_eq!(s.watch_from("x", OWN, ""), Err(SessionError::OwnStream)); + + // A failed join request ends the session. + s.watch_from("s-2", OTHER, "").unwrap(); + let (requests, _) = drain(&mut s); + s.request_failed(&requests[0], "stream not found"); + let (_, events) = drain(&mut s); + assert!(matches!( + &events[..], + [StreamEvent::Watch { event: WatchEvent::Ended(EndReason::Failed(_)), .. }] + )); + } + + #[test] + fn directory() { + let mut d = StreamDirectory::default(); + assert!(d.apply(&started("a", ClientId(1), false))); + assert!(!d.apply(&started("a", ClientId(1), false)), "unchanged"); + let renamed = StreamInfo { name: "renamed".into(), ..info("a", ClientId(1)) }; + assert!(d.apply(&StreamNotification::Info(renamed))); + assert_eq!(d.get("a").unwrap().name, "renamed"); + assert!(!d.set_streaming(ClientId(2), true)); + assert_eq!(d.unannounced_streamers().collect::>(), [ClientId(2)]); + assert!(d.apply(&started("b", ClientId(2), false))); + assert_eq!(d.unannounced_streamers().count(), 0); + assert_eq!(d.by_streamer(ClientId(2)).unwrap().id, "b"); + assert!(d.set_streaming(ClientId(2), false)); + assert!(d.retain_streamers(|c| c != ClientId(1))); + assert_eq!(d.iter().count(), 0); + assert!(d.apply(&started("c", ClientId(3), false))); + assert!(d.apply(&stopped("c"))); + assert!(!d.apply(&join(ClientId(3), false))); + } +} diff --git a/crates/tsc-stream/src/source.rs b/crates/tsc-stream/src/source.rs new file mode 100644 index 0000000..23bb948 --- /dev/null +++ b/crates/tsc-stream/src/source.rs @@ -0,0 +1,129 @@ +//! Where a streamer's encoded frames come from. +//! +//! [`FrameSource`] is the seam between capture/encoding (`tsc-media`) and the +//! stream sessions. [`SyntheticSource`] produces decodable placeholder media +//! without any encoder, for tests and `tsctl stream start --synthetic`. + +use std::sync::Arc; +use std::time::{Duration, Instant}; + +use str0m::media::{Frequency, MediaKind, MediaTime}; + +/// One encoded video or audio frame. +#[derive(Clone, Debug)] +pub struct EncodedFrame { + pub kind: MediaKind, + /// RTP time: 90 kHz for video, 48 kHz for Opus. + pub time: MediaTime, + pub data: Arc<[u8]>, +} + +/// Produces encoded frames in real time. +pub trait FrameSource: Send { + /// Append the frames that are due at `now`. + fn poll_frames(&mut self, now: Instant, out: &mut Vec); + + /// A viewer needs a keyframe soon. + fn request_keyframe(&mut self) {} + + /// How often `poll_frames` should be called. + fn interval(&self) -> Duration { + Duration::from_millis(10) + } +} + +/// A complete 1x1 VP8 keyframe (the image of the smallest lossy WebP). +/// Decoders accept it, so browsers count decoded frames. +pub const VP8_KEYFRAME_1X1: [u8; 22] = [ + 0x30, 0x01, 0x00, 0x9d, 0x01, 0x2a, 0x01, 0x00, 0x01, 0x00, 0x0e, 0xc0, 0xfe, 0x25, 0xa4, 0x00, + 0x03, 0x70, 0x00, 0x00, 0x00, 0x00, +]; + +/// A 20 ms Opus frame of silence (CELT, fullband, mono). +pub const OPUS_SILENCE: [u8; 3] = [0xf8, 0xff, 0xfe]; + +/// Opus frame length at 48 kHz (20 ms). +const OPUS_FRAME: u64 = 960; + +/// Synthetic media: every video frame is [`VP8_KEYFRAME_1X1`] padded to a +/// chosen size (large frames span several RTP packets), audio is +/// [`OPUS_SILENCE`] every 20 ms. Byte `VP8_KEYFRAME_1X1.len()` of each video +/// frame holds the low byte of its sequence number. +pub struct SyntheticSource { + start: Instant, + fps: u32, + video_size: usize, + audio: bool, + video_frames: u64, + audio_frames: u64, +} + +impl SyntheticSource { + /// `fps` video frames of `video_size` bytes per second, plus audio if `audio`. + pub fn new(fps: u32, video_size: usize, audio: bool) -> Self { + Self { + start: Instant::now(), + fps: fps.max(1), + video_size: video_size.max(VP8_KEYFRAME_1X1.len() + 1), + audio, + video_frames: 0, + audio_frames: 0, + } + } + + pub fn video_frame(seq: u64, size: usize) -> Vec { + let mut frame = VP8_KEYFRAME_1X1.to_vec(); + frame.push(seq as u8); + frame.extend((frame.len()..size).map(|i| (i as u8).wrapping_mul(31) ^ seq as u8)); + frame + } +} + +impl FrameSource for SyntheticSource { + fn poll_frames(&mut self, now: Instant, out: &mut Vec) { + let elapsed = now.saturating_duration_since(self.start); + let due_video = elapsed.as_micros() as u64 * u64::from(self.fps) / 1_000_000 + 1; + while self.video_frames < due_video { + let n = self.video_frames; + out.push(EncodedFrame { + kind: MediaKind::Video, + time: MediaTime::from_90khz(n * 90_000 / u64::from(self.fps)), + data: Self::video_frame(n, self.video_size).into(), + }); + self.video_frames += 1; + } + if self.audio { + let due_audio = elapsed.as_millis() as u64 / 20 + 1; + while self.audio_frames < due_audio { + let time = + MediaTime::new(self.audio_frames * OPUS_FRAME, Frequency::FORTY_EIGHT_KHZ); + let data = Arc::from(&OPUS_SILENCE[..]); + out.push(EncodedFrame { kind: MediaKind::Audio, time, data }); + self.audio_frames += 1; + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn paced_frames() { + let mut source = SyntheticSource::new(30, 3000, true); + let start = source.start; + let mut out = Vec::new(); + source.poll_frames(start, &mut out); + assert_eq!(out.len(), 2, "one video and one audio frame at the start"); + out.clear(); + source.poll_frames(start + Duration::from_millis(1000), &mut out); + let video: Vec<_> = out.iter().filter(|f| f.kind == MediaKind::Video).collect(); + let audio = out.len() - video.len(); + assert_eq!((video.len(), audio), (30, 50)); + assert_eq!(video[29].time, MediaTime::from_90khz(90_000)); + assert_eq!(video[0].data.len(), 3000); + assert_eq!(video[0].data[..22], VP8_KEYFRAME_1X1); + assert_eq!(video[0].data[22], 1); + } +} diff --git a/crates/tsc-stream/tests/browser_interop.rs b/crates/tsc-stream/tests/browser_interop.rs new file mode 100644 index 0000000..2d0cf13 --- /dev/null +++ b/crates/tsc-stream/tests/browser_interop.rs @@ -0,0 +1,320 @@ +//! Interop with a browser WebRTC stack: headless Chromium (Playwright) is the +//! other peer, driven by `tests/interop/browser-peer.cjs` over stdin/stdout. +//! No TeamSpeak server is involved; SDP goes straight between the peers. +//! +//! Runs only with `TSC_INTEROP=1` (see `tests/interop/README.md`). + +use std::path::PathBuf; +use std::process::Stdio; +use std::time::{Duration, Instant}; + +use serde_json::{Value, json}; +use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader, Lines}; +use tokio::process::{Child, ChildStdin, ChildStdout, Command}; +use tokio::time::timeout; +use tsc_stream::{ + Codec, FrameSource, MediaKind, Peer, PeerConfig, PeerEvent, Signal, SyntheticSource, +}; + +fn enabled() -> bool { + std::env::var("TSC_INTEROP").is_ok_and(|v| v == "1") +} + +/// The Node.js side (headless Chromium). +struct Browser { + _child: Child, + stdin: ChildStdin, + stdout: Lines>, +} + +impl Browser { + async fn start() -> Self { + let script = PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("../../tests/interop/browser-peer.cjs") + .canonicalize() + .expect("tests/interop/browser-peer.cjs"); + let node = std::env::var("TSC_NODE").unwrap_or_else(|_| "node".into()); + let mut command = Command::new(node); + command + .arg(script) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::inherit()) + .kill_on_drop(true); + // Playwright is usually installed globally. + if std::env::var_os("NODE_PATH").is_none() + && let Ok(out) = std::process::Command::new("npm").args(["root", "-g"]).output() + { + command.env("NODE_PATH", String::from_utf8_lossy(&out.stdout).trim()); + } + let mut child = command.spawn().expect("cannot start node (set TSC_NODE)"); + let stdin = child.stdin.take().unwrap(); + let stdout = BufReader::new(child.stdout.take().unwrap()).lines(); + let mut browser = Self { _child: child, stdin, stdout }; + let ready = browser.read().await; + eprintln!("browser: {}", ready["userAgent"]); + browser + } + + async fn read(&mut self) -> Value { + let line = timeout(Duration::from_secs(60), self.stdout.next_line()) + .await + .expect("browser did not answer") + .unwrap() + .expect("browser exited"); + let value: Value = serde_json::from_str(&line).unwrap(); + if let Some(error) = value.get("error") { + panic!("browser: {error}"); + } + value + } + + async fn call(&mut self, command: Value) -> Value { + let mut line = command.to_string(); + line.push('\n'); + self.stdin.write_all(line.as_bytes()).await.unwrap(); + self.read().await + } + + async fn quit(mut self) { + let _ = self.call(json!({ "op": "quit" })).await; + } +} + +async fn wait_connected(peer: &mut Peer) { + timeout(Duration::from_secs(15), async { + loop { + match peer.next_event().await { + Some(PeerEvent::Connected) => return, + Some(PeerEvent::Closed) | None => panic!("closed before connecting"), + _ => {} + } + } + }) + .await + .expect("no connection with the browser"); +} + +/// Our streamer peer (as in a TeamSpeak stream) sends VP8 + Opus to Chromium. +#[tokio::test(flavor = "multi_thread")] +async fn rust_streams_to_browser() { + if !enabled() { + eprintln!("skipped: set TSC_INTEROP=1 (needs node, Playwright and Chromium)"); + return; + } + let _ = tracing_subscriber::fmt().with_env_filter("warn").with_test_writer().try_init(); + let mut browser = Browser::start().await; + let config = PeerConfig::loopback(); + let (mut peer, offer) = Peer::offer(&config, "interop").await.unwrap(); + let answer = browser.call(json!({ "op": "answer", "sdp": offer })).await; + let answer = answer["sdp"].as_str().unwrap(); + eprintln!("browser answer:\n{answer}"); + peer.accept_answer(answer).await.unwrap(); + wait_connected(&mut peer).await; + + // Three seconds of synthetic media. + let mut source = SyntheticSource::new(30, 3000, true); + let mut frames = Vec::new(); + let mut keyframe_requests = 0; + let end = Instant::now() + Duration::from_secs(3); + while Instant::now() < end { + source.poll_frames(Instant::now(), &mut frames); + for f in frames.drain(..) { + peer.write(f.kind, f.time, f.data); + } + while let Some(event) = peer.try_next_event() { + if let PeerEvent::KeyframeRequest = event { + keyframe_requests += 1; + } + } + tokio::time::sleep(Duration::from_millis(10)).await; + } + let stats = browser.call(json!({ "op": "stats" })).await; + eprintln!("browser stats: {stats:#}\nkeyframe requests from the browser: {keyframe_requests}"); + assert_eq!(stats["connectionState"], "connected"); + let video = &stats["inbound"]["video"]; + let audio = &stats["inbound"]["audio"]; + assert_eq!(video["codec"], "video/VP8"); + assert!(video["packetsReceived"].as_u64().unwrap() > 100, "video packets: {video}"); + assert!(video["bytesReceived"].as_u64().unwrap() > 100_000, "video bytes: {video}"); + assert_eq!(audio["codec"], "audio/opus"); + assert!(audio["packetsReceived"].as_u64().unwrap() > 50, "audio packets: {audio}"); + // The synthetic frames are real (tiny) VP8 keyframes. + assert!(video["framesDecoded"].as_u64().unwrap() > 30, "decoded: {video}"); + browser.quit().await; +} + +/// Answer STUN binding requests with a made-up public address, so a peer +/// reports a server-reflexive candidate without internet access. +async fn fake_stun_server() -> std::net::SocketAddr { + let socket = tokio::net::UdpSocket::bind("127.0.0.1:0").await.unwrap(); + let addr = socket.local_addr().unwrap(); + tokio::spawn(async move { + let mut buf = [0; 1500]; + while let Ok((n, from)) = socket.recv_from(&mut buf).await { + if n < 20 || buf[..2] != [0, 1] { + continue; + } + // Binding success with XOR-MAPPED-ADDRESS 203.0.113.9:40000. + let mut resp = vec![0x01, 0x01, 0, 12]; + resp.extend_from_slice(&buf[4..20]); + resp.extend_from_slice(&[0, 0x20, 0, 8, 0, 1]); + resp.extend_from_slice(&(40000u16 ^ 0x2112).to_be_bytes()); + let ip = u32::from(std::net::Ipv4Addr::new(203, 0, 113, 9)) ^ 0x2112_A442; + resp.extend_from_slice(&ip.to_be_bytes()); + let _ = socket.send_to(&resp, from).await; + } + }); + addr +} + +/// A trickled candidate as our sessions send it (`iceCandidate` signal with +/// the peer's mid) must be accepted by the browser. +#[tokio::test(flavor = "multi_thread")] +async fn trickled_candidates_reach_browser() { + if !enabled() { + eprintln!("skipped: set TSC_INTEROP=1 (needs node, Playwright and Chromium)"); + return; + } + let mut browser = Browser::start().await; + // Primary address (STUN is not sent from loopback) and the fake STUN server. + let stun = fake_stun_server().await; + let config = PeerConfig { + hosts: Vec::new(), + stun_servers: vec![stun.to_string()], + ..PeerConfig::loopback() + }; + let (mut peer, offer) = Peer::offer(&config, "interop").await.unwrap(); + let answer = browser.call(json!({ "op": "answer", "sdp": offer })).await; + peer.accept_answer(answer["sdp"].as_str().unwrap()).await.unwrap(); + let (candidate, mid) = timeout(Duration::from_secs(10), async { + loop { + match peer.next_event().await { + Some(PeerEvent::LocalCandidate { candidate, mid }) => return (candidate, mid), + Some(PeerEvent::Closed) | None => panic!("closed"), + _ => {} + } + } + }) + .await + .expect("no server-reflexive candidate"); + assert!(candidate.contains("203.0.113.9 40000 typ srflx"), "{candidate}"); + let first_mid = offer.lines().find_map(|l| l.strip_prefix("a=mid:")).unwrap().trim(); + assert_eq!(mid.as_deref(), Some(first_mid)); + // Through the signal JSON, as the server relays it. + let json = Signal::IceCandidate { candidate, mid, mline_index: Some(0) }.to_json(); + let Signal::IceCandidate { candidate, mid, mline_index } = Signal::parse(&json).unwrap() else { + unreachable!() + }; + let add = json!({ + "op": "candidate", "candidate": candidate, "sdpMid": mid, "sdpMLineIndex": mline_index + }); + browser.call(add).await; + wait_connected(&mut peer).await; + browser.quit().await; +} + +/// Frames per codec. +#[derive(Debug, Default)] +struct Counts(Vec<(Codec, usize)>); + +impl Counts { + fn add(&mut self, codec: Codec) { + match self.0.iter_mut().find(|(c, _)| *c == codec) { + Some((_, n)) => *n += 1, + None => self.0.push((codec, 1)), + } + } + + fn get(&self, codec: Codec) -> usize { + self.0.iter().find(|(c, _)| *c == codec).map_or(0, |(_, n)| *n) + } + + fn total(&self) -> usize { + self.0.iter().map(|(_, n)| n).sum() + } +} + +struct Received { + video: Counts, + audio: Counts, + /// VP8 keyframes (frame tag bit 0 clear). + vp8_keyframes: usize, +} + +/// Collect frames from `peer` for up to `limit` or until `enough`. +async fn receive(peer: &mut Peer, limit: Duration, enough: usize) -> Received { + let mut r = Received { video: Counts::default(), audio: Counts::default(), vp8_keyframes: 0 }; + let _ = timeout(limit, async { + while let Some(event) = peer.next_event().await { + if let PeerEvent::Media(frame) = event { + let map = match frame.kind { + MediaKind::Video => &mut r.video, + MediaKind::Audio => &mut r.audio, + }; + map.add(frame.codec); + if frame.codec == Codec::Vp8 && frame.data.first().is_some_and(|b| b & 1 == 0) { + r.vp8_keyframes += 1; + } + if r.video.total() >= enough && r.audio.total() >= enough { + return; + } + } + } + }) + .await; + r +} + +/// Chromium sends a canvas stream and an oscillator; our viewer peer answers. +#[tokio::test(flavor = "multi_thread")] +async fn browser_streams_to_rust() { + if !enabled() { + eprintln!("skipped: set TSC_INTEROP=1 (needs node, Playwright and Chromium)"); + return; + } + let _ = tracing_subscriber::fmt().with_env_filter("warn").with_test_writer().try_init(); + let mut browser = Browser::start().await; + let config = PeerConfig::loopback(); + let mut tested = Vec::new(); + for (name, codec) in + [("VP8", Codec::Vp8), ("VP9", Codec::Vp9), ("H264", Codec::H264), ("AV1", Codec::Av1)] + { + // VP8 with trickled browser candidates, the others with candidates in the SDP. + let trickle = codec == Codec::Vp8; + let offer = browser.call(json!({ "op": "offer", "codec": name, "trickle": trickle })).await; + if offer.get("unsupported").is_some() { + eprintln!("{name}: the browser cannot send it, skipped"); + continue; + } + let offer = offer["sdp"].as_str().unwrap(); + let (mut peer, answer) = Peer::answer(&config, offer).await.unwrap(); + browser.call(json!({ "op": "accept", "sdp": answer })).await; + if trickle { + let candidates = browser.call(json!({ "op": "candidates" })).await; + let candidates = candidates["candidates"].as_array().unwrap(); + assert!(!candidates.is_empty(), "no browser candidates"); + for c in candidates { + peer.add_remote_candidate(c["candidate"].as_str().unwrap()); + } + } + wait_connected(&mut peer).await; + let received = receive(&mut peer, Duration::from_secs(8), 60).await; + eprintln!( + "{name}: video {:?}, audio {:?}, VP8 keyframes {}", + received.video, received.audio, received.vp8_keyframes + ); + assert!(received.video.get(codec) >= 30, "{name} video frames"); + assert!(received.audio.get(Codec::Opus) >= 30, "{name} Opus frames"); + if codec == Codec::Vp8 { + // A keyframe request (PLI) makes the browser's encoder send one. + let before = received.vp8_keyframes; + peer.request_keyframe(); + let after = receive(&mut peer, Duration::from_secs(3), 90).await; + assert!(after.vp8_keyframes > 0, "no keyframe after PLI (had {before} before)"); + } + tested.push(name); + } + assert!(tested.contains(&"VP8") && tested.contains(&"VP9"), "tested {tested:?}"); + browser.quit().await; +} diff --git a/crates/tsc-stream/tests/sessions.rs b/crates/tsc-stream/tests/sessions.rs new file mode 100644 index 0000000..acba1ab --- /dev/null +++ b/crates/tsc-stream/tests/sessions.rs @@ -0,0 +1,280 @@ +//! Two stream session managers talking through a fake server that relays the +//! commands like the TeamSpeak 6 server does (see +//! `docs/protocol-notes/ts6-streaming.md`), with real peers on loopback. + +use std::collections::HashMap; +use std::time::{Duration, Instant}; + +use tokio::time::timeout; +use tsc_stream::{ + EndReason, FrameSource, LeaveReason, MediaKind, Output, PeerConfig, Request, StreamEvent, + StreamInfo, StreamKind, StreamNotification, StreamSetup, StreamerEvent, StreamerOptions, + Streams, SyntheticSource, ViewerState, WatchEvent, +}; +use tsclientlib::ClientId; + +const STREAMER: usize = 0; +const VIEWER: usize = 1; +const IDS: [ClientId; 2] = [ClientId(5), ClientId(6)]; + +/// Relays requests to notifications, as observed on a TS6 server. +#[derive(Default)] +struct FakeServer { + streams: HashMap, + next: u32, +} + +impl FakeServer { + fn relay(&mut self, from: ClientId, request: Request) -> Vec<(usize, StreamNotification)> { + let everyone = |n: StreamNotification| (0..2).map(move |i| (i, n.clone())); + let to = |client: ClientId| IDS.iter().position(|c| *c == client).unwrap(); + match request { + Request::Setup(setup) => { + self.next += 1; + let id = format!("stream-{}", self.next); + self.streams.insert(id.clone(), from); + let info = StreamInfo { + id, + streamer: from, + name: setup.name, + kind: setup.kind, + bitrate: setup.bitrate, + viewer_limit: setup.viewer_limit, + audio: setup.audio, + }; + (0..2) + .map(|i| { + let own = IDS[i] == from; + let return_code = own.then(|| "1".to_owned()); + (i, StreamNotification::Started { info: info.clone(), return_code }) + }) + .collect() + } + Request::Stop { id } => { + self.streams.remove(&id); + everyone(StreamNotification::Stopped { id, streamer: Some(from), reason: None }) + .collect() + } + Request::Join { id, streamer, message } => vec![( + to(streamer), + StreamNotification::JoinRequest { id, viewer: from, message, remove: false }, + )], + Request::Leave { id, streamer } => vec![( + to(streamer), + StreamNotification::JoinRequest { + id, + viewer: from, + message: String::new(), + remove: true, + }, + )], + Request::Respond { id, viewer, offer, accept } => vec![( + to(viewer), + StreamNotification::JoinResponse { + id, + streamer: Some(from), + accepted: accept, + offer, + message: String::new(), + }, + )], + Request::Signal { id, peer, signal } => vec![( + to(peer), + StreamNotification::Signaling { id, peer: from, json: signal.to_json() }, + )], + Request::RemoveViewer { id, viewer, reason } => { + everyone(StreamNotification::ViewerLeft { id, viewer, reason: Some(reason) }) + .collect() + } + } + } +} + +struct Net { + server: FakeServer, + clients: [Streams; 2], + /// Events not looked at yet, with the client index. + events: Vec<(usize, StreamEvent)>, + source: Option, + video: usize, + audio: usize, +} + +impl Net { + fn new() -> Self { + let config = PeerConfig::loopback(); + Self { + server: FakeServer::default(), + clients: IDS.map(|id| Streams::new(id, config.clone())), + events: Vec::new(), + source: None, + video: 0, + audio: 0, + } + } + + /// Deliver queued requests until nothing is left. + async fn flush(&mut self) { + loop { + let mut notes = Vec::new(); + for (i, client) in self.clients.iter_mut().enumerate() { + while let Some(output) = client.poll_output() { + match output { + Output::Request(r) => notes.extend(self.server.relay(IDS[i], r)), + Output::Event(StreamEvent::Watch { + event: WatchEvent::Frame(f), .. + }) => match f.kind { + MediaKind::Video => self.video += 1, + MediaKind::Audio => self.audio += 1, + }, + Output::Event(e) => self.events.push((i, e)), + } + } + } + if notes.is_empty() { + return; + } + for (to, n) in notes { + self.clients[to].handle_notification(n).await; + } + } + } + + /// Handle queued requests, then wait for peer events or the next frame tick. + async fn step(&mut self) { + self.flush().await; + let [a, b] = &mut self.clients; + tokio::select! { + () = a.wait_peers() => {} + () = b.wait_peers() => {} + () = tokio::time::sleep(Duration::from_millis(10)) => {} + } + if let Some(source) = &mut self.source { + let mut frames = Vec::new(); + source.poll_frames(Instant::now(), &mut frames); + for frame in &frames { + self.clients[STREAMER].write_frame(frame); + } + } + } + + /// Run the network until `f` accepts an event; earlier events are dropped. + async fn until(&mut self, what: &str, mut f: impl FnMut(usize, &StreamEvent) -> bool) { + timeout(Duration::from_secs(10), async { + loop { + self.flush().await; + if let Some(pos) = self.events.iter().position(|(i, e)| f(*i, e)) { + self.events.drain(..=pos); + return; + } + self.step().await; + } + }) + .await + .unwrap_or_else(|_| panic!("timed out waiting for {what}; events: {:?}", self.events)); + } + + /// Run until the viewer received `n` more video and audio frames. + async fn frames(&mut self, n: usize) { + let (video, audio) = (self.video + n, self.audio + n); + let deadline = Instant::now() + Duration::from_secs(10); + while self.video < video || self.audio < audio { + assert!( + Instant::now() < deadline, + "got {} video / {} audio frames", + self.video, + self.audio + ); + self.step().await; + } + } +} + +fn watch_event(event: &StreamEvent, f: impl Fn(&WatchEvent) -> bool) -> bool { + matches!(event, StreamEvent::Watch { event, .. } if f(event)) +} + +#[tokio::test(flavor = "multi_thread")] +async fn stream_between_sessions() { + let _ = tracing_subscriber::fmt().with_env_filter("warn").with_test_writer().try_init(); + let mut net = Net::new(); + let setup = StreamSetup { name: "fake".into(), kind: StreamKind::Screen, ..Default::default() }; + net.clients[STREAMER].start(StreamerOptions { setup, auto_accept: false }).unwrap(); + net.until("live", |i, e| { + i == STREAMER && matches!(e, StreamEvent::Streamer(StreamerEvent::Live { .. })) + }) + .await; + net.until("stream in the viewer's list", |i, e| { + i == VIEWER && matches!(e, StreamEvent::Streams(l) if l.len() == 1) + }) + .await; + let id = net.clients[VIEWER].directory().by_streamer(IDS[STREAMER]).unwrap().id.clone(); + + // Join, accepted by the streamer. + net.clients[VIEWER].watch(&id, "let me see").unwrap(); + net.until("join request", |i, e| { + i == STREAMER && matches!(e, StreamEvent::Streamer(StreamerEvent::Request { .. })) + }) + .await; + net.clients[STREAMER].respond(IDS[VIEWER], true).await.unwrap(); + net.until("viewer connected", |i, e| { + i == VIEWER && watch_event(e, |e| matches!(e, WatchEvent::Connected)) + }) + .await; + net.until("streamer sees the viewer", |i, e| { + i == STREAMER + && matches!(e, StreamEvent::Streamer(StreamerEvent::Viewers(v)) + if v.len() == 1 && v[0].state == ViewerState::Connected) + }) + .await; + + // Media. + net.source = Some(SyntheticSource::new(30, 4000, true)); + net.frames(20).await; + + // The viewer reconnects: new offer, new answer, media again. + net.clients[VIEWER].reconnect(&id).unwrap(); + net.until("reconnected", |i, e| { + i == VIEWER && watch_event(e, |e| matches!(e, WatchEvent::Connected)) + }) + .await; + net.frames(20).await; + + // The streamer kicks the viewer. + net.clients[STREAMER].kick(IDS[VIEWER]).unwrap(); + net.until("kicked", |i, e| { + i == VIEWER + && watch_event(e, |e| { + matches!(e, WatchEvent::Ended(EndReason::Removed(Some(LeaveReason::Kicked)))) + }) + }) + .await; + assert_eq!(net.clients[VIEWER].watching().count(), 0); + + // Watch again, then the viewer leaves by itself. + net.clients[VIEWER].watch(&id, "").unwrap(); + net.until("second join request", |i, e| { + i == STREAMER && matches!(e, StreamEvent::Streamer(StreamerEvent::Request { .. })) + }) + .await; + net.clients[STREAMER].respond(IDS[VIEWER], true).await.unwrap(); + net.until("viewer connected again", |i, e| { + i == VIEWER && watch_event(e, |e| matches!(e, WatchEvent::Connected)) + }) + .await; + net.frames(5).await; + net.clients[VIEWER].leave(&id).unwrap(); + net.until("viewer gone", |i, e| { + i == STREAMER + && matches!(e, StreamEvent::Streamer(StreamerEvent::Viewers(v)) if v.is_empty()) + }) + .await; + + // The streamer stops; the viewer's list empties. + net.clients[STREAMER].stop().unwrap(); + net.until("stream gone", |i, e| { + i == VIEWER && matches!(e, StreamEvent::Streams(l) if l.is_empty()) + }) + .await; + assert!(net.clients[STREAMER].streamer().is_none()); +} diff --git a/crates/tsc-ui/src/app.rs b/crates/tsc-ui/src/app.rs index adff0a5..1a10ac8 100644 --- a/crates/tsc-ui/src/app.rs +++ b/crates/tsc-ui/src/app.rs @@ -601,6 +601,8 @@ impl App { } Event::Chat { session, message } => self.add_message(session as i64, message), Event::Error { message, .. } => self.set_status(message), + // Stream events: the streams panel is not wired yet. + _ => {} } } diff --git a/docs/architecture.md b/docs/architecture.md index 8040cb4..57ed344 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -66,8 +66,8 @@ fuzz/ cargo-fuzz targets | `tsc-gateway-proto`, `tsc-gateway` (`tsgw`) | Companion service for server admins: identity-challenge auth, permission-mirroring authorization, presence stream, chat relay, SQLite history, WebSocket + JSON (`tsgw.v1+json`) | done | | `tsc-store` | Identities, bookmarks, settings, chat cache, secrets (keyring / Android Keystore) | done | | `tsc-audio` | Capture/playback, Opus, echo cancellation, resampling, jitter buffer, mixer, VAD/push-to-talk | v0 (no AEC yet) | -| `tsc-stream` | TS6 stream commands, JSON signalling, str0m peer connections, host/STUN candidates | signalling + transport | -| `tsc-core` | Engine: runtime, per-server sessions, merge of voice/gateway/query sources, event bus, command API | done (no streams yet) | +| `tsc-stream` | TS6 stream commands, JSON signalling, str0m peer connections, host/STUN candidates, streamer/viewer sessions, frame-source seam | sessions + transport | +| `tsc-core` | Engine: runtime, per-server sessions, merge of voice/gateway/query sources, event bus, command API, streams on TS6 | done (streams with synthetic frames) | | `tsc-ui` | Slint UI and the desktop binary | done (no streams yet) | | `tsc-media` | Screen and system-audio capture backends (PipeWire portal, X11, Windows Graphics Capture, Android MediaProjection), video codecs | planned | | `tsc-platform` | Global hotkeys, notifications, paths | planned | @@ -82,6 +82,23 @@ the native command only when voice-connected *and* in that channel, otherwise th gateway, otherwise a local query relay. UI states: `Offline`, `Observing (Gateway|Query)` (invisible), `Connecting`, `Connected`. +## Streams + +`tsc-stream::Streams` holds the stream state of one TS6 connection without +doing connection IO: it is fed stream notifications (and failed commands) and +the app's decisions, owns the str0m peers, and queues requests to send plus +events. Inside it, `StreamerSession` runs our stream (one peer per viewer, our +offer in `respondjoinstreamrequest`), `ViewerSession` one watched stream +(answer through `streamsignaling`), and `StreamDirectory` the streams of our +channel. Its tests drive two instances through a fake relay server. + +In `tsc-core` a stream task per voice connection runs `Streams`; the voice task +forwards `MessageEvent`s and sends the requests. Encoders push frames through +the `StreamSink` of `StreamState::Live`; received frames of watched streams go +to `Engine::subscribe_frames`, not the event bus. `tsc-stream::FrameSource` is +the seam for capture and encoders (`tsc-media`); `SyntheticSource` stands in +for tests and `tsctl stream start --synthetic`. + ## Milestones | | Scope | Exit criteria | diff --git a/docs/audio.md b/docs/audio.md new file mode 100644 index 0000000..b66c796 --- /dev/null +++ b/docs/audio.md @@ -0,0 +1,77 @@ +# Audio pipeline + +``` +microphone ─ cpal ─ resample 48 kHz mono ─ Processor (AEC3, NS, AGC2) ─ 20 ms frames + ─ Vad / push-to-talk / continuous ─ Opus ─ voice connection + +voice connection ─ Mixer (jitter buffer, Opus decode, per-client volume/mute) + ─ output volume ─┬─ resample to device ─ cpal ─ speakers + └─ Processor::render (echo canceller reference) +``` + +The audio thread lives in `tsc-core/src/audio.rs`; the building blocks are in +`tsc-audio`. All user settings are one serde struct, `tsc_audio::AudioSettings`. + +## Echo cancellation, noise suppression, gain control + +[sonora](https://crates.io/crates/sonora) 0.2 (BSD-3-Clause), a pure Rust port of +the WebRTC audio processing module: AEC3, the WebRTC noise suppressor, AGC2 +(adaptive digital gain + limiter) and a high-pass filter. Chosen over: + +- `webrtc-audio-processing`: binds the C++ library, either a system package found + through pkg-config or a bundled C++ build (autotools, bindgen/libclang); its + licence is not an SPDX expression, and Windows/Android need extra toolchain work; +- `nnnoiseless` (RNNoise port): noise suppression only, no echo cancellation. + +sonora needs no C/C++ toolchain, so it builds the same everywhere. It runs on 10 ms +frames; `Processor` frames arbitrary lengths internally. The dev profile compiles +the sonora crates with `opt-level = 3`: unoptimised, AEC alone takes a third of a +core; optimised, the full chain takes about 0.3 ms per 10 ms frame. + +Measured with the unit tests (synthetic signals): + +| | Result | +|---|---| +| Echo (far end delayed 20–120 ms, -6 dB) | about 25–33 dB attenuation within the first second, 50 dB after two; the delay estimate matches | +| Double talk (near-end tone during echo) | near-end tone loses about 3 dB | +| White noise, suppression `High` | 10 dB or more lower; a tone in 200 ms bursts keeps its level within 3 dB | + +A steady tone is treated as stationary noise and suppressed, as expected from +this kind of noise suppressor, so the test uses bursts like syllables. + +## Voice activity + +`Vad`: a level gate in dBFS with hangover (default -40 dBFS, 300 ms). The optional +`Speech` mode also requires the RNN speech probability of WebRTC's AGC2 VAD +(`sonora-agc2`), which rejects noise loud enough to pass the gate. The RNN also +fires on pure tones, and on synthetic vowels only at low pitch, so the plain gate +stays the default until it is checked with real voices. With voice activation the +two 20 ms frames before the gate opened are sent too, so onsets are not cut. + +## Jitter buffer and clock drift + +`Mixer` wraps the vendored `tsclientlib::audio::AudioHandler` (one queue per +talker) and adds per-client volume and mute. The handler absorbs sender clock +drift: an underrun plays Opus loss concealment for the missing frame (one inserted +frame, and the talker is dropped after three in a row), and when the smallest +queue length over the last 255 packets exceeds its spread, it drops every 100th +sample (1 % faster) until the surplus is gone; queues above 0.5 s are truncated. + +`crates/tsc-audio/tests/drift.rs` simulates one hour of continuous speech with +20–60 ms network jitter, reordering and 0.5 % loss, with the sender clock at ++200 and -200 ppm (720 ms of disagreement per hour). Marker frames every 30 s +measure the end-to-end latency: + +| Sender clock | Latency min / max | First 10 min avg | Last 10 min avg | +|---|---|---|---| +| +200 ppm | 73 / 131 ms | 112 ms | 125 ms | +| -200 ppm | 67 / 95 ms | 82 ms | 84 ms | + +## Devices + +Devices are selected by cpal's stable id (`host:device`, e.g. `alsa:hw:1,0`); +`device::input_devices()` / `output_devices()` list them with the system defaults +marked. cpal's error callback flags a stream as lost on fatal errors (not on xruns +or rerouting); `device::Managed` then reopens the selected device, or the default +one while the selected one is missing (retrying every 2 s, moving back within 5 s +of it reappearing). The audio thread reports these changes as session errors. diff --git a/docs/protocol-notes/ts6-streaming.md b/docs/protocol-notes/ts6-streaming.md index a688726..55c11c2 100644 --- a/docs/protocol-notes/ts6-streaming.md +++ b/docs/protocol-notes/ts6-streaming.md @@ -167,6 +167,44 @@ property for the planned SFU mode. Errors: `setupstream` refused with error 2568 ("insufficient client permissions") has been seen; no stream permission names are documented. +More text commands and notifications named in the server binary (not probed +yet): `requeststreaminfo` (its protobuf request only has `stream_id`, so it +cannot discover the ids of unknown streams), `updatestream` (`stream_id`, +`stream_name`, `max_width`, `max_height`, `max_framerate`, `properties`), +`notifystreamupdated`, `notifystreamattendees` (`return_code`, `client_id`). + +### Streams that started before we joined (open) + +`initserver` and `notifycliententerview` carry `client_is_streaming`, but no +stream id. Whether the server sends `notifystreamstarted` for running streams +to a client that connects or enters the channel later is not confirmed yet. +`tsctl stream list` shows such streamers as "id not announced"; `tsctl stream +watch --id ` can still join when the streamer is known (`--streamer-nick`, +or the only other client streaming). The smoke test starts the viewer first. + +### WebRTC interop with Chromium (confirmed, Chromium 141, 2026-09-26) + +`crates/tsc-stream/tests/browser_interop.rs` (`TSC_INTEROP=1`, see +`tests/interop/README.md`) runs our str0m peers against headless Chromium's +libwebrtc, the stack the official client is built on: + +- Our streamer offer (VP8 + Opus, BUNDLE, `setup:actpass`, host candidates in + the SDP) is accepted; Chromium answers `setup:active` and decodes the + synthetic 1x1 VP8 keyframes. Opus packets arrive. +- Chromium's offers (canvas video + oscillator audio) with VP8, VP9 or AV1 + preferred are answered by our viewer, which receives frames of that codec + and Opus; a PLI from us yields a VP8 keyframe. Playwright's Chromium cannot + send H.264. +- Trickled candidates must carry the real `sdpMid`: str0m's mids are random + strings (e.g. `fhs`), not `0`. Our `iceCandidate` signals use the peer's + first mid and `sdpMLineIndex` 0; Chromium's `addIceCandidate` accepts them. +- Without camera/microphone permission Chromium hides host candidates behind + mDNS names (`.local`), which str0m cannot resolve. The test disables + that; the official client may send mDNS candidates, which would then need a + resolver (or its server-reflexive candidates) on our side. +- str0m answers in its own codec order and the offerer sends the answer's + first codec, so `Peer::answer` orders the viewer's codecs like the offer. + ## Open questions - [x] Viewer side: `joinstreamrequest id clid msg is_remove` (see above). @@ -174,9 +212,11 @@ permissions") has been seen; no stream permission names are documented. - [x] Parameters of `stopstream` and `removeclientfromstream` (`reason` is required). - [ ] Which permission gates `setupstream` (error 2568). - [x] Contents of `notifystreamstarted` (see probe results). -- [ ] Contents of `notifystreaminfo` (`requeststreaminfo`). +- [ ] Contents of `notifystreaminfo` (`requeststreaminfo id=`). +- [ ] Whether a client that joins later is told about running streams (see above). - [ ] Interop with the official TS6 client (its offer/answer details, codecs it - actually picks, whether it trickles candidates). + actually picks, whether it trickles candidates, mDNS host candidates). + Chromium's WebRTC stack interoperates (see above). - [ ] Whether stream audio can be sent without video. - [ ] The WebRTC/protobuf transport some TS6 clients use on UDP 9987 (`client_protocol_format=proto`, reported in community reverse engineering). diff --git a/packaging/README.md b/packaging/README.md new file mode 100644 index 0000000..b74a7b5 --- /dev/null +++ b/packaging/README.md @@ -0,0 +1,41 @@ +# Packaging + +The product name is not decided yet: `TS Client` and the app id +`io.github.faumaray.TsClient` are placeholders (also in +`tsc_platform::{APP_NAME, APP_ID}`); rename them everywhere together. + +| Path | What | +|---|---| +| `linux/` | Desktop file, AppStream metainfo and a placeholder icon, named by app id | +| `flatpak/io.github.faumaray.TsClient.yml` | Flatpak manifest | +| `windows/` | NSIS installer and how to build and sign on Windows ([README](windows/README.md)) | + +## Flatpak + +flatpak-builder builds offline, so the crates from `Cargo.lock` are listed as +sources in `flatpak/cargo-sources.json`, generated (not committed) with +[flatpak-cargo-generator](https://github.com/flatpak/flatpak-builder-tools/tree/master/cargo): + +```sh +curl -LO https://raw.githubusercontent.com/flatpak/flatpak-builder-tools/master/cargo/flatpak-cargo-generator.py +python3 flatpak-cargo-generator.py Cargo.lock -o packaging/flatpak/cargo-sources.json + +flatpak install flathub org.freedesktop.Platform//25.08 org.freedesktop.Sdk//25.08 \ + org.freedesktop.Sdk.Extension.rust-stable//25.08 +flatpak-builder --user --install --force-clean build-flatpak packaging/flatpak/io.github.faumaray.TsClient.yml +flatpak run io.github.faumaray.TsClient +``` + +Regenerate `cargo-sources.json` whenever `Cargo.lock` changes. Inside the build +`rust-toolchain.toml` does not apply: the `rust-stable` extension must provide at +least the workspace's `rust-version`. The SDK has everything else the build needs +(CMake for libopus, ALSA, fontconfig, xkbcommon, libvpx, PipeWire, clang). + +Permissions (`finish-args`): network, Wayland with X11 fallback, DRI, PulseAudio +(microphone and speakers), the PipeWire socket (application audio when streaming), +notifications and the Secret Service. Push-to-talk (GlobalShortcuts) and screen +capture (ScreenCast) go through portals and need no permission. + +Desktops match windows to the desktop file (taskbar icon, portal permissions) by +X11 `WM_CLASS`, which is the binary name `tsc-desktop` (hence `StartupWMClass`), +and on Wayland by the window's app id, which the app should set to the app id. diff --git a/packaging/flatpak/io.github.faumaray.TsClient.yml b/packaging/flatpak/io.github.faumaray.TsClient.yml new file mode 100644 index 0000000..cbe7679 --- /dev/null +++ b/packaging/flatpak/io.github.faumaray.TsClient.yml @@ -0,0 +1,54 @@ +# Flatpak manifest for the desktop app. See packaging/README.md for how to +# build it. The app id is a placeholder until the product has a name. +id: io.github.faumaray.TsClient +runtime: org.freedesktop.Platform +runtime-version: "25.08" +sdk: org.freedesktop.Sdk +sdk-extensions: + - org.freedesktop.Sdk.Extension.rust-stable +command: tsc-desktop + +finish-args: + - --share=network + - --share=ipc + # Wayland, with X11 only where there is no Wayland session. + - --socket=wayland + - --socket=fallback-x11 + # GPU for video decoding and rendering. + - --device=dri + # Microphone and speakers (the PulseAudio API, served by PipeWire on + # current desktops). + - --socket=pulseaudio + # PipeWire for capturing application audio when streaming. Screen capture + # itself goes through the ScreenCast portal. + - --filesystem=xdg-run/pipewire-0 + # Desktop notifications. + - --talk-name=org.freedesktop.Notifications + # Passwords in the Secret Service keyring. + - --talk-name=org.freedesktop.secrets + # Portals (GlobalShortcuts for push-to-talk, ScreenCast, file chooser) need + # no permission. + +build-options: + append-path: /usr/lib/sdk/rust-stable/bin + env: + CARGO_HOME: /run/build/tsc/cargo + CARGO_NET_OFFLINE: "true" + +modules: + - name: tsc + buildsystem: simple + build-commands: + - cargo --offline build --release --locked -p tsc-ui + - install -Dm755 target/release/tsc-desktop -t /app/bin/ + - install -Dm644 packaging/linux/io.github.faumaray.TsClient.desktop -t /app/share/applications/ + - install -Dm644 packaging/linux/io.github.faumaray.TsClient.metainfo.xml -t /app/share/metainfo/ + - install -Dm644 packaging/linux/io.github.faumaray.TsClient.svg -t /app/share/icons/hicolor/scalable/apps/ + sources: + - type: dir + path: ../.. + skip: + - target + - .git + # Vendored crates, generated from Cargo.lock (see packaging/README.md). + - cargo-sources.json diff --git a/packaging/linux/io.github.faumaray.TsClient.desktop b/packaging/linux/io.github.faumaray.TsClient.desktop new file mode 100644 index 0000000..37c44ae --- /dev/null +++ b/packaging/linux/io.github.faumaray.TsClient.desktop @@ -0,0 +1,11 @@ +[Desktop Entry] +Type=Application +Name=TS Client +Comment=Voice chat, text chat and screen sharing +Exec=tsc-desktop +Icon=io.github.faumaray.TsClient +Terminal=false +Categories=Network;Chat;InstantMessaging;AudioVideo; +Keywords=voice;chat;voip;push-to-talk; +StartupNotify=true +StartupWMClass=tsc-desktop diff --git a/packaging/linux/io.github.faumaray.TsClient.metainfo.xml b/packaging/linux/io.github.faumaray.TsClient.metainfo.xml new file mode 100644 index 0000000..0a08f0b --- /dev/null +++ b/packaging/linux/io.github.faumaray.TsClient.metainfo.xml @@ -0,0 +1,49 @@ + + + + io.github.faumaray.TsClient + CC0-1.0 + MIT OR Apache-2.0 + TS Client + Voice chat, text chat and screen sharing + +

+ A desktop voice client written in Rust: talk with push-to-talk or voice + activation, chat in channels you are not in, see who is online without + joining, and watch and share screens. +

+
    +
  • Echo cancellation, noise suppression and automatic gain control
  • +
  • Global push-to-talk on Wayland (desktop portal), X11 and Windows
  • +
  • Per-user volume
  • +
+
+ io.github.faumaray.TsClient.desktop + + tsc-desktop + + https://github.com/Faumaray/teamspeak_client_rs + https://github.com/Faumaray/teamspeak_client_rs/issues + + Faumaray + + + intense + intense + + + always + + + keyboard + pointing + + + + +

First packaged build.

+
+
+
+
diff --git a/packaging/linux/io.github.faumaray.TsClient.svg b/packaging/linux/io.github.faumaray.TsClient.svg new file mode 100644 index 0000000..dc11e42 --- /dev/null +++ b/packaging/linux/io.github.faumaray.TsClient.svg @@ -0,0 +1,10 @@ + + + + + + + + + + diff --git a/packaging/windows/README.md b/packaging/windows/README.md new file mode 100644 index 0000000..f3a3113 --- /dev/null +++ b/packaging/windows/README.md @@ -0,0 +1,50 @@ +# Windows build and installer + +CI (`release-build` in `.github/workflows/ci.yml`) builds `tsc-desktop.exe` on +`windows-2025` and uploads it as an artifact, with the installer when NSIS is on +the runner. Nothing is signed there. + +## Build + +Needs the MSVC build tools, CMake (bundled libopus), NASM (assembly of +`aws-lc-sys`, used by the WebRTC stack) and libvpx (video, `tsc-media`): + +```powershell +winget install NASM.NASM Kitware.CMake NSIS.NSIS +vcpkg install libvpx:x64-windows-static-md + +$vpx = "$env:VCPKG_ROOT\installed\x64-windows-static-md" +$env:VPX_LIB_DIR = "$vpx\lib" +$env:VPX_INCLUDE_DIR = "$vpx\include" +$env:VPX_VERSION = "1.15.2" # what `vcpkg list libvpx` shows +$env:VPX_STATIC = "1" + +cargo build --release --locked -p tsc-ui +makensis /DVERSION=0.1.0 packaging\windows\installer.nsi +``` + +This gives `target\release\tsc-desktop.exe` and +`packaging\windows\tsc-desktop-0.1.0-setup.exe`. The installer puts the app in +`Program Files\TS Client`, adds a Start menu shortcut and an uninstaller; user +data stays in `%APPDATA%\tsc`. + +The executable uses the dynamic MSVC runtime (`VCRUNTIME140.dll`, present on most +systems). To drop that dependency build with +`RUSTFLAGS="-C target-feature=+crt-static"` and libvpx from the +`x64-windows-static` triplet, or ship the Visual C++ redistributable. + +## Signing + +Unsigned builds trigger SmartScreen warnings. Sign the executable before packaging +it, then the installer and the uninstaller it writes (NSIS 3.08+ runs the `SIGN` +command on both): + +```powershell +signtool sign /fd SHA256 /tr http://timestamp.digicert.com /td SHA256 /f cert.pfx /p $env:CERT_PASSWORD target\release\tsc-desktop.exe +makensis /DVERSION=0.1.0 "/DSIGN=signtool sign /fd SHA256 /tr http://timestamp.digicert.com /td SHA256 /f cert.pfx /p $env:CERT_PASSWORD %1" packaging\windows\installer.nsi +``` + +Options for the certificate: an OV/EV code-signing certificate on a hardware token +or in a cloud HSM, Azure Trusted Signing, or SignPath's free plan for open-source +projects. In CI, keep the certificate (base64) and password in repository secrets, +decode it to a file in the job, sign, and delete it. diff --git a/packaging/windows/installer.nsi b/packaging/windows/installer.nsi new file mode 100644 index 0000000..1e1680e --- /dev/null +++ b/packaging/windows/installer.nsi @@ -0,0 +1,86 @@ +; NSIS installer for the desktop app (tsc-desktop.exe). See README.md. +; +; makensis /DVERSION=0.1.0 packaging\windows\installer.nsi +; +; Paths are relative to this file. Optional defines: +; BINARY the executable (default ..\..\target\release\tsc-desktop.exe) +; OUTDIR where the installer goes (default: next to this file) +; SIGN a signing command; "%1" is replaced by the file to sign, e.g. +; /DSIGN="signtool sign /fd SHA256 /tr http://timestamp.digicert.com /td SHA256 /a %1" +; +; The product name and app id are placeholders until the product has a name. + +Unicode true +SetCompressor /SOLID lzma + +!ifndef VERSION + !define VERSION "0.1.0" +!endif +!ifndef BINARY + !define BINARY "..\..\target\release\tsc-desktop.exe" +!endif +!ifndef OUTDIR + !define OUTDIR "." +!endif + +!define APP_NAME "TS Client" +!define APP_ID "io.github.faumaray.TsClient" +!define PUBLISHER "Faumaray" +!define EXE "tsc-desktop.exe" +!define UNINSTALL_KEY "Software\Microsoft\Windows\CurrentVersion\Uninstall\${APP_ID}" + +!ifdef SIGN + ; Sign the installer and the uninstaller it writes (NSIS 3.08+). + !finalize '${SIGN}' + !uninstfinalize '${SIGN}' +!endif + +Name "${APP_NAME}" +OutFile "${OUTDIR}\tsc-desktop-${VERSION}-setup.exe" +InstallDir "$PROGRAMFILES64\${APP_NAME}" +InstallDirRegKey HKLM "${UNINSTALL_KEY}" "InstallLocation" +RequestExecutionLevel admin + +VIProductVersion "${VERSION}.0" +VIAddVersionKey "ProductName" "${APP_NAME}" +VIAddVersionKey "ProductVersion" "${VERSION}" +VIAddVersionKey "FileVersion" "${VERSION}" +VIAddVersionKey "CompanyName" "${PUBLISHER}" +VIAddVersionKey "FileDescription" "${APP_NAME} installer" +VIAddVersionKey "LegalCopyright" "MIT OR Apache-2.0" + +!include "MUI2.nsh" +!define MUI_FINISHPAGE_RUN "$INSTDIR\${EXE}" +!insertmacro MUI_PAGE_DIRECTORY +!insertmacro MUI_PAGE_INSTFILES +!insertmacro MUI_PAGE_FINISH +!insertmacro MUI_UNPAGE_CONFIRM +!insertmacro MUI_UNPAGE_INSTFILES +!insertmacro MUI_LANGUAGE "English" + +Section "Install" + SetOutPath "$INSTDIR" + File "/oname=${EXE}" "${BINARY}" + WriteUninstaller "$INSTDIR\uninstall.exe" + + CreateShortcut "$SMPROGRAMS\${APP_NAME}.lnk" "$INSTDIR\${EXE}" + + WriteRegStr HKLM "${UNINSTALL_KEY}" "DisplayName" "${APP_NAME}" + WriteRegStr HKLM "${UNINSTALL_KEY}" "DisplayVersion" "${VERSION}" + WriteRegStr HKLM "${UNINSTALL_KEY}" "Publisher" "${PUBLISHER}" + WriteRegStr HKLM "${UNINSTALL_KEY}" "InstallLocation" "$INSTDIR" + WriteRegStr HKLM "${UNINSTALL_KEY}" "DisplayIcon" "$INSTDIR\${EXE}" + WriteRegStr HKLM "${UNINSTALL_KEY}" "UninstallString" '"$INSTDIR\uninstall.exe"' + WriteRegStr HKLM "${UNINSTALL_KEY}" "QuietUninstallString" '"$INSTDIR\uninstall.exe" /S' + WriteRegDWORD HKLM "${UNINSTALL_KEY}" "NoModify" 1 + WriteRegDWORD HKLM "${UNINSTALL_KEY}" "NoRepair" 1 +SectionEnd + +Section "Uninstall" + ; User data in %APPDATA%\tsc (identities, bookmarks, history) is kept. + Delete "$INSTDIR\${EXE}" + Delete "$INSTDIR\uninstall.exe" + RMDir "$INSTDIR" + Delete "$SMPROGRAMS\${APP_NAME}.lnk" + DeleteRegKey HKLM "${UNINSTALL_KEY}" +SectionEnd diff --git a/scripts/it-smoke.sh b/scripts/it-smoke.sh index 793a16a..6bb2d43 100755 --- a/scripts/it-smoke.sh +++ b/scripts/it-smoke.sh @@ -11,6 +11,7 @@ # 6. relay chat: a query relay reads channel chat and posts into the channel # 7. gateway (tsgw): login with a TeamSpeak identity, presence, channel chat # both ways, refusal of an identity the server does not know +# 8. stream (TeamSpeak 6 only): a viewer watches a synthetic VP8 + Opus stream # # Usage: scripts/it-smoke.sh [ts3|ts6]... (default: both) # Env: TSCTL=path/to/tsctl (default: builds target/debug/tsctl) @@ -108,6 +109,27 @@ voice_roundtrip() { grep "tone ratio" "$out" } +# TeamSpeak 6: a viewer waits for a stream, a streamer sends synthetic frames. +stream_check() { + local addr=$1 out="$STATE_DIR/stream-watch.log" streamer_out="$STATE_DIR/stream-start.log" + # Unique nicknames: other clients may stream on the same server. + local streamer="streamer-$$-$RANDOM" + "$TSCTL" connect "$addr" --nick "viewer-$$" stream --loopback watch --streamer-nick "$streamer" \ + --expect-frames 60 --timeout 30 >"$out" 2>&1 & + local viewer=$! + sleep 2 + if ! "$TSCTL" connect "$addr" --nick "$streamer" stream --loopback start --synthetic \ + --auto-accept --seconds 10 >"$streamer_out" 2>&1; then + cat "$streamer_out" "$out" + fail "streamer failed" + fi + if ! wait "$viewer"; then + cat "$out" "$streamer_out" + fail "stream frames not received" + fi + grep -E "first video frame|received" "$out" +} + # An observer over ServerQuery must see a voice client join. presence_check() { local addr=$1 query=$2 out="$STATE_DIR/observe.log" @@ -213,10 +235,13 @@ for svc in "${SERVERS[@]}"; do presence_check "$addr" "${QUERY[$svc]}" relay_check "$addr" "${QUERY[$svc]}" gateway_check "$svc" "$addr" + if [[ $svc == ts6 ]]; then + stream_check "$addr" + fi done log "engine (tsc-core) against both servers" -TSC_LIVE=1 cargo test --quiet -p tsc-core --test live 2>&1 | grep -E "test result|panicked|timed out" || fail "engine tests failed" +TSC_LIVE=1 cargo test --quiet -p tsc-core --test live --test stream_live 2>&1 | grep -E "test result|panicked|timed out" || fail "engine tests failed" log "stream (tsc-stream) through the TeamSpeak 6 server" TSC_LIVE=1 cargo test --quiet -p tsc-stream --test live_ts6 2>&1 | grep -E "test result|panicked|timed out" || fail "stream test failed" diff --git a/tests/interop/README.md b/tests/interop/README.md new file mode 100644 index 0000000..4f7a0a2 --- /dev/null +++ b/tests/interop/README.md @@ -0,0 +1,46 @@ +# Browser interop test + +`crates/tsc-stream/tests/browser_interop.rs` checks our str0m peers against +the WebRTC stack of Chromium (libwebrtc, the same stack as the official +TeamSpeak 6 client). `browser-peer.cjs` runs headless Chromium through +Playwright and exchanges SDP and candidates with the Rust test as JSON lines +on stdin/stdout. No TeamSpeak server is involved. + +| Test | What it checks | +|---|---| +| `rust_streams_to_browser` | Our streamer offer (`PeerConfig::loopback()`, VP8 + Opus) answered by an `RTCPeerConnection`; `SyntheticSource` media for 3 s; `inbound-rtp` stats: VP8 packets and bytes, decoded frames (the synthetic frames are real 1x1 VP8 keyframes), Opus packets | +| `browser_streams_to_rust` | Chromium offers a canvas `captureStream` and an oscillator with VP8, VP9, H264 and AV1 preferred in turn (codecs the browser cannot send are skipped); our viewer `Peer::answer` must receive frames of that codec and Opus. VP8 also uses trickled browser candidates and checks that a PLI brings a keyframe | +| `trickled_candidates_reach_browser` | A server-reflexive candidate (from a fake STUN server) as our sessions trickle it (`iceCandidate` signal with the peer's mid) is accepted by `addIceCandidate` | + +## Running + +Needs Node.js with Playwright and its Chromium (`npx playwright install +chromium` on a new machine; `PLAYWRIGHT_BROWSERS_PATH` if the browsers live +elsewhere). + +```sh +TSC_INTEROP=1 cargo test -p tsc-stream --test browser_interop -- --nocapture +``` + +Without `TSC_INTEROP=1` the tests return immediately, so `cargo test` passes on +machines without a browser. `TSC_NODE` selects the node binary; `NODE_PATH` +defaults to `npm root -g` so a global Playwright is found. + +Chromium is started with `--disable-features=WebRtcHideLocalIpsWithMdns`: +without camera/microphone permission it would hide host candidates behind +mDNS names (`.local`), which str0m cannot resolve. The official client +may do the same; see `docs/protocol-notes/ts6-streaming.md`. + +## Findings + +- Chromium 141 (Playwright 1.56) connects to a str0m peer on 127.0.0.1 from its + own host candidate on the primary interface; it gathers no loopback candidates. +- str0m's answer lists codecs in its own configured order, and the offerer + sends the first one. `Peer::answer` therefore configures the viewer's codecs + in the order of the offer (`accept_video_codecs` filters them). +- `Peer::write` sends on the first negotiated payload type of a kind, so a + streamer offers only the codecs its encoder produces (`video_codecs`, + default VP8 only). +- str0m mids are random strings (`a=mid:fhs`), not `0`/`1`; trickled + candidates must carry the real mid, or browsers reject them. +- Playwright's Chromium build sends VP8, VP9 and AV1, not H.264. diff --git a/tests/interop/browser-peer.cjs b/tests/interop/browser-peer.cjs new file mode 100644 index 0000000..1dd052e --- /dev/null +++ b/tests/interop/browser-peer.cjs @@ -0,0 +1,198 @@ +// Headless Chromium as the remote WebRTC peer for +// crates/tsc-stream/tests/browser_interop.rs (see README.md here). +// +// Reads one JSON command per line on stdin and writes one JSON reply per line +// on stdout; logs go to stderr. Commands (`op`): +// answer {sdp} answer an offer, wait for ICE gathering -> {sdp} +// offer {codec, trickle} send canvas video + oscillator audio; offer with +// `codec` preferred -> {sdp} or {unsupported}; +// with `trickle` the SDP has no candidates +// candidates candidates gathered so far -> {candidates: [{candidate, sdpMid, sdpMLineIndex}]} +// accept {sdp} apply the answer to our offer +// candidate {candidate, sdpMid, sdpMLineIndex} add a remote candidate +// stats connection state, inbound/outbound RTP counters, +// frames shown by a