diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ef4501d..f7a4991 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -110,6 +110,51 @@ jobs: path: dist/ if-no-files-found: error + # The Android app (docs/android.md): clippy on the Android-only code and a + # debug APK for arm64. Nothing runs on a device here. + android: + name: android (arm64 APK) + runs-on: ubuntu-24.04 + timeout-minutes: 60 + env: + NDK_VERSION: 27.3.13750724 + steps: + - uses: actions/checkout@v4 + - name: Install toolchain (rust-toolchain.toml) + run: | + rustup toolchain install + rustup target add aarch64-linux-android + - uses: Swatinem/rust-cache@v2 + with: + key: android + - uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: 17 + - name: Android SDK packages + run: | + yes | "$ANDROID_HOME/cmdline-tools/latest/bin/sdkmanager" --licenses > /dev/null + "$ANDROID_HOME/cmdline-tools/latest/bin/sdkmanager" \ + "ndk;$NDK_VERSION" "platforms;android-36" "build-tools;36.0.0" > /dev/null + echo "ANDROID_NDK_HOME=$ANDROID_HOME/ndk/$NDK_VERSION" >> "$GITHUB_ENV" + # CMake (libopus) and Slint's Java helper. + echo "ANDROID_NDK_ROOT=$ANDROID_HOME/ndk/$NDK_VERSION" >> "$GITHUB_ENV" + echo "ANDROID_JAR=$ANDROID_HOME/platforms/android-36/android.jar" >> "$GITHUB_ENV" + - name: Install cargo-ndk + run: cargo install cargo-ndk --locked --version 4.1.2 + - name: clippy (Android target, deny warnings) + run: | + cargo ndk -t arm64-v8a --platform 29 clippy --locked -p tsc-android -p tsc-ui --no-deps -- -D warnings + cargo ndk -t arm64-v8a --platform 29 clippy --locked -p tsc-media --no-default-features --no-deps -- -D warnings + - name: Debug APK + working-directory: android + run: ./gradlew --no-daemon assembleDebug -Ptsc.abis=arm64-v8a + - uses: actions/upload-artifact@v4 + with: + name: tsc-android-debug-arm64 + path: android/app/build/outputs/apk/debug/*.apk + if-no-files-found: error + # Licenses, bans, sources and RustSec advisories (the `cargo audit` # database); audit.yml repeats the advisories check daily. deny: diff --git a/Cargo.lock b/Cargo.lock index 8c97fa3..30dcfc0 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -249,6 +249,27 @@ dependencies = [ "pkg-config", ] +[[package]] +name = "android-activity" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee91c0c2905bae44f84bfa4e044536541df26b7703fd0888deeb9060fcc44289" +dependencies = [ + "android-properties", + "bitflags 2.13.2", + "cc", + "cesu8", + "jni 0.21.1", + "jni-sys 0.3.1", + "libc", + "log", + "ndk 0.8.0", + "ndk-context", + "ndk-sys 0.5.0+25.2.9519653", + "num_enum", + "thiserror 1.0.69", +] + [[package]] name = "android-activity" version = "0.6.1" @@ -258,16 +279,25 @@ dependencies = [ "android-properties", "bitflags 2.13.2", "cc", - "jni", + "jni 0.22.4", "libc", "log", - "ndk", + "ndk 0.9.0", "ndk-context", - "ndk-sys", + "ndk-sys 0.6.0+11769913", "num_enum", "thiserror 2.0.21", ] +[[package]] +name = "android-build" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9fc9904ad2ad097c3c1cfe2eacaaf0fc24710936fa9ed941cb310b7c6ed2ab7" +dependencies = [ + "windows-sys 0.52.0", +] + [[package]] name = "android-properties" version = "0.2.2" @@ -1141,6 +1171,12 @@ dependencies = [ "subtle", ] +[[package]] +name = "cesu8" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6d43a04d8753f35258c91f8ec639f792891f748a1edbd759cf1dcea3382ad83c" + [[package]] name = "cexpr" version = "0.6.0" @@ -1525,11 +1561,11 @@ dependencies = [ "block2 0.6.2", "coreaudio-rs", "dasp_sample", - "jni", + "jni 0.22.4", "js-sys", "libc", "mach2", - "ndk", + "ndk 0.9.0", "ndk-context", "num-derive", "num-traits", @@ -3186,7 +3222,7 @@ dependencies = [ "hickory-proto", "idna", "ipnet", - "jni", + "jni 0.22.4", "rand 0.10.3", "thiserror 2.0.21", "tinyvec", @@ -3204,7 +3240,7 @@ dependencies = [ "data-encoding", "idna", "ipnet", - "jni", + "jni 0.22.4", "once_cell", "prefix-trie", "rand 0.10.3", @@ -3227,7 +3263,7 @@ dependencies = [ "hickory-proto", "ipconfig", "ipnet", - "jni", + "jni 0.22.4", "moka", "ndk-context", "once_cell", @@ -3407,6 +3443,23 @@ dependencies = [ "tracing", ] +[[package]] +name = "i-slint-backend-android-activity" +version = "1.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "70d538003a566d7312572ac1435be0704934e46a63d55abdabede513f72332cb" +dependencies = [ + "android-activity 0.5.2", + "android-activity 0.6.1", + "android-build", + "i-slint-common", + "i-slint-core", + "i-slint-renderer-skia", + "jni 0.22.4", + "ndk 0.9.0", + "raw-window-handle", +] + [[package]] name = "i-slint-backend-linuxkms" version = "1.18.1" @@ -3439,6 +3492,7 @@ checksum = "fb974705d61ba56034f6129ff61f3e6282a2c0c07752f25e6cb417d81c0f0958" dependencies = [ "cfg-if", "cfg_aliases", + "i-slint-backend-android-activity", "i-slint-backend-linuxkms", "i-slint-backend-testing", "i-slint-backend-winit", @@ -4088,6 +4142,22 @@ version = "1.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" +[[package]] +name = "jni" +version = "0.21.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1a87aa2bb7d2af34197c04845522473242e1aa17c12f4935d5856491a7fb8c97" +dependencies = [ + "cesu8", + "cfg-if", + "combine", + "jni-sys 0.3.1", + "log", + "thiserror 1.0.69", + "walkdir", + "windows-sys 0.45.0", +] + [[package]] name = "jni" version = "0.22.4" @@ -4717,6 +4787,20 @@ version = "1.0.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "308d96db8debc727c3fd9744aac51751243420e46edf401010908da7f8d5e57c" +[[package]] +name = "ndk" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2076a31b7010b17a38c01907c45b945e8f11495ee4dd588309718901b1f7a5b7" +dependencies = [ + "bitflags 2.13.2", + "jni-sys 0.3.1", + "log", + "ndk-sys 0.5.0+25.2.9519653", + "num_enum", + "thiserror 1.0.69", +] + [[package]] name = "ndk" version = "0.9.0" @@ -4726,7 +4810,7 @@ dependencies = [ "bitflags 2.13.2", "jni-sys 0.3.1", "log", - "ndk-sys", + "ndk-sys 0.6.0+11769913", "num_enum", "raw-window-handle", "thiserror 1.0.69", @@ -4738,6 +4822,15 @@ version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "27b02d87554356db9e9a873add8782d4ea6e3e58ea071a9adb9a2e8ddb884a8b" +[[package]] +name = "ndk-sys" +version = "0.5.0+25.2.9519653" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8c196769dd60fd4f363e11d948139556a344e79d451aeb2fa2fd040738ef7691" +dependencies = [ + "jni-sys 0.3.1", +] + [[package]] name = "ndk-sys" version = "0.6.0+11769913" @@ -6893,7 +6986,7 @@ checksum = "1167586491e2b18b8bfbb293e8180ec17c201c4f076d7cb3070ca964e7598f98" dependencies = [ "core-foundation 0.10.1", "core-foundation-sys", - "jni", + "jni 0.22.4", "log", "once_cell", "rustls", @@ -7445,6 +7538,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "15e477d5ff6fec20909100ff8f7062432ebfbda7a62a0f37d0252aa126f38c83" dependencies = [ "const-field-offset", + "i-slint-backend-android-activity", "i-slint-backend-linuxkms", "i-slint-backend-selector", "i-slint-common", @@ -7586,7 +7680,7 @@ dependencies = [ "fastrand", "js-sys", "memmap2", - "ndk", + "ndk 0.9.0", "objc2 0.6.4", "objc2-core-foundation", "objc2-core-graphics", @@ -8574,6 +8668,25 @@ dependencies = [ "tsproto-types", ] +[[package]] +name = "tsc-android" +version = "0.1.0" +dependencies = [ + "anyhow", + "jni 0.22.4", + "rustls-platform-verifier", + "slint", + "tokio", + "tracing", + "tracing-subscriber", + "tsc-core", + "tsc-media", + "tsc-model", + "tsc-platform", + "tsc-store", + "tsc-ui", +] + [[package]] name = "tsc-audio" version = "0.1.0" @@ -8665,6 +8778,7 @@ dependencies = [ "dav1d", "libvpx-native-sys", "memmap2", + "ndk 0.9.0", "openh264", "pipewire", "reqwest", @@ -9449,7 +9563,7 @@ version = "1.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "62c35be770821a214dbc362fc26908c853e776c0004294d0b10b8a6bad582f94" dependencies = [ - "jni", + "jni 0.22.4", "log", "ndk-context", "objc2 0.6.4", @@ -9894,6 +10008,15 @@ dependencies = [ "windows-link 0.2.1", ] +[[package]] +name = "windows-sys" +version = "0.45.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75283be5efb2831d37ea142365f009c02ec203cd29a3ebecbc093d52315b66d0" +dependencies = [ + "windows-targets 0.42.2", +] + [[package]] name = "windows-sys" version = "0.48.0" @@ -9921,6 +10044,21 @@ dependencies = [ "windows-link 0.2.1", ] +[[package]] +name = "windows-targets" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e5180c00cd44c9b1c88adb3693291f1cd93605ded80c250a75d472756b4d071" +dependencies = [ + "windows_aarch64_gnullvm 0.42.2", + "windows_aarch64_msvc 0.42.2", + "windows_i686_gnu 0.42.2", + "windows_i686_msvc 0.42.2", + "windows_x86_64_gnu 0.42.2", + "windows_x86_64_gnullvm 0.42.2", + "windows_x86_64_msvc 0.42.2", +] + [[package]] name = "windows-targets" version = "0.48.5" @@ -9979,6 +10117,12 @@ dependencies = [ "windows-link 0.2.1", ] +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "597a5118570b68bc08d8d59125332c54f1ba9d9adeedeef5b99b02ba2b0698f8" + [[package]] name = "windows_aarch64_gnullvm" version = "0.48.5" @@ -9991,6 +10135,12 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" +[[package]] +name = "windows_aarch64_msvc" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e08e8864a60f06ef0d0ff4ba04124db8b0fb3be5776a5cd47641e942e58c4d43" + [[package]] name = "windows_aarch64_msvc" version = "0.48.5" @@ -10003,6 +10153,12 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" +[[package]] +name = "windows_i686_gnu" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c61d927d8da41da96a81f029489353e68739737d3beca43145c8afec9a31a84f" + [[package]] name = "windows_i686_gnu" version = "0.48.5" @@ -10021,6 +10177,12 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" +[[package]] +name = "windows_i686_msvc" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "44d840b6ec649f480a41c8d80f9c65108b92d89345dd94027bfe06ac444d1060" + [[package]] name = "windows_i686_msvc" version = "0.48.5" @@ -10033,6 +10195,12 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" +[[package]] +name = "windows_x86_64_gnu" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8de912b8b8feb55c064867cf047dda097f92d51efad5b491dfb98f6bbb70cb36" + [[package]] name = "windows_x86_64_gnu" version = "0.48.5" @@ -10045,6 +10213,12 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "26d41b46a36d453748aedef1486d5c7a85db22e56aff34643984ea85514e94a3" + [[package]] name = "windows_x86_64_gnullvm" version = "0.48.5" @@ -10057,6 +10231,12 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" +[[package]] +name = "windows_x86_64_msvc" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9aec5da331524158c6d1a4ac0ab1541149c0b9505fde06423b02f5ef0106b9f0" + [[package]] name = "windows_x86_64_msvc" version = "0.48.5" @@ -10076,7 +10256,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a6755fa58a9f8350bd1e472d4c3fcc25f824ec358933bba33306d0b63df5978d" dependencies = [ "ahash", - "android-activity", + "android-activity 0.6.1", "atomic-waker", "bitflags 2.13.2", "block2 0.5.1", @@ -10091,7 +10271,7 @@ dependencies = [ "js-sys", "libc", "memmap2", - "ndk", + "ndk 0.9.0", "objc2 0.5.2", "objc2-app-kit 0.2.2", "objc2-foundation 0.2.2", diff --git a/Cargo.toml b/Cargo.toml index 1088f46..7359176 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -8,6 +8,7 @@ members = [ "crates/proto/tsproto", "crates/proto/ts-bookkeeping", "crates/proto/tsclientlib", + "crates/tsc-android", "crates/tsc-audio", "crates/tsc-core", "crates/tsc-gateway", diff --git a/README.md b/README.md index 4b9f4eb..b8f0168 100644 --- a/README.md +++ b/README.md @@ -48,9 +48,12 @@ Done so far (milestones M0–M4 and the first part of M5 of [the plan](docs/arch checks tree, server chat, channel chat, a voice tone round-trip, invisible presence, relay chat and the gateway on both - `fuzz/`: cargo-fuzz targets for packets, commands and the license chain +- `android/` + `crates/tsc-android`: the Android app (the same Slint UI in a NativeActivity, + voice in a foreground service, screen sharing through MediaProjection, MediaCodec, Keystore + passwords). It builds; it has not run on a device yet ([docs/android.md](docs/android.md)) Screen sharing has its protocol and transport layer (`tsc-stream`); capture, codecs and the UI -for it are in progress. No Android build yet. +for it are in progress. | Connected with voice | Observing invisibly through the gateway | |---|---| diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md index d111560..9979541 100644 --- a/THIRD_PARTY_NOTICES.md +++ b/THIRD_PARTY_NOTICES.md @@ -119,6 +119,49 @@ for these implementations of WebM shall terminate as of the date such litigation is filed. ```` +- Skia (Android app only: Slint draws with it there), compiled into the app + from rust-skia's prebuilt binaries (skia-bindings). Its license: + +````text +Copyright (c) 2011 Google Inc. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in + the documentation and/or other materials provided with the + distribution. + + * Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived + from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +```` + + The Skia build includes further libraries under their own licenses: + FreeType (FreeType License: portions of this software are copyright © The + FreeType Project, www.freetype.org, all rights reserved), libpng (PNG + Reference Library License), libjpeg-turbo (IJG License, BSD-3-Clause and + zlib License: this software is based in part on the work of the Independent + JPEG Group), zlib (zlib License), Expat (MIT), Wuffs (Apache-2.0) and the + Vulkan Memory Allocator (MIT). + Other system libraries the app uses at runtime (ALSA, PipeWire, fontconfig, xkbcommon, the C and C++ runtimes) belong to the operating system and are not distributed with it. @@ -132,11 +175,11 @@ the crate's authors are listed as its copyright holders. | License | Crates | |---|---| -| MIT License | 617 | +| MIT License | 619 | | Apache License 2.0 | 29 | | Unicode License v3 | 26 | | BSD 3-Clause "New" or "Revised" License | 22 | -| LicenseRef-Slint-Royalty-free-2.0 | 10 | +| LicenseRef-Slint-Royalty-free-2.0 | 12 | | ISC License | 8 | | BSD 2-Clause "Simplified" License | 3 | | zlib License | 3 | @@ -2631,7 +2674,7 @@ THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH REGARD TO ### LicenseRef-Slint-Royalty-free-2.0 -Used by: i-slint-backend-selector 1.18.1, i-slint-backend-winit 1.18.1, i-slint-common 1.18.1, i-slint-compiler 1.18.1, i-slint-core-macros 1.18.1, i-slint-core 1.18.1, i-slint-renderer-femtovg 1.18.1, i-slint-renderer-software 1.18.1, slint-macros 1.18.1, slint 1.18.1 +Used by: i-slint-backend-android-activity 1.18.1, i-slint-backend-selector 1.18.1, i-slint-backend-winit 1.18.1, i-slint-common 1.18.1, i-slint-compiler 1.18.1, i-slint-core-macros 1.18.1, i-slint-core 1.18.1, i-slint-renderer-femtovg 1.18.1, i-slint-renderer-skia 1.18.1, i-slint-renderer-software 1.18.1, slint-macros 1.18.1, slint 1.18.1 ````text # Slint Royalty-free Desktop, Mobile, and Web Applications License @@ -9498,6 +9541,8 @@ Standard text, used by: - rcgen 0.14.10 (https://github.com/rustls/rcgen) - realfft 3.5.0: HEnquist (https://github.com/HEnquist/realfft) - rustls-platform-verifier-android 0.2.0 (https://github.com/rustls/rustls-platform-verifier) +- skia-bindings 0.153.3: LongYinan , Armin Sander (https://github.com/rust-skia/rust-skia) +- skia-safe 0.153.3: Armin Sander (https://github.com/rust-skia/rust-skia) - str0m-aws-lc-rs 0.6.0: Martin Algesten (https://github.com/algesten/str0m) - str0m-proto 0.7.0: Martin Algesten (https://github.com/algesten/str0m) - taffy 0.10.1: Alice Cecile , Johnathan Kelley , Nico Burns (https://github.com/DioxusLabs/taffy) diff --git a/about.hbs b/about.hbs index 8f3d8dc..926f2e7 100644 --- a/about.hbs +++ b/about.hbs @@ -119,6 +119,49 @@ for these implementations of WebM shall terminate as of the date such litigation is filed. ```` +- Skia (Android app only: Slint draws with it there), compiled into the app + from rust-skia's prebuilt binaries (skia-bindings). Its license: + +````text +Copyright (c) 2011 Google Inc. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in + the documentation and/or other materials provided with the + distribution. + + * Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived + from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +```` + + The Skia build includes further libraries under their own licenses: + FreeType (FreeType License: portions of this software are copyright © The + FreeType Project, www.freetype.org, all rights reserved), libpng (PNG + Reference Library License), libjpeg-turbo (IJG License, BSD-3-Clause and + zlib License: this software is based in part on the work of the Independent + JPEG Group), zlib (zlib License), Expat (MIT), Wuffs (Apache-2.0) and the + Vulkan Memory Allocator (MIT). + Other system libraries the app uses at runtime (ALSA, PipeWire, fontconfig, xkbcommon, the C and C++ runtimes) belong to the operating system and are not distributed with it. diff --git a/android/.gitignore b/android/.gitignore new file mode 100644 index 0000000..a3a3629 --- /dev/null +++ b/android/.gitignore @@ -0,0 +1,6 @@ +.gradle/ +.kotlin/ +build/ +local.properties +*.jks +*.keystore diff --git a/android/app/build.gradle.kts b/android/app/build.gradle.kts new file mode 100644 index 0000000..6305ff6 --- /dev/null +++ b/android/app/build.gradle.kts @@ -0,0 +1,129 @@ +import org.jetbrains.kotlin.gradle.dsl.JvmTarget + +plugins { + id("com.android.application") + id("org.jetbrains.kotlin.android") +} + +/** The Cargo workspace the native library comes from. */ +val workspace: File = rootDir.parentFile + +/** `version` of crates/tsc-android, which is the app's version (docs/release.md). */ +val crateVersion: String = workspace.resolve("crates/tsc-android/Cargo.toml").readLines() + .first { it.startsWith("version = ") } + .substringAfter('"').substringBefore('"') + +/** The version of `crate` in Cargo.lock. */ +fun lockedVersion(crate: String): String { + val lines = workspace.resolve("Cargo.lock").readLines() + val at = lines.indexOfFirst { it == "name = \"$crate\"" } + require(at >= 0) { "$crate is not in Cargo.lock" } + return lines[at + 1].substringAfter('"').substringBefore('"') +} + +/** + * A release signing setting: a Gradle property (e.g. in + * ~/.gradle/gradle.properties) or an environment variable (CI secrets). + * Never stored in the repository. + */ +fun signing(property: String, env: String): String? = + providers.gradleProperty(property).orElse(providers.environmentVariable(env)).orNull + +val releaseStoreFile = signing("tsc.signing.storeFile", "TSC_SIGNING_STORE_FILE") + +android { + namespace = "io.github.faumaray.tsc" + compileSdk = 36 + ndkVersion = "27.3.13750724" + + defaultConfig { + // Placeholder like the desktop app id (packaging/README.md); it cannot + // change after the first upload to Google Play. + applicationId = "io.github.faumaray.TsClient" + minSdk = 29 + targetSdk = 36 + versionName = crateVersion + // major * 1000000 + minor * 1000 + patch (docs/release.md). + versionCode = crateVersion.split('.').map(String::toInt) + .let { (major, minor, patch) -> major * 1_000_000 + minor * 1_000 + patch } + } + + signingConfigs { + if (releaseStoreFile != null) { + create("release") { + storeFile = file(releaseStoreFile) + storePassword = signing("tsc.signing.storePassword", "TSC_SIGNING_STORE_PASSWORD") + keyAlias = signing("tsc.signing.keyAlias", "TSC_SIGNING_KEY_ALIAS") + keyPassword = signing("tsc.signing.keyPassword", "TSC_SIGNING_KEY_PASSWORD") + } + } + } + + buildTypes { + release { + isMinifyEnabled = true + proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro") + // Unsigned without the signing settings. + signingConfig = signingConfigs.findByName("release") + } + } + + compileOptions { + sourceCompatibility = JavaVersion.VERSION_17 + targetCompatibility = JavaVersion.VERSION_17 + } + + packaging { + // Stored uncompressed and page-aligned, loaded straight from the APK. + jniLibs.useLegacyPackaging = false + } +} + +kotlin { + compilerOptions { + jvmTarget.set(JvmTarget.JVM_17) + } +} + +dependencies { + // Must be the version of the rustls-platform-verifier-android crate. + implementation("org.rustls:rustls-platform-verifier:${lockedVersion("rustls-platform-verifier-android")}") +} + +// libtsc_android.so, built with cargo-ndk into build/rust/// +// before the JNI libraries are merged. -Ptsc.skipCargo=true uses what is +// there (e.g. built by CI in an earlier step). +val abis = providers.gradleProperty("tsc.abis").getOrElse("arm64-v8a,x86_64") + .split(',').map(String::trim).filter(String::isNotEmpty) +val skipCargo = providers.gradleProperty("tsc.skipCargo").map(String::toBoolean).getOrElse(false) + +for ((buildType, release) in listOf("debug" to false, "release" to true)) { + val out = layout.buildDirectory.dir("rust/$buildType") + val name = buildType.replaceFirstChar(Char::uppercase) + val cargo = tasks.register("cargoBuild$name") { + group = "build" + description = "Builds the Rust library for $abis with cargo-ndk ($buildType)." + workingDir = workspace + val command = mutableListOf("cargo", "ndk", "--platform", "29", "-o", out.get().asFile.path) + abis.forEach { command += listOf("-t", it) } + command += listOf("build", "-p", "tsc-android") + if (release) command += "--release" + commandLine(command) + val ndk = android.ndkDirectory.path + environment("ANDROID_NDK_HOME", ndk) + // CMake (the bundled libopus) finds the NDK through this one. + environment("ANDROID_NDK_ROOT", ndk) + environment("ANDROID_HOME", android.sdkDirectory.path) + // Slint compiles its Java helper against this. + environment( + "ANDROID_JAR", + android.sdkDirectory.resolve("platforms/android-${android.compileSdk}/android.jar").path, + ) + } + android.sourceSets.getByName(buildType).jniLibs.srcDir(out) + if (!skipCargo) { + tasks.configureEach { + if (this.name == "merge${name}JniLibFolders") dependsOn(cargo) + } + } +} diff --git a/android/app/proguard-rules.pro b/android/app/proguard-rules.pro new file mode 100644 index 0000000..17078d2 --- /dev/null +++ b/android/app/proguard-rules.pro @@ -0,0 +1,7 @@ +# Called from Rust through JNI by name. +-keep class io.github.faumaray.tsc.Bridge { *; } +-keep class io.github.faumaray.tsc.Native { *; } +-keep class io.github.faumaray.tsc.TscApp { *; } + +# rustls-platform-verifier's Kotlin component, also called from Rust. +-keep class org.rustls.platformverifier.** { *; } diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml new file mode 100644 index 0000000..4c842ac --- /dev/null +++ b/android/app/src/main/AndroidManifest.xml @@ -0,0 +1,62 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/android/app/src/main/java/io/github/faumaray/tsc/Bridge.kt b/android/app/src/main/java/io/github/faumaray/tsc/Bridge.kt new file mode 100644 index 0000000..20a8dc3 --- /dev/null +++ b/android/app/src/main/java/io/github/faumaray/tsc/Bridge.kt @@ -0,0 +1,77 @@ +package io.github.faumaray.tsc + +import android.Manifest +import android.content.Context +import android.content.pm.PackageManager +import android.os.Build + +/** + * What the Rust library (crates/tsc-android/src/bridge.rs) calls, from any + * thread. Keep the names and signatures in step with it. + */ +object Bridge { + private val app: TscApp get() = TscApp.instance + + @JvmStatic + fun context(): Context = app + + /** Ask for the microphone (voice) and notification (services) permissions. */ + @JvmStatic + fun requestPermissions() { + val activity = MainActivity.current?.get() ?: return + val wanted = buildList { + add(Manifest.permission.RECORD_AUDIO) + if (Build.VERSION.SDK_INT >= 33) add(Manifest.permission.POST_NOTIFICATIONS) + }.filter { activity.checkSelfPermission(it) != PackageManager.PERMISSION_GRANTED } + if (wanted.isNotEmpty()) { + activity.runOnUiThread { activity.requestPermissions(wanted.toTypedArray(), 1) } + } + } + + /** + * Run the voice service with this notification text (`muted`: the action + * offers Unmute); null stops it. + */ + @JvmStatic + fun setVoiceNotification(text: String?, muted: Boolean) { + if (text == null) VoiceService.stop(app) else VoiceService.start(app, text, muted) + } + + /** Ask the user to share the screen; the answer goes to Native.onScreenCaptureResult. */ + @JvmStatic + fun requestScreenCapture(fps: Int, maxSize: Int) { + val activity = MainActivity.current?.get() + if (activity == null) { + Native.onScreenCaptureResult(false, "the app is not in the foreground") + return + } + activity.runOnUiThread { activity.requestScreenCapture(fps, maxSize) } + } + + @JvmStatic + fun stopScreenCapture() { + ScreenCaptureService.stop(app) + } + + /** Capture what the device plays; false without a running screen capture. */ + @JvmStatic + fun startSystemAudio(): Boolean = ScreenCaptureService.startAudio() + + @JvmStatic + fun stopSystemAudio() { + ScreenCaptureService.stopAudio() + } + + @JvmStatic + fun secretGet(key: String): String? = SecretStore.get(app, key) + + @JvmStatic + fun secretSet(key: String, value: String) { + SecretStore.set(app, key, value) + } + + @JvmStatic + fun secretDelete(key: String) { + SecretStore.delete(app, key) + } +} diff --git a/android/app/src/main/java/io/github/faumaray/tsc/MainActivity.kt b/android/app/src/main/java/io/github/faumaray/tsc/MainActivity.kt new file mode 100644 index 0000000..aaad4ad --- /dev/null +++ b/android/app/src/main/java/io/github/faumaray/tsc/MainActivity.kt @@ -0,0 +1,67 @@ +package io.github.faumaray.tsc + +import android.app.NativeActivity +import android.content.Intent +import android.media.projection.MediaProjectionManager +import android.os.Bundle +import java.lang.ref.WeakReference + +/** + * The window: a NativeActivity running `android_main` of libtsc_android.so + * (the Slint UI). Kotlin only handles what needs an Activity: permission + * prompts and the screen-capture consent dialog. + */ +class MainActivity : NativeActivity() { + private var captureFps = 30 + private var captureMaxSize = 1920 + + override fun onCreate(savedInstanceState: Bundle?) { + current = WeakReference(this) + super.onCreate(savedInstanceState) + } + + override fun onDestroy() { + if (current?.get() === this) current = null + super.onDestroy() + } + + /** + * Back leaves the app like Home instead of finishing the activity, so the + * window (and its state) stays while voice goes on in the background. + */ + @Deprecated("Deprecated in Java") + override fun onBackPressed() { + moveTaskToBack(true) + } + + /** Show the system's "start recording or casting?" dialog. */ + fun requestScreenCapture(fps: Int, maxSize: Int) { + captureFps = fps + captureMaxSize = maxSize + val manager = getSystemService(MediaProjectionManager::class.java) + @Suppress("DEPRECATION") + startActivityForResult(manager.createScreenCaptureIntent(), REQUEST_SCREEN_CAPTURE) + } + + @Deprecated("Deprecated in Java") + override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { + @Suppress("DEPRECATION") + super.onActivityResult(requestCode, resultCode, data) + if (requestCode != REQUEST_SCREEN_CAPTURE) return + if (resultCode == RESULT_OK && data != null) { + // The service reports the outcome to Native.onScreenCaptureResult. + ScreenCaptureService.start(this, resultCode, data, captureFps, captureMaxSize) + } else { + Native.onScreenCaptureResult(false, null) + } + } + + companion object { + private const val REQUEST_SCREEN_CAPTURE = 1001 + + /** The activity in front, if any. */ + @Volatile + var current: WeakReference? = null + private set + } +} diff --git a/android/app/src/main/java/io/github/faumaray/tsc/Native.kt b/android/app/src/main/java/io/github/faumaray/tsc/Native.kt new file mode 100644 index 0000000..55e08f3 --- /dev/null +++ b/android/app/src/main/java/io/github/faumaray/tsc/Native.kt @@ -0,0 +1,45 @@ +package io.github.faumaray.tsc + +import java.nio.ByteBuffer + +/** Callbacks into the Rust library (crates/tsc-android/src/bridge.rs). */ +object Native { + init { + // Already loaded by the NativeActivity; this registers it for JNI + // lookups from this class loader. + System.loadLibrary("tsc_android") + } + + /** The user answered the screen-capture dialog (`error`: why it failed). */ + @JvmStatic + external fun onScreenCaptureResult(granted: Boolean, error: String?) + + /** An RGBA_8888 frame. Returns false when frames are no longer wanted. */ + @JvmStatic + external fun onScreenFrame( + pixels: ByteBuffer, + width: Int, + height: Int, + rowStride: Int, + timestampNs: Long, + ): Boolean + + /** The projection ended (by the app, the user or the system). */ + @JvmStatic + external fun onScreenCaptureStopped() + + /** + * `count` interleaved 48 kHz float samples of what the device plays. + * Returns false when audio is no longer wanted. + */ + @JvmStatic + external fun onSystemAudio(samples: FloatArray, count: Int, channels: Int, timestampNs: Long): Boolean + + /** "Disconnect" in the voice notification. */ + @JvmStatic + external fun onDisconnectVoice() + + /** "Mute" / "Unmute" in the voice notification. */ + @JvmStatic + external fun onToggleMute() +} diff --git a/android/app/src/main/java/io/github/faumaray/tsc/Notifications.kt b/android/app/src/main/java/io/github/faumaray/tsc/Notifications.kt new file mode 100644 index 0000000..502e069 --- /dev/null +++ b/android/app/src/main/java/io/github/faumaray/tsc/Notifications.kt @@ -0,0 +1,61 @@ +package io.github.faumaray.tsc + +import android.app.Notification +import android.app.NotificationChannel +import android.app.NotificationManager +import android.app.PendingIntent +import android.content.Context +import android.content.Intent + +/** Notification channels and the notifications of the foreground services. */ +object Notifications { + const val CHANNEL_VOICE = "voice" + const val CHANNEL_SCREEN = "screen" + + fun createChannels(context: Context) { + val manager = context.getSystemService(NotificationManager::class.java) + manager.createNotificationChannel( + NotificationChannel( + CHANNEL_VOICE, + context.getString(R.string.channel_voice), + NotificationManager.IMPORTANCE_LOW, + ), + ) + manager.createNotificationChannel( + NotificationChannel( + CHANNEL_SCREEN, + context.getString(R.string.channel_screen), + NotificationManager.IMPORTANCE_LOW, + ), + ) + } + + /** Tapping a notification brings the app back. */ + private fun openApp(context: Context): PendingIntent = PendingIntent.getActivity( + context, + 0, + Intent(context, MainActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT), + PendingIntent.FLAG_IMMUTABLE, + ) + + /** An ongoing notification with `actions` (title, intent). */ + fun ongoing( + context: Context, + channel: String, + text: String, + vararg actions: Pair, + ): Notification { + val builder = Notification.Builder(context, channel) + .setSmallIcon(R.drawable.ic_notification) + .setContentTitle(context.getString(R.string.app_name)) + .setContentText(text) + .setContentIntent(openApp(context)) + .setOngoing(true) + .setOnlyAlertOnce(true) + .setCategory(Notification.CATEGORY_CALL) + for ((title, intent) in actions) { + builder.addAction(Notification.Action.Builder(null, title, intent).build()) + } + return builder.build() + } +} diff --git a/android/app/src/main/java/io/github/faumaray/tsc/ScreenCaptureService.kt b/android/app/src/main/java/io/github/faumaray/tsc/ScreenCaptureService.kt new file mode 100644 index 0000000..3cd2084 --- /dev/null +++ b/android/app/src/main/java/io/github/faumaray/tsc/ScreenCaptureService.kt @@ -0,0 +1,257 @@ +package io.github.faumaray.tsc + +import android.Manifest +import android.app.PendingIntent +import android.app.Service +import android.content.Context +import android.content.Intent +import android.content.pm.PackageManager +import android.content.pm.ServiceInfo +import android.graphics.PixelFormat +import android.hardware.display.DisplayManager +import android.hardware.display.VirtualDisplay +import android.media.AudioAttributes +import android.media.AudioFormat +import android.media.AudioPlaybackCaptureConfiguration +import android.media.AudioRecord +import android.media.ImageReader +import android.media.projection.MediaProjection +import android.media.projection.MediaProjectionManager +import android.os.Build +import android.os.Handler +import android.os.HandlerThread +import android.os.IBinder +import android.os.Looper +import android.util.Log +import android.view.Display +import android.view.Surface +import kotlin.concurrent.thread +import kotlin.math.max +import kotlin.math.roundToInt + +/** + * Screen sharing: holds the MediaProjection (a `mediaProjection` foreground + * service, as Android requires), mirrors the display into an ImageReader and + * hands each RGBA frame to Native.onScreenFrame; optionally captures what the + * device plays (AudioPlaybackCapture) for Native.onSystemAudio. + */ +class ScreenCaptureService : Service() { + private var projection: MediaProjection? = null + private var display: VirtualDisplay? = null + private var reader: ImageReader? = null + private var worker: HandlerThread? = null + + @Volatile + private var audioRunning = false + private var audioThread: Thread? = null + + private val main = Handler(Looper.getMainLooper()) + + override fun onBind(intent: Intent?): IBinder? = null + + override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { + if (intent == null || intent.action == ACTION_STOP) { + stopSelf() + return START_NOT_STICKY + } + if (projection != null) return START_NOT_STICKY + val stop = PendingIntent.getService( + this, + 0, + Intent(this, ScreenCaptureService::class.java).setAction(ACTION_STOP), + PendingIntent.FLAG_IMMUTABLE, + ) + val notification = Notifications.ongoing( + this, + Notifications.CHANNEL_SCREEN, + getString(R.string.screen_sharing), + getString(R.string.stop_sharing) to stop, + ) + try { + // Must be in the foreground before getMediaProjection (Android 14). + startForeground(ID, notification, ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PROJECTION) + val data = if (Build.VERSION.SDK_INT >= 33) { + intent.getParcelableExtra(EXTRA_DATA, Intent::class.java) + } else { + @Suppress("DEPRECATION") + intent.getParcelableExtra(EXTRA_DATA) + } ?: throw IllegalStateException("no projection data") + val manager = getSystemService(MediaProjectionManager::class.java) + val projection = manager.getMediaProjection(intent.getIntExtra(EXTRA_RESULT, 0), data) + ?: throw IllegalStateException("the projection was refused") + this.projection = projection + instance = this + startVideo(projection, intent.getIntExtra(EXTRA_FPS, 30), intent.getIntExtra(EXTRA_MAX_SIZE, 1920)) + Native.onScreenCaptureResult(true, null) + } catch (e: Exception) { + Log.w(TAG, "screen capture failed", e) + Native.onScreenCaptureResult(false, e.message ?: e.toString()) + stopSelf() + } + return START_NOT_STICKY + } + + private fun startVideo(projection: MediaProjection, fps: Int, maxSize: Int) { + val worker = HandlerThread("tsc-screen").also { it.start() } + this.worker = worker + val handler = Handler(worker.looper) + // The user or the system can end the projection (status bar chip, + // screen lock); registered before the virtual display (Android 14). + projection.registerCallback(object : MediaProjection.Callback() { + override fun onStop() { + main.post { stopSelf() } + } + }, handler) + + val metrics = resources.displayMetrics + val screen = getSystemService(DisplayManager::class.java).getDisplay(Display.DEFAULT_DISPLAY) + val mode = screen.mode + // The mode is in the display's natural orientation; match the current + // one. (Rotating while sharing letterboxes the picture.) + val rotated = screen.rotation == Surface.ROTATION_90 || screen.rotation == Surface.ROTATION_270 + val (fullWidth, fullHeight) = if (rotated) { + mode.physicalHeight to mode.physicalWidth + } else { + mode.physicalWidth to mode.physicalHeight + } + val scale = minOf(1.0, maxSize.toDouble() / max(fullWidth, fullHeight)) + // Even sizes, as video encoders want. + val width = ((fullWidth * scale).roundToInt() / 2 * 2).coerceAtLeast(2) + val height = ((fullHeight * scale).roundToInt() / 2 * 2).coerceAtLeast(2) + + val reader = ImageReader.newInstance(width, height, PixelFormat.RGBA_8888, 3) + this.reader = reader + val interval = 1_000_000_000L / fps.coerceIn(1, 60) + var last = 0L + reader.setOnImageAvailableListener({ r -> + val image = r.acquireLatestImage() ?: return@setOnImageAvailableListener + try { + // The display renders at its own rate; pass on at most `fps`. + if (image.timestamp - last < interval) return@setOnImageAvailableListener + last = image.timestamp + val plane = image.planes[0] + val wanted = Native.onScreenFrame(plane.buffer, image.width, image.height, plane.rowStride, image.timestamp) + if (!wanted) main.post { stopSelf() } + } finally { + image.close() + } + }, handler) + display = projection.createVirtualDisplay( + "tsc-screen", + width, + height, + metrics.densityDpi, + DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR, + reader.surface, + null, + handler, + ) + } + + /** Capture media, game and unknown-usage playback as 48 kHz stereo float. */ + private fun startAudioCapture(): Boolean { + val projection = projection ?: return false + if (audioRunning) return true + if (checkSelfPermission(Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) { + return false + } + val config = AudioPlaybackCaptureConfiguration.Builder(projection) + .addMatchingUsage(AudioAttributes.USAGE_MEDIA) + .addMatchingUsage(AudioAttributes.USAGE_GAME) + .addMatchingUsage(AudioAttributes.USAGE_UNKNOWN) + .build() + val format = AudioFormat.Builder() + .setEncoding(AudioFormat.ENCODING_PCM_FLOAT) + .setSampleRate(SAMPLE_RATE) + .setChannelMask(AudioFormat.CHANNEL_IN_STEREO) + .build() + val minimum = AudioRecord.getMinBufferSize(SAMPLE_RATE, AudioFormat.CHANNEL_IN_STEREO, AudioFormat.ENCODING_PCM_FLOAT) + val record = try { + AudioRecord.Builder() + .setAudioFormat(format) + .setAudioPlaybackCaptureConfig(config) + // A tenth of a second. + .setBufferSizeInBytes(max(minimum, SAMPLE_RATE / 10 * 2 * 4)) + .build() + } catch (e: Exception) { + Log.w(TAG, "system audio capture unavailable", e) + return false + } + audioRunning = true + record.startRecording() + audioThread = thread(name = "tsc-system-audio") { + // 10 ms of stereo. + val buffer = FloatArray(SAMPLE_RATE / 100 * 2) + try { + while (audioRunning) { + val read = record.read(buffer, 0, buffer.size, AudioRecord.READ_BLOCKING) + if (read < 0) break + if (read > 0 && !Native.onSystemAudio(buffer, read, 2, System.nanoTime())) break + } + } finally { + audioRunning = false + record.stop() + record.release() + } + } + return true + } + + private fun stopAudioCapture() { + audioRunning = false + audioThread?.join(500) + audioThread = null + } + + override fun onDestroy() { + if (instance === this) instance = null + stopAudioCapture() + display?.release() + display = null + reader?.close() + reader = null + projection?.stop() + projection = null + worker?.quitSafely() + worker = null + Native.onScreenCaptureStopped() + super.onDestroy() + } + + companion object { + private const val TAG = "ScreenCaptureService" + private const val ID = 2 + private const val SAMPLE_RATE = 48_000 + private const val ACTION_STOP = "io.github.faumaray.tsc.STOP_SHARING" + private const val EXTRA_RESULT = "result" + private const val EXTRA_DATA = "data" + private const val EXTRA_FPS = "fps" + private const val EXTRA_MAX_SIZE = "max_size" + + @Volatile + private var instance: ScreenCaptureService? = null + + /** Start capturing with the consent the user just gave. */ + fun start(context: Context, resultCode: Int, data: Intent, fps: Int, maxSize: Int) { + val intent = Intent(context, ScreenCaptureService::class.java) + .putExtra(EXTRA_RESULT, resultCode) + .putExtra(EXTRA_DATA, data) + .putExtra(EXTRA_FPS, fps) + .putExtra(EXTRA_MAX_SIZE, maxSize) + context.startForegroundService(intent) + } + + fun stop(context: Context) { + context.stopService(Intent(context, ScreenCaptureService::class.java)) + } + + fun startAudio(): Boolean { + val service = instance ?: return false + return service.startAudioCapture() + } + + fun stopAudio() { + instance?.stopAudioCapture() + } + } +} diff --git a/android/app/src/main/java/io/github/faumaray/tsc/SecretStore.kt b/android/app/src/main/java/io/github/faumaray/tsc/SecretStore.kt new file mode 100644 index 0000000..86d83c5 --- /dev/null +++ b/android/app/src/main/java/io/github/faumaray/tsc/SecretStore.kt @@ -0,0 +1,81 @@ +package io.github.faumaray.tsc + +import android.content.Context +import android.security.keystore.KeyGenParameterSpec +import android.security.keystore.KeyProperties +import android.util.Base64 +import android.util.Log +import java.security.KeyStore +import javax.crypto.Cipher +import javax.crypto.KeyGenerator +import javax.crypto.SecretKey +import javax.crypto.spec.GCMParameterSpec + +/** + * Saved passwords (server, query), for the Rust side's `Secrets`. + * + * Each value is encrypted with AES-256-GCM under a key that never leaves the + * Android Keystore (hardware-backed where available); the key name is the + * associated data, so a value cannot be moved to another key. Only the + * ciphertext is stored, in private preferences excluded from backups. + */ +object SecretStore { + private const val TAG = "SecretStore" + private const val KEYSTORE = "AndroidKeyStore" + private const val KEY_ALIAS = "tsc-secrets" + private const val PREFS = "secrets" + private const val TRANSFORMATION = "AES/GCM/NoPadding" + private const val IV_BYTES = 12 + private const val TAG_BITS = 128 + + private fun key(): SecretKey { + val keyStore = KeyStore.getInstance(KEYSTORE).apply { load(null) } + (keyStore.getKey(KEY_ALIAS, null) as? SecretKey)?.let { return it } + val generator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, KEYSTORE) + generator.init( + KeyGenParameterSpec.Builder( + KEY_ALIAS, + KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT, + ) + .setBlockModes(KeyProperties.BLOCK_MODE_GCM) + .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE) + .setKeySize(256) + .build(), + ) + return generator.generateKey() + } + + private fun prefs(context: Context) = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE) + + /** The value, or null if none is saved or it cannot be decrypted. */ + @Synchronized + fun get(context: Context, name: String): String? { + val stored = prefs(context).getString(name, null) ?: return null + return try { + val bytes = Base64.decode(stored, Base64.NO_WRAP) + val cipher = Cipher.getInstance(TRANSFORMATION) + cipher.init(Cipher.DECRYPT_MODE, key(), GCMParameterSpec(TAG_BITS, bytes, 0, IV_BYTES)) + cipher.updateAAD(name.toByteArray()) + String(cipher.doFinal(bytes, IV_BYTES, bytes.size - IV_BYTES), Charsets.UTF_8) + } catch (e: Exception) { + // E.g. the key was lost (the device's lock screen was reset). + Log.w(TAG, "cannot decrypt $name", e) + null + } + } + + @Synchronized + fun set(context: Context, name: String, value: String) { + val cipher = Cipher.getInstance(TRANSFORMATION) + cipher.init(Cipher.ENCRYPT_MODE, key()) + cipher.updateAAD(name.toByteArray()) + val sealed = cipher.iv + cipher.doFinal(value.toByteArray(Charsets.UTF_8)) + check(cipher.iv.size == IV_BYTES) + prefs(context).edit().putString(name, Base64.encodeToString(sealed, Base64.NO_WRAP)).commit() + } + + @Synchronized + fun delete(context: Context, name: String) { + prefs(context).edit().remove(name).commit() + } +} diff --git a/android/app/src/main/java/io/github/faumaray/tsc/TscApp.kt b/android/app/src/main/java/io/github/faumaray/tsc/TscApp.kt new file mode 100644 index 0000000..5c29cfc --- /dev/null +++ b/android/app/src/main/java/io/github/faumaray/tsc/TscApp.kt @@ -0,0 +1,17 @@ +package io.github.faumaray.tsc + +import android.app.Application + +/** The process's application object; the Rust side reaches Android through it. */ +class TscApp : Application() { + override fun onCreate() { + super.onCreate() + instance = this + Notifications.createChannels(this) + } + + companion object { + lateinit var instance: TscApp + private set + } +} diff --git a/android/app/src/main/java/io/github/faumaray/tsc/VoiceService.kt b/android/app/src/main/java/io/github/faumaray/tsc/VoiceService.kt new file mode 100644 index 0000000..d56357b --- /dev/null +++ b/android/app/src/main/java/io/github/faumaray/tsc/VoiceService.kt @@ -0,0 +1,110 @@ +package io.github.faumaray.tsc + +import android.app.Notification +import android.app.NotificationManager +import android.app.PendingIntent +import android.app.Service +import android.content.Context +import android.content.Intent +import android.content.pm.ServiceInfo +import android.os.Build +import android.os.IBinder +import android.util.Log + +/** + * Foreground service while a voice connection exists: Android keeps the + * process, the network and (type microphone) the microphone of an app in + * the background only this way. The Rust side starts, updates and stops it. + */ +class VoiceService : Service() { + override fun onBind(intent: Intent?): IBinder? = null + + override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { + when (intent?.action) { + ACTION_DISCONNECT -> { + Native.onDisconnectVoice() + return START_NOT_STICKY + } + ACTION_TOGGLE_MUTE -> { + Native.onToggleMute() + return START_NOT_STICKY + } + } + val text = intent?.getStringExtra(EXTRA_TEXT) ?: getString(R.string.voice_connected) + val muted = intent?.getBooleanExtra(EXTRA_MUTED, false) ?: false + try { + if (Build.VERSION.SDK_INT >= 30) { + startForeground(ID, notification(this, text, muted), ServiceInfo.FOREGROUND_SERVICE_TYPE_MICROPHONE) + } else { + startForeground(ID, notification(this, text, muted)) + } + running = this + } catch (e: RuntimeException) { + // E.g. no microphone permission (Android 14 refuses the type): + // voice then works only while the app is in front. + Log.w(TAG, "voice service cannot run in the foreground", e) + stopSelf() + } + return START_NOT_STICKY + } + + override fun onDestroy() { + if (running === this) running = null + super.onDestroy() + } + + companion object { + private const val TAG = "VoiceService" + private const val ID = 1 + private const val EXTRA_TEXT = "text" + private const val EXTRA_MUTED = "muted" + private const val ACTION_DISCONNECT = "io.github.faumaray.tsc.DISCONNECT" + private const val ACTION_TOGGLE_MUTE = "io.github.faumaray.tsc.TOGGLE_MUTE" + + @Volatile + private var running: VoiceService? = null + + private fun action(context: Context, action: String, request: Int): PendingIntent = + PendingIntent.getService( + context, + request, + Intent(context, VoiceService::class.java).setAction(action), + PendingIntent.FLAG_IMMUTABLE, + ) + + private fun notification(context: Context, text: String, muted: Boolean): Notification = + Notifications.ongoing( + context, + Notifications.CHANNEL_VOICE, + text, + context.getString(if (muted) R.string.unmute else R.string.mute) to + action(context, ACTION_TOGGLE_MUTE, 1), + context.getString(R.string.disconnect) to action(context, ACTION_DISCONNECT, 0), + ) + + /** Start the service, or update its notification when it runs. */ + fun start(context: Context, text: String, muted: Boolean) { + val service = running + if (service != null) { + service.getSystemService(NotificationManager::class.java) + .notify(ID, notification(service, text, muted)) + return + } + try { + context.startForegroundService( + Intent(context, VoiceService::class.java) + .putExtra(EXTRA_TEXT, text) + .putExtra(EXTRA_MUTED, muted), + ) + } catch (e: RuntimeException) { + // Not allowed from the background (Android 12+). Voice is + // connected from the UI, so this should not happen. + Log.w(TAG, "cannot start the voice service", e) + } + } + + fun stop(context: Context) { + context.stopService(Intent(context, VoiceService::class.java)) + } + } +} diff --git a/android/app/src/main/res/drawable/ic_launcher_foreground.xml b/android/app/src/main/res/drawable/ic_launcher_foreground.xml new file mode 100644 index 0000000..679d723 --- /dev/null +++ b/android/app/src/main/res/drawable/ic_launcher_foreground.xml @@ -0,0 +1,26 @@ + + + + + + + + diff --git a/android/app/src/main/res/drawable/ic_notification.xml b/android/app/src/main/res/drawable/ic_notification.xml new file mode 100644 index 0000000..7810123 --- /dev/null +++ b/android/app/src/main/res/drawable/ic_notification.xml @@ -0,0 +1,12 @@ + + + + + diff --git a/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml b/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml new file mode 100644 index 0000000..2e4a27f --- /dev/null +++ b/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml @@ -0,0 +1,6 @@ + + + + + + diff --git a/android/app/src/main/res/values/colors.xml b/android/app/src/main/res/values/colors.xml new file mode 100644 index 0000000..1a3fe07 --- /dev/null +++ b/android/app/src/main/res/values/colors.xml @@ -0,0 +1,6 @@ + + + #FF1C1C1C + + #FF238636 + diff --git a/android/app/src/main/res/values/strings.xml b/android/app/src/main/res/values/strings.xml new file mode 100644 index 0000000..f1e2b43 --- /dev/null +++ b/android/app/src/main/res/values/strings.xml @@ -0,0 +1,13 @@ + + + + TS Client + Voice connection + Screen sharing + Connected to voice + Disconnect + Mute + Unmute + Sharing your screen + Stop sharing + diff --git a/android/app/src/main/res/values/themes.xml b/android/app/src/main/res/values/themes.xml new file mode 100644 index 0000000..db390b8 --- /dev/null +++ b/android/app/src/main/res/values/themes.xml @@ -0,0 +1,7 @@ + + + + + diff --git a/android/build.gradle.kts b/android/build.gradle.kts new file mode 100644 index 0000000..300289d --- /dev/null +++ b/android/build.gradle.kts @@ -0,0 +1,4 @@ +plugins { + id("com.android.application") version "8.13.2" apply false + id("org.jetbrains.kotlin.android") version "2.3.21" apply false +} diff --git a/android/gradle.properties b/android/gradle.properties new file mode 100644 index 0000000..27d1956 --- /dev/null +++ b/android/gradle.properties @@ -0,0 +1,7 @@ +org.gradle.jvmargs=-Xmx2g -Dfile.encoding=UTF-8 +android.useAndroidX=false +android.nonTransitiveRClass=true +kotlin.code.style=official +# ABIs the Rust library is built for (cargo-ndk names), e.g. only +# -Ptsc.abis=arm64-v8a for a phone. +tsc.abis=arm64-v8a,x86_64 diff --git a/android/gradle/wrapper/gradle-wrapper.jar b/android/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..1b33c55 Binary files /dev/null and b/android/gradle/wrapper/gradle-wrapper.jar differ diff --git a/android/gradle/wrapper/gradle-wrapper.properties b/android/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..78cb6e1 --- /dev/null +++ b/android/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,8 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionSha256Sum=bd71102213493060956ec229d946beee57158dbd89d0e62b91bca0fa2c5f3531 +distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.3-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/android/gradlew b/android/gradlew new file mode 100755 index 0000000..23d15a9 --- /dev/null +++ b/android/gradlew @@ -0,0 +1,251 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# SPDX-License-Identifier: Apache-2.0 +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH="\\\"\\\"" + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/android/gradlew.bat b/android/gradlew.bat new file mode 100644 index 0000000..5eed7ee --- /dev/null +++ b/android/gradlew.bat @@ -0,0 +1,94 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH= + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/android/settings.gradle.kts b/android/settings.gradle.kts new file mode 100644 index 0000000..9d519fe --- /dev/null +++ b/android/settings.gradle.kts @@ -0,0 +1,24 @@ +pluginManagement { + repositories { + google() + mavenCentral() + gradlePluginPortal() + } +} + +dependencyResolutionManagement { + repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS) + repositories { + google() + mavenCentral() + // The Kotlin half of rustls-platform-verifier (the Rust code checks + // TLS certificates against the Android trust store through it). + maven { + url = uri("https://raw.githubusercontent.com/rustls/rustls-platform-verifier/maven-archive/android-release-support/maven/") + content { includeGroup("org.rustls") } + } + } +} + +rootProject.name = "tsc" +include(":app") diff --git a/crates/tsc-android/Cargo.toml b/crates/tsc-android/Cargo.toml new file mode 100644 index 0000000..a2a044a --- /dev/null +++ b/crates/tsc-android/Cargo.toml @@ -0,0 +1,37 @@ +[package] +name = "tsc-android" +version = "0.1.0" +description = "Android app library: native activity entry point, engine kept for the whole process, JNI bridge to the Kotlin services (voice, screen share), Android Keystore secrets." +edition.workspace = true +rust-version.workspace = true +license.workspace = true +repository.workspace = true +publish.workspace = true + +[lib] +name = "tsc_android" +# cdylib: libtsc_android.so, loaded by the app's NativeActivity. rlib: tests +# and type checks on the host. +crate-type = ["cdylib", "rlib"] + +[dependencies] +tokio = { version = "1.53.1", features = ["rt-multi-thread", "macros", "sync", "time"] } +tracing = "0.1.44" +tsc-core = { path = "../tsc-core" } + +[target.'cfg(target_os = "android")'.dependencies] +anyhow = "1.0.104" +jni = "0.22.4" +rustls-platform-verifier = "0.7.1" +slint = { version = "1.18", default-features = false, features = ["std", "compat-1-2", "backend-android-activity-06"] } +tracing-subscriber = { version = "0.3.23", features = ["env-filter"] } +tsc-media = { path = "../tsc-media", default-features = false } +tsc-platform = { path = "../tsc-platform", default-features = false } +tsc-store = { path = "../tsc-store" } +tsc-ui = { path = "../tsc-ui" } + +[dev-dependencies] +tsc-model = { path = "../tsc-model" } + +[lints] +workspace = true diff --git a/crates/tsc-android/src/app.rs b/crates/tsc-android/src/app.rs new file mode 100644 index 0000000..3961f9d --- /dev/null +++ b/crates/tsc-android/src/app.rs @@ -0,0 +1,148 @@ +//! `android_main`: the activity's native thread. +//! +//! android-activity calls it on a new thread for every activity instance +//! (the process can outlive activities while voice runs in the service). +//! Process-wide setup happens once; the window is built per activity. + +use std::path::Path; +use std::sync::{Mutex, Once, OnceLock, PoisonError}; + +use anyhow::Context as _; +use slint::android::AndroidApp; +use tracing::{error, info, warn}; +use tsc_core::Command; + +use crate::foreground::Foreground; +use crate::host::EngineHost; +use crate::{bridge, capture, secrets}; + +/// Store setting (`bool`): the user's opt-in to local crash reports. +pub const CRASH_REPORTS_SETTING: &str = "crash_reports"; + +static HOST: OnceLock = OnceLock::new(); +static FOREGROUND: Mutex> = Mutex::new(None); + +fn host() -> anyhow::Result<&'static EngineHost> { + if let Some(host) = HOST.get() { + return Ok(host); + } + let host = EngineHost::start().context("starting the engine runtime")?; + Ok(HOST.get_or_init(|| host)) +} + +fn with_foreground(f: impl FnOnce(&mut Foreground) -> R) -> R { + let mut guard = FOREGROUND.lock().unwrap_or_else(PoisonError::into_inner); + f(guard.get_or_insert_with(Foreground::default)) +} + +/// The entry point android-activity looks up in this library. +#[allow(unsafe_code)] // an exported symbol +#[unsafe(no_mangle)] +fn android_main(app: AndroidApp) { + init_logging(); + info!("android_main"); + if let Err(e) = run(app) { + error!("{e:#}"); + } + info!("android_main done"); +} + +fn init_logging() { + // android-activity forwards stderr to logcat (tag RustStdoutStderr). + let filter = tracing_subscriber::EnvFilter::try_from_default_env() + .unwrap_or_else(|_| tracing_subscriber::EnvFilter::new("info")); + let _ = tracing_subscriber::fmt() + .with_env_filter(filter) + .with_ansi(false) + .without_time() + .with_writer(std::io::stderr) + .try_init(); +} + +fn run(app: AndroidApp) -> anyhow::Result<()> { + let data_dir = app.internal_data_path().context("the app has no internal storage path")?; + install_crash_reports(&data_dir); + jni::JavaVM::singleton()?.attach_current_thread(|env| -> jni::errors::Result<()> { + bridge::init(env)?; + // reqwest (HTTPS queries, tsclientlib) verifies certificates with + // the system's trust store through rustls-platform-verifier. + let context = bridge::context(env)?; + rustls_platform_verifier::android::init_with_env(env, context)?; + Ok(()) + })?; + let host = host()?; + static PROCESS: Once = Once::new(); + PROCESS.call_once(|| { + capture::register(); + watch_voice(host); + }); + if let Err(e) = bridge::request_permissions() { + warn!("requesting permissions: {e}"); + } + + slint::android::init(app).context("Slint Android backend")?; + let attached = host.attach(); + tsc_ui::run(tsc_ui::RunOptions { + data_dir: Some(data_dir), + secrets: Some(Box::new(secrets::KeystoreSecrets)), + engine: Some(tsc_ui::HostedEngine { + engine: attached.engine, + runtime: attached.runtime, + events: attached.events, + }), + }) +} + +/// Local crash reports in `/crash-reports`, recorded only if the +/// user opted in (off by default). +fn install_crash_reports(data_dir: &Path) { + tsc_platform::crash::set_app_version(env!("CARGO_PKG_VERSION")); + let enabled = tsc_store::Store::open(&data_dir.join("client.db")) + .ok() + .and_then(|store| store.setting::(CRASH_REPORTS_SETTING).ok().flatten()) + .unwrap_or(false); + tsc_platform::crash::install(data_dir.join(tsc_platform::crash::DIR_NAME), enabled); +} + +/// Keep the voice foreground service in step with the voice connections. +fn watch_voice(host: &'static EngineHost) { + let mut events = host.engine().subscribe(); + host.runtime().spawn(async move { + loop { + match events.recv().await { + Ok(event) => { + if let Some(notice) = with_foreground(|f| f.update(&event)) + && let Err(e) = bridge::set_voice_notification(notice.as_ref()) + { + warn!("voice service: {e}"); + } + } + Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => continue, + Err(tokio::sync::broadcast::error::RecvError::Closed) => break, + } + } + }); +} + +/// "Disconnect" in the voice notification. +pub fn disconnect_voice() { + let Some(host) = HOST.get() else { + return; + }; + for session in with_foreground(|f| f.voice_sessions()) { + host.engine().send(Command::DisconnectVoice { session }); + } +} + +/// "Mute" / "Unmute" in the voice notification: mute every voice session, +/// or unmute them all when all are muted. +pub fn toggle_mute() { + let Some(host) = HOST.get() else { + return; + }; + let (sessions, muted) = + with_foreground(|f| (f.voice_sessions(), f.notice().is_some_and(|n| n.muted))); + for session in sessions { + host.engine().send(Command::SetInputMuted { session, muted: !muted }); + } +} diff --git a/crates/tsc-android/src/bridge.rs b/crates/tsc-android/src/bridge.rs new file mode 100644 index 0000000..56e92d1 --- /dev/null +++ b/crates/tsc-android/src/bridge.rs @@ -0,0 +1,273 @@ +//! JNI glue with the app's Kotlin side (`android/app/src/main/java/...`). +//! +//! - Rust → Kotlin: static methods of `io.github.faumaray.tsc.Bridge`, called +//! from any thread (the class is looked up once on the `android_main` +//! thread, whose class loader sees the app's classes). +//! - Kotlin → Rust: the `external` methods of `io.github.faumaray.tsc.Native`, +//! exported below with `native_method!` (panics and errors become Java +//! exceptions instead of crossing the FFI boundary). + +use std::sync::OnceLock; + +use jni::errors::{Error, Result}; +use jni::objects::{JByteBuffer, JClass, JFloatArray, JObject, JString, JValue}; +use jni::refs::{Global, Reference as _}; +use jni::sys::{jboolean, jint, jlong}; +use jni::{Env, JavaVM, jni_sig, jni_str, native_method}; + +use crate::foreground::VoiceNotice; + +static BRIDGE: OnceLock>> = OnceLock::new(); + +/// Look up `Bridge` (on the `android_main` thread). +pub fn init(env: &mut Env) -> Result<()> { + if BRIDGE.get().is_none() { + let class = env.load_class(jni_str!("io.github.faumaray.tsc.Bridge"))?; + let _ = BRIDGE.set(env.new_global_ref(class)?); + } + Ok(()) +} + +/// Run `f` with an attached thread and the `Bridge` class. +fn with_bridge(f: impl FnOnce(&mut Env, &Global>) -> Result) -> Result { + let class = BRIDGE + .get() + .ok_or_else(|| Error::ClassNotFound { name: "io.github.faumaray.tsc.Bridge".into() })?; + JavaVM::singleton()?.attach_current_thread(|env| f(env, class)) +} + +/// The application `Context`, as a local reference of `env`'s frame. +pub fn context<'local>(env: &mut Env<'local>) -> Result> { + let class = BRIDGE + .get() + .ok_or_else(|| Error::ClassNotFound { name: "io.github.faumaray.tsc.Bridge".into() })?; + env.call_static_method( + class, + jni_str!("context"), + jni_sig!(() -> android.content.Context), + &[], + )? + .l() +} + +/// Ask for the microphone and notification permissions if not granted yet. +pub fn request_permissions() -> Result<()> { + with_bridge(|env, class| { + env.call_static_method(class, jni_str!("requestPermissions"), jni_sig!(() -> void), &[])?; + Ok(()) + }) +} + +/// Show or update the voice service's notification; `None` stops the service. +pub fn set_voice_notification(notice: Option<&VoiceNotice>) -> Result<()> { + with_bridge(|env, class| { + let (text, muted) = match notice { + Some(n) => (JObject::from(env.new_string(&n.text)?), n.muted), + None => (JObject::null(), false), + }; + env.call_static_method( + class, + jni_str!("setVoiceNotification"), + jni_sig!((text: java.lang.String, muted: jboolean) -> void), + &[JValue::Object(&text), JValue::Bool(muted)], + )?; + Ok(()) + }) +} + +/// Ask the user to share the screen. The answer comes back through +/// `Native.onScreenCaptureResult`. +pub fn request_screen_capture(fps: u32, max_size: u32) -> Result<()> { + with_bridge(|env, class| { + env.call_static_method( + class, + jni_str!("requestScreenCapture"), + jni_sig!((fps: jint, max_size: jint) -> void), + &[JValue::Int(fps as jint), JValue::Int(max_size as jint)], + )?; + Ok(()) + }) +} + +pub fn stop_screen_capture() -> Result<()> { + with_bridge(|env, class| { + env.call_static_method(class, jni_str!("stopScreenCapture"), jni_sig!(() -> void), &[])?; + Ok(()) + }) +} + +/// Capture what the device plays; `false` without a running screen capture. +pub fn start_system_audio() -> Result { + with_bridge(|env, class| { + env.call_static_method(class, jni_str!("startSystemAudio"), jni_sig!(() -> jboolean), &[])? + .z() + }) +} + +pub fn stop_system_audio() -> Result<()> { + with_bridge(|env, class| { + env.call_static_method(class, jni_str!("stopSystemAudio"), jni_sig!(() -> void), &[])?; + Ok(()) + }) +} + +pub fn secret_get(key: &str) -> Result> { + with_bridge(|env, class| { + let key = JObject::from(env.new_string(key)?); + let value = env + .call_static_method( + class, + jni_str!("secretGet"), + jni_sig!((key: java.lang.String) -> java.lang.String), + &[JValue::Object(&key)], + )? + .l()?; + if value.is_null() { + return Ok(None); + } + let value = env.cast_local::(value)?; + Ok(Some(value.try_to_string(env)?)) + }) +} + +pub fn secret_set(key: &str, value: &str) -> Result<()> { + with_bridge(|env, class| { + let key = JObject::from(env.new_string(key)?); + let value = JObject::from(env.new_string(value)?); + env.call_static_method( + class, + jni_str!("secretSet"), + jni_sig!((key: java.lang.String, value: java.lang.String) -> void), + &[JValue::Object(&key), JValue::Object(&value)], + )?; + Ok(()) + }) +} + +pub fn secret_delete(key: &str) -> Result<()> { + with_bridge(|env, class| { + let key = JObject::from(env.new_string(key)?); + env.call_static_method( + class, + jni_str!("secretDelete"), + jni_sig!((key: java.lang.String) -> void), + &[JValue::Object(&key)], + )?; + Ok(()) + }) +} + +// Native methods of `Native` (Kotlin `object` with `@JvmStatic external`). + +const _: jni::NativeMethod = native_method! { + java_type = "io.github.faumaray.tsc.Native", + static extern fn on_screen_capture_result(granted: jboolean, error: JString), +}; + +fn on_screen_capture_result<'local>( + env: &mut Env<'local>, + _class: JClass<'local>, + granted: jboolean, + error: JString<'local>, +) -> Result<()> { + let error = if error.is_null() { None } else { Some(error.try_to_string(env)?) }; + crate::capture::on_result(granted, error); + Ok(()) +} + +const _: jni::NativeMethod = native_method! { + java_type = "io.github.faumaray.tsc.Native", + static extern fn on_screen_frame( + pixels: JByteBuffer, + width: jint, + height: jint, + row_stride: jint, + timestamp_ns: jlong, + ) -> jboolean, +}; + +/// An RGBA frame from the `ImageReader`. Returns `false` when frames are no +/// longer wanted (the service then stops capturing). +fn on_screen_frame<'local>( + env: &mut Env<'local>, + _class: JClass<'local>, + pixels: JByteBuffer<'local>, + width: jint, + height: jint, + row_stride: jint, + timestamp_ns: jlong, +) -> Result { + if !crate::capture::wants_frames() { + return Ok(false); + } + let address = env.get_direct_buffer_address(&pixels)?; + let capacity = env.get_direct_buffer_capacity(&pixels)?; + if address.is_null() { + return Err(Error::NullPtr("screen frame buffer")); + } + // SAFETY: a direct buffer's memory is `capacity` bytes at `address`, and + // the `Image` it belongs to stays open until this call returns. + #[allow(unsafe_code)] + let bytes = unsafe { std::slice::from_raw_parts(address, capacity) }.to_vec(); + Ok(crate::capture::on_frame( + bytes, + width.max(0) as u32, + height.max(0) as u32, + row_stride.max(0) as usize, + timestamp_ns, + )) +} + +const _: jni::NativeMethod = native_method! { + java_type = "io.github.faumaray.tsc.Native", + static extern fn on_screen_capture_stopped(), +}; + +fn on_screen_capture_stopped<'local>(_env: &mut Env<'local>, _class: JClass<'local>) -> Result<()> { + crate::capture::on_stopped(); + Ok(()) +} + +const _: jni::NativeMethod = native_method! { + java_type = "io.github.faumaray.tsc.Native", + static extern fn on_system_audio(samples: jfloat[], count: jint, channels: jint, timestamp_ns: jlong) -> jboolean, +}; + +/// Interleaved 48 kHz float samples of what the device plays. +fn on_system_audio<'local>( + env: &mut Env<'local>, + _class: JClass<'local>, + samples: JFloatArray<'local>, + count: jint, + channels: jint, + timestamp_ns: jlong, +) -> Result { + if !crate::capture::wants_audio() { + return Ok(false); + } + let mut buffer = vec![0f32; count.max(0) as usize]; + samples.get_region(env, 0, &mut buffer)?; + Ok(crate::capture::on_audio(buffer, channels.clamp(1, 8) as u16, timestamp_ns)) +} + +const _: jni::NativeMethod = native_method! { + java_type = "io.github.faumaray.tsc.Native", + static extern fn on_disconnect_voice(), +}; + +/// "Disconnect" in the voice notification. +fn on_disconnect_voice<'local>(_env: &mut Env<'local>, _class: JClass<'local>) -> Result<()> { + crate::app::disconnect_voice(); + Ok(()) +} + +const _: jni::NativeMethod = native_method! { + java_type = "io.github.faumaray.tsc.Native", + static extern fn on_toggle_mute(), +}; + +/// "Mute" / "Unmute" in the voice notification. +fn on_toggle_mute<'local>(_env: &mut Env<'local>, _class: JClass<'local>) -> Result<()> { + crate::app::toggle_mute(); + Ok(()) +} diff --git a/crates/tsc-android/src/capture.rs b/crates/tsc-android/src/capture.rs new file mode 100644 index 0000000..a73caa3 --- /dev/null +++ b/crates/tsc-android/src/capture.rs @@ -0,0 +1,216 @@ +//! Screen and system-audio capture through MediaProjection. +//! +//! Registered as `tsc_media` capture providers, so stream code captures with +//! `tsc_media::capture::default_screen_capture()` as on desktop. Starting +//! asks the Kotlin side for the user's consent; on consent it runs +//! `ScreenCaptureService` (a `mediaProjection` foreground service) whose +//! `ImageReader` hands RGBA frames to [`on_frame`]. System audio +//! (`AudioPlaybackCapture`, 48 kHz float) needs that running projection. + +use std::sync::{Arc, Mutex, MutexGuard, PoisonError}; +use std::time::Duration; + +use tokio::sync::oneshot; +use tracing::warn; +use tsc_media::capture::external::{self, AudioProvider, ScreenProvider}; +use tsc_media::capture::{BoxFuture, CaptureOptions, CaptureSource, SourceId}; +use tsc_media::{AudioBuffer, Error, FrameSender, Result, VideoFrame}; + +use crate::bridge; + +const SCREEN: &str = "mediaprojection"; +const AUDIO: &str = "playbackcapture"; +/// Longest side of captured frames (the service scales the display down). +const MAX_SIZE: u32 = 1920; + +#[derive(Default)] +struct State { + frames: Option>, + /// Answer for the pending `start`. + pending: Option>>, + audio: Option>, + /// Clock origin of frame and audio timestamps (both `CLOCK_MONOTONIC` + /// nanoseconds: `Image.timestamp`, `System.nanoTime`), so they stay in sync. + origin_ns: Option, +} + +static STATE: Mutex> = Mutex::new(None); + +fn with_state(f: impl FnOnce(&mut State) -> R) -> R { + let mut guard: MutexGuard<'_, Option> = + STATE.lock().unwrap_or_else(PoisonError::into_inner); + f(guard.get_or_insert_with(State::default)) +} + +/// Make MediaProjection the default screen and audio capture. +pub fn register() { + external::set_screen_provider(Some(Arc::new(Projection))); + external::set_audio_provider(Some(Arc::new(PlaybackAudio))); +} + +fn since(first: &mut Option, now_ns: i64) -> Duration { + let first = *first.get_or_insert(now_ns); + Duration::from_nanos(u64::try_from(now_ns - first).unwrap_or(0)) +} + +struct Projection; + +impl ScreenProvider for Projection { + fn name(&self) -> &'static str { + SCREEN + } + + fn sources(&self) -> Vec { + vec![CaptureSource { + // The system dialog picks (whole screen, or one app on Android 14+). + id: SourceId::Portal, + name: "Screen".into(), + width: 0, + height: 0, + primary: true, + }] + } + + fn start( + &self, + _source: &SourceId, + options: &CaptureOptions, + frames: FrameSender, + ) -> BoxFuture<'static, Result<()>> { + let (tx, rx) = oneshot::channel(); + with_state(|s| { + if let Some(previous) = s.pending.replace(tx) { + let _ = previous.send(Err(Error::Cancelled)); + } + s.frames = Some(frames); + s.origin_ns = None; + }); + if let Err(e) = bridge::request_screen_capture(options.fps.clamp(1, 60), MAX_SIZE) { + with_state(|s| { + s.pending = None; + s.frames = None; + }); + let error = Error::CaptureUnavailable { backend: SCREEN, reason: e.to_string() }; + return Box::pin(async move { Err(error) }); + } + Box::pin(async move { rx.await.unwrap_or(Err(Error::Cancelled)) }) + } + + fn stop(&self) { + on_stopped(); + if let Err(e) = bridge::stop_screen_capture() { + warn!("stopping screen capture: {e}"); + } + } +} + +struct PlaybackAudio; + +impl AudioProvider for PlaybackAudio { + fn name(&self) -> &'static str { + AUDIO + } + + fn start(&self, buffers: FrameSender) -> Result<()> { + with_state(|s| { + s.audio = Some(buffers); + }); + let started = bridge::start_system_audio(); + match started { + Ok(true) => Ok(()), + Ok(false) | Err(_) => { + with_state(|s| s.audio = None); + let reason = match started { + Err(e) => e.to_string(), + _ => "needs a running screen capture (and the microphone permission)".into(), + }; + Err(Error::CaptureUnavailable { backend: AUDIO, reason }) + } + } + } + + fn stop(&self) { + with_state(|s| s.audio = None); + if let Err(e) = bridge::stop_system_audio() { + warn!("stopping system audio: {e}"); + } + } +} + +/// The user answered the consent dialog (or the service failed to start). +pub fn on_result(granted: bool, error: Option) { + with_state(|s| { + let result = match (granted, error) { + (true, _) => Ok(()), + (false, None) => Err(Error::Cancelled), + (false, Some(message)) => Err(Error::Capture { backend: SCREEN, message }), + }; + if result.is_err() { + s.frames = None; + } + if let Some(pending) = s.pending.take() { + let _ = pending.send(result); + } + }); +} + +pub fn wants_frames() -> bool { + with_state(|s| s.frames.as_ref().is_some_and(|f| !f.is_closed())) +} + +/// A captured RGBA frame. Returns `false` once nobody wants frames. +pub fn on_frame( + pixels: Vec, + width: u32, + height: u32, + stride: usize, + timestamp_ns: i64, +) -> bool { + with_state(|s| { + let timestamp = since(&mut s.origin_ns, timestamp_ns); + let Some(frames) = &s.frames else { + return false; + }; + match VideoFrame::from_rgba(width, height, stride, pixels) { + Ok(frame) => { + if !frames.send(frame.with_timestamp(timestamp)) { + s.frames = None; + return false; + } + } + Err(e) => warn!("dropping a screen frame: {e}"), + } + true + }) +} + +/// The projection ended (stopped by us, the user, or the system): the +/// consumers see their channels close. +pub fn on_stopped() { + with_state(|s| { + s.frames = None; + s.audio = None; + if let Some(pending) = s.pending.take() { + let _ = pending.send(Err(Error::Cancelled)); + } + }); +} + +pub fn wants_audio() -> bool { + with_state(|s| s.audio.as_ref().is_some_and(|a| !a.is_closed())) +} + +/// Captured playback audio. Returns `false` once nobody wants it. +pub fn on_audio(samples: Vec, channels: u16, timestamp_ns: i64) -> bool { + with_state(|s| { + let timestamp = since(&mut s.origin_ns, timestamp_ns); + let Some(audio) = &s.audio else { + return false; + }; + if !audio.send(AudioBuffer { samples, channels, timestamp }) { + s.audio = None; + return false; + } + true + }) +} diff --git a/crates/tsc-android/src/foreground.rs b/crates/tsc-android/src/foreground.rs new file mode 100644 index 0000000..a1c376c --- /dev/null +++ b/crates/tsc-android/src/foreground.rs @@ -0,0 +1,132 @@ +//! When the app needs its voice foreground service. +//! +//! Android keeps the microphone and the process of a backgrounded app only +//! while a foreground service with a visible notification runs. The service +//! runs while any session has a voice connection (connecting or connected); +//! its notification names the servers and offers Mute and Disconnect. + +use std::collections::BTreeMap; + +use tsc_core::{Event, SessionId, VoiceState}; + +/// What the voice notification shows. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct VoiceNotice { + pub text: String, + /// The microphone is muted in every voice session (the action unmutes). + pub muted: bool, +} + +#[derive(Default)] +pub struct Foreground { + sessions: BTreeMap, +} + +#[derive(Default)] +struct Session { + name: Option, + voice: VoiceState, + muted: bool, +} + +impl Foreground { + /// Apply `event`. Returns the new notification when it changed: + /// `Some(None)` means the service should stop. + pub fn update(&mut self, event: &Event) -> Option> { + let before = self.notice(); + match event { + Event::State { session, state } => { + let s = self.sessions.entry(*session).or_default(); + s.voice = state.voice; + s.muted = state.input_muted; + } + Event::ServerInfo { session, name, .. } => { + self.sessions.entry(*session).or_default().name = Some(name.clone()); + } + _ => return None, + } + let after = self.notice(); + (after != before).then_some(after) + } + + fn active(&self) -> impl Iterator { + self.sessions.iter().filter(|(_, s)| s.voice != VoiceState::Disconnected) + } + + /// Sessions with a voice connection (for the notification's actions). + pub fn voice_sessions(&self) -> Vec { + self.active().map(|(id, _)| *id).collect() + } + + /// The notification, `None` without voice. + pub fn notice(&self) -> Option { + let active: Vec<&Session> = self.active().map(|(_, s)| s).collect(); + if active.is_empty() { + return None; + } + let names: Vec<&str> = + active.iter().map(|s| s.name.as_deref().unwrap_or("a server")).collect(); + let names = names.join(", "); + let text = if active.iter().all(|s| s.voice == VoiceState::Connecting) { + format!("Connecting to {names}") + } else { + format!("In voice on {names}") + }; + Some(VoiceNotice { text, muted: active.iter().all(|s| s.muted) }) + } +} + +#[cfg(test)] +mod tests { + use tsc_core::SessionState; + use tsc_model::{Capabilities, ServerFlavor}; + + use super::*; + + fn voice(session: SessionId, voice: VoiceState, input_muted: bool) -> Event { + Event::State { + session, + state: SessionState { voice, input_muted, ..SessionState::default() }, + } + } + + fn notice(text: &str, muted: bool) -> Option> { + Some(Some(VoiceNotice { text: text.into(), muted })) + } + + #[test] + fn service_follows_voice_connections() { + let mut fg = Foreground::default(); + assert_eq!(fg.update(&voice(1, VoiceState::Disconnected, false)), None); + assert_eq!( + fg.update(&voice(1, VoiceState::Connecting, false)), + notice("Connecting to a server", false) + ); + let info = Event::ServerInfo { + session: 1, + name: "Home".into(), + flavor: ServerFlavor::Unknown(String::new()), + capabilities: Capabilities::default(), + }; + assert_eq!(fg.update(&info), notice("Connecting to Home", false)); + assert_eq!( + fg.update(&voice(1, VoiceState::Connected, false)), + notice("In voice on Home", false) + ); + assert_eq!(fg.update(&voice(1, VoiceState::Connected, false)), None, "no change"); + assert_eq!( + fg.update(&voice(1, VoiceState::Connected, true)), + notice("In voice on Home", true) + ); + // A second session that is not muted: the action mutes both. + assert_eq!( + fg.update(&voice(2, VoiceState::Connecting, false)), + notice("In voice on Home, a server", false) + ); + assert_eq!(fg.voice_sessions(), [1, 2]); + assert_eq!(fg.update(&Event::Error { session: 1, message: "x".into() }), None); + fg.update(&voice(2, VoiceState::Disconnected, false)); + assert_eq!(fg.update(&voice(1, VoiceState::Disconnected, true)), Some(None)); + assert!(fg.voice_sessions().is_empty()); + } +} diff --git a/crates/tsc-android/src/host.rs b/crates/tsc-android/src/host.rs new file mode 100644 index 0000000..a2117b5 --- /dev/null +++ b/crates/tsc-android/src/host.rs @@ -0,0 +1,314 @@ +//! The engine for the whole process. +//! +//! Android destroys and recreates the activity (and so the window and its +//! thread) while a voice call goes on in a foreground service. The engine +//! therefore lives here, on its own runtime, for as long as the process; a +//! new window [attaches](EngineHost::attach) and first receives events that +//! rebuild the current state ([`Replay`]), then the live ones. + +use std::collections::{BTreeMap, VecDeque}; +use std::sync::{Arc, Mutex, MutexGuard, PoisonError}; + +use tokio::runtime::{Handle, Runtime}; +use tokio::sync::{broadcast, mpsc}; +use tsc_core::{Engine, Event, SessionId, StreamState, WatchState}; + +/// Chat messages per session a new window gets back. +pub const CHAT_BACKLOG: usize = 300; + +/// The latest state-bearing events per session. +#[derive(Default)] +pub struct Replay { + sessions: BTreeMap, +} + +#[derive(Default)] +struct SessionReplay { + server_info: Option, + state: Option, + presence: Option, + streams: Option, + own_stream: Option, + viewers: Option, + watching: BTreeMap, + chat: VecDeque, +} + +impl Replay { + /// Remember what `event` changes. + pub fn record(&mut self, event: &Event) { + let session = match event { + Event::State { session, .. } + | Event::ServerInfo { session, .. } + | Event::Presence { session, .. } + | Event::Chat { session, .. } + | Event::StreamsChanged { session, .. } + | Event::StreamState { session, .. } + | Event::StreamViewers { session, .. } + | Event::WatchState { session, .. } => *session, + // Transient: talking flags, errors, requests, keyframe requests. + _ => return, + }; + let s = self.sessions.entry(session).or_default(); + let slot = Some(event.clone()); + match event { + Event::State { .. } => s.state = slot, + Event::ServerInfo { .. } => s.server_info = slot, + Event::Presence { .. } => s.presence = slot, + Event::StreamsChanged { .. } => s.streams = slot, + Event::StreamViewers { .. } => s.viewers = slot, + Event::StreamState { state, .. } => { + if matches!(state, StreamState::Ended(_)) { + s.own_stream = None; + s.viewers = None; + } else { + s.own_stream = slot; + } + } + Event::WatchState { stream_id, state, .. } => { + if matches!(state, WatchState::Ended(_)) { + s.watching.remove(stream_id); + } else { + s.watching.insert(stream_id.clone(), event.clone()); + } + } + Event::Chat { .. } => { + if s.chat.len() == CHAT_BACKLOG { + s.chat.pop_front(); + } + s.chat.push_back(event.clone()); + } + _ => {} + } + } + + /// Events that rebuild the recorded state, per session: server info, + /// state, presence, chat, then streams. + pub fn events(&self) -> Vec { + let mut out = Vec::new(); + for s in self.sessions.values() { + out.extend(s.server_info.iter().cloned()); + out.extend(s.state.iter().cloned()); + out.extend(s.presence.iter().cloned()); + out.extend(s.chat.iter().cloned()); + out.extend(s.streams.iter().cloned()); + out.extend(s.own_stream.iter().cloned()); + out.extend(s.viewers.iter().cloned()); + out.extend(s.watching.values().cloned()); + } + out + } +} + +/// Events of one source, recorded and passed on to the attached window. +#[derive(Clone, Default)] +pub struct Fanout { + shared: Arc>, +} + +#[derive(Default)] +struct FanoutState { + replay: Replay, + window: Option>, +} + +impl Fanout { + fn lock(&self) -> MutexGuard<'_, FanoutState> { + self.shared.lock().unwrap_or_else(PoisonError::into_inner) + } + + /// Record `event` and pass it to the window, if one is attached. + pub fn publish(&self, event: Event) { + let mut state = self.lock(); + state.replay.record(&event); + if let Some(window) = &state.window + && window.send(event).is_err() + { + state.window = None; + } + } + + /// Receive events from now on, starting with the replay. A previously + /// attached window stops receiving (its channel closes). + pub fn attach(&self) -> mpsc::UnboundedReceiver { + let (tx, rx) = mpsc::unbounded_channel(); + let mut state = self.lock(); + for event in state.replay.events() { + let _ = tx.send(event); + } + state.window = Some(tx); + rx + } + + /// Forward `source` until it closes; then the window's channel closes. + pub async fn pump(self, mut source: broadcast::Receiver) { + loop { + match source.recv().await { + Ok(event) => self.publish(event), + Err(broadcast::error::RecvError::Lagged(n)) => { + tracing::warn!(missed = n, "engine events lagged"); + } + Err(broadcast::error::RecvError::Closed) => break, + } + } + self.lock().window = None; + } +} + +/// The process's engine, runtime and event fan-out. +pub struct EngineHost { + runtime: Runtime, + engine: Engine, + fanout: Fanout, +} + +/// What a window needs: see `tsc_ui::HostedEngine`. +pub struct Attached { + pub engine: Engine, + pub runtime: Handle, + pub events: mpsc::UnboundedReceiver, +} + +impl EngineHost { + pub fn start() -> std::io::Result { + let runtime = tokio::runtime::Builder::new_multi_thread() + .enable_all() + .thread_name("tsc-engine") + .build()?; + let engine = runtime.block_on(async { Engine::start() }); + let fanout = Fanout::default(); + runtime.spawn(fanout.clone().pump(engine.subscribe())); + Ok(Self { runtime, engine, fanout }) + } + + pub fn engine(&self) -> &Engine { + &self.engine + } + + pub fn runtime(&self) -> &Handle { + self.runtime.handle() + } + + /// Hand the engine to a new window. + pub fn attach(&self) -> Attached { + Attached { + engine: self.engine.clone(), + runtime: self.runtime.handle().clone(), + events: self.fanout.attach(), + } + } +} + +#[cfg(test)] +mod tests { + use std::sync::Arc as StdArc; + + use tsc_core::{SessionState, VoiceState}; + use tsc_model::{ChatMessage, ChatTarget, Presence}; + + use super::*; + + fn state(session: SessionId, voice: VoiceState) -> Event { + Event::State { session, state: SessionState { voice, ..SessionState::default() } } + } + + fn chat(session: SessionId, text: &str) -> Event { + Event::Chat { + session, + message: ChatMessage { + target: ChatTarget::Server, + author_name: "a".into(), + author_uid: None, + author_id: None, + text: text.into(), + ts_ms: 0, + via_relay: false, + }, + } + } + + fn describe(events: &[Event]) -> Vec { + events + .iter() + .map(|e| match e { + Event::State { session, state } => format!("{session} state {:?}", state.voice), + Event::Presence { session, .. } => format!("{session} presence"), + Event::Chat { session, message } => format!("{session} chat {}", message.text), + Event::WatchState { session, stream_id, .. } => { + format!("{session} watch {stream_id}") + } + other => format!("{other:?}"), + }) + .collect() + } + + #[test] + fn replay_keeps_the_latest_state_and_the_chat_backlog() { + let mut replay = Replay::default(); + replay.record(&state(2, VoiceState::Connecting)); + replay.record(&Event::Presence { session: 2, presence: StdArc::new(Presence::default()) }); + replay.record(&state(2, VoiceState::Connected)); + replay.record(&Event::Talking { session: 2, client: 5, talking: true }); + replay.record(&Event::Error { session: 2, message: "x".into() }); + for i in 0..CHAT_BACKLOG + 2 { + replay.record(&chat(1, &i.to_string())); + } + replay.record(&Event::WatchState { + session: 2, + stream_id: "s1".into(), + state: WatchState::Connected, + }); + replay.record(&Event::WatchState { + session: 2, + stream_id: "s2".into(), + state: WatchState::Requested, + }); + replay.record(&Event::WatchState { + session: 2, + stream_id: "s2".into(), + state: WatchState::Ended(tsc_core::stream::EndReason::Local), + }); + + let events = describe(&replay.events()); + assert_eq!(events.len(), CHAT_BACKLOG + 3); + assert_eq!(events[0], "1 chat 2", "the oldest messages are dropped"); + assert_eq!(events[CHAT_BACKLOG - 1], format!("1 chat {}", CHAT_BACKLOG + 1)); + assert_eq!( + events[CHAT_BACKLOG..], + ["2 state Connected", "2 presence", "2 watch s1"].map(String::from) + ); + } + + #[tokio::test] + async fn a_new_window_gets_the_replay_then_live_events() { + let (tx, rx) = broadcast::channel(16); + let fanout = Fanout::default(); + let pump = tokio::spawn(fanout.clone().pump(rx)); + + tx.send(state(1, VoiceState::Connected)).unwrap(); + tx.send(chat(1, "before")).unwrap(); + tokio::task::yield_now().await; + while fanout.lock().replay.events().len() < 2 { + tokio::task::yield_now().await; + } + + let mut first = fanout.attach(); + assert_eq!(describe(&[first.recv().await.unwrap()]), ["1 state Connected"]); + assert_eq!(describe(&[first.recv().await.unwrap()]), ["1 chat before"]); + tx.send(chat(1, "live")).unwrap(); + assert_eq!(describe(&[first.recv().await.unwrap()]), ["1 chat live"]); + + // The activity is recreated: the old window's channel ends. + let mut second = fanout.attach(); + assert!(first.recv().await.is_none()); + let mut replayed = Vec::new(); + for _ in 0..3 { + replayed.push(second.recv().await.unwrap()); + } + assert_eq!(describe(&replayed), ["1 state Connected", "1 chat before", "1 chat live"]); + + drop(tx); + pump.await.unwrap(); + assert!(second.recv().await.is_none(), "the source closed"); + } +} diff --git a/crates/tsc-android/src/lib.rs b/crates/tsc-android/src/lib.rs new file mode 100644 index 0000000..dcd1198 --- /dev/null +++ b/crates/tsc-android/src/lib.rs @@ -0,0 +1,30 @@ +//! The Android app's native library (`libtsc_android.so`). +//! +//! The APK (`android/`) starts a `NativeActivity` subclass that loads this +//! library; `android_main` then runs the shared Slint UI (`tsc_ui`) on +//! Slint's Android backend. The pieces around it: +//! +//! - [`host`]: one engine per process, so voice survives the activity being +//! destroyed and recreated; a new window gets the current state replayed +//! - [`foreground`]: when the voice foreground service must run (Android +//! only lets a service with a notification keep the microphone in the +//! background) +//! - `bridge` (Android): JNI calls into the Kotlin side (`Bridge`) and the +//! native methods it calls back (`Native`) +//! - `capture` (Android): screen and system-audio capture through +//! MediaProjection, registered as `tsc_media` capture providers +//! - `secrets` (Android): passwords encrypted with an Android Keystore key +//! +//! Only [`host`] and [`foreground`] build on other platforms, for tests. + +pub mod foreground; +pub mod host; + +#[cfg(target_os = "android")] +mod app; +#[cfg(target_os = "android")] +mod bridge; +#[cfg(target_os = "android")] +mod capture; +#[cfg(target_os = "android")] +mod secrets; diff --git a/crates/tsc-android/src/secrets.rs b/crates/tsc-android/src/secrets.rs new file mode 100644 index 0000000..ccdb032 --- /dev/null +++ b/crates/tsc-android/src/secrets.rs @@ -0,0 +1,29 @@ +//! Passwords in the Android Keystore. +//! +//! The Kotlin `SecretStore` encrypts each value with an AES-GCM key that +//! lives in the Android Keystore (hardware-backed where the device has it) +//! and keeps the ciphertext in the app's private preferences. + +use tsc_store::{Error, Result, Secrets}; + +use crate::bridge; + +pub struct KeystoreSecrets; + +fn error(e: jni::errors::Error) -> Error { + Error::Secrets(format!("Android Keystore: {e}")) +} + +impl Secrets for KeystoreSecrets { + fn get(&self, key: &str) -> Result> { + bridge::secret_get(key).map_err(error) + } + + fn set(&self, key: &str, value: &str) -> Result<()> { + bridge::secret_set(key, value).map_err(error) + } + + fn delete(&self, key: &str) -> Result<()> { + bridge::secret_delete(key).map_err(error) + } +} diff --git a/crates/tsc-media/Cargo.toml b/crates/tsc-media/Cargo.toml index 2e9cb5e..427736f 100644 --- a/crates/tsc-media/Cargo.toml +++ b/crates/tsc-media/Cargo.toml @@ -47,6 +47,9 @@ pipewire = { version = "0.10.1", optional = true } rustix = { version = "1.1.5", features = ["fs"], optional = true } x11rb = { version = "0.13.2", features = ["randr", "shm", "xfixes"], optional = true } +[target.'cfg(target_os = "android")'.dependencies] +ndk = { version = "0.9.0", default-features = false, features = ["media", "api-level-29"] } + [target.'cfg(windows)'.dependencies] wasapi = "0.24.0" windows-capture = "2.0.1" diff --git a/crates/tsc-media/src/capture/external.rs b/crates/tsc-media/src/capture/external.rs new file mode 100644 index 0000000..be60731 --- /dev/null +++ b/crates/tsc-media/src/capture/external.rs @@ -0,0 +1,274 @@ +//! Capture driven by platform code outside this crate. +//! +//! On Android, screen and system-audio capture need a MediaProjection, which +//! only the app's Java/Kotlin side can obtain (it asks the user and runs a +//! foreground service). The app registers a [`ScreenProvider`] and an +//! [`AudioProvider`] at start; [`super::default_screen_capture`] and +//! [`super::default_audio_capture`] then hand out capture backends that +//! forward to them, so stream code needs no platform knowledge. +//! +//! A provider receives the [`FrameSender`] of the capture and pushes frames +//! into it from any thread; dropping the sender ends the capture for the +//! consumer (e.g. when the user stops sharing from the system UI). + +use std::sync::{Arc, Mutex, PoisonError}; + +use crate::Result; +use crate::capture::{ + AudioCapture, BoxFuture, CaptureOptions, CaptureSource, ScreenCapture, SourceId, +}; +use crate::frame::{AudioBuffer, VideoFrame}; +use crate::queue::{FrameReceiver, FrameSender, frame_channel}; + +/// Platform code that captures the screen. +pub trait ScreenProvider: Send + Sync { + /// Short name for logs (`"mediaprojection"`). + fn name(&self) -> &'static str; + + /// What can be captured (Android: the whole screen, as one + /// [`SourceId::Portal`] entry since the system dialog picks). + fn sources(&self) -> Vec; + + /// Start delivering frames into `frames`. Resolves once frames flow, or + /// with an error such as [`crate::Error::Cancelled`] when the user + /// declined. + fn start( + &self, + source: &SourceId, + options: &CaptureOptions, + frames: FrameSender, + ) -> BoxFuture<'static, Result<()>>; + + fn stop(&self); +} + +/// Platform code that captures what the device plays (48 kHz `f32`). +pub trait AudioProvider: Send + Sync { + fn name(&self) -> &'static str; + + /// Start delivering audio into `buffers`. + fn start(&self, buffers: FrameSender) -> Result<()>; + + fn stop(&self); +} + +type Slot = Mutex>>; + +static SCREEN: Slot = Mutex::new(None); +static AUDIO: Slot = Mutex::new(None); + +fn get(slot: &Slot) -> Option> { + slot.lock().unwrap_or_else(PoisonError::into_inner).clone() +} + +/// Make [`super::default_screen_capture`] use `provider` (`None` restores +/// the built-in backends). +pub fn set_screen_provider(provider: Option>) { + *SCREEN.lock().unwrap_or_else(PoisonError::into_inner) = provider; +} + +/// Make [`super::default_audio_capture`] use `provider`. +pub fn set_audio_provider(provider: Option>) { + *AUDIO.lock().unwrap_or_else(PoisonError::into_inner) = provider; +} + +pub fn screen_provider() -> Option> { + get(&SCREEN) +} + +pub fn audio_provider() -> Option> { + get(&AUDIO) +} + +/// A [`ScreenCapture`] backed by a [`ScreenProvider`]. +pub struct ExternalScreenCapture { + provider: Arc, + running: bool, +} + +impl ExternalScreenCapture { + pub fn new(provider: Arc) -> Self { + Self { provider, running: false } + } +} + +impl ScreenCapture for ExternalScreenCapture { + fn backend(&self) -> &'static str { + self.provider.name() + } + + fn sources(&mut self) -> Result> { + Ok(self.provider.sources()) + } + + fn start( + &mut self, + source: &SourceId, + options: &CaptureOptions, + ) -> BoxFuture<'_, Result>> { + self.stop(); + let (tx, rx) = frame_channel(options.queue); + let started = self.provider.start(source, options, tx); + self.running = true; + Box::pin(async move { + started.await?; + Ok(rx) + }) + } + + fn stop(&mut self) { + if std::mem::take(&mut self.running) { + self.provider.stop(); + } + } +} + +impl Drop for ExternalScreenCapture { + fn drop(&mut self) { + self.stop(); + } +} + +/// An [`AudioCapture`] backed by an [`AudioProvider`]. +pub struct ExternalAudioCapture { + provider: Arc, + running: bool, +} + +impl ExternalAudioCapture { + pub fn new(provider: Arc) -> Self { + Self { provider, running: false } + } +} + +impl AudioCapture for ExternalAudioCapture { + fn backend(&self) -> &'static str { + self.provider.name() + } + + fn start(&mut self) -> Result> { + self.stop(); + // About a second of 10 ms buffers. + let (tx, rx) = frame_channel(100); + self.provider.start(tx)?; + self.running = true; + Ok(rx) + } + + fn stop(&mut self) { + if std::mem::take(&mut self.running) { + self.provider.stop(); + } + } +} + +impl Drop for ExternalAudioCapture { + fn drop(&mut self) { + self.stop(); + } +} + +#[cfg(test)] +mod tests { + use std::sync::atomic::{AtomicUsize, Ordering}; + use std::time::Duration; + + use super::*; + use crate::Error; + + /// Sends one frame per start, or refuses. + #[derive(Default)] + struct Fake { + refuse: bool, + stops: AtomicUsize, + sender: Mutex>>, + } + + impl ScreenProvider for Fake { + fn name(&self) -> &'static str { + "fake" + } + + fn sources(&self) -> Vec { + vec![CaptureSource { + id: SourceId::Portal, + name: "Screen".into(), + width: 0, + height: 0, + primary: true, + }] + } + + fn start( + &self, + _: &SourceId, + _: &CaptureOptions, + frames: FrameSender, + ) -> BoxFuture<'static, Result<()>> { + if self.refuse { + return Box::pin(async { Err(Error::Cancelled) }); + } + frames.send(VideoFrame::black_i420(4, 4)); + *self.sender.lock().unwrap() = Some(frames); + Box::pin(async { Ok(()) }) + } + + fn stop(&self) { + self.stops.fetch_add(1, Ordering::Relaxed); + self.sender.lock().unwrap().take(); + } + } + + #[tokio::test] + async fn frames_flow_until_the_provider_drops_the_sender() { + let fake = Arc::new(Fake::default()); + let mut capture = ExternalScreenCapture::new(fake.clone()); + assert_eq!(capture.backend(), "fake"); + assert_eq!(capture.sources().unwrap().len(), 1); + let mut rx = capture.start(&SourceId::Portal, &CaptureOptions::default()).await.unwrap(); + assert_eq!(rx.recv().await.unwrap().width, 4); + // The system stopped the projection. + fake.sender.lock().unwrap().take(); + assert!(rx.recv_timeout(Duration::from_millis(10)).is_none()); + assert!(rx.is_closed()); + drop(capture); + assert_eq!(fake.stops.load(Ordering::Relaxed), 1); + } + + #[tokio::test] + async fn refusal_is_an_error_and_stop_is_not_repeated() { + let fake = Arc::new(Fake { refuse: true, ..Fake::default() }); + let mut capture = ExternalScreenCapture::new(fake.clone()); + let result = capture.start(&SourceId::Portal, &CaptureOptions::default()).await; + assert!(matches!(result, Err(Error::Cancelled))); + capture.stop(); + capture.stop(); + assert_eq!(fake.stops.load(Ordering::Relaxed), 1); + } + + #[test] + fn registered_provider_is_the_default() { + struct Silent; + impl AudioProvider for Silent { + fn name(&self) -> &'static str { + "silent" + } + fn start(&self, buffers: FrameSender) -> Result<()> { + buffers.send(AudioBuffer { + samples: vec![0.0; 960], + channels: 2, + timestamp: Duration::ZERO, + }); + Ok(()) + } + fn stop(&self) {} + } + set_audio_provider(Some(Arc::new(Silent))); + let mut capture = crate::capture::default_audio_capture().unwrap(); + assert_eq!(capture.backend(), "silent"); + let mut rx = capture.start().unwrap(); + assert_eq!(rx.try_recv().unwrap().frames(), 480); + set_audio_provider(None); + assert!(audio_provider().is_none()); + } +} diff --git a/crates/tsc-media/src/capture/mod.rs b/crates/tsc-media/src/capture/mod.rs index 4264192..2717fb9 100644 --- a/crates/tsc-media/src/capture/mod.rs +++ b/crates/tsc-media/src/capture/mod.rs @@ -9,6 +9,7 @@ //! | `x11` (Linux, feature `x11`) | MIT-SHM / GetImage, XFixes cursor | | //! | `portal` / `pipewire_audio` (Linux, feature `pipewire`) | ScreenCast portal + PipeWire | default sink monitor | //! | `windows` | Windows Graphics Capture | WASAPI process loopback | +//! | [`external`] | platform code (Android MediaProjection) | same | use std::future::Future; use std::pin::Pin; @@ -21,6 +22,7 @@ use crate::frame::{AudioBuffer, VideoFrame}; use crate::queue::FrameReceiver; use crate::{Error, Result}; +pub mod external; #[cfg(all(target_os = "linux", feature = "pipewire"))] pub mod pipewire_audio; #[cfg(all(target_os = "linux", feature = "pipewire"))] @@ -106,9 +108,13 @@ pub trait AudioCapture: Send { fn stop(&mut self); } -/// The screen capture backend for this session: the ScreenCast portal on +/// The screen capture backend for this session: a registered +/// [`external::ScreenProvider`] (Android), else the ScreenCast portal on /// Wayland, X11 otherwise on Linux, Windows Graphics Capture on Windows. pub fn default_screen_capture() -> Result> { + if let Some(provider) = external::screen_provider() { + return Ok(Box::new(external::ExternalScreenCapture::new(provider))); + } #[cfg(target_os = "linux")] { let wayland = std::env::var_os("WAYLAND_DISPLAY").is_some() @@ -132,8 +138,12 @@ pub fn default_screen_capture() -> Result> { }) } -/// The system-audio backend: PipeWire on Linux, WASAPI loopback on Windows. +/// The system-audio backend: a registered [`external::AudioProvider`] +/// (Android), else PipeWire on Linux, WASAPI loopback on Windows. pub fn default_audio_capture() -> Result> { + if let Some(provider) = external::audio_provider() { + return Ok(Box::new(external::ExternalAudioCapture::new(provider))); + } #[cfg(all(target_os = "linux", feature = "pipewire"))] return Ok(Box::new(pipewire_audio::PipeWireAudioCapture::new())); #[cfg(windows)] diff --git a/crates/tsc-media/src/codec/hw.rs b/crates/tsc-media/src/codec/hw.rs index da24495..5d26b17 100644 --- a/crates/tsc-media/src/codec/hw.rs +++ b/crates/tsc-media/src/codec/hw.rs @@ -7,6 +7,7 @@ //! through `cros-libva`. TODO. //! - Windows: Media Foundation H.264 encoder MFT (NVENC / QuickSync / AMF //! behind it). TODO. +//! - Android: MediaCodec ([`super::mediacodec`]). use crate::Result; use crate::codec::{Codec, EncoderConfig, VideoEncoder}; @@ -33,6 +34,10 @@ pub fn probe() -> Vec> { if let Some(f) = media_foundation::probe() { found.push(Box::new(f)); } + #[cfg(target_os = "android")] + if let Some(f) = super::mediacodec::probe() { + found.push(Box::new(f)); + } found } diff --git a/crates/tsc-media/src/codec/image_layout.rs b/crates/tsc-media/src/codec/image_layout.rs new file mode 100644 index 0000000..e77e3c9 --- /dev/null +++ b/crates/tsc-media/src/codec/image_layout.rs @@ -0,0 +1,324 @@ +//! Where the Y, U and V samples of a 4:2:0 image sit in a codec's linear +//! buffer, and copies between such buffers and [`VideoFrame`]s. +//! +//! Android's MediaCodec describes its byte-buffer layout either by a color +//! format (19 = planar I420, 21 = semi-planar NV12) plus `stride` and +//! `slice-height`, or exactly by a `MediaImage2` struct in the format's +//! `image-data` entry. Both become an [`ImageLayout`] here; this module has +//! no Android dependency so it is tested on every platform. + +use crate::convert; +use crate::frame::{FrameData, Plane, VideoFrame, chroma_size}; +use crate::{Error, Result}; + +/// `COLOR_FormatYUV420Planar`. +pub const COLOR_FORMAT_I420: i32 = 19; +/// `COLOR_FormatYUV420SemiPlanar`. +pub const COLOR_FORMAT_NV12: i32 = 21; +/// `COLOR_FormatYUV420Flexible`: the real layout is in `image-data`. +pub const COLOR_FORMAT_FLEXIBLE: i32 = 0x7F42_0888; + +/// One plane: first sample at `offset`, next sample in the row `col_inc` +/// bytes further, next row `row_inc` bytes further. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct PlaneLayout { + pub offset: usize, + pub col_inc: usize, + pub row_inc: usize, +} + +/// An 8-bit YUV 4:2:0 image of `width` x `height` in a linear buffer. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct ImageLayout { + pub width: u32, + pub height: u32, + pub y: PlaneLayout, + pub u: PlaneLayout, + pub v: PlaneLayout, +} + +/// Size of `MediaImage2` (`media/hardware/VideoAPI.h`): six `u32` fields +/// and four planes of five 32-bit fields. +const MEDIA_IMAGE2_SIZE: usize = 6 * 4 + 4 * 5 * 4; +const MEDIA_IMAGE_TYPE_YUV: u32 = 1; + +impl ImageLayout { + /// Planar I420: Y rows of `stride` bytes, `slice_height` rows, then U and + /// V with half the stride and half the rows. + pub fn i420(width: u32, height: u32, stride: usize, slice_height: usize) -> Self { + let stride = stride.max(width as usize); + let slice_height = slice_height.max(height as usize); + let c_stride = stride.div_ceil(2); + let u = stride * slice_height; + let v = u + c_stride * slice_height.div_ceil(2); + Self { + width, + height, + y: PlaneLayout { offset: 0, col_inc: 1, row_inc: stride }, + u: PlaneLayout { offset: u, col_inc: 1, row_inc: c_stride }, + v: PlaneLayout { offset: v, col_inc: 1, row_inc: c_stride }, + } + } + + /// Semi-planar NV12: Y, then interleaved U/V rows of `stride` bytes. + pub fn nv12(width: u32, height: u32, stride: usize, slice_height: usize) -> Self { + let stride = stride.max(width as usize); + let slice_height = slice_height.max(height as usize); + let uv = stride * slice_height; + Self { + width, + height, + y: PlaneLayout { offset: 0, col_inc: 1, row_inc: stride }, + u: PlaneLayout { offset: uv, col_inc: 2, row_inc: stride }, + v: PlaneLayout { offset: uv + 1, col_inc: 2, row_inc: stride }, + } + } + + /// The layout of a color format with `stride` / `slice-height` (0 when + /// unknown). Flexible and vendor formats need `image-data` instead. + pub fn from_color_format( + color_format: i32, + width: u32, + height: u32, + stride: usize, + slice_height: usize, + ) -> Option { + match color_format { + COLOR_FORMAT_I420 => Some(Self::i420(width, height, stride, slice_height)), + COLOR_FORMAT_NV12 => Some(Self::nv12(width, height, stride, slice_height)), + _ => None, + } + } + + /// Parse a `MediaImage2` (little-endian, as on every Android ABI). + /// Only 8-bit YUV 4:2:0 with three planes is accepted. + pub fn from_media_image2(data: &[u8]) -> Option { + if data.len() < MEDIA_IMAGE2_SIZE { + return None; + } + let word = |i: usize| u32::from_le_bytes(data[i * 4..i * 4 + 4].try_into().unwrap()); + let (kind, planes, width, height, depth, allocated) = + (word(0), word(1), word(2), word(3), word(4), word(5)); + if kind != MEDIA_IMAGE_TYPE_YUV || planes != 3 || depth != 8 || allocated != 8 { + return None; + } + let plane = |p: usize, subsampling: u32| -> Option { + let base = 6 + p * 5; + let (offset, col_inc, row_inc) = + (word(base), word(base + 1) as i32, word(base + 2) as i32); + if word(base + 3) != subsampling || word(base + 4) != subsampling { + return None; + } + Some(PlaneLayout { + offset: offset as usize, + col_inc: usize::try_from(col_inc).ok().filter(|&c| c > 0)?, + row_inc: usize::try_from(row_inc).ok().filter(|&r| r > 0)?, + }) + }; + Some(Self { width, height, y: plane(0, 1)?, u: plane(1, 2)?, v: plane(2, 2)? }) + } + + /// The same buffer layout for a smaller visible area (a crop from the + /// top-left corner), e.g. a decoder's 1920x1088 buffer showing 1080 rows. + pub fn cropped(mut self, width: u32, height: u32) -> Self { + self.width = width.min(self.width); + self.height = height.min(self.height); + self + } + + /// Bytes a buffer needs to hold this image. + pub fn buffer_len(&self) -> usize { + let (cw, ch) = chroma_size(self.width, self.height); + let end = |p: &PlaneLayout, w: usize, h: usize| { + if w == 0 || h == 0 { + 0 + } else { + p.offset + (h - 1) * p.row_inc + (w - 1) * p.col_inc + 1 + } + }; + let (w, h) = (self.width as usize, self.height as usize); + end(&self.y, w, h).max(end(&self.u, cw, ch)).max(end(&self.v, cw, ch)) + } + + fn check(&self, len: usize) -> Result<()> { + if len < self.buffer_len() { + return Err(Error::InvalidFrame(format!( + "codec buffer has {len} bytes, the {}x{} image needs {}", + self.width, + self.height, + self.buffer_len() + ))); + } + Ok(()) + } + + /// Copy an image out of a codec buffer: NV12 when the layout is NV12, + /// I420 otherwise. + pub fn read(&self, buf: &[u8]) -> Result { + self.check(buf.len())?; + let (w, h) = (self.width as usize, self.height as usize); + let (cw, ch) = chroma_size(self.width, self.height); + let y = read_plane(buf, &self.y, w, h); + let data = if self.u.col_inc == 2 + && self.v.col_inc == 2 + && self.v.offset == self.u.offset + 1 + && self.u.row_inc == self.v.row_inc + { + let uv = PlaneLayout { col_inc: 1, ..self.u }; + FrameData::Nv12 { y, uv: read_plane(buf, &uv, cw * 2, ch) } + } else { + FrameData::I420 { + y, + u: read_plane(buf, &self.u, cw, ch), + v: read_plane(buf, &self.v, cw, ch), + } + }; + let frame = VideoFrame { + width: self.width, + height: self.height, + timestamp: std::time::Duration::ZERO, + data, + }; + frame.validate()?; + Ok(frame) + } + + /// Write `frame` (any pixel format, same size as the layout) into a codec + /// buffer. Returns the bytes used. + pub fn write(&self, frame: &VideoFrame, buf: &mut [u8]) -> Result { + if (frame.width, frame.height) != (self.width, self.height) { + return Err(Error::InvalidFrame(format!( + "{}x{} frame for a {}x{} codec buffer", + frame.width, frame.height, self.width, self.height + ))); + } + self.check(buf.len())?; + let i420 = convert::to_i420(frame)?; + let FrameData::I420 { y, u, v } = &i420.data else { + unreachable!("to_i420 returns I420"); + }; + let (w, h) = (self.width as usize, self.height as usize); + let (cw, ch) = chroma_size(self.width, self.height); + write_plane(buf, &self.y, y, w, h); + write_plane(buf, &self.u, u, cw, ch); + write_plane(buf, &self.v, v, cw, ch); + Ok(self.buffer_len()) + } +} + +fn read_plane(buf: &[u8], p: &PlaneLayout, width: usize, rows: usize) -> Plane { + let mut data = Vec::with_capacity(width * rows); + for row in 0..rows { + let start = p.offset + row * p.row_inc; + if p.col_inc == 1 { + data.extend_from_slice(&buf[start..start + width]); + } else { + data.extend((0..width).map(|x| buf[start + x * p.col_inc])); + } + } + Plane::new(data, width) +} + +fn write_plane(buf: &mut [u8], p: &PlaneLayout, src: &Plane, width: usize, rows: usize) { + for row in 0..rows { + let line = src.row(row, width); + let start = p.offset + row * p.row_inc; + if p.col_inc == 1 { + buf[start..start + width].copy_from_slice(line); + } else { + for (x, &sample) in line.iter().enumerate() { + buf[start + x * p.col_inc] = sample; + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A 6x4 I420 frame with distinct samples per plane. + fn frame() -> VideoFrame { + let (w, h) = (6usize, 4usize); + let (cw, ch) = chroma_size(6, 4); + VideoFrame { + width: 6, + height: 4, + timestamp: std::time::Duration::ZERO, + data: FrameData::I420 { + y: Plane::new((0..w * h).map(|i| i as u8).collect(), w), + u: Plane::new((0..cw * ch).map(|i| 100 + i as u8).collect(), cw), + v: Plane::new((0..cw * ch).map(|i| 200 + i as u8).collect(), cw), + }, + } + } + + fn as_i420(frame: &VideoFrame) -> VideoFrame { + convert::to_i420(frame).unwrap().into_owned() + } + + #[test] + fn i420_and_nv12_round_trip_with_padding() { + let src = frame(); + for layout in [ImageLayout::i420(6, 4, 8, 6), ImageLayout::nv12(6, 4, 8, 6)] { + let mut buf = vec![0xEE; layout.buffer_len()]; + assert_eq!(layout.write(&src, &mut buf).unwrap(), buf.len()); + let back = layout.read(&buf).unwrap(); + assert_eq!(as_i420(&back).data, src.data, "{layout:?}"); + } + // NV12 reads back as NV12 without conversion. + let layout = ImageLayout::nv12(6, 4, 6, 4); + let mut buf = vec![0; layout.buffer_len()]; + layout.write(&src, &mut buf).unwrap(); + assert!(matches!(layout.read(&buf).unwrap().data, FrameData::Nv12 { .. })); + assert_eq!(&buf[24..30], &[100, 200, 101, 201, 102, 202]); + } + + #[test] + fn media_image2_describes_nv21() { + // 6x4, stride 8, 4 rows: V first in the interleaved plane (NV21). + let mut raw = Vec::new(); + for w in [1u32, 3, 6, 4, 8, 8] { + raw.extend(w.to_le_bytes()); + } + for (offset, col, row, sub) in [(0u32, 1i32, 8i32, 1u32), (33, 2, 8, 2), (32, 2, 8, 2)] { + raw.extend(offset.to_le_bytes()); + raw.extend(col.to_le_bytes()); + raw.extend(row.to_le_bytes()); + raw.extend(sub.to_le_bytes()); + raw.extend(sub.to_le_bytes()); + } + raw.extend([0; 20]); + let layout = ImageLayout::from_media_image2(&raw).unwrap(); + assert_eq!(layout.u, PlaneLayout { offset: 33, col_inc: 2, row_inc: 8 }); + let mut buf = vec![0; layout.buffer_len()]; + layout.write(&frame(), &mut buf).unwrap(); + assert_eq!(&buf[32..36], &[200, 100, 201, 101]); + let back = layout.read(&buf).unwrap(); + assert!(matches!(back.data, FrameData::I420 { .. })); + assert_eq!(back.data, frame().data); + + // Not YUV, too short, or a 10-bit image: rejected. + let mut rgb = raw.clone(); + rgb[0] = 3; + assert!(ImageLayout::from_media_image2(&rgb).is_none()); + assert!(ImageLayout::from_media_image2(&raw[..100]).is_none()); + let mut deep = raw.clone(); + deep[16] = 10; + assert!(ImageLayout::from_media_image2(&deep).is_none()); + } + + #[test] + fn crop_and_size_checks() { + // A decoder buffer of 8x6 (stride 8) showing 6x4. + let layout = + ImageLayout::from_color_format(COLOR_FORMAT_I420, 8, 6, 8, 6).unwrap().cropped(6, 4); + assert_eq!((layout.width, layout.height), (6, 4)); + assert_eq!(layout.u.offset, 48); + assert!(ImageLayout::from_color_format(COLOR_FORMAT_FLEXIBLE, 8, 6, 8, 6).is_none()); + let short = vec![0; 10]; + assert!(matches!(layout.read(&short), Err(Error::InvalidFrame(_)))); + let mut buf = vec![0; 100]; + assert!(layout.write(&VideoFrame::black_i420(4, 4), &mut buf).is_err()); + } +} diff --git a/crates/tsc-media/src/codec/mediacodec.rs b/crates/tsc-media/src/codec/mediacodec.rs new file mode 100644 index 0000000..864fff0 --- /dev/null +++ b/crates/tsc-media/src/codec/mediacodec.rs @@ -0,0 +1,566 @@ +//! Android MediaCodec (NDK `AMediaCodec`) encoders and decoders. +//! +//! Byte-buffer mode on both sides, so frames stay [`VideoFrame`]s like with +//! the software codecs: encoders take I420 / NV12 (whatever the codec asks +//! for, see [`ImageLayout`]), decoders return I420 or NV12. The device's +//! default codec for a MIME type is used; most phones have hardware H.264, +//! many hardware VP8 / VP9, and every Android has Google's software VP8, +//! VP9 and H.264 (`c2.android.*`). +//! +//! H.264 is encoded as High profile without B-frames (the Constrained High +//! stream TeamSpeak negotiates, see `tsc-stream`), SPS/PPS in front of every +//! keyframe. + +// AMediaCodec handles are used from one thread at a time (`&mut self`), which +// the NDK allows from any thread; the wrapper only asserts that. +#![allow(unsafe_code)] + +use std::sync::OnceLock; +use std::time::Duration; + +use ndk::media::media_codec::{ + DequeuedInputBufferResult, DequeuedOutputBufferInfoResult, MediaCodec, MediaCodecDirection, +}; +use ndk::media::media_format::MediaFormat; +use tracing::{debug, info}; + +use super::hw::HardwareEncoderFactory; +use super::image_layout::{ + COLOR_FORMAT_FLEXIBLE, COLOR_FORMAT_I420, COLOR_FORMAT_NV12, ImageLayout, +}; +use super::{Codec, EncodedFrame, EncoderBackend, EncoderConfig, VideoDecoder, VideoEncoder}; +use crate::frame::{FrameData, VideoFrame}; +use crate::{Error, Result, convert}; + +/// `BUFFER_FLAG_KEY_FRAME`. +const FLAG_KEY_FRAME: u32 = 1; +/// `BUFFER_FLAG_CODEC_CONFIG`: SPS/PPS (H.264), no picture. +const FLAG_CODEC_CONFIG: u32 = 2; +/// `AVCProfileHigh`, `AVCProfileConstrainedHigh`. +const AVC_PROFILE_HIGH: i32 = 0x08; +const AVC_PROFILE_CONSTRAINED_HIGH: i32 = 0x80000; +/// `BITRATE_MODE_VBR`. +const BITRATE_MODE_VBR: i32 = 1; +/// Keyframe interval for "only on request" (seconds; what WebRTC uses). +const NO_PERIODIC_KEYFRAMES: i32 = 3600; +/// How long `decode` / `encode` wait for a free input buffer. +const INPUT_WAIT: Duration = Duration::from_millis(20); +/// How long they wait for the first output of a call. +const OUTPUT_WAIT: Duration = Duration::from_millis(5); + +pub const NAME: &str = "mediacodec"; + +fn mime(codec: Codec) -> &'static str { + match codec { + Codec::Vp8 => "video/x-vnd.on2.vp8", + Codec::Vp9 => "video/x-vnd.on2.vp9", + Codec::H264 => "video/avc", + Codec::Av1 => "video/av01", + } +} + +/// Google's software codecs (as opposed to the vendor's hardware ones). +fn is_software(name: &str) -> bool { + name.starts_with("c2.android.") || name.starts_with("OMX.google.") || name.contains(".sw.") +} + +/// An `AMediaCodec` that may move between threads. +struct Handle(MediaCodec); + +// SAFETY: see the module attribute; `Handle` is only reached through +// `&mut self` of its owner, never shared. +unsafe impl Send for Handle {} + +impl Drop for Handle { + fn drop(&mut self) { + let _ = self.0.stop(); + } +} + +fn encoder_error(codec: Codec, context: &str, e: impl std::fmt::Display) -> Error { + Error::Encoder { codec, message: format!("{context}: {e}") } +} + +fn decoder_error(codec: Codec, context: &str, e: impl std::fmt::Display) -> Error { + Error::Decoder { codec, message: format!("{context}: {e}") } +} + +/// The default codec's name per MIME type and direction, probed once. +struct Available { + encoders: Vec<(Codec, String)>, + decoders: Vec<(Codec, String)>, +} + +fn available() -> &'static Available { + static AVAILABLE: OnceLock = OnceLock::new(); + AVAILABLE.get_or_init(|| { + let probe = |create: fn(&str) -> Option| { + Codec::ALL + .into_iter() + .filter_map(|codec| { + let handle = Handle(create(mime(codec))?); + let name = handle.0.name().unwrap_or_else(|_| "?".into()); + Some((codec, name)) + }) + .collect::>() + }; + let found = Available { + encoders: probe(MediaCodec::from_encoder_type), + decoders: probe(MediaCodec::from_decoder_type), + }; + info!(encoders = ?found.encoders, decoders = ?found.decoders, "MediaCodec"); + found + }) +} + +/// Whether the device decodes `codec`. +pub fn check_decoder(codec: Codec) -> Result<()> { + if available().decoders.iter().any(|(c, _)| *c == codec) { + Ok(()) + } else { + Err(Error::CodecUnavailable { codec, reason: "no MediaCodec decoder".into() }) + } +} + +/// Encoders of this device: hardware ones first (H.264, VP9, VP8), then +/// Google's software VP8 and H.264. Software VP9 and AV1 are too slow. +pub fn probe() -> Option { + let encoders = &available().encoders; + let name = |codec| encoders.iter().find(|(c, _)| *c == codec).map(|(_, n)| n.as_str()); + let mut codecs = Vec::new(); + for codec in [Codec::H264, Codec::Vp9, Codec::Vp8, Codec::Av1] { + if name(codec).is_some_and(|n| !is_software(n)) { + codecs.push(codec); + } + } + for codec in [Codec::Vp8, Codec::H264] { + if name(codec).is_some_and(is_software) { + codecs.push(codec); + } + } + (!codecs.is_empty()).then_some(MediaCodecFactory { codecs }) +} + +pub struct MediaCodecFactory { + codecs: Vec, +} + +impl HardwareEncoderFactory for MediaCodecFactory { + fn name(&self) -> &'static str { + NAME + } + + fn codecs(&self) -> Vec { + self.codecs.clone() + } + + fn create(&self, codec: Codec, config: &EncoderConfig) -> Result> { + if !self.codecs.contains(&codec) { + return Err(Error::CodecUnavailable { codec, reason: "no MediaCodec encoder".into() }); + } + Ok(Box::new(MediaCodecEncoder { codec, config: config.clone(), session: None })) + } +} + +/// A MediaCodec encoder. The codec is (re)created for the frame size. +pub struct MediaCodecEncoder { + codec: Codec, + config: EncoderConfig, + session: Option, +} + +struct EncoderSession { + handle: Handle, + layout: ImageLayout, + /// H.264 SPS/PPS, put in front of keyframes that lack them. + parameter_sets: Vec, + /// Staging buffer for the codec's input layout. + staging: Vec, + last_pts_us: Option, +} + +impl MediaCodecEncoder { + fn format( + &self, + width: u32, + height: u32, + color_format: i32, + profile: Option, + ) -> MediaFormat { + let mut format = MediaFormat::new(); + format.set_str("mime", mime(self.codec)); + format.set_i32("width", width as i32); + format.set_i32("height", height as i32); + format.set_i32("color-format", color_format); + format.set_i32("bitrate", self.config.bitrate_bps.min(i32::MAX as u32) as i32); + format.set_i32("bitrate-mode", BITRATE_MODE_VBR); + format.set_i32("frame-rate", self.config.fps.max(1) as i32); + let interval = match self.config.keyframe_interval { + Some(frames) => frames.div_ceil(self.config.fps.max(1)).max(1) as i32, + None => NO_PERIODIC_KEYFRAMES, + }; + format.set_i32("i-frame-interval", interval); + if self.codec == Codec::H264 { + format.set_i32("max-bframes", 0); + format.set_i32("prepend-sps-pps-to-idr-frames", 1); + if let Some(profile) = profile { + format.set_i32("profile", profile); + } + } + format + } + + /// Start a codec for `width` x `height`: NV12 input, else I420; for + /// H.264 Constrained High, else High, else the codec's default profile. + fn start(&self, width: u32, height: u32) -> Result { + let codec = self.codec; + let profiles: &[Option] = if codec == Codec::H264 { + &[Some(AVC_PROFILE_CONSTRAINED_HIGH), Some(AVC_PROFILE_HIGH), None] + } else { + &[None] + }; + let mut last_error = String::from("no configuration tried"); + for color_format in [COLOR_FORMAT_NV12, COLOR_FORMAT_I420] { + for &profile in profiles { + let handle = Handle( + MediaCodec::from_encoder_type(mime(codec)) + .ok_or_else(|| encoder_error(codec, "create", "no encoder"))?, + ); + let format = self.format(width, height, color_format, profile); + if let Err(e) = handle.0.configure(&format, None, MediaCodecDirection::Encoder) { + last_error = format!("configure {color_format}/{profile:?}: {e}"); + continue; + } + let layout = input_layout(&handle.0.input_format(), width, height, color_format); + handle.0.start().map_err(|e| encoder_error(codec, "start", e))?; + debug!(%codec, width, height, color_format, ?profile, ?layout, "MediaCodec encoder"); + return Ok(EncoderSession { + handle, + layout, + parameter_sets: Vec::new(), + staging: Vec::new(), + last_pts_us: None, + }); + } + } + Err(encoder_error(codec, "no working configuration", last_error)) + } +} + +/// Where the encoder wants its input: `image-data` if it says, else the +/// color format with its `stride` / `slice-height`. +fn input_layout(format: &MediaFormat, width: u32, height: u32, requested: i32) -> ImageLayout { + if let Some(layout) = format + .buffer("image-data") + .and_then(ImageLayout::from_media_image2) + .filter(|l| l.width >= width && l.height >= height) + { + return layout.cropped(width, height); + } + let stride = format.i32("stride").and_then(|s| usize::try_from(s).ok()).unwrap_or(0); + let slice = format.i32("slice-height").and_then(|s| usize::try_from(s).ok()).unwrap_or(0); + let color = match format.i32("color-format") { + Some(c @ (COLOR_FORMAT_I420 | COLOR_FORMAT_NV12)) => c, + // Flexible or unset: what we asked for. + _ => requested, + }; + ImageLayout::from_color_format(color, width, height, stride, slice) + .unwrap_or_else(|| ImageLayout::nv12(width, height, stride, slice)) +} + +/// The top-left `width` x `height` of an I420 frame (planes keep their +/// stride, so nothing is copied). +fn crop_i420(mut frame: VideoFrame, width: u32, height: u32) -> VideoFrame { + debug_assert!(matches!(frame.data, FrameData::I420 { .. })); + frame.width = width; + frame.height = height; + frame +} + +/// H.264 NAL unit type of the first NAL after a start code. +fn first_nal_type(data: &[u8]) -> Option { + let start = if data.starts_with(&[0, 0, 0, 1]) { + 4 + } else if data.starts_with(&[0, 0, 1]) { + 3 + } else { + return None; + }; + data.get(start).map(|b| b & 0x1f) +} + +impl VideoEncoder for MediaCodecEncoder { + fn codec(&self) -> Codec { + self.codec + } + + fn backend(&self) -> EncoderBackend { + EncoderBackend::Hardware(NAME) + } + + fn encode(&mut self, frame: &VideoFrame, force_keyframe: bool) -> Result> { + let codec = self.codec; + // Encoders want even sizes. + let (width, height) = (frame.width & !1, frame.height & !1); + if width == 0 || height == 0 { + return Err(Error::InvalidFrame(format!("{}x{} frame", frame.width, frame.height))); + } + let resized = self + .session + .as_ref() + .is_some_and(|s| (s.layout.width, s.layout.height) != (width, height)); + if resized || self.session.is_none() { + self.session = None; + self.session = Some(self.start(width, height)?); + } + let session = self.session.as_mut().expect("started above"); + let mut i420 = convert::to_i420(frame)?.into_owned(); + if (i420.width, i420.height) != (width, height) { + i420 = crop_i420(i420, width, height); + } + + // Strictly increasing presentation times. + let mut pts_us = i420.timestamp.as_micros() as u64; + if let Some(last) = session.last_pts_us + && pts_us <= last + { + pts_us = last + 1; + } + + if force_keyframe && !resized { + let mut params = MediaFormat::new(); + params.set_i32("request-sync", 0); + session + .handle + .0 + .set_parameters(params) + .map_err(|e| encoder_error(codec, "request keyframe", e))?; + } + + let len = session.layout.buffer_len(); + session.staging.resize(len, 0); + session.layout.write(&i420, &mut session.staging)?; + match session + .handle + .0 + .dequeue_input_buffer(INPUT_WAIT) + .map_err(|e| encoder_error(codec, "dequeue input", e))? + { + DequeuedInputBufferResult::Buffer(mut buffer) => { + let dst = buffer.buffer_mut(); + if dst.len() < len { + return Err(encoder_error( + codec, + "input buffer", + format!("{} bytes, need {len}", dst.len()), + )); + } + dst[..len].write_copy_of_slice(&session.staging); + session + .handle + .0 + .queue_input_buffer(buffer, 0, len, pts_us, 0) + .map_err(|e| encoder_error(codec, "queue input", e))?; + session.last_pts_us = Some(pts_us); + } + // The codec is still busy: skip this frame (rate control). + DequeuedInputBufferResult::TryAgainLater => {} + } + drain_encoder(codec, session) + } + + fn set_bitrate(&mut self, bps: u32) -> Result<()> { + self.config.bitrate_bps = bps; + if let Some(session) = &self.session { + let mut params = MediaFormat::new(); + params.set_i32("video-bitrate", bps.min(i32::MAX as u32) as i32); + session + .handle + .0 + .set_parameters(params) + .map_err(|e| encoder_error(self.codec, "set bitrate", e))?; + } + Ok(()) + } +} + +/// Collect what the encoder has finished. +fn drain_encoder(codec: Codec, session: &mut EncoderSession) -> Result> { + let mut out = Vec::new(); + let mut wait = OUTPUT_WAIT; + loop { + let result = session + .handle + .0 + .dequeue_output_buffer(wait) + .map_err(|e| encoder_error(codec, "dequeue output", e))?; + wait = Duration::ZERO; + match result { + DequeuedOutputBufferInfoResult::Buffer(buffer) => { + let info = *buffer.info(); + let offset = usize::try_from(info.offset()).unwrap_or(0); + let size = usize::try_from(info.size()).unwrap_or(0); + let data = buffer.buffer().get(offset..offset + size).map(<[u8]>::to_vec); + session + .handle + .0 + .release_output_buffer(buffer, false) + .map_err(|e| encoder_error(codec, "release output", e))?; + let Some(mut data) = data.filter(|d| !d.is_empty()) else { + continue; + }; + if info.flags() & FLAG_CODEC_CONFIG != 0 { + session.parameter_sets = data; + continue; + } + let keyframe = info.flags() & FLAG_KEY_FRAME != 0; + if keyframe + && codec == Codec::H264 + && !session.parameter_sets.is_empty() + && first_nal_type(&data) != Some(7) + { + let mut with_sps = session.parameter_sets.clone(); + with_sps.append(&mut data); + data = with_sps; + } + let pts_us = u64::try_from(info.presentation_time_us()).unwrap_or(0); + out.push(EncodedFrame { data, keyframe, pts_90khz: pts_us * 9 / 100 }); + } + DequeuedOutputBufferInfoResult::OutputFormatChanged + | DequeuedOutputBufferInfoResult::OutputBuffersChanged => {} + DequeuedOutputBufferInfoResult::TryAgainLater => return Ok(out), + } + } +} + +/// A MediaCodec decoder. +pub struct MediaCodecDecoder { + codec: Codec, + handle: Handle, + /// Output layout, known after the first format change. + layout: Option, + pts_us: u64, +} + +impl MediaCodecDecoder { + pub fn new(codec: Codec) -> Result { + check_decoder(codec)?; + let handle = Handle( + MediaCodec::from_decoder_type(mime(codec)) + .ok_or_else(|| decoder_error(codec, "create", "no decoder"))?, + ); + let mut format = MediaFormat::new(); + format.set_str("mime", mime(codec)); + // A hint; the stream's own size wins. + format.set_i32("width", 1920); + format.set_i32("height", 1080); + format.set_i32("color-format", COLOR_FORMAT_FLEXIBLE); + handle + .0 + .configure(&format, None, MediaCodecDirection::Decoder) + .map_err(|e| decoder_error(codec, "configure", e))?; + handle.0.start().map_err(|e| decoder_error(codec, "start", e))?; + Ok(Self { codec, handle, layout: None, pts_us: 0 }) + } + + fn update_layout(&mut self) { + let format = self.handle.0.output_format(); + let width = format.i32("width").unwrap_or(0).max(0) as u32; + let height = format.i32("height").unwrap_or(0).max(0) as u32; + let (visible_w, visible_h) = match format.rect("crop") { + Some((left, top, right, bottom)) if left == 0 && top == 0 => { + ((right + 1).max(0) as u32, (bottom + 1).max(0) as u32) + } + _ => (width, height), + }; + let stride = format.i32("stride").and_then(|s| usize::try_from(s).ok()).unwrap_or(0); + let slice = format.i32("slice-height").and_then(|s| usize::try_from(s).ok()).unwrap_or(0); + let layout = format + .buffer("image-data") + .and_then(ImageLayout::from_media_image2) + .or_else(|| { + ImageLayout::from_color_format( + format.i32("color-format").unwrap_or(0), + width, + height, + stride, + slice, + ) + }) + .map(|l| l.cropped(visible_w, visible_h)); + debug!(codec = %self.codec, ?layout, "MediaCodec decoder output"); + self.layout = layout; + } +} + +impl VideoDecoder for MediaCodecDecoder { + fn codec(&self) -> Codec { + self.codec + } + + fn decode(&mut self, data: &[u8]) -> Result> { + let codec = self.codec; + match self + .handle + .0 + .dequeue_input_buffer(INPUT_WAIT) + .map_err(|e| decoder_error(codec, "dequeue input", e))? + { + DequeuedInputBufferResult::Buffer(mut buffer) => { + let dst = buffer.buffer_mut(); + if dst.len() < data.len() { + return Err(decoder_error( + codec, + "input buffer", + format!("{} bytes for a {} byte frame", dst.len(), data.len()), + )); + } + dst[..data.len()].write_copy_of_slice(data); + // Only the order matters; the caller knows the RTP time. + self.pts_us += 33_333; + self.handle + .0 + .queue_input_buffer(buffer, 0, data.len(), self.pts_us, 0) + .map_err(|e| decoder_error(codec, "queue input", e))?; + } + DequeuedInputBufferResult::TryAgainLater => { + return Err(decoder_error(codec, "dequeue input", "the decoder is stalled")); + } + } + + // The newest finished picture; older ones are dropped. + let mut picture = None; + let mut wait = OUTPUT_WAIT; + loop { + let result = self + .handle + .0 + .dequeue_output_buffer(wait) + .map_err(|e| decoder_error(codec, "dequeue output", e))?; + wait = Duration::ZERO; + match result { + DequeuedOutputBufferInfoResult::Buffer(buffer) => { + let info = *buffer.info(); + let offset = usize::try_from(info.offset()).unwrap_or(0); + let size = usize::try_from(info.size()).unwrap_or(0); + let read = match (&self.layout, buffer.buffer().get(offset..offset + size)) { + (Some(layout), Some(bytes)) if size > 0 => Some(layout.read(bytes)), + _ => None, + }; + self.handle + .0 + .release_output_buffer(buffer, false) + .map_err(|e| decoder_error(codec, "release output", e))?; + match read { + Some(Ok(frame)) => picture = Some(frame), + Some(Err(e)) => return Err(decoder_error(codec, "output", e)), + None => {} + } + } + DequeuedOutputBufferInfoResult::OutputFormatChanged => self.update_layout(), + DequeuedOutputBufferInfoResult::OutputBuffersChanged => {} + DequeuedOutputBufferInfoResult::TryAgainLater => return Ok(picture), + } + } + } +} diff --git a/crates/tsc-media/src/codec/mod.rs b/crates/tsc-media/src/codec/mod.rs index c666333..48e7d9e 100644 --- a/crates/tsc-media/src/codec/mod.rs +++ b/crates/tsc-media/src/codec/mod.rs @@ -8,6 +8,8 @@ //! loaded at runtime //! - [`av1`] (feature `av1`): AV1 decoding with the system libdav1d //! - [`hw`]: hardware encoders (VA-API, Media Foundation); not implemented yet +//! - `mediacodec` (Android): the device's MediaCodec encoders and decoders +//! (hardware, or Google's software VP8 / VP9 / H.264) use std::fmt; use std::str::FromStr; @@ -20,6 +22,9 @@ pub mod av1; #[cfg(feature = "openh264")] pub mod h264; pub mod hw; +pub mod image_layout; +#[cfg(target_os = "android")] +pub mod mediacodec; #[cfg(feature = "vpx")] pub mod vpx; @@ -263,6 +268,10 @@ impl Codecs { /// Whether `codec` can be decoded, or why not. pub fn check_decoder(&self, codec: Codec) -> Result<()> { + #[cfg(target_os = "android")] + if mediacodec::check_decoder(codec).is_ok() { + return Ok(()); + } match codec { Codec::Vp8 | Codec::Vp9 => { #[cfg(feature = "vpx")] @@ -321,6 +330,10 @@ impl Codecs { } pub fn new_decoder(&self, codec: Codec) -> Result> { + #[cfg(target_os = "android")] + if mediacodec::check_decoder(codec).is_ok() { + return Ok(Box::new(mediacodec::MediaCodecDecoder::new(codec)?)); + } self.check_decoder(codec)?; match codec { #[cfg(feature = "vpx")] diff --git a/crates/tsc-ui/Cargo.toml b/crates/tsc-ui/Cargo.toml index d053477..bbfd97f 100644 --- a/crates/tsc-ui/Cargo.toml +++ b/crates/tsc-ui/Cargo.toml @@ -21,16 +21,24 @@ anyhow = "1.0.104" chrono = { version = "0.4.45", default-features = false, features = ["clock"] } dirs = "6" png = "0.18" -slint = { version = "1.18", features = ["renderer-software"] } tokio = { version = "1.53.1", features = ["rt-multi-thread", "macros", "time", "sync"] } tracing = "0.1.44" tracing-subscriber = { version = "0.3.23", features = ["env-filter"] } tsc-core = { path = "../tsc-core" } tsc-model = { path = "../tsc-model" } tsc-query = { path = "../tsc-query" } -tsc-store = { path = "../tsc-store", features = ["keyring"] } +tsc-store = { path = "../tsc-store" } tsclientlib = { path = "../proto/tsclientlib" } +# Android (tsc-android): no keyring backend (the app passes Keystore-backed +# secrets) and no winit/femtovg (the app picks Slint's Android backend). +[target.'cfg(not(target_os = "android"))'.dependencies] +slint = { version = "1.18", features = ["renderer-software"] } +tsc-store = { path = "../tsc-store", features = ["keyring"] } + +[target.'cfg(target_os = "android")'.dependencies] +slint = { version = "1.18", default-features = false, features = ["std", "compat-1-2", "renderer-software"] } + [build-dependencies] slint-build = "1.18" diff --git a/crates/tsc-ui/src/app.rs b/crates/tsc-ui/src/app.rs index 1a10ac8..95033df 100644 --- a/crates/tsc-ui/src/app.rs +++ b/crates/tsc-ui/src/app.rs @@ -19,11 +19,25 @@ slint::include_modules!(); /// Secrets in the OS keyring, or in memory when there is none (headless /// Linux without a Secret Service). +#[cfg(not(target_os = "android"))] struct FallbackSecrets { keyring: tsc_store::KeyringSecrets, memory: MemorySecrets, } +/// The secrets store when [`RunOptions::secrets`] is not given: the OS +/// keyring on desktop, memory elsewhere. +fn default_secrets() -> Box { + #[cfg(not(target_os = "android"))] + return Box::new(FallbackSecrets { + keyring: tsc_store::KeyringSecrets::new("tsc-client"), + memory: MemorySecrets::default(), + }); + #[cfg(target_os = "android")] + return Box::new(MemorySecrets::default()); +} + +#[cfg(not(target_os = "android"))] impl Secrets for FallbackSecrets { fn get(&self, key: &str) -> tsc_store::Result> { match self.memory.get(key)? { @@ -105,18 +119,76 @@ fn with_app(f: impl FnOnce(&mut App) -> R) -> Option { } /// Start options for [`run`]. -#[derive(Clone, Debug, Default)] +#[derive(Default)] pub struct RunOptions { /// Where the client database lives. Default: `TSC_DATA_DIR`, else /// `/tsc`. Mobile platforms pass their app storage directory. pub data_dir: Option, + /// Where passwords are kept. Default: the OS keyring, in memory when it + /// is unavailable. + pub secrets: Option>, + /// An engine the caller keeps running across windows (Android: voice + /// goes on in a service while the activity is recreated). Default: an + /// engine that stops with the window. + pub engine: Option, +} + +impl std::fmt::Debug for RunOptions { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("RunOptions") + .field("data_dir", &self.data_dir) + .field("secrets", &self.secrets.is_some()) + .field("engine", &self.engine.is_some()) + .finish() + } +} + +/// An engine owned by the caller of [`run`]. +pub struct HostedEngine { + pub engine: Engine, + /// The runtime the engine runs on; the window's tasks run there too. + pub runtime: tokio::runtime::Handle, + /// The engine's events for this window: first events that rebuild the + /// current state of every session, then new ones. The window stops + /// reading when it closes. + pub events: tokio::sync::mpsc::UnboundedReceiver, +} + +impl HostedEngine { + /// A new engine on `runtime`, all of whose events go to the window. + fn start(runtime: &Runtime) -> Self { + let engine = runtime.block_on(async { Engine::start() }); + let (tx, events) = tokio::sync::mpsc::unbounded_channel(); + let mut rx = engine.subscribe(); + runtime.spawn(async move { + loop { + match rx.recv().await { + Ok(event) => { + if tx.send(event).is_err() { + break; + } + } + Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => continue, + Err(_) => break, + } + } + }); + Self { engine, runtime: runtime.handle().clone(), events } + } } /// Run the app on the current thread until the window closes. The Slint /// platform must be set up before (the default backend on desktop). pub fn run(options: RunOptions) -> Result<()> { - let runtime = Runtime::new()?; - let engine = runtime.block_on(async { Engine::start() }); + let (own_runtime, hosted) = match options.engine { + Some(hosted) => (None, hosted), + None => { + let runtime = Runtime::new()?; + let hosted = HostedEngine::start(&runtime); + (Some(runtime), hosted) + } + }; + let HostedEngine { engine, runtime, mut events } = hosted; // Development switches: TSC_DATA_DIR isolates the database, // TSC_AUTOCONNECT=voice|observe connects the first bookmark on start, @@ -143,10 +215,7 @@ pub fn run(options: RunOptions) -> Result<()> { let app = App { ui: ui.as_weak(), store, - secrets: Box::new(FallbackSecrets { - keyring: tsc_store::KeyringSecrets::new("tsc-client"), - memory: MemorySecrets::default(), - }), + secrets: options.secrets.unwrap_or_else(default_secrets), engine: engine.clone(), identity, current: bookmarks.first().map(|b| b.id), @@ -158,18 +227,14 @@ pub fn run(options: RunOptions) -> Result<()> { wire_callbacks(&ui); with_app(|app| app.refresh_all()); - // Engine events -> UI thread. - let mut events = engine.subscribe(); + // Engine events -> UI thread, until the event loop is gone. runtime.spawn(async move { - loop { - match events.recv().await { - Ok(event) => { - let _ = slint::invoke_from_event_loop(move || { - with_app(|app| app.handle_event(event)); - }); - } - Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => continue, - Err(_) => break, + while let Some(event) = events.recv().await { + let posted = slint::invoke_from_event_loop(move || { + with_app(|app| app.handle_event(event)); + }); + if posted.is_err() { + break; } } }); @@ -205,7 +270,9 @@ pub fn run(options: RunOptions) -> Result<()> { ui.run()?; APP.with(|a| a.borrow_mut().take()); - runtime.shutdown_timeout(std::time::Duration::from_secs(2)); + if let Some(runtime) = own_runtime { + runtime.shutdown_timeout(std::time::Duration::from_secs(2)); + } Ok(()) } diff --git a/crates/tsc-ui/src/lib.rs b/crates/tsc-ui/src/lib.rs index f65782f..30d05ec 100644 --- a/crates/tsc-ui/src/lib.rs +++ b/crates/tsc-ui/src/lib.rs @@ -2,4 +2,4 @@ mod app; -pub use app::{RunOptions, run}; +pub use app::{HostedEngine, RunOptions, run}; diff --git a/crates/tsc-ui/ui/app.slint b/crates/tsc-ui/ui/app.slint index 4fd44a4..6069f1d 100644 --- a/crates/tsc-ui/ui/app.slint +++ b/crates/tsc-ui/ui/app.slint @@ -391,8 +391,19 @@ export component MainWindow inherits Window { changed width => { narrow = self.width < 800px; } init => { narrow = self.width < 800px; } property pane: 1; + // Android: the space under the on-screen keyboard (the window is not + // resized for it). Zero on desktop. + property keyboard-inset: 0; + changed virtual-keyboard-size => { + keyboard-inset = self.virtual-keyboard-size.height > 0 ? self.height - self.virtual-keyboard-position.y : 0; + } VerticalLayout { + // Android draws the window under the status and navigation bars. + padding-top: root.safe-area-insets.top; + padding-left: root.safe-area-insets.left; + padding-right: root.safe-area-insets.right; + padding-bottom: max(root.safe-area-insets.bottom, root.keyboard-inset); // Toolbar Rectangle { height: 48px; diff --git a/docs/android.md b/docs/android.md new file mode 100644 index 0000000..4e04426 --- /dev/null +++ b/docs/android.md @@ -0,0 +1,135 @@ +# Android app + +The Android app is the desktop UI (`tsc-ui`, Slint) running in a +`NativeActivity`, plus a thin Kotlin layer for what only Java APIs can do: +foreground services, the screen-capture consent, the Keystore. + +``` +android/ Gradle project (AGP 8.13, Kotlin 2.3, Gradle 8.14.3 wrapper) + app/src/main/java/.../tsc/ MainActivity (NativeActivity), Bridge, Native, + VoiceService, ScreenCaptureService, SecretStore +crates/tsc-android/ libtsc_android.so: android_main, engine host, + JNI glue, capture providers, Keystore secrets +``` + +## Building + +Requirements: + +- Android SDK with `platforms;android-36` and `build-tools;36.0.0` + (`ANDROID_HOME`, or `sdk.dir` in `android/local.properties`), NDK + `27.3.13750724` (`ndk;27.3.13750724`; the version is pinned in + `app/build.gradle.kts`) +- JDK 17 or newer +- Rust targets: `rustup target add aarch64-linux-android x86_64-linux-android` +- `cargo install cargo-ndk --locked` (4.x) +- CMake and make (or `CMAKE_GENERATOR=Ninja` with ninja): libopus is built + from source + +```sh +cd android +./gradlew assembleDebug # arm64-v8a + x86_64 (emulator) +./gradlew assembleDebug -Ptsc.abis=arm64-v8a # phones only, half the build +adb install -r app/build/outputs/apk/debug/app-debug.apk +adb logcat -s RustStdoutStderr ScreenCaptureService VoiceService SecretStore +``` + +`assemble` runs `cargo ndk ... build -p tsc-android` (with +`--release` for release) into `app/build/rust///` before the +native libraries are merged; `-Ptsc.skipCargo=true` packages what is there +(for CI steps that built the library already). The app's `versionName` is the +version of `crates/tsc-android`, and `versionCode` is derived from it +(docs/release.md). The Kotlin half of `rustls-platform-verifier` comes from +its Maven archive in the version `Cargo.lock` pins. + +Release builds are minified (R8) and signed only when the signing settings +are given as Gradle properties (e.g. `~/.gradle/gradle.properties`) or +environment variables; nothing of it lives in the repository: + +| Gradle property | Environment variable | +|---|---| +| `tsc.signing.storeFile` | `TSC_SIGNING_STORE_FILE` | +| `tsc.signing.storePassword` | `TSC_SIGNING_STORE_PASSWORD` | +| `tsc.signing.keyAlias` | `TSC_SIGNING_KEY_ALIAS` | +| `tsc.signing.keyPassword` | `TSC_SIGNING_KEY_PASSWORD` | + +```sh +TSC_SIGNING_STORE_FILE=~/keys/tsc-release.jks TSC_SIGNING_STORE_PASSWORD=... \ +TSC_SIGNING_KEY_ALIAS=tsc TSC_SIGNING_KEY_PASSWORD=... ./gradlew assembleRelease bundleRelease +``` + +minSdk is 29 (Android 10: MediaProjection foreground service type, playback +capture, NDK MediaCodec format queries); targetSdk and compileSdk 36. + +## How it fits together + +- **Entry**: the activity loads `libtsc_android.so` (`android.app.lib_name`); + android-activity calls `android_main` on a new thread for every activity + instance. It installs crash reports (opt-in, `crash_reports` setting, + `/crash-reports`), looks up the Kotlin `Bridge` class, initialises + `rustls-platform-verifier` (HTTPS certificate checks against the system + trust store), asks for the microphone and notification permissions, sets + Slint's Android backend and runs `tsc_ui::run` with the app's files + directory, Keystore secrets and the process's engine. +- **Engine for the process** (`host.rs`): one tokio runtime and `Engine` + per process. The activity may be destroyed while voice goes on; a new + window attaches and first receives events that rebuild the current state + (server info, state, presence, the last 300 chat messages per session, + streams), then live events (`tsc_ui::HostedEngine`). Back moves the task + to the background instead of finishing the activity; configuration changes + do not recreate it. +- **Voice in the background**: while any session has a voice connection, + `VoiceService` runs as a foreground service of type `microphone` with a + notification ("In voice on …", Mute or Unmute, Disconnect). Rust drives it + from engine events (`foreground.rs`, `Bridge.setVoiceNotification`). Audio + itself is cpal on AAudio, as on desktop. +- **Sharing the screen**: `tsc_media::capture::default_screen_capture()` + returns the MediaProjection provider (`capture.rs`) registered at start. + Starting shows the system consent dialog; on consent `ScreenCaptureService` + (type `mediaProjection`) mirrors the display into an `ImageReader` at the + requested frame rate, longest side at most 1920 px, and hands RGBA frames to + `Native.onScreenFrame`. System audio (`default_audio_capture()`) is + `AudioPlaybackCapture` of media, game and unknown usages, 48 kHz stereo + float, only while the projection runs. Ending the projection from the + status bar or the notification closes the capture channels. +- **Watching and encoding**: `tsc_media::Codecs` uses the device's + MediaCodec encoders (hardware first) and decoders on Android + ([media.md](media.md)). +- **Secrets**: `SecretStore` encrypts each password with AES-256-GCM under a + non-exportable Android Keystore key and keeps the ciphertext in private + preferences. The app disables Android backups (the database holds the + identity's private key). +- **JNI**: Rust calls static methods of `Bridge` (class looked up once on the + `android_main` thread, usable from any thread); Kotlin calls the + `external` methods of `Native`, exported by `native_method!` (panics and + errors become Java exceptions). Keep `bridge.rs`, `Bridge.kt` and + `Native.kt` in step. + +Permissions: `INTERNET`, `ACCESS_NETWORK_STATE`, `RECORD_AUDIO`, +`MODIFY_AUDIO_SETTINGS`, `FOREGROUND_SERVICE` with `_MICROPHONE` and +`_MEDIA_PROJECTION`, `POST_NOTIFICATIONS`. + +## Status + +| What | How | Status | +|---|---|---| +| `libtsc_android.so` for `aarch64-linux-android` (Slint Android backend with Skia, AAudio, AWS-LC, SQLite, libopus) | `cargo ndk -t arm64-v8a build -p tsc-android` | builds; exports `android_main` and the `Native` methods | +| Debug APK | `./gradlew assembleDebug -Ptsc.abis=arm64-v8a` | builds | +| Engine host replay, voice service policy | unit tests (`cargo test -p tsc-android`) | tested | +| External capture providers, MediaCodec buffer layouts | `tsc-media` unit tests | tested | +| The app on a device: UI, voice in the background, screen sharing, watching, Keystore | manual matrix row IN3 and the Android rows | not run yet (no device or emulator in this environment) | + +Known gaps: + +- The streams panel of the UI and the stream media pipeline of `tsc-core` + must build without the desktop media backends on Android (libvpx, X11, + PipeWire): `tsc-media` with `default-features = false` there, so that + `Codecs` uses MediaCodec. +- Rotating the device while sharing letterboxes the picture (the virtual + display keeps its size). +- The safe area (status and navigation bars) and the on-screen keyboard pad + the main window; dialogs drawn over it do not account for them yet. +- Only `arm64-v8a` and `x86_64` are built; 32-bit devices are not supported. +- No audio focus handling yet: a phone call does not pause our audio + (matrix row AN4). After a network change (Wi-Fi to mobile data) only + tsclientlib's own reconnect applies; untested on a phone. diff --git a/docs/architecture.md b/docs/architecture.md index 57ed344..b8038b3 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -71,7 +71,7 @@ fuzz/ cargo-fuzz targets | `tsc-ui` | Slint UI and the desktop binary | done (no streams yet) | | `tsc-media` | Screen and system-audio capture backends (PipeWire portal, X11, Windows Graphics Capture, Android MediaProjection), video codecs | planned | | `tsc-platform` | Global hotkeys, notifications, paths | planned | -| `tsc-android` + `android/` | Android library + Gradle/Kotlin app (foreground services for voice and screen capture) | planned | +| `tsc-android` + `android/` | Android library + Gradle/Kotlin app (foreground services for voice and screen capture); see [android.md](android.md) | builds, not yet run on a device | ## Merging sources diff --git a/docs/media.md b/docs/media.md index 4469277..0792e0c 100644 --- a/docs/media.md +++ b/docs/media.md @@ -50,6 +50,17 @@ software). `Codecs` filters both lists by what is compiled in and loaded. | OpenH264 | `openh264` (default) | H.264 Constrained High / Baseline | H.264 | Cisco's prebuilt binary, loaded at runtime | | dav1d | `av1` | – | AV1 | system libdav1d >= 1.3 (1.4.1 tested) | | hardware | – | not yet | – | `codec::hw::HardwareEncoderFactory`; VA-API and Media Foundation stubs report nothing (TODO) | +| MediaCodec (Android) | – | H.264, VP8, VP9 | VP8, VP9, H.264, AV1 | the device's default codec per type through the NDK (`ndk` crate); a hardware encoder factory named `mediacodec` | + +On Android, `codec::mediacodec` uses byte-buffer mode on both sides, so it +takes and returns `VideoFrame`s like the software codecs. Encoders get NV12 +(else I420) in the layout the codec reports (`image-data` / `stride` / +`slice-height`, parsed by `codec::image_layout`, which is tested on every +platform); H.264 is High (preferably Constrained High) without B-frames, SPS/PPS +in front of every keyframe, keyframes on request (`request-sync`), bitrate +changes at runtime (`video-bitrate`). Encoder order: the device's hardware +encoders (H.264, VP9, VP8), then Google's software VP8 and H.264. Decoders +return the newest finished picture per `decode` call (NV12 or I420). libvpx settings follow libwebrtc's realtime setup: one pass CBR, no lag, `VPX_DL_REALTIME`, error resilient, `cpu-used` 8 (VP8: fixed speed −8), keyframes @@ -57,7 +68,8 @@ only at start and on request unless `keyframe_interval` is set, screen content tuning (`VP8E_SET_SCREEN_CONTENT_MODE`, `VP9E_SET_TUNE_CONTENT`, static threshold), VP9 row-mt, tiles and cyclic-refresh AQ. `set_bitrate` reconfigures the running encoder (`vpx_codec_enc_config_set`). The C API is wrapped in -`codec/vpx/raw.rs`, one of the two modules with `unsafe` code; existing safe +`codec/vpx/raw.rs`, one of three modules with `unsafe` code (with the X11 SHM +mapping and the `Send` wrapper in `codec/mediacodec.rs`); existing safe wrappers either encode only or cannot change the bitrate at runtime. The OpenH264 encoder has no safe runtime bitrate change in the `openh264` @@ -98,9 +110,13 @@ found at ..."). | Linux X11 (`x11`, default) | `X11Capture`: MIT-SHM 1.2 (memfd passed to the server) or GetImage; RandR 1.5 monitors; windows from `_NET_CLIENT_LIST` (root children without a WM); XFixes cursor blended in | | | Linux Wayland (`pipewire`, default) | `PortalCapture`: xdg-desktop-portal ScreenCast via `ashpd`, frames from a PipeWire video stream | `PipeWireAudioCapture`: default sink monitor (`stream.capture.sink = true`) | | Windows | `WindowsCapture`: Windows Graphics Capture (`windows-capture`), monitors and windows | `WasapiLoopback`: process loopback excluding our own process tree, falling back to plain loopback | +| Android | `ExternalScreenCapture` fed by the app (MediaProjection → `ImageReader`, RGBA; see [android.md](android.md)) | `ExternalAudioCapture` fed by the app (`AudioPlaybackCapture`, 48 kHz float) | -`default_screen_capture()` picks the portal when `WAYLAND_DISPLAY` is set (or -`XDG_SESSION_TYPE=wayland`), X11 when `DISPLAY` is set, WGC on Windows. +`default_screen_capture()` picks a registered external provider first +(`capture::external::set_screen_provider`, which the Android app calls at +start), then the portal when `WAYLAND_DISPLAY` is set (or +`XDG_SESSION_TYPE=wayland`), X11 when `DISPLAY` is set, WGC on Windows; +`default_audio_capture()` likewise. Notes: @@ -171,3 +187,6 @@ run on Windows yet. | Portal capture, PipeWire video and audio streams | – | compiles only (no portal or PipeWire daemon here) | | Windows Graphics Capture, WASAPI | – | type-checked for `x86_64-pc-windows-gnu` only | | Hardware encoders | – | stubs | +| External capture providers (start, refusal, end of capture, default selection) | unit tests | tested | +| MediaCodec buffer layouts (I420, NV12 with padding, `MediaImage2` NV21, crop) | unit tests (`codec::image_layout`) | tested | +| MediaCodec encoders and decoders | – | compiles for `aarch64-linux-android` only (no device or emulator here) | diff --git a/docs/release.md b/docs/release.md index f187648..6765448 100644 --- a/docs/release.md +++ b/docs/release.md @@ -132,8 +132,12 @@ repository; losing it means existing installs can no longer be updated. and back it up (two offline copies, password in a password manager). - The Gradle build reads the keystore path, alias and passwords from Gradle properties or environment variables (`~/.gradle/gradle.properties`, CI - secrets), never from files in the repository. Without them it builds - unsigned or debug-signed artifacts only. + secrets), never from files in the repository: `tsc.signing.storeFile`, + `tsc.signing.storePassword`, `tsc.signing.keyAlias`, + `tsc.signing.keyPassword`, or `TSC_SIGNING_STORE_FILE`, + `TSC_SIGNING_STORE_PASSWORD`, `TSC_SIGNING_KEY_ALIAS`, + `TSC_SIGNING_KEY_PASSWORD` ([android.md](android.md)). Without them it + builds unsigned or debug-signed artifacts only. - CI: the keystore as a base64 secret, decoded to `$RUNNER_TEMP`, removed afterwards. Check with `apksigner verify --print-certs app-release.apk`. - Google Play: use Play App Signing; our keystore is then the upload key