diff --git a/Cargo.lock b/Cargo.lock
index 42b09e9..9613471 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