Merge claude/gifted-lovelace-1crlx2 (Wave 5B) into the negotiation work
The base moved on (the phone and Android wave, the quick share's sound, voelinctl subscribing to every channel); it merges without conflicts and the negotiation changes build and pass on top of it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
No files matched your search
@@ -9435,6 +9435,7 @@ dependencies = [
|
||||
"tokio",
|
||||
"tracing",
|
||||
"tracing-subscriber",
|
||||
"tsclientlib",
|
||||
"voelin-core",
|
||||
"voelin-media",
|
||||
"voelin-model",
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -10,6 +10,9 @@
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_MICROPHONE" />
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PROJECTION" />
|
||||
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
|
||||
<!-- Camera sources of the Stream Studio; asked for when one is added. -->
|
||||
<uses-permission android:name="android.permission.CAMERA" />
|
||||
<uses-feature android:name="android.hardware.camera.any" android:required="false" />
|
||||
|
||||
<!--
|
||||
Launchable apps are visible (Android 11+ package visibility): the
|
||||
@@ -56,6 +59,17 @@
|
||||
<action android:name="android.intent.action.MAIN" />
|
||||
<category android:name="android.intent.category.LAUNCHER" />
|
||||
</intent-filter>
|
||||
<!--
|
||||
"Share to Voelin": text and links go into the composer of
|
||||
the current chat, files (pictures, videos, documents) are
|
||||
uploaded to the current channel.
|
||||
-->
|
||||
<intent-filter android:label="@string/share_label">
|
||||
<action android:name="android.intent.action.SEND" />
|
||||
<action android:name="android.intent.action.SEND_MULTIPLE" />
|
||||
<category android:name="android.intent.category.DEFAULT" />
|
||||
<data android:mimeType="*/*" />
|
||||
</intent-filter>
|
||||
</activity>
|
||||
|
||||
<!-- Keeps the microphone and the connection while in the background. -->
|
||||
|
||||
@@ -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 "label<TAB>package" lines sorted by label. */
|
||||
/**
|
||||
* Launchable apps other than us, as "label<TAB>package<TAB>icon" 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
|
||||
|
||||
@@ -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<Long, Running>()
|
||||
|
||||
/** Starts waiting for the CAMERA permission, by id. */
|
||||
private val waiting = ConcurrentHashMap<Long, () -> 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<Size> =
|
||||
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<Range<Int>> =
|
||||
c.get(CameraCharacteristics.CONTROL_AE_AVAILABLE_TARGET_FPS_RANGES)?.toList().orEmpty()
|
||||
|
||||
/**
|
||||
* The cameras, front ones first: "id<TAB>facing<TAB>sizes<TAB>maxFps"
|
||||
* 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<Size>, 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<Range<Int>>, fps: Int): Range<Int>? =
|
||||
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
|
||||
}
|
||||
}
|
||||
@@ -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<Uri> = 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<out String>, 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
|
||||
|
||||
@@ -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?)
|
||||
}
|
||||
@@ -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<String, PendingIntent>,
|
||||
): 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()
|
||||
}
|
||||
|
||||
@@ -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<String, String>? = 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)
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,12 +1,16 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources>
|
||||
<string name="app_name">Voelin</string>
|
||||
<string name="share_label">Voelin</string>
|
||||
<string name="channel_voice">Voice connection</string>
|
||||
<string name="channel_screen">Screen sharing</string>
|
||||
<string name="voice_connected">Connected to voice</string>
|
||||
<string name="disconnect">Disconnect</string>
|
||||
<string name="leave">Leave</string>
|
||||
<string name="mute">Mute</string>
|
||||
<string name="unmute">Unmute</string>
|
||||
<string name="deafen">Deafen</string>
|
||||
<string name="undeafen">Undeafen</string>
|
||||
<string name="screen_sharing">Sharing your screen</string>
|
||||
<string name="screen_sharing_text">Starting the stream</string>
|
||||
<string name="stop_sharing">Stop sharing</string>
|
||||
</resources>
|
||||
@@ -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
|
||||
@@ -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 });
|
||||
}
|
||||
}
|
||||
@@ -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<Global<JClass<'static>>> = 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<JObject<'local>> {
|
||||
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<Vec<(String, String)>> {
|
||||
/// 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<Vec<(String, String, String)>> {
|
||||
let lines = with_bridge(|env, class| {
|
||||
let value = env
|
||||
.call_static_method(
|
||||
@@ -163,19 +236,71 @@ pub fn launchable_apps() -> Result<Vec<(String, String)>> {
|
||||
Ok(parse_apps(&lines))
|
||||
}
|
||||
|
||||
/// `label<TAB>package` lines.
|
||||
fn parse_apps(lines: &str) -> Vec<(String, String)> {
|
||||
/// `label<TAB>package<TAB>icon` 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`): `id<TAB>facing<TAB>sizes<TAB>maxFps`
|
||||
/// lines.
|
||||
pub fn cameras() -> Result<String> {
|
||||
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::<JString>(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<bool> {
|
||||
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<Option<String>> {
|
||||
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<jboolean> {
|
||||
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<Vec<f32>> = 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<jboolean> {
|
||||
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(())
|
||||
}
|
||||
@@ -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<dyn FrameSink>,
|
||||
feed: Arc<Feed>,
|
||||
/// Clock origin of the frames' timestamps (`Image.timestamp`).
|
||||
origin_ns: Option<i64>,
|
||||
/// Gathered or turned pictures (I420), reused.
|
||||
scratch: Vec<u8>,
|
||||
}
|
||||
|
||||
static RUNNING: Mutex<Option<HashMap<u64, Running>>> = Mutex::new(None);
|
||||
|
||||
fn running() -> MutexGuard<'static, Option<HashMap<u64, Running>>> {
|
||||
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<Camera> {
|
||||
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<dyn FrameSink>,
|
||||
feed: Arc<Feed>,
|
||||
) -> Result<Box<dyn Send>> {
|
||||
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 })
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `id<TAB>facing<TAB>sizes<TAB>maxFps` lines (`CameraCapture.list`).
|
||||
fn parse(lines: &str) -> Vec<Camera> {
|
||||
let mut seen: HashMap<String, usize> = 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::<Vec<(u32, u32)>>();
|
||||
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 });
|
||||
}
|
||||
}
|
||||
@@ -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<R>(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<Box<dyn FrameSink>>,
|
||||
/// 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<u64>,
|
||||
}
|
||||
|
||||
static VIDEO: Mutex<Option<Video>> = Mutex::new(None);
|
||||
|
||||
fn with_video<R>(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<i64>, now_ns: i64) -> Duration {
|
||||
|
||||
struct Projection;
|
||||
|
||||
impl Projection {
|
||||
/// Ask for consent; `Ok` once the capture runs.
|
||||
fn request(options: &CaptureOptions, tx: oneshot::Sender<Result<()>>) -> 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<VideoFrame>,
|
||||
) -> 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<dyn FrameSink>,
|
||||
) -> 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<Option<InputSurface>> = 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<String>) {
|
||||
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<String>) {
|
||||
}
|
||||
|
||||
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<u8>,
|
||||
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;
|
||||
|
||||
@@ -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<Option<VoiceNotice>>,
|
||||
pub screen: Option<Option<ScreenNotice>>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
@@ -27,26 +56,81 @@ struct Session {
|
||||
name: Option<String>,
|
||||
voice: VoiceState,
|
||||
muted: bool,
|
||||
deafened: bool,
|
||||
own_channel: Option<u64>,
|
||||
presence: Arc<Presence>,
|
||||
/// When voice connected (Unix ms).
|
||||
since_ms: Option<u64>,
|
||||
/// 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<Option<VoiceNotice>> {
|
||||
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<Item = (&SessionId, &Session)> {
|
||||
@@ -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<VoiceNotice> {
|
||||
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::<Vec<_>>().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<ScreenNotice> {
|
||||
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<Option<VoiceNotice>> {
|
||||
Some(Some(VoiceNotice { text: text.into(), muted }))
|
||||
fn notice(title: &str, text: &str, muted: bool, since_ms: u64) -> Option<Option<VoiceNotice>> {
|
||||
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));
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
@@ -1591,7 +1591,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"))]
|
||||
{
|
||||
@@ -1602,7 +1603,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
|
||||
}
|
||||
|
||||
@@ -1726,7 +1738,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
|
||||
|
||||
@@ -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<VideoFrame>,
|
||||
) -> 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<dyn FrameSink>,
|
||||
) -> 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<dyn FrameSink>,
|
||||
) -> 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();
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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<Option<InputSurface>> = 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<InputSurface> {
|
||||
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<MediaCodecFactory> {
|
||||
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<EncoderSession>,
|
||||
/// 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<u8>,
|
||||
last_pts_us: Option<u64>,
|
||||
/// The surface path: the generation of the input surface it published.
|
||||
surface: Option<u64>,
|
||||
}
|
||||
|
||||
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<EncoderSession> {
|
||||
let codec = self.codec;
|
||||
let profiles: &[Option<i32>] = 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<Vec<EncodedFrame>> {
|
||||
/// 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<Vec<EncodedFrame>> {
|
||||
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<Vec<Encod
|
||||
with_sps.append(&mut data);
|
||||
data = with_sps;
|
||||
}
|
||||
let pts_us = u64::try_from(info.presentation_time_us()).unwrap_or(0);
|
||||
let mut pts_us = info.presentation_time_us();
|
||||
if session.surface.is_some() {
|
||||
// The display's clock: onto the capture's timeline.
|
||||
let origin = SCREEN_ORIGIN_NS.load(Ordering::Relaxed);
|
||||
if origin != i64::MIN {
|
||||
pts_us -= origin / 1000;
|
||||
}
|
||||
}
|
||||
let pts_us = u64::try_from(pts_us).unwrap_or(0);
|
||||
out.push(EncodedFrame { data, keyframe, pts_90khz: pts_us * 9 / 100 });
|
||||
}
|
||||
DequeuedOutputBufferInfoResult::OutputFormatChanged
|
||||
|
||||
@@ -288,8 +288,10 @@ impl VideoFrame {
|
||||
/// from a captured DMA-BUF on the GPU (`ffmpeg::GpuConverter`, Linux) so
|
||||
/// that no CPU reads its pixels, for the encoders that take one
|
||||
/// ([`VideoEncoder::gpu_alignment`](crate::VideoEncoder::gpu_alignment)).
|
||||
/// Dropping it gives the surface back to its pool. Only this crate makes
|
||||
/// them.
|
||||
/// Dropping it gives the surface back to its pool. On Android it stands for
|
||||
/// a screen picture the virtual display renders straight into MediaCodec's
|
||||
/// input surface ([`GpuFrame::rendered`]): only its size and time travel.
|
||||
/// Only this crate makes them.
|
||||
#[non_exhaustive]
|
||||
pub struct GpuFrame {
|
||||
pub width: u32,
|
||||
@@ -306,6 +308,27 @@ impl GpuFrame {
|
||||
(self.timestamp.as_micros() * u128::from(VIDEO_CLOCK_RATE) / 1_000_000) as u64
|
||||
}
|
||||
|
||||
/// A screen picture the virtual display renders straight into the
|
||||
/// encoder's input surface (`codec::mediacodec`, the zero-copy path):
|
||||
/// nothing but its size and time is handed over.
|
||||
#[cfg(all(target_os = "android", not(feature = "ffmpeg")))]
|
||||
pub fn rendered(width: u32, height: u32, timestamp: Duration) -> 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 {
|
||||
|
||||
@@ -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<Format>,
|
||||
/// 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<Camera> {
|
||||
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<Camera>;
|
||||
|
||||
/// 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<dyn FrameSink>,
|
||||
feed: Arc<Feed>,
|
||||
) -> Result<Box<dyn Send>>;
|
||||
}
|
||||
|
||||
static PROVIDER: Mutex<Option<Arc<dyn CameraProvider>>> = Mutex::new(None);
|
||||
|
||||
/// Make [`list`] and [`Capture::start`] use `provider` (`None`: only the
|
||||
/// built-in cameras).
|
||||
pub fn set_provider(provider: Option<Arc<dyn CameraProvider>>) {
|
||||
*PROVIDER.lock().unwrap_or_else(PoisonError::into_inner) = provider;
|
||||
}
|
||||
|
||||
fn provider() -> Option<Arc<dyn CameraProvider>> {
|
||||
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<u8>) -> Result<FrameRef<'a>> {
|
||||
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<Box<dyn ScreenCapture>>,
|
||||
/// A [`CameraProvider`]'s camera, stopped when dropped.
|
||||
_external: Option<Box<dyn Send>>,
|
||||
#[cfg(all(target_os = "linux", feature = "pipewire"))]
|
||||
stream: Option<pipewire_camera::Stream>,
|
||||
/// 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<u8> = (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));
|
||||
|
||||
@@ -229,7 +229,8 @@ pub fn list() -> Vec<Camera> {
|
||||
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)
|
||||
})
|
||||
|
||||
@@ -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<String>) -> 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,
|
||||
|
||||
@@ -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<Option<App>> = const { RefCell::new(None) };
|
||||
}
|
||||
|
||||
@@ -631,6 +634,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
|
||||
@@ -730,6 +735,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();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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());
|
||||
}
|
||||
@@ -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));
|
||||
|
||||
@@ -335,7 +335,17 @@ impl App {
|
||||
let tabs: Vec<ChatTab> = 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;
|
||||
|
||||
@@ -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>` (text shared to the app on Android),
|
||||
//! `pins`, `topics` (the drawers),
|
||||
//! `topic:<id>` (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| {
|
||||
|
||||
@@ -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<String>, files: Vec<PathBuf> },
|
||||
}
|
||||
|
||||
static PENDING: Mutex<Vec<Request>> = 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::<Nav>();
|
||||
for request in requests {
|
||||
match request {
|
||||
Request::ShowVoice => {
|
||||
nav.invoke_show(Page::Server);
|
||||
nav.invoke_show_voice(true);
|
||||
}
|
||||
Request::Share { text, files } => {
|
||||
// The phone shows the chat it went to.
|
||||
nav.set_mobile_tab(MobileTab::Chat);
|
||||
nav.invoke_show(Page::Server);
|
||||
with_app(|app| app.share(&nav, text, files));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl App {
|
||||
fn share(&mut self, nav: &Nav<'_>, text: Option<String>, files: Vec<PathBuf>) {
|
||||
let current = self.current.and_then(|id| {
|
||||
let view = self.sessions.get(&id)?;
|
||||
let tab = &view.tabs[view.current_tab];
|
||||
// Files go to the channel of the chat, else to ours.
|
||||
let channel = match tab.target {
|
||||
ChatTarget::Channel(channel) => Some(channel),
|
||||
_ => view.state.own_channel,
|
||||
}
|
||||
.map(|c| {
|
||||
let name = view.presence.channels.get(&c).map(|c| c.name.as_str());
|
||||
(c, name.map_or_else(|| "the channel".to_owned(), |n| format!("#{n}")))
|
||||
});
|
||||
Some((id, tab.title.clone(), channel))
|
||||
});
|
||||
if let Some(text) = text.filter(|t| !t.trim().is_empty()) {
|
||||
nav.set_draft(text.into());
|
||||
self.set_status(match ¤t {
|
||||
Some((_, title, _)) => format!("Shared text is ready to send to {title}"),
|
||||
None => "Shared text is in the composer".to_owned(),
|
||||
});
|
||||
}
|
||||
if files.is_empty() {
|
||||
return;
|
||||
}
|
||||
match current {
|
||||
Some((id, _, Some((channel, name)))) if !self.demo_ui => {
|
||||
let count = files.len();
|
||||
for file in files {
|
||||
self.upload(id, channel, file);
|
||||
}
|
||||
let what = if count == 1 {
|
||||
"the shared file".to_owned()
|
||||
} else {
|
||||
format!("{count} files")
|
||||
};
|
||||
self.set_status(format!("Uploading {what} to {name}"));
|
||||
}
|
||||
_ => self.set_status("Open a channel's chat (or join a channel) to share files there"),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,7 @@ mod dev;
|
||||
mod emoji;
|
||||
mod hotkey;
|
||||
mod images;
|
||||
mod inbox;
|
||||
mod members;
|
||||
mod servers;
|
||||
mod settings;
|
||||
@@ -18,3 +19,4 @@ mod video;
|
||||
mod vm;
|
||||
|
||||
pub use app::{HostedEngine, RunOptions, run};
|
||||
pub use inbox::{Request, request};
|
||||
@@ -316,6 +316,33 @@ impl App {
|
||||
self.refresh_tree();
|
||||
}
|
||||
|
||||
/// A link to the voice channel we are in, for the Invite button (which
|
||||
/// copies it); empty, with a note, without one.
|
||||
pub(crate) fn invite_link(&mut self) -> String {
|
||||
let bookmark = self.current.and_then(|id| self.bookmark(id)).map(|b| b.address.clone());
|
||||
let path = self.view().and_then(|v| {
|
||||
let mut names = Vec::new();
|
||||
let mut channel = v.presence.channels.get(&v.state.own_channel?)?;
|
||||
loop {
|
||||
names.push(channel.name.clone());
|
||||
match v.presence.channels.get(&channel.parent) {
|
||||
Some(parent) if channel.parent != 0 && names.len() < 64 => channel = parent,
|
||||
_ => break,
|
||||
}
|
||||
}
|
||||
names.reverse();
|
||||
Some(names)
|
||||
});
|
||||
let (Some(address), Some(path)) = (bookmark, path) else {
|
||||
self.set_status("Join a voice channel to invite others to it");
|
||||
return String::new();
|
||||
};
|
||||
let path: Vec<&str> = path.iter().map(String::as_str).collect();
|
||||
let link = vm::servers::invite_link(&address, &path);
|
||||
self.set_status(format!("Copied an invite to {}: {link}", path.last().unwrap_or(&"")));
|
||||
link
|
||||
}
|
||||
|
||||
pub(crate) fn toggle_collapse(&mut self, channel: u64) {
|
||||
if let Some(view) = self.view_mut()
|
||||
&& !view.collapsed.remove(&channel)
|
||||
|
||||
@@ -2,16 +2,22 @@
|
||||
//! viewer. The engine runs the stream sessions; `video.rs` captures,
|
||||
//! encodes and decodes.
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
use slint::{ComponentHandle, Model};
|
||||
use tracing::warn;
|
||||
use voelin_core::media::audio_source_specs;
|
||||
use voelin_core::settings::{STREAM_AUDIO_SOURCES, STREAM_BITRATE_KBPS, STREAM_FPS};
|
||||
use voelin_core::media::{Streamer, audio_source_specs};
|
||||
use voelin_core::settings::{
|
||||
AudioSourceSetting, STREAM_AUDIO_SOURCES, STREAM_BITRATE_KBPS, STREAM_FPS,
|
||||
};
|
||||
use voelin_core::stream::{
|
||||
EndReason, LayerId, LayerSpec, LeaveReason, StreamKind, StreamSetup, ViewerInfo, ViewerState,
|
||||
};
|
||||
use voelin_core::{Command, Event, StreamState, WatchState};
|
||||
|
||||
use crate::app::{App, Bridge, ShareForm, SourceItem, StreamItem, ViewerItem, later, model};
|
||||
use crate::app::{
|
||||
App, Bridge, ShareForm, SourceItem, StreamItem, ViewerItem, later, model, with_app,
|
||||
};
|
||||
use crate::settings::{
|
||||
BITRATE_CHOICES, FPS_CHOICES, ShareDefaults, nearest_choice, parse_positive,
|
||||
};
|
||||
@@ -27,6 +33,46 @@ pub(crate) struct Share {
|
||||
viewers: Vec<ViewerInfo>,
|
||||
/// The capture ended by itself and the stream is being stopped.
|
||||
stopping: bool,
|
||||
/// The audio mixer's meters (the studio's rows), about 15 times a second.
|
||||
_meters: slint::Timer,
|
||||
}
|
||||
|
||||
/// What the share dialog asks of the capture: the audio mixer's `sources`
|
||||
/// (`stream.audio_sources`) while "Share system audio" is on; off, or with
|
||||
/// no sources, no audio at all.
|
||||
fn capture_request(
|
||||
fps: u32,
|
||||
bitrate_kbps: u32,
|
||||
audio: bool,
|
||||
sources: &[AudioSourceSetting],
|
||||
restore_token: Option<String>,
|
||||
) -> CaptureRequest {
|
||||
let audio_sources = if audio { audio_source_specs(sources) } else { Vec::new() };
|
||||
CaptureRequest {
|
||||
fps,
|
||||
bitrate_kbps,
|
||||
audio: !audio_sources.is_empty(),
|
||||
audio_sources,
|
||||
restore_token,
|
||||
}
|
||||
}
|
||||
|
||||
/// The viewers of the sample share (VOELIN_DEMO_UI): two watch, one asks.
|
||||
fn demo_viewers() -> Vec<ViewerInfo> {
|
||||
let viewer = |id, state, message: &str| ViewerInfo {
|
||||
client: tsclientlib::ClientId(id),
|
||||
state,
|
||||
message: message.into(),
|
||||
layer: None,
|
||||
estimate: None,
|
||||
srtp_profile: None,
|
||||
codec: None,
|
||||
};
|
||||
vec![
|
||||
viewer(3, ViewerState::Connected, ""),
|
||||
viewer(5, ViewerState::Connected, ""),
|
||||
viewer(4, ViewerState::Requested, "Can I watch?"),
|
||||
]
|
||||
}
|
||||
|
||||
/// The stream in the viewer.
|
||||
@@ -189,6 +235,7 @@ impl App {
|
||||
} else {
|
||||
share_end_text(&reason)
|
||||
});
|
||||
self.mixer_refresh();
|
||||
}
|
||||
}
|
||||
self.refresh_streams();
|
||||
@@ -305,6 +352,7 @@ impl App {
|
||||
bridge.set_share_state(state.into());
|
||||
bridge.set_share_busy(self.share_busy);
|
||||
bridge.set_share_error(self.share_error.clone().into());
|
||||
bridge.set_share_audio(share.is_some_and(|s| s.capture.has_audio()));
|
||||
let viewers: Vec<ViewerItem> = share
|
||||
.map(|s| {
|
||||
s.viewers
|
||||
@@ -367,6 +415,12 @@ impl App {
|
||||
.and_then(|v| v.streams.iter().find(|s| s.id == watch.stream_id))
|
||||
.map_or(-1, |s| i32::from(s.streamer.0));
|
||||
bridge.set_viewer_streamer_id(streamer);
|
||||
let members = &self.models.members;
|
||||
bridge.set_viewer_streamer_admin(
|
||||
(0..members.row_count())
|
||||
.filter_map(|i| members.row_data(i))
|
||||
.any(|m| m.id == streamer && m.admin),
|
||||
);
|
||||
let channel = u16::try_from(streamer).ok().and_then(|id| {
|
||||
let view = self.view()?;
|
||||
view.presence.channels.get(&view.channel_of(id)?).map(|c| c.name.clone())
|
||||
@@ -428,6 +482,8 @@ impl App {
|
||||
if self.share.is_some() {
|
||||
self.refresh_streams();
|
||||
}
|
||||
// The share dialog's audio mixer (studio.rs).
|
||||
self.mixer_tick();
|
||||
if self.watch.is_some() {
|
||||
self.refresh_viewer();
|
||||
}
|
||||
@@ -461,6 +517,8 @@ impl App {
|
||||
ui.global::<Bridge>().set_share_sources(model(items));
|
||||
}
|
||||
self.refresh_streams();
|
||||
// Its audio: the Stream Studio's mixer rows and picker.
|
||||
self.mixer_show();
|
||||
let defaults = &self.settings.share;
|
||||
let nickname = self.current.and_then(|id| self.bookmark(id)).map(|b| b.nickname.clone());
|
||||
let (fps, bitrate) = (self.prefs.get(&STREAM_FPS), self.prefs.get(&STREAM_BITRATE_KBPS));
|
||||
@@ -479,21 +537,34 @@ impl App {
|
||||
}
|
||||
}
|
||||
|
||||
/// The share dialog's form with the test pattern chosen.
|
||||
fn test_pattern_form(&mut self) -> Option<ShareForm> {
|
||||
let mut form = self.open_share();
|
||||
let ui = self.ui.upgrade()?;
|
||||
let sources = ui.global::<Bridge>().get_share_sources();
|
||||
let pattern = (0..sources.row_count())
|
||||
.find(|&i| sources.row_data(i).is_some_and(|s| s.name == "Test pattern"))?;
|
||||
form.source = pattern as i32;
|
||||
Some(form)
|
||||
}
|
||||
|
||||
/// Development switch `VOELIN_AUTOSHARE`: share the test pattern once.
|
||||
pub(crate) fn autoshare(&mut self) {
|
||||
if !self.autoshare || !self.view().is_some_and(|v| v.streams_available()) {
|
||||
return;
|
||||
}
|
||||
self.autoshare = false;
|
||||
let mut form = self.open_share();
|
||||
let Some(ui) = self.ui.upgrade() else { return };
|
||||
let sources = ui.global::<Bridge>().get_share_sources();
|
||||
let pattern = (0..sources.row_count())
|
||||
.find(|&i| sources.row_data(i).is_some_and(|s| s.name == "Test pattern"));
|
||||
let Some(index) = pattern else { return };
|
||||
form.source = index as i32;
|
||||
form.auto_accept = true;
|
||||
self.start_share(form);
|
||||
if let Some(form) = self.test_pattern_form() {
|
||||
self.start_share(ShareForm { auto_accept: true, ..form });
|
||||
}
|
||||
}
|
||||
|
||||
/// `VOELIN_OPEN=share:live` with sample data: the test pattern shared
|
||||
/// with the sample mixer's sources (live at once, `capture_ready`).
|
||||
pub(crate) fn demo_share(&mut self) {
|
||||
if let Some(form) = self.test_pattern_form() {
|
||||
self.start_share(ShareForm { audio: true, ..form });
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn start_share(&mut self, form: ShareForm) {
|
||||
@@ -527,15 +598,10 @@ impl App {
|
||||
audio: form.audio,
|
||||
auto_accept: form.auto_accept,
|
||||
};
|
||||
// No sources configured: no audio.
|
||||
let audio_sources = audio_source_specs(&self.prefs.get(&STREAM_AUDIO_SOURCES));
|
||||
let request = CaptureRequest {
|
||||
fps,
|
||||
bitrate_kbps: bitrate,
|
||||
audio: form.audio && !audio_sources.is_empty(),
|
||||
audio_sources,
|
||||
restore_token: self.settings.portal_restore_token.clone(),
|
||||
};
|
||||
// The mixer's sources (the sample studio's with VOELIN_DEMO_UI).
|
||||
let sources = self.studio_settings().get(&STREAM_AUDIO_SOURCES);
|
||||
let token = self.settings.portal_restore_token.clone();
|
||||
let request = capture_request(fps, bitrate, form.audio, &sources, token);
|
||||
self.settings.share = defaults;
|
||||
self.store_settings();
|
||||
self.share_busy = true;
|
||||
@@ -544,7 +610,7 @@ impl App {
|
||||
let setup = StreamSetup {
|
||||
name: form.name.trim().to_owned(),
|
||||
bitrate,
|
||||
audio: form.audio,
|
||||
audio: request.audio,
|
||||
..StreamSetup::default()
|
||||
};
|
||||
let auto_accept = form.auto_accept;
|
||||
@@ -580,30 +646,64 @@ impl App {
|
||||
let reason = capture.audio_error().unwrap_or_default();
|
||||
self.set_status(format!("Sharing without sound: {reason}"));
|
||||
}
|
||||
self.engine.send(Command::StartStream {
|
||||
session: session as u64,
|
||||
setup,
|
||||
auto_accept,
|
||||
// Sample data has no server: live at once, with viewers.
|
||||
let (live, viewers) = if self.demo_ui {
|
||||
(true, demo_viewers())
|
||||
} else {
|
||||
let session = session as u64;
|
||||
self.engine.send(Command::StartStream { session, setup, auto_accept });
|
||||
(false, Vec::new())
|
||||
};
|
||||
let meters = slint::Timer::default();
|
||||
meters.start(slint::TimerMode::Repeated, Duration::from_millis(66), || {
|
||||
with_app(|app| app.studio_meters());
|
||||
});
|
||||
self.share = Some(Share {
|
||||
session,
|
||||
capture,
|
||||
live: false,
|
||||
viewers: Vec::new(),
|
||||
live,
|
||||
viewers,
|
||||
stopping: false,
|
||||
_meters: meters,
|
||||
});
|
||||
// The mixer's rows follow this capture's sources.
|
||||
self.mixer_refresh();
|
||||
}
|
||||
}
|
||||
self.refresh_streams();
|
||||
}
|
||||
|
||||
pub(crate) fn stop_share(&mut self) {
|
||||
if let Some(share) = &mut self.share {
|
||||
share.stopping = true;
|
||||
self.engine.send(Command::StopStream { session: share.session as u64 });
|
||||
let Some(share) = &mut self.share else { return };
|
||||
share.stopping = true;
|
||||
let session = share.session;
|
||||
if self.demo_ui {
|
||||
self.share_state(session, StreamState::Ended(EndReason::Local));
|
||||
} else {
|
||||
self.engine.send(Command::StopStream { session: session as u64 });
|
||||
}
|
||||
}
|
||||
|
||||
/// The running share's streamer (the mixer's rows, studio.rs).
|
||||
pub(crate) fn share_streamer(&self) -> Option<&Streamer> {
|
||||
self.share.as_ref().map(|s| s.capture.streamer())
|
||||
}
|
||||
|
||||
/// `stream.audio_sources` changed (the mixer, the settings, another
|
||||
/// window): a running share mixes the new sources.
|
||||
pub(crate) fn share_audio_changed(&mut self) {
|
||||
if self.share.is_none() {
|
||||
return;
|
||||
}
|
||||
let sources = audio_source_specs(&self.studio_settings().get(&STREAM_AUDIO_SOURCES));
|
||||
let codecs = self.video.codecs();
|
||||
let Some(share) = &self.share else { return };
|
||||
if let Err(e) = share.capture.follow_audio(&codecs, sources) {
|
||||
self.set_status(format!("Stream audio: {e}"));
|
||||
}
|
||||
self.mixer_refresh();
|
||||
}
|
||||
|
||||
pub(crate) fn respond_viewer(&mut self, viewer: u16, accept: bool) {
|
||||
if let Some(share) = &self.share {
|
||||
let session = share.session as u64;
|
||||
@@ -814,4 +914,34 @@ mod tests {
|
||||
assert_eq!(super::bitrate_text(8000), "8 Mbit/s");
|
||||
assert_eq!(super::bitrate_text(4608), "4.6 Mbit/s");
|
||||
}
|
||||
|
||||
/// What the share dialog's mixer holds goes to the capture, with each
|
||||
/// source's gain and mute; "Share system audio" off (or nothing picked)
|
||||
/// shares no audio at all.
|
||||
#[test]
|
||||
fn the_share_carries_the_picked_audio() {
|
||||
use voelin_core::media::{AppMatch, AudioSourceKind};
|
||||
use voelin_core::settings::{AudioSourceKindSetting, AudioSourceSetting};
|
||||
let app = AudioSourceKindSetting::App { name: Some("firefox".into()), pid: None };
|
||||
let picked = [
|
||||
AudioSourceSetting { gain: 0.5, ..AudioSourceSetting::new(app) },
|
||||
AudioSourceSetting {
|
||||
muted: true,
|
||||
..AudioSourceSetting::new(AudioSourceKindSetting::Microphone)
|
||||
},
|
||||
];
|
||||
let request = super::capture_request(30, 4608, true, &picked, None);
|
||||
assert!(request.audio);
|
||||
let kinds: Vec<_> = request.audio_sources.iter().map(|s| s.kind.clone()).collect();
|
||||
let firefox = AudioSourceKind::App(AppMatch::Name("firefox".into()));
|
||||
assert_eq!(kinds, [firefox, AudioSourceKind::Microphone]);
|
||||
let mix: Vec<_> = request.audio_sources.iter().map(|s| (s.gain, s.muted)).collect();
|
||||
assert_eq!(mix, [(0.5, false), (1.0, true)]);
|
||||
assert_eq!((request.fps, request.bitrate_kbps), (30, 4608));
|
||||
|
||||
let off = super::capture_request(30, 4608, false, &picked, None);
|
||||
assert!(!off.audio && off.audio_sources.is_empty());
|
||||
let none = super::capture_request(30, 4608, true, &[], None);
|
||||
assert!(!none.audio && none.audio_sources.is_empty());
|
||||
}
|
||||
}
|
||||
@@ -12,7 +12,7 @@
|
||||
//! VecModels) and get the same values; their callbacks come here
|
||||
//! (bind/studio.rs). Commands go to the studio through one task, in order.
|
||||
|
||||
use std::path::PathBuf;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::rc::Rc;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::{Arc, Weak};
|
||||
@@ -28,8 +28,8 @@ use voelin_core::media::voelin_media::handoff::Handoff;
|
||||
use voelin_core::media::voelin_media::mix::SourceHandle;
|
||||
use voelin_core::media::voelin_media::{VideoFrame, convert};
|
||||
use voelin_core::media::{
|
||||
AudioApps, AudioSourceSpec, Latest, Streamer, StreamerConfigUpdate, StreamerStats, audio_apps,
|
||||
audio_source_specs, screen_sources,
|
||||
AudioApps, AudioSourceSpec, AudioSourceStats, Latest, Streamer, StreamerConfigUpdate,
|
||||
StreamerStats, audio_apps, audio_source_specs, screen_sources,
|
||||
};
|
||||
use voelin_core::settings::{
|
||||
AudioSourceKindSetting, AudioSourceSetting, Key, Kind, STREAM_AUDIO_SOURCES,
|
||||
@@ -38,7 +38,7 @@ use voelin_core::settings::{
|
||||
};
|
||||
use voelin_core::stream::{EndReason, StreamSetup, ViewerInfo, ViewerState};
|
||||
use voelin_core::studio::scene::{
|
||||
Align, Background, Colour, Fit, Scene, Scenes, Source, SourceKind, Transform,
|
||||
Align, Background, Colour, Crop, Fit, Scene, Scenes, Source, SourceKind, Transform,
|
||||
};
|
||||
use voelin_core::studio::{self, SourceChange, Stats, Status, Studio, camera};
|
||||
use voelin_core::{Command, HistoryMessage, HistorySource, StreamState};
|
||||
@@ -329,15 +329,16 @@ fn demo_settings() -> Settings {
|
||||
let mut cam = source(2, "Camera", camera.clone(), Transform::default());
|
||||
cam.transform = vm::studio::placement(&camera, (1920, 1080));
|
||||
cam.background = Background::Blur { strength: 0.04 };
|
||||
main.sources = vec![
|
||||
source(
|
||||
1,
|
||||
"Game Capture",
|
||||
SourceKind::Pattern { size: (1280, 720) },
|
||||
Transform { fit: Fit::Cover, ..Transform::full(1920, 1080) },
|
||||
),
|
||||
cam,
|
||||
];
|
||||
let mut game = source(
|
||||
1,
|
||||
"Game Capture",
|
||||
SourceKind::Pattern { size: (1280, 720) },
|
||||
Transform { fit: Fit::Cover, ..Transform::full(1920, 1080) },
|
||||
);
|
||||
// The pattern's frame counter sits in its top-left corner, under the
|
||||
// preview's LIVE badge and timer: cropped away.
|
||||
game.crop = Crop { top: 120, ..Crop::default() };
|
||||
main.sources = vec![game, cam];
|
||||
let mut chatting = Scene::new(2, "Just Chatting");
|
||||
chatting.sources = vec![source(
|
||||
1,
|
||||
@@ -420,8 +421,9 @@ fn file_name(what: &str) -> String {
|
||||
}
|
||||
|
||||
impl App {
|
||||
/// The studio's settings (made once).
|
||||
fn studio_settings(&mut self) -> Settings {
|
||||
/// The studio's settings (made once): its mixer's `stream.audio_sources`
|
||||
/// are the share dialog's too.
|
||||
pub(crate) fn studio_settings(&mut self) -> Settings {
|
||||
let demo = self.demo_ui;
|
||||
let prefs = &self.prefs;
|
||||
self.studio
|
||||
@@ -477,14 +479,19 @@ impl App {
|
||||
|| self.ui.upgrade().is_some_and(|ui| ui.global::<Nav>().get_page() == Page::Studio)
|
||||
}
|
||||
|
||||
/// The studio page or window appeared: show it and start the studio.
|
||||
pub(crate) fn studio_open(&mut self) {
|
||||
/// The models in the main window's StudioBridge (once).
|
||||
fn studio_attach_main(&mut self) {
|
||||
if !self.studio.attached
|
||||
&& let Some(ui) = self.ui.upgrade()
|
||||
{
|
||||
self.studio_attach(&ui.global::<StudioBridge>());
|
||||
self.studio.attached = true;
|
||||
}
|
||||
}
|
||||
|
||||
/// The studio page or window appeared: show it and start the studio.
|
||||
pub(crate) fn studio_open(&mut self) {
|
||||
self.studio_attach_main();
|
||||
if let Some(window) = &self.studio.window
|
||||
&& let Err(e) = window.show()
|
||||
{
|
||||
@@ -725,12 +732,23 @@ impl App {
|
||||
vm::list::sync(&m.sources, &vm::studio::sources(self.studio.scenes.active(), stats));
|
||||
}
|
||||
|
||||
/// The streamer whose mixer the audio rows show: a quick share's while
|
||||
/// one runs (what goes out; both mix `stream.audio_sources`), else the
|
||||
/// studio's encoder.
|
||||
fn mixer_streamer(&self) -> Option<&Streamer> {
|
||||
self.share_streamer().or_else(|| self.studio_streamer())
|
||||
}
|
||||
|
||||
/// What the mixer says about each of its sources now.
|
||||
fn mixer_stats(&self) -> Vec<AudioSourceStats> {
|
||||
self.mixer_streamer().map(|s| s.stats().audio_sources).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// The mixer source of each audio row, and why one captures nothing.
|
||||
fn studio_map_meters(&mut self) {
|
||||
let sources = self.studio.settings.as_ref().map(|s| s.get(&STREAM_AUDIO_SOURCES));
|
||||
let streamer = self.studio_streamer();
|
||||
let mixer = streamer.and_then(Streamer::audio_mixer);
|
||||
let stats = self.studio.encoder.as_ref().map(|s| &s.audio_sources[..]).unwrap_or_default();
|
||||
let mixer = self.mixer_streamer().and_then(Streamer::audio_mixer);
|
||||
let stats = self.mixer_stats();
|
||||
self.studio.meters = sources
|
||||
.unwrap_or_default()
|
||||
.iter()
|
||||
@@ -745,7 +763,7 @@ impl App {
|
||||
fn studio_refresh_audio(&self) {
|
||||
let Some(settings) = &self.studio.settings else { return };
|
||||
let sources = settings.get(&STREAM_AUDIO_SOURCES);
|
||||
let stats = self.studio.encoder.as_ref().map(|s| &s.audio_sources[..]).unwrap_or_default();
|
||||
let stats = self.mixer_stats();
|
||||
let live: Vec<Option<vm::studio::AudioLive>> = sources
|
||||
.iter()
|
||||
.enumerate()
|
||||
@@ -760,8 +778,38 @@ impl App {
|
||||
vm::list::sync(&self.studio.models.audio, &vm::studio::audio(&sources, &live));
|
||||
}
|
||||
|
||||
/// The share dialog's audio: the studio's mixer rows and picker in the
|
||||
/// main window, without starting the studio.
|
||||
pub(crate) fn mixer_show(&mut self) {
|
||||
self.studio_attach_main();
|
||||
self.studio_settings();
|
||||
self.mixer_refresh();
|
||||
}
|
||||
|
||||
/// The audio rows again: which mixer source each meter reads, levels
|
||||
/// and errors.
|
||||
pub(crate) fn mixer_refresh(&mut self) {
|
||||
self.studio_map_meters();
|
||||
self.studio_refresh_audio();
|
||||
}
|
||||
|
||||
/// Once a second while the studio does not run (it has its own tick):
|
||||
/// the share's rows, and the picker's application list let go once the
|
||||
/// share dialog is closed.
|
||||
pub(crate) fn mixer_tick(&mut self) {
|
||||
if self.studio.run.is_some() {
|
||||
return;
|
||||
}
|
||||
if self.share.is_some() {
|
||||
self.mixer_refresh();
|
||||
}
|
||||
if !self.ui.upgrade().is_some_and(|ui| ui.global::<Nav>().get_share_open()) {
|
||||
self.studio.apps = None;
|
||||
}
|
||||
}
|
||||
|
||||
/// The meters, about 15 times a second (only rows that moved redraw).
|
||||
fn studio_meters(&mut self) {
|
||||
pub(crate) fn studio_meters(&mut self) {
|
||||
let model = &self.studio.models.audio;
|
||||
for (i, meter) in self.studio.meters.iter().enumerate() {
|
||||
let level = meter.as_ref().map_or(-100.0, |m| m.level().peak_db().max(-100.0));
|
||||
@@ -830,7 +878,12 @@ impl App {
|
||||
.iter()
|
||||
.map(|(id, _)| {
|
||||
let (channel, server) = self.studio_destination_parts(*id);
|
||||
StudioPick { name: channel.into(), detail: server.into(), kind: "server".into() }
|
||||
StudioPick {
|
||||
name: channel.into(),
|
||||
detail: server.into(),
|
||||
kind: "server".into(),
|
||||
..Default::default()
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
vm::list::sync(&self.studio.models.destinations, &rows);
|
||||
@@ -1363,6 +1416,35 @@ impl App {
|
||||
"remove" => {
|
||||
self.studio_op(Op::Apply(studio::Command::RemoveSource { scene, source: id }));
|
||||
}
|
||||
// The next camera (a phone's front and back), mirrored as that
|
||||
// camera is by default.
|
||||
"next-camera" => {
|
||||
let SourceKind::Camera { device, size, fps, .. } = source.kind.clone() else {
|
||||
return;
|
||||
};
|
||||
let name = source.name.clone();
|
||||
let cameras = if self.demo_ui { Vec::new() } else { camera::list() };
|
||||
let real: Vec<_> = cameras.iter().filter(|c| c.backend != "synthetic").collect();
|
||||
let at = real.iter().position(|c| c.id == device);
|
||||
let next = at.map_or(real.first(), |i| real.get((i + 1) % real.len()));
|
||||
let Some(next) = next.filter(|c| c.id != device) else {
|
||||
self.set_status("There is no other camera.");
|
||||
return;
|
||||
};
|
||||
let kind = SourceKind::Camera {
|
||||
device: next.id.clone(),
|
||||
size,
|
||||
fps,
|
||||
mirror: next.mirrored,
|
||||
};
|
||||
// A source named after its camera is named after the next.
|
||||
let renamed = name.is_empty() || at.is_some_and(|i| real[i].name == name);
|
||||
let name = renamed.then(|| next.name.clone());
|
||||
self.studio_update(
|
||||
id,
|
||||
SourceChange { kind: Some(kind), name, ..Default::default() },
|
||||
);
|
||||
}
|
||||
"bg-keep" | "bg-blur" => {
|
||||
let background = if action == "bg-blur" {
|
||||
Background::Blur { strength: 0.04 }
|
||||
@@ -1423,6 +1505,7 @@ impl App {
|
||||
name: name.into(),
|
||||
detail: detail.into(),
|
||||
kind: icon.into(),
|
||||
..Default::default()
|
||||
};
|
||||
let mut picks: Vec<(Pick, StudioPick)> = Vec::new();
|
||||
let source = |name: &str, kind: SourceKind| Pick::Source { name: name.into(), kind };
|
||||
@@ -1434,6 +1517,7 @@ impl App {
|
||||
camera::SYNTHETIC.to_owned(),
|
||||
"Test pattern".to_owned(),
|
||||
"1280×720".to_owned(),
|
||||
true,
|
||||
)]
|
||||
} else {
|
||||
camera::list()
|
||||
@@ -1443,12 +1527,12 @@ impl App {
|
||||
c.formats.iter().flat_map(|f| &f.sizes).max_by_key(|(w, h)| w * h);
|
||||
let detail =
|
||||
biggest.map_or(String::new(), |(w, h)| format!("up to {w}×{h}"));
|
||||
(c.id, c.name, detail)
|
||||
(c.id, c.name, detail, c.mirrored)
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
for (device, name, detail) in cameras {
|
||||
let kind = SourceKind::Camera { device, size: None, fps: None, mirror: true };
|
||||
for (device, name, detail, mirror) in cameras {
|
||||
let kind = SourceKind::Camera { device, size: None, fps: None, mirror };
|
||||
picks.push((source(&name, kind), row(&name, detail, "camera")));
|
||||
}
|
||||
}
|
||||
@@ -1580,11 +1664,24 @@ impl App {
|
||||
let settings = self.studio_settings();
|
||||
let current = settings.get(&STREAM_AUDIO_SOURCES);
|
||||
let mut picks: Vec<(Pick, StudioPick)> = Vec::new();
|
||||
let mut add = |setting: AudioSourceSetting, name: String, detail: String| {
|
||||
let (_, _, kind) = vm::studio::audio_label(&setting.kind);
|
||||
let row = StudioPick { name: name.into(), detail: detail.into(), kind: kind.into() };
|
||||
picks.push((Pick::Audio(setting), row));
|
||||
};
|
||||
let mut add =
|
||||
|setting: AudioSourceSetting, name: String, detail: String, icon: Option<&str>| {
|
||||
let (_, _, kind) = vm::studio::audio_label(&setting.kind);
|
||||
let row = StudioPick {
|
||||
name: name.into(),
|
||||
detail: detail.into(),
|
||||
kind: kind.into(),
|
||||
// An application's own icon, when it gave a file (Android
|
||||
// does; a desktop icon theme name is left out).
|
||||
icon: icon
|
||||
.map(Path::new)
|
||||
.filter(|p| p.is_absolute())
|
||||
.map(crate::images::file)
|
||||
.unwrap_or_default(),
|
||||
selected: current.iter().any(|s| s.kind == setting.kind),
|
||||
};
|
||||
picks.push((Pick::Audio(setting), row));
|
||||
};
|
||||
let fixed = [
|
||||
(AudioSourceKindSetting::Microphone, "Microphone", "What you say in voice, cleaned up"),
|
||||
(
|
||||
@@ -1599,14 +1696,17 @@ impl App {
|
||||
),
|
||||
];
|
||||
for (kind, name, detail) in fixed {
|
||||
if !current.iter().any(|s| s.kind == kind) {
|
||||
add(AudioSourceSetting::new(kind), name.into(), detail.into());
|
||||
// A phone shares the whole screen: there is no window's app.
|
||||
if cfg!(target_os = "android") && kind == AudioSourceKindSetting::Window {
|
||||
continue;
|
||||
}
|
||||
add(AudioSourceSetting::new(kind), name.into(), detail.into(), None);
|
||||
}
|
||||
if self.demo_ui {
|
||||
for frequency in [330, 550] {
|
||||
for frequency in [440, 660, 330] {
|
||||
let kind = AudioSourceKindSetting::Synthetic { frequency };
|
||||
add(AudioSourceSetting::new(kind), "Test tone".into(), format!("{frequency} Hz"));
|
||||
let detail = format!("{frequency} Hz");
|
||||
add(AudioSourceSetting::new(kind), "Test tone".into(), detail, None);
|
||||
}
|
||||
} else {
|
||||
if self.studio.apps.is_none() {
|
||||
@@ -1623,7 +1723,7 @@ impl App {
|
||||
.media
|
||||
.clone()
|
||||
.unwrap_or_else(|| if app.playing { "playing".into() } else { String::new() });
|
||||
add(AudioSourceSetting::new(kind), app.name, detail);
|
||||
add(AudioSourceSetting::new(kind), app.name, detail, app.icon.as_deref());
|
||||
}
|
||||
}
|
||||
self.studio_set_picks(picks);
|
||||
@@ -1636,13 +1736,24 @@ impl App {
|
||||
if let Err(e) = settings.set(&STREAM_AUDIO_SOURCES, sources) {
|
||||
self.set_status(e.to_string());
|
||||
}
|
||||
// A quick share follows at once (the studio through its watch).
|
||||
self.share_audio_changed();
|
||||
self.studio_refresh_audio();
|
||||
}
|
||||
|
||||
pub(crate) fn studio_add_audio(&mut self, index: usize) {
|
||||
/// Mix a picked source in, or take it out if it is (the picker
|
||||
/// chooses several at once), and mark the picks again.
|
||||
pub(crate) fn studio_toggle_audio(&mut self, index: usize) {
|
||||
let Some(Pick::Audio(setting)) = self.studio.picks.get(index) else { return };
|
||||
let setting = setting.clone();
|
||||
self.studio_audio_sources(|sources| sources.push(setting));
|
||||
self.studio_audio_sources(|sources| {
|
||||
if sources.iter().any(|s| s.kind == setting.kind) {
|
||||
sources.retain(|s| s.kind != setting.kind);
|
||||
} else {
|
||||
sources.push(setting);
|
||||
}
|
||||
});
|
||||
self.studio_list_audio();
|
||||
}
|
||||
|
||||
/// While dragging the gain goes to the mixer directly; at the end it is
|
||||
|
||||
@@ -14,7 +14,7 @@ use voelin_core::media::voelin_media::capture::{CaptureSource, SourceId};
|
||||
use voelin_core::media::voelin_media::{Codec, Codecs, EncoderReport, VideoFrame, convert};
|
||||
use voelin_core::media::{
|
||||
self, AudioSourceSpec, EncoderPreference, Latest, LocalPreview, Streamer, StreamerConfig,
|
||||
Viewer, peer_config, preferred_codec, stream_codec,
|
||||
StreamerConfigUpdate, Viewer, peer_config, preferred_codec, stream_codec,
|
||||
};
|
||||
use voelin_core::stream::{LayerSpec, PeerConfig};
|
||||
use voelin_core::studio::Studio;
|
||||
@@ -426,6 +426,28 @@ impl Capture {
|
||||
self.streamer.audio_error()
|
||||
}
|
||||
|
||||
/// For the audio mixer's rows: its levels and errors.
|
||||
pub fn streamer(&self) -> &Streamer {
|
||||
&self.streamer
|
||||
}
|
||||
|
||||
/// Mix `sources` from now on (`stream.audio_sources` changed while
|
||||
/// sharing): a source whose kind stays keeps capturing with the new
|
||||
/// gain and mute, new ones start, removed ones stop. True if anything
|
||||
/// changed. A capture without sound stays so: its stream has no audio
|
||||
/// track to carry them.
|
||||
pub fn follow_audio(
|
||||
&self,
|
||||
codecs: &Codecs,
|
||||
sources: Vec<AudioSourceSpec>,
|
||||
) -> Result<bool, String> {
|
||||
if !self.has_audio() || self.streamer.audio_sources() == sources {
|
||||
return Ok(false);
|
||||
}
|
||||
let update = StreamerConfigUpdate { audio_sources: Some(sources), ..Default::default() };
|
||||
self.streamer.reconfigure(codecs, update).map(|()| true).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
/// The portal's token for this choice, to keep.
|
||||
pub fn restore_token(&self) -> Option<String> {
|
||||
self.streamer.restore_token().map(str::to_owned)
|
||||
@@ -528,4 +550,41 @@ mod tests {
|
||||
let restore: Vec<_> = entries.iter().map(|e| e.2).collect();
|
||||
assert_eq!(restore, [false, true]);
|
||||
}
|
||||
|
||||
/// A running share mixes what `stream.audio_sources` says now; one
|
||||
/// started without sound has no audio track to change.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_share_follows_its_audio_sources() {
|
||||
use voelin_core::media::AudioSourceKind;
|
||||
let codecs = Codecs::new();
|
||||
let tone = |hz| AudioSourceSpec::new(AudioSourceKind::Synthetic { hz });
|
||||
let start = async |audio| {
|
||||
let config = StreamerConfig {
|
||||
source: SourceId::Synthetic,
|
||||
synthetic_size: (64, 48),
|
||||
audio,
|
||||
audio_sources: vec![tone(440)],
|
||||
..StreamerConfig::default()
|
||||
};
|
||||
let streamer = Streamer::start(&codecs, config).await.unwrap();
|
||||
Capture { streamer, name: "Test pattern".into() }
|
||||
};
|
||||
let share = start(true).await;
|
||||
let mixed = vec![
|
||||
AudioSourceSpec { muted: true, ..tone(440) },
|
||||
AudioSourceSpec { gain: 0.5, ..tone(660) },
|
||||
];
|
||||
assert_eq!(share.follow_audio(&codecs, mixed.clone()), Ok(true));
|
||||
assert_eq!(share.streamer().audio_sources(), mixed);
|
||||
assert_eq!(share.follow_audio(&codecs, mixed), Ok(false), "nothing changed");
|
||||
// Every source taken out: silence, the track stays for new ones.
|
||||
assert_eq!(share.follow_audio(&codecs, Vec::new()), Ok(true));
|
||||
assert!(share.has_audio() && share.streamer().audio_sources().is_empty());
|
||||
assert_eq!(share.follow_audio(&codecs, vec![tone(330)]), Ok(true));
|
||||
assert_eq!(share.streamer().audio_sources(), [tone(330)]);
|
||||
|
||||
let silent = start(false).await;
|
||||
assert_eq!(silent.follow_audio(&codecs, vec![tone(660)]), Ok(false));
|
||||
assert!(!silent.has_audio());
|
||||
}
|
||||
}
|
||||
@@ -99,6 +99,29 @@ fn without_links(text: &str, files: &[FileRef]) -> String {
|
||||
out.replace("[/URL]", "").replace("[/url]", "").trim().to_owned()
|
||||
}
|
||||
|
||||
/// A chat's last message for a list of chats, on one line ("Mira: the
|
||||
/// banner I promised: guild-banner.png"), and when it came.
|
||||
pub fn preview(message: &ChatMessage) -> (String, String) {
|
||||
let text = if message.blocked {
|
||||
"Message from a blocked contact.".to_owned()
|
||||
} else {
|
||||
let files = message.file_refs();
|
||||
let names = files.iter().map(|f| f.name.as_str());
|
||||
let text = without_links(&message.text, &files);
|
||||
std::iter::once(text.as_str()).chain(names).collect::<Vec<_>>().join(" ")
|
||||
};
|
||||
// A one-line text cannot show emoji (they are pictures): left out.
|
||||
let plain = match emoji::runs(&text) {
|
||||
Some(runs) => runs.into_iter().filter(|r| r.emoji.is_none()).map(|r| r.text).collect(),
|
||||
None => text,
|
||||
};
|
||||
let mut text = plain.split_whitespace().collect::<Vec<_>>().join(" ");
|
||||
if text.is_empty() {
|
||||
text = "sent an emoji".into();
|
||||
}
|
||||
(format!("{}: {text}", message.author_name), time_of(message.ts_ms))
|
||||
}
|
||||
|
||||
fn runs_model(runs: &[emoji::Run]) -> ModelRc<TextRun> {
|
||||
ModelRc::from(Rc::new(VecModel::from(
|
||||
runs.iter()
|
||||
@@ -289,6 +312,23 @@ mod tests {
|
||||
assert!(line.text.starts_with("here you go"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn previews_are_one_line() {
|
||||
let url = "ts3file://plan.pdf?channel=2&path=/&filename=plan.pdf&isDir=0&size=2048";
|
||||
let text = format!("route\nfor tonight: [URL={url}]plan.pdf[/URL]");
|
||||
let (last, time) = preview(&message("Mira", &text, 0));
|
||||
assert_eq!(last, "Mira: route for tonight: plan.pdf");
|
||||
assert!(!time.is_empty());
|
||||
assert_eq!(
|
||||
preview(&message("Ari", "co-op later? 👀 Posting", 0)).0,
|
||||
"Ari: co-op later? Posting"
|
||||
);
|
||||
assert_eq!(preview(&message("dex", "🎉🎉", 0)).0, "dex: sent an emoji");
|
||||
let mut blocked = message("X", "secret", 0);
|
||||
blocked.blocked = true;
|
||||
assert_eq!(preview(&blocked).0, "X: Message from a blocked contact.");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stamps() {
|
||||
let at = |d: &str| chrono::NaiveDateTime::parse_from_str(d, "%Y-%m-%d %H:%M").unwrap();
|
||||
|
||||
@@ -17,7 +17,7 @@ pub fn status(state: &SessionState) -> &'static str {
|
||||
}
|
||||
|
||||
/// A server of the rail. `unread`: messages in its chats; `live`:
|
||||
/// streams in our channel there.
|
||||
/// streams on it.
|
||||
pub fn item(bookmark: &Bookmark, state: &SessionState, unread: i32, live: bool) -> ServerItem {
|
||||
ServerItem {
|
||||
id: bookmark.id as i32,
|
||||
@@ -31,10 +31,69 @@ pub fn item(bookmark: &Bookmark, state: &SessionState, unread: i32, live: bool)
|
||||
}
|
||||
}
|
||||
|
||||
/// A `ts3server://` link that joins the channel at `path` (its names from
|
||||
/// the top) on the server at `address` (`host`, `host:port` or
|
||||
/// `[v6]:port`), as TeamSpeak clients open them.
|
||||
pub fn invite_link(address: &str, path: &[&str]) -> String {
|
||||
fn encode(text: &str) -> String {
|
||||
text.bytes()
|
||||
.map(|b| match b {
|
||||
b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' | b'_' | b'~' => {
|
||||
char::from(b).to_string()
|
||||
}
|
||||
_ => format!("%{b:02X}"),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
let address = address.trim();
|
||||
// A port follows the last colon, unless that colon is inside an IPv6
|
||||
// address without brackets.
|
||||
let (host, port) = match address.rsplit_once(':') {
|
||||
Some((host, port))
|
||||
if !port.is_empty()
|
||||
&& port.bytes().all(|b| b.is_ascii_digit())
|
||||
&& (!host.contains(':') || host.ends_with(']')) =>
|
||||
{
|
||||
(host, Some(port))
|
||||
}
|
||||
_ => (address, None),
|
||||
};
|
||||
let mut link = format!("ts3server://{host}");
|
||||
let mut query = Vec::new();
|
||||
if let Some(port) = port {
|
||||
query.push(format!("port={port}"));
|
||||
}
|
||||
if !path.is_empty() {
|
||||
let names: Vec<String> = path.iter().map(|n| encode(n)).collect();
|
||||
query.push(format!("channel={}", names.join("/")));
|
||||
}
|
||||
if !query.is_empty() {
|
||||
link.push('?');
|
||||
link.push_str(&query.join("&"));
|
||||
}
|
||||
link
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn invite_links() {
|
||||
assert_eq!(
|
||||
invite_link("ts.example.com:9988", &["Gaming", "Raid Night"]),
|
||||
"ts3server://ts.example.com?port=9988&channel=Gaming/Raid%20Night"
|
||||
);
|
||||
assert_eq!(invite_link(" ts.example.com ", &[]), "ts3server://ts.example.com");
|
||||
assert_eq!(
|
||||
invite_link("[2001:db8::1]:9987", &["Chill & Co"]),
|
||||
"ts3server://[2001:db8::1]?port=9987&channel=Chill%20%26%20Co"
|
||||
);
|
||||
// A bare IPv6 address has no port.
|
||||
assert_eq!(invite_link("2001:db8::1", &[]), "ts3server://2001:db8::1");
|
||||
assert_eq!(invite_link("h:x", &["Ä/b"]), "ts3server://h:x?channel=%C3%84%2Fb");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn states() {
|
||||
let mut s = SessionState::default();
|
||||
|
||||
@@ -25,7 +25,8 @@ import { VoiceView } from "screens/voice.slint";
|
||||
import { StreamViewer } from "screens/streams.slint";
|
||||
import { SettingsNav, SettingsPage } from "screens/settings.slint";
|
||||
import { HomeNav, HomePage } from "screens/home.slint";
|
||||
import { MobileServers, ActivityPage, YouPage } from "screens/mobile.slint";
|
||||
import { MobileServers, ActivityPage, YouPage, PhoneSheet } from "screens/mobile.slint";
|
||||
import { MobileVoice } from "screens/mobile-voice.slint";
|
||||
import { BookmarkDialog, ShareDialog, ClientAudioDialog, AboutDialog } from "screens/dialogs.slint";
|
||||
import { StudioBridge } from "studio-bridge.slint";
|
||||
import { StudioPage, MobileStudio } from "screens/studio.slint";
|
||||
@@ -171,26 +172,38 @@ export component MainWindow inherits Window {
|
||||
|
||||
if Nav.narrow && root.chrome: MobileShell {
|
||||
title: Nav.page == Page.settings ? @tr("Settings")
|
||||
: Nav.phone-voice ? Bridge.app-name
|
||||
: Nav.mobile-tab == MobileTab.home ? Bridge.app-name
|
||||
: Nav.mobile-tab == MobileTab.you ? @tr("You")
|
||||
: Nav.mobile-tab == MobileTab.activity ? @tr("Activity")
|
||||
: Bridge.server-title;
|
||||
subtitle: Nav.page == Page.settings ? "" : Nav.mobile-tab == MobileTab.chat && Bridge.current-tab >= 0 && Bridge.current-tab < Bridge.tabs.length ? Bridge.tabs[Bridge.current-tab].title : Nav.mobile-tab == MobileTab.servers ? Bridge.server-stats : "";
|
||||
subtitle: Nav.page == Page.settings ? ""
|
||||
: Nav.phone-voice ? Bridge.server-title
|
||||
: Nav.mobile-tab == MobileTab.chat && Bridge.current-tab >= 0 && Bridge.current-tab < Bridge.tabs.length ? Bridge.tabs[Bridge.current-tab].title
|
||||
: Nav.mobile-tab == MobileTab.servers ? Bridge.server-stats
|
||||
: Nav.page == Page.home || Nav.mobile-tab == MobileTab.home ? @tr("Talk. Watch. Share.") : "";
|
||||
back: Nav.page == Page.settings;
|
||||
unread: Bridge.unread-total;
|
||||
voice: Nav.phone-voice;
|
||||
// The voice channel and the studio bring their own controls.
|
||||
navigation: !Nav.phone-voice && Nav.page != Page.studio;
|
||||
go-back => { Nav.show(Page.server); }
|
||||
if Nav.page == Page.settings: SettingsPage {
|
||||
compact: true;
|
||||
}
|
||||
if Nav.page != Page.settings && Nav.page != Page.studio && (Nav.page == Page.home || Nav.mobile-tab == MobileTab.home): HomePage { }
|
||||
if Nav.page == Page.server && Nav.mobile-tab == MobileTab.servers: MobileServers { }
|
||||
if Nav.page == Page.server && Nav.mobile-tab == MobileTab.chat && Bridge.viewer-open: StreamViewer { }
|
||||
if Nav.page == Page.server && Nav.mobile-tab == MobileTab.chat && !Bridge.viewer-open: ChatView {
|
||||
if Nav.page != Page.settings && Nav.page != Page.studio && !Nav.phone-voice && (Nav.page == Page.home || Nav.mobile-tab == MobileTab.home): HomePage { }
|
||||
if Nav.phone-voice: MobileVoice { }
|
||||
if Nav.page == Page.server && !Nav.phone-voice && Nav.mobile-tab == MobileTab.servers: MobileServers { }
|
||||
// Watching without voice (the local test stream): the player.
|
||||
if Nav.page == Page.server && !Nav.phone-voice && Nav.mobile-tab == MobileTab.chat && Bridge.viewer-open: StreamViewer { }
|
||||
if Nav.page == Page.server && !Nav.phone-voice && Nav.mobile-tab == MobileTab.chat && !Bridge.viewer-open: ChatView {
|
||||
header: false;
|
||||
}
|
||||
if Nav.page == Page.server && Nav.mobile-tab == MobileTab.activity: ActivityPage { }
|
||||
if Nav.page == Page.server && Nav.mobile-tab == MobileTab.you: YouPage { }
|
||||
if Nav.page == Page.server && !Nav.phone-voice && Nav.mobile-tab == MobileTab.activity: ActivityPage { }
|
||||
if Nav.page == Page.server && !Nav.phone-voice && Nav.mobile-tab == MobileTab.you: YouPage { }
|
||||
if Nav.page == Page.studio && !StudioBridge.status.detached: MobileStudio { }
|
||||
// Pins, topics or the members, over the page.
|
||||
if Nav.page == Page.server && (Nav.pins-open || Nav.topics-open || Nav.members-open): PhoneSheet { }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -118,6 +118,9 @@ export struct ChatTab {
|
||||
unread: int,
|
||||
// The channel's topic (channel chats).
|
||||
topic: string,
|
||||
// The last message ("Mira: the banner I promised") and its time.
|
||||
last: string,
|
||||
time: string,
|
||||
}
|
||||
|
||||
// A piece of a chat line: text, or an emoji shown as an image (`emoji` is
|
||||
@@ -377,6 +380,8 @@ export global Bridge {
|
||||
in property <[SourceItem]> share-sources;
|
||||
in property <string> share-error;
|
||||
in property <bool> share-busy;
|
||||
// Our share carries sound: its audio mixer can change it.
|
||||
in property <bool> share-audio;
|
||||
// Whether capture and encoding are built in.
|
||||
in property <bool> can-share: true;
|
||||
|
||||
@@ -406,6 +411,8 @@ export global Bridge {
|
||||
in-out property <int> viewer-quality: 0;
|
||||
// What "Auto" picked ("720p · 2.4 Mbit/s").
|
||||
in property <string> viewer-quality-detail;
|
||||
// The streamer is in an admin group (the crown beside their name).
|
||||
in property <bool> viewer-streamer-admin;
|
||||
|
||||
// Settings.
|
||||
in property <[string]> input-devices;
|
||||
@@ -513,6 +520,9 @@ export global Bridge {
|
||||
callback delete-crash-reports();
|
||||
callback dismiss-crash-notice();
|
||||
callback open-about();
|
||||
// A link to our voice channel (`ts3server://`) to hand to others; the
|
||||
// caller copies it.
|
||||
callback invite() -> string;
|
||||
}
|
||||
|
||||
// Decoded images by key, from Rust's image cache (src/images.rs): each is
|
||||
|
||||
@@ -69,6 +69,14 @@ export global Nav {
|
||||
in-out property <BookmarkForm> bookmark-form;
|
||||
in-out property <ShareForm> share-form;
|
||||
|
||||
// The phone layout (narrow windows).
|
||||
// The server's members as a page of their own (the desktop shows them
|
||||
// beside the chat).
|
||||
in-out property <bool> members-open;
|
||||
// The voice channel screen (design mockup 02) instead of a tab: the
|
||||
// voice channel view, or a stream we watch.
|
||||
out property <bool> phone-voice: narrow && page == Page.server && Bridge.voice-connected && (voice-view || Bridge.viewer-open);
|
||||
|
||||
// Settings were opened (so leaving them tells Rust).
|
||||
property <bool> settings-active;
|
||||
|
||||
@@ -77,9 +85,28 @@ export global Nav {
|
||||
settings-active = false;
|
||||
Bridge.close-settings();
|
||||
}
|
||||
// The phone shows Home on its own tab: a server goes to Servers,
|
||||
// and Home from anywhere (the desktop's logo, a switch) is that tab.
|
||||
// Also while wide, so the tab is right when the window narrows.
|
||||
if p == Page.server && mobile-tab == MobileTab.home {
|
||||
mobile-tab = MobileTab.servers;
|
||||
}
|
||||
if p == Page.home {
|
||||
mobile-tab = MobileTab.home;
|
||||
}
|
||||
page = p;
|
||||
}
|
||||
|
||||
// A tab of the phone's bottom navigation, without the pages that were
|
||||
// over the last one (pins, topics, members).
|
||||
public function show-tab(tab: MobileTab) {
|
||||
pins-open = false;
|
||||
topics-open = false;
|
||||
members-open = false;
|
||||
show(tab == MobileTab.home ? Page.home : Page.server);
|
||||
mobile-tab = tab;
|
||||
}
|
||||
|
||||
public function open-settings(section: SettingsSection) {
|
||||
if !settings-active {
|
||||
settings-active = true;
|
||||
|
||||
@@ -6,6 +6,8 @@ import { Bridge, BookmarkForm, ShareForm } from "../bridge.slint";
|
||||
import { Nav } from "../nav.slint";
|
||||
import { Icon, Button, ButtonKind, IconButton, TextField, Field, Select, Toggle, ToggleRow, Slider, Modal, Card, Chip, Banner, Avatar, Status, ListView, ScrollView } from "../components/index.slint";
|
||||
import { AboutSlint } from "std-widgets.slint";
|
||||
import { StudioBridge } from "../studio-bridge.slint";
|
||||
import { MixerRow, PickDialog } from "studio-parts.slint";
|
||||
|
||||
// Buttons at the bottom right of a dialog.
|
||||
component Footer inherits HorizontalLayout {
|
||||
@@ -175,15 +177,57 @@ component SourceCard inherits Rectangle {
|
||||
}
|
||||
}
|
||||
|
||||
export component ShareDialog inherits Modal {
|
||||
// The stream's audio: the Stream Studio's mixer rows (`stream.audio_sources`,
|
||||
// levels while live) and Add, which opens its picker.
|
||||
component ShareAudio inherits VerticalLayout {
|
||||
callback add();
|
||||
spacing: Theme.space-1;
|
||||
HorizontalLayout {
|
||||
spacing: Theme.space-2;
|
||||
Text {
|
||||
text: @tr("Audio sources");
|
||||
color: Theme.text-secondary;
|
||||
font-size: Theme.font-sm;
|
||||
font-weight: Theme.weight-semibold;
|
||||
vertical-alignment: center;
|
||||
horizontal-stretch: 1;
|
||||
}
|
||||
Button {
|
||||
small: true;
|
||||
icon: Icons.plus;
|
||||
text: @tr("Add");
|
||||
clicked => { root.add(); }
|
||||
}
|
||||
}
|
||||
if StudioBridge.audio.length == 0: Text {
|
||||
text: @tr("No audio: add your microphone, the desktop or an application.");
|
||||
color: Theme.text-muted;
|
||||
font-size: Theme.font-sm;
|
||||
wrap: word-wrap;
|
||||
}
|
||||
// Three rows at a time.
|
||||
if StudioBridge.audio.length > 0: ListView {
|
||||
height: min(StudioBridge.audio.length, 3) * 56px;
|
||||
accessible-label: @tr("Audio sources");
|
||||
for audio[i] in StudioBridge.audio: MixerRow {
|
||||
audio: audio;
|
||||
index: i;
|
||||
compact: true;
|
||||
phone: Nav.narrow;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
component ShareCard inherits Modal {
|
||||
in-out property <ShareForm> form;
|
||||
callback done();
|
||||
callback pick-audio();
|
||||
property <bool> live: Bridge.share-state == "live" || Bridge.share-state == "starting";
|
||||
title: Bridge.share-state == "live" ? @tr("You are sharing your screen") : Bridge.share-state == "starting" ? @tr("Starting…") : @tr("Share screen");
|
||||
subtitle: live ? Bridge.share-status : @tr("Stream to the people in your channel.");
|
||||
icon: Icons.radio;
|
||||
card-width: 600px;
|
||||
card-height: 660px;
|
||||
card-height: 860px;
|
||||
dismissed => { done(); }
|
||||
|
||||
if live: VerticalLayout {
|
||||
@@ -257,6 +301,15 @@ export component ShareDialog inherits Modal {
|
||||
}
|
||||
}
|
||||
}
|
||||
// Changes apply to the stream at once.
|
||||
if Bridge.share-audio: ShareAudio {
|
||||
add => { root.pick-audio(); }
|
||||
}
|
||||
if !Bridge.share-audio: Text {
|
||||
text: @tr("This stream has no sound.");
|
||||
color: Theme.text-muted;
|
||||
font-size: Theme.font-sm;
|
||||
}
|
||||
Footer {
|
||||
Button {
|
||||
text: @tr("Close");
|
||||
@@ -313,7 +366,8 @@ export component ShareDialog inherits Modal {
|
||||
input-type: number;
|
||||
placeholder: @tr("fps");
|
||||
label: @tr("Frames per second");
|
||||
width: 80px;
|
||||
// On a phone both pairs fit side by side.
|
||||
width: Nav.narrow ? 60px : 80px;
|
||||
horizontal-stretch: 0;
|
||||
}
|
||||
}
|
||||
@@ -333,17 +387,22 @@ export component ShareDialog inherits Modal {
|
||||
input-type: number;
|
||||
placeholder: @tr("kbit/s");
|
||||
label: @tr("Bitrate in kbit/s");
|
||||
width: 80px;
|
||||
// On a phone both pairs fit side by side.
|
||||
width: Nav.narrow ? 60px : 80px;
|
||||
horizontal-stretch: 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// Off: no audio at all.
|
||||
ToggleRow {
|
||||
text: @tr("Share system audio");
|
||||
icon: Icons.volume-2;
|
||||
checked <=> form.audio;
|
||||
}
|
||||
if form.audio: ShareAudio {
|
||||
add => { root.pick-audio(); }
|
||||
}
|
||||
ToggleRow {
|
||||
text: @tr("Let everyone in the channel watch without asking");
|
||||
icon: Icons.users;
|
||||
@@ -370,6 +429,30 @@ export component ShareDialog inherits Modal {
|
||||
}
|
||||
}
|
||||
|
||||
// Share the screen or a window, with the stream's audio; the studio's
|
||||
// audio picker opens over it.
|
||||
export component ShareDialog inherits Rectangle {
|
||||
in-out property <ShareForm> form;
|
||||
callback done();
|
||||
property <bool> picking;
|
||||
ShareCard {
|
||||
width: parent.width;
|
||||
height: parent.height;
|
||||
form <=> root.form;
|
||||
done => { root.done(); }
|
||||
pick-audio => {
|
||||
StudioBridge.list-audio();
|
||||
root.picking = true;
|
||||
}
|
||||
}
|
||||
if root.picking: PickDialog {
|
||||
width: parent.width;
|
||||
height: parent.height;
|
||||
kind: "audio";
|
||||
done => { root.picking = false; }
|
||||
}
|
||||
}
|
||||
|
||||
// Local volume and mute of one client.
|
||||
export component ClientAudioDialog inherits Modal {
|
||||
callback done();
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
// The home page: a welcome banner and the servers at a glance. Later
|
||||
// versions add friends, live rooms and activity here.
|
||||
// The home page: a welcome banner, who is online on the current server,
|
||||
// its chats with their last message, the servers, and the streams of our
|
||||
// channel (design mockups 01, desktop and phone).
|
||||
|
||||
import { Theme } from "../theme.slint";
|
||||
import { Icons } from "../icons.slint";
|
||||
import { Bridge, ServerItem } from "../bridge.slint";
|
||||
import { Nav, Page, SettingsSection } from "../nav.slint";
|
||||
import { Bridge, ServerItem, MemberItem, StreamItem, ChatTab } from "../bridge.slint";
|
||||
import { Nav, Page, MobileTab, SettingsSection } from "../nav.slint";
|
||||
import { Icon, Button, ButtonKind, Avatar, Status, Chip, SectionHeader, NavItem, Divider, CountBadge, LiveBadge, ScrollView } from "../components/index.slint";
|
||||
|
||||
// The sidebar next to the home page.
|
||||
@@ -125,16 +126,212 @@ component ServerCard inherits Rectangle {
|
||||
}
|
||||
}
|
||||
|
||||
// Someone on the current server (the "Online now" row); a tap opens their
|
||||
// card.
|
||||
component PersonChip inherits VerticalLayout {
|
||||
in property <MemberItem> member;
|
||||
width: 76px;
|
||||
spacing: Theme.space-1;
|
||||
accessible-role: AccessibleRole.list-item;
|
||||
accessible-label: member.name;
|
||||
accessible-description: member.status;
|
||||
accessible-action-default => { Bridge.open-member(member.id); }
|
||||
HorizontalLayout {
|
||||
alignment: center;
|
||||
Avatar {
|
||||
size: 56px;
|
||||
initials: member.initials;
|
||||
tint: member.tint;
|
||||
image: member.avatar;
|
||||
label: member.name;
|
||||
speaking: member.talking;
|
||||
crown: member.admin;
|
||||
status: member.away ? Status.idle : member.streaming ? Status.info : Status.online;
|
||||
TouchArea {
|
||||
mouse-cursor: MouseCursor.pointer;
|
||||
clicked => { Bridge.open-member(member.id); }
|
||||
}
|
||||
}
|
||||
}
|
||||
Text {
|
||||
text: member.name;
|
||||
color: Theme.text;
|
||||
font-size: Theme.font-sm;
|
||||
horizontal-alignment: center;
|
||||
overflow: elide;
|
||||
}
|
||||
Text {
|
||||
text: member.status;
|
||||
color: member.streaming ? Theme.live : Theme.text-muted;
|
||||
font-size: Theme.font-xs;
|
||||
horizontal-alignment: center;
|
||||
overflow: elide;
|
||||
}
|
||||
}
|
||||
|
||||
// A stream of our channel (the "Live now" row): LIVE, viewers, the title,
|
||||
// who; a tap watches it.
|
||||
component LiveCard inherits Rectangle {
|
||||
in property <StreamItem> stream;
|
||||
width: 224px;
|
||||
height: 136px;
|
||||
border-radius: Theme.radius-lg;
|
||||
clip: true;
|
||||
background: @linear-gradient(160deg, #26237a 0%, #0c1430 100%);
|
||||
border-width: 1px;
|
||||
border-color: stream.watching ? Theme.accent : area.has-hover ? Theme.border-strong : Theme.border;
|
||||
accessible-role: AccessibleRole.button;
|
||||
accessible-label: stream.name;
|
||||
accessible-action-default => { area.watch(); }
|
||||
area := TouchArea {
|
||||
mouse-cursor: MouseCursor.pointer;
|
||||
function watch() {
|
||||
if stream.id == "" || stream.own {
|
||||
return;
|
||||
}
|
||||
Nav.show(Page.server);
|
||||
if stream.watching {
|
||||
Bridge.show-viewer();
|
||||
} else {
|
||||
Bridge.watch-stream(stream.id);
|
||||
}
|
||||
}
|
||||
clicked => { self.watch(); }
|
||||
}
|
||||
Icon {
|
||||
source: stream.kind == "Camera" ? Icons.video : Icons.monitor-up;
|
||||
size: 56px;
|
||||
tint: #ffffff1c;
|
||||
}
|
||||
HorizontalLayout {
|
||||
x: Theme.space-3;
|
||||
y: Theme.space-3;
|
||||
height: 22px;
|
||||
spacing: Theme.space-2;
|
||||
LiveBadge {
|
||||
y: (parent.height - self.height) / 2;
|
||||
}
|
||||
if stream.viewers > 0: Chip {
|
||||
text: stream.viewers;
|
||||
icon: Icons.eye;
|
||||
tint: #ffffff;
|
||||
fill: #060a18a0;
|
||||
y: (parent.height - self.height) / 2;
|
||||
}
|
||||
}
|
||||
VerticalLayout {
|
||||
padding: Theme.space-3;
|
||||
alignment: end;
|
||||
spacing: 1px;
|
||||
Text {
|
||||
text: stream.id == "" ? @tr("{} is streaming", stream.streamer) : stream.name != "" ? stream.name : @tr("Untitled stream");
|
||||
color: #ffffff;
|
||||
font-weight: Theme.weight-semibold;
|
||||
overflow: elide;
|
||||
}
|
||||
Text {
|
||||
text: stream.channel != "" ? stream.streamer + " • " + stream.channel
|
||||
: stream.kind != "" ? stream.streamer + " • " + stream.kind : stream.streamer;
|
||||
color: #ffffffb0;
|
||||
font-size: Theme.font-sm;
|
||||
overflow: elide;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A chat of the current server with its last message ("Chats"); a tap
|
||||
// opens it.
|
||||
component ChatRow inherits Rectangle {
|
||||
in property <ChatTab> tab;
|
||||
in property <int> index;
|
||||
height: 60px;
|
||||
border-radius: Theme.radius-lg;
|
||||
background: area.has-hover ? Theme.surface-3 : Theme.surface-2;
|
||||
border-width: 1px;
|
||||
border-color: Theme.border;
|
||||
accessible-role: AccessibleRole.button;
|
||||
accessible-label: tab.title;
|
||||
accessible-description: tab.last;
|
||||
accessible-action-default => { area.open(); }
|
||||
area := TouchArea {
|
||||
mouse-cursor: MouseCursor.pointer;
|
||||
function open() {
|
||||
Bridge.select-tab(root.index);
|
||||
Nav.mobile-tab = MobileTab.chat;
|
||||
Nav.show(Page.server);
|
||||
}
|
||||
clicked => { self.open(); }
|
||||
}
|
||||
HorizontalLayout {
|
||||
padding-left: Theme.space-3;
|
||||
padding-right: Theme.space-3;
|
||||
spacing: Theme.space-3;
|
||||
Rectangle {
|
||||
width: 40px;
|
||||
height: 40px;
|
||||
y: (parent.height - self.height) / 2;
|
||||
border-radius: 20px;
|
||||
background: Theme.surface-4;
|
||||
Icon {
|
||||
source: tab.kind == 1 ? Icons.hash : tab.kind == 2 ? Icons.at-sign : Icons.message-square;
|
||||
size: Theme.icon-md;
|
||||
tint: Theme.accent-text;
|
||||
}
|
||||
}
|
||||
VerticalLayout {
|
||||
alignment: center;
|
||||
horizontal-stretch: 1;
|
||||
spacing: 1px;
|
||||
HorizontalLayout {
|
||||
spacing: Theme.space-3;
|
||||
Text {
|
||||
text: tab.title;
|
||||
color: Theme.name-text;
|
||||
font-weight: Theme.weight-semibold;
|
||||
overflow: elide;
|
||||
max-width: self.preferred-width;
|
||||
}
|
||||
Text {
|
||||
text: tab.time;
|
||||
color: Theme.text-muted;
|
||||
font-size: Theme.font-xs;
|
||||
vertical-alignment: center;
|
||||
horizontal-stretch: 1;
|
||||
}
|
||||
}
|
||||
Text {
|
||||
text: tab.last != "" ? tab.last : @tr("No messages yet");
|
||||
color: tab.last != "" ? Theme.text-secondary : Theme.text-muted;
|
||||
font-size: Theme.font-sm;
|
||||
overflow: elide;
|
||||
}
|
||||
}
|
||||
if tab.unread > 0: CountBadge {
|
||||
count: tab.unread;
|
||||
fill: Theme.accent;
|
||||
y: (parent.height - self.height) / 2;
|
||||
}
|
||||
Icon {
|
||||
source: Icons.chevron-right;
|
||||
size: Theme.icon-sm;
|
||||
tint: Theme.text-muted;
|
||||
y: (parent.height - self.height) / 2;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export component HomePage inherits Rectangle {
|
||||
sv := ScrollView {
|
||||
VerticalLayout {
|
||||
width: sv.visible-width;
|
||||
padding: Theme.space-6;
|
||||
spacing: Theme.space-6;
|
||||
padding: Nav.narrow ? Theme.space-4 : Theme.space-6;
|
||||
spacing: Nav.narrow ? Theme.space-5 : Theme.space-6;
|
||||
alignment: start;
|
||||
// Welcome banner.
|
||||
Rectangle {
|
||||
min-height: 220px;
|
||||
// Wrapped text is measured at an unknown width: room
|
||||
// for it on the phone.
|
||||
min-height: Nav.narrow ? 236px : 220px;
|
||||
border-radius: Theme.radius-xl;
|
||||
clip: true;
|
||||
background: @linear-gradient(115deg, #0e1d5c 0%, #1c1470 45%, #3a1f86 75%, #0b2a6b 100%);
|
||||
@@ -169,21 +366,21 @@ export component HomePage inherits Rectangle {
|
||||
background: #ffffffc0;
|
||||
}
|
||||
VerticalLayout {
|
||||
padding: Theme.space-7;
|
||||
padding: Nav.narrow ? Theme.space-5 : Theme.space-7;
|
||||
spacing: Theme.space-3;
|
||||
alignment: center;
|
||||
HorizontalLayout {
|
||||
spacing: Theme.space-4;
|
||||
alignment: start;
|
||||
Image {
|
||||
width: 52px;
|
||||
height: 52px;
|
||||
width: Nav.narrow ? 40px : 52px;
|
||||
height: self.width;
|
||||
source: Icons.logo;
|
||||
}
|
||||
Text {
|
||||
text: Bridge.app-name;
|
||||
color: #ffffff;
|
||||
font-size: 40px * Theme.font-scale;
|
||||
font-size: (Nav.narrow ? 30px : 40px) * Theme.font-scale;
|
||||
font-weight: Theme.weight-bold;
|
||||
vertical-alignment: center;
|
||||
}
|
||||
@@ -211,12 +408,57 @@ export component HomePage inherits Rectangle {
|
||||
}
|
||||
if Bridge.servers.length > 0: Button {
|
||||
icon: Icons.arrow-right;
|
||||
text: @tr("Open {}", Bridge.server-title);
|
||||
text: Nav.narrow ? @tr("Open") : @tr("Open {}", Bridge.server-title);
|
||||
clicked => { Nav.show(Page.server); }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// Who is on the current server.
|
||||
if Bridge.server-members.length > 0: SectionHeader {
|
||||
text: @tr("Online now");
|
||||
icon: Icons.users;
|
||||
count: Bridge.server-members.length;
|
||||
action: @tr("See All");
|
||||
action-clicked => {
|
||||
Nav.show(Page.server);
|
||||
if Nav.narrow {
|
||||
Nav.members-open = true;
|
||||
} else {
|
||||
Nav.right-panel-open = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
if Bridge.server-members.length > 0: ScrollView {
|
||||
height: 118px;
|
||||
HorizontalLayout {
|
||||
// Room for the crowns.
|
||||
padding-top: 6px;
|
||||
spacing: Theme.space-2;
|
||||
alignment: start;
|
||||
for member in Bridge.server-members: PersonChip {
|
||||
member: member;
|
||||
}
|
||||
}
|
||||
}
|
||||
// The current server's chats with their last message.
|
||||
if Bridge.current-server >= 0 && Bridge.tabs.length > 0: SectionHeader {
|
||||
text: @tr("Chats");
|
||||
icon: Icons.message-square;
|
||||
count: Bridge.unread-total > 0 ? Bridge.unread-total : "";
|
||||
action: @tr("See All");
|
||||
action-clicked => {
|
||||
Nav.mobile-tab = MobileTab.chat;
|
||||
Nav.show(Page.server);
|
||||
}
|
||||
}
|
||||
if Bridge.current-server >= 0: VerticalLayout {
|
||||
spacing: Theme.space-2;
|
||||
for tab[i] in Bridge.tabs: ChatRow {
|
||||
tab: tab;
|
||||
index: i;
|
||||
}
|
||||
}
|
||||
SectionHeader {
|
||||
text: @tr("Your servers");
|
||||
icon: Icons.server;
|
||||
@@ -228,13 +470,41 @@ export component HomePage inherits Rectangle {
|
||||
text: @tr("No servers yet. Add one with its address and your nickname.");
|
||||
color: Theme.text-muted;
|
||||
}
|
||||
FlexboxLayout {
|
||||
// The phone scrolls them sideways.
|
||||
if Nav.narrow && Bridge.servers.length > 0: ScrollView {
|
||||
height: 140px;
|
||||
HorizontalLayout {
|
||||
spacing: Theme.space-3;
|
||||
alignment: start;
|
||||
for server in Bridge.servers: ServerCard {
|
||||
width: 236px;
|
||||
server: server;
|
||||
}
|
||||
}
|
||||
}
|
||||
if !Nav.narrow: FlexboxLayout {
|
||||
spacing: Theme.space-4;
|
||||
alignment: stretch;
|
||||
for server in Bridge.servers: ServerCard {
|
||||
server: server;
|
||||
}
|
||||
}
|
||||
// The streams on the server, ours first.
|
||||
if Bridge.streams.length > 0: SectionHeader {
|
||||
text: @tr("Live now");
|
||||
icon: Icons.radio;
|
||||
count: Bridge.streams.length;
|
||||
}
|
||||
if Bridge.streams.length > 0: ScrollView {
|
||||
height: 140px;
|
||||
HorizontalLayout {
|
||||
spacing: Theme.space-3;
|
||||
alignment: start;
|
||||
for stream in Bridge.streams: LiveCard {
|
||||
stream: stream;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,713 @@
|
||||
// The voice channel on the phone (design mockup 02): the channel's name
|
||||
// and Leave, the stream we watch (or a card to watch one), the people in
|
||||
// the channel, the channel's chat, and the voice controls at the bottom in
|
||||
// place of the navigation.
|
||||
|
||||
import { Theme } from "../theme.slint";
|
||||
import { Icons } from "../icons.slint";
|
||||
import { Bridge, MemberItem, StreamItem } from "../bridge.slint";
|
||||
import { Nav, MobileTab } from "../nav.slint";
|
||||
import { Icon, IconButton, Button, ButtonKind, Avatar, LiveBadge, Select, Slider, SpeakingBars, ScrollView } from "../components/index.slint";
|
||||
import { MessageList, Composer } from "chat.slint";
|
||||
import { StudioBridge } from "../studio-bridge.slint";
|
||||
|
||||
// Back to the navigation; a stream we watch goes on behind it.
|
||||
export global PhoneVoice {
|
||||
public function close() {
|
||||
if Bridge.viewer-open {
|
||||
Bridge.hide-viewer();
|
||||
}
|
||||
Nav.show-voice(false);
|
||||
}
|
||||
}
|
||||
|
||||
// The channel's name and topic, back, and Leave.
|
||||
component ChannelBar inherits HorizontalLayout {
|
||||
padding-left: Theme.space-3;
|
||||
padding-right: Theme.space-3;
|
||||
spacing: Theme.space-3;
|
||||
height: 56px;
|
||||
IconButton {
|
||||
icon: Icons.arrow-left;
|
||||
label: @tr("Back");
|
||||
round: true;
|
||||
filled: true;
|
||||
size: 40px;
|
||||
y: (parent.height - self.height) / 2;
|
||||
clicked => { PhoneVoice.close(); }
|
||||
}
|
||||
Icon {
|
||||
source: Icons.volume-2;
|
||||
size: 28px;
|
||||
tint: Theme.text-secondary;
|
||||
y: (parent.height - self.height) / 2;
|
||||
}
|
||||
VerticalLayout {
|
||||
alignment: center;
|
||||
horizontal-stretch: 1;
|
||||
Text {
|
||||
text: Bridge.own-channel;
|
||||
color: Theme.text;
|
||||
font-size: Theme.font-lg;
|
||||
font-weight: Theme.weight-semibold;
|
||||
overflow: elide;
|
||||
}
|
||||
if Bridge.own-channel-topic != "": Text {
|
||||
text: Bridge.own-channel-topic;
|
||||
color: Theme.text-secondary;
|
||||
font-size: Theme.font-sm;
|
||||
overflow: elide;
|
||||
}
|
||||
}
|
||||
Button {
|
||||
kind: ButtonKind.danger;
|
||||
icon: Icons.log-out;
|
||||
text: @tr("Leave");
|
||||
y: (parent.height - self.height) / 2;
|
||||
clicked => {
|
||||
PhoneVoice.close();
|
||||
Bridge.disconnect-voice();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A translucent pill over the picture.
|
||||
component OverlayChip inherits Rectangle {
|
||||
in property <string> text;
|
||||
in property <image> icon;
|
||||
height: 26px;
|
||||
width: row.preferred-width;
|
||||
border-radius: Theme.radius-pill;
|
||||
background: #060a18b0;
|
||||
border-width: 1px;
|
||||
border-color: #ffffff24;
|
||||
row := HorizontalLayout {
|
||||
padding-left: Theme.space-3;
|
||||
padding-right: Theme.space-3;
|
||||
spacing: Theme.space-2;
|
||||
if root.icon.width > 0: Icon {
|
||||
source: root.icon;
|
||||
size: 14px;
|
||||
tint: #ffffff;
|
||||
y: (parent.height - self.height) / 2;
|
||||
}
|
||||
Text {
|
||||
text: root.text;
|
||||
color: #ffffff;
|
||||
font-size: Theme.font-sm;
|
||||
font-weight: Theme.weight-medium;
|
||||
vertical-alignment: center;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The stream we watch: the picture with LIVE, the viewers and the quality
|
||||
// over its top, the title and who streams it over its bottom, and volume
|
||||
// and full screen below them.
|
||||
component PhonePlayer inherits Rectangle {
|
||||
border-radius: Theme.radius-lg;
|
||||
clip: true;
|
||||
background: #000000;
|
||||
border-width: 1px;
|
||||
border-color: Theme.accent.transparentize(0.45);
|
||||
accessible-role: AccessibleRole.groupbox;
|
||||
accessible-label: Bridge.viewer-title;
|
||||
Image {
|
||||
width: parent.width;
|
||||
height: parent.height;
|
||||
source: Bridge.viewer-frame;
|
||||
image-fit: contain;
|
||||
visible: Bridge.viewer-has-frame;
|
||||
accessible-role: AccessibleRole.image;
|
||||
accessible-label: @tr("Stream picture");
|
||||
}
|
||||
if Bridge.viewer-status != "": Text {
|
||||
width: parent.width - 48px;
|
||||
text: Bridge.viewer-status;
|
||||
color: #ffffff;
|
||||
font-size: Theme.font-sm;
|
||||
horizontal-alignment: center;
|
||||
vertical-alignment: center;
|
||||
wrap: word-wrap;
|
||||
accessible-live-region: polite;
|
||||
}
|
||||
// Shades for what is drawn over the picture.
|
||||
Rectangle {
|
||||
y: 0;
|
||||
height: 64px;
|
||||
background: @linear-gradient(180deg, #000000b0 0%, #00000000 100%);
|
||||
}
|
||||
Rectangle {
|
||||
y: parent.height - self.height;
|
||||
height: 104px;
|
||||
background: @linear-gradient(180deg, #00000000 0%, #000000d0 100%);
|
||||
}
|
||||
// LIVE, viewers; the quality and full screen.
|
||||
HorizontalLayout {
|
||||
y: Theme.space-3;
|
||||
height: 30px;
|
||||
padding-left: Theme.space-3;
|
||||
padding-right: Theme.space-3;
|
||||
spacing: Theme.space-2;
|
||||
if !Bridge.viewer-ended: LiveBadge {
|
||||
large: true;
|
||||
y: (parent.height - self.height) / 2;
|
||||
}
|
||||
if Bridge.viewer-count > 0: OverlayChip {
|
||||
icon: Icons.eye;
|
||||
text: Bridge.viewer-count;
|
||||
y: (parent.height - self.height) / 2;
|
||||
}
|
||||
Rectangle { horizontal-stretch: 1; }
|
||||
// Simulcast layers the streamer offers ("Auto" follows the
|
||||
// bandwidth estimate); otherwise the height of what arrives.
|
||||
if Bridge.viewer-qualities.length > 1: Select {
|
||||
width: 116px;
|
||||
horizontal-stretch: 0;
|
||||
label: @tr("Quality");
|
||||
model: Bridge.viewer-qualities;
|
||||
current-index <=> Bridge.viewer-quality;
|
||||
selected(_) => { Bridge.set-stream-quality(Bridge.viewer-quality); }
|
||||
}
|
||||
if Bridge.viewer-qualities.length <= 1 && Bridge.viewer-has-frame: OverlayChip {
|
||||
text: @tr("{}p", Bridge.viewer-frame.height);
|
||||
y: (parent.height - self.height) / 2;
|
||||
}
|
||||
IconButton {
|
||||
icon: Icons.maximize;
|
||||
label: @tr("Full screen");
|
||||
size: 30px;
|
||||
icon-size: 16px;
|
||||
tint: #ffffff;
|
||||
y: (parent.height - self.height) / 2;
|
||||
clicked => { Bridge.toggle-fullscreen(); }
|
||||
}
|
||||
}
|
||||
// The title, who streams it, and the controls.
|
||||
VerticalLayout {
|
||||
height: self.preferred-height;
|
||||
y: parent.height - self.height;
|
||||
padding-left: Theme.space-4;
|
||||
padding-right: Theme.space-3;
|
||||
padding-bottom: Theme.space-1;
|
||||
spacing: 1px;
|
||||
Text {
|
||||
text: Bridge.viewer-title;
|
||||
color: #ffffff;
|
||||
font-size: Theme.font-md;
|
||||
font-weight: Theme.weight-semibold;
|
||||
overflow: elide;
|
||||
}
|
||||
HorizontalLayout {
|
||||
spacing: Theme.space-2;
|
||||
alignment: start;
|
||||
Text {
|
||||
text: Bridge.viewer-streamer;
|
||||
color: #ffffffd0;
|
||||
font-size: Theme.font-sm;
|
||||
vertical-alignment: center;
|
||||
overflow: elide;
|
||||
}
|
||||
if Bridge.viewer-streamer-admin: Icon {
|
||||
source: Icons.crown;
|
||||
size: 14px;
|
||||
tint: Theme.gold;
|
||||
y: (parent.height - self.height) / 2;
|
||||
}
|
||||
if !Bridge.viewer-ended: Text {
|
||||
text: "• " + Bridge.viewer-elapsed;
|
||||
color: #ffffffa0;
|
||||
font-size: Theme.font-sm;
|
||||
vertical-alignment: center;
|
||||
}
|
||||
}
|
||||
HorizontalLayout {
|
||||
height: 40px;
|
||||
spacing: Theme.space-2;
|
||||
IconButton {
|
||||
icon: Bridge.viewer-volume > 0 ? Icons.volume-2 : Icons.volume-x;
|
||||
label: Bridge.viewer-volume > 0 ? @tr("Mute") : @tr("Unmute");
|
||||
size: 34px;
|
||||
tint: #ffffff;
|
||||
y: (parent.height - self.height) / 2;
|
||||
clicked => { Bridge.set-stream-volume(Bridge.viewer-volume > 0 ? 0 : 100); }
|
||||
}
|
||||
Slider {
|
||||
y: (parent.height - self.height) / 2;
|
||||
minimum: 0;
|
||||
maximum: 200;
|
||||
step: 5;
|
||||
value <=> Bridge.viewer-volume;
|
||||
enabled: !Bridge.viewer-ended;
|
||||
label: @tr("Stream volume");
|
||||
changed(v) => { Bridge.set-stream-volume(v); }
|
||||
}
|
||||
IconButton {
|
||||
icon: Bridge.viewer-ended ? Icons.x : Icons.log-out;
|
||||
label: Bridge.viewer-ended ? @tr("Close") : @tr("Stop watching");
|
||||
size: 34px;
|
||||
tint: #ffffff;
|
||||
y: (parent.height - self.height) / 2;
|
||||
clicked => { Bridge.leave-stream(); }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A stream in the channel that we do not show: LIVE, the title, who, and
|
||||
// Watch (or Show, if we watch it already).
|
||||
component StreamPrompt inherits Rectangle {
|
||||
in property <StreamItem> stream;
|
||||
height: 76px;
|
||||
border-radius: Theme.radius-lg;
|
||||
clip: true;
|
||||
background: @linear-gradient(160deg, #26237a 0%, #0c1430 100%);
|
||||
border-width: 1px;
|
||||
border-color: stream.watching ? Theme.accent : Theme.border-strong;
|
||||
accessible-role: AccessibleRole.groupbox;
|
||||
accessible-label: stream.name;
|
||||
HorizontalLayout {
|
||||
padding: Theme.space-3;
|
||||
padding-left: Theme.space-4;
|
||||
spacing: Theme.space-3;
|
||||
VerticalLayout {
|
||||
alignment: center;
|
||||
horizontal-stretch: 1;
|
||||
spacing: Theme.space-1;
|
||||
HorizontalLayout {
|
||||
spacing: Theme.space-2;
|
||||
alignment: start;
|
||||
if stream.id != "": LiveBadge {
|
||||
y: (parent.height - self.height) / 2;
|
||||
}
|
||||
Text {
|
||||
text: stream.id == "" ? @tr("{} is streaming", stream.streamer) : stream.name != "" ? stream.name : @tr("Untitled stream");
|
||||
color: #ffffff;
|
||||
font-weight: Theme.weight-semibold;
|
||||
vertical-alignment: center;
|
||||
overflow: elide;
|
||||
}
|
||||
}
|
||||
Text {
|
||||
text: stream.id == "" ? (stream.channel == "" ? @tr("Looking it up…") : @tr("In {}; looking it up…", stream.channel))
|
||||
: stream.own ? @tr("Your stream")
|
||||
: stream.channel != "" ? @tr("{} · in {}", stream.streamer, stream.channel)
|
||||
: stream.viewers > 0 ? @tr("{} · {} watching", stream.streamer, stream.viewers)
|
||||
: stream.streamer;
|
||||
color: #ffffffb0;
|
||||
font-size: Theme.font-sm;
|
||||
overflow: elide;
|
||||
}
|
||||
}
|
||||
if stream.id != "" && !stream.own: Button {
|
||||
kind: ButtonKind.primary;
|
||||
small: true;
|
||||
icon: stream.watching ? Icons.monitor : Icons.eye;
|
||||
text: stream.watching ? @tr("Show") : @tr("Watch");
|
||||
y: (parent.height - self.height) / 2;
|
||||
clicked => {
|
||||
if stream.watching {
|
||||
Bridge.show-viewer();
|
||||
} else {
|
||||
Bridge.watch-stream(stream.id);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// One person: an avatar ringed green while talking (blue while
|
||||
// streaming), the muted mark, the name with the crown, LIVE below.
|
||||
component VoiceMember inherits VerticalLayout {
|
||||
in property <MemberItem> member;
|
||||
property <length> size: 54px;
|
||||
width: 68px;
|
||||
spacing: Theme.space-1;
|
||||
accessible-role: AccessibleRole.list-item;
|
||||
accessible-label: member.name;
|
||||
accessible-description: member.status;
|
||||
accessible-action-default => { Bridge.open-member(member.id); }
|
||||
HorizontalLayout {
|
||||
alignment: center;
|
||||
Rectangle {
|
||||
width: root.size + 8px;
|
||||
height: root.size + 8px;
|
||||
border-radius: self.width / 2;
|
||||
border-width: member.talking || member.streaming ? 2px : 0px;
|
||||
border-color: member.talking ? Theme.success : Theme.accent;
|
||||
Avatar {
|
||||
size: root.size;
|
||||
initials: member.initials;
|
||||
tint: member.tint;
|
||||
image: member.avatar;
|
||||
label: member.name;
|
||||
}
|
||||
if member.talking || member.muted || member.sound-off: Rectangle {
|
||||
x: parent.width - self.width;
|
||||
y: parent.height - self.height;
|
||||
width: 22px;
|
||||
height: 22px;
|
||||
border-radius: 11px;
|
||||
background: member.talking ? Theme.accent : Theme.surface;
|
||||
border-width: 2px;
|
||||
border-color: Theme.surface;
|
||||
if member.talking: SpeakingBars {
|
||||
width: 12px;
|
||||
height: 12px;
|
||||
tint: #ffffff;
|
||||
}
|
||||
if !member.talking: Icon {
|
||||
source: member.sound-off ? Icons.headphone-off : Icons.mic-off;
|
||||
size: 12px;
|
||||
tint: Theme.danger;
|
||||
}
|
||||
}
|
||||
TouchArea {
|
||||
clicked => { Bridge.open-member(member.id); }
|
||||
}
|
||||
}
|
||||
}
|
||||
HorizontalLayout {
|
||||
alignment: center;
|
||||
spacing: Theme.space-1;
|
||||
Text {
|
||||
text: member.name;
|
||||
color: member.myself ? Theme.accent-text : Theme.text;
|
||||
font-size: Theme.font-sm;
|
||||
overflow: elide;
|
||||
max-width: root.width - (member.admin ? 16px : 0px);
|
||||
}
|
||||
if member.admin: Icon {
|
||||
source: Icons.crown;
|
||||
size: 13px;
|
||||
tint: Theme.gold;
|
||||
y: (parent.height - self.height) / 2;
|
||||
}
|
||||
}
|
||||
if member.streaming: HorizontalLayout {
|
||||
alignment: center;
|
||||
LiveBadge { }
|
||||
}
|
||||
}
|
||||
|
||||
// "# Chill Zone Chat · Linked to this voice channel", with the pins, the
|
||||
// topics and the members.
|
||||
component ChatHeader inherits Rectangle {
|
||||
height: 56px;
|
||||
border-radius: Theme.radius-lg;
|
||||
background: Theme.surface-2;
|
||||
border-width: 1px;
|
||||
border-color: Theme.border;
|
||||
HorizontalLayout {
|
||||
padding-left: Theme.space-4;
|
||||
padding-right: Theme.space-3;
|
||||
spacing: Theme.space-3;
|
||||
Icon {
|
||||
source: Icons.hash;
|
||||
size: 24px;
|
||||
tint: Theme.text-secondary;
|
||||
y: (parent.height - self.height) / 2;
|
||||
}
|
||||
VerticalLayout {
|
||||
alignment: center;
|
||||
horizontal-stretch: 1;
|
||||
Text {
|
||||
text: @tr("{} Chat", Bridge.own-channel);
|
||||
color: Theme.text;
|
||||
font-size: Theme.font-md;
|
||||
font-weight: Theme.weight-semibold;
|
||||
overflow: elide;
|
||||
}
|
||||
Text {
|
||||
text: @tr("Linked to this voice channel");
|
||||
color: Theme.text-secondary;
|
||||
font-size: Theme.font-xs;
|
||||
overflow: elide;
|
||||
}
|
||||
}
|
||||
if Bridge.has-pins: IconButton {
|
||||
icon: Icons.pin;
|
||||
label: @tr("Pinned Messages");
|
||||
filled: true;
|
||||
size: 36px;
|
||||
icon-size: 18px;
|
||||
tint: Theme.accent-text;
|
||||
y: (parent.height - self.height) / 2;
|
||||
clicked => { Nav.show-pins(true); }
|
||||
}
|
||||
if Bridge.has-topics: IconButton {
|
||||
icon: Icons.book-open;
|
||||
label: @tr("Topics");
|
||||
filled: true;
|
||||
size: 36px;
|
||||
icon-size: 18px;
|
||||
y: (parent.height - self.height) / 2;
|
||||
clicked => { Nav.show-topics(true); }
|
||||
}
|
||||
IconButton {
|
||||
icon: Icons.users;
|
||||
label: @tr("Members");
|
||||
filled: true;
|
||||
size: 36px;
|
||||
icon-size: 18px;
|
||||
y: (parent.height - self.height) / 2;
|
||||
clicked => { Nav.members-open = true; }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A round control with its caption, for the voice bar.
|
||||
component VoiceControl inherits VerticalLayout {
|
||||
in property <image> icon;
|
||||
in property <string> text;
|
||||
in property <bool> checked;
|
||||
in property <bool> danger;
|
||||
in property <bool> enabled: true;
|
||||
// Filled red (Leave).
|
||||
in property <bool> alarm;
|
||||
callback clicked();
|
||||
horizontal-stretch: 1;
|
||||
spacing: Theme.space-1;
|
||||
alignment: center;
|
||||
accessible-role: AccessibleRole.button;
|
||||
accessible-label: text;
|
||||
accessible-enabled: enabled;
|
||||
accessible-checkable: !alarm;
|
||||
accessible-checked: checked;
|
||||
accessible-action-default => { if enabled { clicked(); } }
|
||||
HorizontalLayout {
|
||||
alignment: center;
|
||||
Rectangle {
|
||||
width: 48px;
|
||||
height: 48px;
|
||||
border-radius: 24px;
|
||||
background: root.alarm ? (touch.pressed ? Theme.danger.darker(0.2) : Theme.danger)
|
||||
: root.checked ? (root.danger ? Theme.danger-soft : Theme.accent-soft)
|
||||
: touch.pressed ? Theme.surface-4 : Theme.surface-2;
|
||||
border-width: root.alarm ? 0px : 1px;
|
||||
border-color: root.checked ? (root.danger ? Theme.danger.transparentize(0.5) : Theme.accent) : Theme.border-strong;
|
||||
opacity: root.enabled ? 1.0 : 0.45;
|
||||
Icon {
|
||||
source: root.icon;
|
||||
size: 22px;
|
||||
tint: root.alarm ? #ffffff : root.checked ? (root.danger ? Theme.danger : Theme.accent-text) : Theme.icon;
|
||||
}
|
||||
touch := TouchArea {
|
||||
enabled: root.enabled;
|
||||
clicked => { root.clicked(); }
|
||||
}
|
||||
}
|
||||
}
|
||||
Text {
|
||||
text: root.text;
|
||||
color: root.checked && root.danger ? Theme.danger : Theme.text-secondary;
|
||||
font-size: Theme.font-xs;
|
||||
horizontal-alignment: center;
|
||||
accessible-role: AccessibleRole.none;
|
||||
}
|
||||
}
|
||||
|
||||
// Mute, Deafen, Go Live (the Stream Studio; "Live" while it or a share
|
||||
// is), Share (the screen, at once) and Leave.
|
||||
component VoiceBar inherits Rectangle {
|
||||
height: 84px;
|
||||
background: Theme.surface;
|
||||
border-width: 1px;
|
||||
border-color: Theme.border;
|
||||
accessible-role: AccessibleRole.groupbox;
|
||||
accessible-label: @tr("Voice");
|
||||
HorizontalLayout {
|
||||
padding-left: Theme.space-2;
|
||||
padding-right: Theme.space-2;
|
||||
padding-top: Theme.space-3;
|
||||
padding-bottom: Theme.space-3;
|
||||
VoiceControl {
|
||||
icon: Bridge.input-muted ? Icons.mic-off : Icons.mic;
|
||||
text: Bridge.input-muted ? @tr("Unmute") : @tr("Mute");
|
||||
checked: Bridge.input-muted;
|
||||
danger: true;
|
||||
clicked => { Bridge.set-input-muted(!Bridge.input-muted); }
|
||||
}
|
||||
VoiceControl {
|
||||
icon: Bridge.output-muted ? Icons.headphone-off : Icons.headphones;
|
||||
text: Bridge.output-muted ? @tr("Undeafen") : @tr("Deafen");
|
||||
checked: Bridge.output-muted;
|
||||
danger: true;
|
||||
clicked => { Bridge.set-output-muted(!Bridge.output-muted); }
|
||||
}
|
||||
// The big one: the Stream Studio, or live there.
|
||||
if Bridge.streams-available && Bridge.can-share: VerticalLayout {
|
||||
horizontal-stretch: 1.6;
|
||||
spacing: Theme.space-1;
|
||||
alignment: center;
|
||||
accessible-role: AccessibleRole.button;
|
||||
accessible-label: @tr("Go Live");
|
||||
accessible-action-default => { Nav.open-studio(); }
|
||||
Rectangle {
|
||||
height: 48px;
|
||||
border-radius: 24px;
|
||||
background: live.pressed ? Theme.accent-pressed : Theme.accent;
|
||||
border-width: 2px;
|
||||
border-color: Theme.glow;
|
||||
Icon {
|
||||
source: Icons.radio;
|
||||
size: 26px;
|
||||
tint: Theme.on-accent;
|
||||
}
|
||||
live := TouchArea {
|
||||
clicked => { Nav.open-studio(); }
|
||||
}
|
||||
}
|
||||
Text {
|
||||
text: Bridge.share-state == "live" || StudioBridge.status.live ? @tr("Live") : @tr("Go Live");
|
||||
color: Theme.text;
|
||||
font-size: Theme.font-xs;
|
||||
font-weight: Theme.weight-semibold;
|
||||
horizontal-alignment: center;
|
||||
}
|
||||
}
|
||||
if Bridge.streams-available && Bridge.can-share: VoiceControl {
|
||||
icon: Icons.screen-share;
|
||||
text: Bridge.share-state == "live" ? @tr("Sharing") : @tr("Share");
|
||||
checked: Bridge.share-state == "live";
|
||||
clicked => { Nav.open-share(); }
|
||||
}
|
||||
VoiceControl {
|
||||
icon: Icons.phone-off;
|
||||
text: @tr("Leave");
|
||||
alarm: true;
|
||||
clicked => {
|
||||
PhoneVoice.close();
|
||||
Bridge.disconnect-voice();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Push-to-talk at the end of the composer: talks while held.
|
||||
component TalkButton inherits Rectangle {
|
||||
width: 48px;
|
||||
height: 48px;
|
||||
border-radius: 24px;
|
||||
background: Bridge.transmitting ? Theme.success : touch.pressed ? Theme.accent-pressed : Theme.accent;
|
||||
border-width: 2px;
|
||||
border-color: Bridge.transmitting ? Theme.success.transparentize(0.4) : Theme.glow;
|
||||
accessible-role: AccessibleRole.button;
|
||||
accessible-label: @tr("Hold to talk");
|
||||
accessible-checkable: true;
|
||||
accessible-checked: Bridge.transmitting;
|
||||
accessible-action-default => { Bridge.push-to-talk(!Bridge.transmitting); }
|
||||
Icon {
|
||||
source: Icons.mic;
|
||||
size: 22px;
|
||||
tint: Theme.on-accent;
|
||||
}
|
||||
touch := TouchArea {
|
||||
pointer-event(e) => {
|
||||
if e.kind == PointerEventKind.down {
|
||||
Bridge.push-to-talk(true);
|
||||
} else if e.kind == PointerEventKind.up || e.kind == PointerEventKind.cancel {
|
||||
Bridge.push-to-talk(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The whole screen.
|
||||
export component MobileVoice inherits VerticalLayout {
|
||||
// A topic opened from the drawer shows in the chat page.
|
||||
property <int> topic: Bridge.current-topic;
|
||||
changed topic => {
|
||||
if topic >= 0 {
|
||||
PhoneVoice.close();
|
||||
Nav.mobile-tab = MobileTab.chat;
|
||||
}
|
||||
}
|
||||
clip := TextInput {
|
||||
visible: false;
|
||||
width: 0;
|
||||
height: 0;
|
||||
}
|
||||
ChannelBar { }
|
||||
sv := ScrollView {
|
||||
// The stream, the people and the chat header scroll away together
|
||||
// when the window is short; the messages always keep some room.
|
||||
vertical-stretch: 0;
|
||||
height: min(content.preferred-height, root.height * 0.55);
|
||||
content := VerticalLayout {
|
||||
width: sv.visible-width;
|
||||
padding-left: Theme.space-3;
|
||||
padding-right: Theme.space-3;
|
||||
spacing: Theme.space-3;
|
||||
if Bridge.viewer-open: PhonePlayer {
|
||||
height: (sv.visible-width - 2 * Theme.space-3) * 9 / 16;
|
||||
}
|
||||
if !Bridge.viewer-open: VerticalLayout {
|
||||
spacing: Theme.space-2;
|
||||
for stream in Bridge.streams: StreamPrompt {
|
||||
stream: stream;
|
||||
}
|
||||
}
|
||||
people := ScrollView {
|
||||
height: 112px;
|
||||
HorizontalLayout {
|
||||
padding-top: Theme.space-2;
|
||||
spacing: Theme.space-2;
|
||||
alignment: start;
|
||||
for member in Bridge.members: VoiceMember {
|
||||
member: member;
|
||||
}
|
||||
VerticalLayout {
|
||||
width: 68px;
|
||||
spacing: Theme.space-1;
|
||||
alignment: start;
|
||||
HorizontalLayout {
|
||||
alignment: center;
|
||||
IconButton {
|
||||
icon: Icons.user-plus;
|
||||
label: @tr("Invite: copy a link to this channel");
|
||||
round: true;
|
||||
filled: true;
|
||||
size: 62px;
|
||||
icon-size: 24px;
|
||||
// Through a text field: Slint copies only
|
||||
// what is selected in one.
|
||||
clicked => {
|
||||
clip.text = Bridge.invite();
|
||||
clip.select-all();
|
||||
clip.copy();
|
||||
}
|
||||
}
|
||||
}
|
||||
Text {
|
||||
text: @tr("Invite");
|
||||
color: Theme.text-secondary;
|
||||
font-size: Theme.font-sm;
|
||||
horizontal-alignment: center;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
ChatHeader { }
|
||||
}
|
||||
}
|
||||
MessageList {
|
||||
vertical-stretch: 1;
|
||||
min-height: 96px;
|
||||
model: Bridge.messages;
|
||||
older: true;
|
||||
}
|
||||
HorizontalLayout {
|
||||
padding-right: Bridge.audio.transmit == 0 ? Theme.space-4 : 0px;
|
||||
Composer {
|
||||
placeholder: @tr("Message #{}…", Bridge.own-channel);
|
||||
padding: Theme.space-3;
|
||||
padding-right: Bridge.audio.transmit == 0 ? Theme.space-3 : Theme.space-5;
|
||||
}
|
||||
// Push-to-talk is the transmit mode: talking is at hand.
|
||||
if Bridge.audio.transmit == 0: TalkButton {
|
||||
y: (parent.height - self.height) / 2;
|
||||
}
|
||||
}
|
||||
VoiceBar { }
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
// Pages of the narrow (phone) layout that the desktop shows elsewhere:
|
||||
// the server list with the channels, activity, and the "You" page.
|
||||
// the server list with the channels, activity, the "You" page, and the
|
||||
// pins, topics and members over the page.
|
||||
|
||||
import { Theme } from "../theme.slint";
|
||||
import { Icons } from "../icons.slint";
|
||||
@@ -8,6 +9,8 @@ import { Nav, Page, SettingsSection } from "../nav.slint";
|
||||
import { Icon, Button, ButtonKind, IconButton, Avatar, Status, CountBadge, LiveBadge, NavItem, ListItem, SectionHeader, Card, Banner, ScrollView, ActionButton } from "../components/index.slint";
|
||||
import { ServerHeader, ConnectActions, ChannelTree } from "channels.slint";
|
||||
import { StreamsPanel } from "streams.slint";
|
||||
import { PinsDrawer, TopicsDrawer } from "drawers.slint";
|
||||
import { MembersPanel } from "members.slint";
|
||||
import { VoiceCard, VoiceButtons } from "../shells/common.slint";
|
||||
import { StudioBridge } from "../studio-bridge.slint";
|
||||
import { ShareMenu } from "../share-menu.slint";
|
||||
@@ -230,3 +233,32 @@ export component YouPage inherits ScrollView {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The pins, the topics or the server's members as a page over the current
|
||||
// one (the desktop shows them beside the chat).
|
||||
export component PhoneSheet inherits Rectangle {
|
||||
background: Theme.bg-app;
|
||||
// Nothing below takes clicks while it is shown.
|
||||
TouchArea { }
|
||||
if Nav.pins-open: PinsDrawer { }
|
||||
if Nav.topics-open && !Nav.pins-open: TopicsDrawer { }
|
||||
if Nav.members-open && !Nav.pins-open && !Nav.topics-open: VerticalLayout {
|
||||
HorizontalLayout {
|
||||
padding-left: Theme.space-3;
|
||||
padding-top: Theme.space-3;
|
||||
spacing: Theme.space-2;
|
||||
alignment: start;
|
||||
IconButton {
|
||||
icon: Icons.arrow-left;
|
||||
label: @tr("Back");
|
||||
round: true;
|
||||
filled: true;
|
||||
size: 36px;
|
||||
clicked => { Nav.members-open = false; }
|
||||
}
|
||||
}
|
||||
MembersPanel {
|
||||
vertical-stretch: 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -108,12 +108,13 @@ export component StreamsPanel inherits VerticalLayout {
|
||||
overflow: elide;
|
||||
vertical-alignment: center;
|
||||
}
|
||||
IconButton {
|
||||
icon: Icons.x;
|
||||
label: @tr("Close the panel");
|
||||
// The phone's voice channel screen.
|
||||
if Bridge.voice-connected: IconButton {
|
||||
icon: Icons.chevron-right;
|
||||
label: @tr("Open the voice channel");
|
||||
size: 28px;
|
||||
icon-size: Theme.icon-sm;
|
||||
clicked => { Nav.right-panel-open = false; }
|
||||
clicked => { Nav.show-voice(true); }
|
||||
}
|
||||
}
|
||||
if Bridge.members.length == 0: Text {
|
||||
|
||||
@@ -317,21 +317,25 @@ component SourceRow inherits Rectangle {
|
||||
{ text: source.locked ? @tr("Unlock") : @tr("Lock"), icon: Icons.lock, enabled: true },
|
||||
{ text: source.background == "keep" ? @tr("Blur background") : @tr("Background effect off"), icon: Icons.sparkles, enabled: source.kind == "camera", separator: true },
|
||||
{ text: @tr("Background effect…"), icon: Icons.sliders-horizontal, enabled: source.kind == "camera" },
|
||||
// A phone's front and back camera, or the next webcam.
|
||||
{ text: @tr("Switch camera"), icon: Icons.video, enabled: source.kind == "camera" },
|
||||
{ text: @tr("Bring forward"), icon: Icons.chevron-up, enabled: !source.front, separator: true },
|
||||
{ text: @tr("Send backward"), icon: Icons.chevron-down, enabled: !source.back },
|
||||
{ text: @tr("Rename…"), icon: Icons.pencil, enabled: true, separator: true },
|
||||
{ text: @tr("Remove"), icon: Icons.trash-2, enabled: true, danger: true },
|
||||
];
|
||||
activated(i) => {
|
||||
if i == 0 || i == 1 || i == 2 || i == 5 || i == 8 {
|
||||
if i == 0 || i == 1 || i == 2 || i == 5 || i == 9 {
|
||||
StudioNav.edit-source(source.id);
|
||||
} else if i == 3 {
|
||||
StudioBridge.source-action(source.id, "lock");
|
||||
} else if i == 4 {
|
||||
StudioBridge.source-action(source.id, source.background == "keep" ? "bg-blur" : "bg-keep");
|
||||
} else if i == 6 {
|
||||
StudioBridge.source-action(source.id, "up");
|
||||
StudioBridge.source-action(source.id, "next-camera");
|
||||
} else if i == 7 {
|
||||
StudioBridge.source-action(source.id, "up");
|
||||
} else if i == 8 {
|
||||
StudioBridge.source-action(source.id, "down");
|
||||
} else {
|
||||
StudioBridge.source-action(source.id, "remove");
|
||||
@@ -731,8 +735,8 @@ export component StudioHeader inherits HorizontalLayout {
|
||||
}
|
||||
}
|
||||
|
||||
// One audio source: meter, gain, mute, a menu.
|
||||
component MixerRow inherits Rectangle {
|
||||
// One audio source: meter, gain, mute, a menu (also the share dialog's).
|
||||
export component MixerRow inherits Rectangle {
|
||||
in property <StudioAudio> audio;
|
||||
in property <int> index;
|
||||
in property <bool> compact;
|
||||
@@ -1918,12 +1922,13 @@ component SourceDialog inherits Modal {
|
||||
}
|
||||
}
|
||||
|
||||
// Pick a screen, window, camera or audio source.
|
||||
component PickDialog inherits Modal {
|
||||
// Pick a screen, window, camera or audio source (audio: also over the
|
||||
// share dialog).
|
||||
export component PickDialog inherits Modal {
|
||||
in property <string> kind;
|
||||
callback done();
|
||||
title: kind == "screen" ? @tr("Share a screen") : kind == "window" ? @tr("Share a window") : kind == "camera" ? @tr("Add a camera") : @tr("Add an audio source");
|
||||
subtitle: kind == "audio" ? @tr("Mixed into the stream's audio.") : @tr("Added to the live scene.");
|
||||
title: kind == "screen" ? @tr("Share a screen") : kind == "window" ? @tr("Share a window") : kind == "camera" ? @tr("Add a camera") : @tr("Audio sources");
|
||||
subtitle: kind == "audio" ? @tr("Mixed into the stream's audio. Pick as many as you like.") : @tr("Added to the live scene.");
|
||||
icon: StudioKinds.icon(kind == "audio" ? "microphone" : kind);
|
||||
card-width: 520px;
|
||||
card-height: 540px;
|
||||
@@ -1944,24 +1949,22 @@ component PickDialog inherits Modal {
|
||||
accessible-role: AccessibleRole.button;
|
||||
accessible-label: pick.name;
|
||||
accessible-description: pick.detail;
|
||||
accessible-action-default => {
|
||||
if root.kind == "audio" {
|
||||
StudioBridge.add-audio(i);
|
||||
} else {
|
||||
StudioBridge.add-picked(root.kind, i);
|
||||
}
|
||||
root.done();
|
||||
}
|
||||
accessible-checkable: root.kind == "audio";
|
||||
accessible-checked: pick.selected;
|
||||
accessible-action-default => { pick-touch.pick(); }
|
||||
pick-touch := TouchArea {
|
||||
mouse-cursor: MouseCursor.pointer;
|
||||
clicked => {
|
||||
// Audio sources are switched on and off (several at once);
|
||||
// the rest is added and the picker closes.
|
||||
function pick() {
|
||||
if root.kind == "audio" {
|
||||
StudioBridge.add-audio(i);
|
||||
StudioBridge.toggle-audio(i);
|
||||
} else {
|
||||
StudioBridge.add-picked(root.kind, i);
|
||||
root.done();
|
||||
}
|
||||
root.done();
|
||||
}
|
||||
clicked => { self.pick(); }
|
||||
}
|
||||
HorizontalLayout {
|
||||
padding-left: Theme.space-3;
|
||||
@@ -1973,10 +1976,15 @@ component PickDialog inherits Modal {
|
||||
y: (parent.height - self.height) / 2;
|
||||
border-radius: Theme.radius-md;
|
||||
background: Theme.surface-3;
|
||||
Icon {
|
||||
if pick.icon.width == 0: Icon {
|
||||
source: StudioKinds.icon(pick.kind);
|
||||
size: 18px;
|
||||
}
|
||||
if pick.icon.width > 0: Image {
|
||||
width: 28px;
|
||||
height: 28px;
|
||||
source: pick.icon;
|
||||
}
|
||||
}
|
||||
VerticalLayout {
|
||||
alignment: center;
|
||||
@@ -1993,9 +2001,31 @@ component PickDialog inherits Modal {
|
||||
overflow: elide;
|
||||
}
|
||||
}
|
||||
if root.kind == "audio": Rectangle {
|
||||
width: 24px;
|
||||
height: 24px;
|
||||
y: (parent.height - self.height) / 2;
|
||||
border-radius: 12px;
|
||||
background: pick.selected ? Theme.accent : transparent;
|
||||
border-width: pick.selected ? 0 : 1.5px;
|
||||
border-color: Theme.border-strong;
|
||||
if pick.selected: Icon {
|
||||
source: Icons.check;
|
||||
size: 16px;
|
||||
tint: Theme.on-accent;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if root.kind == "audio": HorizontalLayout {
|
||||
alignment: end;
|
||||
Button {
|
||||
kind: ButtonKind.primary;
|
||||
text: @tr("Done");
|
||||
clicked => { root.done(); }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Rename a scene.
|
||||
|
||||
@@ -69,6 +69,10 @@ export component VoiceCard inherits Rectangle {
|
||||
border-color: Theme.border;
|
||||
accessible-role: AccessibleRole.groupbox;
|
||||
accessible-label: @tr("Voice");
|
||||
// The phone: a tap opens the voice channel screen.
|
||||
if Nav.narrow && Bridge.voice-connected: TouchArea {
|
||||
clicked => { Nav.show-voice(true); }
|
||||
}
|
||||
VerticalLayout {
|
||||
padding: Theme.space-3;
|
||||
spacing: Theme.space-3;
|
||||
@@ -97,6 +101,14 @@ export component VoiceCard inherits Rectangle {
|
||||
overflow: elide;
|
||||
}
|
||||
}
|
||||
if Nav.narrow && Bridge.voice-connected: IconButton {
|
||||
icon: Icons.chevron-right;
|
||||
label: @tr("Open the voice channel");
|
||||
size: 32px;
|
||||
icon-size: Theme.icon-sm;
|
||||
y: (parent.height - self.height) / 2;
|
||||
clicked => { Nav.show-voice(true); }
|
||||
}
|
||||
IconButton {
|
||||
icon: Icons.phone-off;
|
||||
label: @tr("Disconnect");
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
// The narrow (phone) frame: a top bar, one page at a time (@children), and
|
||||
// the bottom navigation (Home, Servers, Chat, Activity, You). Used while
|
||||
// the bottom navigation (Home, Servers, Chats, Activity, You). Used while
|
||||
// the window is narrower than `Nav.narrow-breakpoint`.
|
||||
|
||||
import { Theme } from "../theme.slint";
|
||||
import { Icons } from "../icons.slint";
|
||||
import { Bridge } from "../bridge.slint";
|
||||
import { Nav, Page, MobileTab, SettingsSection } from "../nav.slint";
|
||||
import { Icon, IconButton, CountBadge } from "../components/index.slint";
|
||||
import { Icon, IconButton, CountBadge, PopupMenu, MenuEntry } from "../components/index.slint";
|
||||
import { PhoneVoice } from "../screens/mobile-voice.slint";
|
||||
|
||||
// One entry of the bottom navigation.
|
||||
component NavTab inherits Rectangle {
|
||||
@@ -68,6 +69,40 @@ component NavTab inherits Rectangle {
|
||||
}
|
||||
}
|
||||
|
||||
// The people in our channel, as a pill (the voice channel screen's top bar).
|
||||
component PeoplePill inherits Rectangle {
|
||||
callback clicked();
|
||||
width: row.preferred-width;
|
||||
height: 40px;
|
||||
border-radius: 20px;
|
||||
background: touch.pressed ? Theme.surface-4 : Theme.surface-2;
|
||||
border-width: 1px;
|
||||
border-color: Theme.border;
|
||||
accessible-role: AccessibleRole.button;
|
||||
accessible-label: @tr("{} in voice", Bridge.members.length);
|
||||
accessible-action-default => { root.clicked(); }
|
||||
touch := TouchArea {
|
||||
clicked => { root.clicked(); }
|
||||
}
|
||||
row := HorizontalLayout {
|
||||
padding-left: Theme.space-4;
|
||||
padding-right: Theme.space-4;
|
||||
spacing: Theme.space-2;
|
||||
Icon {
|
||||
source: Icons.users;
|
||||
size: 18px;
|
||||
tint: Theme.icon;
|
||||
y: (parent.height - self.height) / 2;
|
||||
}
|
||||
Text {
|
||||
text: Bridge.members.length;
|
||||
color: Theme.text;
|
||||
font-size: Theme.font-md;
|
||||
vertical-alignment: center;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export component MobileShell inherits Rectangle {
|
||||
in property <string> title;
|
||||
in property <string> subtitle;
|
||||
@@ -75,6 +110,12 @@ export component MobileShell inherits Rectangle {
|
||||
in property <int> unread;
|
||||
// Show a back arrow (sub-pages such as the settings).
|
||||
in property <bool> back;
|
||||
// The bottom navigation; pages with their own controls there (the
|
||||
// voice channel, the Stream Studio) go without.
|
||||
in property <bool> navigation: true;
|
||||
// The voice channel screen's buttons in the top bar: the people, the
|
||||
// chats and a menu.
|
||||
in property <bool> voice;
|
||||
callback go-back();
|
||||
background: Theme.backdrop;
|
||||
VerticalLayout {
|
||||
@@ -117,7 +158,21 @@ export component MobileShell inherits Rectangle {
|
||||
overflow: elide;
|
||||
}
|
||||
}
|
||||
IconButton {
|
||||
// The voice channel we are in, from any page.
|
||||
if !root.voice && Bridge.voice-connected: IconButton {
|
||||
icon: Icons.volume-2;
|
||||
label: @tr("Voice channel");
|
||||
round: true;
|
||||
filled: true;
|
||||
dot: true;
|
||||
dot-color: Theme.success;
|
||||
y: (parent.height - self.height) / 2;
|
||||
clicked => {
|
||||
Nav.show(Page.server);
|
||||
Nav.show-voice(true);
|
||||
}
|
||||
}
|
||||
if !root.voice: IconButton {
|
||||
icon: Icons.bell;
|
||||
label: @tr("Notifications");
|
||||
round: true;
|
||||
@@ -126,6 +181,60 @@ export component MobileShell inherits Rectangle {
|
||||
y: (parent.height - self.height) / 2;
|
||||
clicked => { Nav.mobile-tab = MobileTab.activity; Nav.show(Page.server); }
|
||||
}
|
||||
if root.voice: PeoplePill {
|
||||
y: (parent.height - self.height) / 2;
|
||||
clicked => { Nav.members-open = true; }
|
||||
}
|
||||
if root.voice: Rectangle {
|
||||
width: 40px;
|
||||
height: 40px;
|
||||
y: (parent.height - self.height) / 2;
|
||||
IconButton {
|
||||
icon: Icons.message-square;
|
||||
label: @tr("Chats");
|
||||
round: true;
|
||||
filled: true;
|
||||
size: 40px;
|
||||
clicked => {
|
||||
PhoneVoice.close();
|
||||
Nav.mobile-tab = MobileTab.chat;
|
||||
}
|
||||
}
|
||||
if root.unread > 0: CountBadge {
|
||||
x: parent.width - self.width / 2 - 4px;
|
||||
y: -4px;
|
||||
count: root.unread;
|
||||
}
|
||||
}
|
||||
if root.voice: IconButton {
|
||||
icon: Icons.more-horizontal;
|
||||
label: @tr("More");
|
||||
round: true;
|
||||
filled: true;
|
||||
y: (parent.height - self.height) / 2;
|
||||
clicked => { more.show(self.x + self.width - 220px, self.y + self.height + 4px); }
|
||||
}
|
||||
}
|
||||
more := PopupMenu {
|
||||
entries: [
|
||||
{ text: @tr("Stream Studio"), icon: Icons.radio, enabled: Bridge.streams-available },
|
||||
{ text: @tr("Voice Settings"), icon: Icons.settings, enabled: true },
|
||||
{ text: @tr("Activity"), icon: Icons.activity, enabled: true },
|
||||
{ text: @tr("Leave Voice"), icon: Icons.phone-off, danger: true, enabled: true, separator: true },
|
||||
];
|
||||
activated(i) => {
|
||||
if i == 0 {
|
||||
Nav.open-studio();
|
||||
} else if i == 1 {
|
||||
Nav.open-settings(SettingsSection.voice);
|
||||
} else if i == 2 {
|
||||
PhoneVoice.close();
|
||||
Nav.mobile-tab = MobileTab.activity;
|
||||
} else {
|
||||
PhoneVoice.close();
|
||||
Bridge.disconnect-voice();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Rectangle {
|
||||
@@ -133,7 +242,7 @@ export component MobileShell inherits Rectangle {
|
||||
@children
|
||||
}
|
||||
// Bottom navigation.
|
||||
Rectangle {
|
||||
if root.navigation: Rectangle {
|
||||
height: 64px;
|
||||
background: Theme.surface;
|
||||
border-width: 1px;
|
||||
@@ -147,34 +256,34 @@ export component MobileShell inherits Rectangle {
|
||||
icon: Icons.home;
|
||||
text: @tr("Home");
|
||||
selected: Nav.mobile-tab == MobileTab.home && Nav.page != Page.settings;
|
||||
clicked => { Nav.show(Page.home); Nav.mobile-tab = MobileTab.home; }
|
||||
clicked => { Nav.show-tab(MobileTab.home); }
|
||||
}
|
||||
NavTab {
|
||||
icon: Icons.server;
|
||||
text: @tr("Servers");
|
||||
selected: Nav.mobile-tab == MobileTab.servers && Nav.page != Page.settings;
|
||||
dot: Bridge.voice-connected;
|
||||
clicked => { Nav.show(Page.server); Nav.mobile-tab = MobileTab.servers; }
|
||||
clicked => { Nav.show-tab(MobileTab.servers); }
|
||||
}
|
||||
NavTab {
|
||||
icon: Bridge.viewer-open ? Icons.monitor : Icons.message-circle;
|
||||
text: Bridge.viewer-open ? @tr("Stream") : @tr("Chat");
|
||||
icon: Icons.message-circle;
|
||||
text: @tr("Chats");
|
||||
selected: Nav.mobile-tab == MobileTab.chat && Nav.page != Page.settings;
|
||||
badge: root.unread;
|
||||
clicked => { Nav.show(Page.server); Nav.mobile-tab = MobileTab.chat; }
|
||||
clicked => { Nav.show-tab(MobileTab.chat); }
|
||||
}
|
||||
NavTab {
|
||||
icon: Icons.activity;
|
||||
text: @tr("Activity");
|
||||
selected: Nav.mobile-tab == MobileTab.activity && Nav.page != Page.settings;
|
||||
badge: Bridge.share-requests;
|
||||
clicked => { Nav.show(Page.server); Nav.mobile-tab = MobileTab.activity; }
|
||||
clicked => { Nav.show-tab(MobileTab.activity); }
|
||||
}
|
||||
NavTab {
|
||||
icon: Icons.user;
|
||||
text: @tr("You");
|
||||
selected: Nav.mobile-tab == MobileTab.you || Nav.page == Page.settings;
|
||||
clicked => { Nav.show(Page.server); Nav.mobile-tab = MobileTab.you; }
|
||||
clicked => { Nav.show-tab(MobileTab.you); }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -78,6 +78,10 @@ export struct StudioPick {
|
||||
detail: string,
|
||||
// For the icon: monitor, window, portal, camera, microphone, desktop, app, tone
|
||||
kind: string,
|
||||
// The application's own icon (audio), if it has one.
|
||||
icon: image,
|
||||
// Already mixed in (audio): picking it again takes it out.
|
||||
selected: bool,
|
||||
}
|
||||
|
||||
// The header, the preview's badges and the bottom bar.
|
||||
@@ -223,9 +227,10 @@ export global StudioBridge {
|
||||
// The phone layout's source cards: screen, camera, window.
|
||||
callback main-source(string);
|
||||
|
||||
// Audio: fill `picks` with what can be added; add, change, remove.
|
||||
// Audio: fill `picks` with what can be mixed in (marking what is);
|
||||
// mix one in or take it out, change, remove.
|
||||
callback list-audio();
|
||||
callback add-audio(int);
|
||||
callback toggle-audio(int);
|
||||
// While dragging (`done` false) and at the end.
|
||||
callback set-gain(int, float, bool);
|
||||
callback toggle-mute(int);
|
||||
|
||||
@@ -2,23 +2,30 @@
|
||||
|
||||
The Android app is the desktop UI (`voelin-ui`, Slint) running in a
|
||||
`NativeActivity`, plus a thin Kotlin layer for what only Java APIs can do:
|
||||
foreground services, the screen-capture consent, the Keystore.
|
||||
foreground services and their notifications, the screen-capture consent,
|
||||
the cameras, the share sheet, the Keystore.
|
||||
|
||||
```
|
||||
android/ Gradle project (AGP 8.13, Kotlin 2.3, Gradle 8.14.3 wrapper)
|
||||
app/src/main/java/.../voelin/ MainActivity (NativeActivity), Bridge, Native,
|
||||
VoiceService, ScreenCaptureService, SecretStore
|
||||
app/src/main/java/.../voelin/ MainActivity (NativeActivity, Share to Voelin), Bridge,
|
||||
Native, VoiceService, ScreenCaptureService, Notifications,
|
||||
CameraCapture, SecretStore
|
||||
crates/voelin-android/ libvoelin_android.so: android_main, engine host,
|
||||
JNI glue, capture providers, Keystore secrets
|
||||
JNI glue, capture and camera providers, notifications
|
||||
(foreground.rs), Keystore secrets
|
||||
```
|
||||
|
||||
The phone layout of the UI (the voice channel with a stream, the bottom
|
||||
navigation, the studio, the share dialog) is described in
|
||||
[ui.md](ui.md); its screenshots are taken on the desktop at 390×844.
|
||||
|
||||
## Building
|
||||
|
||||
Requirements:
|
||||
|
||||
- Android SDK with `platforms;android-36` and `build-tools;36.0.0`
|
||||
(`ANDROID_HOME`, or `sdk.dir` in `android/local.properties`), NDK
|
||||
`27.3.13750724` (`ndk;27.3.13750724`; the version is pinned in
|
||||
`27.3.13750724` (`ndk;27.3.13750724`; the versions are pinned in
|
||||
`app/build.gradle.kts`)
|
||||
- JDK 17 or newer
|
||||
- Rust targets: `rustup target add aarch64-linux-android x86_64-linux-android`
|
||||
@@ -28,7 +35,7 @@ Requirements:
|
||||
|
||||
```sh
|
||||
cd android
|
||||
./gradlew assembleDebug # arm64-v8a + x86_64 (emulator)
|
||||
./gradlew assembleDebug # arm64-v8a + x86_64 (emulator, Waydroid)
|
||||
./gradlew assembleDebug -Pvoelin.abis=arm64-v8a # phones only, half the build
|
||||
adb install -r app/build/outputs/apk/debug/app-debug.apk
|
||||
adb logcat -s RustStdoutStderr ScreenCaptureService VoiceService SecretStore
|
||||
@@ -79,19 +86,61 @@ capture, NDK MediaCodec format queries); targetSdk and compileSdk 36.
|
||||
to the background instead of finishing the activity; configuration changes
|
||||
do not recreate it.
|
||||
- **Voice in the background**: while any session has a voice connection,
|
||||
`VoiceService` runs as a foreground service of type `microphone` with a
|
||||
notification ("In voice on …", Mute or Unmute, Disconnect). Rust drives it
|
||||
from engine events (`foreground.rs`, `Bridge.setVoiceNotification`). Audio
|
||||
itself is cpal on AAudio, as on desktop.
|
||||
`VoiceService` runs as a foreground service of type `microphone`. Its
|
||||
notification reads like the app's voice card: the channel as the title,
|
||||
the server and who is there ("Home · 3 in voice", "just you"), the time
|
||||
in voice as a chronometer, and Mute, Deafen and Leave, which act on every
|
||||
voice session; with several servers, "In voice on 2 servers" and their
|
||||
names. Tapping it opens the voice channel screen (the activity hands the
|
||||
request to Rust, which queues it until the window runs:
|
||||
`voelin_ui::request`). Rust drives it from engine events (`foreground.rs`,
|
||||
`Bridge.setVoiceNotification`). Audio itself is cpal on AAudio, as on
|
||||
desktop.
|
||||
- **Sharing the screen**: `voelin_media::capture::default_screen_capture()`
|
||||
returns the MediaProjection provider (`capture.rs`) registered at start.
|
||||
Starting shows the system consent dialog; on consent `ScreenCaptureService`
|
||||
(type `mediaProjection`) mirrors the display into an `ImageReader` at the
|
||||
requested frame rate, longest side at most 1920 px, and hands RGBA frames to
|
||||
`Native.onScreenFrame`. System audio (`default_audio_capture()`) is
|
||||
(type `mediaProjection`) mirrors the display, longest side at most
|
||||
1920 px. While one MediaCodec encoder runs (one simulcast layer, one
|
||||
codec: the common case) the virtual display renders straight into that
|
||||
encoder's input surface, with no copy of a frame on the CPU; with more
|
||||
encoders (layers, or a codec a viewer chose) it renders into an
|
||||
`ImageReader` again, whose RGBA buffers go to the encoders borrowed
|
||||
(`Native.onScreenFrame`), until one encoder is left ([media.md](media.md),
|
||||
MediaCodec). System audio (`default_audio_capture()`) is
|
||||
`AudioPlaybackCapture` of media, game and unknown usages, 48 kHz stereo
|
||||
float, only while the projection runs. Ending the projection from the
|
||||
status bar or the notification closes the capture channels.
|
||||
float, only while the projection runs; single apps are captured by their
|
||||
uid (`addMatchingUid`), "every app but ours" excludes ours. While our
|
||||
stream is live the notification says where and who watches ("Live in
|
||||
Chill Zone", "Home · 2 watching") with Stop sharing. Ending the
|
||||
projection from the status bar or the notification closes the capture
|
||||
channels.
|
||||
- **Choosing the stream's sound**: the share dialog and the Stream Studio
|
||||
pick the sources of `stream.audio_sources` in the studio's picker:
|
||||
the microphone, every app but ours, and the launchable apps
|
||||
(PackageManager) with their own icons, several at once. Kotlin draws each
|
||||
app's icon once per installed version into a 96 px PNG in the cache
|
||||
(`Bridge.launchableApps`, `AudioApp::icon`). The shared window's audio is not
|
||||
offered: a phone shares the whole screen.
|
||||
- **Cameras** (the Stream Studio's camera sources): `CameraCapture.kt`
|
||||
lists the Camera2 cameras (front first, their YUV sizes and highest frame
|
||||
rate) and asks for the `CAMERA` permission when a camera is first opened
|
||||
(the source shows why if it is refused). It opens the camera into an
|
||||
`ImageReader` (`YUV_420_888`) at the wished size or the nearest (16:9
|
||||
first, 1280×720 by default) and hands each frame's planes to Rust as
|
||||
direct buffers valid during the call, with the turn that makes it
|
||||
upright. Rust (`camera.rs`) passes upright planar or NV12 pictures on as
|
||||
they are and gathers NV21 or turned ones into I420 in a buffer each
|
||||
camera keeps: nothing is allocated per frame. Cameras that face the user
|
||||
are mirrored by default; the source menu's Switch camera moves a source
|
||||
to the next camera ([studio.md](studio.md)).
|
||||
- **Share to Voelin**: the activity takes `ACTION_SEND` and
|
||||
`ACTION_SEND_MULTIPLE` of any type. Text and links go into the composer
|
||||
of the current chat, which the phone then shows (one tap sends them).
|
||||
Files are copied out of the sending app while its content URIs are
|
||||
readable, on a thread of their own, under the name the app gives (made
|
||||
safe as a path component), then uploaded to the current chat's channel
|
||||
(or the channel we are in) and linked there as the attach button does.
|
||||
The copies live in the cache and are removed at the next start.
|
||||
- **Watching and encoding**: `voelin_media::Codecs` uses the device's
|
||||
MediaCodec encoders (hardware first) and decoders on Android
|
||||
([media.md](media.md)).
|
||||
@@ -107,7 +156,8 @@ capture, NDK MediaCodec format queries); targetSdk and compileSdk 36.
|
||||
|
||||
Permissions: `INTERNET`, `ACCESS_NETWORK_STATE`, `RECORD_AUDIO`,
|
||||
`MODIFY_AUDIO_SETTINGS`, `FOREGROUND_SERVICE` with `_MICROPHONE` and
|
||||
`_MEDIA_PROJECTION`, `POST_NOTIFICATIONS`.
|
||||
`_MEDIA_PROJECTION`, `POST_NOTIFICATIONS`, `CAMERA` (asked for when a camera
|
||||
is first opened; `android.hardware.camera.any` is optional).
|
||||
|
||||
## Status
|
||||
|
||||
@@ -115,8 +165,14 @@ Permissions: `INTERNET`, `ACCESS_NETWORK_STATE`, `RECORD_AUDIO`,
|
||||
|---|---|---|
|
||||
| `libvoelin_android.so` for `aarch64-linux-android` (Slint Android backend with Skia, AAudio, AWS-LC, SQLite, libopus) | `cargo ndk -t arm64-v8a build -p voelin-android` | builds; exports `android_main` and the `Native` methods |
|
||||
| Debug APK | `./gradlew assembleDebug -Pvoelin.abis=arm64-v8a` | builds |
|
||||
| Engine host replay, voice service policy | unit tests (`cargo test -p voelin-android`) | tested |
|
||||
| Debug APK for phones and Waydroid (`arm64-v8a` + `x86_64`) | `./gradlew assembleDebug` on Linux: the Gradle 8.14.3 wrapper, Temurin JDK 17, an SDK with only `platforms;android-36`, `build-tools;36.0.0` and the NDK 27.3 | builds (Kotlin without warnings) |
|
||||
| Engine host replay, voice service policy, the voice notification's text (deafen across sessions, several servers), the live stream's notice | unit tests (`cargo test -p voelin-android`) | tested |
|
||||
| External capture providers, MediaCodec buffer layouts | `voelin-media` unit tests | tested |
|
||||
| The phone screens: voice channel with a stream, Home, Servers, Chats, Activity, You, Settings, Stream Studio, the share dialog with its sound | headless screenshots at 390×844 ([ui.md](ui.md)) | tested on the desktop (the same Slint UI; not on a device) |
|
||||
| A tapped voice notification opens the voice screen; text shared to the app lands in the composer | `VOELIN_OPEN=notification`, `VOELIN_OPEN=shared:<text>` on the desktop | the Rust side tested headless; the notifications, their actions, the share sheet and file uploads from it compile only |
|
||||
| Cameras: YUV planes borrowed, gathered into I420, turned | `voelin-media` `camera::tests::camera_planes_are_borrowed_gathered_and_turned` | the Rust side tested; Camera2, the permission flow and switching compile only |
|
||||
| The virtual display into the encoder's input surface, back to the reader for simulcast | `cargo ndk -t arm64-v8a clippy` | compiles only: frames per second and CPU use not measured (no device; Waydroid's encoders are software ones, if any) |
|
||||
| The app picker with icons | the studio's and the share dialog's picker with sample data (headless) | the UI tested; the PackageManager list and its icons compile only |
|
||||
| The app on a device: UI, voice in the background, screen sharing, watching, Keystore | manual matrix row IN3 and the Android rows | not run yet (no device or emulator in this environment) |
|
||||
| Waydroid (Mesa GL) | the debug APK, `waydroid logcat` | works with the EGL workaround (below); before it, the app ended at start because Skia could not create its GL context |
|
||||
|
||||
@@ -128,6 +184,9 @@ Known gaps:
|
||||
`Codecs` uses MediaCodec.
|
||||
- Rotating the device while sharing letterboxes the picture (the virtual
|
||||
display keeps its size).
|
||||
- Cameras deliver while the app is in front: there is no foreground service
|
||||
of type `camera`, so Android stops a camera source when the app goes to
|
||||
the background (the screen share goes on).
|
||||
- The safe area (status and navigation bars) and the on-screen keyboard pad
|
||||
the main window; dialogs drawn over it do not account for them yet.
|
||||
- Only `arm64-v8a` and `x86_64` are built; 32-bit devices are not supported.
|
||||
@@ -154,3 +213,24 @@ I RustStdoutStderr: … Could not create Skia Direct Context from GL interface
|
||||
at start, before Slint's surface, so they get slots first (logcat:
|
||||
`EGL: N of 83 Skia extension functions resolved`). Vendor GPU drivers on
|
||||
phones return nothing for desktop-only names and are not affected.
|
||||
|
||||
### Trying it on Waydroid
|
||||
|
||||
Waydroid on a PC runs the `x86_64` library, which the default
|
||||
`assembleDebug` builds (`rustup target add x86_64-linux-android` first):
|
||||
|
||||
```sh
|
||||
cd android && ./gradlew assembleDebug
|
||||
waydroid app install app/build/outputs/apk/debug/app-debug.apk
|
||||
waydroid app launch io.github.faumaray.Voelin
|
||||
waydroid logcat | grep -E 'RustStdoutStderr|MainActivity|VoiceService|ScreenCaptureService|CameraCapture'
|
||||
```
|
||||
|
||||
Things to try there: the bottom navigation (Home, Servers, Chats,
|
||||
Activity, You), joining a voice channel and its screen from the top bar's
|
||||
voice button, the voice notification (pull down the shade: Mute, Deafen,
|
||||
Leave, tap it), Share from another app's share sheet (text, then a file),
|
||||
the voice screen's Share (the screen share dialog) with sound from the
|
||||
audio picker (app icons) and its gain and mute while live, and Go Live's
|
||||
Stream Studio with a camera source (Waydroid usually has no camera: the
|
||||
source then says why).
|
||||
@@ -21,8 +21,8 @@ described in [studio.md](studio.md).
|
||||
| `AudioBuffer { samples, channels, timestamp }` | interleaved `f32`, 48 kHz |
|
||||
| `convert::to_rgba(&frame, out, stride)`, `to_rgba_vec`, `to_i420`, `psnr` | BT.601 limited range (the WebRTC default). `to_rgba` writes straight into a Slint `SharedPixelBuffer<Rgba8Pixel>` (`make_mut_bytes()`, stride `width * 4`) |
|
||||
| `Codec` | `Vp8`, `Vp9`, `H264`, `Av1`; `FromStr` for SDP/MIME names; `From`/`TryFrom` `str0m::format::Codec` with feature `str0m` |
|
||||
| `VideoEncoder` | `encode(&frame, force_keyframe) -> Vec<EncodedFrame>`; `encode_with(&frame, force_keyframe, &mut |EncodedChunk| ..)` hands out the encoder's own buffer (no copy); `set_bitrate(bps)` (libvpx: in place, no keyframe), `set_fps`, `speed()`, `codec()`, `backend()`; `gpu_alignment()` / `encode_gpu(&GpuFrame, ..)` for encoders that take frames in GPU memory (VA-API) |
|
||||
| `GpuFrame` | a picture in GPU memory (an NV12 VA-API surface), made by `ffmpeg::GpuConverter` from a captured DMA-BUF; `width`, `height`, `timestamp`, `at(timestamp)` (the same surface at another time) |
|
||||
| `VideoEncoder` | `encode(&frame, force_keyframe) -> Vec<EncodedFrame>`; `encode_with(&frame, force_keyframe, &mut |EncodedChunk| ..)` hands out the encoder's own buffer (no copy); `set_bitrate(bps)` (libvpx: in place, no keyframe), `set_fps`, `speed()`, `codec()`, `backend()`; `gpu_alignment()` / `encode_gpu(&GpuFrame, ..)` for encoders that take frames in GPU memory (VA-API; MediaCodec's surface path on Android) |
|
||||
| `GpuFrame` | a picture in GPU memory (an NV12 VA-API surface), made by `ffmpeg::GpuConverter` from a captured DMA-BUF; `width`, `height`, `timestamp`, `at(timestamp)` (the same surface at another time). On Android `rendered(width, height, timestamp)`: a screen picture the virtual display renders straight into MediaCodec's input surface, only its size and time travel |
|
||||
| `EncodedFrame { data, keyframe, pts_90khz }` | one frame for `Peer::write` |
|
||||
| `VideoDecoder` | `decode(&[u8]) -> Option<VideoFrame>` (timestamp zero; the caller knows the RTP time) |
|
||||
| `EncoderConfig { fps, bitrate_bps, keyframe_interval, content, threads, speed }` | resolution follows the frames; a size change restarts with a keyframe; `threads` is a maximum (0: all CPUs but one), still capped at one per 320x240 pixels; `speed: None` adapts libvpx `cpu-used` to the encode time |
|
||||
@@ -281,9 +281,13 @@ The audio of our stream is a mix of any number of sources
|
||||
`[{"kind": "desktop"}, {"kind": "app", "name": "firefox", "gain": 0.5},
|
||||
{"kind": "microphone", "muted": true}]`. Other kinds are `"window"` and
|
||||
`"synthetic"` (`frequency`), and an app can be given by `"pid"`. The
|
||||
default is desktop audio; `[]` shares without sound. The desktop app
|
||||
reads it when sharing starts (`media::audio_source_specs`).
|
||||
`media::audio_apps()` lists the applications for a picker.
|
||||
default is desktop audio; `[]` shares without sound. The app's share
|
||||
dialog and the Stream Studio pick and mix the sources with the same
|
||||
mixer rows and picker ([ui.md](ui.md#sound-in-the-quick-share)); a share
|
||||
hands them to its capture when it starts (`media::audio_source_specs`),
|
||||
and a running share or studio follows every change of the key through
|
||||
`Streamer::reconfigure`. `media::audio_apps()` lists the applications
|
||||
for a picker.
|
||||
|
||||
What applications play is captured by `capture::playback::start_playback`:
|
||||
|
||||
@@ -593,9 +597,32 @@ takes and returns `VideoFrame`s like the software codecs. Encoders get NV12
|
||||
`slice-height`, parsed by `codec::image_layout`, which is tested on every
|
||||
platform); H.264 is High (preferably Constrained High) without B-frames, SPS/PPS
|
||||
in front of every keyframe, keyframes on request (`request-sync`), bitrate
|
||||
changes at runtime (`video-bitrate`). Encoder order: the device's hardware
|
||||
encoders (H.264, VP9, VP8), then Google's software VP8 and H.264. Decoders
|
||||
return the newest finished picture per `decode` call (NV12 or I420).
|
||||
changes at runtime (`video-bitrate`). Encoders: the device's hardware ones
|
||||
(H.264, VP9, VP8, AV1) and Google's software VP8 and H.264 (software VP9 and
|
||||
AV1 are too slow), ordered by codec like every hardware encoder: the codecs
|
||||
every TeamSpeak client decodes (AV1, VP9, VP8) before H.264. So a phone
|
||||
without a hardware VP8, VP9 or AV1 encoder streams Google's software VP8 by
|
||||
default; a stream codec set to H.264 uses its hardware H.264 encoder.
|
||||
Decoders return the newest finished picture per `decode` call (NV12 or I420).
|
||||
|
||||
The zero-copy path for screen sharing: while it is the only MediaCodec
|
||||
encoder in the process (one simulcast layer, one codec), an encoder reports a
|
||||
`gpu_alignment`, and the capture's sink then takes `GpuFrame`s. The Android
|
||||
provider's ticker hands it one per frame at the stream's rate; for the first
|
||||
the encoder starts a codec with an input surface (`createInputSurface`,
|
||||
`COLOR_FormatSurface`, `max-fps-to-encoder` at the stream's rate,
|
||||
`repeat-previous-frame-after` 100 ms so a still screen still answers keyframe
|
||||
requests) and publishes it (`mediacodec::input_surface`); the app points its
|
||||
virtual display at that surface (`Bridge.setScreenSurface`, resized to the
|
||||
layer's size), so the compositor renders the screen into the encoder: no
|
||||
`ImageReader` frame, no RGBA to NV12 conversion, no copy. Each `GpuFrame`
|
||||
then only collects what the codec encoded since; presentation times are the
|
||||
display's (`CLOCK_MONOTONIC`), moved onto the capture's timeline. A second
|
||||
encoder (another simulcast layer, another codec a viewer chose) turns the
|
||||
path off for every encoder: the display goes back to the reader and frames
|
||||
in memory, until it is the only one again. An encoder whose surface fails to
|
||||
start stays on frames in memory. A frame-rate change restarts the surface
|
||||
codec (the cap is fixed when it starts).
|
||||
|
||||
libvpx settings follow libwebrtc's realtime setup: one pass CBR, no lag,
|
||||
`VPX_DL_REALTIME`, error resilient, keyframes only at start and on request
|
||||
@@ -664,7 +691,7 @@ found at ...").
|
||||
| Linux Wayland (`pipewire`, default) | `PortalCapture`: xdg-desktop-portal ScreenCast via `ashpd`, frames from a PipeWire video stream (LINEAR DMA-BUF or shared memory) | `PipeWireAudioCapture`: default sink monitor (`stream.capture.sink = true`) |
|
||||
| Linux wlroots (`wlroots`, default) | `WlrootsCapture`: `ext-image-copy-capture-v1`, else `wlr-screencopy-unstable-v1`, outputs only, shared memory | |
|
||||
| Windows | `WindowsCapture`: Windows Graphics Capture (`windows-capture`), monitors and windows | `WasapiLoopback`: process loopback excluding our own process tree, falling back to plain loopback |
|
||||
| Android | `ExternalScreenCapture` fed by the app (MediaProjection → `ImageReader`, RGBA; see [android.md](android.md)) | `ExternalAudioCapture` fed by the app (`AudioPlaybackCapture` of every app but ours, 48 kHz float) |
|
||||
| Android | `ExternalScreenCapture` fed by the app (MediaProjection → `ImageReader`, RGBA borrowed from the reader; or straight into the MediaCodec encoder's input surface, see [MediaCodec](#codecs); [android.md](android.md)) | `ExternalAudioCapture` fed by the app (`AudioPlaybackCapture` of every app but ours, 48 kHz float) |
|
||||
|
||||
`default_screen_capture()` picks a registered external provider first
|
||||
(`capture::external::set_screen_provider`, which the Android app calls at
|
||||
@@ -728,7 +755,8 @@ renders into one buffer, conversion and scaling write into recycled frames,
|
||||
handoffs are atomic pointer swaps, and libvpx output is borrowed. The one
|
||||
allocation per encoded frame is the `Arc<[u8]>` of `EncodedFrame`, whose size
|
||||
varies per frame and so cannot be recycled. Backends outside our control add
|
||||
their own (x11rb reply buffers; the Android provider hands owned frames).
|
||||
their own (x11rb reply buffers; the Android provider's `start` path copies
|
||||
frames into the queue, its `start_sink` path, the one streams use, does not).
|
||||
|
||||
```sh
|
||||
# The real pipeline on the test pattern, no server:
|
||||
@@ -1060,6 +1088,7 @@ has not run on Windows yet.
|
||||
| Stream mixer (latency, fade on underrun, drift correction, rate conversion, limiter, levels, live source changes), `BlockClock` | `voelin-media` `mix::tests`, `tests/mix_alloc.rs` (no allocation per block) | tested |
|
||||
| Application audio on PipeWire: desktop without our own stream, by name, by pid, a new player linked live, a quit one dropped, a restarted one matched again, the app list | `voelin-media/tests/pipewire_apps.rs` (private PipeWire, WirePlumber and D-Bus; tones told apart by frequency) | tested with PipeWire 1.0 and WirePlumber 0.4; skipped without them |
|
||||
| Streamer audio sources (mix levels, gain, mute, live change, microphone tap, window source error, silence) | `voelin-core` `media::tests::audio_sources_change_live`, `audio_sources_from_settings`, `settings::tests::audio_sources` | tested |
|
||||
| The share dialog's audio: the picked sources (gain, mute) in the capture request, none with "Share system audio" off; a running share following `stream.audio_sources` (a share without sound left so) | `voelin-ui` `streams::tests::the_share_carries_the_picked_audio`, `video::tests::a_share_follows_its_audio_sources`; headless screenshots (`share`, `share:live`) | tested; the dialog itself only in headless screenshots (nothing clicked) |
|
||||
| X11 `_NET_WM_PID` of the shared window | `tests/x11_capture.rs` under Xvfb (`VOELIN_X11_TEST_DISPLAY`) | tested |
|
||||
| WASAPI per-process loopback, audio sessions, `HWND` owner | – | type-checked for `x86_64-pc-windows-gnu` only |
|
||||
| Android per-app and all-but-ours playback capture | `cargo ndk -t arm64-v8a clippy`, `gradlew compileDebugKotlin` | compiles only (no device or emulator here) |
|
||||
@@ -1069,3 +1098,4 @@ has not run on Windows yet.
|
||||
| External capture providers (start, refusal, end of capture, default selection) | unit tests | tested |
|
||||
| MediaCodec buffer layouts (I420, NV12 with padding, `MediaImage2` NV21, crop) | unit tests (`codec::image_layout`) | tested |
|
||||
| MediaCodec encoders and decoders | – | compiles for `aarch64-linux-android` only (no device or emulator here) |
|
||||
| MediaCodec zero-copy screen path (virtual display into the encoder's input surface, back to the reader for simulcast) | `cargo ndk -t arm64-v8a clippy` | compiles only (no device or emulator here; fps and CPU not measured) |
|
||||
|
Before Width: | Height: | Size: 108 KiB After Width: | Height: | Size: 114 KiB |
|
After Width: | Height: | Size: 124 KiB |
|
Before Width: | Height: | Size: 48 KiB After Width: | Height: | Size: 48 KiB |
|
Before Width: | Height: | Size: 152 KiB After Width: | Height: | Size: 122 KiB |
|
Before Width: | Height: | Size: 98 KiB After Width: | Height: | Size: 98 KiB |
|
Before Width: | Height: | Size: 138 KiB After Width: | Height: | Size: 138 KiB |
|
Before Width: | Height: | Size: 122 KiB After Width: | Height: | Size: 121 KiB |
|
After Width: | Height: | Size: 31 KiB |
|
Before Width: | Height: | Size: 44 KiB After Width: | Height: | Size: 44 KiB |
|
Before Width: | Height: | Size: 34 KiB After Width: | Height: | Size: 40 KiB |
|
Before Width: | Height: | Size: 28 KiB After Width: | Height: | Size: 29 KiB |
|
Before Width: | Height: | Size: 42 KiB After Width: | Height: | Size: 41 KiB |
|
After Width: | Height: | Size: 15 KiB |
|
After Width: | Height: | Size: 19 KiB |
|
Before Width: | Height: | Size: 45 KiB After Width: | Height: | Size: 47 KiB |
|
Before Width: | Height: | Size: 40 KiB After Width: | Height: | Size: 38 KiB |
|
After Width: | Height: | Size: 41 KiB |
|
Before Width: | Height: | Size: 28 KiB After Width: | Height: | Size: 30 KiB |
@@ -133,6 +133,17 @@ other formats itself. Frames go through the same pacer, pool and
|
||||
background filter as on Linux. **Never run**: it is type-checked for
|
||||
`x86_64-pc-windows-gnu` only, as nothing here runs Windows.
|
||||
|
||||
Android: the app registers a `camera::CameraProvider` (Camera2 through its
|
||||
Kotlin side, [android.md](android.md#cameras)), whose cameras `list()` puts
|
||||
first (front ones first). A camera opens into an `ImageReader`
|
||||
(YUV_420_888) and its planes arrive as `camera::YuvPlanes` with the turn
|
||||
that makes the picture upright for the screen's rotation: an upright planar
|
||||
or NV12 picture goes to the source's sink as it is, NV21 and turned ones are
|
||||
gathered into I420 in a buffer each camera keeps (nothing is allocated per
|
||||
frame). `Camera::mirrored` is the default mirroring (a camera that faces the
|
||||
user; not a phone's back camera); the source menu's Switch camera moves a
|
||||
camera source to the next camera.
|
||||
|
||||
## Background replacement (`studio::segment`)
|
||||
|
||||
A source's `background` is `keep`, `blur` (`strength`: radius as a fraction
|
||||
@@ -356,7 +367,7 @@ two threads) takes about 3 ms at its own rate (15 fps by default).
|
||||
| Background blur, image and colour backdrops on the oval mask | `segment::tests` | tested |
|
||||
| Person segmentation (PP-HumanSeg through tract): loads, 192x192 mask, nobody in an empty room, time per mask | `segment::tests::the_model_finds_nobody_in_an_empty_room` | tested (about 50 ms per mask); on a photo of a person the mask follows the silhouette, arms and legs included (checked by eye, the photo is not in the repository); not yet tried with a camera |
|
||||
| Windows cameras (Media Foundation: listing, the native format nearest the wanted size, NV12 through the source reader, MJPEG decoded by it) | `cargo clippy --target x86_64-pc-windows-gnu -p voelin-media` | type-checked only, never run |
|
||||
| Android cameras | – | not implemented: `camera::list()` has only the test pattern there |
|
||||
| Android cameras (Camera2): planes borrowed, gathered or turned | `camera::tests::camera_planes_are_borrowed_gathered_and_turned` (the Rust side) | tested on the host; the Camera2 side compiles only (no device here) |
|
||||
| RTMP: the FLV tags (sizes, times past 24 bits, AVC from Annex B, `onMetaData` in AMF0), URL and key handling (the name hides the key), dead servers refused | `flv::tests`, `rtmp::tests` | tested |
|
||||
| RTMP beside another stream codec: an output asks for H.264 of its layer only, its packets reach it alone, the recording and the replay buffer keep the stream's | `studio::tests::packets_reach_the_outputs_and_the_studio_is_a_capture_backend` | tested |
|
||||
| RTMP: write errors seen (`AVIOContext.error`, found at load), an abort ends a stuck connect, the sample format field of the AAC encoder, Opus → AAC (frames back to back from the packets' clock, priming, a gap restarts the clock) | `ffmpeg::avio::tests`, `ffmpeg::audio::tests`, `ffmpeg::tests` | tested with FFmpeg 9.0.1 (libavformat 63: `error` at 84, `sample_fmt` at 348) and FFmpeg 4.4.8 (58: 120 and 408) |
|
||||
|
||||
@@ -181,6 +181,25 @@ game"), which is also what the gateway's directory shows. With sample data
|
||||
the synthetic camera with background blur, text, colours) and test tones,
|
||||
on settings in memory, and recordings go to a temporary folder.
|
||||
|
||||
### Sound in the quick share
|
||||
|
||||
The share dialog (`share`, and `share:live` for a running share) mixes its
|
||||
sound with the studio's pieces: while "Share system audio" is on (off: no
|
||||
audio at all) it shows the studio's mixer rows (`MixerRow`: meter, gain,
|
||||
mute, a menu) for `stream.audio_sources`, and Add opens the studio's picker
|
||||
(`PickDialog`) over it: the microphone, desktop audio without Voelin, the
|
||||
shared window's application, any application that plays (on Android the
|
||||
launchable apps with their icons), several at once. The rows read the
|
||||
main window's `StudioBridge`, filled without starting the studio
|
||||
(`App::mixer_show`). Starting a share hands the sources to the capture
|
||||
(`CaptureRequest::audio_sources`); while it runs the dialog shows the
|
||||
same rows with the share mixer's meters (about 15 times a second), and
|
||||
every change of `stream.audio_sources`, from the dialog or anywhere else,
|
||||
goes to the running capture at once (`Capture::follow_audio`, which calls
|
||||
`Streamer::reconfigure`). A share started without sound has no audio track
|
||||
to add sources to. With sample data `share:live` shares the test pattern
|
||||
with the sample studio's sources, live at once with sample viewers.
|
||||
|
||||
## Adding a screen
|
||||
|
||||
1. Write the screen in `ui/screens/<name>.slint` from the components
|
||||
@@ -243,7 +262,7 @@ Environment variables (see `src/dev.rs`):
|
||||
- `VOELIN_DEMO_UI=1`: sample servers, channels, members, chat with emoji and
|
||||
a stream, without a server (nothing is stored).
|
||||
- `VOELIN_OPEN=<what>[,<what>...]`: `home`, `server`, `settings[:voice|keybinds|streaming|privacy|appearance]`,
|
||||
`about`, `share`, `bookmark`, `emoji`, `client`, `panel`, `no-panel`,
|
||||
`about`, `share[:live]`, `bookmark`, `emoji`, `client`, `panel`, `no-panel`,
|
||||
`voice`, `pins`, `topics`, `topic:<id>`, `member`, `watch`, `popout`
|
||||
(the server page, above), `tab:<home|servers|chat|activity|you>` (phone
|
||||
layout). With sample data, `watch` plays the local test pattern in the
|
||||
@@ -296,13 +315,13 @@ the window's size so the pointer is not over the window, and passes
|
||||
|  |  |
|
||||
|  |  |
|
||||
|  |  |
|
||||
|  |  |
|
||||
|  | |
|
||||
|  |  |
|
||||
|  |  |
|
||||
|
||||
| Phone layout | | | | |
|
||||
|---|---|---|---|---|
|
||||
|  |  |  |  |  |
|
||||
|  | | | | |
|
||||
|  |  |  |  |  |
|
||||
|
||||
## Limits
|
||||
|
||||
|
||||
@@ -147,6 +147,9 @@ pub async fn run(con: &mut Connection, args: &StreamArgs) -> Result<()> {
|
||||
if !ServerFlavor::from_version_string(&version).capabilities().streams {
|
||||
bail!("streams need a TeamSpeak 6 server (this one is {version})");
|
||||
}
|
||||
// Every channel, as the app does: a stream can be watched from any
|
||||
// channel, and the server shows a streamer only in subscribed channels.
|
||||
con.get_state()?.server.set_subscribed(true).send(con)?;
|
||||
let mut config = if args.loopback { PeerConfig::loopback() } else { PeerConfig::default() };
|
||||
if !args.stun.is_empty() {
|
||||
config.stun_servers = args.stun.clone();
|
||||
|
||||