diff --git a/Cargo.lock b/Cargo.lock index 002150b..e719e13 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -9435,6 +9435,7 @@ dependencies = [ "tokio", "tracing", "tracing-subscriber", + "tsclientlib", "voelin-core", "voelin-media", "voelin-model", diff --git a/android/app/build.gradle.kts b/android/app/build.gradle.kts index 19f4bae..4612f00 100644 --- a/android/app/build.gradle.kts +++ b/android/app/build.gradle.kts @@ -34,6 +34,9 @@ val releaseStoreFile = signing("voelin.signing.storeFile", "VOELIN_SIGNING_STORE android { namespace = "io.github.faumaray.voelin" compileSdk = 36 + // What the release workflow and the Docker build install (AGP's + // default would be 35.0.0). + buildToolsVersion = "36.0.0" ndkVersion = "27.3.13750724" defaultConfig { diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml index 6716b43..4af7cc3 100644 --- a/android/app/src/main/AndroidManifest.xml +++ b/android/app/src/main/AndroidManifest.xml @@ -10,6 +10,9 @@ + + + + + + + + + diff --git a/android/app/src/main/java/io/github/faumaray/voelin/Bridge.kt b/android/app/src/main/java/io/github/faumaray/voelin/Bridge.kt index 64a199a..28b912e 100644 --- a/android/app/src/main/java/io/github/faumaray/voelin/Bridge.kt +++ b/android/app/src/main/java/io/github/faumaray/voelin/Bridge.kt @@ -4,7 +4,12 @@ import android.Manifest import android.content.Context import android.content.Intent import android.content.pm.PackageManager +import android.content.pm.ResolveInfo +import android.graphics.Bitmap +import android.graphics.Canvas import android.os.Build +import android.view.Surface +import java.io.File /** * What the Rust library (crates/voelin-android/src/bridge.rs) calls, from any @@ -30,12 +35,23 @@ object Bridge { } /** - * Run the voice service with this notification text (`muted`: the action - * offers Unmute); null stops it. + * Run the voice service with this notification (`muted`, `deafened`: the + * actions offer Unmute, Undeafen; `sinceMs`: in voice since, Unix ms, 0 + * while connecting); a null title stops it. */ @JvmStatic - fun setVoiceNotification(text: String?, muted: Boolean) { - if (text == null) VoiceService.stop(app) else VoiceService.start(app, text, muted) + fun setVoiceNotification(title: String?, text: String?, muted: Boolean, deafened: Boolean, sinceMs: Long) { + if (title == null) { + VoiceService.stop(app) + } else { + VoiceService.start(app, VoiceService.Notice(title, text ?: "", muted, deafened, sinceMs)) + } + } + + /** What the screen-sharing notification says while our stream is live; null: the default. */ + @JvmStatic + fun setScreenNotification(title: String?, text: String?) { + ScreenCaptureService.setNotice(title, text) } /** Ask the user to share the screen; the answer goes to Native.onScreenCaptureResult. */ @@ -54,6 +70,16 @@ object Bridge { ScreenCaptureService.stop(app) } + /** + * Render the shared screen into `surface` (an encoder's input, + * `width` x `height`: the zero-copy path), or with null back into the + * frame reader. + */ + @JvmStatic + fun setScreenSurface(surface: Surface?, width: Int, height: Int) { + ScreenCaptureService.redirect(surface, width, height) + } + /** Capture what the device plays; false without a running screen capture. */ @JvmStatic fun startSystemAudio(): Boolean = ScreenCaptureService.startAudio() @@ -77,7 +103,10 @@ object Bridge { ScreenCaptureService.stopInput(id) } - /** Launchable apps other than us, as "labelpackage" lines sorted by label. */ + /** + * Launchable apps other than us, as "labelpackageicon" lines + * sorted by label; the icon is a PNG in our cache (empty if it has none). + */ @JvmStatic fun launchableApps(): String { val pm = app.packageManager @@ -89,12 +118,54 @@ object Bridge { pm.queryIntentActivities(launcher, 0) } val separators = Regex("[\t\n]") + val icons = File(app.cacheDir, "app-icons").apply { mkdirs() } return activities - .map { it.activityInfo.packageName to it.loadLabel(pm).toString() } - .filter { it.first != app.packageName } - .distinctBy { it.first } - .sortedBy { it.second.lowercase() } - .joinToString("\n") { (packageName, label) -> label.replace(separators, " ") + "\t" + packageName } + .filter { it.activityInfo.packageName != app.packageName } + .distinctBy { it.activityInfo.packageName } + .map { Triple(it, it.activityInfo.packageName, it.loadLabel(pm).toString()) } + .sortedBy { it.third.lowercase() } + .joinToString("\n") { (info, packageName, label) -> + val icon = appIcon(pm, info, packageName, icons)?.path.orEmpty() + label.replace(separators, " ") + "\t" + packageName + "\t" + icon + } + } + + private const val ICON_SIZE = 96 + + /** The app's icon as a PNG in `dir`, drawn once per installed version. */ + private fun appIcon(pm: PackageManager, info: ResolveInfo, packageName: String, dir: File): File? { + val version = info.activityInfo.applicationInfo.sourceDir?.let { File(it).lastModified() } ?: 0L + val file = File(dir, "$packageName-$version.png") + if (file.exists()) return file + return try { + val bitmap = Bitmap.createBitmap(ICON_SIZE, ICON_SIZE, Bitmap.Config.ARGB_8888) + info.loadIcon(pm).apply { setBounds(0, 0, ICON_SIZE, ICON_SIZE) }.draw(Canvas(bitmap)) + file.outputStream().use { bitmap.compress(Bitmap.CompressFormat.PNG, 100, it) } + bitmap.recycle() + // Icons of earlier versions. + dir.listFiles { f -> f.name.startsWith("$packageName-") && f.name != file.name }?.forEach { it.delete() } + file + } catch (e: Exception) { + file.delete() + null + } + } + + /** The cameras, as CameraCapture.list describes them. */ + @JvmStatic + fun cameras(): String = CameraCapture.list(app) + + /** + * Open camera `cameraId` for feed `id` (Native.onCameraFrame, errors to + * Native.onCameraError); 0 x 0: its default size. + */ + @JvmStatic + fun startCamera(id: Long, cameraId: String, width: Int, height: Int, fps: Int): Boolean = + CameraCapture.start(app, id, cameraId, width, height, fps) + + @JvmStatic + fun stopCamera(id: Long) { + CameraCapture.stop(id) } @JvmStatic diff --git a/android/app/src/main/java/io/github/faumaray/voelin/CameraCapture.kt b/android/app/src/main/java/io/github/faumaray/voelin/CameraCapture.kt new file mode 100644 index 0000000..f118a91 --- /dev/null +++ b/android/app/src/main/java/io/github/faumaray/voelin/CameraCapture.kt @@ -0,0 +1,293 @@ +package io.github.faumaray.voelin + +import android.Manifest +import android.content.Context +import android.content.pm.PackageManager +import android.graphics.ImageFormat +import android.hardware.camera2.CameraCaptureSession +import android.hardware.camera2.CameraCharacteristics +import android.hardware.camera2.CameraDevice +import android.hardware.camera2.CameraManager +import android.hardware.camera2.CaptureRequest +import android.hardware.camera2.params.OutputConfiguration +import android.hardware.camera2.params.SessionConfiguration +import android.hardware.display.DisplayManager +import android.media.ImageReader +import android.os.Handler +import android.os.HandlerThread +import android.util.Log +import android.util.Range +import android.util.Size +import android.view.Display +import android.view.Surface +import java.util.concurrent.ConcurrentHashMap +import java.util.concurrent.Executor +import kotlin.math.abs + +/** + * Cameras for the Stream Studio (crates/voelin-android/src/camera.rs): + * Camera2 into an ImageReader (YUV_420_888); each frame's planes go to + * Native.onCameraFrame as direct buffers, valid during the call, so the + * Rust side converts straight from the camera's memory. Several cameras + * may run at once, each under the id the Rust side gave it. + */ +object CameraCapture { + private const val TAG = "CameraCapture" + + /** Without a wish: about this size (16:9, what the studio composes). */ + private const val DEFAULT_WIDTH = 1280 + private const val DEFAULT_HEIGHT = 720 + + private class Running(val id: Long, val cameraId: String) { + @Volatile + var stopped = false + var thread: HandlerThread? = null + var device: CameraDevice? = null + var session: CameraCaptureSession? = null + var reader: ImageReader? = null + } + + private val running = ConcurrentHashMap() + + /** Starts waiting for the CAMERA permission, by id. */ + private val waiting = ConcurrentHashMap Unit>() + + private fun facing(c: CameraCharacteristics): String = when (c.get(CameraCharacteristics.LENS_FACING)) { + CameraCharacteristics.LENS_FACING_FRONT -> "front" + CameraCharacteristics.LENS_FACING_BACK -> "back" + else -> "external" + } + + private fun sizes(c: CameraCharacteristics): List = + c.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP) + ?.getOutputSizes(ImageFormat.YUV_420_888) + ?.sortedByDescending { it.width.toLong() * it.height } + .orEmpty() + + private fun fpsRanges(c: CameraCharacteristics): List> = + c.get(CameraCharacteristics.CONTROL_AE_AVAILABLE_TARGET_FPS_RANGES)?.toList().orEmpty() + + /** + * The cameras, front ones first: "idfacingsizesmaxFps" + * lines, sizes as "1920x1080,1280x720" (largest first). + */ + fun list(context: Context): String { + val manager = context.getSystemService(CameraManager::class.java) ?: return "" + val ids = try { + manager.cameraIdList.toList() + } catch (e: Exception) { + Log.w(TAG, "cannot list the cameras", e) + return "" + } + return ids.mapNotNull { id -> + try { + val c = manager.getCameraCharacteristics(id) + val sizes = sizes(c).joinToString(",") { "${it.width}x${it.height}" } + val fps = fpsRanges(c).maxOfOrNull { it.upper } ?: 30 + Triple(id, facing(c), "$sizes\t$fps") + } catch (e: Exception) { + Log.w(TAG, "cannot ask camera $id", e) + null + } + } + .sortedBy { (_, facing, _) -> if (facing == "front") 0 else if (facing == "back") 1 else 2 } + .joinToString("\n") { (id, facing, rest) -> "$id\t$facing\t$rest" } + } + + /** + * Open `cameraId` for mixer feed `id` at about `width` x `height` (0: + * the default) and `fps`. Asks for the CAMERA permission first if + * needed; failures later go to Native.onCameraError. + */ + fun start(context: Context, id: Long, cameraId: String, width: Int, height: Int, fps: Int): Boolean { + if (context.checkSelfPermission(Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) { + return open(context, id, cameraId, width, height, fps) + } + val activity = MainActivity.current?.get() + if (activity == null) { + Native.onCameraError(id, "Allow Voelin to use the camera (open the app)") + return false + } + waiting[id] = { open(context, id, cameraId, width, height, fps) } + activity.runOnUiThread { activity.requestCameraPermission() } + return true + } + + /** The answer to the CAMERA permission prompt (MainActivity). */ + fun onPermissionResult(granted: Boolean) { + val starts = waiting.keys.toList().mapNotNull { id -> waiting.remove(id)?.let { id to it } } + for ((id, start) in starts) { + if (granted) { + start() + } else { + Native.onCameraError(id, "Voelin may not use the camera (Android settings, Apps, Voelin, Permissions)") + } + } + } + + private fun open(context: Context, id: Long, cameraId: String, width: Int, height: Int, fps: Int): Boolean { + stop(id) + val manager = context.getSystemService(CameraManager::class.java) ?: return false + val c = try { + manager.getCameraCharacteristics(cameraId) + } catch (e: Exception) { + Native.onCameraError(id, "no camera $cameraId: ${e.message}") + return false + } + val size = pick(sizes(c), width, height) ?: run { + Native.onCameraError(id, "camera $cameraId has no YUV output") + return false + } + val range = fpsRange(fpsRanges(c), fps) + val front = c.get(CameraCharacteristics.LENS_FACING) == CameraCharacteristics.LENS_FACING_FRONT + val sensor = c.get(CameraCharacteristics.SENSOR_ORIENTATION) ?: 0 + val display = context.getSystemService(DisplayManager::class.java)?.getDisplay(Display.DEFAULT_DISPLAY) + + val run = Running(id, cameraId) + running[id] = run + val thread = HandlerThread("voelin-camera-$id").also { it.start() } + run.thread = thread + val handler = Handler(thread.looper) + val executor = Executor { handler.post(it) } + val reader = ImageReader.newInstance(size.width, size.height, ImageFormat.YUV_420_888, 3) + run.reader = reader + reader.setOnImageAvailableListener({ r -> + val image = try { + r.acquireLatestImage() + } catch (e: IllegalStateException) { + null + } ?: return@setOnImageAvailableListener + try { + if (run.stopped) return@setOnImageAvailableListener + val planes = image.planes + val wanted = Native.onCameraFrame( + id, + planes[0].buffer, + planes[1].buffer, + planes[2].buffer, + planes[0].rowStride, + planes[1].rowStride, + planes[1].pixelStride, + image.width, + image.height, + rotation(sensor, front, display), + image.timestamp, + ) + if (!wanted) stop(id) + } finally { + image.close() + } + }, handler) + + val fail = { message: String -> + if (!run.stopped) Native.onCameraError(id, message) + stop(id) + } + try { + manager.openCamera(cameraId, executor, object : CameraDevice.StateCallback() { + override fun onOpened(device: CameraDevice) { + if (run.stopped) { + device.close() + return + } + run.device = device + val request = device.createCaptureRequest(CameraDevice.TEMPLATE_RECORD).apply { + addTarget(reader.surface) + if (range != null) set(CaptureRequest.CONTROL_AE_TARGET_FPS_RANGE, range) + } + val outputs = listOf(OutputConfiguration(reader.surface)) + device.createCaptureSession( + SessionConfiguration( + SessionConfiguration.SESSION_REGULAR, + outputs, + executor, + object : CameraCaptureSession.StateCallback() { + override fun onConfigured(session: CameraCaptureSession) { + if (run.stopped) { + session.close() + return + } + run.session = session + try { + session.setRepeatingRequest(request.build(), null, handler) + } catch (e: Exception) { + fail("camera $cameraId: ${e.message}") + } + } + + override fun onConfigureFailed(session: CameraCaptureSession) { + fail("camera $cameraId cannot deliver ${size.width}x${size.height}") + } + }, + ), + ) + } + + override fun onDisconnected(device: CameraDevice) { + device.close() + // Another app took it, or it was unplugged. + fail("camera $cameraId was disconnected") + } + + override fun onError(device: CameraDevice, error: Int) { + device.close() + fail("camera $cameraId failed (error $error)") + } + }) + } catch (e: SecurityException) { + fail("Voelin may not use the camera") + return false + } catch (e: Exception) { + fail("cannot open camera $cameraId: ${e.message}") + return false + } + return true + } + + fun stop(id: Long) { + waiting.remove(id) + val run = running.remove(id) ?: return + run.stopped = true + try { + run.session?.close() + run.device?.close() + } catch (e: Exception) { + Log.w(TAG, "closing camera ${run.cameraId}", e) + } + run.thread?.let { thread -> + // The reader is closed on its own thread, after the last frame. + Handler(thread.looper).post { run.reader?.close() } + thread.quitSafely() + } + } + + /** The wished size if the camera has it, else the nearest in pixels (16:9 first). */ + private fun pick(sizes: List, width: Int, height: Int): Size? { + if (sizes.isEmpty()) return null + val (w, h) = if (width > 0 && height > 0) width to height else DEFAULT_WIDTH to DEFAULT_HEIGHT + sizes.firstOrNull { it.width == w && it.height == h }?.let { return it } + val wanted = w.toLong() * h + val sameShape = sizes.filter { it.width.toLong() * h == it.height.toLong() * w } + return (sameShape.ifEmpty { sizes }).minByOrNull { abs(it.width.toLong() * it.height - wanted) } + } + + /** A fixed `fps` range if there is one, else the nearest that reaches it. */ + private fun fpsRange(ranges: List>, fps: Int): Range? = + ranges.firstOrNull { it.lower == fps && it.upper == fps } + ?: ranges.filter { it.upper >= fps }.minWithOrNull(compareBy({ it.upper }, { -it.lower })) + ?: ranges.maxByOrNull { it.upper } + + /** + * Clockwise degrees that turn the sensor's picture upright for the + * screen's current rotation (front cameras turn the other way). + */ + private fun rotation(sensor: Int, front: Boolean, display: Display?): Int { + val screen = when (display?.rotation) { + Surface.ROTATION_90 -> 90 + Surface.ROTATION_180 -> 180 + Surface.ROTATION_270 -> 270 + else -> 0 + } + return if (front) (sensor + screen) % 360 else (sensor - screen + 360) % 360 + } +} diff --git a/android/app/src/main/java/io/github/faumaray/voelin/MainActivity.kt b/android/app/src/main/java/io/github/faumaray/voelin/MainActivity.kt index 98c995c..ce89123 100644 --- a/android/app/src/main/java/io/github/faumaray/voelin/MainActivity.kt +++ b/android/app/src/main/java/io/github/faumaray/voelin/MainActivity.kt @@ -1,15 +1,24 @@ package io.github.faumaray.voelin +import android.Manifest import android.app.NativeActivity import android.content.Intent +import android.content.pm.PackageManager import android.media.projection.MediaProjectionManager +import android.net.Uri +import android.os.Build import android.os.Bundle +import android.provider.OpenableColumns +import android.util.Log +import java.io.File import java.lang.ref.WeakReference +import kotlin.concurrent.thread /** * The window: a NativeActivity running `android_main` of libvoelin_android.so * (the Slint UI). Kotlin only handles what needs an Activity: permission - * prompts and the screen-capture consent dialog. + * prompts, the screen-capture consent dialog, a tapped notification and + * what is shared to the app ("Share to Voelin"). */ class MainActivity : NativeActivity() { private var captureFps = 30 @@ -18,6 +27,14 @@ class MainActivity : NativeActivity() { override fun onCreate(savedInstanceState: Bundle?) { current = WeakReference(this) super.onCreate(savedInstanceState) + // Not again when the activity is recreated with the same intent. + if (savedInstanceState == null) handle(intent) + } + + override fun onNewIntent(intent: Intent) { + super.onNewIntent(intent) + setIntent(intent) + handle(intent) } override fun onDestroy() { @@ -34,6 +51,92 @@ class MainActivity : NativeActivity() { moveTaskToBack(true) } + /** A tapped voice notification, or something shared to us. */ + private fun handle(intent: Intent?) { + when (intent?.action) { + VoiceService.ACTION_OPEN_VOICE -> Native.onOpenVoice() + Intent.ACTION_SEND, Intent.ACTION_SEND_MULTIPLE -> share(intent) + } + } + + /** + * Text goes into the current chat's composer; files are copied out of the + * sending app (its content URIs are readable only now) into our cache, + * then uploaded to the current channel by the Rust side. + */ + private fun share(intent: Intent) { + val subject = intent.getStringExtra(Intent.EXTRA_SUBJECT)?.trim().orEmpty() + val body = intent.getCharSequenceExtra(Intent.EXTRA_TEXT)?.toString()?.trim().orEmpty() + val text = when { + subject.isEmpty() -> body + body.isEmpty() || body.contains(subject) -> body.ifEmpty { subject } + else -> "$subject\n$body" + }.ifEmpty { null } + val uris = sharedUris(intent) + if (uris.isEmpty()) { + if (text != null) Native.onShare(text, null) + return + } + val resolver = contentResolver + val dir = File(cacheDir, "shared/${System.nanoTime()}") + thread(name = "voelin-share") { + val paths = uris.mapIndexedNotNull { i, uri -> + try { + val name = displayName(uri) ?: "shared-file-${i + 1}" + // Two shared files may have the same name. + val file = File(dir, name).takeUnless { it.exists() } ?: File(dir, "${i + 1}-$name") + dir.mkdirs() + resolver.openInputStream(uri)?.use { input -> + file.outputStream().use { input.copyTo(it) } + } ?: return@mapIndexedNotNull null + file.path + } catch (e: Exception) { + Log.w(TAG, "cannot read the shared $uri", e) + null + } + } + Native.onShare(text, paths.joinToString("\n").ifEmpty { null }) + } + } + + private fun sharedUris(intent: Intent): List = if (intent.action == Intent.ACTION_SEND_MULTIPLE) { + if (Build.VERSION.SDK_INT >= 33) { + intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM, Uri::class.java) + } else { + @Suppress("DEPRECATION") + intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM) + }.orEmpty() + } else { + listOfNotNull( + if (Build.VERSION.SDK_INT >= 33) { + intent.getParcelableExtra(Intent.EXTRA_STREAM, Uri::class.java) + } else { + @Suppress("DEPRECATION") + intent.getParcelableExtra(Intent.EXTRA_STREAM) + }, + ) + } + + /** The file name the sending app gives, made safe as one path component. */ + private fun displayName(uri: Uri): String? { + val name = contentResolver.query(uri, arrayOf(OpenableColumns.DISPLAY_NAME), null, null, null)?.use { + if (it.moveToFirst()) it.getString(0) else null + } ?: uri.lastPathSegment + return name?.replace(Regex("[/\\\\\n\r\u0000]"), "_")?.trim()?.takeIf { it.isNotEmpty() && it != "." && it != ".." } + } + + /** Ask for the camera (a studio camera source); CameraCapture gets the answer. */ + fun requestCameraPermission() { + requestPermissions(arrayOf(Manifest.permission.CAMERA), REQUEST_CAMERA) + } + + override fun onRequestPermissionsResult(requestCode: Int, permissions: Array, grantResults: IntArray) { + super.onRequestPermissionsResult(requestCode, permissions, grantResults) + if (requestCode == REQUEST_CAMERA) { + CameraCapture.onPermissionResult(grantResults.firstOrNull() == PackageManager.PERMISSION_GRANTED) + } + } + /** Show the system's "start recording or casting?" dialog. */ fun requestScreenCapture(fps: Int, maxSize: Int) { captureFps = fps @@ -57,7 +160,9 @@ class MainActivity : NativeActivity() { } companion object { + private const val TAG = "MainActivity" private const val REQUEST_SCREEN_CAPTURE = 1001 + private const val REQUEST_CAMERA = 1002 /** The activity in front, if any. */ @Volatile diff --git a/android/app/src/main/java/io/github/faumaray/voelin/Native.kt b/android/app/src/main/java/io/github/faumaray/voelin/Native.kt index 7aacd8e..877b64a 100644 --- a/android/app/src/main/java/io/github/faumaray/voelin/Native.kt +++ b/android/app/src/main/java/io/github/faumaray/voelin/Native.kt @@ -49,4 +49,46 @@ object Native { /** "Mute" / "Unmute" in the voice notification. */ @JvmStatic external fun onToggleMute() + + /** "Deafen" / "Undeafen" in the voice notification. */ + @JvmStatic + external fun onToggleDeafen() + + /** + * A YUV_420_888 camera frame for feed `id`: the three planes (direct + * buffers, valid during the call), the luma and chroma row strides, the + * chroma pixel stride (1: planar, 2: interleaved), and the clockwise + * rotation that turns it upright. Returns false when it is no longer + * wanted. + */ + @JvmStatic + external fun onCameraFrame( + id: Long, + y: ByteBuffer, + u: ByteBuffer, + v: ByteBuffer, + yRowStride: Int, + uvRowStride: Int, + uvPixelStride: Int, + width: Int, + height: Int, + rotation: Int, + timestampNs: Long, + ): Boolean + + /** Camera feed `id` failed or could not start (`message`: why). */ + @JvmStatic + external fun onCameraError(id: Long, message: String) + + /** The voice notification was tapped: show the voice channel. */ + @JvmStatic + external fun onOpenVoice() + + /** + * Shared to the app ("Share to Voelin"): text for the current chat's + * composer, and copies of the shared files (one path per line) for the + * current channel. + */ + @JvmStatic + external fun onShare(text: String?, paths: String?) } diff --git a/android/app/src/main/java/io/github/faumaray/voelin/Notifications.kt b/android/app/src/main/java/io/github/faumaray/voelin/Notifications.kt index f537eee..07fedbb 100644 --- a/android/app/src/main/java/io/github/faumaray/voelin/Notifications.kt +++ b/android/app/src/main/java/io/github/faumaray/voelin/Notifications.kt @@ -12,6 +12,9 @@ object Notifications { const val CHANNEL_VOICE = "voice" const val CHANNEL_SCREEN = "screen" + /** The app's accent (Theme.accent of the UI). */ + private const val ACCENT = 0xFF2D6BFF.toInt() + fun createChannels(context: Context) { val manager = context.getSystemService(NotificationManager::class.java) manager.createNotificationChannel( @@ -30,31 +33,45 @@ object Notifications { ) } - /** Tapping a notification brings the app back. */ - private fun openApp(context: Context): PendingIntent = PendingIntent.getActivity( + /** Tapping a notification brings the app back, with `action` for MainActivity. */ + fun openApp(context: Context, action: String? = null): PendingIntent = PendingIntent.getActivity( context, - 0, - Intent(context, MainActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT), + action.hashCode(), + Intent(context, MainActivity::class.java) + .setAction(action) + .addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT), PendingIntent.FLAG_IMMUTABLE, ) - /** An ongoing notification with `actions` (title, intent). */ + /** + * An ongoing notification: `title` and `text`, a chronometer from + * `sinceMs` (Unix ms; 0: none), `actions` (title, intent). + */ fun ongoing( context: Context, channel: String, + title: String, text: String, + open: PendingIntent, + sinceMs: Long, vararg actions: Pair, ): Notification { val builder = Notification.Builder(context, channel) .setSmallIcon(R.drawable.ic_notification) - .setContentTitle(context.getString(R.string.app_name)) + .setColor(ACCENT) + .setContentTitle(title) .setContentText(text) - .setContentIntent(openApp(context)) + .setContentIntent(open) .setOngoing(true) .setOnlyAlertOnce(true) .setCategory(Notification.CATEGORY_CALL) - for ((title, intent) in actions) { - builder.addAction(Notification.Action.Builder(null, title, intent).build()) + if (sinceMs > 0) { + builder.setWhen(sinceMs).setShowWhen(true).setUsesChronometer(true) + } else { + builder.setShowWhen(false) + } + for ((label, intent) in actions) { + builder.addAction(Notification.Action.Builder(null, label, intent).build()) } return builder.build() } diff --git a/android/app/src/main/java/io/github/faumaray/voelin/ScreenCaptureService.kt b/android/app/src/main/java/io/github/faumaray/voelin/ScreenCaptureService.kt index 0daf999..b76a793 100644 --- a/android/app/src/main/java/io/github/faumaray/voelin/ScreenCaptureService.kt +++ b/android/app/src/main/java/io/github/faumaray/voelin/ScreenCaptureService.kt @@ -1,6 +1,8 @@ package io.github.faumaray.voelin import android.Manifest +import android.app.Notification +import android.app.NotificationManager import android.app.PendingIntent import android.app.Service import android.content.Context @@ -34,9 +36,10 @@ 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 - * other apps play (AudioPlaybackCapture: all but us, or one app) for - * Native.onSystemAudio and Native.onAudioInput. + * hands each RGBA frame to Native.onScreenFrame, or (the zero-copy path, + * Bridge.setScreenSurface) straight into an encoder's input surface; + * optionally captures what other apps play (AudioPlaybackCapture: all but + * us, or one app) for Native.onSystemAudio and Native.onAudioInput. */ class ScreenCaptureService : Service() { private var projection: MediaProjection? = null @@ -66,21 +69,9 @@ class ScreenCaptureService : Service() { 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) + startForeground(ID, notification(this), ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PROJECTION) val data = if (Build.VERSION.SDK_INT >= 33) { intent.getParcelableExtra(EXTRA_DATA, Intent::class.java) } else { @@ -159,6 +150,32 @@ class ScreenCaptureService : Service() { ) } + /** + * Point the virtual display at `surface` (an encoder's input surface, + * `width` x `height`: the screen goes into the encoder without a copy), + * or with null back at the reader, at the reader's size. + */ + @Synchronized + private fun redirectTo(surface: Surface?, width: Int, height: Int) { + val display = display ?: return + val reader = reader ?: return + val dpi = resources.displayMetrics.densityDpi + try { + // Detached while resizing, so neither consumer gets a picture of + // the other's size. + display.surface = null + if (surface != null) { + display.resize(width, height, dpi) + display.surface = surface + } else { + display.resize(reader.width, reader.height, dpi) + display.surface = reader.surface + } + } catch (e: RuntimeException) { + Log.w(TAG, "cannot point the screen at ${if (surface != null) "the encoder" else "the reader"}", e) + } + } + /** * Capture media, game and unknown-usage playback as 48 kHz stereo float: * of app `uid`, or with null of every app but us (our voices and watched @@ -259,6 +276,36 @@ class ScreenCaptureService : Service() { @Volatile private var instance: ScreenCaptureService? = null + /** Where our stream is live and who watches ("Live in Chill Zone"), or null. */ + @Volatile + private var notice: Pair? = null + + private fun notification(context: Context): Notification { + val stop = PendingIntent.getService( + context, + 0, + Intent(context, ScreenCaptureService::class.java).setAction(ACTION_STOP), + PendingIntent.FLAG_IMMUTABLE, + ) + val (title, text) = notice ?: (context.getString(R.string.screen_sharing) to context.getString(R.string.screen_sharing_text)) + return Notifications.ongoing( + context, + Notifications.CHANNEL_SCREEN, + title, + text, + Notifications.openApp(context), + 0, + context.getString(R.string.stop_sharing) to stop, + ) + } + + /** What the notification says while our stream is live (null: the default). */ + fun setNotice(title: String?, text: String?) { + notice = if (title != null) title to (text ?: "") else null + val service = instance ?: return + service.getSystemService(NotificationManager::class.java).notify(ID, notification(service)) + } + /** 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) @@ -273,6 +320,11 @@ class ScreenCaptureService : Service() { context.stopService(Intent(context, ScreenCaptureService::class.java)) } + /** See redirectTo; nothing without a running capture. */ + fun redirect(surface: Surface?, width: Int, height: Int) { + instance?.redirectTo(surface, width, height) + } + fun startAudio(): Boolean { val service = instance ?: return false return service.startAudioCapture(SYSTEM_AUDIO, null) diff --git a/android/app/src/main/java/io/github/faumaray/voelin/VoelinApp.kt b/android/app/src/main/java/io/github/faumaray/voelin/VoelinApp.kt index 848ad83..700a3ac 100644 --- a/android/app/src/main/java/io/github/faumaray/voelin/VoelinApp.kt +++ b/android/app/src/main/java/io/github/faumaray/voelin/VoelinApp.kt @@ -1,6 +1,7 @@ package io.github.faumaray.voelin import android.app.Application +import java.io.File /** The process's application object; the Rust side reaches Android through it. */ class VoelinApp : Application() { @@ -8,6 +9,8 @@ class VoelinApp : Application() { super.onCreate() instance = this Notifications.createChannels(this) + // Copies of files shared to us (MainActivity.share) from before. + File(cacheDir, "shared").deleteRecursively() } companion object { diff --git a/android/app/src/main/java/io/github/faumaray/voelin/VoiceService.kt b/android/app/src/main/java/io/github/faumaray/voelin/VoiceService.kt index b0e15d2..0f43e0f 100644 --- a/android/app/src/main/java/io/github/faumaray/voelin/VoiceService.kt +++ b/android/app/src/main/java/io/github/faumaray/voelin/VoiceService.kt @@ -15,8 +15,19 @@ 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. + * Its notification is the voice bar of the app: the channel, the server and + * how many are there, the time in voice, and Mute, Deafen and Leave. */ class VoiceService : Service() { + /** What the notification shows (crates/voelin-android/src/foreground.rs). */ + data class Notice( + val title: String, + val text: String, + val muted: Boolean, + val deafened: Boolean, + val sinceMs: Long, + ) + override fun onBind(intent: Intent?): IBinder? = null override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { @@ -29,14 +40,17 @@ class VoiceService : Service() { Native.onToggleMute() return START_NOT_STICKY } + ACTION_TOGGLE_DEAFEN -> { + Native.onToggleDeafen() + return START_NOT_STICKY + } } - val text = intent?.getStringExtra(EXTRA_TEXT) ?: getString(R.string.voice_connected) - val muted = intent?.getBooleanExtra(EXTRA_MUTED, false) ?: false + val notice = notice ?: Notice(getString(R.string.voice_connected), "", false, false, 0) try { if (Build.VERSION.SDK_INT >= 30) { - startForeground(ID, notification(this, text, muted), ServiceInfo.FOREGROUND_SERVICE_TYPE_MICROPHONE) + startForeground(ID, notification(this, notice), ServiceInfo.FOREGROUND_SERVICE_TYPE_MICROPHONE) } else { - startForeground(ID, notification(this, text, muted)) + startForeground(ID, notification(this, notice)) } running = this } catch (e: RuntimeException) { @@ -56,14 +70,20 @@ class VoiceService : Service() { 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.voelin.DISCONNECT" private const val ACTION_TOGGLE_MUTE = "io.github.faumaray.voelin.TOGGLE_MUTE" + private const val ACTION_TOGGLE_DEAFEN = "io.github.faumaray.voelin.TOGGLE_DEAFEN" + + /** MainActivity shows the voice channel for this action. */ + const val ACTION_OPEN_VOICE = "io.github.faumaray.voelin.OPEN_VOICE" @Volatile private var running: VoiceService? = null + /** The latest notice, for a service that is still starting. */ + @Volatile + private var notice: Notice? = null + private fun action(context: Context, action: String, request: Int): PendingIntent = PendingIntent.getService( context, @@ -72,30 +92,32 @@ class VoiceService : Service() { PendingIntent.FLAG_IMMUTABLE, ) - private fun notification(context: Context, text: String, muted: Boolean): Notification = + private fun notification(context: Context, notice: Notice): Notification = Notifications.ongoing( context, Notifications.CHANNEL_VOICE, - text, - context.getString(if (muted) R.string.unmute else R.string.mute) to + notice.title, + notice.text, + Notifications.openApp(context, ACTION_OPEN_VOICE), + notice.sinceMs, + context.getString(if (notice.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), + context.getString(if (notice.deafened) R.string.undeafen else R.string.deafen) to + action(context, ACTION_TOGGLE_DEAFEN, 2), + context.getString(R.string.leave) to action(context, ACTION_DISCONNECT, 0), ) /** Start the service, or update its notification when it runs. */ - fun start(context: Context, text: String, muted: Boolean) { + fun start(context: Context, notice: Notice) { + this.notice = notice val service = running if (service != null) { service.getSystemService(NotificationManager::class.java) - .notify(ID, notification(service, text, muted)) + .notify(ID, notification(service, notice)) return } try { - context.startForegroundService( - Intent(context, VoiceService::class.java) - .putExtra(EXTRA_TEXT, text) - .putExtra(EXTRA_MUTED, muted), - ) + context.startForegroundService(Intent(context, VoiceService::class.java)) } catch (e: RuntimeException) { // Not allowed from the background (Android 12+). Voice is // connected from the UI, so this should not happen. @@ -104,6 +126,7 @@ class VoiceService : Service() { } fun stop(context: Context) { + notice = null context.stopService(Intent(context, VoiceService::class.java)) } } diff --git a/android/app/src/main/res/values/strings.xml b/android/app/src/main/res/values/strings.xml index 864bada..f365cd0 100644 --- a/android/app/src/main/res/values/strings.xml +++ b/android/app/src/main/res/values/strings.xml @@ -1,12 +1,16 @@ Voelin + Voelin Voice connection Screen sharing Connected to voice - Disconnect + Leave Mute Unmute + Deafen + Undeafen Sharing your screen + Starting the stream Stop sharing diff --git a/crates/voelin-android/Cargo.toml b/crates/voelin-android/Cargo.toml index 4bca1ef..7ba4c75 100644 --- a/crates/voelin-android/Cargo.toml +++ b/crates/voelin-android/Cargo.toml @@ -18,6 +18,8 @@ crate-type = ["cdylib", "rlib"] tokio = { version = "1.53.1", features = ["rt-multi-thread", "macros", "sync", "time"] } tracing = "0.1.44" voelin-core = { path = "../voelin-core" } +# Channels and people for the voice notification. +voelin-model = { path = "../voelin-model" } [target.'cfg(target_os = "android")'.dependencies] anyhow = "1.0.104" @@ -31,7 +33,8 @@ voelin-store = { path = "../voelin-store" } voelin-ui = { path = "../voelin-ui" } [dev-dependencies] -voelin-model = { path = "../voelin-model" } +# Client ids of stream viewers in the tests. +tsclientlib = { path = "../proto/tsclientlib" } [lints] workspace = true diff --git a/crates/voelin-android/src/app.rs b/crates/voelin-android/src/app.rs index 4290811..0bb4b58 100644 --- a/crates/voelin-android/src/app.rs +++ b/crates/voelin-android/src/app.rs @@ -14,7 +14,7 @@ use voelin_core::Command; use crate::foreground::Foreground; use crate::host::EngineHost; -use crate::{bridge, capture, egl, secrets}; +use crate::{bridge, camera, capture, egl, secrets}; /// Store setting (`bool`): the user's opt-in to local crash reports (read /// before the settings service starts, straight from the database). @@ -77,6 +77,7 @@ fn run(app: AndroidApp) -> anyhow::Result<()> { // Before Slint creates the first window surface. egl::reserve_skia_extension_slots(); capture::register(); + camera::register(); watch_voice(host); }); if let Err(e) = bridge::request_permissions() { @@ -108,18 +109,25 @@ fn install_crash_reports(data_dir: &Path) { voelin_platform::crash::install(data_dir.join(voelin_platform::crash::DIR_NAME), enabled); } -/// Keep the voice foreground service in step with the voice connections. +/// Keep the voice foreground service, and the screen-sharing service's +/// notification, in step with the voice connections and our stream. 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 changes = with_foreground(|f| f.update(&event)); + if let Some(notice) = changes.voice && let Err(e) = bridge::set_voice_notification(notice.as_ref()) { warn!("voice service: {e}"); } + if let Some(notice) = changes.screen + && let Err(e) = bridge::set_screen_notification(notice.as_ref()) + { + warn!("screen sharing notification: {e}"); + } } Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => continue, Err(tokio::sync::broadcast::error::RecvError::Closed) => break, @@ -150,3 +158,15 @@ pub fn toggle_mute() { host.engine().send(Command::SetInputMuted { session, muted: !muted }); } } + +/// "Deafen" / "Undeafen" in the voice notification, as Mute does. +pub fn toggle_deafen() { + let Some(host) = HOST.get() else { + return; + }; + let (sessions, deafened) = + with_foreground(|f| (f.voice_sessions(), f.notice().is_some_and(|n| n.deafened))); + for session in sessions { + host.engine().send(Command::SetOutputMuted { session, muted: !deafened }); + } +} diff --git a/crates/voelin-android/src/bridge.rs b/crates/voelin-android/src/bridge.rs index f7d442d..1047256 100644 --- a/crates/voelin-android/src/bridge.rs +++ b/crates/voelin-android/src/bridge.rs @@ -15,7 +15,7 @@ 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; +use crate::foreground::{ScreenNotice, VoiceNotice}; static BRIDGE: OnceLock>> = OnceLock::new(); @@ -58,18 +58,90 @@ pub fn request_permissions() -> Result<()> { }) } +/// A Java string, or `null` for `None`. +fn string_or_null<'local>(env: &mut Env<'local>, text: Option<&str>) -> Result> { + Ok(match text { + Some(text) => JObject::from(env.new_string(text)?), + None => JObject::null(), + }) +} + /// 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), - }; + let title = string_or_null(env, notice.map(|n| n.title.as_str()))?; + let text = string_or_null(env, notice.map(|n| n.text.as_str()))?; + let (muted, deafened, since) = + notice.map_or((false, false, 0), |n| (n.muted, n.deafened, n.since_ms)); env.call_static_method( class, jni_str!("setVoiceNotification"), - jni_sig!((text: java.lang.String, muted: jboolean) -> void), - &[JValue::Object(&text), JValue::Bool(muted)], + jni_sig!( + ( + title: java.lang.String, + text: java.lang.String, + muted: jboolean, + deafened: jboolean, + since_ms: jlong, + ) -> void + ), + &[ + JValue::Object(&title), + JValue::Object(&text), + JValue::Bool(muted), + JValue::Bool(deafened), + JValue::Long(since as jlong), + ], + )?; + Ok(()) + }) +} + +/// What the screen-sharing notification says while our stream is live; +/// `None` puts back the plain "sharing your screen". +pub fn set_screen_notification(notice: Option<&ScreenNotice>) -> Result<()> { + with_bridge(|env, class| { + let title = string_or_null(env, notice.map(|n| n.title.as_str()))?; + let text = string_or_null(env, notice.map(|n| n.text.as_str()))?; + env.call_static_method( + class, + jni_str!("setScreenNotification"), + jni_sig!((title: java.lang.String, text: java.lang.String) -> void), + &[JValue::Object(&title), JValue::Object(&text)], + )?; + Ok(()) + }) +} + +/// Point the screen's virtual display at an encoder's input surface (the +/// zero-copy path), or back at the frame reader with `None`. +pub fn set_screen_surface( + surface: Option<&voelin_media::codec::mediacodec::InputSurface>, +) -> Result<()> { + with_bridge(|env, class| { + let (object, width, height) = match surface { + Some(surface) => { + // SAFETY: `env` is this thread's JNI environment, and the + // window stays alive (`surface` holds a reference) while + // Java makes a Surface of it. + #[allow(unsafe_code)] + let raw = unsafe { surface.window.to_surface(env.get_raw().cast()) }; + if raw.is_null() { + return Err(Error::NullPtr("encoder surface")); + } + // SAFETY: `raw` is a new local reference to an + // android.view.Surface of this frame. + #[allow(unsafe_code)] + let object = unsafe { JObject::from_raw(env, raw.cast()) }; + (object, surface.width, surface.height) + } + None => (JObject::null(), 0, 0), + }; + env.call_static_method( + class, + jni_str!("setScreenSurface"), + jni_sig!((surface: android.view.Surface, width: jint, height: jint) -> void), + &[JValue::Object(&object), JValue::Int(width as jint), JValue::Int(height as jint)], )?; Ok(()) }) @@ -143,8 +215,9 @@ pub fn stop_audio_input(id: u64) -> Result<()> { }) } -/// Launchable apps other than ours, as `(label, package)`, sorted by label. -pub fn launchable_apps() -> Result> { +/// Launchable apps other than ours, as `(label, package, icon)`, sorted by +/// label; `icon` is the path of a PNG in the app's cache, or empty. +pub fn launchable_apps() -> Result> { let lines = with_bridge(|env, class| { let value = env .call_static_method( @@ -163,19 +236,71 @@ pub fn launchable_apps() -> Result> { Ok(parse_apps(&lines)) } -/// `labelpackage` lines. -fn parse_apps(lines: &str) -> Vec<(String, String)> { +/// `labelpackageicon` lines (the icon may be missing). +fn parse_apps(lines: &str) -> Vec<(String, String, String)> { lines .lines() .filter_map(|line| { - let (label, package) = line.split_once('\t')?; - let package = package.trim(); - let label = if label.trim().is_empty() { package } else { label.trim() }; - (!package.is_empty()).then(|| (label.to_owned(), package.to_owned())) + let mut parts = line.split('\t'); + let label = parts.next()?.trim(); + let package = parts.next()?.trim(); + let icon = parts.next().unwrap_or_default().trim(); + let label = if label.is_empty() { package } else { label }; + (!package.is_empty()).then(|| (label.to_owned(), package.to_owned(), icon.to_owned())) }) .collect() } +/// The cameras (`CameraCapture.list`): `idfacingsizesmaxFps` +/// lines. +pub fn cameras() -> Result { + with_bridge(|env, class| { + let value = env + .call_static_method(class, jni_str!("cameras"), jni_sig!(() -> java.lang.String), &[])? + .l()?; + if value.is_null() { + return Ok(String::new()); + } + let value = env.cast_local::(value)?; + value.try_to_string(env) + }) +} + +/// Open camera `device` for feed `id` (frames to `Native.onCameraFrame`, +/// later failures to `Native.onCameraError`); 0 x 0: its default size. +pub fn start_camera(id: u64, device: &str, width: u32, height: u32, fps: u32) -> Result { + with_bridge(|env, class| { + let device = JObject::from(env.new_string(device)?); + env.call_static_method( + class, + jni_str!("startCamera"), + jni_sig!( + (id: jlong, camera_id: java.lang.String, width: jint, height: jint, fps: jint) -> jboolean + ), + &[ + JValue::Long(id as jlong), + JValue::Object(&device), + JValue::Int(width as jint), + JValue::Int(height as jint), + JValue::Int(fps as jint), + ], + )? + .z() + }) +} + +pub fn stop_camera(id: u64) -> Result<()> { + with_bridge(|env, class| { + env.call_static_method( + class, + jni_str!("stopCamera"), + jni_sig!((id: jlong) -> void), + &[JValue::Long(id as jlong)], + )?; + Ok(()) + }) +} + pub fn secret_get(key: &str) -> Result> { with_bridge(|env, class| { let key = JObject::from(env.new_string(key)?); @@ -271,9 +396,10 @@ fn on_screen_frame<'local>( 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. + // the `Image` it belongs to stays open until this call returns (the + // frame is borrowed only during it). #[allow(unsafe_code)] - let bytes = unsafe { std::slice::from_raw_parts(address, capacity) }.to_vec(); + let bytes = unsafe { std::slice::from_raw_parts(address, capacity) }; Ok(crate::capture::on_frame( bytes, width.max(0) as u32, @@ -331,7 +457,9 @@ fn on_audio_input<'local>( channels: jint, ) -> Result { thread_local! { - // One per capture thread, reused for every call. + // One per capture thread, reused for every call. (It is `const`; + // clippy for Android does not see that through the expansion.) + #[allow(clippy::missing_const_for_thread_local)] static BUFFER: std::cell::RefCell> = const { std::cell::RefCell::new(Vec::new()) }; } let id = id as u64; @@ -345,6 +473,101 @@ fn on_audio_input<'local>( }) } +/// The memory of a direct buffer: its address and capacity. +fn direct(env: &Env<'_>, buffer: &JByteBuffer<'_>, what: &'static str) -> Result<(*mut u8, usize)> { + let address = env.get_direct_buffer_address(buffer)?; + if address.is_null() { + return Err(Error::NullPtr(what)); + } + Ok((address, env.get_direct_buffer_capacity(buffer)?)) +} + +const _: jni::NativeMethod = native_method! { + java_type = "io.github.faumaray.voelin.Native", + static extern fn on_camera_frame( + id: jlong, + y: JByteBuffer, + u: JByteBuffer, + v: JByteBuffer, + y_row_stride: jint, + uv_row_stride: jint, + uv_pixel_stride: jint, + width: jint, + height: jint, + rotation: jint, + timestamp_ns: jlong, + ) -> jboolean, +}; + +/// A YUV_420_888 camera frame (see `crate::camera`). Returns `false` once +/// it is no longer wanted. +#[allow(clippy::too_many_arguments)] +fn on_camera_frame<'local>( + env: &mut Env<'local>, + _class: JClass<'local>, + id: jlong, + y: JByteBuffer<'local>, + u: JByteBuffer<'local>, + v: JByteBuffer<'local>, + y_row_stride: jint, + uv_row_stride: jint, + uv_pixel_stride: jint, + width: jint, + height: jint, + rotation: jint, + timestamp_ns: jlong, +) -> Result { + let (y_at, y_len) = direct(env, &y, "camera luma")?; + let (u_at, u_len) = direct(env, &u, "camera U")?; + let (v_at, v_len) = direct(env, &v, "camera V")?; + let step = uv_pixel_stride.max(1) as usize; + // SAFETY: a direct buffer's memory is `capacity` bytes at its address, + // and the `Image` the planes belong to stays open until this call + // returns. With V one byte after U (interleaved, U first), U's address + // and V's length plus one span both planes up to the end of V's buffer: + // memory of the same image. + #[allow(unsafe_code)] + let (y, u, v, nv12) = unsafe { + let nv12 = (step == 2 && v_at as usize == u_at as usize + 1) + .then(|| std::slice::from_raw_parts(u_at, v_len + 1)); + ( + std::slice::from_raw_parts(y_at, y_len), + std::slice::from_raw_parts(u_at, u_len), + std::slice::from_raw_parts(v_at, v_len), + nv12, + ) + }; + let planes = voelin_media::studio::camera::YuvPlanes { + width: width.max(0) as u32, + height: height.max(0) as u32, + y, + y_stride: y_row_stride.max(0) as usize, + u, + v, + uv_stride: uv_row_stride.max(0) as usize, + uv_step: step, + nv12, + rotation: rotation.max(0) as u32, + }; + Ok(crate::camera::on_frame(id as u64, &planes, timestamp_ns)) +} + +const _: jni::NativeMethod = native_method! { + java_type = "io.github.faumaray.voelin.Native", + static extern fn on_camera_error(id: jlong, message: JString), +}; + +fn on_camera_error<'local>( + env: &mut Env<'local>, + _class: JClass<'local>, + id: jlong, + message: JString<'local>, +) -> Result<()> { + let message = if message.is_null() { String::new() } else { message.try_to_string(env)? }; + crate::camera::on_error(id as u64, message); + Ok(()) +} + const _: jni::NativeMethod = native_method! { java_type = "io.github.faumaray.voelin.Native", static extern fn on_disconnect_voice(), @@ -366,3 +589,45 @@ fn on_toggle_mute<'local>(_env: &mut Env<'local>, _class: JClass<'local>) -> Res crate::app::toggle_mute(); Ok(()) } + +const _: jni::NativeMethod = native_method! { + java_type = "io.github.faumaray.voelin.Native", + static extern fn on_toggle_deafen(), +}; + +/// "Deafen" / "Undeafen" in the voice notification. +fn on_toggle_deafen<'local>(_env: &mut Env<'local>, _class: JClass<'local>) -> Result<()> { + crate::app::toggle_deafen(); + Ok(()) +} + +const _: jni::NativeMethod = native_method! { + java_type = "io.github.faumaray.voelin.Native", + static extern fn on_open_voice(), +}; + +/// The voice notification was tapped: show the voice channel. +fn on_open_voice<'local>(_env: &mut Env<'local>, _class: JClass<'local>) -> Result<()> { + voelin_ui::request(voelin_ui::Request::ShowVoice); + Ok(()) +} + +const _: jni::NativeMethod = native_method! { + java_type = "io.github.faumaray.voelin.Native", + static extern fn on_share(text: JString, paths: JString), +}; + +/// Shared to the app: text, and copies of the shared files (one path per +/// line). +fn on_share<'local>( + env: &mut Env<'local>, + _class: JClass<'local>, + text: JString<'local>, + paths: JString<'local>, +) -> Result<()> { + let text = if text.is_null() { None } else { Some(text.try_to_string(env)?) }; + let paths = if paths.is_null() { String::new() } else { paths.try_to_string(env)? }; + let files = paths.lines().filter(|l| !l.is_empty()).map(std::path::PathBuf::from).collect(); + voelin_ui::request(voelin_ui::Request::Share { text, files }); + Ok(()) +} diff --git a/crates/voelin-android/src/camera.rs b/crates/voelin-android/src/camera.rs new file mode 100644 index 0000000..15c38ec --- /dev/null +++ b/crates/voelin-android/src/camera.rs @@ -0,0 +1,174 @@ +//! Cameras for the Stream Studio through Camera2. +//! +//! Registered as the studio's [`CameraProvider`]: the studio's camera +//! picker lists the device's cameras (front ones first; a back camera is +//! not mirrored by default), and a camera source opens one. +//! `CameraCapture.kt` asks for the CAMERA permission if needed, opens the +//! camera into an `ImageReader` (YUV_420_888) and hands each frame's planes +//! to [`on_frame`] as direct buffers valid during the call, with the turn +//! that makes it upright for the screen's rotation. The studio's sink +//! converts straight from the camera's memory when the picture is upright +//! and planar or NV12; otherwise it is gathered (and turned) into a buffer +//! each camera keeps, so a running camera allocates nothing per frame. + +use std::collections::HashMap; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::{Arc, Mutex, MutexGuard, PoisonError}; +use std::time::Duration; + +use tracing::warn; +use voelin_media::capture::FrameSink; +use voelin_media::studio::camera::{Camera, CameraProvider, Format, Pixel, YuvPlanes}; +use voelin_media::studio::compose::Feed; +use voelin_media::{Error, Result}; + +use crate::bridge; + +const BACKEND: &str = "camera2"; + +struct Running { + sink: Box, + feed: Arc, + /// Clock origin of the frames' timestamps (`Image.timestamp`). + origin_ns: Option, + /// Gathered or turned pictures (I420), reused. + scratch: Vec, +} + +static RUNNING: Mutex>> = Mutex::new(None); + +fn running() -> MutexGuard<'static, Option>> { + RUNNING.lock().unwrap_or_else(PoisonError::into_inner) +} + +/// Make Camera2 the studio's cameras. +pub fn register() { + voelin_media::studio::camera::set_provider(Some(Arc::new(Camera2))); +} + +struct Camera2; + +/// Stops its camera when dropped. +struct Guard(u64); + +impl Drop for Guard { + fn drop(&mut self) { + running().as_mut().map(|r| r.remove(&self.0)); + if let Err(e) = bridge::stop_camera(self.0) { + warn!("stopping camera {}: {e}", self.0); + } + } +} + +impl CameraProvider for Camera2 { + fn name(&self) -> &'static str { + BACKEND + } + + fn list(&self) -> Vec { + match bridge::cameras() { + Ok(lines) => parse(&lines), + Err(e) => { + warn!("listing cameras: {e}"); + Vec::new() + } + } + } + + fn start( + &self, + device: &str, + size: Option<(u32, u32)>, + fps: u32, + sink: Box, + feed: Arc, + ) -> Result> { + static NEXT: AtomicU64 = AtomicU64::new(1); + let id = NEXT.fetch_add(1, Ordering::Relaxed); + let entry = Running { sink, feed, origin_ns: None, scratch: Vec::new() }; + running().get_or_insert_with(HashMap::new).insert(id, entry); + let (width, height) = size.unwrap_or((0, 0)); + match bridge::start_camera(id, device, width, height, fps) { + Ok(true) => Ok(Box::new(Guard(id))), + started => { + running().as_mut().map(|r| r.remove(&id)); + let reason = match started { + Err(e) => e.to_string(), + _ => format!("camera {device:?} cannot be opened"), + }; + Err(Error::CaptureUnavailable { backend: BACKEND, reason }) + } + } + } +} + +/// `idfacingsizesmaxFps` lines (`CameraCapture.list`). +fn parse(lines: &str) -> Vec { + let mut seen: HashMap = HashMap::new(); + lines + .lines() + .filter_map(|line| { + let mut parts = line.split('\t'); + let id = parts.next()?.trim(); + let facing = parts.next()?.trim(); + let sizes = parts + .next() + .unwrap_or_default() + .split(',') + .filter_map(|s| { + let (w, h) = s.trim().split_once('x')?; + Some((w.parse().ok()?, h.parse().ok()?)) + }) + .collect::>(); + let max_fps = parts.next().and_then(|f| f.trim().parse().ok()).unwrap_or(0); + if id.is_empty() { + return None; + } + let label = match facing { + "front" => "Front camera", + "back" => "Back camera", + _ => "External camera", + }; + let n = seen.entry(label.to_owned()).or_insert(0); + *n += 1; + let name = if *n == 1 { label.to_owned() } else { format!("{label} {n}") }; + Some(Camera { + id: id.to_owned(), + name, + backend: BACKEND, + formats: vec![Format { pixel: Pixel::I420, sizes, max_fps }], + // What faces the user is mirrored, as a mirror would be. + mirrored: facing != "back", + }) + }) + .collect() +} + +/// A frame of camera `id`. Returns `false` once it is no longer wanted. +pub fn on_frame(id: u64, planes: &YuvPlanes<'_>, timestamp_ns: i64) -> bool { + let mut guard = running(); + let Some(run) = guard.as_mut().and_then(|r| r.get_mut(&id)) else { return false }; + let Running { sink, feed, origin_ns, scratch } = run; + if feed.is_closed() { + return false; + } + let origin = *origin_ns.get_or_insert(timestamp_ns); + let timestamp = Duration::from_nanos(u64::try_from(timestamp_ns - origin).unwrap_or(0)); + if !sink.wants(timestamp) { + return true; + } + match planes.frame(timestamp, scratch) { + Ok(frame) => sink.frame(frame), + Err(e) => { + warn!("dropping a camera frame: {e}"); + true + } + } +} + +/// Camera `id` failed (or could not open): the studio shows why. +pub fn on_error(id: u64, message: String) { + if let Some(run) = running().as_ref().and_then(|r| r.get(&id)) { + run.feed.set_error(Error::Capture { backend: BACKEND, message }); + } +} diff --git a/crates/voelin-android/src/capture.rs b/crates/voelin-android/src/capture.rs index a52d8d7..744695c 100644 --- a/crates/voelin-android/src/capture.rs +++ b/crates/voelin-android/src/capture.rs @@ -4,23 +4,38 @@ //! `voelin_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: -//! everything but our own uid, or one app's uid, each into a stream mixer -//! input ([`on_input`]); several captures may run at once. +//! virtual display renders into an `ImageReader`, whose RGBA frames come to +//! [`on_frame`]. A stream's sink takes them borrowed, converting straight +//! from the reader's buffer. +//! +//! The zero-copy path: while every encoder the sink feeds takes pictures +//! straight from the screen ([`FrameSink::accepts_gpu`]: one MediaCodec +//! encoder, see `voelin_media::codec::mediacodec`), a ticker at the +//! stream's frame rate tells the sink a picture is due; the first one makes +//! the encoder publish its input surface, and the virtual display is +//! pointed at it, so the screen goes from the compositor into the encoder +//! without a copy. When that stops (a second simulcast layer or codec, the +//! encoder gone or failed) the display goes back to the reader. +//! +//! System audio (`AudioPlaybackCapture`, 48 kHz float) needs that running +//! projection: everything but our own uid, or one app's uid, each into a +//! stream mixer input ([`on_input`]); several captures may run at once. use std::collections::HashMap; use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::{Arc, Mutex, MutexGuard, PoisonError}; -use std::time::Duration; +use std::time::{Duration, Instant}; use tokio::sync::oneshot; -use tracing::warn; +use tracing::{debug, warn}; use voelin_media::capture::external::{self, AudioProvider, ScreenProvider}; use voelin_media::capture::playback::{AppMatch, AudioApp, PlaybackFilter}; -use voelin_media::capture::{BoxFuture, CaptureOptions, CaptureSource, SourceId}; +use voelin_media::capture::{BoxFuture, CaptureOptions, CaptureSource, FrameSink, SourceId}; +use voelin_media::codec::mediacodec::{self, InputSurface}; use voelin_media::mix::SourceInput; -use voelin_media::{AudioBuffer, Error, FrameSender, Result, VideoFrame}; +use voelin_media::{ + AudioBuffer, Error, FrameRef, FrameSender, GpuFrame, PixelsRef, PlaneRef, Result, VideoFrame, +}; use crate::bridge; @@ -50,6 +65,29 @@ fn with_state(f: impl FnOnce(&mut State) -> R) -> R { f(guard.get_or_insert_with(State::default)) } +/// The screen's consumer of [`ScreenProvider::start_sink`], apart from the +/// audio state so that converting a frame does not hold up audio. +#[derive(Default)] +struct Video { + sink: Option>, + /// The ticker that serves this sink. + ticker: u64, + /// Size of the captured screen (the reader's), once a frame came. + size: (u32, u32), + /// The last frame's time and when it came: the ticker's pictures + /// continue that clock. + last: Option<(Duration, Instant)>, + /// The encoder surface the display renders into (its generation). + rendering: Option, +} + +static VIDEO: Mutex> = Mutex::new(None); + +fn with_video(f: impl FnOnce(&mut Video) -> R) -> R { + let mut guard = VIDEO.lock().unwrap_or_else(PoisonError::into_inner); + f(guard.get_or_insert_with(Video::default)) +} + /// Make MediaProjection the default screen and audio capture. pub fn register() { external::set_screen_provider(Some(Arc::new(Projection))); @@ -63,6 +101,22 @@ fn since(first: &mut Option, now_ns: i64) -> Duration { struct Projection; +impl Projection { + /// Ask for consent; `Ok` once the capture runs. + fn request(options: &CaptureOptions, tx: oneshot::Sender>) -> Result<()> { + with_state(|s| { + if let Some(previous) = s.pending.replace(tx) { + let _ = previous.send(Err(Error::Cancelled)); + } + s.origin_ns = None; + }); + bridge::request_screen_capture(options.fps.clamp(1, 60), MAX_SIZE).map_err(|e| { + with_state(|s| s.pending = None); + Error::CaptureUnavailable { backend: SCREEN, reason: e.to_string() } + }) + } +} + impl ScreenProvider for Projection { fn name(&self) -> &'static str { SCREEN @@ -86,20 +140,35 @@ impl ScreenProvider for Projection { 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) }); + with_video(|v| v.sink = None); + with_state(|s| s.frames = Some(frames)); + if let Err(e) = Self::request(options, tx) { + with_state(|s| s.frames = None); + return Box::pin(async move { Err(e) }); + } + Box::pin(async move { rx.await.unwrap_or(Err(Error::Cancelled)) }) + } + + fn start_sink( + &self, + _source: &SourceId, + options: &CaptureOptions, + sink: Box, + ) -> BoxFuture<'static, Result<()>> { + static TICKERS: AtomicU64 = AtomicU64::new(1); + let (tx, rx) = oneshot::channel(); + with_state(|s| s.frames = None); + let ticker = TICKERS.fetch_add(1, Ordering::Relaxed); + with_video(|v| *v = Video { sink: Some(sink), ticker, ..Video::default() }); + if let Err(e) = Self::request(options, tx) { + with_video(|v| v.sink = None); + return Box::pin(async move { Err(e) }); + } + if let Err(e) = std::thread::Builder::new() + .name("voelin-screen-ticker".into()) + .spawn(move || run_ticker(ticker)) + { + warn!("no zero-copy screen path: {e}"); } Box::pin(async move { rx.await.unwrap_or(Err(Error::Cancelled)) }) } @@ -112,6 +181,64 @@ impl ScreenProvider for Projection { } } +/// The zero-copy path's ticker (see the [module docs](self)): runs until +/// its sink is gone or replaced. +fn run_ticker(id: u64) { + loop { + let mut redirect: Option> = None; + let interval = with_video(|v| { + if v.ticker != id { + return None; + } + let Some(sink) = v.sink.as_mut() else { + // Back to the reader, whose next frame stops the service. + if v.rendering.take().is_some() { + redirect = Some(None); + } + return None; + }; + let interval = Duration::from_secs(1) / sink.max_fps().max(1); + let (width, height) = v.size; + if width == 0 { + // No frame yet. + return Some(interval); + } + if !sink.accepts_gpu() { + if v.rendering.take().is_some() { + debug!("screen back to frames in memory"); + redirect = Some(None); + } + return Some(interval); + } + // The encoder makes its surface for the first picture. + match (mediacodec::input_surface(), v.rendering) { + (Some(surface), rendering) if rendering != Some(surface.generation) => { + debug!(surface.width, surface.height, "screen straight into the encoder"); + v.rendering = Some(surface.generation); + redirect = Some(Some(surface)); + } + (None, Some(_)) => { + v.rendering = None; + redirect = Some(None); + } + _ => {} + } + let timestamp = v.last.map_or(Duration::ZERO, |(at, when)| at + when.elapsed()); + if sink.wants(timestamp) && !sink.gpu(GpuFrame::rendered(width, height, timestamp)) { + v.sink = None; + } + Some(interval) + }); + if let Some(target) = redirect + && let Err(e) = bridge::set_screen_surface(target.as_ref()) + { + warn!("pointing the screen at the encoder: {e}"); + } + let Some(interval) = interval else { return }; + std::thread::sleep(interval); + } +} + struct PlaybackAudio; impl AudioProvider for PlaybackAudio { @@ -196,9 +323,10 @@ impl AudioProvider for PlaybackAudio { match bridge::launchable_apps() { Ok(apps) => apps .into_iter() - .map(|(name, package)| AudioApp { + .map(|(name, package, icon)| AudioApp { name, binary: Some(package), + icon: (!icon.is_empty()).then_some(icon), ..AudioApp::default() }) .collect(), @@ -230,6 +358,9 @@ pub fn on_input(id: u64, samples: &[f32], channels: u16) -> bool { /// The user answered the consent dialog (or the service failed to start). pub fn on_result(granted: bool, error: Option) { + if !granted { + with_video(|v| v.sink = None); + } with_state(|s| { let result = match (granted, error) { (true, _) => Ok(()), @@ -246,23 +377,49 @@ pub fn on_result(granted: bool, error: Option) { } pub fn wants_frames() -> bool { - with_state(|s| s.frames.as_ref().is_some_and(|f| !f.is_closed())) + with_video(|v| v.sink.is_some()) + || 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| { +/// A captured RGBA frame, valid during the call. Returns `false` once +/// nobody wants frames. +pub fn on_frame(pixels: &[u8], width: u32, height: u32, stride: usize, timestamp_ns: i64) -> bool { + let timestamp = with_state(|s| { let timestamp = since(&mut s.origin_ns, timestamp_ns); + if let Some(origin) = s.origin_ns { + mediacodec::set_screen_origin(origin); + } + timestamp + }); + let taken = with_video(|v| { + let sink = v.sink.as_mut()?; + v.size = (width, height); + v.last = Some((timestamp, Instant::now())); + // While the screen renders into the encoder, what still reaches + // the reader is not used. + if sink.accepts_gpu() || !sink.wants(timestamp) { + return Some(true); + } + let pixels = PixelsRef::Rgba(PlaneRef::new(pixels, stride)); + let frame = FrameRef { width, height, timestamp, pixels }; + if let Err(e) = frame.validate() { + warn!("dropping a screen frame: {e}"); + return Some(true); + } + if !sink.frame(frame) { + v.sink = None; + return Some(false); + } + Some(true) + }); + if let Some(more) = taken { + return more; + } + with_state(|s| { let Some(frames) = &s.frames else { return false; }; - match VideoFrame::from_rgba(width, height, stride, pixels) { + match VideoFrame::from_rgba(width, height, stride, pixels.to_vec()) { Ok(frame) => { if !frames.send(frame.with_timestamp(timestamp)) { s.frames = None; @@ -278,6 +435,7 @@ pub fn on_frame( /// The projection ended (stopped by us, the user, or the system): the /// consumers see their channels close. pub fn on_stopped() { + with_video(|v| v.sink = None); with_state(|s| { s.frames = None; s.audio = None; diff --git a/crates/voelin-android/src/foreground.rs b/crates/voelin-android/src/foreground.rs index bd6bc1f..e48434e 100644 --- a/crates/voelin-android/src/foreground.rs +++ b/crates/voelin-android/src/foreground.rs @@ -1,20 +1,49 @@ -//! When the app needs its voice foreground service. +//! What the app's foreground services show. //! //! 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. +//! while a foreground service with a visible notification runs. The voice +//! service runs while any session has a voice connection (connecting or +//! connected); its notification names the channel and the server, counts +//! the people there and offers Mute, Deafen and Leave. While our stream is +//! live, the screen-sharing service's notification says where it goes and +//! how many watch. use std::collections::BTreeMap; +use std::sync::Arc; +use voelin_core::stream::{StreamState, ViewerInfo, ViewerState}; use voelin_core::{Event, SessionId, VoiceState}; +use voelin_model::Presence; /// What the voice notification shows. #[derive(Clone, Debug, PartialEq, Eq)] pub struct VoiceNotice { + /// The channel we are in ("Chill Zone"), or what is going on. + pub title: String, + /// The server and how many are in the channel. pub text: String, /// The microphone is muted in every voice session (the action unmutes). pub muted: bool, + /// The sound is off in every voice session (the action turns it on). + pub deafened: bool, + /// When the first voice session connected (Unix ms), for the elapsed + /// time; 0 while connecting. + pub since_ms: u64, +} + +/// What the screen-sharing notification shows while our stream is live. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ScreenNotice { + pub title: String, + pub text: String, +} + +/// The notifications that changed with an event: `Some(None)` stops the +/// voice service, or puts the screen notification back to its default. +#[derive(Debug, Default, PartialEq, Eq)] +pub struct Changes { + pub voice: Option>, + pub screen: Option>, } #[derive(Default)] @@ -27,26 +56,81 @@ struct Session { name: Option, voice: VoiceState, muted: bool, + deafened: bool, + own_channel: Option, + presence: Arc, + /// When voice connected (Unix ms). + since_ms: Option, + /// Our stream is live. + live: bool, + /// Viewers connected to our stream. + watching: usize, +} + +impl Session { + fn name(&self) -> &str { + self.name.as_deref().unwrap_or("a server") + } + + /// Our channel's name and how many are in it. + fn channel(&self) -> Option<(&str, usize)> { + let id = self.own_channel?; + let channel = self.presence.channels.get(&id)?; + let people = + self.presence.clients.values().filter(|c| c.channel == id && !c.is_query).count(); + Some((channel.name.as_str(), people)) + } +} + +fn now_ms() -> u64 { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_or(0, |d| d.as_millis() as u64) } 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(); + /// Apply `event`; the notifications it changed. + pub fn update(&mut self, event: &Event) -> Changes { + self.update_at(event, now_ms()) + } + + fn update_at(&mut self, event: &Event, now_ms: u64) -> Changes { + let (voice, screen) = (self.notice(), self.screen()); match event { Event::State { session, state } => { let s = self.sessions.entry(*session).or_default(); + s.since_ms = match state.voice { + VoiceState::Connected => s.since_ms.or(Some(now_ms)), + _ => None, + }; s.voice = state.voice; s.muted = state.input_muted; + s.deafened = state.output_muted; + s.own_channel = state.own_channel; } Event::ServerInfo { session, name, .. } => { self.sessions.entry(*session).or_default().name = Some(name.clone()); } - _ => return None, + Event::Presence { session, presence } => { + self.sessions.entry(*session).or_default().presence = presence.clone(); + } + Event::StreamState { session, state } => { + let s = self.sessions.entry(*session).or_default(); + s.live = matches!(state, StreamState::Live { .. }); + if !s.live { + s.watching = 0; + } + } + Event::StreamViewers { session, viewers } => { + self.sessions.entry(*session).or_default().watching = connected(viewers); + } + _ => return Changes::default(), + } + let (voice_after, screen_after) = (self.notice(), self.screen()); + Changes { + voice: (voice_after != voice).then_some(voice_after), + screen: (screen_after != screen).then_some(screen_after), } - let after = self.notice(); - (after != before).then_some(after) } fn active(&self) -> impl Iterator { @@ -58,49 +142,101 @@ impl Foreground { self.active().map(|(id, _)| *id).collect() } - /// The notification, `None` without voice. + /// The voice 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}") + let connecting = active.iter().all(|s| s.voice == VoiceState::Connecting); + let (title, text) = match active.as_slice() { + [] => return None, + [one] if connecting => ("Connecting…".to_owned(), one.name().to_owned()), + [one] => match one.channel() { + Some((channel, 1)) => (channel.to_owned(), format!("{} · just you", one.name())), + Some((channel, n)) => { + (channel.to_owned(), format!("{} · {n} in voice", one.name())) + } + None => ("In voice".to_owned(), one.name().to_owned()), + }, + several => ( + format!("In voice on {} servers", several.len()), + several.iter().map(|s| s.name()).collect::>().join(", "), + ), }; - Some(VoiceNotice { text, muted: active.iter().all(|s| s.muted) }) + Some(VoiceNotice { + title, + text, + muted: active.iter().all(|s| s.muted), + deafened: active.iter().all(|s| s.deafened), + since_ms: active.iter().filter_map(|s| s.since_ms).min().unwrap_or(0), + }) } + + /// The screen-sharing notification while our stream is live. + pub fn screen(&self) -> Option { + let s = self.sessions.values().find(|s| s.live)?; + let title = match s.channel() { + Some((channel, _)) => format!("Live in {channel}"), + None => "Live".to_owned(), + }; + let text = match s.watching { + 0 => s.name().to_owned(), + 1 => format!("{} · 1 watching", s.name()), + n => format!("{} · {n} watching", s.name()), + }; + Some(ScreenNotice { title, text }) + } +} + +fn connected(viewers: &[ViewerInfo]) -> usize { + viewers.iter().filter(|v| v.state == ViewerState::Connected).count() } #[cfg(test)] mod tests { use voelin_core::SessionState; - use voelin_model::{Capabilities, ServerFlavor}; + use voelin_core::stream::EndReason; + use voelin_model::{Capabilities, ChannelInfo, ClientInfo, ServerFlavor}; use super::*; fn voice(session: SessionId, voice: VoiceState, input_muted: bool) -> Event { Event::State { session, - state: SessionState { voice, input_muted, ..SessionState::default() }, + state: SessionState { + voice, + input_muted, + own_channel: Some(2), + ..SessionState::default() + }, } } - fn notice(text: &str, muted: bool) -> Option> { - Some(Some(VoiceNotice { text: text.into(), muted })) + fn notice(title: &str, text: &str, muted: bool, since_ms: u64) -> Option> { + Some(Some(VoiceNotice { + title: title.into(), + text: text.into(), + muted, + deafened: false, + since_ms, + })) + } + + fn presence(people: u16) -> Event { + let mut p = Presence::default(); + p.channels + .insert(2, ChannelInfo { id: 2, name: "Chill Zone".into(), ..Default::default() }); + for id in 1..=people { + p.clients.insert(id, ClientInfo { id, channel: 2, ..Default::default() }); + } + Event::Presence { session: 1, presence: Arc::new(p) } } #[test] - fn service_follows_voice_connections() { + fn the_voice_service_follows_voice_connections() { let mut fg = Foreground::default(); - assert_eq!(fg.update(&voice(1, VoiceState::Disconnected, false)), None); + assert_eq!(fg.update_at(&voice(1, VoiceState::Disconnected, false), 5).voice, None); assert_eq!( - fg.update(&voice(1, VoiceState::Connecting, false)), - notice("Connecting to a server", false) + fg.update_at(&voice(1, VoiceState::Connecting, false), 5).voice, + notice("Connecting…", "a server", false, 0) ); let info = Event::ServerInfo { session: 1, @@ -108,25 +244,93 @@ mod tests { flavor: ServerFlavor::Unknown(String::new()), capabilities: Capabilities::default(), }; - assert_eq!(fg.update(&info), notice("Connecting to Home", false)); + assert_eq!(fg.update_at(&info, 6).voice, notice("Connecting…", "Home", false, 0)); assert_eq!( - fg.update(&voice(1, VoiceState::Connected, false)), - notice("In voice on Home", false) + fg.update_at(&voice(1, VoiceState::Connected, false), 7).voice, + notice("In voice", "Home", false, 7) ); - assert_eq!(fg.update(&voice(1, VoiceState::Connected, false)), None, "no change"); + // The channel and its people, once presence knows them. assert_eq!( - fg.update(&voice(1, VoiceState::Connected, true)), - notice("In voice on Home", true) + fg.update_at(&presence(3), 8).voice, + notice("Chill Zone", "Home · 3 in voice", false, 7) ); - // 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) + fg.update_at(&presence(1), 8).voice, + notice("Chill Zone", "Home · just you", false, 7) + ); + assert_eq!( + fg.update_at(&voice(1, VoiceState::Connected, false), 9).voice, + None, + "no change" + ); + assert_eq!( + fg.update_at(&voice(1, VoiceState::Connected, true), 9).voice, + notice("Chill Zone", "Home · just you", true, 7) + ); + // A second session that is not muted: the action mutes both, and + // the time counts from the first connection. + assert_eq!( + fg.update_at(&voice(2, VoiceState::Connected, false), 20).voice, + notice("In voice on 2 servers", "Home, a server", false, 7) ); 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_eq!( + fg.update(&Event::Error { session: 1, message: "x".into() }), + Changes::default() + ); + fg.update_at(&voice(2, VoiceState::Disconnected, false), 30); + assert_eq!(fg.update_at(&voice(1, VoiceState::Disconnected, true), 30).voice, Some(None)); assert!(fg.voice_sessions().is_empty()); } + + #[test] + fn deafen_needs_every_session_deafened() { + let mut fg = Foreground::default(); + let deaf = |session, output_muted| Event::State { + session, + state: SessionState { + voice: VoiceState::Connected, + output_muted, + ..Default::default() + }, + }; + fg.update_at(&deaf(1, true), 1); + assert!(fg.notice().unwrap().deafened); + fg.update_at(&deaf(2, false), 1); + assert!(!fg.notice().unwrap().deafened); + } + + #[test] + fn the_screen_notice_says_where_we_are_live() { + let mut fg = Foreground::default(); + fg.update_at(&voice(1, VoiceState::Connected, false), 1); + fg.update_at(&presence(2), 1); + assert_eq!(fg.screen(), None); + // `StreamState::Live` carries a sink only the engine makes. + fg.sessions.get_mut(&1).unwrap().live = true; + let screen = |title: &str, text: &str| { + Some(Some(ScreenNotice { title: title.into(), text: text.into() })) + }; + assert_eq!(fg.screen(), screen("Live in Chill Zone", "a server").flatten()); + let viewer = |client, state| ViewerInfo { + client: tsclientlib::ClientId(client), + state, + message: String::new(), + layer: None, + estimate: None, + srtp_profile: None, + codec: None, + }; + let viewers = Event::StreamViewers { + session: 1, + viewers: vec![viewer(2, ViewerState::Connected), viewer(3, ViewerState::Requested)], + }; + assert_eq!( + fg.update_at(&viewers, 3).screen, + screen("Live in Chill Zone", "a server · 1 watching") + ); + let ended = + Event::StreamState { session: 1, state: StreamState::Ended(EndReason::Stopped) }; + assert_eq!(fg.update_at(&ended, 4).screen, Some(None)); + } } diff --git a/crates/voelin-android/src/lib.rs b/crates/voelin-android/src/lib.rs index 117ca35..e304bf3 100644 --- a/crates/voelin-android/src/lib.rs +++ b/crates/voelin-android/src/lib.rs @@ -13,6 +13,8 @@ //! native methods it calls back (`Native`) //! - `capture` (Android): screen and system-audio capture through //! MediaProjection, registered as `voelin_media` capture providers +//! - `camera` (Android): the Stream Studio's cameras through Camera2, +//! registered as its camera provider //! - `secrets` (Android): passwords encrypted with an Android Keystore key //! - `egl` (Android): keeps EGL extension slots for Skia, without which the //! UI cannot draw on Mesa-based Android (Waydroid) @@ -27,6 +29,8 @@ mod app; #[cfg(target_os = "android")] mod bridge; #[cfg(target_os = "android")] +mod camera; +#[cfg(target_os = "android")] mod capture; #[cfg(target_os = "android")] mod egl; diff --git a/crates/voelin-core/src/media.rs b/crates/voelin-core/src/media.rs index 3e56420..3008909 100644 --- a/crates/voelin-core/src/media.rs +++ b/crates/voelin-core/src/media.rs @@ -1584,7 +1584,8 @@ impl Ingest { } /// Whether frames go to the GPU: every layer's encoders take GPU frames - /// and the GPU stage has not failed. + /// and the GPU stage has not failed. On Android: the screen can render + /// straight into the encoder (`mediacodec`'s surface path). fn gpu_path(&self) -> bool { #[cfg(all(target_os = "linux", feature = "media-desktop"))] { @@ -1595,7 +1596,18 @@ impl Ingest { .iter() .all(|l| l.layer.stopped() || l.layer.gpu.load(Ordering::Relaxed) != 0) } - #[cfg(not(all(target_os = "linux", feature = "media-desktop")))] + #[cfg(target_os = "android")] + { + !self.layers.is_empty() + && self + .layers + .iter() + .all(|l| l.layer.stopped() || l.layer.gpu.load(Ordering::Relaxed) != 0) + } + #[cfg(not(any( + all(target_os = "linux", feature = "media-desktop"), + target_os = "android" + )))] false } @@ -1719,7 +1731,38 @@ impl FrameSink for Ingest { } fn accepts_dmabuf(&self) -> bool { - self.gpu_path() + cfg!(all(target_os = "linux", feature = "media-desktop")) && self.gpu_path() + } + + fn accepts_gpu(&self) -> bool { + cfg!(target_os = "android") && self.gpu_path() + } + + /// Android: the screen goes straight into each due layer's encoder, + /// which draws it at the layer's size; only its size and time come here. + #[cfg(target_os = "android")] + fn gpu(&mut self, frame: GpuFrame) -> bool { + if self.shared.stopped() { + return false; + } + self.pacer.keep(frame.timestamp); + self.refresh(); + let shared = &self.shared; + shared.captured.fetch_add(1, Ordering::Relaxed); + shared + .size + .store(u64::from(frame.width) << 32 | u64::from(frame.height), Ordering::Relaxed); + if shared.sink().is_none() { + return true; + } + for l in &mut self.layers { + if !l.layer.stopped() && l.pacer.take(frame.timestamp) { + let (width, height) = l.spec.output_size(frame.width, frame.height); + l.layer.gpu_inbox.put(Arc::new(frame.sized(width, height))); + } + } + shared.gpu_converted.fetch_add(1, Ordering::Relaxed); + true } /// The tiled layout the GPU's own RGB surfaces have, once the GPU stage diff --git a/crates/voelin-media/src/capture/external.rs b/crates/voelin-media/src/capture/external.rs index 2d72691..37d44f0 100644 --- a/crates/voelin-media/src/capture/external.rs +++ b/crates/voelin-media/src/capture/external.rs @@ -15,7 +15,7 @@ use std::sync::{Arc, Mutex, PoisonError}; use crate::capture::playback::{AudioApp, PlaybackFilter, SourceCapture, forward_audio}; use crate::capture::{ - AudioCapture, BoxFuture, CaptureOptions, CaptureSource, ScreenCapture, SourceId, + AudioCapture, BoxFuture, CaptureOptions, CaptureSource, FrameSink, ScreenCapture, SourceId, }; use crate::frame::{AUDIO_SAMPLE_RATE, AudioBuffer, VideoFrame}; use crate::mix::{SourceHandle, SourceInput}; @@ -41,6 +41,24 @@ pub trait ScreenProvider: Send + Sync { frames: FrameSender, ) -> BoxFuture<'static, Result<()>>; + /// Like [`start`](Self::start), but frames go to `sink` from the + /// provider's own thread, borrowed (no copy), and the provider may hand + /// it [`FrameSink::gpu`] pictures while it accepts them. The default + /// forwards the frames of `start`. + fn start_sink( + &self, + source: &SourceId, + options: &CaptureOptions, + sink: Box, + ) -> BoxFuture<'static, Result<()>> { + let (tx, rx) = frame_channel(options.queue); + let started = self.start(source, options, tx); + Box::pin(async move { + started.await?; + super::forward(rx, sink) + }) + } + fn stop(&self); } @@ -175,6 +193,19 @@ impl ScreenCapture for ExternalScreenCapture { }) } + fn start_sink( + &mut self, + source: &SourceId, + options: &CaptureOptions, + sink: Box, + ) -> BoxFuture<'_, Result<()>> { + self.stop(); + let options = CaptureOptions { fps: sink.max_fps(), ..options.clone() }; + let started = self.provider.start_sink(source, &options, sink); + self.running = true; + started + } + fn stop(&mut self) { if std::mem::take(&mut self.running) { self.provider.stop(); diff --git a/crates/voelin-media/src/capture/mod.rs b/crates/voelin-media/src/capture/mod.rs index f064d63..f0568d9 100644 --- a/crates/voelin-media/src/capture/mod.rs +++ b/crates/voelin-media/src/capture/mod.rs @@ -130,6 +130,22 @@ pub trait FrameSink: Send { None } + /// Whether the sink takes pictures the platform puts straight into the + /// encoder ([`gpu`](Self::gpu)), because every encoder it feeds takes + /// them. Android's screen capture then renders into MediaCodec's input + /// surface instead of handing over pixels. + fn accepts_gpu(&self) -> bool { + false + } + + /// Such a picture: only its size and time + /// ([`GpuFrame::rendered`](crate::GpuFrame::rendered)). Returns `false` + /// when no more frames are wanted. + fn gpu(&mut self, frame: crate::GpuFrame) -> bool { + let _ = frame; + true + } + /// Tiled DRM format modifiers of RGB buffers the sink takes now /// ([`accepts_dmabuf`](Self::accepts_dmabuf)), best first; backends that /// negotiate buffers (the portal) offer them ahead of LINEAR, and offer diff --git a/crates/voelin-media/src/codec/mediacodec.rs b/crates/voelin-media/src/codec/mediacodec.rs index 0cd9df5..e789829 100644 --- a/crates/voelin-media/src/codec/mediacodec.rs +++ b/crates/voelin-media/src/codec/mediacodec.rs @@ -10,26 +10,42 @@ //! H.264 is encoded as High profile without B-frames (the Constrained High //! stream TeamSpeak negotiates, see `voelin-stream`), SPS/PPS in front of every //! keyframe. +//! +//! The zero-copy path: while it is the only MediaCodec encoder in the +//! process, an encoder takes [`GpuFrame`]s +//! ([`VideoEncoder::gpu_alignment`]). For the first one it starts a codec +//! with an input surface and publishes it ([`input_surface`]); Android's +//! screen capture points its virtual display at that surface, so the +//! screen goes from the compositor into the encoder without a copy or a +//! CPU conversion, and the `GpuFrame`s only say a picture is due (the +//! encoder hands over what it encoded since). With a second encoder (a +//! simulcast layer, another codec for some viewers) none takes them, and +//! the capture goes back to frames in memory; so does an encoder whose +//! surface failed once. // 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::sync::atomic::{AtomicI64, AtomicU64, AtomicUsize, Ordering}; +use std::sync::{Mutex, OnceLock, PoisonError}; use std::time::Duration; use ndk::media::media_codec::{ DequeuedInputBufferResult, DequeuedOutputBufferInfoResult, MediaCodec, MediaCodecDirection, }; use ndk::media::media_format::MediaFormat; +use ndk::native_window::NativeWindow; use tracing::{debug, info}; use super::hw::EncoderFactory; 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 super::{ + Codec, EncodedChunk, EncodedFrame, EncoderBackend, EncoderConfig, VideoDecoder, VideoEncoder, +}; +use crate::frame::{FrameData, GpuFrame, VideoFrame}; use crate::{Error, Result, convert}; /// `BUFFER_FLAG_KEY_FRAME`. @@ -48,8 +64,47 @@ 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); +/// `COLOR_FormatSurface`: pictures come through an input surface. +const COLOR_FORMAT_SURFACE: i32 = 0x7F00_0789; +/// On the surface path a still screen is encoded again after this long +/// (µs), so a keyframe asked for while nothing moves comes this late at +/// most. +const REPEAT_AFTER_US: i64 = 100_000; + pub const NAME: &str = "mediacodec"; +/// MediaCodec encoders alive in this process. +static LIVE: AtomicUsize = AtomicUsize::new(0); +/// The published input surface (see the [module docs](self)). +static SURFACE: Mutex> = Mutex::new(None); +static GENERATION: AtomicU64 = AtomicU64::new(0); +/// The screen capture's clock origin (`CLOCK_MONOTONIC` ns), which the +/// surface's presentation times are on. +static SCREEN_ORIGIN_NS: AtomicI64 = AtomicI64::new(i64::MIN); + +/// The input surface of the encoder that takes the screen straight from +/// the capture, for the capture's virtual display to render into. +#[derive(Clone)] +pub struct InputSurface { + pub window: NativeWindow, + pub width: u32, + pub height: u32, + /// Changes with every new surface. + pub generation: u64, +} + +/// The surface to render the screen into, if an encoder has one. +pub fn input_surface() -> Option { + SURFACE.lock().unwrap_or_else(PoisonError::into_inner).clone() +} + +/// Where the screen capture's frame times start (`CLOCK_MONOTONIC` ns, +/// what its frames' times are counted from): the surface path puts its +/// presentation times, which are on that clock, on the stream's timeline. +pub fn set_screen_origin(origin_ns: i64) { + SCREEN_ORIGIN_NS.store(origin_ns, Ordering::Relaxed); +} + fn mime(codec: Codec) -> &'static str { match codec { Codec::Vp8 => "video/x-vnd.on2.vp8", @@ -123,8 +178,9 @@ pub fn check_decoder(codec: Codec) -> Result<()> { } } -/// 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. +/// Encoders of this device: the hardware ones (H.264, VP9, VP8, AV1) and +/// Google's software VP8 and H.264; software VP9 and AV1 are too slow. +/// `Codecs` orders them by codec, as every hardware factory. pub fn probe() -> Option { let encoders = &available().encoders; let name = |codec| encoders.iter().find(|(c, _)| *c == codec).map(|(_, n)| n.as_str()); @@ -159,15 +215,32 @@ impl EncoderFactory for MediaCodecFactory { 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 })) + LIVE.fetch_add(1, Ordering::Relaxed); + Ok(Box::new(MediaCodecEncoder { + codec, + config: config.clone(), + session: None, + surface_failed: false, + })) } } -/// A MediaCodec encoder. The codec is (re)created for the frame size. +/// A MediaCodec encoder. The codec is (re)created for the frame size, and +/// for frames in memory or on the surface path. pub struct MediaCodecEncoder { codec: Codec, config: EncoderConfig, session: Option, + /// The surface path failed: frames in memory only from now on. + surface_failed: bool, +} + +impl Drop for MediaCodecEncoder { + fn drop(&mut self) { + // Its surface goes first. + self.session = None; + LIVE.fetch_sub(1, Ordering::Relaxed); + } } struct EncoderSession { @@ -178,6 +251,18 @@ struct EncoderSession { /// Staging buffer for the codec's input layout. staging: Vec, last_pts_us: Option, + /// The surface path: the generation of the input surface it published. + surface: Option, +} + +impl Drop for EncoderSession { + fn drop(&mut self) { + let Some(generation) = self.surface else { return }; + let mut slot = SURFACE.lock().unwrap_or_else(PoisonError::into_inner); + if slot.as_ref().is_some_and(|s| s.generation == generation) { + *slot = None; + } + } } impl MediaCodecEncoder { @@ -241,11 +326,54 @@ impl MediaCodecEncoder { parameter_sets: Vec::new(), staging: Vec::new(), last_pts_us: None, + surface: None, }); } } Err(encoder_error(codec, "no working configuration", last_error)) } + + /// Start a codec for `width` x `height` that takes its pictures through + /// an input surface, and publish the surface for the screen capture. + fn start_surface(&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 &profile in profiles { + let handle = Handle( + MediaCodec::from_encoder_type(mime(codec)) + .ok_or_else(|| encoder_error(codec, "create", "no encoder"))?, + ); + let mut format = self.format(width, height, COLOR_FORMAT_SURFACE, profile); + // The display renders at its own rate; encode at most ours. + format.set_f32("max-fps-to-encoder", self.config.fps.max(1) as f32); + format.set_i64("repeat-previous-frame-after", REPEAT_AFTER_US); + if let Err(e) = handle.0.configure(&format, None, MediaCodecDirection::Encoder) { + last_error = format!("configure surface input/{profile:?}: {e}"); + continue; + } + let window = + handle.0.create_input_surface().map_err(|e| encoder_error(codec, "surface", e))?; + handle.0.start().map_err(|e| encoder_error(codec, "start", e))?; + let generation = GENERATION.fetch_add(1, Ordering::Relaxed) + 1; + *SURFACE.lock().unwrap_or_else(PoisonError::into_inner) = + Some(InputSurface { window, width, height, generation }); + debug!(%codec, width, height, ?profile, "MediaCodec encoder on the surface path"); + return Ok(EncoderSession { + handle, + layout: ImageLayout::nv12(width, height, 0, 0), + parameter_sets: Vec::new(), + staging: Vec::new(), + last_pts_us: None, + surface: Some(generation), + }); + } + Err(encoder_error(codec, "no surface configuration", last_error)) + } } /// Where the encoder wants its input: `image-data` if it says, else the @@ -310,7 +438,9 @@ impl VideoEncoder for MediaCodecEncoder { .session .as_ref() .is_some_and(|s| (s.layout.width, s.layout.height) != (width, height)); - if resized || self.session.is_none() { + // Frames in memory again after the surface path: a codec for them. + let surface = self.session.as_ref().is_some_and(|s| s.surface.is_some()); + if resized || surface || self.session.is_none() { self.session = None; self.session = Some(self.start(width, height)?); } @@ -367,7 +497,72 @@ impl VideoEncoder for MediaCodecEncoder { // The codec is still busy: skip this frame (rate control). DequeuedInputBufferResult::TryAgainLater => {} } - drain_encoder(codec, session) + drain_encoder(codec, session, OUTPUT_WAIT) + } + + /// Only while it is the only MediaCodec encoder: one input surface + /// takes the screen (see the [module docs](self)). + fn gpu_alignment(&self) -> Option<(u32, u32)> { + (!self.surface_failed && LIVE.load(Ordering::Relaxed) == 1).then_some((2, 2)) + } + + /// A picture is due: on the first one (and when the size changes) the + /// codec starts on the surface path; then what it encoded since goes to + /// `out`. + fn encode_gpu( + &mut self, + frame: &GpuFrame, + force_keyframe: bool, + out: &mut dyn FnMut(EncodedChunk<'_>), + ) -> Result<()> { + let codec = self.codec; + 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 current = self.session.as_ref().is_some_and(|s| { + s.surface.is_some() && (s.layout.width, s.layout.height) == (width, height) + }); + if !current { + self.session = None; + match self.start_surface(width, height) { + Ok(session) => self.session = Some(session), + Err(e) => { + // Frames in memory from now on (the capture follows + // `gpu_alignment`). + self.surface_failed = true; + return Err(e); + } + } + } else if force_keyframe { + let mut params = MediaFormat::new(); + params.set_i32("request-sync", 0); + let session = self.session.as_ref().expect("checked above"); + session + .handle + .0 + .set_parameters(params) + .map_err(|e| encoder_error(codec, "request keyframe", e))?; + } + let session = self.session.as_mut().expect("started above"); + // Wait up to half a frame for what the display rendered. + let wait = Duration::from_micros(500_000 / u64::from(self.config.fps.max(1))); + for f in drain_encoder(codec, session, wait)? { + out(EncodedChunk { data: &f.data, keyframe: f.keyframe, pts_90khz: f.pts_90khz }); + } + Ok(()) + } + + /// On the surface path the rate caps what the codec takes from the + /// display (`max-fps-to-encoder`, fixed when it starts): the next + /// picture starts it anew. Frames in memory follow their timestamps. + fn set_fps(&mut self, fps: u32) -> Result<()> { + let fps = fps.max(1); + if fps != self.config.fps && self.session.as_ref().is_some_and(|s| s.surface.is_some()) { + self.session = None; + } + self.config.fps = fps; + Ok(()) } fn set_bitrate(&mut self, bps: u32) -> Result<()> { @@ -385,10 +580,15 @@ impl VideoEncoder for MediaCodecEncoder { } } -/// Collect what the encoder has finished. -fn drain_encoder(codec: Codec, session: &mut EncoderSession) -> Result> { +/// Collect what the encoder has finished, waiting up to `wait` for the +/// first of it. +fn drain_encoder( + codec: Codec, + session: &mut EncoderSession, + wait: Duration, +) -> Result> { let mut out = Vec::new(); - let mut wait = OUTPUT_WAIT; + let mut wait = wait; loop { let result = session .handle @@ -424,7 +624,15 @@ fn drain_encoder(codec: Codec, session: &mut EncoderSession) -> Result Self { + Self { width, height, timestamp } + } + + /// Such a picture as a simulcast layer of `width` x `height` sees it + /// (Android: the encoder draws the screen at its own size). + #[cfg(target_os = "android")] + pub fn sized(&self, width: u32, height: u32) -> Self { + Self { + width, + height, + timestamp: self.timestamp, + #[cfg(feature = "ffmpeg")] + surface: self.surface.new_ref(), + } + } + /// The same picture at another time (another reference to the same /// surface), e.g. to send a still screen again. pub fn at(&self, timestamp: Duration) -> Self { diff --git a/crates/voelin-media/src/studio/camera.rs b/crates/voelin-media/src/studio/camera.rs index 073cbce..298c967 100644 --- a/crates/voelin-media/src/studio/camera.rs +++ b/crates/voelin-media/src/studio/camera.rs @@ -24,19 +24,25 @@ //! //! Windows: Media Foundation (`mf`): `MFEnumDeviceSources` lists the //! cameras, an `IMFSourceReader` captures as NV12, decoding MJPEG on the way. -//! Only type-checked, never run. Android has no camera backend yet ([`list`] -//! returns only the synthetic one). +//! Only type-checked, never run. +//! +//! Android: the app registers a [`CameraProvider`] (Camera2 through its +//! Kotlin side) whose cameras [`list`] puts first and [`Capture::start`] +//! opens; its frames come as [`YuvPlanes`], converted straight from the +//! camera's memory where the layout allows. -use std::sync::Arc; use std::sync::atomic::AtomicU32; +use std::sync::{Arc, Mutex, PoisonError}; +use std::time::Duration; -use crate::Result; use crate::capture::synthetic::SyntheticScreen; -use crate::capture::{CaptureOptions, ScreenCapture, SourceId}; +use crate::capture::{CaptureOptions, FrameSink, ScreenCapture, SourceId}; +use crate::frame::{FrameRef, PixelsRef, PlaneRef}; use crate::studio::compose::Feed; use crate::studio::scene::Background; use crate::studio::segment::BackgroundFilter; use crate::studio::source::FeedSink; +use crate::{Error, Result}; /// The id of the camera that is always available: the test pattern. pub const SYNTHETIC: &str = "synthetic"; @@ -118,9 +124,12 @@ pub struct Camera { /// on Linux, or [`SYNTHETIC`]. pub id: String, pub name: String, - /// Where the list came from (`"v4l2"`, `"synthetic"`). + /// Where the list came from (`"v4l2"`, `"synthetic"`, `"camera2"`). pub backend: &'static str, pub formats: Vec, + /// Shown mirrored by default: a camera facing the user (webcams, a + /// phone's front camera), not one facing away. + pub mirrored: bool, } /// Every camera this session can use. Never fails: a device that cannot be @@ -138,8 +147,150 @@ pub fn list() -> Vec { name: "Test pattern".to_owned(), backend: "synthetic", formats: vec![Format { pixel: Pixel::Bgrx, sizes: vec![(1280, 720)], max_fps: 60 }], + mirrored: true, }; - devices.into_iter().chain([synthetic]).collect() + let external = provider().map(|p| p.list()).unwrap_or_default(); + external.into_iter().chain(devices).chain([synthetic]).collect() +} + +/// Cameras of a platform API outside this crate, registered by the app at +/// start like the external screen capture ([`crate::capture::external`]): +/// on Android, Camera2 through the app's Kotlin side. +pub trait CameraProvider: Send + Sync { + /// Short name for logs and [`Capture::backend`] (`"camera2"`). + fn name(&self) -> &'static str; + + /// The cameras, in the order a picker shows them. + fn list(&self) -> Vec; + + /// Open `device` and feed `sink` with up to `fps` frames a second at + /// about `size` (`None`: the camera's default); what fails after the + /// start (a permission refused, the camera taken by another app) goes + /// to `feed`. The camera stops when the returned value is dropped. + fn start( + &self, + device: &str, + size: Option<(u32, u32)>, + fps: u32, + sink: Box, + feed: Arc, + ) -> Result>; +} + +static PROVIDER: Mutex>> = Mutex::new(None); + +/// Make [`list`] and [`Capture::start`] use `provider` (`None`: only the +/// built-in cameras). +pub fn set_provider(provider: Option>) { + *PROVIDER.lock().unwrap_or_else(PoisonError::into_inner) = provider; +} + +fn provider() -> Option> { + PROVIDER.lock().unwrap_or_else(PoisonError::into_inner).clone() +} + +/// A camera picture in three 4:2:0 planes whose chroma samples may lie +/// apart (`uv_step` 2), as Android's `YUV_420_888` hands them over, and the +/// clockwise turn that makes it upright. +#[derive(Clone, Copy, Debug)] +pub struct YuvPlanes<'a> { + pub width: u32, + pub height: u32, + pub y: &'a [u8], + pub y_stride: usize, + pub u: &'a [u8], + pub v: &'a [u8], + /// Bytes per chroma row (both planes). + pub uv_stride: usize, + /// Bytes from one chroma sample to the next in a row: 1 (planar) or 2 + /// (interleaved). + pub uv_step: usize, + /// The chroma as one interleaved block with U first (NV12), when it is + /// one: then taken as it is. + pub nv12: Option<&'a [u8]>, + /// Clockwise degrees: 0, 90, 180 or 270. + pub rotation: u32, +} + +impl<'a> YuvPlanes<'a> { + /// The picture as a frame: borrowed when it is upright and planar or + /// NV12, else gathered (and turned) into `scratch` as I420; `scratch` + /// keeps its capacity, so nothing is allocated once it has grown. + pub fn frame(&self, timestamp: Duration, scratch: &'a mut Vec) -> Result> { + let (w, h) = (self.width as usize, self.height as usize); + if w == 0 || h == 0 { + return Err(Error::InvalidFrame(format!("{w}x{h} camera frame"))); + } + let rotation = self.rotation / 90 % 4 * 90; + let (width, height) = (self.width, self.height); + if rotation == 0 { + let y = PlaneRef::new(self.y, self.y_stride); + let pixels = if self.uv_step == 1 { + let u = PlaneRef::new(self.u, self.uv_stride); + let v = PlaneRef::new(self.v, self.uv_stride); + Some(PixelsRef::I420 { y, u, v }) + } else { + self.nv12.map(|uv| PixelsRef::Nv12 { y, uv: PlaneRef::new(uv, self.uv_stride) }) + }; + if let Some(pixels) = pixels { + return Ok(FrameRef { width, height, timestamp, pixels }); + } + } + let (cw, ch) = crate::frame::chroma_size(self.width, self.height); + let turned = rotation % 180 == 90; + let (ow, oh) = if turned { (h, w) } else { (w, h) }; + let (ocw, och) = if turned { (ch, cw) } else { (cw, ch) }; + scratch.resize(ow * oh + 2 * ocw * och, 0); + { + let (y, rest) = scratch.split_at_mut(ow * oh); + let (u, v) = rest.split_at_mut(ocw * och); + turn(self.y, self.y_stride, 1, w, h, rotation, y)?; + turn(self.u, self.uv_stride, self.uv_step, cw, ch, rotation, u)?; + turn(self.v, self.uv_stride, self.uv_step, cw, ch, rotation, v)?; + } + let scratch: &'a [u8] = scratch; + let (y, rest) = scratch.split_at(ow * oh); + let (u, v) = rest.split_at(ocw * och); + let pixels = PixelsRef::I420 { + y: PlaneRef::new(y, ow), + u: PlaneRef::new(u, ocw), + v: PlaneRef::new(v, ocw), + }; + Ok(FrameRef { width: ow as u32, height: oh as u32, timestamp, pixels }) + } +} + +/// Copy the `w` x `h` samples of a plane (`step` bytes apart in a row, +/// `stride` bytes per row) into `out`, turned clockwise by `rotation`, rows +/// without padding. +fn turn( + src: &[u8], + stride: usize, + step: usize, + w: usize, + h: usize, + rotation: u32, + out: &mut [u8], +) -> Result<()> { + if src.len() < (h - 1) * stride + (w - 1) * step + 1 { + return Err(Error::InvalidFrame(format!( + "camera plane of {} bytes is too small for {w}x{h}", + src.len() + ))); + } + for y in 0..h { + let row = &src[y * stride..]; + for x in 0..w { + let at = match rotation { + 90 => x * h + (h - 1 - y), + 180 => (h - 1 - y) * w + (w - 1 - x), + 270 => (w - 1 - x) * h + y, + _ => y * w + x, + }; + out[at] = row[x * step]; + } + } + Ok(()) } /// A running camera; stops when dropped. @@ -147,6 +298,8 @@ pub struct Capture { backend: &'static str, device: String, screen: Option>, + /// A [`CameraProvider`]'s camera, stopped when dropped. + _external: Option>, #[cfg(all(target_os = "linux", feature = "pipewire"))] stream: Option, /// Stops its thread when dropped. @@ -189,6 +342,25 @@ impl Capture { backend: "synthetic", device: wanted, screen: Some(Box::new(screen)), + _external: None, + #[cfg(all(target_os = "linux", feature = "pipewire"))] + stream: None, + #[cfg(windows)] + _mf: None, + }); + } + if let Some(provider) = provider() { + let mut sink = FeedSink::new(feed.clone(), Arc::new(AtomicU32::new(fps))); + if background.needs_mask() { + sink = sink.with_background(BackgroundFilter::with_default_segmenter(background)); + } + let running = provider.start(&wanted, size, fps, Box::new(sink), feed)?; + tracing::debug!(device = %wanted, backend = provider.name(), "camera"); + return Ok(Self { + backend: provider.name(), + device: wanted, + screen: None, + _external: Some(running), #[cfg(all(target_os = "linux", feature = "pipewire"))] stream: None, #[cfg(windows)] @@ -206,12 +378,24 @@ impl Capture { pipewire_camera::Stream::start(&wanted, size, fps, formats, feed, background) .await?; tracing::debug!(device = %wanted, "camera through PipeWire"); - Ok(Self { backend: "pipewire", device: wanted, screen: None, stream: Some(stream) }) + Ok(Self { + backend: "pipewire", + device: wanted, + screen: None, + _external: None, + stream: Some(stream), + }) } #[cfg(windows)] { let stream = mf::Stream::start(&wanted, size, fps, feed, background)?; - Ok(Self { backend: "mediafoundation", device: wanted, screen: None, _mf: Some(stream) }) + Ok(Self { + backend: "mediafoundation", + device: wanted, + screen: None, + _external: None, + _mf: Some(stream), + }) } #[cfg(not(any(all(target_os = "linux", feature = "pipewire"), windows)))] { @@ -223,7 +407,8 @@ impl Capture { } } - /// Where the frames come from (`"pipewire"`, `"portal"`, `"synthetic"`). + /// Where the frames come from (`"pipewire"`, `"portal"`, `"synthetic"`, + /// a provider's name). pub fn backend(&self) -> &'static str { #[cfg(all(target_os = "linux", feature = "pipewire"))] if let Some(stream) = &self.stream { @@ -483,6 +668,7 @@ mod v4l2 { name: if name.is_empty() { path.to_string_lossy().into_owned() } else { name }, backend: "v4l2", formats, + mirrored: true, }) }) .collect() @@ -1283,6 +1469,74 @@ mod tests { } } + #[test] + fn camera_planes_are_borrowed_gathered_and_turned() { + // 4x2 luma 0..8, one 2x1 chroma row: U 10 11, V 20 21. + let y: Vec = (0..8).collect(); + let planar = YuvPlanes { + width: 4, + height: 2, + y: &y, + y_stride: 4, + u: &[10, 11], + v: &[20, 21], + uv_stride: 2, + uv_step: 1, + nv12: None, + rotation: 0, + }; + let mut scratch = Vec::new(); + let frame = planar.frame(Duration::from_millis(3), &mut scratch).unwrap(); + frame.validate().unwrap(); + assert_eq!(frame.timestamp, Duration::from_millis(3)); + let PixelsRef::I420 { y: luma, .. } = frame.pixels else { panic!("not I420") }; + assert!(std::ptr::eq(luma.data, &y[..]), "upright planar is borrowed"); + + let uv = [10, 20, 11, 21]; + let nv12 = YuvPlanes { + u: &uv[..3], + v: &uv[1..], + uv_stride: 4, + uv_step: 2, + nv12: Some(&uv), + ..planar + }; + let mut scratch = Vec::new(); + let frame = nv12.frame(Duration::ZERO, &mut scratch).unwrap(); + frame.validate().unwrap(); + assert!( + matches!(frame.pixels, PixelsRef::Nv12 { uv: p, .. } if std::ptr::eq(p.data, &uv[..])) + ); + + // NV21 (V first) is gathered into I420. + let vu = [20, 10, 21, 11]; + let nv21 = YuvPlanes { u: &vu[1..], v: &vu[..3], uv_stride: 4, uv_step: 2, ..planar }; + let mut scratch = Vec::new(); + let frame = nv21.frame(Duration::ZERO, &mut scratch).unwrap(); + frame.validate().unwrap(); + let PixelsRef::I420 { y: luma, u, v } = frame.pixels else { panic!("not I420") }; + assert_eq!((luma.data, u.data, v.data), (&y[..], &[10, 11][..], &[20, 21][..])); + + // Turned clockwise; the chroma turns with the luma. + for (rotation, size, luma) in [ + (90, (2, 4), [4, 0, 5, 1, 6, 2, 7, 3]), + (180, (4, 2), [7, 6, 5, 4, 3, 2, 1, 0]), + (270, (2, 4), [3, 7, 2, 6, 1, 5, 0, 4]), + ] { + let mut scratch = Vec::new(); + let frame = YuvPlanes { rotation, ..nv21 }.frame(Duration::ZERO, &mut scratch).unwrap(); + frame.validate().unwrap(); + assert_eq!((frame.width, frame.height), size, "{rotation}"); + let PixelsRef::I420 { y, u, .. } = frame.pixels else { panic!("not I420") }; + assert_eq!(y.data, luma, "{rotation}"); + let chroma: &[u8] = if rotation == 90 { &[10, 11] } else { &[11, 10] }; + assert_eq!(u.data, chroma, "{rotation}"); + } + + let short = YuvPlanes { y: &y[..7], rotation: 90, ..planar }; + assert!(short.frame(Duration::ZERO, &mut Vec::new()).is_err()); + } + #[test] fn four_character_codes() { assert_eq!(Pixel::from_fourcc(u32::from_le_bytes(*b"YUYV")), Some(Pixel::Yuyv)); diff --git a/crates/voelin-media/src/studio/camera/mf.rs b/crates/voelin-media/src/studio/camera/mf.rs index 5511782..70c6d5a 100644 --- a/crates/voelin-media/src/studio/camera/mf.rs +++ b/crates/voelin-media/src/studio/camera/mf.rs @@ -229,7 +229,8 @@ pub fn list() -> Vec { debug!(camera = %name, "cannot read the camera's formats: {e}"); Vec::new() }); - cameras.push(Camera { id, name, backend: "mediafoundation", formats }); + // Webcams face the user. + cameras.push(Camera { id, name, backend: "mediafoundation", formats, mirrored: true }); } Ok(cameras) }) diff --git a/crates/voelin-media/src/studio/output/rtmp.rs b/crates/voelin-media/src/studio/output/rtmp.rs index 9627219..e25e0b5 100644 --- a/crates/voelin-media/src/studio/output/rtmp.rs +++ b/crates/voelin-media/src/studio/output/rtmp.rs @@ -39,6 +39,7 @@ use crate::{Error, Result}; /// Packets waiting for the connection's thread: about two seconds of a /// 60 fps stream with its audio. +#[cfg(feature = "ffmpeg")] const QUEUE: usize = 256; /// The AAC bitrate (bit/s): what the big services recommend. pub const AAC_BITRATE: u64 = 160_000; @@ -46,13 +47,16 @@ pub const AAC_BITRATE: u64 = 160_000; /// before it is given up and made again. const TIMEOUT: Duration = Duration::from_secs(10); /// Waits between connection attempts: doubling from the first to the last. +#[cfg(feature = "ffmpeg")] const BACKOFF: (Duration, Duration) = (Duration::from_secs(1), Duration::from_secs(30)); /// How long closing may take (unpublish) before the network is cut off. const CLOSE_GRACE: Duration = Duration::from_secs(3); /// Audio kept while waiting for the first keyframe (as a recording does). +#[cfg(feature = "ffmpeg")] const BACKLOG_MS: i64 = 2_000; /// Audio waits for the video of its time at most this long (it is written in /// time order with the video, and the video comes later: the encoders' delay). +#[cfg(feature = "ffmpeg")] const INTERLEAVE_MS: i64 = 1_000; fn error(message: impl Into) -> Error { @@ -109,6 +113,10 @@ impl Target { } /// One packet on its way to the connection's thread. +#[cfg_attr( + not(feature = "ffmpeg"), + allow(dead_code, reason = "without FFmpeg no connection thread reads them") +)] struct Queued { video: bool, keyframe: bool, diff --git a/crates/voelin-ui/src/app.rs b/crates/voelin-ui/src/app.rs index 51f2f2b..f7ae014 100644 --- a/crates/voelin-ui/src/app.rs +++ b/crates/voelin-ui/src/app.rs @@ -408,6 +408,9 @@ pub(crate) struct App { } thread_local! { + // It is `const`; clippy for Android targets does not see that through + // the macro's expansion there. + #[allow(clippy::missing_const_for_thread_local)] static APP: RefCell> = const { RefCell::new(None) }; } @@ -647,6 +650,8 @@ pub fn run(options: RunOptions) -> Result<()> { }); let _dev = crate::dev::start(&ui, &switches); + // What the platform asked for before the window ran. + crate::inbox::take(); ui.run()?; // With our own engine, leave servers properly, so no ghost client stays @@ -746,6 +751,9 @@ impl App { self.playback = self.prefs.get(&CLIENT_PLAYBACK); } else if appearance_keys().iter().any(|k| k.name() == key) { self.apply_appearance(); + } else if key == voelin_core::settings::STREAM_AUDIO_SOURCES.name() { + // A running share mixes the new sources (streams.rs). + self.share_audio_changed(); } } diff --git a/crates/voelin-ui/src/bind/servers.rs b/crates/voelin-ui/src/bind/servers.rs index a5100ce..e232a47 100644 --- a/crates/voelin-ui/src/bind/servers.rs +++ b/crates/voelin-ui/src/bind/servers.rs @@ -61,4 +61,5 @@ pub(super) fn wire(ui: &MainWindow) { bridge.on_client_audio_changed(|form| { with_app(|app| app.client_playback_changed(&form)); }); + bridge.on_invite(|| with_app(|app| app.invite_link()).unwrap_or_default().into()); } diff --git a/crates/voelin-ui/src/bind/studio.rs b/crates/voelin-ui/src/bind/studio.rs index 1d3a0c1..4ed0b1c 100644 --- a/crates/voelin-ui/src/bind/studio.rs +++ b/crates/voelin-ui/src/bind/studio.rs @@ -73,8 +73,8 @@ pub(crate) fn wire(bridge: &StudioBridge) { bridge.on_list_audio(|| { with_app(|app| app.studio_list_audio()); }); - bridge.on_add_audio(|i| { - with_app(|app| app.studio_add_audio(index(i))); + bridge.on_toggle_audio(|i| { + with_app(|app| app.studio_toggle_audio(index(i))); }); bridge.on_set_gain(|i, db, done| { with_app(|app| app.studio_set_gain(index(i), db, done)); diff --git a/crates/voelin-ui/src/chat.rs b/crates/voelin-ui/src/chat.rs index 57fa9fc..80bea68 100644 --- a/crates/voelin-ui/src/chat.rs +++ b/crates/voelin-ui/src/chat.rs @@ -335,7 +335,17 @@ impl App { let tabs: Vec = view .tabs .iter() - .map(|t| ChatTab { + .map(|t| { + let (last, time) = t + .messages + .last() + .map(|m| vm::chat::preview(&m.message.message)) + .unwrap_or_default(); + (t, last, time) + }) + .map(|(t, last, time)| ChatTab { + last: last.into(), + time: time.into(), title: t.title.clone().into(), name: t.title.trim_start_matches(['#', '@']).into(), kind: match t.target { @@ -740,7 +750,7 @@ impl App { } /// Upload a file into a channel and link it in the chat once it is up. - fn upload(&mut self, id: i64, channel: u64, from: PathBuf) { + pub(crate) fn upload(&mut self, id: i64, channel: u64, from: PathBuf) { let Some(name) = from.file_name().map(|n| n.to_string_lossy().to_string()) else { return }; let view = self.sessions.entry(id).or_default(); let transfer = view.next_transfer; diff --git a/crates/voelin-ui/src/dev.rs b/crates/voelin-ui/src/dev.rs index 5342aae..c99af1b 100644 --- a/crates/voelin-ui/src/dev.rs +++ b/crates/voelin-ui/src/dev.rs @@ -15,7 +15,10 @@ //! appearance, or 0-4), `about`, `share`, `bookmark` (add a server), //! `emoji` (the picker), `client` (the volume dialog of the first other //! client once connected), `panel` / `no-panel` (the members panel), -//! `voice` (the voice channel view), `pins`, `topics` (the drawers), +//! `voice` (the voice channel view; on the phone its own screen), +//! `members` (the phone's members page), `notification` (a tapped voice +//! notification), `shared:` (text shared to the app on Android), +//! `pins`, `topics` (the drawers), //! `topic:` (a topic's messages), `member` (the member card of the //! first other client), `watch` (the first stream; with sample data the //! local test pattern in its place), `popout` (the same, popped out), @@ -149,7 +152,13 @@ pub(crate) fn start(ui: &MainWindow, switches: &Switches) -> Running { "server" => nav.invoke_show(Page::Server), "settings" => nav.invoke_open_settings(section(arg)), "about" => nav.invoke_open_about(), - "share" => nav.invoke_open_share(), + "share" => { + nav.invoke_open_share(); + // The sample share of the test pattern, live at once. + if arg == "live" && switches.demo_ui { + with_app(|app| app.demo_share()); + } + } "bookmark" => nav.invoke_add_server(), "emoji" => nav.set_emoji_open(true), "panel" => nav.set_right_panel_open(true), @@ -157,6 +166,15 @@ pub(crate) fn start(ui: &MainWindow, switches: &Switches) -> Running { "tab" => nav.set_mobile_tab(mobile_tab(arg)), "voice" => nav.invoke_show_voice(true), "pins" => nav.invoke_show_pins(true), + // The phone's members page. + "members" => nav.set_members_open(true), + // What Android hands over: a tapped voice notification, text + // shared to the app. + "notification" => crate::inbox::request(crate::inbox::Request::ShowVoice), + "shared" => crate::inbox::request(crate::inbox::Request::Share { + text: Some(arg.to_owned()), + files: Vec::new(), + }), "topics" => nav.invoke_show_topics(true), "topic" => { with_app(|app| { diff --git a/crates/voelin-ui/src/inbox.rs b/crates/voelin-ui/src/inbox.rs new file mode 100644 index 0000000..0bb05c1 --- /dev/null +++ b/crates/voelin-ui/src/inbox.rs @@ -0,0 +1,101 @@ +//! Requests from the platform around the window: on Android a tapped +//! notification or something shared to the app ("Share to Voelin"). They +//! can come from any thread and before the window runs; [`request`] keeps +//! them until the window takes them on its thread. + +use std::path::PathBuf; +use std::sync::{Mutex, PoisonError}; + +use slint::ComponentHandle; +use voelin_model::ChatTarget; + +use crate::app::{App, MobileTab, Nav, Page, with_app}; + +/// What the platform asks the window to do. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Request { + /// Show the voice channel we are in (the phone's voice screen). + ShowVoice, + /// Shared to the app: the text goes into the current chat's composer + /// (to send with one tap, or edit, as a mis-tap in the share sheet + /// should not post into a chat), the files are uploaded to the current + /// channel and linked there, as the composer's attach button does. + Share { text: Option, files: Vec }, +} + +static PENDING: Mutex> = Mutex::new(Vec::new()); + +/// Hand `request` to the window: at once if it runs, else when it starts. +pub fn request(request: Request) { + PENDING.lock().unwrap_or_else(PoisonError::into_inner).push(request); + // Fails without an event loop yet; `run` takes them then. + let _ = slint::invoke_from_event_loop(take); +} + +/// Handle what is pending, on the window's thread; kept while there is no +/// window. +pub(crate) fn take() { + let Some(ui) = with_app(|app| app.ui.upgrade()).flatten() else { return }; + let requests = std::mem::take(&mut *PENDING.lock().unwrap_or_else(PoisonError::into_inner)); + // Not inside `with_app`: navigating calls back into Rust, which borrows + // the app again. + let nav = ui.global::