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 b7020b1..8c97fa3 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]] @@ -1204,7 +1204,7 @@ dependencies = [ "js-sys", "num-traits", "wasm-bindgen", - "windows-link", + "windows-link 0.2.1", ] [[package]] @@ -1541,8 +1541,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]] @@ -2624,8 +2624,8 @@ dependencies = [ "read-fonts", "roxmltree", "smallvec", - "windows", - "windows-core", + "windows 0.62.2", + "windows-core 0.62.2", "yeslogic-fontconfig-sys", ] @@ -2823,7 +2823,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]] @@ -3023,7 +3023,7 @@ dependencies = [ "log", "presser", "thiserror 2.0.21", - "windows", + "windows 0.62.2", ] [[package]] @@ -3502,7 +3502,7 @@ dependencies = [ "wasm-bindgen", "web-sys", "webbrowser", - "windows", + "windows 0.62.2", "winit", "zbus", ] @@ -3610,7 +3610,7 @@ dependencies = [ "web-sys", "web-time", "wgpu", - "windows", + "windows 0.62.2", ] [[package]] @@ -3679,8 +3679,8 @@ dependencies = [ "vtable", "wgpu", "wgpu-hal", - "windows", - "windows-core", + "windows 0.62.2", + "windows-core 0.62.2", "write-fonts", ] @@ -3715,7 +3715,7 @@ dependencies = [ "js-sys", "log", "wasm-bindgen", - "windows-core", + "windows-core 0.62.2", ] [[package]] @@ -4023,7 +4023,7 @@ dependencies = [ "socket2", "widestring", "windows-registry", - "windows-result", + "windows-result 0.4.1", "windows-sys 0.61.2", ] @@ -4102,7 +4102,7 @@ dependencies = [ "simd_cesu8", "thiserror 2.0.21", "walkdir", - "windows-link", + "windows-link 0.2.1", ] [[package]] @@ -4280,7 +4280,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d7c4b02199fee7c5d21a5ae7d8cfa79a6ef5bb2fc834d6e9058e89c825efdc55" dependencies = [ "cfg-if", - "windows-link", + "windows-link 0.2.1", ] [[package]] @@ -4488,6 +4488,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" @@ -4764,6 +4778,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" @@ -5480,8 +5508,8 @@ dependencies = [ "sha2 0.11.0", "thiserror 2.0.21", "tokio", - "windows", - "windows-strings", + "windows 0.62.2", + "windows-strings 0.5.1", ] [[package]] @@ -5510,7 +5538,7 @@ dependencies = [ "libc", "redox_syscall 0.5.18", "smallvec", - "windows-link", + "windows-link 0.2.1", ] [[package]] @@ -7391,7 +7419,7 @@ checksum = "c61cb643dac43067f3eb76c866635a74377ac0abca0ff2590674e1e295514c3d" dependencies = [ "bitflags 2.13.2", "skia-bindings", - "windows", + "windows 0.62.2", ] [[package]] @@ -7578,6 +7606,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" @@ -7976,6 +8077,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" @@ -8471,6 +8583,11 @@ dependencies = [ "opus2", "rtrb", "rubato", + "serde", + "serde_json", + "sonora", + "sonora-agc2", + "sonora-simd", "thiserror 2.0.21", "tracing", "tsclientlib", @@ -8582,6 +8699,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" @@ -9105,8 +9239,8 @@ dependencies = [ "log", "num-integer", "thiserror 2.0.21", - "windows", - "windows-core", + "windows 0.62.2", + "windows-core 0.62.2", ] [[package]] @@ -9458,8 +9592,8 @@ dependencies = [ "thiserror 2.0.21", "wgpu-naga-bridge", "wgpu-types", - "windows", - "windows-core", + "windows 0.62.2", + "windows-core 0.62.2", ] [[package]] @@ -9542,16 +9676,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]] @@ -9563,8 +9710,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]] @@ -9573,7 +9729,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]] @@ -9584,9 +9753,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]] @@ -9595,9 +9775,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]] @@ -9622,6 +9802,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" @@ -9641,14 +9827,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]] @@ -9657,9 +9853,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]] @@ -9668,7 +9873,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]] @@ -9677,7 +9891,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]] @@ -9704,7 +9918,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]] @@ -9738,13 +9952,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 a42ab6a..1088f46 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -15,6 +15,7 @@ members = [ "crates/tsc-media", "crates/tsc-model", "crates/tsc-observer", + "crates/tsc-platform", "crates/tsc-query", "crates/tsc-store", "crates/tsc-stream", @@ -34,6 +35,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", @@ -60,6 +62,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/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-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/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/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