diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ef4501d..be550e6 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 --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 9f0cc3d..30dcfc0 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -8682,6 +8682,7 @@ dependencies = [ "tsc-core", "tsc-media", "tsc-model", + "tsc-platform", "tsc-store", "tsc-ui", ] 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..01d902b 100644 --- a/THIRD_PARTY_NOTICES.md +++ b/THIRD_PARTY_NOTICES.md @@ -132,11 +132,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 +2631,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 +9498,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/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..835aed5 --- /dev/null +++ b/android/app/src/main/java/io/github/faumaray/tsc/Bridge.kt @@ -0,0 +1,74 @@ +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; null stops it. */ + @JvmStatic + fun setVoiceNotification(text: String?) { + if (text == null) VoiceService.stop(app) else VoiceService.start(app, text) + } + + /** 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..cb57838 --- /dev/null +++ b/android/app/src/main/java/io/github/faumaray/tsc/Native.kt @@ -0,0 +1,41 @@ +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() +} 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..dca1560 --- /dev/null +++ b/android/app/src/main/java/io/github/faumaray/tsc/Notifications.kt @@ -0,0 +1,56 @@ +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, + ) + + fun ongoing( + context: Context, + channel: String, + text: String, + actionTitle: String, + action: PendingIntent, + ): Notification = Notification.Builder(context, channel) + .setSmallIcon(R.drawable.ic_notification) + .setContentTitle(context.getString(R.string.app_name)) + .setContentText(text) + .setContentIntent(openApp(context)) + .setOngoing(true) + .setCategory(Notification.CATEGORY_CALL) + .addAction(Notification.Action.Builder(null, actionTitle, action).build()) + .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..0e69bf5 --- /dev/null +++ b/android/app/src/main/java/io/github/faumaray/tsc/ScreenCaptureService.kt @@ -0,0 +1,258 @@ +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), + 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..62c338b --- /dev/null +++ b/android/app/src/main/java/io/github/faumaray/tsc/VoiceService.kt @@ -0,0 +1,97 @@ +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 { + if (intent?.action == ACTION_DISCONNECT) { + Native.onDisconnectVoice() + return START_NOT_STICKY + } + val text = intent?.getStringExtra(EXTRA_TEXT) ?: getString(R.string.voice_connected) + try { + if (Build.VERSION.SDK_INT >= 30) { + startForeground(ID, notification(this, text), ServiceInfo.FOREGROUND_SERVICE_TYPE_MICROPHONE) + } else { + startForeground(ID, notification(this, text)) + } + 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 ACTION_DISCONNECT = "io.github.faumaray.tsc.DISCONNECT" + + @Volatile + private var running: VoiceService? = null + + private fun notification(context: Context, text: String): Notification { + val disconnect = PendingIntent.getService( + context, + 0, + Intent(context, VoiceService::class.java).setAction(ACTION_DISCONNECT), + PendingIntent.FLAG_IMMUTABLE, + ) + return Notifications.ongoing( + context, + Notifications.CHANNEL_VOICE, + text, + context.getString(R.string.disconnect), + disconnect, + ) + } + + /** Start the service, or update its notification when it runs. */ + fun start(context: Context, text: String) { + val service = running + if (service != null) { + service.getSystemService(NotificationManager::class.java) + .notify(ID, notification(service, text)) + return + } + try { + context.startForegroundService( + Intent(context, VoiceService::class.java).putExtra(EXTRA_TEXT, text), + ) + } 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..f5c94cb --- /dev/null +++ b/android/app/src/main/res/values/strings.xml @@ -0,0 +1,11 @@ + + + + TS Client + Voice connection + Screen sharing + Connected to voice + Disconnect + 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 index 3f27c20..a2a044a 100644 --- a/crates/tsc-android/Cargo.toml +++ b/crates/tsc-android/Cargo.toml @@ -26,6 +26,7 @@ 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" } diff --git a/crates/tsc-android/src/app.rs b/crates/tsc-android/src/app.rs index db39416..f1c2d63 100644 --- a/crates/tsc-android/src/app.rs +++ b/crates/tsc-android/src/app.rs @@ -4,6 +4,7 @@ //! (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 _; @@ -15,6 +16,9 @@ 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); @@ -56,6 +60,8 @@ fn init_logging() { } 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 @@ -74,7 +80,6 @@ fn run(app: AndroidApp) -> anyhow::Result<()> { warn!("requesting permissions: {e}"); } - let data_dir = app.internal_data_path().context("the app has no internal storage path")?; slint::android::init(app).context("Slint Android backend")?; let attached = host.attach(); tsc_ui::run(tsc_ui::RunOptions { @@ -88,6 +93,17 @@ fn run(app: AndroidApp) -> anyhow::Result<()> { }) } +/// 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(); 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..2809925 --- /dev/null +++ b/docs/android.md @@ -0,0 +1,132 @@ +# 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 …", 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. 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) |