diff --git a/Cargo.lock b/Cargo.lock index e9cca21..4c3d9b5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -9435,6 +9435,7 @@ dependencies = [ "tokio", "tracing", "tracing-subscriber", + "tsclientlib", "voelin-core", "voelin-media", "voelin-model", @@ -9556,6 +9557,7 @@ dependencies = [ "memmap2", "ndk 0.9.0", "openh264", + "opus2", "pipewire", "reqwest", "rtrb", @@ -9578,6 +9580,8 @@ dependencies = [ "windows-capture", "x11rb", "yuv", + "zune-core", + "zune-jpeg", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index 7fbda55..e85f785 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -121,6 +121,9 @@ opt-level = 3 opt-level = 3 [profile.dev.package.wayland-client] opt-level = 3 +# MJPEG cameras: unoptimized, a 1440p picture takes most of a second. +[profile.dev.package.zune-jpeg] +opt-level = 3 [profile.dev] # Line tables (for backtraces) for workspace crates, no debug info for diff --git a/android/app/build.gradle.kts b/android/app/build.gradle.kts index 19f4bae..4612f00 100644 --- a/android/app/build.gradle.kts +++ b/android/app/build.gradle.kts @@ -34,6 +34,9 @@ val releaseStoreFile = signing("voelin.signing.storeFile", "VOELIN_SIGNING_STORE android { namespace = "io.github.faumaray.voelin" compileSdk = 36 + // What the release workflow and the Docker build install (AGP's + // default would be 35.0.0). + buildToolsVersion = "36.0.0" ndkVersion = "27.3.13750724" defaultConfig { diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml index 6716b43..4af7cc3 100644 --- a/android/app/src/main/AndroidManifest.xml +++ b/android/app/src/main/AndroidManifest.xml @@ -10,6 +10,9 @@ + + + + + + + + + diff --git a/android/app/src/main/java/io/github/faumaray/voelin/Bridge.kt b/android/app/src/main/java/io/github/faumaray/voelin/Bridge.kt index 64a199a..28b912e 100644 --- a/android/app/src/main/java/io/github/faumaray/voelin/Bridge.kt +++ b/android/app/src/main/java/io/github/faumaray/voelin/Bridge.kt @@ -4,7 +4,12 @@ import android.Manifest import android.content.Context import android.content.Intent import android.content.pm.PackageManager +import android.content.pm.ResolveInfo +import android.graphics.Bitmap +import android.graphics.Canvas import android.os.Build +import android.view.Surface +import java.io.File /** * What the Rust library (crates/voelin-android/src/bridge.rs) calls, from any @@ -30,12 +35,23 @@ object Bridge { } /** - * Run the voice service with this notification text (`muted`: the action - * offers Unmute); null stops it. + * Run the voice service with this notification (`muted`, `deafened`: the + * actions offer Unmute, Undeafen; `sinceMs`: in voice since, Unix ms, 0 + * while connecting); a null title stops it. */ @JvmStatic - fun setVoiceNotification(text: String?, muted: Boolean) { - if (text == null) VoiceService.stop(app) else VoiceService.start(app, text, muted) + fun setVoiceNotification(title: String?, text: String?, muted: Boolean, deafened: Boolean, sinceMs: Long) { + if (title == null) { + VoiceService.stop(app) + } else { + VoiceService.start(app, VoiceService.Notice(title, text ?: "", muted, deafened, sinceMs)) + } + } + + /** What the screen-sharing notification says while our stream is live; null: the default. */ + @JvmStatic + fun setScreenNotification(title: String?, text: String?) { + ScreenCaptureService.setNotice(title, text) } /** Ask the user to share the screen; the answer goes to Native.onScreenCaptureResult. */ @@ -54,6 +70,16 @@ object Bridge { ScreenCaptureService.stop(app) } + /** + * Render the shared screen into `surface` (an encoder's input, + * `width` x `height`: the zero-copy path), or with null back into the + * frame reader. + */ + @JvmStatic + fun setScreenSurface(surface: Surface?, width: Int, height: Int) { + ScreenCaptureService.redirect(surface, width, height) + } + /** Capture what the device plays; false without a running screen capture. */ @JvmStatic fun startSystemAudio(): Boolean = ScreenCaptureService.startAudio() @@ -77,7 +103,10 @@ object Bridge { ScreenCaptureService.stopInput(id) } - /** Launchable apps other than us, as "labelpackage" lines sorted by label. */ + /** + * Launchable apps other than us, as "labelpackageicon" lines + * sorted by label; the icon is a PNG in our cache (empty if it has none). + */ @JvmStatic fun launchableApps(): String { val pm = app.packageManager @@ -89,12 +118,54 @@ object Bridge { pm.queryIntentActivities(launcher, 0) } val separators = Regex("[\t\n]") + val icons = File(app.cacheDir, "app-icons").apply { mkdirs() } return activities - .map { it.activityInfo.packageName to it.loadLabel(pm).toString() } - .filter { it.first != app.packageName } - .distinctBy { it.first } - .sortedBy { it.second.lowercase() } - .joinToString("\n") { (packageName, label) -> label.replace(separators, " ") + "\t" + packageName } + .filter { it.activityInfo.packageName != app.packageName } + .distinctBy { it.activityInfo.packageName } + .map { Triple(it, it.activityInfo.packageName, it.loadLabel(pm).toString()) } + .sortedBy { it.third.lowercase() } + .joinToString("\n") { (info, packageName, label) -> + val icon = appIcon(pm, info, packageName, icons)?.path.orEmpty() + label.replace(separators, " ") + "\t" + packageName + "\t" + icon + } + } + + private const val ICON_SIZE = 96 + + /** The app's icon as a PNG in `dir`, drawn once per installed version. */ + private fun appIcon(pm: PackageManager, info: ResolveInfo, packageName: String, dir: File): File? { + val version = info.activityInfo.applicationInfo.sourceDir?.let { File(it).lastModified() } ?: 0L + val file = File(dir, "$packageName-$version.png") + if (file.exists()) return file + return try { + val bitmap = Bitmap.createBitmap(ICON_SIZE, ICON_SIZE, Bitmap.Config.ARGB_8888) + info.loadIcon(pm).apply { setBounds(0, 0, ICON_SIZE, ICON_SIZE) }.draw(Canvas(bitmap)) + file.outputStream().use { bitmap.compress(Bitmap.CompressFormat.PNG, 100, it) } + bitmap.recycle() + // Icons of earlier versions. + dir.listFiles { f -> f.name.startsWith("$packageName-") && f.name != file.name }?.forEach { it.delete() } + file + } catch (e: Exception) { + file.delete() + null + } + } + + /** The cameras, as CameraCapture.list describes them. */ + @JvmStatic + fun cameras(): String = CameraCapture.list(app) + + /** + * Open camera `cameraId` for feed `id` (Native.onCameraFrame, errors to + * Native.onCameraError); 0 x 0: its default size. + */ + @JvmStatic + fun startCamera(id: Long, cameraId: String, width: Int, height: Int, fps: Int): Boolean = + CameraCapture.start(app, id, cameraId, width, height, fps) + + @JvmStatic + fun stopCamera(id: Long) { + CameraCapture.stop(id) } @JvmStatic diff --git a/android/app/src/main/java/io/github/faumaray/voelin/CameraCapture.kt b/android/app/src/main/java/io/github/faumaray/voelin/CameraCapture.kt new file mode 100644 index 0000000..f118a91 --- /dev/null +++ b/android/app/src/main/java/io/github/faumaray/voelin/CameraCapture.kt @@ -0,0 +1,293 @@ +package io.github.faumaray.voelin + +import android.Manifest +import android.content.Context +import android.content.pm.PackageManager +import android.graphics.ImageFormat +import android.hardware.camera2.CameraCaptureSession +import android.hardware.camera2.CameraCharacteristics +import android.hardware.camera2.CameraDevice +import android.hardware.camera2.CameraManager +import android.hardware.camera2.CaptureRequest +import android.hardware.camera2.params.OutputConfiguration +import android.hardware.camera2.params.SessionConfiguration +import android.hardware.display.DisplayManager +import android.media.ImageReader +import android.os.Handler +import android.os.HandlerThread +import android.util.Log +import android.util.Range +import android.util.Size +import android.view.Display +import android.view.Surface +import java.util.concurrent.ConcurrentHashMap +import java.util.concurrent.Executor +import kotlin.math.abs + +/** + * Cameras for the Stream Studio (crates/voelin-android/src/camera.rs): + * Camera2 into an ImageReader (YUV_420_888); each frame's planes go to + * Native.onCameraFrame as direct buffers, valid during the call, so the + * Rust side converts straight from the camera's memory. Several cameras + * may run at once, each under the id the Rust side gave it. + */ +object CameraCapture { + private const val TAG = "CameraCapture" + + /** Without a wish: about this size (16:9, what the studio composes). */ + private const val DEFAULT_WIDTH = 1280 + private const val DEFAULT_HEIGHT = 720 + + private class Running(val id: Long, val cameraId: String) { + @Volatile + var stopped = false + var thread: HandlerThread? = null + var device: CameraDevice? = null + var session: CameraCaptureSession? = null + var reader: ImageReader? = null + } + + private val running = ConcurrentHashMap() + + /** Starts waiting for the CAMERA permission, by id. */ + private val waiting = ConcurrentHashMap Unit>() + + private fun facing(c: CameraCharacteristics): String = when (c.get(CameraCharacteristics.LENS_FACING)) { + CameraCharacteristics.LENS_FACING_FRONT -> "front" + CameraCharacteristics.LENS_FACING_BACK -> "back" + else -> "external" + } + + private fun sizes(c: CameraCharacteristics): List = + c.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP) + ?.getOutputSizes(ImageFormat.YUV_420_888) + ?.sortedByDescending { it.width.toLong() * it.height } + .orEmpty() + + private fun fpsRanges(c: CameraCharacteristics): List> = + c.get(CameraCharacteristics.CONTROL_AE_AVAILABLE_TARGET_FPS_RANGES)?.toList().orEmpty() + + /** + * The cameras, front ones first: "idfacingsizesmaxFps" + * lines, sizes as "1920x1080,1280x720" (largest first). + */ + fun list(context: Context): String { + val manager = context.getSystemService(CameraManager::class.java) ?: return "" + val ids = try { + manager.cameraIdList.toList() + } catch (e: Exception) { + Log.w(TAG, "cannot list the cameras", e) + return "" + } + return ids.mapNotNull { id -> + try { + val c = manager.getCameraCharacteristics(id) + val sizes = sizes(c).joinToString(",") { "${it.width}x${it.height}" } + val fps = fpsRanges(c).maxOfOrNull { it.upper } ?: 30 + Triple(id, facing(c), "$sizes\t$fps") + } catch (e: Exception) { + Log.w(TAG, "cannot ask camera $id", e) + null + } + } + .sortedBy { (_, facing, _) -> if (facing == "front") 0 else if (facing == "back") 1 else 2 } + .joinToString("\n") { (id, facing, rest) -> "$id\t$facing\t$rest" } + } + + /** + * Open `cameraId` for mixer feed `id` at about `width` x `height` (0: + * the default) and `fps`. Asks for the CAMERA permission first if + * needed; failures later go to Native.onCameraError. + */ + fun start(context: Context, id: Long, cameraId: String, width: Int, height: Int, fps: Int): Boolean { + if (context.checkSelfPermission(Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) { + return open(context, id, cameraId, width, height, fps) + } + val activity = MainActivity.current?.get() + if (activity == null) { + Native.onCameraError(id, "Allow Voelin to use the camera (open the app)") + return false + } + waiting[id] = { open(context, id, cameraId, width, height, fps) } + activity.runOnUiThread { activity.requestCameraPermission() } + return true + } + + /** The answer to the CAMERA permission prompt (MainActivity). */ + fun onPermissionResult(granted: Boolean) { + val starts = waiting.keys.toList().mapNotNull { id -> waiting.remove(id)?.let { id to it } } + for ((id, start) in starts) { + if (granted) { + start() + } else { + Native.onCameraError(id, "Voelin may not use the camera (Android settings, Apps, Voelin, Permissions)") + } + } + } + + private fun open(context: Context, id: Long, cameraId: String, width: Int, height: Int, fps: Int): Boolean { + stop(id) + val manager = context.getSystemService(CameraManager::class.java) ?: return false + val c = try { + manager.getCameraCharacteristics(cameraId) + } catch (e: Exception) { + Native.onCameraError(id, "no camera $cameraId: ${e.message}") + return false + } + val size = pick(sizes(c), width, height) ?: run { + Native.onCameraError(id, "camera $cameraId has no YUV output") + return false + } + val range = fpsRange(fpsRanges(c), fps) + val front = c.get(CameraCharacteristics.LENS_FACING) == CameraCharacteristics.LENS_FACING_FRONT + val sensor = c.get(CameraCharacteristics.SENSOR_ORIENTATION) ?: 0 + val display = context.getSystemService(DisplayManager::class.java)?.getDisplay(Display.DEFAULT_DISPLAY) + + val run = Running(id, cameraId) + running[id] = run + val thread = HandlerThread("voelin-camera-$id").also { it.start() } + run.thread = thread + val handler = Handler(thread.looper) + val executor = Executor { handler.post(it) } + val reader = ImageReader.newInstance(size.width, size.height, ImageFormat.YUV_420_888, 3) + run.reader = reader + reader.setOnImageAvailableListener({ r -> + val image = try { + r.acquireLatestImage() + } catch (e: IllegalStateException) { + null + } ?: return@setOnImageAvailableListener + try { + if (run.stopped) return@setOnImageAvailableListener + val planes = image.planes + val wanted = Native.onCameraFrame( + id, + planes[0].buffer, + planes[1].buffer, + planes[2].buffer, + planes[0].rowStride, + planes[1].rowStride, + planes[1].pixelStride, + image.width, + image.height, + rotation(sensor, front, display), + image.timestamp, + ) + if (!wanted) stop(id) + } finally { + image.close() + } + }, handler) + + val fail = { message: String -> + if (!run.stopped) Native.onCameraError(id, message) + stop(id) + } + try { + manager.openCamera(cameraId, executor, object : CameraDevice.StateCallback() { + override fun onOpened(device: CameraDevice) { + if (run.stopped) { + device.close() + return + } + run.device = device + val request = device.createCaptureRequest(CameraDevice.TEMPLATE_RECORD).apply { + addTarget(reader.surface) + if (range != null) set(CaptureRequest.CONTROL_AE_TARGET_FPS_RANGE, range) + } + val outputs = listOf(OutputConfiguration(reader.surface)) + device.createCaptureSession( + SessionConfiguration( + SessionConfiguration.SESSION_REGULAR, + outputs, + executor, + object : CameraCaptureSession.StateCallback() { + override fun onConfigured(session: CameraCaptureSession) { + if (run.stopped) { + session.close() + return + } + run.session = session + try { + session.setRepeatingRequest(request.build(), null, handler) + } catch (e: Exception) { + fail("camera $cameraId: ${e.message}") + } + } + + override fun onConfigureFailed(session: CameraCaptureSession) { + fail("camera $cameraId cannot deliver ${size.width}x${size.height}") + } + }, + ), + ) + } + + override fun onDisconnected(device: CameraDevice) { + device.close() + // Another app took it, or it was unplugged. + fail("camera $cameraId was disconnected") + } + + override fun onError(device: CameraDevice, error: Int) { + device.close() + fail("camera $cameraId failed (error $error)") + } + }) + } catch (e: SecurityException) { + fail("Voelin may not use the camera") + return false + } catch (e: Exception) { + fail("cannot open camera $cameraId: ${e.message}") + return false + } + return true + } + + fun stop(id: Long) { + waiting.remove(id) + val run = running.remove(id) ?: return + run.stopped = true + try { + run.session?.close() + run.device?.close() + } catch (e: Exception) { + Log.w(TAG, "closing camera ${run.cameraId}", e) + } + run.thread?.let { thread -> + // The reader is closed on its own thread, after the last frame. + Handler(thread.looper).post { run.reader?.close() } + thread.quitSafely() + } + } + + /** The wished size if the camera has it, else the nearest in pixels (16:9 first). */ + private fun pick(sizes: List, width: Int, height: Int): Size? { + if (sizes.isEmpty()) return null + val (w, h) = if (width > 0 && height > 0) width to height else DEFAULT_WIDTH to DEFAULT_HEIGHT + sizes.firstOrNull { it.width == w && it.height == h }?.let { return it } + val wanted = w.toLong() * h + val sameShape = sizes.filter { it.width.toLong() * h == it.height.toLong() * w } + return (sameShape.ifEmpty { sizes }).minByOrNull { abs(it.width.toLong() * it.height - wanted) } + } + + /** A fixed `fps` range if there is one, else the nearest that reaches it. */ + private fun fpsRange(ranges: List>, fps: Int): Range? = + ranges.firstOrNull { it.lower == fps && it.upper == fps } + ?: ranges.filter { it.upper >= fps }.minWithOrNull(compareBy({ it.upper }, { -it.lower })) + ?: ranges.maxByOrNull { it.upper } + + /** + * Clockwise degrees that turn the sensor's picture upright for the + * screen's current rotation (front cameras turn the other way). + */ + private fun rotation(sensor: Int, front: Boolean, display: Display?): Int { + val screen = when (display?.rotation) { + Surface.ROTATION_90 -> 90 + Surface.ROTATION_180 -> 180 + Surface.ROTATION_270 -> 270 + else -> 0 + } + return if (front) (sensor + screen) % 360 else (sensor - screen + 360) % 360 + } +} diff --git a/android/app/src/main/java/io/github/faumaray/voelin/MainActivity.kt b/android/app/src/main/java/io/github/faumaray/voelin/MainActivity.kt index 98c995c..ce89123 100644 --- a/android/app/src/main/java/io/github/faumaray/voelin/MainActivity.kt +++ b/android/app/src/main/java/io/github/faumaray/voelin/MainActivity.kt @@ -1,15 +1,24 @@ package io.github.faumaray.voelin +import android.Manifest import android.app.NativeActivity import android.content.Intent +import android.content.pm.PackageManager import android.media.projection.MediaProjectionManager +import android.net.Uri +import android.os.Build import android.os.Bundle +import android.provider.OpenableColumns +import android.util.Log +import java.io.File import java.lang.ref.WeakReference +import kotlin.concurrent.thread /** * The window: a NativeActivity running `android_main` of libvoelin_android.so * (the Slint UI). Kotlin only handles what needs an Activity: permission - * prompts and the screen-capture consent dialog. + * prompts, the screen-capture consent dialog, a tapped notification and + * what is shared to the app ("Share to Voelin"). */ class MainActivity : NativeActivity() { private var captureFps = 30 @@ -18,6 +27,14 @@ class MainActivity : NativeActivity() { override fun onCreate(savedInstanceState: Bundle?) { current = WeakReference(this) super.onCreate(savedInstanceState) + // Not again when the activity is recreated with the same intent. + if (savedInstanceState == null) handle(intent) + } + + override fun onNewIntent(intent: Intent) { + super.onNewIntent(intent) + setIntent(intent) + handle(intent) } override fun onDestroy() { @@ -34,6 +51,92 @@ class MainActivity : NativeActivity() { moveTaskToBack(true) } + /** A tapped voice notification, or something shared to us. */ + private fun handle(intent: Intent?) { + when (intent?.action) { + VoiceService.ACTION_OPEN_VOICE -> Native.onOpenVoice() + Intent.ACTION_SEND, Intent.ACTION_SEND_MULTIPLE -> share(intent) + } + } + + /** + * Text goes into the current chat's composer; files are copied out of the + * sending app (its content URIs are readable only now) into our cache, + * then uploaded to the current channel by the Rust side. + */ + private fun share(intent: Intent) { + val subject = intent.getStringExtra(Intent.EXTRA_SUBJECT)?.trim().orEmpty() + val body = intent.getCharSequenceExtra(Intent.EXTRA_TEXT)?.toString()?.trim().orEmpty() + val text = when { + subject.isEmpty() -> body + body.isEmpty() || body.contains(subject) -> body.ifEmpty { subject } + else -> "$subject\n$body" + }.ifEmpty { null } + val uris = sharedUris(intent) + if (uris.isEmpty()) { + if (text != null) Native.onShare(text, null) + return + } + val resolver = contentResolver + val dir = File(cacheDir, "shared/${System.nanoTime()}") + thread(name = "voelin-share") { + val paths = uris.mapIndexedNotNull { i, uri -> + try { + val name = displayName(uri) ?: "shared-file-${i + 1}" + // Two shared files may have the same name. + val file = File(dir, name).takeUnless { it.exists() } ?: File(dir, "${i + 1}-$name") + dir.mkdirs() + resolver.openInputStream(uri)?.use { input -> + file.outputStream().use { input.copyTo(it) } + } ?: return@mapIndexedNotNull null + file.path + } catch (e: Exception) { + Log.w(TAG, "cannot read the shared $uri", e) + null + } + } + Native.onShare(text, paths.joinToString("\n").ifEmpty { null }) + } + } + + private fun sharedUris(intent: Intent): List = if (intent.action == Intent.ACTION_SEND_MULTIPLE) { + if (Build.VERSION.SDK_INT >= 33) { + intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM, Uri::class.java) + } else { + @Suppress("DEPRECATION") + intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM) + }.orEmpty() + } else { + listOfNotNull( + if (Build.VERSION.SDK_INT >= 33) { + intent.getParcelableExtra(Intent.EXTRA_STREAM, Uri::class.java) + } else { + @Suppress("DEPRECATION") + intent.getParcelableExtra(Intent.EXTRA_STREAM) + }, + ) + } + + /** The file name the sending app gives, made safe as one path component. */ + private fun displayName(uri: Uri): String? { + val name = contentResolver.query(uri, arrayOf(OpenableColumns.DISPLAY_NAME), null, null, null)?.use { + if (it.moveToFirst()) it.getString(0) else null + } ?: uri.lastPathSegment + return name?.replace(Regex("[/\\\\\n\r\u0000]"), "_")?.trim()?.takeIf { it.isNotEmpty() && it != "." && it != ".." } + } + + /** Ask for the camera (a studio camera source); CameraCapture gets the answer. */ + fun requestCameraPermission() { + requestPermissions(arrayOf(Manifest.permission.CAMERA), REQUEST_CAMERA) + } + + override fun onRequestPermissionsResult(requestCode: Int, permissions: Array, grantResults: IntArray) { + super.onRequestPermissionsResult(requestCode, permissions, grantResults) + if (requestCode == REQUEST_CAMERA) { + CameraCapture.onPermissionResult(grantResults.firstOrNull() == PackageManager.PERMISSION_GRANTED) + } + } + /** Show the system's "start recording or casting?" dialog. */ fun requestScreenCapture(fps: Int, maxSize: Int) { captureFps = fps @@ -57,7 +160,9 @@ class MainActivity : NativeActivity() { } companion object { + private const val TAG = "MainActivity" private const val REQUEST_SCREEN_CAPTURE = 1001 + private const val REQUEST_CAMERA = 1002 /** The activity in front, if any. */ @Volatile diff --git a/android/app/src/main/java/io/github/faumaray/voelin/Native.kt b/android/app/src/main/java/io/github/faumaray/voelin/Native.kt index 7aacd8e..877b64a 100644 --- a/android/app/src/main/java/io/github/faumaray/voelin/Native.kt +++ b/android/app/src/main/java/io/github/faumaray/voelin/Native.kt @@ -49,4 +49,46 @@ object Native { /** "Mute" / "Unmute" in the voice notification. */ @JvmStatic external fun onToggleMute() + + /** "Deafen" / "Undeafen" in the voice notification. */ + @JvmStatic + external fun onToggleDeafen() + + /** + * A YUV_420_888 camera frame for feed `id`: the three planes (direct + * buffers, valid during the call), the luma and chroma row strides, the + * chroma pixel stride (1: planar, 2: interleaved), and the clockwise + * rotation that turns it upright. Returns false when it is no longer + * wanted. + */ + @JvmStatic + external fun onCameraFrame( + id: Long, + y: ByteBuffer, + u: ByteBuffer, + v: ByteBuffer, + yRowStride: Int, + uvRowStride: Int, + uvPixelStride: Int, + width: Int, + height: Int, + rotation: Int, + timestampNs: Long, + ): Boolean + + /** Camera feed `id` failed or could not start (`message`: why). */ + @JvmStatic + external fun onCameraError(id: Long, message: String) + + /** The voice notification was tapped: show the voice channel. */ + @JvmStatic + external fun onOpenVoice() + + /** + * Shared to the app ("Share to Voelin"): text for the current chat's + * composer, and copies of the shared files (one path per line) for the + * current channel. + */ + @JvmStatic + external fun onShare(text: String?, paths: String?) } diff --git a/android/app/src/main/java/io/github/faumaray/voelin/Notifications.kt b/android/app/src/main/java/io/github/faumaray/voelin/Notifications.kt index f537eee..07fedbb 100644 --- a/android/app/src/main/java/io/github/faumaray/voelin/Notifications.kt +++ b/android/app/src/main/java/io/github/faumaray/voelin/Notifications.kt @@ -12,6 +12,9 @@ object Notifications { const val CHANNEL_VOICE = "voice" const val CHANNEL_SCREEN = "screen" + /** The app's accent (Theme.accent of the UI). */ + private const val ACCENT = 0xFF2D6BFF.toInt() + fun createChannels(context: Context) { val manager = context.getSystemService(NotificationManager::class.java) manager.createNotificationChannel( @@ -30,31 +33,45 @@ object Notifications { ) } - /** Tapping a notification brings the app back. */ - private fun openApp(context: Context): PendingIntent = PendingIntent.getActivity( + /** Tapping a notification brings the app back, with `action` for MainActivity. */ + fun openApp(context: Context, action: String? = null): PendingIntent = PendingIntent.getActivity( context, - 0, - Intent(context, MainActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT), + action.hashCode(), + Intent(context, MainActivity::class.java) + .setAction(action) + .addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT), PendingIntent.FLAG_IMMUTABLE, ) - /** An ongoing notification with `actions` (title, intent). */ + /** + * An ongoing notification: `title` and `text`, a chronometer from + * `sinceMs` (Unix ms; 0: none), `actions` (title, intent). + */ fun ongoing( context: Context, channel: String, + title: String, text: String, + open: PendingIntent, + sinceMs: Long, vararg actions: Pair, ): Notification { val builder = Notification.Builder(context, channel) .setSmallIcon(R.drawable.ic_notification) - .setContentTitle(context.getString(R.string.app_name)) + .setColor(ACCENT) + .setContentTitle(title) .setContentText(text) - .setContentIntent(openApp(context)) + .setContentIntent(open) .setOngoing(true) .setOnlyAlertOnce(true) .setCategory(Notification.CATEGORY_CALL) - for ((title, intent) in actions) { - builder.addAction(Notification.Action.Builder(null, title, intent).build()) + if (sinceMs > 0) { + builder.setWhen(sinceMs).setShowWhen(true).setUsesChronometer(true) + } else { + builder.setShowWhen(false) + } + for ((label, intent) in actions) { + builder.addAction(Notification.Action.Builder(null, label, intent).build()) } return builder.build() } diff --git a/android/app/src/main/java/io/github/faumaray/voelin/ScreenCaptureService.kt b/android/app/src/main/java/io/github/faumaray/voelin/ScreenCaptureService.kt index 0daf999..b76a793 100644 --- a/android/app/src/main/java/io/github/faumaray/voelin/ScreenCaptureService.kt +++ b/android/app/src/main/java/io/github/faumaray/voelin/ScreenCaptureService.kt @@ -1,6 +1,8 @@ package io.github.faumaray.voelin import android.Manifest +import android.app.Notification +import android.app.NotificationManager import android.app.PendingIntent import android.app.Service import android.content.Context @@ -34,9 +36,10 @@ import kotlin.math.roundToInt /** * Screen sharing: holds the MediaProjection (a `mediaProjection` foreground * service, as Android requires), mirrors the display into an ImageReader and - * hands each RGBA frame to Native.onScreenFrame; optionally captures what - * other apps play (AudioPlaybackCapture: all but us, or one app) for - * Native.onSystemAudio and Native.onAudioInput. + * hands each RGBA frame to Native.onScreenFrame, or (the zero-copy path, + * Bridge.setScreenSurface) straight into an encoder's input surface; + * optionally captures what other apps play (AudioPlaybackCapture: all but + * us, or one app) for Native.onSystemAudio and Native.onAudioInput. */ class ScreenCaptureService : Service() { private var projection: MediaProjection? = null @@ -66,21 +69,9 @@ class ScreenCaptureService : Service() { return START_NOT_STICKY } if (projection != null) return START_NOT_STICKY - val stop = PendingIntent.getService( - this, - 0, - Intent(this, ScreenCaptureService::class.java).setAction(ACTION_STOP), - PendingIntent.FLAG_IMMUTABLE, - ) - val notification = Notifications.ongoing( - this, - Notifications.CHANNEL_SCREEN, - getString(R.string.screen_sharing), - getString(R.string.stop_sharing) to stop, - ) try { // Must be in the foreground before getMediaProjection (Android 14). - startForeground(ID, notification, ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PROJECTION) + startForeground(ID, notification(this), ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PROJECTION) val data = if (Build.VERSION.SDK_INT >= 33) { intent.getParcelableExtra(EXTRA_DATA, Intent::class.java) } else { @@ -159,6 +150,32 @@ class ScreenCaptureService : Service() { ) } + /** + * Point the virtual display at `surface` (an encoder's input surface, + * `width` x `height`: the screen goes into the encoder without a copy), + * or with null back at the reader, at the reader's size. + */ + @Synchronized + private fun redirectTo(surface: Surface?, width: Int, height: Int) { + val display = display ?: return + val reader = reader ?: return + val dpi = resources.displayMetrics.densityDpi + try { + // Detached while resizing, so neither consumer gets a picture of + // the other's size. + display.surface = null + if (surface != null) { + display.resize(width, height, dpi) + display.surface = surface + } else { + display.resize(reader.width, reader.height, dpi) + display.surface = reader.surface + } + } catch (e: RuntimeException) { + Log.w(TAG, "cannot point the screen at ${if (surface != null) "the encoder" else "the reader"}", e) + } + } + /** * Capture media, game and unknown-usage playback as 48 kHz stereo float: * of app `uid`, or with null of every app but us (our voices and watched @@ -259,6 +276,36 @@ class ScreenCaptureService : Service() { @Volatile private var instance: ScreenCaptureService? = null + /** Where our stream is live and who watches ("Live in Chill Zone"), or null. */ + @Volatile + private var notice: Pair? = null + + private fun notification(context: Context): Notification { + val stop = PendingIntent.getService( + context, + 0, + Intent(context, ScreenCaptureService::class.java).setAction(ACTION_STOP), + PendingIntent.FLAG_IMMUTABLE, + ) + val (title, text) = notice ?: (context.getString(R.string.screen_sharing) to context.getString(R.string.screen_sharing_text)) + return Notifications.ongoing( + context, + Notifications.CHANNEL_SCREEN, + title, + text, + Notifications.openApp(context), + 0, + context.getString(R.string.stop_sharing) to stop, + ) + } + + /** What the notification says while our stream is live (null: the default). */ + fun setNotice(title: String?, text: String?) { + notice = if (title != null) title to (text ?: "") else null + val service = instance ?: return + service.getSystemService(NotificationManager::class.java).notify(ID, notification(service)) + } + /** Start capturing with the consent the user just gave. */ fun start(context: Context, resultCode: Int, data: Intent, fps: Int, maxSize: Int) { val intent = Intent(context, ScreenCaptureService::class.java) @@ -273,6 +320,11 @@ class ScreenCaptureService : Service() { context.stopService(Intent(context, ScreenCaptureService::class.java)) } + /** See redirectTo; nothing without a running capture. */ + fun redirect(surface: Surface?, width: Int, height: Int) { + instance?.redirectTo(surface, width, height) + } + fun startAudio(): Boolean { val service = instance ?: return false return service.startAudioCapture(SYSTEM_AUDIO, null) diff --git a/android/app/src/main/java/io/github/faumaray/voelin/VoelinApp.kt b/android/app/src/main/java/io/github/faumaray/voelin/VoelinApp.kt index 848ad83..700a3ac 100644 --- a/android/app/src/main/java/io/github/faumaray/voelin/VoelinApp.kt +++ b/android/app/src/main/java/io/github/faumaray/voelin/VoelinApp.kt @@ -1,6 +1,7 @@ package io.github.faumaray.voelin import android.app.Application +import java.io.File /** The process's application object; the Rust side reaches Android through it. */ class VoelinApp : Application() { @@ -8,6 +9,8 @@ class VoelinApp : Application() { super.onCreate() instance = this Notifications.createChannels(this) + // Copies of files shared to us (MainActivity.share) from before. + File(cacheDir, "shared").deleteRecursively() } companion object { diff --git a/android/app/src/main/java/io/github/faumaray/voelin/VoiceService.kt b/android/app/src/main/java/io/github/faumaray/voelin/VoiceService.kt index b0e15d2..0f43e0f 100644 --- a/android/app/src/main/java/io/github/faumaray/voelin/VoiceService.kt +++ b/android/app/src/main/java/io/github/faumaray/voelin/VoiceService.kt @@ -15,8 +15,19 @@ import android.util.Log * Foreground service while a voice connection exists: Android keeps the * process, the network and (type microphone) the microphone of an app in * the background only this way. The Rust side starts, updates and stops it. + * Its notification is the voice bar of the app: the channel, the server and + * how many are there, the time in voice, and Mute, Deafen and Leave. */ class VoiceService : Service() { + /** What the notification shows (crates/voelin-android/src/foreground.rs). */ + data class Notice( + val title: String, + val text: String, + val muted: Boolean, + val deafened: Boolean, + val sinceMs: Long, + ) + override fun onBind(intent: Intent?): IBinder? = null override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { @@ -29,14 +40,17 @@ class VoiceService : Service() { Native.onToggleMute() return START_NOT_STICKY } + ACTION_TOGGLE_DEAFEN -> { + Native.onToggleDeafen() + return START_NOT_STICKY + } } - val text = intent?.getStringExtra(EXTRA_TEXT) ?: getString(R.string.voice_connected) - val muted = intent?.getBooleanExtra(EXTRA_MUTED, false) ?: false + val notice = notice ?: Notice(getString(R.string.voice_connected), "", false, false, 0) try { if (Build.VERSION.SDK_INT >= 30) { - startForeground(ID, notification(this, text, muted), ServiceInfo.FOREGROUND_SERVICE_TYPE_MICROPHONE) + startForeground(ID, notification(this, notice), ServiceInfo.FOREGROUND_SERVICE_TYPE_MICROPHONE) } else { - startForeground(ID, notification(this, text, muted)) + startForeground(ID, notification(this, notice)) } running = this } catch (e: RuntimeException) { @@ -56,14 +70,20 @@ class VoiceService : Service() { companion object { private const val TAG = "VoiceService" private const val ID = 1 - private const val EXTRA_TEXT = "text" - private const val EXTRA_MUTED = "muted" private const val ACTION_DISCONNECT = "io.github.faumaray.voelin.DISCONNECT" private const val ACTION_TOGGLE_MUTE = "io.github.faumaray.voelin.TOGGLE_MUTE" + private const val ACTION_TOGGLE_DEAFEN = "io.github.faumaray.voelin.TOGGLE_DEAFEN" + + /** MainActivity shows the voice channel for this action. */ + const val ACTION_OPEN_VOICE = "io.github.faumaray.voelin.OPEN_VOICE" @Volatile private var running: VoiceService? = null + /** The latest notice, for a service that is still starting. */ + @Volatile + private var notice: Notice? = null + private fun action(context: Context, action: String, request: Int): PendingIntent = PendingIntent.getService( context, @@ -72,30 +92,32 @@ class VoiceService : Service() { PendingIntent.FLAG_IMMUTABLE, ) - private fun notification(context: Context, text: String, muted: Boolean): Notification = + private fun notification(context: Context, notice: Notice): Notification = Notifications.ongoing( context, Notifications.CHANNEL_VOICE, - text, - context.getString(if (muted) R.string.unmute else R.string.mute) to + notice.title, + notice.text, + Notifications.openApp(context, ACTION_OPEN_VOICE), + notice.sinceMs, + context.getString(if (notice.muted) R.string.unmute else R.string.mute) to action(context, ACTION_TOGGLE_MUTE, 1), - context.getString(R.string.disconnect) to action(context, ACTION_DISCONNECT, 0), + context.getString(if (notice.deafened) R.string.undeafen else R.string.deafen) to + action(context, ACTION_TOGGLE_DEAFEN, 2), + context.getString(R.string.leave) to action(context, ACTION_DISCONNECT, 0), ) /** Start the service, or update its notification when it runs. */ - fun start(context: Context, text: String, muted: Boolean) { + fun start(context: Context, notice: Notice) { + this.notice = notice val service = running if (service != null) { service.getSystemService(NotificationManager::class.java) - .notify(ID, notification(service, text, muted)) + .notify(ID, notification(service, notice)) return } try { - context.startForegroundService( - Intent(context, VoiceService::class.java) - .putExtra(EXTRA_TEXT, text) - .putExtra(EXTRA_MUTED, muted), - ) + context.startForegroundService(Intent(context, VoiceService::class.java)) } catch (e: RuntimeException) { // Not allowed from the background (Android 12+). Voice is // connected from the UI, so this should not happen. @@ -104,6 +126,7 @@ class VoiceService : Service() { } fun stop(context: Context) { + notice = null context.stopService(Intent(context, VoiceService::class.java)) } } diff --git a/android/app/src/main/res/values/strings.xml b/android/app/src/main/res/values/strings.xml index 864bada..f365cd0 100644 --- a/android/app/src/main/res/values/strings.xml +++ b/android/app/src/main/res/values/strings.xml @@ -1,12 +1,16 @@ Voelin + Voelin Voice connection Screen sharing Connected to voice - Disconnect + Leave Mute Unmute + Deafen + Undeafen Sharing your screen + Starting the stream Stop sharing diff --git a/crates/voelin-android/Cargo.toml b/crates/voelin-android/Cargo.toml index 4bca1ef..7ba4c75 100644 --- a/crates/voelin-android/Cargo.toml +++ b/crates/voelin-android/Cargo.toml @@ -18,6 +18,8 @@ crate-type = ["cdylib", "rlib"] tokio = { version = "1.53.1", features = ["rt-multi-thread", "macros", "sync", "time"] } tracing = "0.1.44" voelin-core = { path = "../voelin-core" } +# Channels and people for the voice notification. +voelin-model = { path = "../voelin-model" } [target.'cfg(target_os = "android")'.dependencies] anyhow = "1.0.104" @@ -31,7 +33,8 @@ voelin-store = { path = "../voelin-store" } voelin-ui = { path = "../voelin-ui" } [dev-dependencies] -voelin-model = { path = "../voelin-model" } +# Client ids of stream viewers in the tests. +tsclientlib = { path = "../proto/tsclientlib" } [lints] workspace = true diff --git a/crates/voelin-android/src/app.rs b/crates/voelin-android/src/app.rs index 4290811..0bb4b58 100644 --- a/crates/voelin-android/src/app.rs +++ b/crates/voelin-android/src/app.rs @@ -14,7 +14,7 @@ use voelin_core::Command; use crate::foreground::Foreground; use crate::host::EngineHost; -use crate::{bridge, capture, egl, secrets}; +use crate::{bridge, camera, capture, egl, secrets}; /// Store setting (`bool`): the user's opt-in to local crash reports (read /// before the settings service starts, straight from the database). @@ -77,6 +77,7 @@ fn run(app: AndroidApp) -> anyhow::Result<()> { // Before Slint creates the first window surface. egl::reserve_skia_extension_slots(); capture::register(); + camera::register(); watch_voice(host); }); if let Err(e) = bridge::request_permissions() { @@ -108,18 +109,25 @@ fn install_crash_reports(data_dir: &Path) { voelin_platform::crash::install(data_dir.join(voelin_platform::crash::DIR_NAME), enabled); } -/// Keep the voice foreground service in step with the voice connections. +/// Keep the voice foreground service, and the screen-sharing service's +/// notification, in step with the voice connections and our stream. fn watch_voice(host: &'static EngineHost) { let mut events = host.engine().subscribe(); host.runtime().spawn(async move { loop { match events.recv().await { Ok(event) => { - if let Some(notice) = with_foreground(|f| f.update(&event)) + let changes = with_foreground(|f| f.update(&event)); + if let Some(notice) = changes.voice && let Err(e) = bridge::set_voice_notification(notice.as_ref()) { warn!("voice service: {e}"); } + if let Some(notice) = changes.screen + && let Err(e) = bridge::set_screen_notification(notice.as_ref()) + { + warn!("screen sharing notification: {e}"); + } } Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => continue, Err(tokio::sync::broadcast::error::RecvError::Closed) => break, @@ -150,3 +158,15 @@ pub fn toggle_mute() { host.engine().send(Command::SetInputMuted { session, muted: !muted }); } } + +/// "Deafen" / "Undeafen" in the voice notification, as Mute does. +pub fn toggle_deafen() { + let Some(host) = HOST.get() else { + return; + }; + let (sessions, deafened) = + with_foreground(|f| (f.voice_sessions(), f.notice().is_some_and(|n| n.deafened))); + for session in sessions { + host.engine().send(Command::SetOutputMuted { session, muted: !deafened }); + } +} diff --git a/crates/voelin-android/src/bridge.rs b/crates/voelin-android/src/bridge.rs index f7d442d..1047256 100644 --- a/crates/voelin-android/src/bridge.rs +++ b/crates/voelin-android/src/bridge.rs @@ -15,7 +15,7 @@ use jni::refs::{Global, Reference as _}; use jni::sys::{jboolean, jint, jlong}; use jni::{Env, JavaVM, jni_sig, jni_str, native_method}; -use crate::foreground::VoiceNotice; +use crate::foreground::{ScreenNotice, VoiceNotice}; static BRIDGE: OnceLock>> = OnceLock::new(); @@ -58,18 +58,90 @@ pub fn request_permissions() -> Result<()> { }) } +/// A Java string, or `null` for `None`. +fn string_or_null<'local>(env: &mut Env<'local>, text: Option<&str>) -> Result> { + Ok(match text { + Some(text) => JObject::from(env.new_string(text)?), + None => JObject::null(), + }) +} + /// Show or update the voice service's notification; `None` stops the service. pub fn set_voice_notification(notice: Option<&VoiceNotice>) -> Result<()> { with_bridge(|env, class| { - let (text, muted) = match notice { - Some(n) => (JObject::from(env.new_string(&n.text)?), n.muted), - None => (JObject::null(), false), - }; + let title = string_or_null(env, notice.map(|n| n.title.as_str()))?; + let text = string_or_null(env, notice.map(|n| n.text.as_str()))?; + let (muted, deafened, since) = + notice.map_or((false, false, 0), |n| (n.muted, n.deafened, n.since_ms)); env.call_static_method( class, jni_str!("setVoiceNotification"), - jni_sig!((text: java.lang.String, muted: jboolean) -> void), - &[JValue::Object(&text), JValue::Bool(muted)], + jni_sig!( + ( + title: java.lang.String, + text: java.lang.String, + muted: jboolean, + deafened: jboolean, + since_ms: jlong, + ) -> void + ), + &[ + JValue::Object(&title), + JValue::Object(&text), + JValue::Bool(muted), + JValue::Bool(deafened), + JValue::Long(since as jlong), + ], + )?; + Ok(()) + }) +} + +/// What the screen-sharing notification says while our stream is live; +/// `None` puts back the plain "sharing your screen". +pub fn set_screen_notification(notice: Option<&ScreenNotice>) -> Result<()> { + with_bridge(|env, class| { + let title = string_or_null(env, notice.map(|n| n.title.as_str()))?; + let text = string_or_null(env, notice.map(|n| n.text.as_str()))?; + env.call_static_method( + class, + jni_str!("setScreenNotification"), + jni_sig!((title: java.lang.String, text: java.lang.String) -> void), + &[JValue::Object(&title), JValue::Object(&text)], + )?; + Ok(()) + }) +} + +/// Point the screen's virtual display at an encoder's input surface (the +/// zero-copy path), or back at the frame reader with `None`. +pub fn set_screen_surface( + surface: Option<&voelin_media::codec::mediacodec::InputSurface>, +) -> Result<()> { + with_bridge(|env, class| { + let (object, width, height) = match surface { + Some(surface) => { + // SAFETY: `env` is this thread's JNI environment, and the + // window stays alive (`surface` holds a reference) while + // Java makes a Surface of it. + #[allow(unsafe_code)] + let raw = unsafe { surface.window.to_surface(env.get_raw().cast()) }; + if raw.is_null() { + return Err(Error::NullPtr("encoder surface")); + } + // SAFETY: `raw` is a new local reference to an + // android.view.Surface of this frame. + #[allow(unsafe_code)] + let object = unsafe { JObject::from_raw(env, raw.cast()) }; + (object, surface.width, surface.height) + } + None => (JObject::null(), 0, 0), + }; + env.call_static_method( + class, + jni_str!("setScreenSurface"), + jni_sig!((surface: android.view.Surface, width: jint, height: jint) -> void), + &[JValue::Object(&object), JValue::Int(width as jint), JValue::Int(height as jint)], )?; Ok(()) }) @@ -143,8 +215,9 @@ pub fn stop_audio_input(id: u64) -> Result<()> { }) } -/// Launchable apps other than ours, as `(label, package)`, sorted by label. -pub fn launchable_apps() -> Result> { +/// Launchable apps other than ours, as `(label, package, icon)`, sorted by +/// label; `icon` is the path of a PNG in the app's cache, or empty. +pub fn launchable_apps() -> Result> { let lines = with_bridge(|env, class| { let value = env .call_static_method( @@ -163,19 +236,71 @@ pub fn launchable_apps() -> Result> { Ok(parse_apps(&lines)) } -/// `labelpackage` lines. -fn parse_apps(lines: &str) -> Vec<(String, String)> { +/// `labelpackageicon` lines (the icon may be missing). +fn parse_apps(lines: &str) -> Vec<(String, String, String)> { lines .lines() .filter_map(|line| { - let (label, package) = line.split_once('\t')?; - let package = package.trim(); - let label = if label.trim().is_empty() { package } else { label.trim() }; - (!package.is_empty()).then(|| (label.to_owned(), package.to_owned())) + let mut parts = line.split('\t'); + let label = parts.next()?.trim(); + let package = parts.next()?.trim(); + let icon = parts.next().unwrap_or_default().trim(); + let label = if label.is_empty() { package } else { label }; + (!package.is_empty()).then(|| (label.to_owned(), package.to_owned(), icon.to_owned())) }) .collect() } +/// The cameras (`CameraCapture.list`): `idfacingsizesmaxFps` +/// lines. +pub fn cameras() -> Result { + with_bridge(|env, class| { + let value = env + .call_static_method(class, jni_str!("cameras"), jni_sig!(() -> java.lang.String), &[])? + .l()?; + if value.is_null() { + return Ok(String::new()); + } + let value = env.cast_local::(value)?; + value.try_to_string(env) + }) +} + +/// Open camera `device` for feed `id` (frames to `Native.onCameraFrame`, +/// later failures to `Native.onCameraError`); 0 x 0: its default size. +pub fn start_camera(id: u64, device: &str, width: u32, height: u32, fps: u32) -> Result { + with_bridge(|env, class| { + let device = JObject::from(env.new_string(device)?); + env.call_static_method( + class, + jni_str!("startCamera"), + jni_sig!( + (id: jlong, camera_id: java.lang.String, width: jint, height: jint, fps: jint) -> jboolean + ), + &[ + JValue::Long(id as jlong), + JValue::Object(&device), + JValue::Int(width as jint), + JValue::Int(height as jint), + JValue::Int(fps as jint), + ], + )? + .z() + }) +} + +pub fn stop_camera(id: u64) -> Result<()> { + with_bridge(|env, class| { + env.call_static_method( + class, + jni_str!("stopCamera"), + jni_sig!((id: jlong) -> void), + &[JValue::Long(id as jlong)], + )?; + Ok(()) + }) +} + pub fn secret_get(key: &str) -> Result> { with_bridge(|env, class| { let key = JObject::from(env.new_string(key)?); @@ -271,9 +396,10 @@ fn on_screen_frame<'local>( return Err(Error::NullPtr("screen frame buffer")); } // SAFETY: a direct buffer's memory is `capacity` bytes at `address`, and - // the `Image` it belongs to stays open until this call returns. + // the `Image` it belongs to stays open until this call returns (the + // frame is borrowed only during it). #[allow(unsafe_code)] - let bytes = unsafe { std::slice::from_raw_parts(address, capacity) }.to_vec(); + let bytes = unsafe { std::slice::from_raw_parts(address, capacity) }; Ok(crate::capture::on_frame( bytes, width.max(0) as u32, @@ -331,7 +457,9 @@ fn on_audio_input<'local>( channels: jint, ) -> Result { thread_local! { - // One per capture thread, reused for every call. + // One per capture thread, reused for every call. (It is `const`; + // clippy for Android does not see that through the expansion.) + #[allow(clippy::missing_const_for_thread_local)] static BUFFER: std::cell::RefCell> = const { std::cell::RefCell::new(Vec::new()) }; } let id = id as u64; @@ -345,6 +473,101 @@ fn on_audio_input<'local>( }) } +/// The memory of a direct buffer: its address and capacity. +fn direct(env: &Env<'_>, buffer: &JByteBuffer<'_>, what: &'static str) -> Result<(*mut u8, usize)> { + let address = env.get_direct_buffer_address(buffer)?; + if address.is_null() { + return Err(Error::NullPtr(what)); + } + Ok((address, env.get_direct_buffer_capacity(buffer)?)) +} + +const _: jni::NativeMethod = native_method! { + java_type = "io.github.faumaray.voelin.Native", + static extern fn on_camera_frame( + id: jlong, + y: JByteBuffer, + u: JByteBuffer, + v: JByteBuffer, + y_row_stride: jint, + uv_row_stride: jint, + uv_pixel_stride: jint, + width: jint, + height: jint, + rotation: jint, + timestamp_ns: jlong, + ) -> jboolean, +}; + +/// A YUV_420_888 camera frame (see `crate::camera`). Returns `false` once +/// it is no longer wanted. +#[allow(clippy::too_many_arguments)] +fn on_camera_frame<'local>( + env: &mut Env<'local>, + _class: JClass<'local>, + id: jlong, + y: JByteBuffer<'local>, + u: JByteBuffer<'local>, + v: JByteBuffer<'local>, + y_row_stride: jint, + uv_row_stride: jint, + uv_pixel_stride: jint, + width: jint, + height: jint, + rotation: jint, + timestamp_ns: jlong, +) -> Result { + let (y_at, y_len) = direct(env, &y, "camera luma")?; + let (u_at, u_len) = direct(env, &u, "camera U")?; + let (v_at, v_len) = direct(env, &v, "camera V")?; + let step = uv_pixel_stride.max(1) as usize; + // SAFETY: a direct buffer's memory is `capacity` bytes at its address, + // and the `Image` the planes belong to stays open until this call + // returns. With V one byte after U (interleaved, U first), U's address + // and V's length plus one span both planes up to the end of V's buffer: + // memory of the same image. + #[allow(unsafe_code)] + let (y, u, v, nv12) = unsafe { + let nv12 = (step == 2 && v_at as usize == u_at as usize + 1) + .then(|| std::slice::from_raw_parts(u_at, v_len + 1)); + ( + std::slice::from_raw_parts(y_at, y_len), + std::slice::from_raw_parts(u_at, u_len), + std::slice::from_raw_parts(v_at, v_len), + nv12, + ) + }; + let planes = voelin_media::studio::camera::YuvPlanes { + width: width.max(0) as u32, + height: height.max(0) as u32, + y, + y_stride: y_row_stride.max(0) as usize, + u, + v, + uv_stride: uv_row_stride.max(0) as usize, + uv_step: step, + nv12, + rotation: rotation.max(0) as u32, + }; + Ok(crate::camera::on_frame(id as u64, &planes, timestamp_ns)) +} + +const _: jni::NativeMethod = native_method! { + java_type = "io.github.faumaray.voelin.Native", + static extern fn on_camera_error(id: jlong, message: JString), +}; + +fn on_camera_error<'local>( + env: &mut Env<'local>, + _class: JClass<'local>, + id: jlong, + message: JString<'local>, +) -> Result<()> { + let message = if message.is_null() { String::new() } else { message.try_to_string(env)? }; + crate::camera::on_error(id as u64, message); + Ok(()) +} + const _: jni::NativeMethod = native_method! { java_type = "io.github.faumaray.voelin.Native", static extern fn on_disconnect_voice(), @@ -366,3 +589,45 @@ fn on_toggle_mute<'local>(_env: &mut Env<'local>, _class: JClass<'local>) -> Res crate::app::toggle_mute(); Ok(()) } + +const _: jni::NativeMethod = native_method! { + java_type = "io.github.faumaray.voelin.Native", + static extern fn on_toggle_deafen(), +}; + +/// "Deafen" / "Undeafen" in the voice notification. +fn on_toggle_deafen<'local>(_env: &mut Env<'local>, _class: JClass<'local>) -> Result<()> { + crate::app::toggle_deafen(); + Ok(()) +} + +const _: jni::NativeMethod = native_method! { + java_type = "io.github.faumaray.voelin.Native", + static extern fn on_open_voice(), +}; + +/// The voice notification was tapped: show the voice channel. +fn on_open_voice<'local>(_env: &mut Env<'local>, _class: JClass<'local>) -> Result<()> { + voelin_ui::request(voelin_ui::Request::ShowVoice); + Ok(()) +} + +const _: jni::NativeMethod = native_method! { + java_type = "io.github.faumaray.voelin.Native", + static extern fn on_share(text: JString, paths: JString), +}; + +/// Shared to the app: text, and copies of the shared files (one path per +/// line). +fn on_share<'local>( + env: &mut Env<'local>, + _class: JClass<'local>, + text: JString<'local>, + paths: JString<'local>, +) -> Result<()> { + let text = if text.is_null() { None } else { Some(text.try_to_string(env)?) }; + let paths = if paths.is_null() { String::new() } else { paths.try_to_string(env)? }; + let files = paths.lines().filter(|l| !l.is_empty()).map(std::path::PathBuf::from).collect(); + voelin_ui::request(voelin_ui::Request::Share { text, files }); + Ok(()) +} diff --git a/crates/voelin-android/src/camera.rs b/crates/voelin-android/src/camera.rs new file mode 100644 index 0000000..15c38ec --- /dev/null +++ b/crates/voelin-android/src/camera.rs @@ -0,0 +1,174 @@ +//! Cameras for the Stream Studio through Camera2. +//! +//! Registered as the studio's [`CameraProvider`]: the studio's camera +//! picker lists the device's cameras (front ones first; a back camera is +//! not mirrored by default), and a camera source opens one. +//! `CameraCapture.kt` asks for the CAMERA permission if needed, opens the +//! camera into an `ImageReader` (YUV_420_888) and hands each frame's planes +//! to [`on_frame`] as direct buffers valid during the call, with the turn +//! that makes it upright for the screen's rotation. The studio's sink +//! converts straight from the camera's memory when the picture is upright +//! and planar or NV12; otherwise it is gathered (and turned) into a buffer +//! each camera keeps, so a running camera allocates nothing per frame. + +use std::collections::HashMap; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::{Arc, Mutex, MutexGuard, PoisonError}; +use std::time::Duration; + +use tracing::warn; +use voelin_media::capture::FrameSink; +use voelin_media::studio::camera::{Camera, CameraProvider, Format, Pixel, YuvPlanes}; +use voelin_media::studio::compose::Feed; +use voelin_media::{Error, Result}; + +use crate::bridge; + +const BACKEND: &str = "camera2"; + +struct Running { + sink: Box, + feed: Arc, + /// Clock origin of the frames' timestamps (`Image.timestamp`). + origin_ns: Option, + /// Gathered or turned pictures (I420), reused. + scratch: Vec, +} + +static RUNNING: Mutex>> = Mutex::new(None); + +fn running() -> MutexGuard<'static, Option>> { + RUNNING.lock().unwrap_or_else(PoisonError::into_inner) +} + +/// Make Camera2 the studio's cameras. +pub fn register() { + voelin_media::studio::camera::set_provider(Some(Arc::new(Camera2))); +} + +struct Camera2; + +/// Stops its camera when dropped. +struct Guard(u64); + +impl Drop for Guard { + fn drop(&mut self) { + running().as_mut().map(|r| r.remove(&self.0)); + if let Err(e) = bridge::stop_camera(self.0) { + warn!("stopping camera {}: {e}", self.0); + } + } +} + +impl CameraProvider for Camera2 { + fn name(&self) -> &'static str { + BACKEND + } + + fn list(&self) -> Vec { + match bridge::cameras() { + Ok(lines) => parse(&lines), + Err(e) => { + warn!("listing cameras: {e}"); + Vec::new() + } + } + } + + fn start( + &self, + device: &str, + size: Option<(u32, u32)>, + fps: u32, + sink: Box, + feed: Arc, + ) -> Result> { + static NEXT: AtomicU64 = AtomicU64::new(1); + let id = NEXT.fetch_add(1, Ordering::Relaxed); + let entry = Running { sink, feed, origin_ns: None, scratch: Vec::new() }; + running().get_or_insert_with(HashMap::new).insert(id, entry); + let (width, height) = size.unwrap_or((0, 0)); + match bridge::start_camera(id, device, width, height, fps) { + Ok(true) => Ok(Box::new(Guard(id))), + started => { + running().as_mut().map(|r| r.remove(&id)); + let reason = match started { + Err(e) => e.to_string(), + _ => format!("camera {device:?} cannot be opened"), + }; + Err(Error::CaptureUnavailable { backend: BACKEND, reason }) + } + } + } +} + +/// `idfacingsizesmaxFps` lines (`CameraCapture.list`). +fn parse(lines: &str) -> Vec { + let mut seen: HashMap = HashMap::new(); + lines + .lines() + .filter_map(|line| { + let mut parts = line.split('\t'); + let id = parts.next()?.trim(); + let facing = parts.next()?.trim(); + let sizes = parts + .next() + .unwrap_or_default() + .split(',') + .filter_map(|s| { + let (w, h) = s.trim().split_once('x')?; + Some((w.parse().ok()?, h.parse().ok()?)) + }) + .collect::>(); + let max_fps = parts.next().and_then(|f| f.trim().parse().ok()).unwrap_or(0); + if id.is_empty() { + return None; + } + let label = match facing { + "front" => "Front camera", + "back" => "Back camera", + _ => "External camera", + }; + let n = seen.entry(label.to_owned()).or_insert(0); + *n += 1; + let name = if *n == 1 { label.to_owned() } else { format!("{label} {n}") }; + Some(Camera { + id: id.to_owned(), + name, + backend: BACKEND, + formats: vec![Format { pixel: Pixel::I420, sizes, max_fps }], + // What faces the user is mirrored, as a mirror would be. + mirrored: facing != "back", + }) + }) + .collect() +} + +/// A frame of camera `id`. Returns `false` once it is no longer wanted. +pub fn on_frame(id: u64, planes: &YuvPlanes<'_>, timestamp_ns: i64) -> bool { + let mut guard = running(); + let Some(run) = guard.as_mut().and_then(|r| r.get_mut(&id)) else { return false }; + let Running { sink, feed, origin_ns, scratch } = run; + if feed.is_closed() { + return false; + } + let origin = *origin_ns.get_or_insert(timestamp_ns); + let timestamp = Duration::from_nanos(u64::try_from(timestamp_ns - origin).unwrap_or(0)); + if !sink.wants(timestamp) { + return true; + } + match planes.frame(timestamp, scratch) { + Ok(frame) => sink.frame(frame), + Err(e) => { + warn!("dropping a camera frame: {e}"); + true + } + } +} + +/// Camera `id` failed (or could not open): the studio shows why. +pub fn on_error(id: u64, message: String) { + if let Some(run) = running().as_ref().and_then(|r| r.get(&id)) { + run.feed.set_error(Error::Capture { backend: BACKEND, message }); + } +} diff --git a/crates/voelin-android/src/capture.rs b/crates/voelin-android/src/capture.rs index a52d8d7..744695c 100644 --- a/crates/voelin-android/src/capture.rs +++ b/crates/voelin-android/src/capture.rs @@ -4,23 +4,38 @@ //! `voelin_media::capture::default_screen_capture()` as on desktop. Starting //! asks the Kotlin side for the user's consent; on consent it runs //! `ScreenCaptureService` (a `mediaProjection` foreground service) whose -//! `ImageReader` hands RGBA frames to [`on_frame`]. System audio -//! (`AudioPlaybackCapture`, 48 kHz float) needs that running projection: -//! everything but our own uid, or one app's uid, each into a stream mixer -//! input ([`on_input`]); several captures may run at once. +//! virtual display renders into an `ImageReader`, whose RGBA frames come to +//! [`on_frame`]. A stream's sink takes them borrowed, converting straight +//! from the reader's buffer. +//! +//! The zero-copy path: while every encoder the sink feeds takes pictures +//! straight from the screen ([`FrameSink::accepts_gpu`]: one MediaCodec +//! encoder, see `voelin_media::codec::mediacodec`), a ticker at the +//! stream's frame rate tells the sink a picture is due; the first one makes +//! the encoder publish its input surface, and the virtual display is +//! pointed at it, so the screen goes from the compositor into the encoder +//! without a copy. When that stops (a second simulcast layer or codec, the +//! encoder gone or failed) the display goes back to the reader. +//! +//! System audio (`AudioPlaybackCapture`, 48 kHz float) needs that running +//! projection: everything but our own uid, or one app's uid, each into a +//! stream mixer input ([`on_input`]); several captures may run at once. use std::collections::HashMap; use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::{Arc, Mutex, MutexGuard, PoisonError}; -use std::time::Duration; +use std::time::{Duration, Instant}; use tokio::sync::oneshot; -use tracing::warn; +use tracing::{debug, warn}; use voelin_media::capture::external::{self, AudioProvider, ScreenProvider}; use voelin_media::capture::playback::{AppMatch, AudioApp, PlaybackFilter}; -use voelin_media::capture::{BoxFuture, CaptureOptions, CaptureSource, SourceId}; +use voelin_media::capture::{BoxFuture, CaptureOptions, CaptureSource, FrameSink, SourceId}; +use voelin_media::codec::mediacodec::{self, InputSurface}; use voelin_media::mix::SourceInput; -use voelin_media::{AudioBuffer, Error, FrameSender, Result, VideoFrame}; +use voelin_media::{ + AudioBuffer, Error, FrameRef, FrameSender, GpuFrame, PixelsRef, PlaneRef, Result, VideoFrame, +}; use crate::bridge; @@ -50,6 +65,29 @@ fn with_state(f: impl FnOnce(&mut State) -> R) -> R { f(guard.get_or_insert_with(State::default)) } +/// The screen's consumer of [`ScreenProvider::start_sink`], apart from the +/// audio state so that converting a frame does not hold up audio. +#[derive(Default)] +struct Video { + sink: Option>, + /// The ticker that serves this sink. + ticker: u64, + /// Size of the captured screen (the reader's), once a frame came. + size: (u32, u32), + /// The last frame's time and when it came: the ticker's pictures + /// continue that clock. + last: Option<(Duration, Instant)>, + /// The encoder surface the display renders into (its generation). + rendering: Option, +} + +static VIDEO: Mutex> = Mutex::new(None); + +fn with_video(f: impl FnOnce(&mut Video) -> R) -> R { + let mut guard = VIDEO.lock().unwrap_or_else(PoisonError::into_inner); + f(guard.get_or_insert_with(Video::default)) +} + /// Make MediaProjection the default screen and audio capture. pub fn register() { external::set_screen_provider(Some(Arc::new(Projection))); @@ -63,6 +101,22 @@ fn since(first: &mut Option, now_ns: i64) -> Duration { struct Projection; +impl Projection { + /// Ask for consent; `Ok` once the capture runs. + fn request(options: &CaptureOptions, tx: oneshot::Sender>) -> Result<()> { + with_state(|s| { + if let Some(previous) = s.pending.replace(tx) { + let _ = previous.send(Err(Error::Cancelled)); + } + s.origin_ns = None; + }); + bridge::request_screen_capture(options.fps.clamp(1, 60), MAX_SIZE).map_err(|e| { + with_state(|s| s.pending = None); + Error::CaptureUnavailable { backend: SCREEN, reason: e.to_string() } + }) + } +} + impl ScreenProvider for Projection { fn name(&self) -> &'static str { SCREEN @@ -86,20 +140,35 @@ impl ScreenProvider for Projection { frames: FrameSender, ) -> BoxFuture<'static, Result<()>> { let (tx, rx) = oneshot::channel(); - with_state(|s| { - if let Some(previous) = s.pending.replace(tx) { - let _ = previous.send(Err(Error::Cancelled)); - } - s.frames = Some(frames); - s.origin_ns = None; - }); - if let Err(e) = bridge::request_screen_capture(options.fps.clamp(1, 60), MAX_SIZE) { - with_state(|s| { - s.pending = None; - s.frames = None; - }); - let error = Error::CaptureUnavailable { backend: SCREEN, reason: e.to_string() }; - return Box::pin(async move { Err(error) }); + with_video(|v| v.sink = None); + with_state(|s| s.frames = Some(frames)); + if let Err(e) = Self::request(options, tx) { + with_state(|s| s.frames = None); + return Box::pin(async move { Err(e) }); + } + Box::pin(async move { rx.await.unwrap_or(Err(Error::Cancelled)) }) + } + + fn start_sink( + &self, + _source: &SourceId, + options: &CaptureOptions, + sink: Box, + ) -> BoxFuture<'static, Result<()>> { + static TICKERS: AtomicU64 = AtomicU64::new(1); + let (tx, rx) = oneshot::channel(); + with_state(|s| s.frames = None); + let ticker = TICKERS.fetch_add(1, Ordering::Relaxed); + with_video(|v| *v = Video { sink: Some(sink), ticker, ..Video::default() }); + if let Err(e) = Self::request(options, tx) { + with_video(|v| v.sink = None); + return Box::pin(async move { Err(e) }); + } + if let Err(e) = std::thread::Builder::new() + .name("voelin-screen-ticker".into()) + .spawn(move || run_ticker(ticker)) + { + warn!("no zero-copy screen path: {e}"); } Box::pin(async move { rx.await.unwrap_or(Err(Error::Cancelled)) }) } @@ -112,6 +181,64 @@ impl ScreenProvider for Projection { } } +/// The zero-copy path's ticker (see the [module docs](self)): runs until +/// its sink is gone or replaced. +fn run_ticker(id: u64) { + loop { + let mut redirect: Option> = None; + let interval = with_video(|v| { + if v.ticker != id { + return None; + } + let Some(sink) = v.sink.as_mut() else { + // Back to the reader, whose next frame stops the service. + if v.rendering.take().is_some() { + redirect = Some(None); + } + return None; + }; + let interval = Duration::from_secs(1) / sink.max_fps().max(1); + let (width, height) = v.size; + if width == 0 { + // No frame yet. + return Some(interval); + } + if !sink.accepts_gpu() { + if v.rendering.take().is_some() { + debug!("screen back to frames in memory"); + redirect = Some(None); + } + return Some(interval); + } + // The encoder makes its surface for the first picture. + match (mediacodec::input_surface(), v.rendering) { + (Some(surface), rendering) if rendering != Some(surface.generation) => { + debug!(surface.width, surface.height, "screen straight into the encoder"); + v.rendering = Some(surface.generation); + redirect = Some(Some(surface)); + } + (None, Some(_)) => { + v.rendering = None; + redirect = Some(None); + } + _ => {} + } + let timestamp = v.last.map_or(Duration::ZERO, |(at, when)| at + when.elapsed()); + if sink.wants(timestamp) && !sink.gpu(GpuFrame::rendered(width, height, timestamp)) { + v.sink = None; + } + Some(interval) + }); + if let Some(target) = redirect + && let Err(e) = bridge::set_screen_surface(target.as_ref()) + { + warn!("pointing the screen at the encoder: {e}"); + } + let Some(interval) = interval else { return }; + std::thread::sleep(interval); + } +} + struct PlaybackAudio; impl AudioProvider for PlaybackAudio { @@ -196,9 +323,10 @@ impl AudioProvider for PlaybackAudio { match bridge::launchable_apps() { Ok(apps) => apps .into_iter() - .map(|(name, package)| AudioApp { + .map(|(name, package, icon)| AudioApp { name, binary: Some(package), + icon: (!icon.is_empty()).then_some(icon), ..AudioApp::default() }) .collect(), @@ -230,6 +358,9 @@ pub fn on_input(id: u64, samples: &[f32], channels: u16) -> bool { /// The user answered the consent dialog (or the service failed to start). pub fn on_result(granted: bool, error: Option) { + if !granted { + with_video(|v| v.sink = None); + } with_state(|s| { let result = match (granted, error) { (true, _) => Ok(()), @@ -246,23 +377,49 @@ pub fn on_result(granted: bool, error: Option) { } pub fn wants_frames() -> bool { - with_state(|s| s.frames.as_ref().is_some_and(|f| !f.is_closed())) + with_video(|v| v.sink.is_some()) + || with_state(|s| s.frames.as_ref().is_some_and(|f| !f.is_closed())) } -/// A captured RGBA frame. Returns `false` once nobody wants frames. -pub fn on_frame( - pixels: Vec, - width: u32, - height: u32, - stride: usize, - timestamp_ns: i64, -) -> bool { - with_state(|s| { +/// A captured RGBA frame, valid during the call. Returns `false` once +/// nobody wants frames. +pub fn on_frame(pixels: &[u8], width: u32, height: u32, stride: usize, timestamp_ns: i64) -> bool { + let timestamp = with_state(|s| { let timestamp = since(&mut s.origin_ns, timestamp_ns); + if let Some(origin) = s.origin_ns { + mediacodec::set_screen_origin(origin); + } + timestamp + }); + let taken = with_video(|v| { + let sink = v.sink.as_mut()?; + v.size = (width, height); + v.last = Some((timestamp, Instant::now())); + // While the screen renders into the encoder, what still reaches + // the reader is not used. + if sink.accepts_gpu() || !sink.wants(timestamp) { + return Some(true); + } + let pixels = PixelsRef::Rgba(PlaneRef::new(pixels, stride)); + let frame = FrameRef { width, height, timestamp, pixels }; + if let Err(e) = frame.validate() { + warn!("dropping a screen frame: {e}"); + return Some(true); + } + if !sink.frame(frame) { + v.sink = None; + return Some(false); + } + Some(true) + }); + if let Some(more) = taken { + return more; + } + with_state(|s| { let Some(frames) = &s.frames else { return false; }; - match VideoFrame::from_rgba(width, height, stride, pixels) { + match VideoFrame::from_rgba(width, height, stride, pixels.to_vec()) { Ok(frame) => { if !frames.send(frame.with_timestamp(timestamp)) { s.frames = None; @@ -278,6 +435,7 @@ pub fn on_frame( /// The projection ended (stopped by us, the user, or the system): the /// consumers see their channels close. pub fn on_stopped() { + with_video(|v| v.sink = None); with_state(|s| { s.frames = None; s.audio = None; diff --git a/crates/voelin-android/src/foreground.rs b/crates/voelin-android/src/foreground.rs index bd6bc1f..e48434e 100644 --- a/crates/voelin-android/src/foreground.rs +++ b/crates/voelin-android/src/foreground.rs @@ -1,20 +1,49 @@ -//! When the app needs its voice foreground service. +//! What the app's foreground services show. //! //! Android keeps the microphone and the process of a backgrounded app only -//! while a foreground service with a visible notification runs. The service -//! runs while any session has a voice connection (connecting or connected); -//! its notification names the servers and offers Mute and Disconnect. +//! while a foreground service with a visible notification runs. The voice +//! service runs while any session has a voice connection (connecting or +//! connected); its notification names the channel and the server, counts +//! the people there and offers Mute, Deafen and Leave. While our stream is +//! live, the screen-sharing service's notification says where it goes and +//! how many watch. use std::collections::BTreeMap; +use std::sync::Arc; +use voelin_core::stream::{StreamState, ViewerInfo, ViewerState}; use voelin_core::{Event, SessionId, VoiceState}; +use voelin_model::Presence; /// What the voice notification shows. #[derive(Clone, Debug, PartialEq, Eq)] pub struct VoiceNotice { + /// The channel we are in ("Chill Zone"), or what is going on. + pub title: String, + /// The server and how many are in the channel. pub text: String, /// The microphone is muted in every voice session (the action unmutes). pub muted: bool, + /// The sound is off in every voice session (the action turns it on). + pub deafened: bool, + /// When the first voice session connected (Unix ms), for the elapsed + /// time; 0 while connecting. + pub since_ms: u64, +} + +/// What the screen-sharing notification shows while our stream is live. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ScreenNotice { + pub title: String, + pub text: String, +} + +/// The notifications that changed with an event: `Some(None)` stops the +/// voice service, or puts the screen notification back to its default. +#[derive(Debug, Default, PartialEq, Eq)] +pub struct Changes { + pub voice: Option>, + pub screen: Option>, } #[derive(Default)] @@ -27,26 +56,81 @@ struct Session { name: Option, voice: VoiceState, muted: bool, + deafened: bool, + own_channel: Option, + presence: Arc, + /// When voice connected (Unix ms). + since_ms: Option, + /// Our stream is live. + live: bool, + /// Viewers connected to our stream. + watching: usize, +} + +impl Session { + fn name(&self) -> &str { + self.name.as_deref().unwrap_or("a server") + } + + /// Our channel's name and how many are in it. + fn channel(&self) -> Option<(&str, usize)> { + let id = self.own_channel?; + let channel = self.presence.channels.get(&id)?; + let people = + self.presence.clients.values().filter(|c| c.channel == id && !c.is_query).count(); + Some((channel.name.as_str(), people)) + } +} + +fn now_ms() -> u64 { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_or(0, |d| d.as_millis() as u64) } impl Foreground { - /// Apply `event`. Returns the new notification when it changed: - /// `Some(None)` means the service should stop. - pub fn update(&mut self, event: &Event) -> Option> { - let before = self.notice(); + /// Apply `event`; the notifications it changed. + pub fn update(&mut self, event: &Event) -> Changes { + self.update_at(event, now_ms()) + } + + fn update_at(&mut self, event: &Event, now_ms: u64) -> Changes { + let (voice, screen) = (self.notice(), self.screen()); match event { Event::State { session, state } => { let s = self.sessions.entry(*session).or_default(); + s.since_ms = match state.voice { + VoiceState::Connected => s.since_ms.or(Some(now_ms)), + _ => None, + }; s.voice = state.voice; s.muted = state.input_muted; + s.deafened = state.output_muted; + s.own_channel = state.own_channel; } Event::ServerInfo { session, name, .. } => { self.sessions.entry(*session).or_default().name = Some(name.clone()); } - _ => return None, + Event::Presence { session, presence } => { + self.sessions.entry(*session).or_default().presence = presence.clone(); + } + Event::StreamState { session, state } => { + let s = self.sessions.entry(*session).or_default(); + s.live = matches!(state, StreamState::Live { .. }); + if !s.live { + s.watching = 0; + } + } + Event::StreamViewers { session, viewers } => { + self.sessions.entry(*session).or_default().watching = connected(viewers); + } + _ => return Changes::default(), + } + let (voice_after, screen_after) = (self.notice(), self.screen()); + Changes { + voice: (voice_after != voice).then_some(voice_after), + screen: (screen_after != screen).then_some(screen_after), } - let after = self.notice(); - (after != before).then_some(after) } fn active(&self) -> impl Iterator { @@ -58,49 +142,101 @@ impl Foreground { self.active().map(|(id, _)| *id).collect() } - /// The notification, `None` without voice. + /// The voice notification, `None` without voice. pub fn notice(&self) -> Option { let active: Vec<&Session> = self.active().map(|(_, s)| s).collect(); - if active.is_empty() { - return None; - } - let names: Vec<&str> = - active.iter().map(|s| s.name.as_deref().unwrap_or("a server")).collect(); - let names = names.join(", "); - let text = if active.iter().all(|s| s.voice == VoiceState::Connecting) { - format!("Connecting to {names}") - } else { - format!("In voice on {names}") + let connecting = active.iter().all(|s| s.voice == VoiceState::Connecting); + let (title, text) = match active.as_slice() { + [] => return None, + [one] if connecting => ("Connecting…".to_owned(), one.name().to_owned()), + [one] => match one.channel() { + Some((channel, 1)) => (channel.to_owned(), format!("{} · just you", one.name())), + Some((channel, n)) => { + (channel.to_owned(), format!("{} · {n} in voice", one.name())) + } + None => ("In voice".to_owned(), one.name().to_owned()), + }, + several => ( + format!("In voice on {} servers", several.len()), + several.iter().map(|s| s.name()).collect::>().join(", "), + ), }; - Some(VoiceNotice { text, muted: active.iter().all(|s| s.muted) }) + Some(VoiceNotice { + title, + text, + muted: active.iter().all(|s| s.muted), + deafened: active.iter().all(|s| s.deafened), + since_ms: active.iter().filter_map(|s| s.since_ms).min().unwrap_or(0), + }) } + + /// The screen-sharing notification while our stream is live. + pub fn screen(&self) -> Option { + let s = self.sessions.values().find(|s| s.live)?; + let title = match s.channel() { + Some((channel, _)) => format!("Live in {channel}"), + None => "Live".to_owned(), + }; + let text = match s.watching { + 0 => s.name().to_owned(), + 1 => format!("{} · 1 watching", s.name()), + n => format!("{} · {n} watching", s.name()), + }; + Some(ScreenNotice { title, text }) + } +} + +fn connected(viewers: &[ViewerInfo]) -> usize { + viewers.iter().filter(|v| v.state == ViewerState::Connected).count() } #[cfg(test)] mod tests { use voelin_core::SessionState; - use voelin_model::{Capabilities, ServerFlavor}; + use voelin_core::stream::EndReason; + use voelin_model::{Capabilities, ChannelInfo, ClientInfo, ServerFlavor}; use super::*; fn voice(session: SessionId, voice: VoiceState, input_muted: bool) -> Event { Event::State { session, - state: SessionState { voice, input_muted, ..SessionState::default() }, + state: SessionState { + voice, + input_muted, + own_channel: Some(2), + ..SessionState::default() + }, } } - fn notice(text: &str, muted: bool) -> Option> { - Some(Some(VoiceNotice { text: text.into(), muted })) + fn notice(title: &str, text: &str, muted: bool, since_ms: u64) -> Option> { + Some(Some(VoiceNotice { + title: title.into(), + text: text.into(), + muted, + deafened: false, + since_ms, + })) + } + + fn presence(people: u16) -> Event { + let mut p = Presence::default(); + p.channels + .insert(2, ChannelInfo { id: 2, name: "Chill Zone".into(), ..Default::default() }); + for id in 1..=people { + p.clients.insert(id, ClientInfo { id, channel: 2, ..Default::default() }); + } + Event::Presence { session: 1, presence: Arc::new(p) } } #[test] - fn service_follows_voice_connections() { + fn the_voice_service_follows_voice_connections() { let mut fg = Foreground::default(); - assert_eq!(fg.update(&voice(1, VoiceState::Disconnected, false)), None); + assert_eq!(fg.update_at(&voice(1, VoiceState::Disconnected, false), 5).voice, None); assert_eq!( - fg.update(&voice(1, VoiceState::Connecting, false)), - notice("Connecting to a server", false) + fg.update_at(&voice(1, VoiceState::Connecting, false), 5).voice, + notice("Connecting…", "a server", false, 0) ); let info = Event::ServerInfo { session: 1, @@ -108,25 +244,93 @@ mod tests { flavor: ServerFlavor::Unknown(String::new()), capabilities: Capabilities::default(), }; - assert_eq!(fg.update(&info), notice("Connecting to Home", false)); + assert_eq!(fg.update_at(&info, 6).voice, notice("Connecting…", "Home", false, 0)); assert_eq!( - fg.update(&voice(1, VoiceState::Connected, false)), - notice("In voice on Home", false) + fg.update_at(&voice(1, VoiceState::Connected, false), 7).voice, + notice("In voice", "Home", false, 7) ); - assert_eq!(fg.update(&voice(1, VoiceState::Connected, false)), None, "no change"); + // The channel and its people, once presence knows them. assert_eq!( - fg.update(&voice(1, VoiceState::Connected, true)), - notice("In voice on Home", true) + fg.update_at(&presence(3), 8).voice, + notice("Chill Zone", "Home · 3 in voice", false, 7) ); - // A second session that is not muted: the action mutes both. assert_eq!( - fg.update(&voice(2, VoiceState::Connecting, false)), - notice("In voice on Home, a server", false) + fg.update_at(&presence(1), 8).voice, + notice("Chill Zone", "Home · just you", false, 7) + ); + assert_eq!( + fg.update_at(&voice(1, VoiceState::Connected, false), 9).voice, + None, + "no change" + ); + assert_eq!( + fg.update_at(&voice(1, VoiceState::Connected, true), 9).voice, + notice("Chill Zone", "Home · just you", true, 7) + ); + // A second session that is not muted: the action mutes both, and + // the time counts from the first connection. + assert_eq!( + fg.update_at(&voice(2, VoiceState::Connected, false), 20).voice, + notice("In voice on 2 servers", "Home, a server", false, 7) ); assert_eq!(fg.voice_sessions(), [1, 2]); - assert_eq!(fg.update(&Event::Error { session: 1, message: "x".into() }), None); - fg.update(&voice(2, VoiceState::Disconnected, false)); - assert_eq!(fg.update(&voice(1, VoiceState::Disconnected, true)), Some(None)); + assert_eq!( + fg.update(&Event::Error { session: 1, message: "x".into() }), + Changes::default() + ); + fg.update_at(&voice(2, VoiceState::Disconnected, false), 30); + assert_eq!(fg.update_at(&voice(1, VoiceState::Disconnected, true), 30).voice, Some(None)); assert!(fg.voice_sessions().is_empty()); } + + #[test] + fn deafen_needs_every_session_deafened() { + let mut fg = Foreground::default(); + let deaf = |session, output_muted| Event::State { + session, + state: SessionState { + voice: VoiceState::Connected, + output_muted, + ..Default::default() + }, + }; + fg.update_at(&deaf(1, true), 1); + assert!(fg.notice().unwrap().deafened); + fg.update_at(&deaf(2, false), 1); + assert!(!fg.notice().unwrap().deafened); + } + + #[test] + fn the_screen_notice_says_where_we_are_live() { + let mut fg = Foreground::default(); + fg.update_at(&voice(1, VoiceState::Connected, false), 1); + fg.update_at(&presence(2), 1); + assert_eq!(fg.screen(), None); + // `StreamState::Live` carries a sink only the engine makes. + fg.sessions.get_mut(&1).unwrap().live = true; + let screen = |title: &str, text: &str| { + Some(Some(ScreenNotice { title: title.into(), text: text.into() })) + }; + assert_eq!(fg.screen(), screen("Live in Chill Zone", "a server").flatten()); + let viewer = |client, state| ViewerInfo { + client: tsclientlib::ClientId(client), + state, + message: String::new(), + layer: None, + estimate: None, + srtp_profile: None, + codec: None, + }; + let viewers = Event::StreamViewers { + session: 1, + viewers: vec![viewer(2, ViewerState::Connected), viewer(3, ViewerState::Requested)], + }; + assert_eq!( + fg.update_at(&viewers, 3).screen, + screen("Live in Chill Zone", "a server · 1 watching") + ); + let ended = + Event::StreamState { session: 1, state: StreamState::Ended(EndReason::Stopped) }; + assert_eq!(fg.update_at(&ended, 4).screen, Some(None)); + } } diff --git a/crates/voelin-android/src/lib.rs b/crates/voelin-android/src/lib.rs index 117ca35..e304bf3 100644 --- a/crates/voelin-android/src/lib.rs +++ b/crates/voelin-android/src/lib.rs @@ -13,6 +13,8 @@ //! native methods it calls back (`Native`) //! - `capture` (Android): screen and system-audio capture through //! MediaProjection, registered as `voelin_media` capture providers +//! - `camera` (Android): the Stream Studio's cameras through Camera2, +//! registered as its camera provider //! - `secrets` (Android): passwords encrypted with an Android Keystore key //! - `egl` (Android): keeps EGL extension slots for Skia, without which the //! UI cannot draw on Mesa-based Android (Waydroid) @@ -27,6 +29,8 @@ mod app; #[cfg(target_os = "android")] mod bridge; #[cfg(target_os = "android")] +mod camera; +#[cfg(target_os = "android")] mod capture; #[cfg(target_os = "android")] mod egl; diff --git a/crates/voelin-core/src/lib.rs b/crates/voelin-core/src/lib.rs index 6b33338..705179f 100644 --- a/crates/voelin-core/src/lib.rs +++ b/crates/voelin-core/src/lib.rs @@ -243,6 +243,14 @@ pub enum Command { session: SessionId, stream_id: String, }, + /// Watch simulcast layer `layer` of a stream (`None`: as the bandwidth + /// allows). Only for a stream whose [`Event::WatchLayers`] listed + /// layers; otherwise an [`Event::Error`]. + SetWatchLayer { + session: SessionId, + stream_id: String, + layer: Option, + }, /// Playback volume of a watched stream's audio, linear (1 = unchanged, /// up to 4). SetStreamVolume { @@ -552,6 +560,15 @@ pub enum Event { stream_id: String, state: WatchState, }, + /// The simulcast layers a watched stream offers (a Voelin streamer with + /// several lists them; empty: none to choose from), and the one we asked + /// for with [`Command::SetWatchLayer`] (`None`: as the bandwidth allows). + WatchLayers { + session: SessionId, + stream_id: String, + layers: Vec, + layer: Option, + }, /// A setting was set or reset (by anyone: a command, the UI through /// [`Engine::settings`], …). Read the new value from the settings. SettingChanged { @@ -944,6 +961,7 @@ fn command_session(command: &Command) -> SessionId { | Command::WatchStream { session, .. } | Command::LeaveStream { session, .. } | Command::RequestStreamKeyframe { session, .. } + | Command::SetWatchLayer { session, .. } | Command::SetStreamVolume { session, .. } | Command::SetClientVolume { session, .. } | Command::SetClientMuted { session, .. } diff --git a/crates/voelin-core/src/media.rs b/crates/voelin-core/src/media.rs index b309c13..3008909 100644 --- a/crates/voelin-core/src/media.rs +++ b/crates/voelin-core/src/media.rs @@ -79,6 +79,8 @@ const OPUS_BITRATE: i32 = 128_000; pub const MAX_QUEUED: usize = 30; /// Keyframe requests while waiting for one are at least this far apart. const KEYFRAME_RETRY: Duration = Duration::from_millis(500); +/// The decoding rates of [`DecodeStats`] cover at least this long. +const RATE_WINDOW: Duration = Duration::from_millis(500); #[derive(Debug, thiserror::Error)] pub enum MediaError { @@ -1582,7 +1584,8 @@ impl Ingest { } /// Whether frames go to the GPU: every layer's encoders take GPU frames - /// and the GPU stage has not failed. + /// and the GPU stage has not failed. On Android: the screen can render + /// straight into the encoder (`mediacodec`'s surface path). fn gpu_path(&self) -> bool { #[cfg(all(target_os = "linux", feature = "media-desktop"))] { @@ -1593,7 +1596,18 @@ impl Ingest { .iter() .all(|l| l.layer.stopped() || l.layer.gpu.load(Ordering::Relaxed) != 0) } - #[cfg(not(all(target_os = "linux", feature = "media-desktop")))] + #[cfg(target_os = "android")] + { + !self.layers.is_empty() + && self + .layers + .iter() + .all(|l| l.layer.stopped() || l.layer.gpu.load(Ordering::Relaxed) != 0) + } + #[cfg(not(any( + all(target_os = "linux", feature = "media-desktop"), + target_os = "android" + )))] false } @@ -1717,7 +1731,38 @@ impl FrameSink for Ingest { } fn accepts_dmabuf(&self) -> bool { - self.gpu_path() + cfg!(all(target_os = "linux", feature = "media-desktop")) && self.gpu_path() + } + + fn accepts_gpu(&self) -> bool { + cfg!(target_os = "android") && self.gpu_path() + } + + /// Android: the screen goes straight into each due layer's encoder, + /// which draws it at the layer's size; only its size and time come here. + #[cfg(target_os = "android")] + fn gpu(&mut self, frame: GpuFrame) -> bool { + if self.shared.stopped() { + return false; + } + self.pacer.keep(frame.timestamp); + self.refresh(); + let shared = &self.shared; + shared.captured.fetch_add(1, Ordering::Relaxed); + shared + .size + .store(u64::from(frame.width) << 32 | u64::from(frame.height), Ordering::Relaxed); + if shared.sink().is_none() { + return true; + } + for l in &mut self.layers { + if !l.layer.stopped() && l.pacer.take(frame.timestamp) { + let (width, height) = l.spec.output_size(frame.width, frame.height); + l.layer.gpu_inbox.put(Arc::new(frame.sized(width, height))); + } + } + shared.gpu_converted.fetch_add(1, Ordering::Relaxed); + true } /// The tiled layout the GPU's own RGB surfaces have, once the GPU stage @@ -1852,6 +1897,17 @@ fn gpu_alignment<'a>(encoders: impl IntoIterator) - u64::from(alignment.0) << 32 | u64::from(alignment.1) } +/// Which of a studio's outputs get an encoder's packets. +#[derive(Clone, Copy)] +enum ToStudio<'a> { + None, + /// The stream codec's: all of them, recordings and replay buffer too. + All(&'a Studio), + /// Another codec's: the outputs that asked for it + /// ([`Studio::output_codecs`]). + Asked(&'a Studio), +} + /// One encoder of a layer: its keyframe and bitrate state. struct LayerEncoder { codec: Codec, @@ -1878,7 +1934,7 @@ impl LayerEncoder { shared: &Shared, layer: &Layer, sink: &dyn MediaSink, - studio: Option<&Studio>, + studio: ToStudio<'_>, picture: &Picture, requested: bool, target: u64, @@ -1907,15 +1963,18 @@ impl LayerEncoder { let mut produced_keyframe = false; let mut out = |chunk: EncodedChunk<'_>| { produced_keyframe |= chunk.keyframe; - if let Some(studio) = studio { - studio.write_packet(&Packet { - track: Track::Video { codec, layer: u32::from(layer.id) }, - pts_90khz: chunk.pts_90khz, - keyframe: chunk.keyframe, - width, - height, - data: chunk.data, - }); + let packet = Packet { + track: Track::Video { codec, layer: u32::from(layer.id) }, + pts_90khz: chunk.pts_90khz, + keyframe: chunk.keyframe, + width, + height, + data: chunk.data, + }; + match studio { + ToStudio::All(studio) => studio.write_packet(&packet), + ToStudio::Asked(studio) => studio.write_output_packet(&packet), + ToStudio::None => {} } let encoded = EncodedFrame { kind: MediaKind::Video, @@ -2007,6 +2066,14 @@ fn encode_loop(shared: &Shared, layer: &Layer, encoder: Box) { // The codecs viewers chose; none known: the stream codec. wanted.clear(); sink.video_codecs(&mut wanted); + // With a studio, the stream codec for its recordings and replay + // buffer, and the codecs its outputs of this layer need (RTMP: H.264). + if let Some(studio) = &shared.studio { + if !wanted.contains(&primary.codec) { + wanted.insert(0, primary.codec); + } + studio.output_codecs(u32::from(layer.id), &mut wanted); + } let now = shared.encoders_generation.load(Ordering::Relaxed); if now != generation { generation = now; @@ -2068,12 +2135,13 @@ fn encode_loop(shared: &Shared, layer: &Layer, encoder: Box) { let target = sink.layer_bitrate(layer.id).unwrap_or(configured).clamp(1, cap); let started = Instant::now(); if primary_on { - let studio = shared.studio.as_deref(); + let studio = shared.studio.as_deref().map_or(ToStudio::None, ToStudio::All); primary.encode(shared, layer, &*sink, studio, &picture, requested, target); layer.target.store(primary.bitrate, Ordering::Relaxed); } for encoder in &mut extra { - encoder.encode(shared, layer, &*sink, None, &picture, requested, target); + let studio = shared.studio.as_deref().map_or(ToStudio::None, ToStudio::Asked); + encoder.encode(shared, layer, &*sink, studio, &picture, requested, target); } layer.encode_ns.fetch_add(started.elapsed().as_nanos() as u64, Ordering::Relaxed); layer.encoded.fetch_add(1, Ordering::Relaxed); @@ -2401,6 +2469,23 @@ pub struct DecodeStats { pub height: u32, /// The last error (no decoder for the codec, decoding failed). pub error: Option, + /// Bytes of video received. + pub bytes: u64, + /// Pictures decoded per second and video received in bit/s, over the + /// time since the previous [`VideoPipeline::stats`] (at least + /// [`RATE_WINDOW`]; the watch screen asks once a second). + pub fps: u32, + pub bitrate: u64, +} + +/// Where the rates of [`DecodeStats`] were last measured from. +#[derive(Default)] +struct DecodeRates { + since: Option, + decoded: u64, + bytes: u64, + fps: u32, + bitrate: u64, } #[derive(Default)] @@ -2416,6 +2501,7 @@ struct DecodeQueue { state: Mutex, cond: Condvar, stats: Mutex, + rates: Mutex, } /// Feeds frames into a [`VideoPipeline`]; cheap to clone. @@ -2432,6 +2518,7 @@ impl FrameInput { if frame.kind != MediaKind::Video { return; } + lock(&self.queue.stats).bytes += frame.data.len() as u64; let mut state = lock(&self.queue.state); if state.frames.len() >= MAX_QUEUED { state.frames.clear(); @@ -2486,7 +2573,19 @@ impl VideoPipeline { } pub fn stats(&self) -> DecodeStats { - lock(&self.input.queue.stats).clone() + let mut stats = lock(&self.input.queue.stats).clone(); + let mut rates = lock(&self.input.queue.rates); + let now = Instant::now(); + let elapsed = rates.since.map(|since| now.saturating_duration_since(since)); + if elapsed.is_none_or(|e| e >= RATE_WINDOW) { + if let Some(seconds) = elapsed.map(|e| e.as_secs_f64()) { + rates.fps = ((stats.decoded - rates.decoded) as f64 / seconds).round() as u32; + rates.bitrate = ((stats.bytes - rates.bytes) as f64 * 8.0 / seconds) as u64; + } + (rates.since, rates.decoded, rates.bytes) = (Some(now), stats.decoded, stats.bytes); + } + (stats.fps, stats.bitrate) = (rates.fps, rates.bitrate); + stats } } @@ -2981,6 +3080,11 @@ mod tests { assert!(stats.decoded >= 10 && stats.error.is_none(), "{stats:?}"); assert_eq!(stats.codec, Some(Codec::Vp8)); assert_eq!(preview.streamer().backend(), "synthetic"); + // Rates over the second since: the pattern's rate, its bitrate. + tokio::time::sleep(Duration::from_secs(1)).await; + let stats = preview.stats(); + assert!((20..=40).contains(&stats.fps), "{stats:?}"); + assert!((100_000..5_000_000).contains(&stats.bitrate), "{stats:?}"); } fn layer(id: LayerId, scale: f32, max_fps: Option, bitrate: u64) -> LayerSpec { diff --git a/crates/voelin-core/src/session.rs b/crates/voelin-core/src/session.rs index 68911b9..a885a14 100644 --- a/crates/voelin-core/src/session.rs +++ b/crates/voelin-core/src/session.rs @@ -484,6 +484,9 @@ impl Session { Command::RequestStreamKeyframe { stream_id, .. } => { self.stream_input(StreamInput::RequestKeyframe { stream_id }); } + Command::SetWatchLayer { stream_id, layer, .. } => { + self.stream_input(StreamInput::WatchLayer { stream_id, layer }); + } // Kept for streams started later, also without a connection. Command::SetStreamLayers { layers, .. } => { self.stream_layers = layers.clone(); @@ -1118,6 +1121,8 @@ impl Session { bitrate: 0, viewer_limit: 0, audio: true, + // The UI takes the directory's count, which stays current. + viewers: None, }) }) .collect(); diff --git a/crates/voelin-core/src/stream.rs b/crates/voelin-core/src/stream.rs index 018bda3..ad1a486 100644 --- a/crates/voelin-core/src/stream.rs +++ b/crates/voelin-core/src/stream.rs @@ -38,6 +38,10 @@ use crate::settings::{STREAM_PERMISSIONS, SharedSettings, StreamPermissions}; use crate::voice::VoiceCmd; use crate::{Event, SessionId}; +/// How often the viewer count of one stream in our channel is asked for +/// (round robin, see [`Streams::refresh_viewer_counts`]). +const VIEWER_COUNTS: std::time::Duration = std::time::Duration::from_secs(5); + /// Our own stream. #[derive(Clone, Debug, PartialEq)] pub enum StreamState { @@ -159,6 +163,10 @@ pub(crate) enum StreamInput { RequestKeyframe { stream_id: String, }, + WatchLayer { + stream_id: String, + layer: Option, + }, /// Simulcast layers of our stream (now and for streams started later). Layers(Vec), /// SRTP profile order of new connections. @@ -320,6 +328,8 @@ struct StreamTask { impl StreamTask { async fn run(mut self, mut rx: mpsc::UnboundedReceiver) { + let mut counts = tokio::time::interval(VIEWER_COUNTS); + counts.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay); loop { tokio::select! { input = rx.recv() => match input { @@ -331,6 +341,7 @@ impl StreamTask { Some(input) => self.input(input).await, }, () = self.streams.wait_peers() => {} + _ = counts.tick() => self.streams.refresh_viewer_counts(), } self.flush(); } @@ -365,6 +376,10 @@ impl StreamTask { self.streams.request_keyframe(&stream_id); Ok(()) } + StreamInput::WatchLayer { stream_id, layer } => self + .streams + .set_watch_layer(&stream_id, layer) + .map(|()| self.watch_layers(&stream_id)), StreamInput::Layers(layers) => { self.layers = layers.clone(); // Without a stream they are used for the next one. @@ -533,6 +548,7 @@ impl StreamTask { } WatchState::Ended(reason) } + WatchEvent::Layers(_) => return self.watch_layers(&id), WatchEvent::Frame(frame) => { if let (MediaKind::Audio, Some(audio)) = (frame.kind, &self.audio) { audio.send(AudioIn::StreamAudio { @@ -550,6 +566,17 @@ impl StreamTask { } } + /// Tell the layers of watched stream `id` and the one we asked for. + fn watch_layers(&self, id: &str) { + let Some(watched) = self.streams.watching().find(|v| v.id() == id) else { return }; + self.emit(Event::WatchLayers { + session: self.session, + stream_id: id.to_owned(), + layers: watched.layers().to_vec(), + layer: watched.layer(), + }); + } + /// The answer `stream.permissions` gives to a join request; `None`: ask. fn join_decision(&self, viewer: ClientId) -> Option { match *self.settings.current().get_arc(&STREAM_PERMISSIONS) { @@ -618,6 +645,7 @@ mod tests { bitrate: setup.bitrate, viewer_limit: setup.viewer_limit, audio: setup.audio, + viewers: Some(0), }; let return_code = (c == from).then(|| "1".to_owned()); (c, StreamNotification::Started { info, return_code }) @@ -977,6 +1005,7 @@ mod tests { bitrate: 0, viewer_limit: 0, audio: true, + viewers: None, }; handles[1].send(StreamInput::Directory(vec![entry])); wait(&mut rx, |e| match e { diff --git a/crates/voelin-core/tests/studio.rs b/crates/voelin-core/tests/studio.rs index f68d832..5e6a70b 100644 --- a/crates/voelin-core/tests/studio.rs +++ b/crates/voelin-core/tests/studio.rs @@ -180,6 +180,250 @@ async fn a_studio_stream_records_and_replays_while_the_scene_switches() { std::fs::remove_dir_all(&dir).ok(); } +/// FFmpeg's own RTMP server (`ffmpeg -listen 1`) on `port`, keeping what +/// it receives in `out`; its log goes to `out` with `.log`. +fn rtmp_server(port: u16, out: &Path) -> std::process::Child { + let log = std::fs::File::create(out.with_extension("log")).unwrap(); + Process::new("ffmpeg") + .args(["-hide_banner", "-nostdin", "-loglevel", "warning", "-listen", "1", "-i"]) + .arg(format!("rtmp://127.0.0.1:{port}/live/test-key")) + .args(["-c", "copy", "-y"]) + .arg(out) + .stderr(log) + .spawn() + .unwrap() +} + +/// Add the RTMP output `spec`, trying again while the server starts. +async fn add_rtmp(studio: &studio::Studio, spec: &voelin_core::studio::OutputSpec) { + let deadline = Instant::now() + Duration::from_secs(10); + loop { + match studio.apply(Command::AddOutput(spec.clone())).await { + Ok(()) => return, + Err(e) if Instant::now() < deadline => { + eprintln!("not yet: {e}"); + tokio::time::sleep(Duration::from_millis(200)).await; + } + Err(e) => panic!("the RTMP output did not connect: {e}"), + } + } +} + +/// Wait up to `limit` for `child` to exit by itself. +fn wait_exit(child: &mut std::process::Child, limit: Duration) -> Option { + let deadline = Instant::now() + limit; + while Instant::now() < deadline { + if let Some(status) = child.try_wait().unwrap() { + return Some(status); + } + std::thread::sleep(Duration::from_millis(50)); + } + None +} + +/// ffprobe's view of the streams of `path`: codec, width, height, sample +/// rate and channels per stream. +fn probe_streams(path: &Path) -> Vec { + let out = Process::new("ffprobe") + .args(["-v", "error", "-show_entries"]) + .args(["stream=codec_name,width,height,sample_rate,channels", "-of", "csv=p=0"]) + .arg(path) + .output() + .unwrap(); + assert!(out.status.success(), "ffprobe: {}", String::from_utf8_lossy(&out.stderr)); + String::from_utf8_lossy(&out.stdout) + .lines() + .map(|l| l.trim_end_matches(',').to_owned()) + .collect() +} + +/// The audio of `path`, mono, decoded by ffmpeg: its length in seconds and +/// its frequency (from the zero crossings), ignoring the first 100 ms. +fn tone(path: &Path) -> (f64, f64) { + let out = Process::new("ffmpeg") + .args(["-v", "error", "-i"]) + .arg(path) + .args(["-map", "0:a", "-ac", "1", "-ar", "48000", "-f", "f32le", "-"]) + .output() + .unwrap(); + assert!(out.status.success(), "ffmpeg: {}", String::from_utf8_lossy(&out.stderr)); + let samples: Vec = + out.stdout.chunks_exact(4).map(|b| f32::from_le_bytes(b.try_into().unwrap())).collect(); + let tail = &samples[samples.len().min(4800)..]; + let crossings = tail.windows(2).filter(|w| (w[0] < 0.0) != (w[1] < 0.0)).count(); + let seconds = tail.len() as f64 / 48_000.0; + (samples.len() as f64 / 48_000.0, crossings as f64 / 2.0 / seconds.max(1e-9)) +} + +/// Whether the first video frame of `path` is a keyframe. +fn starts_with_keyframe(path: &Path) -> bool { + let out = Process::new("ffprobe") + .args(["-v", "error", "-select_streams", "v", "-read_intervals", "%+#1"]) + .args(["-show_entries", "frame=key_frame", "-of", "csv=p=0"]) + .arg(path) + .output() + .unwrap(); + // Side data (an encoder's SEI) adds fields after the flag. + String::from_utf8_lossy(&out.stdout).lines().next().and_then(|l| l.split(',').next()) + == Some("1") +} + +/// The studio pushed over RTMP to FFmpeg's own RTMP server: H.264 as +/// encoded and the tone as AAC arrive, with the stream key; the server goes +/// away mid-stream and a new one takes its place, which the output finds +/// again (starting at a keyframe); End Stream unpublishes cleanly, so the +/// server finishes its file and exits by itself. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn a_studio_stream_goes_out_over_rtmp_and_comes_back_after_the_server_did() { + use voelin_core::media::voelin_media::ffmpeg::avio::Connection; + use voelin_core::studio::OutputSpec; + + if !has("ffmpeg") || !has("ffprobe") { + eprintln!("skipped: ffmpeg and ffprobe are the RTMP server and the check"); + return; + } + if let Err(e) = Connection::available() { + eprintln!("skipped: no FFmpeg libraries with RTMP: {e}"); + return; + } + let codecs = Codecs::new(); + if !codecs.encoder_codecs().contains(&Codec::H264) { + eprintln!("skipped: no H.264 encoder"); + return; + } + let settings = Settings::in_memory(); + let mut scenes = + Scenes { width: WIDTH, height: HEIGHT, fps: 30, active: 1, ..Scenes::default() }; + scenes.scenes.push(colour_scene(1, "Red", RED)); + settings.set(&STUDIO_SCENES, scenes).unwrap(); + let studio = studio::start(&settings).await.unwrap(); + let config = StreamerConfig { + fps: 30, + bitrate_kbps: 800, + codec: Codec::H264, + audio_sources: vec![AudioSourceSpec::new(AudioSourceKind::Synthetic { hz: 440 })], + ..StreamerConfig::default() + }; + let mut streamer = Streamer::start_studio(&codecs, config, studio.clone()).await.unwrap(); + + let port = std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port(); + let dir = std::env::temp_dir().join(format!("voelin-studio-rtmp-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let (first, second) = (dir.join("first.flv"), dir.join("second.flv")); + let mut server = rtmp_server(port, &first); + // The key apart from the URL, as a service gives them. + let spec = OutputSpec::Url { + url: format!("rtmp://127.0.0.1:{port}/live"), + token: Some("test-key".into()), + }; + add_rtmp(&studio, &spec).await; + studio.apply(Command::GoLive).await.unwrap(); + tokio::time::sleep(Duration::from_secs(3)).await; + + // The server goes away (as a service restarting would); another one + // takes the address. + Process::new("kill").args(["-TERM", &server.id().to_string()]).status().unwrap(); + assert!(wait_exit(&mut server, Duration::from_secs(10)).is_some(), "the first server hangs"); + let mut server = rtmp_server(port, &second); + let deadline = Instant::now() + Duration::from_secs(20); + while std::fs::metadata(&second).map_or(0, |m| m.len()) < 20_000 { + assert!(Instant::now() < deadline, "the output did not come back"); + tokio::time::sleep(Duration::from_millis(100)).await; + } + tokio::time::sleep(Duration::from_secs(2)).await; + studio.apply(Command::EndStream).await.unwrap(); + let status = wait_exit(&mut server, Duration::from_secs(10)); + if status.is_none() { + let _ = server.kill(); + } + streamer.stop(); + assert!(status.is_some_and(|s| s.success()), "the server did not finish: {status:?}"); + + for (file, seconds) in [(&first, 2.0), (&second, 1.5)] { + let log = std::fs::read_to_string(file.with_extension("log")).unwrap_or_default(); + // The key arrived as the stream's name. + assert!(!log.contains("Unexpected stream"), "{log}"); + let streams = probe_streams(file); + assert_eq!(streams, [format!("h264,{WIDTH},{HEIGHT}"), "aac,48000,2".to_owned()], "{log}"); + assert!(starts_with_keyframe(file), "{}", file.display()); + let pictures = decode(file); + assert!(pictures.len() as f64 >= seconds * 25.0, "{} pictures", pictures.len()); + assert!(near(centre(&pictures[0]), RED), "{:?}", centre(&pictures[0])); + let (length, hz) = tone(file); + assert!(length >= seconds, "{length} s of audio in {}", file.display()); + assert!((430.0..450.0).contains(&hz), "{hz} Hz in {}", file.display()); + } + std::fs::remove_dir_all(&dir).ok(); +} + +/// A VP8 stream goes out over RTMP all the same: the streamer encodes H.264 +/// of the output's layer beside the VP8 (the key in the URL this time), +/// while the recording keeps the stream's VP8. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn a_vp8_stream_goes_out_over_rtmp_as_h264() { + use voelin_core::media::voelin_media::ffmpeg::avio::Connection; + use voelin_core::studio::OutputSpec; + + if !has("ffmpeg") || !has("ffprobe") || Connection::available().is_err() { + eprintln!("skipped: needs ffmpeg, ffprobe and the FFmpeg libraries with RTMP"); + return; + } + let codecs = Codecs::new(); + if ![Codec::Vp8, Codec::H264].iter().all(|c| codecs.encoder_codecs().contains(c)) { + eprintln!("skipped: needs VP8 and H.264 encoders"); + return; + } + let settings = Settings::in_memory(); + let mut scenes = + Scenes { width: WIDTH, height: HEIGHT, fps: 30, active: 1, ..Scenes::default() }; + scenes.scenes.push(colour_scene(1, "Red", RED)); + settings.set(&STUDIO_SCENES, scenes).unwrap(); + let studio = studio::start(&settings).await.unwrap(); + let config = StreamerConfig { + fps: 30, + bitrate_kbps: 800, + codec: Codec::Vp8, + audio_sources: vec![AudioSourceSpec::new(AudioSourceKind::Synthetic { hz: 440 })], + ..StreamerConfig::default() + }; + let mut streamer = Streamer::start_studio(&codecs, config, studio.clone()).await.unwrap(); + + let port = std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port(); + let dir = std::env::temp_dir().join(format!("voelin-studio-rtmp-vp8-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let (pushed, recording) = (dir.join("pushed.flv"), dir.join("recording.webm")); + let mut server = rtmp_server(port, &pushed); + let spec = + OutputSpec::Url { url: format!("rtmp://127.0.0.1:{port}/live/test-key"), token: None }; + add_rtmp(&studio, &spec).await; + studio.apply(Command::StartRecording { path: recording.clone() }).await.unwrap(); + tokio::time::sleep(Duration::from_secs(3)).await; + let encoded = streamer.stats().layers[0].codecs.clone(); + studio.apply(Command::StopRecording).await.unwrap(); + studio.apply(Command::EndStream).await.unwrap(); + let status = wait_exit(&mut server, Duration::from_secs(10)); + if status.is_none() { + let _ = server.kill(); + } + streamer.stop(); + assert!(status.is_some_and(|s| s.success()), "the server did not finish: {status:?}"); + assert_eq!(encoded, [Codec::Vp8, Codec::H264]); + + let log = std::fs::read_to_string(pushed.with_extension("log")).unwrap_or_default(); + assert!(!log.contains("Unexpected stream"), "{log}"); + let streams = probe_streams(&pushed); + assert_eq!(streams, [format!("h264,{WIDTH},{HEIGHT}"), "aac,48000,2".to_owned()], "{log}"); + assert!(starts_with_keyframe(&pushed)); + let pictures = decode(&pushed); + assert!(pictures.len() >= 60, "{} pictures", pictures.len()); + assert!(near(centre(&pictures[0]), RED), "{:?}", centre(&pictures[0])); + let (length, hz) = tone(&pushed); + assert!(length >= 2.0 && (430.0..450.0).contains(&hz), "{length} s at {hz} Hz"); + let (streams, _) = probe(&recording); + check_streams(&streams); + std::fs::remove_dir_all(&dir).ok(); +} + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn the_studio_source_needs_a_studio() { let codecs = Codecs::new(); diff --git a/crates/voelin-media/Cargo.toml b/crates/voelin-media/Cargo.toml index 8bfe996..6e1c23f 100644 --- a/crates/voelin-media/Cargo.toml +++ b/crates/voelin-media/Cargo.toml @@ -27,7 +27,9 @@ av1 = ["dep:dav1d"] x11 = ["dep:x11rb", "dep:memmap2", "dep:rustix"] # Wayland screen capture (ScreenCast portal + PipeWire, shared memory or # LINEAR DMA-BUFs) and PipeWire system audio (Linux). -pipewire = ["dep:ashpd", "dep:pipewire", "dep:memmap2", "dep:rustix"] +# MJPEG cameras are decoded with zune-jpeg (already in the tree through +# `image`). +pipewire = ["dep:ashpd", "dep:pipewire", "dep:memmap2", "dep:rustix", "dep:zune-core", "dep:zune-jpeg"] # Screen capture on wlroots compositors (Sway, Hyprland, river, ...) without # the portal: ext-image-copy-capture-v1 or wlr-screencopy-unstable-v1 (Linux). wlroots = ["dep:wayland-client", "dep:wayland-protocols", "dep:wayland-protocols-wlr", "dep:memmap2", "dep:rustix"] @@ -72,18 +74,24 @@ wayland-client = { version = "0.31.15", optional = true } wayland-protocols = { version = "0.32.13", features = ["client", "staging"], optional = true } wayland-protocols-wlr = { version = "0.3.12", features = ["client"], optional = true } x11rb = { version = "0.13.2", features = ["randr", "shm", "xfixes"], optional = true } +zune-core = { version = "0.5.3", default-features = false, optional = true } +zune-jpeg = { version = "0.5.15", optional = true } [target.'cfg(target_os = "android")'.dependencies] ndk = { version = "0.9.0", default-features = false, features = ["media", "api-level-29"] } [target.'cfg(windows)'.dependencies] wasapi = "0.24.0" -# Process names for the list of applications with audio sessions. -windows = { version = "0.62", features = ["Win32_Foundation", "Win32_System_Threading"] } +# Process names for the list of applications with audio sessions, +# and studio cameras (Media Foundation). +windows = { version = "0.62", features = ["Win32_Foundation", "Win32_Media_MediaFoundation", "Win32_System_Com", "Win32_System_Threading"] } windows-capture = "2.0.1" [dev-dependencies] criterion = "0.8" +# Opus packets to feed the RTMP output's AAC encoder in tests (the voice +# codec's crate, already in the tree through voelin-audio). +opus2 = "0.4" serde_json = "1" # The H.264 `profile-level-id` the signalling offers, to check it against the # SPS the encoders really emit (`tests/ffmpeg.rs`). No cycle: voelin-stream diff --git a/crates/voelin-media/src/capture/external.rs b/crates/voelin-media/src/capture/external.rs index 2d72691..37d44f0 100644 --- a/crates/voelin-media/src/capture/external.rs +++ b/crates/voelin-media/src/capture/external.rs @@ -15,7 +15,7 @@ use std::sync::{Arc, Mutex, PoisonError}; use crate::capture::playback::{AudioApp, PlaybackFilter, SourceCapture, forward_audio}; use crate::capture::{ - AudioCapture, BoxFuture, CaptureOptions, CaptureSource, ScreenCapture, SourceId, + AudioCapture, BoxFuture, CaptureOptions, CaptureSource, FrameSink, ScreenCapture, SourceId, }; use crate::frame::{AUDIO_SAMPLE_RATE, AudioBuffer, VideoFrame}; use crate::mix::{SourceHandle, SourceInput}; @@ -41,6 +41,24 @@ pub trait ScreenProvider: Send + Sync { frames: FrameSender, ) -> BoxFuture<'static, Result<()>>; + /// Like [`start`](Self::start), but frames go to `sink` from the + /// provider's own thread, borrowed (no copy), and the provider may hand + /// it [`FrameSink::gpu`] pictures while it accepts them. The default + /// forwards the frames of `start`. + fn start_sink( + &self, + source: &SourceId, + options: &CaptureOptions, + sink: Box, + ) -> BoxFuture<'static, Result<()>> { + let (tx, rx) = frame_channel(options.queue); + let started = self.start(source, options, tx); + Box::pin(async move { + started.await?; + super::forward(rx, sink) + }) + } + fn stop(&self); } @@ -175,6 +193,19 @@ impl ScreenCapture for ExternalScreenCapture { }) } + fn start_sink( + &mut self, + source: &SourceId, + options: &CaptureOptions, + sink: Box, + ) -> BoxFuture<'_, Result<()>> { + self.stop(); + let options = CaptureOptions { fps: sink.max_fps(), ..options.clone() }; + let started = self.provider.start_sink(source, &options, sink); + self.running = true; + started + } + fn stop(&mut self) { if std::mem::take(&mut self.running) { self.provider.stop(); diff --git a/crates/voelin-media/src/capture/mod.rs b/crates/voelin-media/src/capture/mod.rs index f064d63..f0568d9 100644 --- a/crates/voelin-media/src/capture/mod.rs +++ b/crates/voelin-media/src/capture/mod.rs @@ -130,6 +130,22 @@ pub trait FrameSink: Send { None } + /// Whether the sink takes pictures the platform puts straight into the + /// encoder ([`gpu`](Self::gpu)), because every encoder it feeds takes + /// them. Android's screen capture then renders into MediaCodec's input + /// surface instead of handing over pixels. + fn accepts_gpu(&self) -> bool { + false + } + + /// Such a picture: only its size and time + /// ([`GpuFrame::rendered`](crate::GpuFrame::rendered)). Returns `false` + /// when no more frames are wanted. + fn gpu(&mut self, frame: crate::GpuFrame) -> bool { + let _ = frame; + true + } + /// Tiled DRM format modifiers of RGB buffers the sink takes now /// ([`accepts_dmabuf`](Self::accepts_dmabuf)), best first; backends that /// negotiate buffers (the portal) offer them ahead of LINEAR, and offer diff --git a/crates/voelin-media/src/codec/mediacodec.rs b/crates/voelin-media/src/codec/mediacodec.rs index 0cd9df5..e789829 100644 --- a/crates/voelin-media/src/codec/mediacodec.rs +++ b/crates/voelin-media/src/codec/mediacodec.rs @@ -10,26 +10,42 @@ //! H.264 is encoded as High profile without B-frames (the Constrained High //! stream TeamSpeak negotiates, see `voelin-stream`), SPS/PPS in front of every //! keyframe. +//! +//! The zero-copy path: while it is the only MediaCodec encoder in the +//! process, an encoder takes [`GpuFrame`]s +//! ([`VideoEncoder::gpu_alignment`]). For the first one it starts a codec +//! with an input surface and publishes it ([`input_surface`]); Android's +//! screen capture points its virtual display at that surface, so the +//! screen goes from the compositor into the encoder without a copy or a +//! CPU conversion, and the `GpuFrame`s only say a picture is due (the +//! encoder hands over what it encoded since). With a second encoder (a +//! simulcast layer, another codec for some viewers) none takes them, and +//! the capture goes back to frames in memory; so does an encoder whose +//! surface failed once. // AMediaCodec handles are used from one thread at a time (`&mut self`), which // the NDK allows from any thread; the wrapper only asserts that. #![allow(unsafe_code)] -use std::sync::OnceLock; +use std::sync::atomic::{AtomicI64, AtomicU64, AtomicUsize, Ordering}; +use std::sync::{Mutex, OnceLock, PoisonError}; use std::time::Duration; use ndk::media::media_codec::{ DequeuedInputBufferResult, DequeuedOutputBufferInfoResult, MediaCodec, MediaCodecDirection, }; use ndk::media::media_format::MediaFormat; +use ndk::native_window::NativeWindow; use tracing::{debug, info}; use super::hw::EncoderFactory; use super::image_layout::{ COLOR_FORMAT_FLEXIBLE, COLOR_FORMAT_I420, COLOR_FORMAT_NV12, ImageLayout, }; -use super::{Codec, EncodedFrame, EncoderBackend, EncoderConfig, VideoDecoder, VideoEncoder}; -use crate::frame::{FrameData, VideoFrame}; +use super::{ + Codec, EncodedChunk, EncodedFrame, EncoderBackend, EncoderConfig, VideoDecoder, VideoEncoder, +}; +use crate::frame::{FrameData, GpuFrame, VideoFrame}; use crate::{Error, Result, convert}; /// `BUFFER_FLAG_KEY_FRAME`. @@ -48,8 +64,47 @@ const INPUT_WAIT: Duration = Duration::from_millis(20); /// How long they wait for the first output of a call. const OUTPUT_WAIT: Duration = Duration::from_millis(5); +/// `COLOR_FormatSurface`: pictures come through an input surface. +const COLOR_FORMAT_SURFACE: i32 = 0x7F00_0789; +/// On the surface path a still screen is encoded again after this long +/// (µs), so a keyframe asked for while nothing moves comes this late at +/// most. +const REPEAT_AFTER_US: i64 = 100_000; + pub const NAME: &str = "mediacodec"; +/// MediaCodec encoders alive in this process. +static LIVE: AtomicUsize = AtomicUsize::new(0); +/// The published input surface (see the [module docs](self)). +static SURFACE: Mutex> = Mutex::new(None); +static GENERATION: AtomicU64 = AtomicU64::new(0); +/// The screen capture's clock origin (`CLOCK_MONOTONIC` ns), which the +/// surface's presentation times are on. +static SCREEN_ORIGIN_NS: AtomicI64 = AtomicI64::new(i64::MIN); + +/// The input surface of the encoder that takes the screen straight from +/// the capture, for the capture's virtual display to render into. +#[derive(Clone)] +pub struct InputSurface { + pub window: NativeWindow, + pub width: u32, + pub height: u32, + /// Changes with every new surface. + pub generation: u64, +} + +/// The surface to render the screen into, if an encoder has one. +pub fn input_surface() -> Option { + SURFACE.lock().unwrap_or_else(PoisonError::into_inner).clone() +} + +/// Where the screen capture's frame times start (`CLOCK_MONOTONIC` ns, +/// what its frames' times are counted from): the surface path puts its +/// presentation times, which are on that clock, on the stream's timeline. +pub fn set_screen_origin(origin_ns: i64) { + SCREEN_ORIGIN_NS.store(origin_ns, Ordering::Relaxed); +} + fn mime(codec: Codec) -> &'static str { match codec { Codec::Vp8 => "video/x-vnd.on2.vp8", @@ -123,8 +178,9 @@ pub fn check_decoder(codec: Codec) -> Result<()> { } } -/// Encoders of this device: hardware ones first (H.264, VP9, VP8), then -/// Google's software VP8 and H.264. Software VP9 and AV1 are too slow. +/// Encoders of this device: the hardware ones (H.264, VP9, VP8, AV1) and +/// Google's software VP8 and H.264; software VP9 and AV1 are too slow. +/// `Codecs` orders them by codec, as every hardware factory. pub fn probe() -> Option { let encoders = &available().encoders; let name = |codec| encoders.iter().find(|(c, _)| *c == codec).map(|(_, n)| n.as_str()); @@ -159,15 +215,32 @@ impl EncoderFactory for MediaCodecFactory { if !self.codecs.contains(&codec) { return Err(Error::CodecUnavailable { codec, reason: "no MediaCodec encoder".into() }); } - Ok(Box::new(MediaCodecEncoder { codec, config: config.clone(), session: None })) + LIVE.fetch_add(1, Ordering::Relaxed); + Ok(Box::new(MediaCodecEncoder { + codec, + config: config.clone(), + session: None, + surface_failed: false, + })) } } -/// A MediaCodec encoder. The codec is (re)created for the frame size. +/// A MediaCodec encoder. The codec is (re)created for the frame size, and +/// for frames in memory or on the surface path. pub struct MediaCodecEncoder { codec: Codec, config: EncoderConfig, session: Option, + /// The surface path failed: frames in memory only from now on. + surface_failed: bool, +} + +impl Drop for MediaCodecEncoder { + fn drop(&mut self) { + // Its surface goes first. + self.session = None; + LIVE.fetch_sub(1, Ordering::Relaxed); + } } struct EncoderSession { @@ -178,6 +251,18 @@ struct EncoderSession { /// Staging buffer for the codec's input layout. staging: Vec, last_pts_us: Option, + /// The surface path: the generation of the input surface it published. + surface: Option, +} + +impl Drop for EncoderSession { + fn drop(&mut self) { + let Some(generation) = self.surface else { return }; + let mut slot = SURFACE.lock().unwrap_or_else(PoisonError::into_inner); + if slot.as_ref().is_some_and(|s| s.generation == generation) { + *slot = None; + } + } } impl MediaCodecEncoder { @@ -241,11 +326,54 @@ impl MediaCodecEncoder { parameter_sets: Vec::new(), staging: Vec::new(), last_pts_us: None, + surface: None, }); } } Err(encoder_error(codec, "no working configuration", last_error)) } + + /// Start a codec for `width` x `height` that takes its pictures through + /// an input surface, and publish the surface for the screen capture. + fn start_surface(&self, width: u32, height: u32) -> Result { + let codec = self.codec; + let profiles: &[Option] = if codec == Codec::H264 { + &[Some(AVC_PROFILE_CONSTRAINED_HIGH), Some(AVC_PROFILE_HIGH), None] + } else { + &[None] + }; + let mut last_error = String::from("no configuration tried"); + for &profile in profiles { + let handle = Handle( + MediaCodec::from_encoder_type(mime(codec)) + .ok_or_else(|| encoder_error(codec, "create", "no encoder"))?, + ); + let mut format = self.format(width, height, COLOR_FORMAT_SURFACE, profile); + // The display renders at its own rate; encode at most ours. + format.set_f32("max-fps-to-encoder", self.config.fps.max(1) as f32); + format.set_i64("repeat-previous-frame-after", REPEAT_AFTER_US); + if let Err(e) = handle.0.configure(&format, None, MediaCodecDirection::Encoder) { + last_error = format!("configure surface input/{profile:?}: {e}"); + continue; + } + let window = + handle.0.create_input_surface().map_err(|e| encoder_error(codec, "surface", e))?; + handle.0.start().map_err(|e| encoder_error(codec, "start", e))?; + let generation = GENERATION.fetch_add(1, Ordering::Relaxed) + 1; + *SURFACE.lock().unwrap_or_else(PoisonError::into_inner) = + Some(InputSurface { window, width, height, generation }); + debug!(%codec, width, height, ?profile, "MediaCodec encoder on the surface path"); + return Ok(EncoderSession { + handle, + layout: ImageLayout::nv12(width, height, 0, 0), + parameter_sets: Vec::new(), + staging: Vec::new(), + last_pts_us: None, + surface: Some(generation), + }); + } + Err(encoder_error(codec, "no surface configuration", last_error)) + } } /// Where the encoder wants its input: `image-data` if it says, else the @@ -310,7 +438,9 @@ impl VideoEncoder for MediaCodecEncoder { .session .as_ref() .is_some_and(|s| (s.layout.width, s.layout.height) != (width, height)); - if resized || self.session.is_none() { + // Frames in memory again after the surface path: a codec for them. + let surface = self.session.as_ref().is_some_and(|s| s.surface.is_some()); + if resized || surface || self.session.is_none() { self.session = None; self.session = Some(self.start(width, height)?); } @@ -367,7 +497,72 @@ impl VideoEncoder for MediaCodecEncoder { // The codec is still busy: skip this frame (rate control). DequeuedInputBufferResult::TryAgainLater => {} } - drain_encoder(codec, session) + drain_encoder(codec, session, OUTPUT_WAIT) + } + + /// Only while it is the only MediaCodec encoder: one input surface + /// takes the screen (see the [module docs](self)). + fn gpu_alignment(&self) -> Option<(u32, u32)> { + (!self.surface_failed && LIVE.load(Ordering::Relaxed) == 1).then_some((2, 2)) + } + + /// A picture is due: on the first one (and when the size changes) the + /// codec starts on the surface path; then what it encoded since goes to + /// `out`. + fn encode_gpu( + &mut self, + frame: &GpuFrame, + force_keyframe: bool, + out: &mut dyn FnMut(EncodedChunk<'_>), + ) -> Result<()> { + let codec = self.codec; + let (width, height) = (frame.width & !1, frame.height & !1); + if width == 0 || height == 0 { + return Err(Error::InvalidFrame(format!("{}x{} frame", frame.width, frame.height))); + } + let current = self.session.as_ref().is_some_and(|s| { + s.surface.is_some() && (s.layout.width, s.layout.height) == (width, height) + }); + if !current { + self.session = None; + match self.start_surface(width, height) { + Ok(session) => self.session = Some(session), + Err(e) => { + // Frames in memory from now on (the capture follows + // `gpu_alignment`). + self.surface_failed = true; + return Err(e); + } + } + } else if force_keyframe { + let mut params = MediaFormat::new(); + params.set_i32("request-sync", 0); + let session = self.session.as_ref().expect("checked above"); + session + .handle + .0 + .set_parameters(params) + .map_err(|e| encoder_error(codec, "request keyframe", e))?; + } + let session = self.session.as_mut().expect("started above"); + // Wait up to half a frame for what the display rendered. + let wait = Duration::from_micros(500_000 / u64::from(self.config.fps.max(1))); + for f in drain_encoder(codec, session, wait)? { + out(EncodedChunk { data: &f.data, keyframe: f.keyframe, pts_90khz: f.pts_90khz }); + } + Ok(()) + } + + /// On the surface path the rate caps what the codec takes from the + /// display (`max-fps-to-encoder`, fixed when it starts): the next + /// picture starts it anew. Frames in memory follow their timestamps. + fn set_fps(&mut self, fps: u32) -> Result<()> { + let fps = fps.max(1); + if fps != self.config.fps && self.session.as_ref().is_some_and(|s| s.surface.is_some()) { + self.session = None; + } + self.config.fps = fps; + Ok(()) } fn set_bitrate(&mut self, bps: u32) -> Result<()> { @@ -385,10 +580,15 @@ impl VideoEncoder for MediaCodecEncoder { } } -/// Collect what the encoder has finished. -fn drain_encoder(codec: Codec, session: &mut EncoderSession) -> Result> { +/// Collect what the encoder has finished, waiting up to `wait` for the +/// first of it. +fn drain_encoder( + codec: Codec, + session: &mut EncoderSession, + wait: Duration, +) -> Result> { let mut out = Vec::new(); - let mut wait = OUTPUT_WAIT; + let mut wait = wait; loop { let result = session .handle @@ -424,7 +624,15 @@ fn drain_encoder(codec: Codec, session: &mut EncoderSession) -> Result; 2], + /// The time (48 kHz samples) of the first pending sample. + pending_time: i64, + /// The planes the input frame points at. + planes: [Vec; 2], +} + +// SAFETY: the FFmpeg objects belong to this value and are only used +// through `&mut self`; FFmpeg's codecs have no thread affinity. +unsafe impl Send for AacEncoder {} + +impl AacEncoder { + /// An encoder at `bitrate` bit/s. + pub fn new(bitrate: u64) -> Result { + let ffmpeg = Ffmpeg::get()?; + let api = &ffmpeg.api; + let name = cstr("fltp"); + // SAFETY: a C string. + let fltp = unsafe { (api.av_get_sample_fmt)(name.as_ptr()) }; + if fltp < 0 { + return Err("FFmpeg has no planar float samples".into()); + } + // The fields are filled one by one; Drop frees what was made. + let mut this = Self { + ffmpeg, + decoder: std::ptr::null_mut(), + encoder: std::ptr::null_mut(), + decoded: std::ptr::null_mut(), + input: std::ptr::null_mut(), + packet_in: std::ptr::null_mut(), + packet_out: std::ptr::null_mut(), + fltp, + pending: [Vec::with_capacity(4 * FRAME), Vec::with_capacity(4 * FRAME)], + pending_time: 0, + planes: [vec![0.0; FRAME], vec![0.0; FRAME]], + }; + // SAFETY: allocations whose results are checked; contexts of the + // codecs they are opened with; options set by name on a codec + // context (an AVClass object) with C strings, and `sample_fmt` + // written at the offset located and checked at load. + unsafe { + this.decoded = (api.av_frame_alloc)(); + this.packet_in = (api.av_packet_alloc)(); + this.packet_out = (api.av_packet_alloc)(); + if this.decoded.is_null() || this.packet_in.is_null() || this.packet_out.is_null() { + return Err("out of memory".into()); + } + let opus = cstr("opus"); + let codec = (api.avcodec_find_decoder_by_name)(opus.as_ptr()); + if codec.is_null() { + return Err("this FFmpeg has no Opus decoder".into()); + } + this.decoder = (api.avcodec_alloc_context3)(codec); + if this.decoder.is_null() { + return Err("avcodec_alloc_context3 failed".into()); + } + // Without extradata the decoder gives stereo at 48 kHz. + let ret = (api.avcodec_open2)(this.decoder, codec, std::ptr::null_mut()); + if ret < 0 { + return Err(format!("cannot open the Opus decoder: {}", api.error_text(ret))); + } + let aac = cstr("aac"); + let codec = (api.avcodec_find_encoder_by_name)(aac.as_ptr()); + if codec.is_null() { + return Err("this FFmpeg has no AAC encoder".into()); + } + this.encoder = (api.avcodec_alloc_context3)(codec); + if this.encoder.is_null() { + return Err("avcodec_alloc_context3 failed".into()); + } + let ctx = this.encoder; + let set = |name: &str, value: &str| { + let (name, value) = (cstr(name), cstr(value)); + (api.av_opt_set)(ctx, name.as_ptr(), value.as_ptr(), 0) + }; + let set_int = |name: &str, value: i64| { + let name = cstr(name); + (api.av_opt_set_int)(ctx, name.as_ptr(), value, 0) + }; + // `sample_fmt` has no AVOption: its field, located at load. + let at = ffmpeg.codec_sample_fmt.clone()?; + write::(ctx, at, fltp); + let mut ret = set_int("ar", i64::from(RATE)); + if ret >= 0 { + // `ch_layout` since libavcodec 59.24; before, a channel mask + // (front left | front right) and a channel count. + ret = match set("ch_layout", "stereo") { + OPTION_NOT_FOUND => match set_int("channel_layout", 3) { + r if r < 0 => r, + _ => set_int("ac", 2), + }, + r => r, + }; + } + if ret >= 0 { + ret = set_int("b", i64::try_from(bitrate).unwrap_or(i64::MAX)); + } + if ret >= 0 { + let time_base = cstr("time_base"); + let tb = Rational { num: 1, den: RATE as c_int }; + ret = (api.av_opt_set_q)(ctx, time_base.as_ptr(), tb, 0); + } + if ret < 0 { + return Err(format!("cannot set up the AAC encoder: {}", api.error_text(ret))); + } + let ret = (api.avcodec_open2)(ctx, codec, std::ptr::null_mut()); + if ret < 0 { + return Err(format!("cannot open the AAC encoder: {}", api.error_text(ret))); + } + } + Ok(this) + } + + /// Decode one Opus packet of time `time` (48 kHz samples since any + /// origin) and hand every AAC frame that is complete to `out`, with its + /// time on the same clock (an AAC encoder starts 1024 samples early: + /// its first frame is the codec's priming). + /// + /// A packet that does not follow the last one (a gap in the studio's + /// audio) starts the queue again at its time. A packet that does not + /// decode is an error; the next one is decoded as usual. + pub fn push( + &mut self, + opus: &[u8], + time: i64, + out: &mut dyn FnMut(&[u8], i64), + ) -> Result<(), String> { + let api = &self.ffmpeg.api; + // SAFETY: our packet points at `opus` only during the call that + // copies it (the packet is not reference-counted), then is emptied + // again; the decoder's frames are read within their sample count and + // unreferenced after. + unsafe { + let packet = self.packet_in.cast::(); + (*packet).data = opus.as_ptr().cast_mut(); + (*packet).size = c_int::try_from(opus.len()).map_err(|_| "Opus packet too large")?; + (*packet).pts = NOPTS_VALUE; + let ret = (api.avcodec_send_packet)(self.decoder, self.packet_in); + (*packet).data = std::ptr::null_mut(); + (*packet).size = 0; + if ret < 0 && ret != EAGAIN { + return Err(format!("Opus decoding failed: {}", api.error_text(ret))); + } + let mut time = time; + loop { + let ret = (api.avcodec_receive_frame)(self.decoder, self.decoded); + if ret == EAGAIN || ret == EOF { + break; + } + if ret < 0 { + return Err(format!("Opus decoding failed: {}", api.error_text(ret))); + } + let taken = self.take_decoded(time); + let samples = i64::from((*self.decoded.cast::()).nb_samples); + (api.av_frame_unref)(self.decoded); + taken?; + time += samples; + } + } + while self.pending[0].len() >= FRAME { + self.encode_one(out)?; + } + Ok(()) + } + + /// Queue the samples of the decoded frame, which starts at `time`. + /// + /// # Safety + /// `self.decoded` must hold a frame from the decoder. + unsafe fn take_decoded(&mut self, time: i64) -> Result<(), String> { + let api = &self.ffmpeg.api; + // SAFETY: guaranteed by the caller; planar float planes hold + // `nb_samples` samples each. + unsafe { + let head = &*self.decoded.cast::(); + if head.format != self.fltp { + return Err(format!( + "the Opus decoder gives sample format {}, not planar float", + head.format + )); + } + let n = usize::try_from(head.nb_samples).unwrap_or(0); + if n == 0 || head.data[0].is_null() { + return Ok(()); + } + if self.input.is_null() { + let input = (api.av_frame_alloc)(); + if input.is_null() || (api.av_frame_ref)(input, self.decoded) < 0 { + let mut input = input; + (api.av_frame_free)(&mut input); + return Err("cannot make the AAC encoder's frame".into()); + } + self.input = input; + } + let expected = self.pending_time + self.pending[0].len() as i64; + if self.pending[0].is_empty() || (time - expected).abs() > FRAME as i64 { + self.pending[0].clear(); + self.pending[1].clear(); + self.pending_time = time; + } + let left = std::slice::from_raw_parts(head.data[0].cast::(), n); + // A mono stream gives one plane: both channels get it. + let right = if head.data[1].is_null() { + left + } else { + std::slice::from_raw_parts(head.data[1].cast::(), n) + }; + self.pending[0].extend_from_slice(left); + self.pending[1].extend_from_slice(right); + } + Ok(()) + } + + /// Encode the first [`FRAME`] pending samples. + fn encode_one(&mut self, out: &mut dyn FnMut(&[u8], i64)) -> Result<(), String> { + let api = &self.ffmpeg.api; + for (plane, pending) in self.planes.iter_mut().zip(&mut self.pending) { + plane.copy_from_slice(&pending[..FRAME]); + pending.drain(..FRAME); + } + let time = self.pending_time; + self.pending_time += FRAME as i64; + // SAFETY: `input` is a frame of ours (a reference to a decoded one, + // see the module docs) whose leading fields we point at our planes, + // which live as long as `self` and are not touched until the + // encoder has taken the frame (it copies the samples when it + // encodes, before `avcodec_receive_packet` asks for more input); + // `pts` is the field located at load. Packets are read within their + // size and unreferenced after. + unsafe { + let head = &mut *self.input.cast::(); + for (data, plane) in head.data.iter_mut().zip(&mut self.planes) { + *data = plane.as_mut_ptr().cast(); + } + head.linesize[0] = (FRAME * size_of::()) as c_int; + head.nb_samples = FRAME as c_int; + write::(self.input, self.ffmpeg.frame.pts, time); + let ret = (api.avcodec_send_frame)(self.encoder, self.input); + if ret < 0 { + return Err(format!("AAC encoding failed: {}", api.error_text(ret))); + } + loop { + let ret = (api.avcodec_receive_packet)(self.encoder, self.packet_out); + if ret == EAGAIN || ret == EOF { + break; + } + if ret < 0 { + return Err(format!("AAC encoding failed: {}", api.error_text(ret))); + } + let packet = &*self.packet_out.cast::(); + let size = usize::try_from(packet.size).unwrap_or(0); + if !packet.data.is_null() && size > 0 { + out(std::slice::from_raw_parts(packet.data, size), packet.pts); + } + (api.av_packet_unref)(self.packet_out); + } + } + Ok(()) + } +} + +impl Drop for AacEncoder { + fn drop(&mut self) { + let api = &self.ffmpeg.api; + // SAFETY: every pointer is NULL or an object of ours, freed once; + // the free functions take NULL. + unsafe { + (api.av_frame_free)(&mut self.input); + (api.av_frame_free)(&mut self.decoded); + (api.av_packet_free)(&mut self.packet_in); + (api.av_packet_free)(&mut self.packet_out); + (api.avcodec_free_context)(&mut self.decoder); + (api.avcodec_free_context)(&mut self.encoder); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_audio_specific_config_is_aac_lc_48k_stereo() { + let config = u16::from_be_bytes(AUDIO_SPECIFIC_CONFIG); + assert_eq!(config >> 11, 2, "object type"); + assert_eq!((config >> 7) & 0xF, 3, "sampling index (48 kHz)"); + assert_eq!((config >> 3) & 0xF, 2, "channels"); + } + + /// One second of a stereo tone as 20 ms Opus packets becomes AAC frames + /// of 1024 samples, back to back from the first packet's time (less the + /// encoder's 1024 samples of priming); a gap starts the clock again. + #[test] + fn opus_becomes_aac() { + if Ffmpeg::get().is_err() { + eprintln!("FFmpeg not installed, skipped"); + return; + } + let mut aac = AacEncoder::new(160_000).unwrap(); + let mut opus = + opus2::Encoder::new(RATE, opus2::Channels::Stereo, opus2::Application::Audio).unwrap(); + let mut frames: Vec<(usize, i64)> = Vec::new(); + let mut packet = [0u8; 4000]; + let start = 48_000 * 7; + let mut feed = |aac: &mut AacEncoder, from: i64, packets: i64, frames: &mut Vec<_>| { + for p in 0..packets { + let time = from + p * 960; + let pcm: Vec = (0..960) + .flat_map(|i| { + let t = (time + i) as f32 / RATE as f32; + let v = (t * 440.0 * std::f32::consts::TAU).sin() * 0.3; + [v, v] + }) + .collect(); + let n = opus.encode_float(&pcm, &mut packet).unwrap(); + aac.push(&packet[..n], time, &mut |data, at| frames.push((data.len(), at))) + .unwrap(); + } + }; + feed(&mut aac, start, 50, &mut frames); + assert!(frames.len() >= 44, "{} frames", frames.len()); + assert_eq!(frames[0].1, start - FRAME as i64, "{frames:?}"); + assert!(frames.windows(2).all(|w| w[1].1 - w[0].1 == FRAME as i64), "{frames:?}"); + assert!(frames.iter().all(|(size, _)| *size > 0)); + // Two seconds of silence nobody sent: the clock restarts. + let after = start + 50 * 960 + 96_000; + let before = frames.len(); + feed(&mut aac, after, 10, &mut frames); + let restarted = frames[before..].iter().find(|(_, at)| *at >= after - FRAME as i64); + assert!(restarted.is_some(), "{:?}", &frames[before..]); + } +} diff --git a/crates/voelin-media/src/ffmpeg/avio.rs b/crates/voelin-media/src/ffmpeg/avio.rs new file mode 100644 index 0000000..e9ee90e --- /dev/null +++ b/crates/voelin-media/src/ffmpeg/avio.rs @@ -0,0 +1,256 @@ +//! A connection that bytes are written to through libavformat's protocols +//! (`rtmp://`, `rtmps://`, and whatever else the installed FFmpeg speaks). +//! +//! `avio_write` buffers and `avio_flush` sends; neither returns an error, +//! which lands in `AVIOContext.error` instead (found at load, +//! [`super::layout::avio_error`]), so every write and flush is checked +//! there. Every blocking call (connecting, sending, closing) polls an +//! interrupt callback, so a stuck network or a stop from another thread +//! never holds the caller for longer than FFmpeg's poll interval (100 ms) +//! once the abort flag is set. +#![allow(unsafe_code)] + +use std::ffi::c_int; +use std::sync::Arc; +use std::sync::OnceLock; +use std::sync::atomic::{AtomicBool, Ordering}; + +use super::layout::read; +use super::sys::{AVIO_FLAG_WRITE, InterruptCallback, Ptr, cstr}; +use super::{Ffmpeg, Io, take_log}; + +/// An open connection; closed (cleanly, as far as the abort flag lets it) +/// when dropped. +pub struct Connection { + ffmpeg: &'static Ffmpeg, + ctx: Ptr, + /// What the interrupt callback reads; kept alive as long as the context. + abort: Arc, +} + +// SAFETY: the context is only used through `&mut self` or by value, one +// thread at a time; FFmpeg's I/O contexts have no thread affinity. +unsafe impl Send for Connection {} + +unsafe extern "C" fn interrupted(opaque: Ptr) -> c_int { + // SAFETY: `opaque` is the `AtomicBool` of the `Arc` the connection + // holds for as long as FFmpeg may call this (until its context is + // closed). + c_int::from(unsafe { (*opaque.cast::()).load(Ordering::Relaxed) }) +} + +/// The FFmpeg messages about the connection since the last call, for an +/// error text. +fn messages() -> String { + let mut lines = Vec::new(); + for context in ["rtmp", "tls", "tcp"] { + lines.extend(take_log(context)); + } + lines.join("; ") +} + +impl Connection { + /// Whether this FFmpeg can open connections: libavformat's I/O was + /// loaded and its write errors can be read. + pub fn available() -> Result<(), String> { + Self::libraries().map(|_| ()) + } + + /// The process's FFmpeg and its I/O functions. + fn libraries() -> Result<(&'static Ffmpeg, &'static Io), String> { + let ffmpeg = Ffmpeg::get()?; + Ok((ffmpeg, ffmpeg.io.as_ref().map_err(Clone::clone)?)) + } + + /// Open `url` for writing, with protocol `options` (`rw_timeout`, + /// `rtmp_app`, `rtmp_playpath`, ...; options the protocol does not + /// know are ignored). Once `abort` is set, every blocking call of this + /// connection returns at once (with an error). + pub fn open( + url: &str, + options: &[(&str, &str)], + abort: Arc, + ) -> Result { + let (ffmpeg, io) = Self::libraries()?; + static NETWORK: OnceLock<()> = OnceLock::new(); + NETWORK.get_or_init(|| { + // SAFETY: no arguments; initialises the TLS libraries once. + unsafe { (io.api.avformat_network_init)() }; + }); + // Messages of an earlier connection are not about this one. + messages(); + let url = cstr(url); + let callback = InterruptCallback { + callback: Some(interrupted), + opaque: Arc::as_ptr(&abort).cast_mut().cast(), + }; + let mut ctx: Ptr = std::ptr::null_mut(); + // SAFETY: a dictionary built with av_dict_set and freed with + // av_dict_free; avio_open2 copies the callback and takes C strings + // that outlive the call. + let ret = unsafe { + let mut dict: Ptr = std::ptr::null_mut(); + for (key, value) in options { + let (key, value) = (cstr(key), cstr(value)); + (ffmpeg.api.av_dict_set)(&mut dict, key.as_ptr(), value.as_ptr(), 0); + } + let ret = + (io.api.avio_open2)(&mut ctx, url.as_ptr(), AVIO_FLAG_WRITE, &callback, &mut dict); + (ffmpeg.api.av_dict_free)(&mut dict); + ret + }; + if ret < 0 || ctx.is_null() { + return Err(failure(ffmpeg, ret)); + } + Ok(Self { ffmpeg, ctx, abort }) + } + + fn io(&self) -> &'static Io { + // Checked in `open`. + self.ffmpeg.io.as_ref().expect("a connection is only opened with libavformat's I/O") + } + + /// The write error of the context, if one happened. + fn check(&self) -> Result<(), String> { + // SAFETY: `error` is `AVIOContext.error` of this release (located and + // checked at load); the context is live. + let error: c_int = unsafe { read(self.ctx, self.io().error) }; + if error < 0 { Err(failure(self.ffmpeg, error)) } else { Ok(()) } + } + + /// Hand `data` to the connection (sent at the latest on [`flush`]). + /// + /// [`flush`]: Self::flush + pub fn write(&mut self, data: &[u8]) -> Result<(), String> { + for chunk in data.chunks(c_int::MAX as usize) { + // SAFETY: a live context; the slice is valid for its length. + unsafe { (self.io().api.avio_write)(self.ctx, chunk.as_ptr(), chunk.len() as c_int) }; + } + self.check() + } + + /// Send everything written so far. + pub fn flush(&mut self) -> Result<(), String> { + // SAFETY: a live context. + unsafe { (self.io().api.avio_flush)(self.ctx) }; + self.check() + } + + /// Close the connection (for RTMP: unpublish), reporting a write that + /// failed on the way. + pub fn close(mut self) -> Result<(), String> { + let error = self.check(); + let ret = self.close_context(); + error?; + if ret < 0 { Err(failure(self.ffmpeg, ret)) } else { Ok(()) } + } + + fn close_context(&mut self) -> c_int { + if self.ctx.is_null() { + return 0; + } + // SAFETY: a context from avio_open2; avio_closep sets it to NULL. + unsafe { (self.io().api.avio_closep)(&mut self.ctx) } + } + + /// Whether the abort flag is set. + pub fn aborted(&self) -> bool { + self.abort.load(Ordering::Relaxed) + } +} + +impl Drop for Connection { + fn drop(&mut self) { + self.close_context(); + } +} + +/// FFmpeg's text for `code` with what it logged about the connection. +fn failure(ffmpeg: &Ffmpeg, code: c_int) -> String { + let text = ffmpeg.api.error_text(code); + match messages() { + log if log.is_empty() => text, + log => format!("{log} ({text})"), + } +} + +#[cfg(test)] +mod tests { + use std::io::Read; + use std::net::TcpListener; + use std::time::{Duration, Instant}; + + use super::*; + + /// A file written through libavformat's `file:` protocol arrives whole, + /// and a write error (a connection the other side closed) is seen. + #[test] + fn writes_arrive_and_errors_are_seen() { + if Connection::available().is_err() { + eprintln!("no FFmpeg with libavformat, skipped"); + return; + } + let path = std::env::temp_dir().join(format!("voelin-avio-{}.bin", std::process::id())); + let abort = Arc::new(AtomicBool::new(false)); + let mut file = + Connection::open(&path.to_string_lossy(), &[], abort.clone()).expect("a file opens"); + file.write(b"hello ").unwrap(); + file.write(&[7; 100_000]).unwrap(); + file.flush().unwrap(); + file.close().unwrap(); + let written = std::fs::read(&path).unwrap(); + std::fs::remove_file(&path).unwrap(); + assert_eq!(written.len(), 100_006); + assert!(written.starts_with(b"hello ")); + + // A TCP peer that reads a little and goes away: the writes start + // failing, and the failure is reported. + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let port = listener.local_addr().unwrap().port(); + let peer = std::thread::spawn(move || { + let (mut socket, _) = listener.accept().unwrap(); + let mut buf = [0; 16]; + let _ = socket.read_exact(&mut buf); + }); + let mut tcp = Connection::open( + &format!("tcp://127.0.0.1:{port}"), + &[("rw_timeout", "2000000")], + abort, + ) + .unwrap(); + tcp.write(&[1; 16]).unwrap(); + tcp.flush().unwrap(); + peer.join().unwrap(); + let started = Instant::now(); + let error = loop { + match tcp.write(&[1; 65536]).and_then(|()| tcp.flush()) { + Ok(()) => assert!(started.elapsed() < Duration::from_secs(10), "no error"), + Err(e) => break e, + } + }; + assert!(!error.is_empty()); + assert!(tcp.close().is_err()); + } + + /// An abort flag set while connecting makes the connection give up. + #[test] + fn an_abort_stops_a_connection_attempt() { + if Connection::available().is_err() { + return; + } + // A listener that never accepts: the RTMP handshake waits forever. + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let port = listener.local_addr().unwrap().port(); + let abort = Arc::new(AtomicBool::new(false)); + let stopper = abort.clone(); + std::thread::spawn(move || { + std::thread::sleep(Duration::from_millis(300)); + stopper.store(true, Ordering::Relaxed); + }); + let started = Instant::now(); + let result = Connection::open(&format!("rtmp://127.0.0.1:{port}/app/key"), &[], abort); + assert!(result.is_err()); + assert!(started.elapsed() < Duration::from_secs(5), "{:?}", started.elapsed()); + drop(listener); + } +} diff --git a/crates/voelin-media/src/ffmpeg/layout.rs b/crates/voelin-media/src/ffmpeg/layout.rs index dbf2d2b..087bca9 100644 --- a/crates/voelin-media/src/ffmpeg/layout.rs +++ b/crates/voelin-media/src/ffmpeg/layout.rs @@ -15,20 +15,24 @@ //! | `AVHWFramesContext` `initial_pool_size`, `format`, `sw_format`, `width`, `height` | creating a frame pool | after seven pointers (eight up to libavutil 58: `internal`) | `device_ctx` must equal the device and both formats must be `AV_PIX_FMT_NONE` in a new context | //! | `AVFrame.buf[0]`, `AVFrame.hw_frames_ctx` | importing DMA-BUFs (zero-copy) | a table per libavutil major (56-61, 64-bit only; an unlisted major disables the import) | `buf[0]` of a frame from `av_frame_get_buffer` must hold that frame's `data[0]`; `hw_frames_ctx` of a frame from `av_hwframe_get_buffer` must reference the pool | //! | `AVHWDeviceContext.hwctx` | the `VADisplay`, for the GPU colour conversion of RGB DMA-BUFs | right after `type`, after one pointer (two up to libavutil 58: `internal`) | `type` must be the device's type in exactly that layout | +//! | `AVCodecContext.sample_fmt` | the AAC encoder of RTMP output (an audio encoder needs its sample format before it opens) | after `sample_rate` (option `ar`): directly from libavcodec 61 (then `ch_layout`), after `channels` (option `ac`) up to 60 | the neighbours' option offsets must match exactly one layout, and the field must be `AV_SAMPLE_FMT_NONE` in a new context | +//! | `AVIOContext.error` | RTMP output: a write that failed (`avio_write` and `avio_flush` return nothing) | searched: the `int` where a write callback's failure lands ([`avio_error`]) | exactly one `int` of the first 200 bytes changes to the callback's sentinel value | //! -//! A check that fails disables only what needs the field (VA-API, or the -//! DMA-BUF import), with the reason in the probe results. The first three -//! rows are found by searching, so a new major whose layout matches keeps -//! working without a change here; the last one is a table, because there is -//! nothing to anchor those offsets to, and an unlisted major turns the -//! DMA-BUF import off rather than guess (see [`frame_refs_table`]). +//! A check that fails disables only what needs the field (VA-API, the +//! DMA-BUF import, or RTMP output), with the reason in the probe results. +//! Most rows are found by searching, so a new major whose layout matches +//! keeps working without a change here; `buf[0]` / `hw_frames_ctx` is a +//! table, because there is nothing to anchor those offsets to, and an +//! unlisted major turns the DMA-BUF import off rather than guess (see +//! [`frame_refs_table`]). #![allow(unsafe_code)] use std::ffi::c_int; use std::mem::{offset_of, size_of}; use super::sys::{ - Api, BufferRefHead, FrameHead, NOPTS_VALUE, PICTURE_TYPE_NONE, Ptr, Rational, cstr, + Api, AvioHead, BufferRefHead, FormatApi, FrameHead, NOPTS_VALUE, PICTURE_TYPE_NONE, Ptr, + Rational, cstr, }; /// Offsets of `pict_type` and `pts` in `AVFrame`. @@ -228,6 +232,43 @@ fn locate_hw_frames(api: &Api, ctx: Ptr) -> Result { Ok(found) } +/// Where `sample_fmt` is in `AVCodecContext`, from the offsets of the +/// AVOptions of its neighbours, checked in a new context. +/// +/// An audio encoder must be told its sample format before it opens, and +/// that field has no AVOption. It follows `sample_rate` (option `ar`): +/// directly from libavcodec 61, with `ch_layout` (option `ch_layout`) after +/// it; after `channels` (option `ac`) up to 60, where `ch_layout` sits at +/// the end of the struct. +pub fn codec_sample_fmt(api: &Api) -> Result { + // SAFETY: a generic context (no codec); freed below. + let mut ctx = unsafe { (api.avcodec_alloc_context3)(std::ptr::null_mut()) }; + if ctx.is_null() { + return Err("avcodec_alloc_context3 failed".into()); + } + let offset = |name| option_offset(api, ctx, name); + let rate = offset("ar"); + let found = rate.and_then(|rate| { + let new = offset("ch_layout") == Some(rate + 8); + let old = offset("ac") == Some(rate + 4); + match (new, old) { + (true, false) => Some(rate + 4), + (false, true) => Some(rate + 8), + _ => None, + } + }); + // SAFETY: the offset lies before an option of this context, so inside + // it, and is int-aligned (a neighbour of int fields). + let result = match found { + Some(at) if unsafe { read::(ctx, at) } == -1 => Ok(at), + Some(_) => Err("AVCodecContext.sample_fmt check failed (not NONE in a new context)".into()), + None => Err("unknown AVCodecContext layout (sample_fmt not next to sample_rate)".into()), + }; + // SAFETY: allocated above. + unsafe { (api.avcodec_free_context)(&mut ctx) }; + result +} + /// Offsets in `AVHWFramesContext`. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct HwFramesFields { @@ -400,6 +441,77 @@ fn frame_refs_table(avutil_major: u32) -> Option { Some(FrameRefs { buf, hw_frames_ctx }) } +/// The bytes of an `AVIOContext` searched for `error`: inside the struct of +/// every release (208 bytes in libavformat 63, the smallest so far; 264 in +/// 58), and since libavformat 60 it lives inside the larger `FFIOContext`. +const AVIO_SPAN: usize = 200; + +/// The value [`avio_error`]'s write callback fails with: a negative number +/// no FFmpeg error code uses. +const AVIO_SENTINEL: c_int = -0x4E5F_0321; + +unsafe extern "C" fn refuse_write(_opaque: Ptr, _data: *mut u8, _size: c_int) -> c_int { + AVIO_SENTINEL +} + +/// Where `AVIOContext.error` is, found by search. +/// +/// `avio_write` and `avio_flush` return nothing; a failed write is only +/// stored in `error`, which moved between releases (120 bytes in +/// libavformat 58, after the checksum fields; 84 in 63, right after +/// `eof_reached`). A context whose write callback fails with a sentinel +/// value is written to and flushed, and the one `int` of its first +/// [`AVIO_SPAN`] bytes that changed to the sentinel is `error`. +pub fn avio_error(format: &FormatApi, api: &Api) -> Result { + const SIZE: usize = 4096; + type Snapshot = [c_int; AVIO_SPAN / 4]; + // SAFETY: a context of our own over a buffer from av_malloc, as + // avio_alloc_context documents; it is only written to through FFmpeg, + // and the snapshots read within its first AVIO_SPAN bytes (see there), + // at int-aligned offsets of an allocation FFmpeg aligns. The buffer + // (which FFmpeg may have replaced) and the context are freed as the + // documentation says: `av_freep(&ctx->buffer)`, then + // `avio_context_free`. + unsafe { + let buffer = (api.av_malloc)(SIZE).cast::(); + if buffer.is_null() { + return Err("av_malloc failed".into()); + } + let mut ctx = (format.avio_alloc_context)( + buffer, + SIZE as c_int, + 1, + std::ptr::null_mut(), + None, + Some(refuse_write), + None, + ); + if ctx.is_null() { + let mut buffer = buffer; + (api.av_freep)((&raw mut buffer).cast()); + return Err("avio_alloc_context failed".into()); + } + let snapshot = |ctx: Ptr| -> Snapshot { std::array::from_fn(|i| read(ctx, i * 4)) }; + let before = snapshot(ctx); + (format.avio_write)(ctx, b"voelin".as_ptr(), 6); + (format.avio_flush)(ctx); + let after = snapshot(ctx); + let head = ctx.cast::(); + (api.av_freep)((&raw mut (*head).buffer).cast()); + (format.avio_context_free)(&mut ctx); + let found: Vec = (0..before.len()) + .filter(|&i| before[i] != AVIO_SENTINEL && after[i] == AVIO_SENTINEL) + .map(|i| i * 4) + .collect(); + match found[..] { + [offset] => Ok(offset), + _ => Err(format!( + "unknown AVIOContext layout (write errors at {found:?}, not in exactly one place)" + )), + } + } +} + /// [`FrameRefs`] of this release, with `buf[0]` checked on a real frame /// (`hw_frames_ctx` is checked once a hardware frame exists, see /// [`check_hw_frames_ctx`]). diff --git a/crates/voelin-media/src/ffmpeg/mod.rs b/crates/voelin-media/src/ffmpeg/mod.rs index aed49f5..7839d11 100644 --- a/crates/voelin-media/src/ffmpeg/mod.rs +++ b/crates/voelin-media/src/ffmpeg/mod.rs @@ -18,6 +18,8 @@ use std::ffi::{CStr, c_char, c_int}; use std::path::PathBuf; use std::sync::{Mutex, OnceLock}; +pub mod audio; +pub mod avio; pub mod encoder; mod gpu; mod layout; @@ -33,7 +35,7 @@ pub use encoder::{ pub use sys::Search; use self::layout::{FrameFields, FrameRefs}; -use self::sys::{Api, Libs, LogCallback, Ptr, VaList}; +use self::sys::{Api, FormatApi, Libs, LogCallback, Ptr, VaList}; /// Pixel format numbers of this release (looked up by name). #[derive(Clone, Copy, Debug)] @@ -46,6 +48,13 @@ pub(crate) struct PixFmts { pub bgr0: Option, } +/// libavformat's I/O functions and where a write error lands +/// (`AVIOContext.error`, see [`layout::avio_error`]). +pub(crate) struct Io { + pub api: FormatApi, + pub error: usize, +} + /// What was loaded, for logs and the UI. #[derive(Clone, Debug, PartialEq, Eq)] pub struct LibraryInfo { @@ -56,8 +65,10 @@ pub struct LibraryInfo { /// `major.minor.micro` of libavcodec and libavutil. pub avcodec: String, pub avutil: String, - /// libavformat of the same release was found (for RTMP output later). + /// libavformat of the same release was found. pub avformat: bool, + /// Why RTMP output (libavformat's network I/O) cannot be used, if not. + pub rtmp: Result<(), String>, /// Why hardware frame pools (VA-API) cannot be used, if not. pub hw_frames: Result<(), String>, /// Why DMA-BUF frames cannot be imported (zero-copy), if not. @@ -73,6 +84,10 @@ pub struct Ffmpeg { pub(crate) codec_hw_frames: Result, /// `AVFrame.buf[0]` / `hw_frames_ctx`. pub(crate) frame_refs: Result, + /// `AVCodecContext.sample_fmt`, for the AAC encoder of RTMP output. + pub(crate) codec_sample_fmt: Result, + /// libavformat's I/O for RTMP output. + pub(crate) io: Result, pub(crate) pix: PixFmts, info: LibraryInfo, } @@ -109,6 +124,11 @@ impl Ffmpeg { }; let codec_hw_frames = layout::codec_hw_frames(&api); let frame_refs = layout::frame_refs(&api, yuv420p); + let codec_sample_fmt = layout::codec_sample_fmt(&api); + let io = libs.format_api().and_then(|format| { + let error = layout::avio_error(&format, &api)?; + Ok(Io { api: format, error }) + }); // SAFETY: no arguments; returns version numbers and a static string. let (avcodec, avutil, release) = unsafe { ( @@ -123,6 +143,10 @@ impl Ffmpeg { avcodec: version_text(avcodec), avutil: version_text(avutil), avformat: libs.avformat.is_some(), + rtmp: match (&io, &codec_sample_fmt) { + (Err(e), _) | (_, Err(e)) => Err(e.clone()), + _ => Ok(()), + }, hw_frames: codec_hw_frames.clone().map(|_| ()), dmabuf_import: match (&codec_hw_frames, &frame_refs, pix.drm_prime) { (Err(e), _, _) | (_, Err(e), _) => Err(e.clone()), @@ -130,7 +154,17 @@ impl Ffmpeg { _ => Ok(()), }, }; - Ok(Self { api, _libs: libs, frame, codec_hw_frames, frame_refs, pix, info }) + Ok(Self { + api, + _libs: libs, + frame, + codec_hw_frames, + frame_refs, + codec_sample_fmt, + io, + pix, + info, + }) } /// The process's FFmpeg, loaded on first use from [`Search::from_env`] @@ -253,11 +287,37 @@ mod tests { assert!(!info.release.is_empty()); assert!(info.avcodec.split('.').count() == 3); assert!(info.hw_frames.is_ok(), "{info:?}"); + // libavformat comes with libavcodec in every package. + assert!(info.rtmp.is_ok(), "{info:?}"); if cfg!(target_pointer_width = "64") { assert!(ffmpeg.frame_refs.is_ok(), "{:?}", ffmpeg.frame_refs); } } + /// `AVIOContext.error` is where the headers of the installed releases + /// put it (compiled with `offsetof`: 120 in libavformat 58, FFmpeg 4.4; + /// 84 in 63, FFmpeg 9.0). + #[cfg(target_pointer_width = "64")] + #[test] + fn write_errors_are_found_where_the_headers_put_them() { + let Ok(ffmpeg) = Ffmpeg::get() else { return }; + let io = ffmpeg.io.as_ref().expect("libavformat's I/O"); + // SAFETY: no arguments. + let major = unsafe { (io.api.avformat_version)() } >> 16; + match major { + 58 => assert_eq!(io.error, 120), + 63 => assert_eq!(io.error, 84), + _ => {} + } + // And `AVCodecContext.sample_fmt`: 408 in libavcodec 58, 348 in 63. + // SAFETY: no arguments. + match unsafe { (ffmpeg.api.avcodec_version)() } >> 16 { + 58 => assert_eq!(ffmpeg.codec_sample_fmt, Ok(408)), + 63 => assert_eq!(ffmpeg.codec_sample_fmt, Ok(348)), + _ => {} + } + } + #[test] fn no_ffmpeg_in_an_empty_directory() { let dir = std::env::temp_dir().join(format!("voelin-no-ffmpeg-{}", std::process::id())); diff --git a/crates/voelin-media/src/ffmpeg/sys.rs b/crates/voelin-media/src/ffmpeg/sys.rs index 1cadd07..d409282 100644 --- a/crates/voelin-media/src/ffmpeg/sys.rs +++ b/crates/voelin-media/src/ffmpeg/sys.rs @@ -87,6 +87,15 @@ pub struct BufferRefHead { pub data: *mut u8, } +/// The leading fields of `AVIOContext` (`av_class`, `buffer`), unchanged +/// since libavformat 53. Only `buffer` is read, to free the buffer of a +/// context made with `avio_alloc_context`. +#[repr(C)] +pub struct AvioHead { + pub av_class: Ptr, + pub buffer: *mut u8, +} + /// `AVDRMObjectDescriptor` (`libavutil/hwcontext_drm.h`, unchanged since it /// was added in libavutil 55). #[repr(C)] @@ -167,17 +176,17 @@ pub const EOF: c_int = err_tag(b'E', b'O', b'F', b' '); /// `AVERROR_OPTION_NOT_FOUND`. pub const OPTION_NOT_FOUND: c_int = err_tag(0xF8, b'O', b'P', b'T'); -/// Declares the function table: every function, its library, its C +/// Declares a function table: every function, its library, its C /// signature. `resolve` looks all of them up; a missing one fails the load. macro_rules! api { - ($($lib:ident { $(fn $name:ident($($arg:ident: $ty:ty),*) $(-> $ret:ty)?;)* })*) => { - /// FFmpeg functions used by this crate. + ($(#[$doc:meta])* $api:ident { $($lib:ident { $(fn $name:ident($($arg:ident: $ty:ty),*) $(-> $ret:ty)?;)* })* }) => { + $(#[$doc])* #[allow(non_snake_case, dead_code)] - pub struct Api { + pub struct $api { $($(pub $name: unsafe extern "C" fn($($ty),*) $(-> $ret)?,)*)* } - impl Api { + impl $api { /// # Safety /// The libraries must be FFmpeg's, so the symbols have the /// declared signatures. @@ -191,6 +200,8 @@ macro_rules! api { } api! { + /// FFmpeg functions used by this crate (libavutil and libavcodec). + Api { Util { fn avutil_version() -> c_uint; fn av_version_info() -> *const c_char; @@ -243,6 +254,11 @@ api! { fn av_hwframe_get_buffer(frames: Ptr, frame: Ptr, flags: c_int) -> c_int; fn av_hwframe_transfer_data(dst: Ptr, src: Ptr, flags: c_int) -> c_int; fn av_hwframe_map(dst: Ptr, src: Ptr, flags: c_int) -> c_int; + fn av_get_sample_fmt(name: *const c_char) -> c_int; + fn av_malloc(size: usize) -> *mut c_void; + fn av_freep(ptr: *mut c_void); + fn av_dict_set(dict: *mut Ptr, key: *const c_char, value: *const c_char, flags: c_int) -> c_int; + fn av_dict_free(dict: *mut Ptr); } Codec { @@ -256,9 +272,64 @@ api! { fn av_packet_alloc() -> Ptr; fn av_packet_free(packet: *mut Ptr); fn av_packet_unref(packet: Ptr); + fn avcodec_find_decoder_by_name(name: *const c_char) -> Ptr; + fn avcodec_send_packet(ctx: Ptr, packet: Ptr) -> c_int; + fn avcodec_receive_frame(ctx: Ptr, frame: Ptr) -> c_int; + } } } +api! { + /// libavformat's I/O functions, for RTMP output: the connection is + /// libavformat's (`rtmp://`, `rtmps://`); the FLV inside it is ours + /// (`studio::output::flv`), so no muxer struct is ever touched. + FormatApi { + Format { + fn avformat_version() -> c_uint; + fn avformat_network_init() -> c_int; + fn avio_open2( + ctx: *mut Ptr, + url: *const c_char, + flags: c_int, + interrupt: *const InterruptCallback, + options: *mut Ptr + ) -> c_int; + fn avio_write(ctx: Ptr, data: *const u8, size: c_int); + fn avio_flush(ctx: Ptr); + fn avio_closep(ctx: *mut Ptr) -> c_int; + fn avio_alloc_context( + buffer: *mut u8, + size: c_int, + write_flag: c_int, + opaque: Ptr, + read: Option, + write: Option, + seek: Option + ) -> Ptr; + fn avio_context_free(ctx: *mut Ptr); + } + } +} + +/// `int (*)(void *opaque, uint8_t *buf, int size)`: `read_packet` and +/// `write_packet` of `avio_alloc_context` (`const uint8_t *` for writing +/// since libavformat 61, the same in the ABI). +pub type IoCallback = unsafe extern "C" fn(Ptr, *mut u8, c_int) -> c_int; +/// `int64_t (*)(void *opaque, int64_t offset, int whence)`. +pub type SeekCallback = unsafe extern "C" fn(Ptr, i64, c_int) -> i64; + +/// `AVIOInterruptCB` (`int (*callback)(void *); void *opaque;`), unchanged +/// since it was added (libavformat 53). FFmpeg calls it while it waits for +/// the network; a non-zero return aborts the operation. +#[repr(C)] +pub struct InterruptCallback { + pub callback: Option c_int>, + pub opaque: Ptr, +} + +/// `AVIO_FLAG_WRITE`. +pub const AVIO_FLAG_WRITE: c_int = 2; + /// `void (*)(void *avcl, int level, const char *fmt, va_list vl)`. pub type LogCallback = unsafe extern "C" fn(Ptr, c_int, *const c_char, VaList); @@ -266,6 +337,7 @@ pub type LogCallback = unsafe extern "C" fn(Ptr, c_int, *const c_char, VaList); enum Lib { Util, Codec, + Format, } /// The opened libraries. Never closed: FFmpeg keeps global state (codec @@ -275,19 +347,30 @@ pub struct Libs { /// libavutil where symbols are not found through libavcodec's handle /// (Windows: `GetProcAddress` does not search dependencies). avutil: Option, - /// libavformat, if present (for later use: RTMP output). + /// libavformat, if present (RTMP output). pub avformat: Option, /// Where libavcodec was found. pub path: PathBuf, } impl Libs { + /// libavformat's functions, if libavformat was found and has them all. + pub fn format_api(&self) -> Result { + if self.avformat.is_none() { + return Err(format!("no libavformat of the release of {}", self.path.display())); + } + // SAFETY: the library is libavformat (found by its file name, of + // libavcodec's major), whose functions have the declared signatures. + unsafe { FormatApi::resolve(self) } + } + /// # Safety /// `T` must be the symbol's actual type. unsafe fn symbol(&self, lib: Lib, name: &str) -> Result { let library = match lib { Lib::Util => self.avutil.as_ref().unwrap_or(&self.avcodec), Lib::Codec => &self.avcodec, + Lib::Format => self.avformat.as_ref().ok_or("no libavformat")?, }; // SAFETY: the caller guarantees the type; the library stays loaded // for the life of the process (it is never dropped, see `Libs`). diff --git a/crates/voelin-media/src/frame.rs b/crates/voelin-media/src/frame.rs index b329bd2..46e6379 100644 --- a/crates/voelin-media/src/frame.rs +++ b/crates/voelin-media/src/frame.rs @@ -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 { diff --git a/crates/voelin-media/src/lib.rs b/crates/voelin-media/src/lib.rs index c832d2c..b74516b 100644 --- a/crates/voelin-media/src/lib.rs +++ b/crates/voelin-media/src/lib.rs @@ -70,6 +70,9 @@ pub enum Error { CaptureUnavailable { backend: &'static str, reason: String }, #[error("{backend} capture: {message}")] Capture { backend: &'static str, message: String }, + /// A studio output (WHIP, RTMP) failed or was refused. + #[error("{output}: {message}")] + Output { output: &'static str, message: String }, #[error("capture source not found: {0:?}")] SourceNotFound(SourceId), #[error("the user cancelled the capture")] diff --git a/crates/voelin-media/src/studio/camera.rs b/crates/voelin-media/src/studio/camera.rs index a4bad62..298c967 100644 --- a/crates/voelin-media/src/studio/camera.rs +++ b/crates/voelin-media/src/studio/camera.rs @@ -12,31 +12,46 @@ //! Every camera pixel format PipeWire can give us (YUY2, UYVY, NV12, I420, //! and the packed 24- and 32-bit ones) is converted to RGBA or taken as BGRA //! for the compositor, in one SIMD pass into a pooled frame, so a running -//! camera allocates nothing per frame. Compressed formats (MJPEG) are not -//! offered, so a camera that has both gives us its raw one. +//! camera allocates nothing per frame. MJPEG, which many USB cameras offer +//! for their large sizes only (1080p and up at full rate), is decoded with +//! `zune-jpeg` straight into pooled RGBA frames on a thread of its own: +//! the newest picture wins, so a decode that falls behind drops pictures +//! instead of holding up the camera. A raw format is preferred where it +//! gives the wanted size at the wanted rate (no decoding at all). //! //! [`SYNTHETIC`] is a camera that is always there: the test pattern. Tests //! and machines without a camera use it. //! -//! Windows and Android have no camera backend yet ([`list`] returns only the -//! synthetic one). +//! Windows: Media Foundation (`mf`): `MFEnumDeviceSources` lists the +//! cameras, an `IMFSourceReader` captures as NV12, decoding MJPEG on the way. +//! 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"; const BACKEND: &str = "camera"; +#[cfg(windows)] +mod mf; + /// A pixel format a camera delivers. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub enum Pixel { @@ -53,7 +68,8 @@ pub enum Pixel { /// 3 bytes per pixel. Rgb24, Bgr24, - /// Motion JPEG; not offered (see the [module docs](self)). + /// Motion JPEG, decoded on a thread of its own (see the + /// [module docs](self)). Mjpeg, } @@ -108,9 +124,12 @@ pub struct Camera { /// on Linux, or [`SYNTHETIC`]. pub id: String, pub name: String, - /// Where the list came from (`"v4l2"`, `"synthetic"`). + /// Where the list came from (`"v4l2"`, `"synthetic"`, `"camera2"`). pub backend: &'static str, pub formats: Vec, + /// Shown mirrored by default: a camera facing the user (webcams, a + /// phone's front camera), not one facing away. + pub mirrored: bool, } /// Every camera this session can use. Never fails: a device that cannot be @@ -119,15 +138,159 @@ pub fn list() -> Vec { // Devices are listed where they can be captured: through PipeWire. #[cfg(all(target_os = "linux", feature = "pipewire"))] let devices = v4l2::list(); - #[cfg(not(all(target_os = "linux", feature = "pipewire")))] + #[cfg(windows)] + let devices = mf::list(); + #[cfg(not(any(all(target_os = "linux", feature = "pipewire"), windows)))] let devices = Vec::new(); let synthetic = Camera { id: SYNTHETIC.to_owned(), name: "Test pattern".to_owned(), backend: "synthetic", formats: vec![Format { pixel: Pixel::Bgrx, sizes: vec![(1280, 720)], max_fps: 60 }], + mirrored: true, }; - devices.into_iter().chain([synthetic]).collect() + let external = provider().map(|p| p.list()).unwrap_or_default(); + external.into_iter().chain(devices).chain([synthetic]).collect() +} + +/// Cameras of a platform API outside this crate, registered by the app at +/// start like the external screen capture ([`crate::capture::external`]): +/// on Android, Camera2 through the app's Kotlin side. +pub trait CameraProvider: Send + Sync { + /// Short name for logs and [`Capture::backend`] (`"camera2"`). + fn name(&self) -> &'static str; + + /// The cameras, in the order a picker shows them. + fn list(&self) -> Vec; + + /// Open `device` and feed `sink` with up to `fps` frames a second at + /// about `size` (`None`: the camera's default); what fails after the + /// start (a permission refused, the camera taken by another app) goes + /// to `feed`. The camera stops when the returned value is dropped. + fn start( + &self, + device: &str, + size: Option<(u32, u32)>, + fps: u32, + sink: Box, + feed: Arc, + ) -> Result>; +} + +static PROVIDER: Mutex>> = Mutex::new(None); + +/// Make [`list`] and [`Capture::start`] use `provider` (`None`: only the +/// built-in cameras). +pub fn set_provider(provider: Option>) { + *PROVIDER.lock().unwrap_or_else(PoisonError::into_inner) = provider; +} + +fn provider() -> Option> { + PROVIDER.lock().unwrap_or_else(PoisonError::into_inner).clone() +} + +/// A camera picture in three 4:2:0 planes whose chroma samples may lie +/// apart (`uv_step` 2), as Android's `YUV_420_888` hands them over, and the +/// clockwise turn that makes it upright. +#[derive(Clone, Copy, Debug)] +pub struct YuvPlanes<'a> { + pub width: u32, + pub height: u32, + pub y: &'a [u8], + pub y_stride: usize, + pub u: &'a [u8], + pub v: &'a [u8], + /// Bytes per chroma row (both planes). + pub uv_stride: usize, + /// Bytes from one chroma sample to the next in a row: 1 (planar) or 2 + /// (interleaved). + pub uv_step: usize, + /// The chroma as one interleaved block with U first (NV12), when it is + /// one: then taken as it is. + pub nv12: Option<&'a [u8]>, + /// Clockwise degrees: 0, 90, 180 or 270. + pub rotation: u32, +} + +impl<'a> YuvPlanes<'a> { + /// The picture as a frame: borrowed when it is upright and planar or + /// NV12, else gathered (and turned) into `scratch` as I420; `scratch` + /// keeps its capacity, so nothing is allocated once it has grown. + pub fn frame(&self, timestamp: Duration, scratch: &'a mut Vec) -> Result> { + let (w, h) = (self.width as usize, self.height as usize); + if w == 0 || h == 0 { + return Err(Error::InvalidFrame(format!("{w}x{h} camera frame"))); + } + let rotation = self.rotation / 90 % 4 * 90; + let (width, height) = (self.width, self.height); + if rotation == 0 { + let y = PlaneRef::new(self.y, self.y_stride); + let pixels = if self.uv_step == 1 { + let u = PlaneRef::new(self.u, self.uv_stride); + let v = PlaneRef::new(self.v, self.uv_stride); + Some(PixelsRef::I420 { y, u, v }) + } else { + self.nv12.map(|uv| PixelsRef::Nv12 { y, uv: PlaneRef::new(uv, self.uv_stride) }) + }; + if let Some(pixels) = pixels { + return Ok(FrameRef { width, height, timestamp, pixels }); + } + } + let (cw, ch) = crate::frame::chroma_size(self.width, self.height); + let turned = rotation % 180 == 90; + let (ow, oh) = if turned { (h, w) } else { (w, h) }; + let (ocw, och) = if turned { (ch, cw) } else { (cw, ch) }; + scratch.resize(ow * oh + 2 * ocw * och, 0); + { + let (y, rest) = scratch.split_at_mut(ow * oh); + let (u, v) = rest.split_at_mut(ocw * och); + turn(self.y, self.y_stride, 1, w, h, rotation, y)?; + turn(self.u, self.uv_stride, self.uv_step, cw, ch, rotation, u)?; + turn(self.v, self.uv_stride, self.uv_step, cw, ch, rotation, v)?; + } + let scratch: &'a [u8] = scratch; + let (y, rest) = scratch.split_at(ow * oh); + let (u, v) = rest.split_at(ocw * och); + let pixels = PixelsRef::I420 { + y: PlaneRef::new(y, ow), + u: PlaneRef::new(u, ocw), + v: PlaneRef::new(v, ocw), + }; + Ok(FrameRef { width: ow as u32, height: oh as u32, timestamp, pixels }) + } +} + +/// Copy the `w` x `h` samples of a plane (`step` bytes apart in a row, +/// `stride` bytes per row) into `out`, turned clockwise by `rotation`, rows +/// without padding. +fn turn( + src: &[u8], + stride: usize, + step: usize, + w: usize, + h: usize, + rotation: u32, + out: &mut [u8], +) -> Result<()> { + if src.len() < (h - 1) * stride + (w - 1) * step + 1 { + return Err(Error::InvalidFrame(format!( + "camera plane of {} bytes is too small for {w}x{h}", + src.len() + ))); + } + for y in 0..h { + let row = &src[y * stride..]; + for x in 0..w { + let at = match rotation { + 90 => x * h + (h - 1 - y), + 180 => (h - 1 - y) * w + (w - 1 - x), + 270 => (w - 1 - x) * h + y, + _ => y * w + x, + }; + out[at] = row[x * step]; + } + } + Ok(()) } /// A running camera; stops when dropped. @@ -135,8 +298,13 @@ pub struct Capture { backend: &'static str, device: String, screen: Option>, + /// A [`CameraProvider`]'s camera, stopped when dropped. + _external: Option>, #[cfg(all(target_os = "linux", feature = "pipewire"))] stream: Option, + /// Stops its thread when dropped. + #[cfg(windows)] + _mf: Option, } impl Capture { @@ -174,18 +342,62 @@ 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)] + _mf: None, }); } #[cfg(all(target_os = "linux", feature = "pipewire"))] { + let formats = v4l2::list() + .into_iter() + .find(|c| c.id == wanted) + .map(|c| c.formats) + .unwrap_or_default(); let stream = - pipewire_camera::Stream::start(&wanted, size, fps, feed, background).await?; + 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(not(all(target_os = "linux", feature = "pipewire")))] + #[cfg(windows)] + { + let stream = mf::Stream::start(&wanted, size, fps, feed, background)?; + Ok(Self { + backend: "mediafoundation", + device: wanted, + screen: None, + _external: None, + _mf: Some(stream), + }) + } + #[cfg(not(any(all(target_os = "linux", feature = "pipewire"), windows)))] { let _ = (size, feed, background); Err(crate::Error::CaptureUnavailable { @@ -195,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 { @@ -455,6 +668,7 @@ mod v4l2 { name: if name.is_empty() { path.to_string_lossy().into_owned() } else { name }, backend: "v4l2", formats, + mirrored: true, }) }) .collect() @@ -472,8 +686,8 @@ mod pipewire_camera { use pipewire as pw; use pw::spa::param::format::{FormatProperties, MediaSubtype, MediaType}; use pw::spa::param::video::{VideoFormat, VideoInfoRaw}; - use pw::spa::pod::{Object, Value, property}; - use pw::spa::utils::{Fraction, Rectangle, SpaTypes}; + use pw::spa::pod::{ChoiceValue, Object, Property, PropertyFlags, Value, property}; + use pw::spa::utils::{Choice, ChoiceEnum, ChoiceFlags, Fraction, Rectangle, SpaTypes}; use tracing::{debug, warn}; use crate::capture::FramePacer; @@ -486,7 +700,7 @@ mod pipewire_camera { use crate::studio::source::deliver; use crate::{Error, Result}; - use super::BACKEND; + use super::{BACKEND, Format, Pixel, mjpeg}; /// The pixel formats we take, in order of preference; all of them the /// compositor can use after one conversion. @@ -509,22 +723,27 @@ mod pipewire_camera { impl Stream { /// Connect to `device` (a `/dev/video*` path) and feed `feed`. + /// `formats` are what V4L2 lists for it (empty if unknown). pub async fn start( device: &str, size: Option<(u32, u32)>, fps: u32, + formats: Vec, feed: Arc, background: Background, ) -> Result { // The daemon first: it needs no dialog. A sandbox refuses it, and // then the portal's connection is the only way in. - let direct = connect(None, device, size, fps, feed.clone(), background.clone()); + let offers = enum_formats(size, fps, &formats) + .map_err(|e| Error::Capture { backend: BACKEND, message: e })?; + let direct = + connect(None, device, offers.clone(), fps, feed.clone(), background.clone()); match direct { Ok(thread) => Ok(Self { backend: "pipewire", _thread: thread }), Err(direct) => { debug!("PipeWire cameras: {direct}; asking the camera portal"); let fd = portal_fd().await?; - let thread = connect(Some(fd), device, size, fps, feed, background)?; + let thread = connect(Some(fd), device, offers, fps, feed, background)?; Ok(Self { backend: "portal", _thread: thread }) } } @@ -564,7 +783,7 @@ mod pipewire_camera { fn connect( fd: Option, device: &str, - size: Option<(u32, u32)>, + offers: Vec>, fps: u32, feed: Arc, background: Background, @@ -574,7 +793,7 @@ mod pipewire_camera { // No target node: the session manager connects the stream to the // default camera. Picking one of several by `api.v4l2.path` // needs a registry round trip and is not done yet. - camera_stream(core, mainloop, None, &device, size, fps, feed, background) + camera_stream(core, mainloop, None, &device, &offers, fps, feed, background) }) .map_err(|e| Error::Capture { backend: BACKEND, message: e }) } @@ -585,10 +804,20 @@ mod pipewire_camera { pool: FramePool, pacer: FramePacer, started: Instant, - format: Option<(VideoFormat, u32, u32)>, + format: Option, + /// The MJPEG decoder, once MJPEG was negotiated. + mjpeg: Option, mainloop: pw::main_loop::MainLoopWeak, } + /// What the camera and we agreed on. + #[derive(Clone, Copy, Debug)] + enum Negotiated { + Raw(VideoFormat, u32, u32), + /// The size comes with each picture. + Mjpeg, + } + type Parts = (pw::stream::StreamRc, pw::stream::StreamListener); #[allow(clippy::too_many_arguments)] @@ -597,7 +826,7 @@ mod pipewire_camera { mainloop: &pw::main_loop::MainLoopRc, target: Option, device: &str, - size: Option<(u32, u32)>, + offers: &[Vec], fps: u32, feed: Arc, background: Background, @@ -618,6 +847,7 @@ mod pipewire_camera { pacer: FramePacer::new(Some(fps)), started: Instant::now(), format: None, + mjpeg: None, mainloop: mainloop.downgrade(), }; let listener = stream @@ -640,19 +870,24 @@ mod pipewire_camera { if id != pw::spa::param::ParamType::Format.as_raw() { return; } - let Ok((MediaType::Video, MediaSubtype::Raw)) = - pw::spa::param::format_utils::parse_format(param) - else { - return; - }; - let mut info = VideoInfoRaw::new(); - if let Err(e) = info.parse(param) { - warn!("cannot parse the camera format: {e}"); - return; + match pw::spa::param::format_utils::parse_format(param) { + Ok((MediaType::Video, MediaSubtype::Raw)) => { + let mut info = VideoInfoRaw::new(); + if let Err(e) = info.parse(param) { + warn!("cannot parse the camera format: {e}"); + return; + } + let size = info.size(); + debug!(format = ?info.format(), size.width, size.height, "camera format"); + state.format = + Some(Negotiated::Raw(info.format(), size.width, size.height)); + } + Ok((MediaType::Video, MediaSubtype::Mjpg)) => { + debug!("camera format MJPEG"); + state.format = Some(Negotiated::Mjpeg); + } + _ => return, } - let size = info.size(); - debug!(format = ?info.format(), size.width, size.height, "camera format"); - state.format = Some((info.format(), size.width, size.height)); // Only buffers the CPU can read: a camera node may otherwise // hand out DMA-BUFs, which this path cannot map. if let Err(e) = use_memory_buffers(stream) { @@ -662,9 +897,7 @@ mod pipewire_camera { .process(process) .register() .map_err(|e| format!("PipeWire listener: {e}"))?; - let formats = enum_formats(size, fps)?; - let mut pods = - formats.iter().map(|f| pod(f)).collect::, _>>()?; + let mut pods = offers.iter().map(|f| pod(f)).collect::, _>>()?; stream .connect( pw::spa::utils::Direction::Input, @@ -691,62 +924,137 @@ mod pipewire_camera { stream.update_params(&mut [pod(&buffers)?]).map_err(|e| e.to_string()) } - /// The offers, best first: every pixel format at the wanted size, then - /// every pixel format at any size. A camera has a handful of fixed - /// sizes, and PipeWire takes the first offer that fits, so the exact - /// size has to come before the range or a range's smallest size wins. + type Sizes = Vec<(u32, u32)>; + + /// The PipeWire format of a camera pixel format: `None` for MJPEG. + fn spa_format(pixel: Pixel) -> Option { + Some(match pixel { + Pixel::Nv12 => VideoFormat::NV12, + Pixel::I420 => VideoFormat::I420, + Pixel::Yuyv => VideoFormat::YUY2, + Pixel::Uyvy => VideoFormat::UYVY, + Pixel::Bgrx => VideoFormat::BGRx, + Pixel::Rgbx => VideoFormat::RGBx, + Pixel::Bgr24 => VideoFormat::BGR, + Pixel::Rgb24 => VideoFormat::RGB, + Pixel::Mjpeg => return None, + }) + } + + /// The offers, best first, from what the driver lists for the camera + /// (`formats`, from V4L2): + /// + /// 1. the wanted size at least at the wanted rate, raw formats first + /// (nothing to decode); + /// 2. the wanted size at any rate, MJPEG first: cameras give their large + /// sizes at full rate only compressed (a raw 1080p over USB 2 is a few + /// frames a second); + /// 3. every format at the sizes it lists (the one nearest the wanted + /// size first), raw formats first. + /// + /// Every offer names sizes the driver lists for its format: PipeWire's + /// V4L2 source does not always check (it took a fixed size on trust, and + /// a range too, and then failed to set NV12 at 2560x1440 on a camera + /// that has that size only as MJPEG). PipeWire takes the first offer + /// that fits. Without a list (a camera only the portal can see), every + /// format at the wanted size, then at any. fn enum_formats( size: Option<(u32, u32)>, fps: u32, + formats: &[Format], ) -> std::result::Result>, String> { let (w, h) = size.unwrap_or((1280, 720)); - let exact = Rectangle { width: w.max(2), height: h.max(2) }; - let mut formats = Vec::new(); - for fixed in [true, false] { - for format in FORMATS { - let mut properties = vec![ - property!(FormatProperties::MediaType, Id, MediaType::Video), - property!(FormatProperties::MediaSubtype, Id, MediaSubtype::Raw), - property!(FormatProperties::VideoFormat, Id, format), - ]; - properties.push(if fixed { - property!(FormatProperties::VideoSize, Rectangle, exact) - } else { - property!( - FormatProperties::VideoSize, - Choice, - Range, - Rectangle, - exact, - Rectangle { width: 1, height: 1 }, - Rectangle { width: 16384, height: 16384 } - ) - }); - // Any rate the camera has, preferring the wanted one: a - // camera offers fixed rates (often only 30), and - // `FramePacer` brings whatever we get down to `fps`. - properties.push(property!( - FormatProperties::VideoFramerate, - Choice, - Range, - Fraction, - Fraction { num: fps, denom: 1 }, - Fraction { num: 0, denom: 1 }, - Fraction { num: 1000, denom: 1 } - )); - formats.push(serialize(Value::Object(Object { - type_: SpaTypes::ObjectParamFormat.as_raw(), - id: pw::spa::param::ParamType::EnumFormat.as_raw(), - properties, - }))?); + let exact = (w.max(2), h.max(2)); + let rect = |(width, height): (u32, u32)| Rectangle { width, height }; + // Our order of preference among raw formats, then MJPEG. + let rank = |f: Option| match f { + Some(f) => FORMATS.iter().position(|x| *x == f).unwrap_or(FORMATS.len()), + None => FORMATS.len() + 1, + }; + let mut known: Vec<(Option, Sizes)> = formats + .iter() + .map(|f| (spa_format(f.pixel), f.sizes.clone())) + .filter(|(_, sizes)| !sizes.is_empty()) + .collect(); + known.sort_by_key(|(f, _)| rank(*f)); + // Format (`None`: MJPEG), sizes (empty: any), lowest rate. + let mut offers: Vec<(Option, Sizes, u32)> = Vec::new(); + if known.is_empty() { + let all: Vec> = + FORMATS.iter().copied().map(Some).chain([None]).collect(); + offers.extend(all.iter().map(|f| (*f, vec![exact], fps))); + offers.extend(all.iter().map(|f| (*f, Vec::new(), 0))); + } else { + let at_size: Vec> = + known.iter().filter(|(_, sizes)| sizes.contains(&exact)).map(|(f, _)| *f).collect(); + offers.extend(at_size.iter().map(|f| (*f, vec![exact], fps))); + let mjpeg_first = at_size + .iter() + .filter(|f| f.is_none()) + .chain(at_size.iter().filter(|f| f.is_some())); + offers.extend(mjpeg_first.map(|f| (*f, vec![exact], 0))); + let area = |(w, h): (u32, u32)| i64::from(w) * i64::from(h); + for (format, sizes) in &known { + let mut sizes = sizes.clone(); + sizes.sort_by_key(|s| (area(*s) - area(exact)).abs()); + offers.push((*format, sizes, 0)); } } - Ok(formats) + let mut params = Vec::with_capacity(offers.len()); + for (format, sizes, min_fps) in offers { + let mut properties = vec![ + property!(FormatProperties::MediaType, Id, MediaType::Video), + property!( + FormatProperties::MediaSubtype, + Id, + if format.is_some() { MediaSubtype::Raw } else { MediaSubtype::Mjpg } + ), + ]; + if let Some(format) = format { + properties.push(property!(FormatProperties::VideoFormat, Id, format)); + } + // A list (also of one size): the source checks each against + // what the driver lists. No list: any size, the wanted first. + let choice = match sizes.split_first() { + Some((first, _)) => ChoiceEnum::Enum { + default: rect(*first), + alternatives: sizes.iter().copied().map(rect).collect(), + }, + None => ChoiceEnum::Range { + default: rect(exact), + min: Rectangle { width: 1, height: 1 }, + max: Rectangle { width: 16384, height: 16384 }, + }, + }; + properties.push(Property { + key: FormatProperties::VideoSize.as_raw(), + flags: PropertyFlags::empty(), + value: Value::Choice(ChoiceValue::Rectangle(Choice(ChoiceFlags::empty(), choice))), + }); + // The wanted rate or any above it (any at all in the later + // passes): a camera offers fixed rates (often only 30), and + // `FramePacer` brings whatever we get down to `fps`. + properties.push(property!( + FormatProperties::VideoFramerate, + Choice, + Range, + Fraction, + Fraction { num: fps, denom: 1 }, + Fraction { num: min_fps, denom: 1 }, + Fraction { num: 1000, denom: 1 } + )); + params.push(serialize(Value::Object(Object { + type_: SpaTypes::ObjectParamFormat.as_raw(), + id: pw::spa::param::ParamType::EnumFormat.as_raw(), + properties, + }))?); + } + Ok(params) } fn process(stream: &pw::stream::Stream, state: &mut State) { let Some(mut buffer) = stream.dequeue_buffer() else { return }; - let Some((format, width, height)) = state.format else { return }; + let Some(negotiated) = state.format else { return }; let timestamp = state.started.elapsed(); if state.feed.is_closed() { if let Some(mainloop) = state.mainloop.upgrade() { @@ -763,9 +1071,34 @@ mod pipewire_camera { return; } let (offset, stride) = (chunk.offset() as usize, chunk.stride() as usize); + let size = chunk.size() as usize; let Some(bytes) = data.data() else { return }; let Some(bytes) = bytes.get(offset..) else { return }; - if let Err(e) = take(state, format, width, height, stride, bytes, timestamp) { + let result = match negotiated { + Negotiated::Raw(format, width, height) => { + take(state, format, width, height, stride, bytes, timestamp) + } + Negotiated::Mjpeg => { + let jpeg = &bytes[..size.min(bytes.len())]; + // The decoder starts with the first picture; the background + // filter moves to its thread. + let decoder = match &mut state.mjpeg { + Some(decoder) => decoder, + slot @ None => { + match mjpeg::Decoder::start(state.feed.clone(), state.filter.take()) { + Ok(decoder) => slot.insert(decoder), + Err(e) => { + state.feed.set_error(e.to_string()); + return; + } + } + } + }; + decoder.put(jpeg, timestamp); + Ok(()) + } + }; + if let Err(e) = result { warn!("cannot take a camera frame: {e}"); state.feed.set_error(e); } @@ -894,6 +1227,209 @@ mod pipewire_camera { } } +/// MJPEG pictures decoded on a thread of their own, the newest first: the +/// camera's thread copies each picture into a recycled buffer and hands it +/// over latest-wins, so a decode that falls behind skips pictures instead +/// of holding up the camera. Each picture is decoded by `zune-jpeg` +/// straight into a pooled RGBA frame (its SIMD paths do the colour +/// conversion on the way), and the background filter, if any, runs there +/// too. +/// +/// ponytail: one decoder thread. A camera-like 1440p picture (400 KB) takes +/// about 30 ms here, so 1440p at 30 fps is about all one thread does; +/// decode alternate pictures on a second thread (dropping any that come out +/// late) if larger MJPEG cameras need it. +#[cfg(all(target_os = "linux", feature = "pipewire"))] +mod mjpeg { + use std::sync::Arc; + use std::thread::JoinHandle; + use std::time::Duration; + + use tracing::debug; + use zune_core::bytestream::ZCursor; + use zune_core::colorspace::ColorSpace; + use zune_core::options::DecoderOptions; + use zune_jpeg::JpegDecoder; + + use crate::frame::{FrameData, PixelFormat}; + use crate::handoff::Handoff; + use crate::pool::FramePool; + use crate::studio::compose::Feed; + use crate::studio::segment::BackgroundFilter; + use crate::{Error, Result}; + + /// Pictures in a row that do not decode before the source reports an + /// error: a camera sends a broken picture now and then. + const FAILURES: u32 = 30; + /// How often the decoder checks whether to stop. + const POLL: Duration = Duration::from_millis(100); + + /// One compressed picture. + pub struct Jpeg { + pub data: Vec, + pub timestamp: Duration, + } + + /// The decoder thread; stops when dropped. + pub struct Decoder { + input: Arc>, + /// Buffers handed over, reused once the decoder let go of them. + spare: Vec>, + thread: Option>, + } + + impl Decoder { + /// Decode into `feed`, through `filter` if given. + pub fn start(feed: Arc, filter: Option) -> Result { + let input = Arc::new(Handoff::new()); + let thread = std::thread::Builder::new() + .name("voelin-mjpeg".into()) + .spawn({ + let input = input.clone(); + move || run(&input, &feed, filter) + }) + .map_err(Error::Io)?; + Ok(Self { input, spare: Vec::new(), thread: Some(thread) }) + } + + /// Hand over a picture (copied); one the decoder has not taken yet + /// is replaced. + pub fn put(&mut self, data: &[u8], timestamp: Duration) { + let free = self.spare.iter().position(|j| Arc::strong_count(j) == 1); + let slot = match free { + Some(i) => &mut self.spare[i], + None => { + self.spare.push(Arc::new(Jpeg { data: Vec::new(), timestamp })); + self.spare.last_mut().expect("just pushed") + } + }; + let jpeg = Arc::get_mut(slot).expect("nobody else holds a spare buffer"); + jpeg.data.clear(); + jpeg.data.extend_from_slice(data); + jpeg.timestamp = timestamp; + self.input.put(slot.clone()); + } + } + + impl Drop for Decoder { + fn drop(&mut self) { + self.input.close(); + if let Some(thread) = self.thread.take() { + let _ = thread.join(); + } + } + } + + fn run(input: &Handoff, feed: &Feed, mut filter: Option) { + let mut pool = FramePool::new(); + let mut failures = 0; + while !input.is_closed() && !feed.is_closed() { + let Some(jpeg) = input.wait_timeout(POLL) else { continue }; + match decode(&jpeg, &mut pool, feed, filter.as_mut()) { + Ok(()) => failures = 0, + Err(e) => { + failures += 1; + debug!("an MJPEG picture did not decode: {e}"); + if failures == FAILURES { + feed.set_error(format!("the camera's MJPEG does not decode: {e}")); + } + } + } + } + } + + /// Decode `jpeg` into a pooled RGBA frame and hand it to `feed`. + pub fn decode( + jpeg: &Jpeg, + pool: &mut FramePool, + feed: &Feed, + filter: Option<&mut BackgroundFilter>, + ) -> Result<()> { + let convert = |e: zune_jpeg::errors::DecodeErrors| Error::Convert(format!("MJPEG: {e}")); + let options = DecoderOptions::default().jpeg_set_out_colorspace(ColorSpace::RGBA); + let mut decoder = JpegDecoder::new_with_options(ZCursor::new(&jpeg.data[..]), options); + decoder.decode_headers().map_err(convert)?; + let (w, h) = decoder + .dimensions() + .ok_or_else(|| Error::Convert("MJPEG: a picture without a size".into()))?; + let (width, height) = ( + u32::try_from(w).map_err(|_| Error::Convert("MJPEG: too wide".into()))?, + u32::try_from(h).map_err(|_| Error::Convert("MJPEG: too high".into()))?, + ); + let slot = pool.get_format(width, height, PixelFormat::Rgba); + let target = Arc::get_mut(slot).expect("the pool hands out unshared frames"); + target.timestamp = jpeg.timestamp; + let FrameData::Rgba(plane) = &mut target.data else { + return Err(Error::InvalidFrame("the camera pool is not RGBA".into())); + }; + // Pooled planes are tightly packed: exactly what the decoder writes. + decoder.decode_into(&mut plane.data).map_err(convert)?; + if let Some(filter) = filter { + filter.apply(target)?; + } + feed.put(slot.clone()); + Ok(()) + } + + #[cfg(test)] + mod tests { + use super::*; + + /// A JPEG of `width` x `height`: red on the left half, blue on the + /// right (made with the `image` crate's encoder). + fn picture(width: u32, height: u32) -> Vec { + let image = image::RgbImage::from_fn(width, height, |x, _| { + if x < width / 2 { image::Rgb([220, 30, 30]) } else { image::Rgb([30, 30, 220]) } + }); + let mut out = std::io::Cursor::new(Vec::new()); + image.write_to(&mut out, image::ImageFormat::Jpeg).unwrap(); + out.into_inner() + } + + #[test] + fn pictures_decode_into_pooled_frames() { + let feed = Feed::new(); + let mut pool = FramePool::new(); + for n in 0..3u64 { + let jpeg = Jpeg { data: picture(64, 36), timestamp: Duration::from_millis(n * 33) }; + decode(&jpeg, &mut pool, &feed, None).unwrap(); + let frame = feed.take().expect("a frame"); + assert_eq!((frame.width, frame.height), (64, 36)); + assert_eq!(frame.timestamp, Duration::from_millis(n * 33)); + let FrameData::Rgba(plane) = &frame.data else { panic!("not RGBA") }; + let pixel = |x: usize| &plane.data[(18 * 64 + x) * 4..][..4]; + let near = |p: &[u8], c: [u8; 3]| p.iter().zip(c).all(|(a, b)| a.abs_diff(b) < 24); + assert!(near(pixel(8), [220, 30, 30]), "{:?}", pixel(8)); + assert!(near(pixel(56), [30, 30, 220]), "{:?}", pixel(56)); + assert_eq!(pixel(8)[3], 255); + } + // The same frame came back each time. + assert_eq!(pool.allocated(), 1); + let broken = Jpeg { data: vec![0xFF, 0xD8, 1, 2, 3], timestamp: Duration::ZERO }; + assert!(decode(&broken, &mut pool, &feed, None).is_err()); + } + + #[test] + fn the_thread_takes_the_newest_picture() { + let feed = Arc::new(Feed::new()); + let mut decoder = Decoder::start(feed.clone(), None).unwrap(); + let jpeg = picture(32, 18); + for n in 0..5u64 { + decoder.put(&jpeg, Duration::from_millis(n)); + } + let started = std::time::Instant::now(); + while feed.delivered() == 0 && started.elapsed() < Duration::from_secs(5) { + std::thread::sleep(Duration::from_millis(5)); + } + assert!(feed.delivered() >= 1); + assert_eq!(feed.size(), (32, 18)); + // Buffers are reused, not one per picture. + assert!(decoder.spare.len() <= 3, "{}", decoder.spare.len()); + drop(decoder); + } + } +} + #[cfg(test)] mod tests { use std::time::Duration; @@ -933,6 +1469,74 @@ mod tests { } } + #[test] + fn camera_planes_are_borrowed_gathered_and_turned() { + // 4x2 luma 0..8, one 2x1 chroma row: U 10 11, V 20 21. + let y: Vec = (0..8).collect(); + let planar = YuvPlanes { + width: 4, + height: 2, + y: &y, + y_stride: 4, + u: &[10, 11], + v: &[20, 21], + uv_stride: 2, + uv_step: 1, + nv12: None, + rotation: 0, + }; + let mut scratch = Vec::new(); + let frame = planar.frame(Duration::from_millis(3), &mut scratch).unwrap(); + frame.validate().unwrap(); + assert_eq!(frame.timestamp, Duration::from_millis(3)); + let PixelsRef::I420 { y: luma, .. } = frame.pixels else { panic!("not I420") }; + assert!(std::ptr::eq(luma.data, &y[..]), "upright planar is borrowed"); + + let uv = [10, 20, 11, 21]; + let nv12 = YuvPlanes { + u: &uv[..3], + v: &uv[1..], + uv_stride: 4, + uv_step: 2, + nv12: Some(&uv), + ..planar + }; + let mut scratch = Vec::new(); + let frame = nv12.frame(Duration::ZERO, &mut scratch).unwrap(); + frame.validate().unwrap(); + assert!( + matches!(frame.pixels, PixelsRef::Nv12 { uv: p, .. } if std::ptr::eq(p.data, &uv[..])) + ); + + // NV21 (V first) is gathered into I420. + let vu = [20, 10, 21, 11]; + let nv21 = YuvPlanes { u: &vu[1..], v: &vu[..3], uv_stride: 4, uv_step: 2, ..planar }; + let mut scratch = Vec::new(); + let frame = nv21.frame(Duration::ZERO, &mut scratch).unwrap(); + frame.validate().unwrap(); + let PixelsRef::I420 { y: luma, u, v } = frame.pixels else { panic!("not I420") }; + assert_eq!((luma.data, u.data, v.data), (&y[..], &[10, 11][..], &[20, 21][..])); + + // Turned clockwise; the chroma turns with the luma. + for (rotation, size, luma) in [ + (90, (2, 4), [4, 0, 5, 1, 6, 2, 7, 3]), + (180, (4, 2), [7, 6, 5, 4, 3, 2, 1, 0]), + (270, (2, 4), [3, 7, 2, 6, 1, 5, 0, 4]), + ] { + let mut scratch = Vec::new(); + let frame = YuvPlanes { rotation, ..nv21 }.frame(Duration::ZERO, &mut scratch).unwrap(); + frame.validate().unwrap(); + assert_eq!((frame.width, frame.height), size, "{rotation}"); + let PixelsRef::I420 { y, u, .. } = frame.pixels else { panic!("not I420") }; + assert_eq!(y.data, luma, "{rotation}"); + let chroma: &[u8] = if rotation == 90 { &[10, 11] } else { &[11, 10] }; + assert_eq!(u.data, chroma, "{rotation}"); + } + + let short = YuvPlanes { y: &y[..7], rotation: 90, ..planar }; + assert!(short.frame(Duration::ZERO, &mut Vec::new()).is_err()); + } + #[test] fn four_character_codes() { assert_eq!(Pixel::from_fourcc(u32::from_le_bytes(*b"YUYV")), Some(Pixel::Yuyv)); @@ -972,6 +1576,50 @@ mod tests { frame.validate().unwrap(); } + /// The first real camera at its largest MJPEG size (decoded on our + /// thread), for three seconds: prints the size and the rate that + /// arrived. Needs a camera with MJPEG and PipeWire: + /// `cargo test -p voelin-media --lib largest_mjpeg -- --ignored --nocapture`. + #[tokio::test] + #[ignore = "needs a camera with MJPEG and PipeWire"] + async fn a_real_camera_delivers_its_largest_mjpeg_size() { + let Some((camera, (w, h), fps)) = list().into_iter().find_map(|c| { + let mjpeg = c.formats.iter().find(|f| f.pixel == Pixel::Mjpeg)?; + // `VOELIN_CAMERA_SIZE=1920x1080` picks another of its sizes. + let wanted = std::env::var("VOELIN_CAMERA_SIZE").ok().and_then(|s| { + let (w, h) = s.split_once('x')?; + Some((w.parse().ok()?, h.parse().ok()?)) + }); + let size = wanted.unwrap_or(*mjpeg.sizes.first()?); + Some((c.clone(), size, mjpeg.max_fps.max(1))) + }) else { + panic!("no camera with MJPEG on this machine"); + }; + let feed = Arc::new(Feed::new()); + let capture = Capture::start(&camera.id, Some((w, h)), fps, feed.clone(), Background::Keep) + .await + .unwrap(); + let started = std::time::Instant::now(); + while feed.delivered() < 2 && started.elapsed() < Duration::from_secs(20) { + tokio::time::sleep(Duration::from_millis(20)).await; + } + let (first, at) = (feed.delivered(), std::time::Instant::now()); + tokio::time::sleep(Duration::from_secs(3)).await; + let rate = (feed.delivered() - first) as f64 / at.elapsed().as_secs_f64(); + println!( + "{} through {}: asked {w}x{h} at {fps} fps, got {:?} at {rate:.1} fps, error {:?}", + camera.name, + capture.backend(), + feed.size(), + feed.error() + ); + drop(capture); + assert_eq!(feed.size(), (w, h)); + // Not `fps`: in low light a camera's auto exposure lowers its rate + // (the Fifine K420 gives 10 fps at 1440p then, also to `v4l2-ctl`). + assert!(rate >= 1.0, "{rate:.1} fps"); + } + #[tokio::test] async fn the_synthetic_camera_delivers() { let feed = Arc::new(Feed::new()); diff --git a/crates/voelin-media/src/studio/camera/mf.rs b/crates/voelin-media/src/studio/camera/mf.rs new file mode 100644 index 0000000..70c6d5a --- /dev/null +++ b/crates/voelin-media/src/studio/camera/mf.rs @@ -0,0 +1,442 @@ +//! Cameras through Media Foundation (Windows): listed with +//! `MFEnumDeviceSources` (the friendly name, every native format with its +//! sizes), captured with an `IMFSourceReader` on a thread of its own. The +//! reader sets the camera to the native format nearest the wanted size and +//! hands out NV12, decoding MJPEG and converting the rest itself (advanced +//! video processing), so every camera reaches the compositor the same way. +//! +//! Untested: type-checked for `x86_64-pc-windows-gnu` only. +#![allow(unsafe_code)] + +use std::marker::PhantomData; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::thread::JoinHandle; +use std::time::Instant; + +use tracing::{debug, warn}; +use windows::Win32::Foundation::E_FAIL; +use windows::Win32::Media::MediaFoundation::{ + IMF2DBuffer, IMFActivate, IMFAttributes, IMFMediaSource, IMFMediaType, IMFSourceReader, + MF_DEVSOURCE_ATTRIBUTE_FRIENDLY_NAME, MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE, + MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE_VIDCAP_GUID, + MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE_VIDCAP_SYMBOLIC_LINK, MF_MT_FRAME_RATE, MF_MT_FRAME_SIZE, + MF_MT_MAJOR_TYPE, MF_MT_SUBTYPE, MF_SOURCE_READER_ENABLE_ADVANCED_VIDEO_PROCESSING, + MF_SOURCE_READER_FIRST_VIDEO_STREAM, MF_SOURCE_READERF_ENDOFSTREAM, MF_SOURCE_READERF_ERROR, + MF_VERSION, MFCreateAttributes, MFCreateMediaType, MFCreateSourceReaderFromMediaSource, + MFEnumDeviceSources, MFMediaType_Video, MFSTARTUP_NOSOCKET, MFShutdown, MFStartup, + MFVideoFormat_I420, MFVideoFormat_IYUV, MFVideoFormat_MJPG, MFVideoFormat_NV12, + MFVideoFormat_RGB24, MFVideoFormat_RGB32, MFVideoFormat_UYVY, MFVideoFormat_YUY2, +}; +use windows::Win32::System::Com::{ + COINIT_MULTITHREADED, CoInitializeEx, CoTaskMemFree, CoUninitialize, +}; +use windows::core::{GUID, Interface, PWSTR}; + +use super::{BACKEND, Camera, Format, Pixel}; +use crate::capture::FramePacer; +use crate::frame::{FrameRef, PixelsRef, PlaneRef}; +use crate::pool::FramePool; +use crate::studio::compose::Feed; +use crate::studio::scene::Background; +use crate::studio::segment::BackgroundFilter; +use crate::studio::source::deliver; +use crate::{Error, Result}; + +const STREAM: u32 = MF_SOURCE_READER_FIRST_VIDEO_STREAM.0 as u32; + +/// COM and Media Foundation on the calling thread, until dropped there (it +/// is not `Send`). Every user makes it on a thread of its own. +struct Mf(PhantomData<*const ()>); + +impl Mf { + fn start() -> windows::core::Result { + // SAFETY: initialisation for this thread, undone by `Drop` on it. + unsafe { + CoInitializeEx(None, COINIT_MULTITHREADED).ok()?; + if let Err(e) = MFStartup(MF_VERSION, MFSTARTUP_NOSOCKET) { + CoUninitialize(); + return Err(e); + } + } + Ok(Self(PhantomData)) + } +} + +impl Drop for Mf { + fn drop(&mut self) { + // SAFETY: paired with the calls in `start`, on the same thread; the + // users release their COM objects before. + unsafe { + let _ = MFShutdown(); + CoUninitialize(); + } + } +} + +fn capture_error(e: impl std::fmt::Display) -> Error { + Error::Capture { backend: BACKEND, message: e.to_string() } +} + +/// Attributes with room for one item. +fn attributes() -> windows::core::Result { + let mut attributes = None; + // SAFETY: the call fills `attributes`. + unsafe { MFCreateAttributes(&mut attributes, 1)? }; + attributes.ok_or_else(windows::core::Error::empty) +} + +/// The video capture devices. +fn devices() -> windows::core::Result> { + let attributes = attributes()?; + let mut list: *mut Option = std::ptr::null_mut(); + let mut count = 0u32; + // SAFETY: `MFEnumDeviceSources` hands back an array of `count` interface + // pointers allocated with CoTaskMemAlloc; they are moved out (`take`) + // before the array is freed. + unsafe { + attributes.SetGUID( + &MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE, + &MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE_VIDCAP_GUID, + )?; + MFEnumDeviceSources(&attributes, &mut list, &mut count)?; + if list.is_null() { + return Ok(Vec::new()); + } + let devices = (0..count as usize).filter_map(|i| (*list.add(i)).take()).collect(); + CoTaskMemFree(Some(list.cast_const().cast())); + Ok(devices) + } +} + +/// A string attribute of a device. +fn string(device: &IMFActivate, key: &GUID) -> windows::core::Result { + let mut value = PWSTR::null(); + let mut len = 0u32; + // SAFETY: the string is allocated by the call, copied, then freed. + unsafe { + device.GetAllocatedString(key, &mut value, &mut len)?; + let text = value.to_string().unwrap_or_default(); + CoTaskMemFree(Some(value.0.cast_const().cast())); + Ok(text) + } +} + +/// The pixel format of a Media Foundation subtype. +fn pixel_of(subtype: GUID) -> Option { + Some(match subtype { + s if s == MFVideoFormat_NV12 => Pixel::Nv12, + s if s == MFVideoFormat_YUY2 => Pixel::Yuyv, + s if s == MFVideoFormat_UYVY => Pixel::Uyvy, + s if s == MFVideoFormat_I420 || s == MFVideoFormat_IYUV => Pixel::I420, + s if s == MFVideoFormat_RGB32 => Pixel::Bgrx, + s if s == MFVideoFormat_RGB24 => Pixel::Bgr24, + s if s == MFVideoFormat_MJPG => Pixel::Mjpeg, + _ => return None, + }) +} + +/// A `UINT64` attribute holding two `u32`s (frame size, frame rate). +fn pair(media: &IMFMediaType, key: &GUID) -> Option<(u32, u32)> { + // SAFETY: an attribute read. + let value = unsafe { media.GetUINT64(key) }.ok()?; + Some(((value >> 32) as u32, value as u32)) +} + +/// Frames per second of a media type, 0 if it does not say. +fn rate(media: &IMFMediaType) -> u32 { + pair(media, &MF_MT_FRAME_RATE).map_or(0, |(n, d)| n / d.max(1)) +} + +/// The native media types of a camera. +fn native_types(reader: &IMFSourceReader) -> Vec { + // SAFETY: `GetNativeMediaType` fails past the last type. + (0..).map_while(|i| unsafe { reader.GetNativeMediaType(STREAM, i) }.ok()).collect() +} + +/// Open a camera: its media source and a source reader for it. +fn open( + device: &IMFActivate, + attributes: Option<&IMFAttributes>, +) -> windows::core::Result<(IMFMediaSource, IMFSourceReader)> { + // SAFETY: COM calls on interfaces we hold. + unsafe { + let source: IMFMediaSource = device.ActivateObject()?; + let reader = MFCreateSourceReaderFromMediaSource(&source, attributes)?; + Ok((source, reader)) + } +} + +/// The formats of a camera: per pixel format its sizes, largest first, and +/// the highest rate of the largest. +fn formats(device: &IMFActivate) -> windows::core::Result> { + let (source, reader) = open(device, None)?; + // With the area of the largest size so far. + let mut formats: Vec<(Format, u32)> = Vec::new(); + for media in native_types(&reader) { + // SAFETY: an attribute read. + let subtype = unsafe { media.GetGUID(&MF_MT_SUBTYPE) }; + let Some(pixel) = subtype.ok().and_then(pixel_of) else { continue }; + let Some(size) = pair(&media, &MF_MT_FRAME_SIZE) else { continue }; + let at = match formats.iter().position(|(f, _)| f.pixel == pixel) { + Some(at) => at, + None => { + formats.push((Format { pixel, sizes: Vec::new(), max_fps: 0 }, 0)); + formats.len() - 1 + } + }; + let (format, largest) = &mut formats[at]; + if !format.sizes.contains(&size) { + format.sizes.push(size); + } + let area = size.0 * size.1; + if area > *largest { + (*largest, format.max_fps) = (area, rate(&media)); + } else if area == *largest { + format.max_fps = format.max_fps.max(rate(&media)); + } + } + drop(reader); + // SAFETY: the source is ours. + unsafe { + let _ = source.Shutdown(); + } + Ok(formats + .into_iter() + .map(|(mut f, _)| { + f.sizes.sort_unstable_by_key(|&(w, h)| std::cmp::Reverse(u64::from(w) * u64::from(h))); + f + }) + .collect()) +} + +/// Every camera, by symbolic link. Never fails: problems leave cameras out. +pub fn list() -> Vec { + // A thread of its own: the caller's COM apartment does not matter. + let listed = std::thread::spawn(|| -> windows::core::Result> { + let _mf = Mf::start()?; + let mut cameras = Vec::new(); + for device in devices()? { + let Ok(id) = string(&device, &MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE_VIDCAP_SYMBOLIC_LINK) + else { + continue; + }; + let name = string(&device, &MF_DEVSOURCE_ATTRIBUTE_FRIENDLY_NAME) + .ok() + .filter(|n| !n.is_empty()) + .unwrap_or_else(|| id.clone()); + let formats = formats(&device).unwrap_or_else(|e| { + debug!(camera = %name, "cannot read the camera's formats: {e}"); + Vec::new() + }); + // Webcams face the user. + cameras.push(Camera { id, name, backend: "mediafoundation", formats, mirrored: true }); + } + Ok(cameras) + }) + .join(); + match listed { + Ok(Ok(cameras)) => cameras, + Ok(Err(e)) => { + debug!("Media Foundation lists no cameras: {e}"); + Vec::new() + } + Err(_) => Vec::new(), + } +} + +/// A running camera; stops when dropped. +pub struct Stream { + stop: Arc, + thread: Option>, +} + +impl Stream { + /// Open the camera with symbolic link `device` and feed `feed` from a + /// thread of its own; returns once the camera is set up. + pub fn start( + device: &str, + size: Option<(u32, u32)>, + fps: u32, + feed: Arc, + background: Background, + ) -> Result { + let stop = Arc::new(AtomicBool::new(false)); + let (ready_tx, ready_rx) = std::sync::mpsc::channel(); + let device = device.to_owned(); + let thread = std::thread::Builder::new() + .name("voelin-camera".into()) + .spawn({ + let stop = stop.clone(); + move || { + let mf = match Mf::start() { + Ok(mf) => mf, + Err(e) => { + let _ = ready_tx.send(Err(capture_error(e))); + return; + } + }; + match Reader::open(&device, size, fps) { + Ok(reader) => { + let _ = ready_tx.send(Ok(())); + if let Err(e) = reader.run(&stop, &feed, background) { + warn!("camera {device}: {e}"); + feed.set_error(e); + } + // Before Media Foundation shuts down. + drop(reader); + } + Err(e) => { + let _ = ready_tx.send(Err(capture_error(e))); + } + } + drop(mf); + } + }) + .map_err(Error::Io)?; + let stream = Self { stop, thread: Some(thread) }; + ready_rx.recv().unwrap_or_else(|_| Err(capture_error("the camera thread ended")))?; + Ok(stream) + } +} + +impl Drop for Stream { + fn drop(&mut self) { + self.stop.store(true, Ordering::Relaxed); + // The reader looks at `stop` after every frame. + if let Some(thread) = self.thread.take() { + let _ = thread.join(); + } + } +} + +/// An open camera with NV12 output at `width` x `height`. +struct Reader { + source: IMFMediaSource, + reader: IMFSourceReader, + width: u32, + height: u32, + fps: u32, +} + +impl Reader { + fn open(device: &str, size: Option<(u32, u32)>, fps: u32) -> windows::core::Result { + let not_found = || windows::core::Error::new(E_FAIL, "no such camera"); + let camera = devices()? + .into_iter() + .find(|d| { + string(d, &MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE_VIDCAP_SYMBOLIC_LINK) + .is_ok_and(|id| id == device) + }) + .ok_or_else(not_found)?; + let attributes = attributes()?; + // SAFETY: an attribute write. + unsafe { attributes.SetUINT32(&MF_SOURCE_READER_ENABLE_ADVANCED_VIDEO_PROCESSING, 1)? }; + let (source, reader) = open(&camera, Some(&attributes))?; + // The native type nearest the wanted size (default 720p), the + // fastest of those up to `fps`, and NV12 made of it. + let (w, h) = size.unwrap_or((1280, 720)); + let wanted = i64::from(w) * i64::from(h); + let fps = fps.max(1); + let (media, (width, height)) = native_types(&reader) + .into_iter() + .filter_map(|media| { + let size = pair(&media, &MF_MT_FRAME_SIZE)?; + Some((media, size)) + }) + .min_by_key(|(media, (width, height))| { + let distance = (i64::from(*width) * i64::from(*height) - wanted).abs(); + (distance, std::cmp::Reverse(rate(media).min(fps))) + }) + .ok_or_else(not_found)?; + // SAFETY: COM calls on interfaces we hold. + unsafe { + reader.SetCurrentMediaType(STREAM, None, &media)?; + let out = MFCreateMediaType()?; + out.SetGUID(&MF_MT_MAJOR_TYPE, &MFMediaType_Video)?; + out.SetGUID(&MF_MT_SUBTYPE, &MFVideoFormat_NV12)?; + out.SetUINT64(&MF_MT_FRAME_SIZE, (u64::from(width) << 32) | u64::from(height))?; + if let Some((n, d)) = pair(&media, &MF_MT_FRAME_RATE) { + out.SetUINT64(&MF_MT_FRAME_RATE, (u64::from(n) << 32) | u64::from(d))?; + } + reader.SetCurrentMediaType(STREAM, None, &out)?; + } + debug!(device, width, height, rate = rate(&media), "camera through Media Foundation"); + Ok(Self { source, reader, width, height, fps }) + } + + /// Read frames until `stop` or the feed closes. + fn run( + &self, + stop: &AtomicBool, + feed: &Feed, + background: Background, + ) -> std::result::Result<(), String> { + let mut filter = + background.needs_mask().then(|| BackgroundFilter::with_default_segmenter(background)); + let mut pool = FramePool::new(); + let mut pacer = FramePacer::new(Some(self.fps)); + let started = Instant::now(); + let (width, height) = (self.width, self.height); + let rows = height as usize + height.div_ceil(2) as usize; + while !stop.load(Ordering::Relaxed) && !feed.is_closed() { + let (mut flags, mut sample) = (0u32, None); + // SAFETY: a synchronous read into locals. + unsafe { + self.reader.ReadSample(STREAM, 0, None, Some(&mut flags), None, Some(&mut sample)) + } + .map_err(|e| format!("reading the camera failed: {e}"))?; + if flags & (MF_SOURCE_READERF_ENDOFSTREAM.0 | MF_SOURCE_READERF_ERROR.0) as u32 != 0 { + return Err("the camera stopped".into()); + } + let Some(sample) = sample else { continue }; + let timestamp = started.elapsed(); + if !pacer.take(timestamp) { + continue; + } + // SAFETY: the buffer is locked while `bytes` is used, and + // unlocked after any successful lock. + unsafe { + let Ok(buffer) = sample.ConvertToContiguousBuffer() else { continue }; + let two_d = buffer.cast::().ok(); + let (mut data, mut pitch, mut length) = (std::ptr::null_mut(), width as i32, 0u32); + let locked = match &two_d { + Some(b) => b.Lock2D(&mut data, &mut pitch), + None => buffer.Lock(&mut data, None, Some(&mut length)), + }; + if locked.is_err() { + continue; + } + // A bottom-up buffer (negative pitch) is not NV12 as asked. + if !data.is_null() && pitch > 0 { + let stride = pitch as usize; + let length = if two_d.is_some() { stride * rows } else { length as usize }; + let bytes = std::slice::from_raw_parts(data, length); + let (y, uv) = bytes.split_at((stride * height as usize).min(bytes.len())); + let pixels = PixelsRef::Nv12 { + y: PlaneRef::new(y, stride), + uv: PlaneRef::new(uv, stride), + }; + let frame = FrameRef { width, height, timestamp, pixels }; + if let Err(e) = deliver(&mut pool, feed, &frame, filter.as_mut()) { + debug!("a camera frame was not taken: {e}"); + } + } + let _ = match &two_d { + Some(b) => b.Unlock2D(), + None => buffer.Unlock(), + }; + } + } + Ok(()) + } +} + +impl Drop for Reader { + fn drop(&mut self) { + // SAFETY: the source is ours. + unsafe { + let _ = self.source.Shutdown(); + } + } +} diff --git a/crates/voelin-media/src/studio/mod.rs b/crates/voelin-media/src/studio/mod.rs index b444c58..a6d62d8 100644 --- a/crates/voelin-media/src/studio/mod.rs +++ b/crates/voelin-media/src/studio/mod.rs @@ -91,7 +91,8 @@ pub struct SourceChange { pub enum OutputSpec { /// Record to a file; the name decides WebM or Matroska. Record { path: PathBuf }, - /// WHIP (or RTMP, which says it is not implemented yet). + /// WHIP (`http(s)://`, `token`: the bearer token) or RTMP + /// (`rtmp(s)://`, `token`: the stream key, unless it ends the URL). Url { url: String, token: Option }, } @@ -724,11 +725,11 @@ impl Studio { OutputSpec::Record { path } => { (Box::new(output::record::Recorder::start(path, layer, 2)?), false) } + OutputSpec::Url { url, token } if output::rtmp::Rtmp::handles(url) => { + let rtmp = output::rtmp::Rtmp::start(url, token.as_deref(), layer).await?; + (Box::new(rtmp), true) + } OutputSpec::Url { url, token } => { - if output::rtmp::Rtmp::handles(url) { - return Err(output::rtmp::Rtmp::connect(url, token.as_deref()) - .expect_err("the RTMP seam always refuses")); - } #[cfg(feature = "whip")] { let codec = self.stream_codec(); @@ -738,6 +739,7 @@ impl Studio { } #[cfg(not(feature = "whip"))] { + let _ = (url, token); return Err(Error::CaptureUnavailable { backend: "whip", reason: "this build has no WHIP output (feature `whip`)".into(), @@ -834,12 +836,33 @@ impl Studio { self.shared.state_changed(); } - /// Hand one encoded packet to every output. Called on the streamer's - /// encoder threads. + /// Hand one encoded packet of the stream's codec to every output. + /// Called on the streamer's encoder threads. pub fn write_packet(&self, packet: &Packet<'_>) { self.shared.write_packet(packet); } + /// Adds to `out` the video codecs the outputs taking `layer` need besides + /// the stream's ([`OutputSink::video_codec`]), which the streamer then + /// encodes too, for that layer only. + pub fn output_codecs(&self, layer: u32, out: &mut Vec) { + for output in lock(&self.shared.outputs).iter() { + let Some(codec) = output.sink.video_codec() else { continue }; + if !out.contains(&codec) && output.sink.wants(Track::Video { codec, layer }) { + out.push(codec); + } + } + } + + /// Hand a video packet of a codec an output asked for + /// ([`Studio::output_codecs`]) to the outputs that need that codec only: + /// the replay buffer and recordings keep the stream's. + pub fn write_output_packet(&self, packet: &Packet<'_>) { + if let Track::Video { codec, .. } = packet.track { + self.shared.to_outputs(packet, Some(codec)); + } + } + /// Whether an output needs a keyframe of `layer` now (a recording that /// just started, a WHIP session that just connected, the replay buffer's /// next clip start). Only the layer the outputs take @@ -921,11 +944,18 @@ impl Shared { if let Err(e) = lock(&self.replay).write(packet) { self.fail("replay", e); } + self.to_outputs(packet, None); + } + + /// Write `packet` to the outputs that want it; with `codec`, only to + /// those that need that codec of their own. + fn to_outputs(&self, packet: &Packet<'_>, codec: Option) { let mut failed = Vec::new(); { let mut outputs = lock(&self.outputs); for output in outputs.iter_mut() { - if !output.sink.wants(packet.track) { + let own = codec.is_none_or(|c| output.sink.video_codec() == Some(c)); + if !own || !output.sink.wants(packet.track) { continue; } if let Err(e) = output.sink.write(packet) { @@ -1052,7 +1082,7 @@ fn stats_loop(shared: &Shared) { name: output.sink.name().to_owned(), bytes, kbps: output.kbps, - error: output.error.clone(), + error: output.error.clone().or_else(|| output.sink.error()), }); } stats @@ -1292,15 +1322,16 @@ mod tests { .await .unwrap(); studio.apply(Command::SetReplay { seconds: 2, memory_mb: 4 }).await.unwrap(); + let vp8 = |n: u64| Packet { + track: Track::Video { codec: Codec::Vp8, layer: 0 }, + pts_90khz: n * 3000, + keyframe: n.is_multiple_of(15), + width: 64, + height: 48, + data: &[1, 2, 3, 4], + }; for n in 0..30u64 { - studio.write_packet(&Packet { - track: Track::Video { codec: Codec::Vp8, layer: 0 }, - pts_90khz: n * 3000, - keyframe: n.is_multiple_of(15), - width: 64, - height: 48, - data: &[1, 2, 3, 4], - }); + studio.write_packet(&vp8(n)); } { let outputs = lock(&studio.shared.outputs); @@ -1308,16 +1339,60 @@ mod tests { assert!(outputs[0].sink.bytes() > 0); } assert!(lock(&studio.shared.replay).stats().packets > 0); - // An RTMP url is refused with its reason, not silently dropped. - let e = studio - .apply(Command::AddOutput(OutputSpec::Url { - url: "rtmp://live.example/app".into(), - token: None, - })) - .await - .unwrap_err() - .to_string(); - assert!(e.contains("FFmpeg"), "{e}"); + + // An output that needs H.264 of layer 0 (as RTMP does) while the + // stream is VP8: the streamer is asked for H.264 of that layer only, + // and those packets reach that output only. + struct NeedsH264(Arc); + impl OutputSink for NeedsH264 { + fn name(&self) -> &str { + "h264" + } + + fn wants(&self, track: Track) -> bool { + track == Track::Video { codec: Codec::H264, layer: 0 } + } + + fn video_codec(&self) -> Option { + Some(Codec::H264) + } + + fn write(&mut self, packet: &Packet<'_>) -> Result<()> { + self.0.fetch_add(packet.data.len() as u64, Ordering::Relaxed); + Ok(()) + } + } + let got = Arc::new(AtomicU64::new(0)); + lock(&studio.shared.outputs).push(Output { + id: 7, + sink: Box::new(NeedsH264(got.clone())), + path: None, + started: Instant::now(), + kbps: 0.0, + last_bytes: 0, + pushes: true, + error: None, + }); + let mut codecs = vec![Codec::Vp8]; + studio.output_codecs(0, &mut codecs); + assert_eq!(codecs, [Codec::Vp8, Codec::H264]); + let mut codecs = vec![Codec::Vp8]; + studio.output_codecs(1, &mut codecs); + assert_eq!(codecs, [Codec::Vp8], "no H.264 for a layer nothing takes"); + let (recorded, replayed) = { + let outputs = lock(&studio.shared.outputs); + (outputs[0].sink.bytes(), lock(&studio.shared.replay).stats().packets) + }; + let h264 = Packet { track: Track::Video { codec: Codec::H264, layer: 0 }, ..vp8(30) }; + studio.write_output_packet(&h264); + assert_eq!(got.load(Ordering::Relaxed), 4); + // The recording and the replay buffer keep the stream's codec. + assert_eq!(lock(&studio.shared.outputs)[0].sink.bytes(), recorded); + assert_eq!(lock(&studio.shared.replay).stats().packets, replayed); + // And the stream's own packets do not reach it. + studio.write_packet(&vp8(31)); + assert_eq!(got.load(Ordering::Relaxed), 4); + lock(&studio.shared.outputs).retain(|o| o.id != 7); // The studio is a capture backend the streamer can use unchanged. let mut capture = studio.capture(); diff --git a/crates/voelin-media/src/studio/output/flv.rs b/crates/voelin-media/src/studio/output/flv.rs new file mode 100644 index 0000000..81a016e --- /dev/null +++ b/crates/voelin-media/src/studio/output/flv.rs @@ -0,0 +1,203 @@ +//! FLV tags: what libavformat's RTMP protocol takes, one RTMP message per +//! tag. Its writer reads a 13-byte file header first, then per tag the +//! 11-byte tag header, the body and the 4-byte size after it, so what goes +//! into an RTMP connection is exactly an FLV file. +//! +//! Only what a live stream needs: the script tag with `onMetaData` (AMF0), +//! H.264 as AVC tags (a sequence header with the `avcC` record, then NAL +//! units with 4-byte lengths, no B-frames so composition time 0) and AAC (a +//! sequence header with the `AudioSpecificConfig`, then raw frames). + +use crate::studio::output::ebml; + +/// The file header (audio and video), and the size of the tag before the +/// first one (0). +pub const HEADER: [u8; 13] = [b'F', b'L', b'V', 1, 0x05, 0, 0, 0, 9, 0, 0, 0, 0]; + +/// Tag types. +pub const AUDIO: u8 = 8; +pub const VIDEO: u8 = 9; +pub const SCRIPT: u8 = 18; + +/// The audio tag flags of AAC: format 10, "44 kHz" (what FLV says for any +/// AAC rate; the sequence header has the real one), 16 bit, stereo. +const AAC_FLAGS: u8 = 0xAF; +/// The video tag codec id of H.264 (AVC). +const AVC: u8 = 7; + +/// Append one tag of `kind` at `ms` (milliseconds; FLV keeps 32 bits) whose +/// body `body` appends. +pub fn tag(out: &mut Vec, kind: u8, ms: u32, body: impl FnOnce(&mut Vec)) { + let start = out.len(); + out.push(kind); + out.extend_from_slice(&[0; 3]); // body size, below + out.extend_from_slice(&ms.to_be_bytes()[1..]); + out.push((ms >> 24) as u8); + out.extend_from_slice(&[0; 3]); // stream id + let body_start = out.len(); + body(out); + let size = (out.len() - body_start) as u32; + out[start + 1..start + 4].copy_from_slice(&size.to_be_bytes()[1..]); + out.extend_from_slice(&(size + 11).to_be_bytes()); +} + +/// What `onMetaData` says about the stream. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Metadata { + pub width: u32, + pub height: u32, + /// Audio sample rate (Hz) and channels. + pub sample_rate: u32, + pub channels: u16, +} + +/// The body of the script tag: `onMetaData` and an ECMA array. +pub fn metadata(out: &mut Vec, meta: &Metadata) { + fn string(out: &mut Vec, text: &str) { + out.extend_from_slice(&(text.len() as u16).to_be_bytes()); + out.extend_from_slice(text.as_bytes()); + } + enum Value<'a> { + Number(f64), + Bool(bool), + Text(&'a str), + } + let entries = [ + ("duration", Value::Number(0.0)), + ("width", Value::Number(f64::from(meta.width))), + ("height", Value::Number(f64::from(meta.height))), + ("videocodecid", Value::Number(f64::from(AVC))), + ("audiocodecid", Value::Number(10.0)), + ("audiosamplerate", Value::Number(f64::from(meta.sample_rate))), + ("audiosamplesize", Value::Number(16.0)), + ("stereo", Value::Bool(meta.channels > 1)), + ("encoder", Value::Text("Voelin")), + ]; + out.push(2); + string(out, "onMetaData"); + out.push(8); + out.extend_from_slice(&(entries.len() as u32).to_be_bytes()); + for (key, value) in entries { + string(out, key); + match value { + Value::Number(n) => { + out.push(0); + out.extend_from_slice(&n.to_be_bytes()); + } + Value::Bool(b) => out.extend_from_slice(&[1, u8::from(b)]), + Value::Text(t) => { + out.push(2); + string(out, t); + } + } + } + out.extend_from_slice(&[0, 0, 9]); +} + +/// The body of the AVC sequence header: the `avcC` record +/// ([`ebml::avcc`]). +pub fn avc_sequence_header(out: &mut Vec, avcc: &[u8]) { + out.extend_from_slice(&[0x10 | AVC, 0, 0, 0, 0]); + out.extend_from_slice(avcc); +} + +/// The body of one H.264 frame given in Annex B: its NAL units with 4-byte +/// lengths (access unit delimiters left out, as in a recording). +pub fn avc_frame(out: &mut Vec, keyframe: bool, annex_b: &[u8]) { + let frame_type = if keyframe { 0x10 } else { 0x20 }; + out.extend_from_slice(&[frame_type | AVC, 1, 0, 0, 0]); + for unit in ebml::annex_b_units(annex_b) { + if unit[0] & 0x1F == 9 { + continue; + } + out.extend_from_slice(&(unit.len() as u32).to_be_bytes()); + out.extend_from_slice(unit); + } +} + +/// The body of the AAC sequence header. +pub fn aac_sequence_header(out: &mut Vec, audio_specific_config: &[u8]) { + out.extend_from_slice(&[AAC_FLAGS, 0]); + out.extend_from_slice(audio_specific_config); +} + +/// The body of one raw AAC frame. +pub fn aac_frame(out: &mut Vec, data: &[u8]) { + out.extend_from_slice(&[AAC_FLAGS, 1]); + out.extend_from_slice(data); +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The tags of an FLV stream: (type, time, body). + fn tags(mut data: &[u8]) -> Vec<(u8, u32, Vec)> { + let mut tags = Vec::new(); + while data.len() >= 11 { + let size = u32::from_be_bytes([0, data[1], data[2], data[3]]) as usize; + let ms = u32::from_be_bytes([data[7], data[4], data[5], data[6]]); + tags.push((data[0], ms, data[11..11 + size].to_vec())); + let previous = u32::from_be_bytes(data[11 + size..15 + size].try_into().unwrap()); + assert_eq!(previous as usize, size + 11); + data = &data[15 + size..]; + } + assert!(data.is_empty()); + tags + } + + #[test] + fn tags_have_sizes_and_times() { + let mut out = Vec::new(); + tag(&mut out, AUDIO, 21, |b| aac_frame(b, &[1, 2, 3])); + // Times past 24 bits use the extension byte. + tag(&mut out, VIDEO, 0x0123_4567, |b| avc_frame(b, false, &[0, 0, 0, 1, 0x41, 9, 9])); + let tags = tags(&out); + assert_eq!(tags[0], (AUDIO, 21, vec![0xAF, 1, 1, 2, 3])); + assert_eq!(tags[1], (VIDEO, 0x0123_4567, vec![0x27, 1, 0, 0, 0, 0, 0, 0, 3, 0x41, 9, 9])); + } + + #[test] + fn h264_becomes_length_prefixed() { + let keyframe = [ + 0, 0, 0, 1, 0x09, 0xF0, // access unit delimiter: dropped + 0, 0, 0, 1, 0x67, 0x64, 0x00, 0x1F, 0xAC, // SPS + 0, 0, 1, 0x68, 0xEE, 0x3C, // PPS + 0, 0, 0, 1, 0x65, 0x88, 0x84, // IDR slice + ]; + let mut body = Vec::new(); + avc_frame(&mut body, true, &keyframe); + assert_eq!( + body, + [ + 0x17, 1, 0, 0, 0, 0, 0, 0, 5, 0x67, 0x64, 0x00, 0x1F, 0xAC, 0, 0, 0, 3, 0x68, 0xEE, + 0x3C, 0, 0, 0, 3, 0x65, 0x88, 0x84 + ] + ); + let avcc = ebml::avcc(&keyframe).unwrap(); + let mut header = Vec::new(); + avc_sequence_header(&mut header, &avcc); + assert_eq!(&header[..5], [0x17, 0, 0, 0, 0]); + // avcC: version 1, profile 100, compatibility 0, level 31. + assert_eq!(&header[5..9], [1, 0x64, 0x00, 0x1F]); + } + + #[test] + fn metadata_is_amf0() { + let mut body = Vec::new(); + metadata( + &mut body, + &Metadata { width: 1280, height: 720, sample_rate: 48_000, channels: 2 }, + ); + assert_eq!(&body[..13], b"\x02\x00\x0aonMetaData"); + assert_eq!(body[13], 8); + assert_eq!(u32::from_be_bytes(body[14..18].try_into().unwrap()), 9); + assert!(body.ends_with(&[0, 0, 9])); + let width = body.windows(5).position(|w| w == b"width").unwrap() + 5; + assert_eq!(body[width], 0); + assert_eq!(f64::from_be_bytes(body[width + 1..width + 9].try_into().unwrap()), 1280.0); + let stereo = body.windows(6).position(|w| w == b"stereo").unwrap() + 6; + assert_eq!(&body[stereo..stereo + 2], [1, 1]); + assert_eq!(HEADER.len(), 13); + } +} diff --git a/crates/voelin-media/src/studio/output/mod.rs b/crates/voelin-media/src/studio/output/mod.rs index f9f6472..e8e3924 100644 --- a/crates/voelin-media/src/studio/output/mod.rs +++ b/crates/voelin-media/src/studio/output/mod.rs @@ -9,7 +9,8 @@ //! out as a clip without re-encoding //! - [`whip`]: WHIP (WebRTC-HTTP ingestion) to a broadcast service (feature //! `whip`) -//! - [`rtmp`]: the seam for RTMP, which will go through the FFmpeg loader +//! - [`rtmp`]: RTMP and RTMPS through libavformat loaded at runtime, with +//! FLV of our own ([`flv`]) and the audio as AAC //! //! A sink never stalls the encoder: [`OutputSink::write`] returns an error //! instead of blocking for long, and the studio drops the sink and reports @@ -19,6 +20,7 @@ use crate::Result; use crate::codec::Codec; pub mod ebml; +pub mod flv; pub mod record; pub mod replay; pub mod rtmp; @@ -89,6 +91,14 @@ pub trait OutputSink: Send { false } + /// The video codec this sink needs whatever the stream encodes (RTMP: + /// H.264). The streamer then encodes it too, as for a viewer that chose + /// it ([`Studio::output_codecs`](crate::studio::Studio::output_codecs)). + /// `None`: the stream's own codec. + fn video_codec(&self) -> Option { + None + } + /// Take one packet. fn write(&mut self, packet: &Packet<'_>) -> Result<()>; @@ -101,6 +111,12 @@ pub trait OutputSink: Send { fn bytes(&self) -> u64 { 0 } + + /// A problem the output reports while it keeps going (a connection + /// being made again), for the stats. + fn error(&self) -> Option { + None + } } #[cfg(test)] diff --git a/crates/voelin-media/src/studio/output/rtmp.rs b/crates/voelin-media/src/studio/output/rtmp.rs index 8c8e888..e25e0b5 100644 --- a/crates/voelin-media/src/studio/output/rtmp.rs +++ b/crates/voelin-media/src/studio/output/rtmp.rs @@ -1,58 +1,597 @@ -//! RTMP: the seam only. +//! RTMP and RTMPS: pushing the studio to a broadcast service (Twitch, +//! YouTube, an nginx-rtmp, anything that takes what OBS sends). //! -//! RTMP will go out through the FFmpeg libraries the crate already loads at -//! runtime ([`crate::ffmpeg`]): `libavformat` speaks `rtmp://` and -//! `rtmps://`, so the studio will hand it the same encoded packets it hands -//! every other output and never link or ship an RTMP stack of its own. +//! The connection is libavformat's, loaded at runtime with the rest of +//! FFmpeg ([`crate::ffmpeg::avio`]): its `rtmp://` and `rtmps://` protocols +//! do the handshake, `connect`, `publish` and TLS, and take an FLV byte +//! stream. The FLV is ours ([`flv`]), as the recordings' Matroska is, so no +//! libavformat struct is touched; the one field read is where a failed +//! write lands, found at load. //! -//! What is missing is the muxer side of that loader (`avformat_alloc_output_ -//! context2`, `av_interleaved_write_frame` and the bitstream filters H.264 -//! and AAC need in FLV). Until then [`Rtmp::connect`] says so rather than -//! pretending, so a scene file or a `voelinctl` command that names an RTMP -//! output fails with a reason instead of silently dropping the stream. +//! - Video: H.264 of one layer (classic RTMP carries nothing else): the +//! stream's packets as they are when it encodes H.264, else those of an +//! H.264 encoder the streamer runs for this output beside the stream's +//! ([`OutputSink::video_codec`]), as it does for a viewer of another +//! codec. +//! - Audio: the studio's Opus, decoded and encoded as AAC-LC by FFmpeg's own +//! codecs ([`crate::ffmpeg::audio`]) on the output's thread. +//! - The stream key: in the URL (`rtmp://host/app/key`) or given apart (the +//! output's token), then sent as the play path with the URL's path as the +//! application. The output's name never shows the key. +//! +//! A thread of its own runs the connection, fed through a bounded queue, so +//! a slow upload never holds up an encoder: a full queue drops the packet, +//! and video resumes at the next keyframe (which it asks for). A connection +//! that fails is made again, after 1, 2, 4, ... up to 30 seconds, for as +//! long as the output exists, each new one starting at a keyframe; the +//! first connection is made by [`Rtmp::start`], so a wrong address or key +//! fails right there. [`OutputSink::finish`] (End Stream) unpublishes and +//! closes, cutting a dead network off after a few seconds. +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::sync::{Arc, Mutex, PoisonError}; +use std::thread::JoinHandle; +use std::time::{Duration, Instant}; + +use crate::codec::Codec; use crate::studio::output::{OutputSink, Packet, Track}; use crate::{Error, Result}; -/// An RTMP output. Not implemented yet; see the [module docs](self). -#[derive(Debug)] -pub struct Rtmp { +/// 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; +/// How long a connection may wait for the network (connecting, a send) +/// before it is given up and made again. +const TIMEOUT: Duration = Duration::from_secs(10); +/// Waits between connection attempts: doubling from the first to the last. +#[cfg(feature = "ffmpeg")] +const BACKOFF: (Duration, Duration) = (Duration::from_secs(1), Duration::from_secs(30)); +/// How long closing may take (unpublish) before the network is cut off. +const CLOSE_GRACE: Duration = Duration::from_secs(3); +/// Audio kept while waiting for the first keyframe (as a recording does). +#[cfg(feature = "ffmpeg")] +const BACKLOG_MS: i64 = 2_000; +/// Audio waits for the video of its time at most this long (it is written in +/// time order with the video, and the video comes later: the encoders' delay). +#[cfg(feature = "ffmpeg")] +const INTERLEAVE_MS: i64 = 1_000; + +fn error(message: impl Into) -> Error { + Error::Output { output: "RTMP", message: message.into() } +} + +fn lock(m: &Mutex) -> std::sync::MutexGuard<'_, T> { + m.lock().unwrap_or_else(PoisonError::into_inner) +} + +/// Where to connect: the URL libavformat opens, its protocol options and a +/// name for the UI that does not show the stream key. +#[derive(Clone, Debug, PartialEq, Eq)] +struct Target { url: String, + options: Vec<(&'static str, String)>, + name: String, +} + +impl Target { + fn new(url: &str, key: Option<&str>) -> Result { + let url = url.trim(); + let lower = url.to_ascii_lowercase(); + let rest = ["rtmp://", "rtmps://"] + .iter() + .find_map(|scheme| lower.starts_with(scheme).then(|| &url[scheme.len()..])) + .ok_or_else(|| error(format!("not an RTMP address: {url}")))?; + let (host, path) = rest.split_once('/').unwrap_or((rest, "")); + if host.is_empty() { + return Err(error(format!("no server in {url}"))); + } + let mut options = vec![ + ("rw_timeout", TIMEOUT.as_micros().to_string()), + // Small tags (audio) go out at once. + ("tcp_nodelay", "1".to_owned()), + ]; + let name = match key.map(str::trim).filter(|k| !k.is_empty()) { + Some(key) => { + let app = path.trim_matches('/'); + if !app.is_empty() { + options.push(("rtmp_app", app.to_owned())); + } + options.push(("rtmp_playpath", key.to_owned())); + url.trim_end_matches('/').to_owned() + } + // The key is the last part of the path. + None => match url.trim_end_matches('/').rsplit_once('/') { + Some((base, _)) if path.trim_matches('/').contains('/') => format!("{base}/…"), + _ => url.to_owned(), + }, + }; + Ok(Self { url: url.to_owned(), options, name }) + } +} + +/// 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, + pts_90khz: u64, + width: u32, + height: u32, + data: Vec, +} + +/// What an RTMP output is doing. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct RtmpStats { + /// Connected and publishing. + pub connected: bool, + /// Bytes sent (FLV), over all connections. + pub bytes: u64, + /// FLV tags sent. + pub tags: u64, + /// Packets dropped because the upload could not keep up, or while + /// disconnected. + pub dropped: u64, + /// Connections made again after one failed. + pub reconnects: u64, + /// The last failure, while it is not connected. + pub error: Option, +} + +#[derive(Default)] +struct Shared { + /// End the connection (cleanly). + stop: AtomicBool, + /// Interrupt whatever FFmpeg is waiting for. + abort: Arc, + /// A keyframe is wanted; taken by [`OutputSink::needs_keyframe`]. + keyframe: AtomicBool, + connected: AtomicBool, + bytes: AtomicU64, + tags: AtomicU64, + dropped: AtomicU64, + reconnects: AtomicU64, + error: Mutex>, +} + +/// An RTMP output; see the [module docs](self). Closes when dropped. +pub struct Rtmp { + name: String, + layer: u32, + queue: Option>, + thread: Option>, + shared: Arc, + /// A video packet was dropped: no more video until a keyframe. + skip_video: bool, } impl Rtmp { - /// Whether `url` is one this output would take. + /// Whether `url` is one this output takes. pub fn handles(url: &str) -> bool { + let url = url.trim_start().to_ascii_lowercase(); url.starts_with("rtmp://") || url.starts_with("rtmps://") } - /// Always fails for now, with what is missing. - pub fn connect(url: &str, _key: Option<&str>) -> Result { - Err(Error::CodecUnavailable { - codec: crate::codec::Codec::H264, - reason: format!( - "RTMP ({url}) needs the muxing side of the FFmpeg loader, which is not \ - written yet; record to a file or use WHIP" - ), - }) + /// Connect to `url` and push `layer` of the studio (in H.264) and its + /// audio. The stream key is the last part of the URL's path, or `key` if + /// given. + /// + /// Fails when there is no FFmpeg with libavformat, or the first + /// connection does (a wrong address, a refused key). + pub async fn start(url: &str, key: Option<&str>, layer: u32) -> Result { + let target = Target::new(url, key)?; + #[cfg(not(feature = "ffmpeg"))] + { + let _ = (target, layer); + Err(error("this build has no FFmpeg (feature `ffmpeg`), which RTMP goes through")) + } + #[cfg(feature = "ffmpeg")] + { + session::start(target, layer).await + } } - pub fn url(&self) -> &str { - &self.url + pub fn stats(&self) -> RtmpStats { + let shared = &self.shared; + let connected = shared.connected.load(Ordering::Relaxed); + RtmpStats { + connected, + bytes: shared.bytes.load(Ordering::Relaxed), + tags: shared.tags.load(Ordering::Relaxed), + dropped: shared.dropped.load(Ordering::Relaxed), + reconnects: shared.reconnects.load(Ordering::Relaxed), + error: if connected { None } else { lock(&shared.error).clone() }, + } + } + + /// Unpublish and close; a network that does not answer is cut off + /// after [`CLOSE_GRACE`]. + fn teardown(&mut self) { + self.shared.stop.store(true, Ordering::Relaxed); + self.queue = None; + let Some(thread) = self.thread.take() else { return }; + let deadline = Instant::now() + CLOSE_GRACE; + while !thread.is_finished() && Instant::now() < deadline { + std::thread::sleep(Duration::from_millis(10)); + } + self.shared.abort.store(true, Ordering::Relaxed); + let _ = thread.join(); + } +} + +impl Drop for Rtmp { + fn drop(&mut self) { + self.teardown(); } } impl OutputSink for Rtmp { fn name(&self) -> &str { - &self.url + &self.name } - fn wants(&self, _track: Track) -> bool { - true + fn wants(&self, track: Track) -> bool { + match track { + Track::Video { codec, layer } => codec == Codec::H264 && layer == self.layer, + Track::Audio { .. } => true, + } } - fn write(&mut self, _packet: &Packet<'_>) -> Result<()> { - Err(Error::Capture { backend: "rtmp", message: "RTMP is not implemented".into() }) + fn needs_keyframe(&mut self) -> bool { + self.shared.keyframe.swap(false, Ordering::Relaxed) + } + + fn video_codec(&self) -> Option { + Some(Codec::H264) + } + + fn write(&mut self, packet: &Packet<'_>) -> Result<()> { + let Some(queue) = &self.queue else { return Ok(()) }; + if packet.track.is_video() { + if !self.wants(packet.track) { + return Ok(()); + } + if self.skip_video { + if !packet.keyframe { + return Ok(()); + } + self.skip_video = false; + } + } + let queued = Queued { + video: packet.track.is_video(), + keyframe: packet.keyframe, + pts_90khz: packet.pts_90khz, + width: packet.width, + height: packet.height, + data: packet.data.to_vec(), + }; + match queue.try_send(queued) { + Ok(()) => Ok(()), + Err(std::sync::mpsc::TrySendError::Full(queued)) => { + self.shared.dropped.fetch_add(1, Ordering::Relaxed); + if queued.video { + self.skip_video = true; + self.shared.keyframe.store(true, Ordering::Relaxed); + } + Ok(()) + } + Err(std::sync::mpsc::TrySendError::Disconnected(_)) => Err(error( + lock(&self.shared.error).clone().unwrap_or_else(|| "the RTMP output ended".into()), + )), + } + } + + fn finish(&mut self) -> Result<()> { + self.teardown(); + Ok(()) + } + + fn bytes(&self) -> u64 { + self.shared.bytes.load(Ordering::Relaxed) + } + + fn error(&self) -> Option { + self.stats().error + } +} + +/// The connection's thread. +#[cfg(feature = "ffmpeg")] +mod session { + use std::collections::VecDeque; + use std::sync::Arc; + use std::sync::atomic::Ordering; + use std::sync::mpsc::{Receiver, RecvTimeoutError, sync_channel}; + use std::time::{Duration, Instant}; + + use tracing::{debug, warn}; + + use super::{ + AAC_BITRATE, BACKLOG_MS, BACKOFF, INTERLEAVE_MS, QUEUE, Queued, Rtmp, Shared, Target, + error, lock, + }; + use crate::Result; + use crate::ffmpeg::audio::{AUDIO_SPECIFIC_CONFIG, AacEncoder, RATE}; + use crate::ffmpeg::avio::Connection; + use crate::studio::output::{ebml, flv}; + + /// How often a thread that waits checks whether to stop. + const POLL: Duration = Duration::from_millis(100); + + pub(super) async fn start(target: Target, layer: u32) -> Result { + Connection::available().map_err(error)?; + let aac = AacEncoder::new(AAC_BITRATE).map_err(error)?; + let shared = Arc::new(Shared::default()); + let (queue, packets) = sync_channel(QUEUE); + let (ready, first) = tokio::sync::oneshot::channel(); + let name = target.name.clone(); + let worker = Worker { target, shared: shared.clone(), packets, aac, buf: Vec::new() }; + let thread = std::thread::Builder::new() + .name("voelin-rtmp".into()) + .spawn(move || worker.run(ready)) + .map_err(|e| error(e.to_string()))?; + match first.await { + Ok(Ok(())) => {} + Ok(Err(e)) => { + let _ = thread.join(); + return Err(error(e)); + } + Err(_) => return Err(error("the RTMP thread ended")), + } + debug!(name, "RTMP output connected"); + Ok(Rtmp { + name, + layer, + queue: Some(queue), + thread: Some(thread), + shared, + skip_video: false, + }) + } + + struct Worker { + target: Target, + shared: Arc, + packets: Receiver, + aac: AacEncoder, + /// The tags being sent. + buf: Vec, + } + + /// What one connection has sent. + #[derive(Default)] + struct Publish { + /// The sequence headers went out (at the first keyframe), and the + /// stream's time 0 (milliseconds on the studio's clock). + base: Option, + /// AAC frames (milliseconds on the studio's clock, data) from before + /// the first keyframe. + backlog: VecDeque<(i64, Vec)>, + /// AAC frames (stream time) waiting for the video of their time. + audio: VecDeque<(i64, Vec)>, + /// The stream time of the last video tag. + video: Option, + /// When the last keyframe request went out, while waiting for one. + asked: Option, + } + + impl Worker { + fn stopped(&self) -> bool { + self.shared.stop.load(Ordering::Relaxed) + } + + fn open(&self) -> std::result::Result { + let options: Vec<(&str, &str)> = + self.target.options.iter().map(|(k, v)| (*k, v.as_str())).collect(); + Connection::open(&self.target.url, &options, self.shared.abort.clone()) + } + + fn run(mut self, ready: tokio::sync::oneshot::Sender>) { + let mut connection = match self.open() { + Ok(connection) => { + let _ = ready.send(Ok(())); + Some(connection) + } + Err(e) => { + let _ = ready.send(Err(e)); + return; + } + }; + let mut backoff = BACKOFF.0; + while !self.stopped() { + let connection = match connection.take() { + Some(connection) => connection, + None => { + if !self.wait(backoff) { + break; + } + match self.open() { + Ok(connection) => { + self.shared.reconnects.fetch_add(1, Ordering::Relaxed); + backoff = BACKOFF.0; + connection + } + Err(e) => { + self.fail(format!("cannot connect again: {e}")); + backoff = (backoff * 2).min(BACKOFF.1); + continue; + } + } + } + }; + self.shared.connected.store(true, Ordering::Relaxed); + *lock(&self.shared.error) = None; + let result = self.publish(connection); + self.shared.connected.store(false, Ordering::Relaxed); + match result { + Ok(()) => break, + Err(e) => self.fail(e), + } + } + debug!(name = self.target.name, "RTMP output closed"); + } + + /// Wait `time` while dropping what comes in; `false` once stopped. + fn wait(&self, time: Duration) -> bool { + let until = Instant::now() + time; + while !self.stopped() { + let now = Instant::now(); + if now >= until { + return true; + } + match self.packets.recv_timeout((until - now).min(POLL)) { + Ok(_) => { + self.shared.dropped.fetch_add(1, Ordering::Relaxed); + } + Err(RecvTimeoutError::Timeout) => {} + Err(RecvTimeoutError::Disconnected) => return false, + } + } + false + } + + fn fail(&self, message: String) { + warn!(name = self.target.name, "RTMP: {message}"); + *lock(&self.shared.error) = Some(message); + } + + /// Send what comes in over `connection` until stopped (`Ok`: closed + /// cleanly) or until it fails. + fn publish(&mut self, mut connection: Connection) -> std::result::Result<(), String> { + connection.write(&flv::HEADER)?; + let mut publish = Publish::default(); + self.ask_keyframe(&mut publish); + loop { + if self.stopped() { + return connection.close(); + } + match self.packets.recv_timeout(POLL) { + Ok(packet) => self.packet(&mut connection, &mut publish, packet)?, + Err(RecvTimeoutError::Timeout) => {} + Err(RecvTimeoutError::Disconnected) => return connection.close(), + } + } + } + + fn ask_keyframe(&self, publish: &mut Publish) { + publish.asked = Some(Instant::now()); + self.shared.keyframe.store(true, Ordering::Relaxed); + } + + fn packet( + &mut self, + connection: &mut Connection, + publish: &mut Publish, + packet: Queued, + ) -> std::result::Result<(), String> { + self.buf.clear(); + if packet.video { + self.video(publish, &packet); + } else { + self.audio(publish, &packet); + } + if self.buf.is_empty() { + return Ok(()); + } + connection.write(&self.buf)?; + connection.flush()?; + self.shared.bytes.fetch_add(self.buf.len() as u64, Ordering::Relaxed); + Ok(()) + } + + /// Append the tags a video packet makes to `self.buf`. + fn video(&mut self, publish: &mut Publish, packet: &Queued) { + let ms = (packet.pts_90khz / 90) as i64; + let base = match publish.base { + Some(base) => base, + None => { + // The stream starts at a keyframe that carries the + // parameter sets the AVC sequence header needs. + let avcc = packet.keyframe.then(|| ebml::avcc(&packet.data)).flatten(); + let Some(avcc) = avcc else { + if publish.asked.is_none_or(|t| t.elapsed() > Duration::from_millis(500)) { + self.ask_keyframe(publish); + } + return; + }; + let meta = flv::Metadata { + width: packet.width, + height: packet.height, + sample_rate: RATE, + channels: 2, + }; + self.tag(flv::SCRIPT, 0, |b| flv::metadata(b, &meta)); + self.tag(flv::VIDEO, 0, |b| flv::avc_sequence_header(b, &avcc)); + self.tag(flv::AUDIO, 0, |b| { + flv::aac_sequence_header(b, &AUDIO_SPECIFIC_CONFIG) + }); + publish.base = Some(ms); + // The audio of the keyframe's moment came before it. + for (time, data) in publish.backlog.drain(..) { + if time >= ms { + publish.audio.push_back((time - ms, data)); + } + } + ms + } + }; + let time = (ms - base).max(publish.video.unwrap_or(0)); + while publish.audio.front().is_some_and(|(t, _)| *t <= time) { + let (t, data) = publish.audio.pop_front().expect("checked"); + self.tag(flv::AUDIO, t, |b| flv::aac_frame(b, &data)); + } + self.tag(flv::VIDEO, time, |b| flv::avc_frame(b, packet.keyframe, &packet.data)); + publish.video = Some(time); + } + + /// Encode an Opus packet as AAC and append the audio tags that are + /// due to `self.buf`. + fn audio(&mut self, publish: &mut Publish, packet: &Queued) { + let time = (packet.pts_90khz * u64::from(RATE) / 90_000) as i64; + let mut frames = Vec::new(); + let result = self.aac.push(&packet.data, time, &mut |data, at| { + frames.push((at * 1000 / i64::from(RATE), data.to_vec())); + }); + if let Err(e) = result { + debug!("RTMP audio: {e}"); + } + for (ms, data) in frames { + match publish.base { + None => { + publish.backlog.push_back((ms, data)); + while publish.backlog.front().is_some_and(|(t, _)| *t + BACKLOG_MS < ms) { + publish.backlog.pop_front(); + } + } + Some(base) if ms >= base => publish.audio.push_back((ms - base, data)), + Some(_) => {} + } + } + // Audio goes out with the video of its time, or once the video + // is late by more than INTERLEAVE_MS. + let newest = publish.audio.back().map_or(0, |(t, _)| *t); + let video = publish.video.unwrap_or(-1); + while publish + .audio + .front() + .is_some_and(|(t, _)| *t <= video || *t + INTERLEAVE_MS < newest) + { + let (t, data) = publish.audio.pop_front().expect("checked"); + self.tag(flv::AUDIO, t, |b| flv::aac_frame(b, &data)); + } + } + + fn tag(&mut self, kind: u8, ms: i64, body: impl FnOnce(&mut Vec)) { + flv::tag(&mut self.buf, kind, ms.clamp(0, i64::from(u32::MAX)) as u32, body); + self.shared.tags.fetch_add(1, Ordering::Relaxed); + } } } @@ -61,11 +600,39 @@ mod tests { use super::*; #[test] - fn rtmp_urls_are_recognised_but_refused() { + fn urls_and_keys() { assert!(Rtmp::handles("rtmp://live.example/app")); - assert!(Rtmp::handles("rtmps://live.example/app")); + assert!(Rtmp::handles("RTMPS://live.example/app")); assert!(!Rtmp::handles("https://example/whip")); - let e = Rtmp::connect("rtmp://live.example/app", Some("key")).unwrap_err().to_string(); - assert!(e.contains("FFmpeg"), "{e}"); + + // The key in the URL: FFmpeg splits it; the name hides it. + let t = Target::new("rtmp://live.example/app/secret-key", None).unwrap(); + assert_eq!(t.url, "rtmp://live.example/app/secret-key"); + assert_eq!(t.name, "rtmp://live.example/app/…"); + assert!(!t.options.iter().any(|(k, _)| k.starts_with("rtmp_"))); + + // The key apart: the play path, the URL's path the application. + let t = Target::new("rtmps://a.rtmp.example:443/live2/", Some(" key?x=1 ")).unwrap(); + assert_eq!(t.name, "rtmps://a.rtmp.example:443/live2"); + assert!(t.options.contains(&("rtmp_app", "live2".to_owned()))); + assert!(t.options.contains(&("rtmp_playpath", "key?x=1".to_owned()))); + assert!(t.options.contains(&("rw_timeout", "10000000".to_owned()))); + assert!(!t.name.contains("key")); + + assert!(Target::new("http://example/app", None).is_err()); + assert!(Target::new("rtmp:///app", None).is_err()); + } + + #[tokio::test] + async fn dead_servers_are_refused() { + // Port 1 on loopback: nothing listens. + if crate::ffmpeg::avio::Connection::available().is_ok() { + let e = Rtmp::start("rtmp://127.0.0.1:1/app", Some("k"), 0) + .await + .err() + .expect("nothing listens") + .to_string(); + assert!(!e.is_empty()); + } } } diff --git a/crates/voelin-media/src/studio/output/whip.rs b/crates/voelin-media/src/studio/output/whip.rs index 13e5355..575306b 100644 --- a/crates/voelin-media/src/studio/output/whip.rs +++ b/crates/voelin-media/src/studio/output/whip.rs @@ -40,7 +40,7 @@ use crate::{Error, Result}; const QUEUE: usize = 256; fn error(message: impl Into) -> Error { - Error::Capture { backend: "whip", message: message.into() } + Error::Output { output: "WHIP", message: message.into() } } fn lock(m: &Mutex) -> std::sync::MutexGuard<'_, T> { @@ -292,6 +292,10 @@ impl OutputSink for Whip { fn bytes(&self) -> u64 { self.shared.bytes.load(Ordering::Relaxed) } + + fn error(&self) -> Option { + lock(&self.shared.error).clone() + } } /// An RTC that offers exactly `codec` and, if `audio`, Opus. diff --git a/crates/voelin-stream/src/discovery.rs b/crates/voelin-stream/src/discovery.rs index 75d3329..0e7d879 100644 --- a/crates/voelin-stream/src/discovery.rs +++ b/crates/voelin-stream/src/discovery.rs @@ -201,6 +201,13 @@ impl Discovery { changed } + /// Ask the server (`requeststreaminfo`) for the streams of `streamer` + /// again, e.g. for their viewer counts; `false` if it cannot answer. + pub fn ask_server(&mut self, streamer: ClientId, out: &mut Outbox) -> bool { + // The server is the first lookup (see `new`). + self.lookups.first_mut().is_some_and(|server| server.lookup(streamer, out)) + } + /// A request of a lookup failed on the server. pub fn failed(&mut self, request: &Request, error: &str) { for lookup in &mut self.lookups { @@ -246,6 +253,7 @@ mod tests { bitrate: 4608, viewer_limit: 0, audio: true, + viewers: Some(0), }, return_code: None, } diff --git a/crates/voelin-stream/src/layer.rs b/crates/voelin-stream/src/layer.rs index f4b538f..a915d7e 100644 --- a/crates/voelin-stream/src/layer.rs +++ b/crates/voelin-stream/src/layer.rs @@ -79,6 +79,56 @@ impl LayerSpec { } } +/// The session-level SDP attribute in which a Voelin streamer's offer lists +/// its layers, so that a Voelin viewer can pick one (`Signal::Layer`): +/// `a=x-voelin-layers: ...`, each layer +/// `//[/]`. WebRTC stacks skip session +/// attributes they do not know (libwebrtc, which the official TeamSpeak +/// client is built on, and str0m), so other viewers are unaffected, and a +/// viewer asks for a layer only when the offer had it. +pub const SDP_ATTRIBUTE: &str = "x-voelin-layers"; + +/// `sdp` with the [`SDP_ATTRIBUTE`] line listing `layers` at the end of its +/// session section (before the first `m=` line). +pub fn add_to_sdp(sdp: &str, layers: &[LayerSpec]) -> String { + let list: Vec = layers + .iter() + .map(|l| { + let size = l.size.map_or_else(|| l.scale.to_string(), |(w, h)| format!("{w}x{h}")); + let fps = l.max_fps.map(|f| format!("/{f}")).unwrap_or_default(); + format!("{}/{size}/{}{fps}", l.id, l.bitrate) + }) + .collect(); + let line = format!("a={SDP_ATTRIBUTE}:{}\r\n", list.join(" ")); + let at = sdp.find("\r\nm=").map_or(sdp.len(), |i| i + 2); + let mut out = String::with_capacity(sdp.len() + line.len()); + out.push_str(&sdp[..at]); + out.push_str(&line); + out.push_str(&sdp[at..]); + out +} + +/// The layers an SDP lists in [`SDP_ATTRIBUTE`]; `None` without the +/// attribute. Entries that do not parse are left out. +pub fn from_sdp(sdp: &str) -> Option> { + let prefix = format!("a={SDP_ATTRIBUTE}:"); + let value = sdp.lines().find_map(|l| l.trim_end().strip_prefix(prefix.as_str()))?; + let layer = |entry: &str| { + let mut parts = entry.split('/'); + let id = parts.next()?.parse().ok()?; + let size = parts.next()?; + let bitrate = parts.next()?.parse().ok()?; + let max_fps = parts.next().map(str::parse).transpose().ok()?; + let mut layer = LayerSpec { id, max_fps, ..LayerSpec::single(bitrate) }; + match size.split_once('x') { + Some((w, h)) => layer.size = Some((w.parse().ok()?, h.parse().ok()?)), + None => layer.scale = size.parse().ok()?, + } + Some(layer) + }; + Some(value.split_whitespace().filter_map(layer).collect()) +} + /// A set of layers, e.g. those waiting for a keyframe. Grows as needed. #[derive(Clone, Default, PartialEq, Eq)] pub struct LayerSet { @@ -192,6 +242,30 @@ mod tests { assert!(set.is_empty()); } + #[test] + fn layers_in_the_sdp() { + let layers = vec![ + LayerSpec { id: 0, size: Some((1920, 1080)), ..LayerSpec::single(6_000_000) }, + LayerSpec { id: 3, scale: 0.5, max_fps: Some(15), ..LayerSpec::single(800_000) }, + ]; + let sdp = "v=0\r\no=- 1 2 IN IP4 0.0.0.0\r\ns=-\r\nt=0 0\r\na=group:BUNDLE 0\r\n\ + m=video 9 UDP/TLS/RTP/SAVPF 96\r\na=mid:0\r\n"; + let with = add_to_sdp(sdp, &layers); + assert_eq!( + with, + "v=0\r\no=- 1 2 IN IP4 0.0.0.0\r\ns=-\r\nt=0 0\r\na=group:BUNDLE 0\r\n\ + a=x-voelin-layers:0/1920x1080/6000000 3/0.5/800000/15\r\n\ + m=video 9 UDP/TLS/RTP/SAVPF 96\r\na=mid:0\r\n" + ); + assert_eq!(from_sdp(&with), Some(layers)); + assert_eq!(from_sdp(sdp), None); + // Garbled entries are left out. + assert_eq!( + from_sdp("a=x-voelin-layers:x/1/2 1/0.5 2/1/700000\r\n").unwrap(), + [LayerSpec { id: 2, ..LayerSpec::single(700_000) }] + ); + } + #[test] fn output_size() { let mut layer = LayerSpec::single(1_000_000); diff --git a/crates/voelin-stream/src/peer.rs b/crates/voelin-stream/src/peer.rs index 3d91125..ff5fdc7 100644 --- a/crates/voelin-stream/src/peer.rs +++ b/crates/voelin-stream/src/peer.rs @@ -252,6 +252,7 @@ pub struct MediaFrame { enum Cmd { Answer(String, oneshot::Sender>), + Offer(String, oneshot::Sender>), RemoteCandidate(String), Write { kind: MediaKind, time: MediaTime, data: Arc<[u8]>, rid: Option }, RequestKeyframe, @@ -372,6 +373,16 @@ impl Peer { rx.await.map_err(|_| PeerError::Closed)? } + /// Viewer side: answer a new offer of the streamer on this connection + /// (a renegotiation: the same ICE credentials and DTLS fingerprint). + /// The official client re-offers when the codec our answer chose is one + /// it does not encode, and expects the answer from the same peer. + pub async fn renegotiate(&self, offer: &str) -> Result { + let (tx, rx) = oneshot::channel(); + self.cmd.send(Cmd::Offer(offer.to_owned(), tx)).map_err(|_| PeerError::Closed)?; + rx.await.map_err(|_| PeerError::Closed)? + } + /// Add a trickled remote candidate (`candidate:...`, `a=` prefix optional). pub fn add_remote_candidate(&self, candidate: &str) { let _ = self.cmd.send(Cmd::RemoteCandidate(candidate.to_owned())); @@ -496,6 +507,40 @@ fn build_rtc( dtls::build_rtc(rtc_config, &config.srtp_profiles) } +/// `answer` with the payload types of each media line in the order of the +/// same media line of `offer` (those the offer lacks last). The offerer sends +/// the answer's first codec; str0m answers a new offer on a running +/// connection in the codec order the connection was built with, so without +/// this a streamer that re-offers with another codec first keeps sending the +/// old one. Only the `m=` line order changes, which str0m's own state does +/// not depend on. +fn order_like_offer(answer: &str, offer: &str) -> String { + let offered: Vec> = offer + .lines() + .filter_map(|l| l.trim_end().strip_prefix("m=")) + .map(|m| m.split_whitespace().skip(3).collect()) + .collect(); + let mut section = 0; + let mut out = String::with_capacity(answer.len()); + for line in answer.split_inclusive('\n') { + let Some(media) = line.trim_end().strip_prefix("m=") else { + out.push_str(line); + continue; + }; + let mut parts: Vec<&str> = media.split_whitespace().collect(); + if let Some(order) = offered.get(section) + && parts.len() > 3 + { + parts[3..].sort_by_key(|pt| order.iter().position(|o| o == pt).unwrap_or(usize::MAX)); + } + section += 1; + out.push_str("m="); + out.push_str(&parts.join(" ")); + out.push_str(&line[line.trim_end().len()..]); + } + out +} + /// The video codecs of the first video media line of `sdp`, in offered order. fn offered_video_codecs(sdp: &str) -> Vec { let mut pts: Vec<&str> = Vec::new(); @@ -826,6 +871,13 @@ impl Task { let result = self.accept_answer(&sdp); let _ = reply.send(result); } + Cmd::Offer(sdp, reply) => { + let result = SdpOffer::from_sdp_string(&sdp) + .map_err(|e| PeerError::Sdp(e.to_string())) + .and_then(|offer| Ok(self.rtc.sdp_api().accept_offer(offer)?.to_sdp_string())) + .map(|answer| order_like_offer(&answer, &sdp)); + let _ = reply.send(result); + } Cmd::RemoteCandidate(line) => { let line = line.trim().trim_start_matches("a="); match Candidate::from_sdp_string(line) { @@ -951,6 +1003,53 @@ mod tests { assert_eq!(offered_video_codecs(&answer), [VideoCodec::Vp8], "{answer}"); } + /// The ICE username fragment and DTLS fingerprint of an SDP. + fn transport(sdp: &str) -> (String, String) { + let line = |prefix: &str| { + sdp.lines().find_map(|l| l.strip_prefix(prefix)).unwrap_or_default().trim().to_owned() + }; + (line("a=ice-ufrag:"), line("a=fingerprint:")) + } + + /// A streamer's new offer (the official client re-offers when it does not + /// encode the codec our answer chose) is answered on the same connection: + /// same ICE credentials and DTLS fingerprint, the new media answered. + #[tokio::test] + async fn a_new_offer_is_answered_on_the_same_connection() { + let mut streamer = RtcConfig::new() + .clear_codecs() + .enable_vp8(true) + .enable_opus(true) + .build(Instant::now()); + let mut api = streamer.sdp_api(); + api.add_media(MediaKind::Video, Direction::SendOnly, None, None, None); + let (offer, pending) = api.apply().unwrap(); + let (peer, answer) = + Peer::answer(&PeerConfig::loopback(), &offer.to_sdp_string()).await.unwrap(); + let answer_sdp = SdpAnswer::from_sdp_string(&answer).unwrap(); + streamer.sdp_api().accept_answer(pending, answer_sdp).unwrap(); + + let mut api = streamer.sdp_api(); + api.add_media(MediaKind::Audio, Direction::SendOnly, None, None, None); + let (offer, _pending) = api.apply().unwrap(); + let again = peer.renegotiate(&offer.to_sdp_string()).await.unwrap(); + assert_eq!(transport(&again), transport(&answer), "{again}"); + assert!(again.lines().all(|l| !l.is_empty() || l.ends_with('\r')), "line ends kept"); + assert!(!transport(&again).0.is_empty()); + assert!(again.contains("m=audio") && again.contains("opus/48000"), "{again}"); + } + + #[test] + fn answers_follow_the_offers_codec_order() { + let offer = "v=0\r\nm=audio 9 UDP/TLS/RTP/SAVPF 111\r\nm=video 9 UDP/TLS/RTP/SAVPF 98 99 96 97 45\r\n"; + let answer = "v=0\r\nm=audio 9 UDP/TLS/RTP/SAVPF 111\r\na=mid:0\r\nm=video 9 UDP/TLS/RTP/SAVPF 96 97 7 98 99\r\na=rtpmap:96 VP8/90000\r\n"; + assert_eq!( + order_like_offer(answer, offer), + "v=0\r\nm=audio 9 UDP/TLS/RTP/SAVPF 111\r\na=mid:0\r\nm=video 9 UDP/TLS/RTP/SAVPF 98 99 96 97 7\r\na=rtpmap:96 VP8/90000\r\n" + ); + assert_eq!(order_like_offer("v=0\r\n", offer), "v=0\r\n"); + } + /// An offer of codecs we cannot decode is refused with the reason, not /// answered with a video section the streamer cannot parse. #[tokio::test] diff --git a/crates/voelin-stream/src/proto.rs b/crates/voelin-stream/src/proto.rs index 38ed4fe..5600618 100644 --- a/crates/voelin-stream/src/proto.rs +++ b/crates/voelin-stream/src/proto.rs @@ -116,6 +116,11 @@ pub struct StreamInfo { pub bitrate: u32, pub viewer_limit: u32, pub audio: bool, + /// How many watch it: `viewer` of `notifystreaminfo`, 0 for a stream + /// that just started, then kept current from the viewers joining and + /// leaving (see [`StreamDirectory`](crate::session::StreamDirectory)). + /// `None` where nothing told (e.g. a gateway's directory entry). + pub viewers: Option, } /// Stream notifications, decoded from [`InMessage`]. @@ -190,6 +195,7 @@ impl StreamNotification { bitrate: p.bitrate.unwrap_or(0), viewer_limit: p.viewer_limit.unwrap_or(0), audio: p.audio.unwrap_or(false), + viewers: Some(0), }, return_code: p.return_code.clone(), }) @@ -207,6 +213,7 @@ impl StreamNotification { bitrate: p.bitrate.unwrap_or(0), viewer_limit: p.viewer_limit.unwrap_or(0), audio: p.audio.unwrap_or(false), + viewers: p.viewers, })) }) .collect(), @@ -399,7 +406,7 @@ mod tests { .iter() .map(|n| match n { StreamNotification::Info(i) => { - (i.id.as_str(), i.streamer, i.name.as_str(), i.audio) + (i.id.as_str(), i.streamer, i.name.as_str(), i.audio, i.viewers) } other => panic!("{other:?}"), }) @@ -407,8 +414,8 @@ mod tests { assert_eq!( infos, [ - ("6b5158dd", ClientId(6), "renamed again", true), - ("069ba23c", ClientId(6), "second", false) + ("6b5158dd", ClientId(6), "renamed again", true, Some(0)), + ("069ba23c", ClientId(6), "second", false, Some(2)) ] ); // A client without streams. diff --git a/crates/voelin-stream/src/session.rs b/crates/voelin-stream/src/session.rs index 5a58e47..32f8167 100644 --- a/crates/voelin-stream/src/session.rs +++ b/crates/voelin-stream/src/session.rs @@ -39,7 +39,7 @@ use tsproto_packets::packets::OutCommand; use crate::discovery::{ClientState, Discovery, StreamLookup}; use crate::dtls::SrtpProfile; use crate::feedback::LayerFeedback; -use crate::layer::{LayerId, LayerSet, LayerSpec}; +use crate::layer::{self, LayerId, LayerSet, LayerSpec}; use crate::peer::{MediaFrame, OfferOptions, Peer, PeerConfig, PeerEvent, VideoCodec}; use crate::proto::{self, LeaveReason, StreamInfo, StreamNotification, StreamSetup}; use crate::signal::Signal; @@ -189,6 +189,10 @@ pub enum WatchEvent { Connected, /// An encoded video or audio frame. Frame(MediaFrame), + /// The simulcast layers the streamer's offer lists + /// ([`layer::SDP_ATTRIBUTE`]): pick one with [`Streams::set_watch_layer`]. + /// Only Voelin streamers list them, and only with several layers. + Layers(Vec), Ended(EndReason), } @@ -252,6 +256,10 @@ pub enum SessionError { NotWatching(String), #[error("cannot watch our own stream")] OwnStream, + #[error("stream {0} has no layers to choose from")] + NoLayers(String), + #[error("stream {0} has no layer {1}")] + UnknownLayer(String, LayerId), } /// The streams in our channel, from `notifystreamstarted`/`notifystreaminfo`/ @@ -284,6 +292,20 @@ impl StreamDirectory { *info != before } StreamNotification::Stopped { id, .. } => self.streams.remove(id).is_some(), + // The server tells the whole channel who joins, but only the + // streamer and the viewer who leaves (and nobody when a viewer + // stops watching by leaving the server): + // [`Streams::refresh_viewer_counts`] asks again now and then. + StreamNotification::ViewerJoined { id, .. } + | StreamNotification::ViewerLeft { id, .. } => { + let joined = matches!(n, StreamNotification::ViewerJoined { .. }); + let Some(count) = self.streams.get_mut(id).and_then(|s| s.viewers.as_mut()) else { + return false; + }; + let before = *count; + *count = if joined { count.saturating_add(1) } else { count.saturating_sub(1) }; + *count != before + } _ => false, } } @@ -547,6 +569,9 @@ struct ViewerSlot { srtp_profile: Option, /// The video codec its answer chose. codec: Option, + /// The layer the viewer asked for ([`Signal::Layer`]); `None`: its + /// estimate decides. + pinned: Option, } impl ViewerSlot { @@ -560,6 +585,7 @@ impl ViewerSlot { estimate: None, srtp_profile: None, codec: None, + pinned: None, } } @@ -746,10 +772,32 @@ impl StreamerSession { self.offer(viewer, true, out).await; } } + Signal::Layer { layer } => self.pin(viewer, layer, out), other => debug!(viewer = viewer.0, "ignoring signal {other:?}"), } } + /// A viewer asks for `layer` ([`Signal::Layer`]; `None`: its estimate + /// decides again). It moves at the layer's next keyframe, which is + /// requested. An unknown layer counts as `None`; viewers with RID + /// simulcast get every layer anyway. + fn pin(&mut self, viewer: ClientId, layer: Option, out: &mut Outbox) { + let start = self.start_bitrate(); + let Some(slot) = self.viewers.get_mut(&viewer.0).filter(|s| s.rids.is_none()) else { + return; + }; + slot.pinned = layer.filter(|l| self.layers.index(*l).is_some()); + slot.choice.up_since = None; + let fitting = self.layers.fitting(slot.estimate.unwrap_or(start)); + let target = slot.pinned.unwrap_or(self.layers.specs[fitting].id); + debug!(viewer = viewer.0, ?layer, target, "viewer picks a layer"); + if let Some(layer) = slot.choice.switch_to(target) { + self.keyframe_request(layer, out); + } + self.emit_viewers(out); + self.update_targets(out); + } + /// The estimate a new viewer starts with. fn start_bitrate(&self) -> u64 { self.options.start_bitrate.unwrap_or(self.layers.specs[self.layers.top()].bitrate) @@ -795,10 +843,19 @@ impl StreamerSession { }; match Peer::offer_with(&self.config, &id, &options).await { Ok((peer, sdp)) => { + // Voelin viewers learn the layers and may pick one (other + // clients skip the attribute); not with RID simulcast, where + // a viewer gets them all. + let sdp = if self.layers.len() > 1 && !rid_offer { + layer::add_to_sdp(&sdp, &self.layers.specs) + } else { + sdp + }; if let Some(slot) = self.viewers.get_mut(&viewer.0) { slot.peer = Some(peer); slot.state = ViewerState::Connecting; - slot.choice = LayerChoice::new(layer); + // A reconnecting viewer keeps the layer it asked for. + slot.choice = LayerChoice::new(slot.pinned.unwrap_or(layer)); slot.codec = None; slot.rids = None; slot.estimate = None; @@ -902,14 +959,17 @@ impl StreamerSession { let start = self.start_bitrate(); let mut keyframes = LayerSet::new(); for slot in self.viewers.values_mut() { + slot.pinned = slot.pinned.filter(|l| self.layers.index(*l).is_some()); if slot.peer.is_none() { - slot.choice = LayerChoice::new(self.layers.specs[self.layers.fitting(start)].id); + let fitting = self.layers.specs[self.layers.fitting(start)].id; + slot.choice = LayerChoice::new(slot.pinned.unwrap_or(fitting)); continue; } if slot.rids.is_none() { let fitting = self.layers.fitting(slot.estimate.unwrap_or(start)); slot.choice.up_since = None; - if let Some(layer) = slot.choice.switch_to(self.layers.specs[fitting].id) { + let target = slot.pinned.unwrap_or(self.layers.specs[fitting].id); + if let Some(layer) = slot.choice.switch_to(target) { keyframes.insert(layer); } if slot.connected() { @@ -1125,7 +1185,7 @@ impl StreamerSession { let (keyframe, affected) = match &slot.rids { Some(_) => (None, None), None => { - let keyframe = if self.layers.len() > 1 { + let keyframe = if self.layers.len() > 1 && slot.pinned.is_none() { slot.choice.estimate(&self.layers, bitrate, now) } else { None @@ -1168,7 +1228,9 @@ impl StreamerSession { let lowest = self .viewers .values() - .filter(|v| v.connected()) + // A viewer that picked its layer takes it as it is: a slow one + // must not lower the picture of everyone else on that layer. + .filter(|v| v.connected() && v.pinned.is_none()) .filter_map(|v| { let estimate = v.estimate?; match &v.rids { @@ -1239,6 +1301,11 @@ pub struct ViewerSession { reconnects: u32, /// The RID simulcast layer we play, if the streamer sends several. layer_rid: Option, + /// The layers the streamer's offer listed; `None`: it listed none (not + /// a Voelin streamer, or one layer), so we never ask for one. + layers: Option>, + /// The layer we asked for; `None`: the streamer's estimate decides. + layer: Option, } impl ViewerSession { @@ -1261,6 +1328,8 @@ impl ViewerSession { peer: None, reconnects: 0, layer_rid: None, + layers: None, + layer: None, } } @@ -1307,6 +1376,18 @@ impl ViewerSession { } } StreamNotification::Signaling { json, .. } => match Signal::parse(json) { + // A new offer on the running connection (the official client + // re-offers when it does not encode the codec we chose) is + // answered by the same peer; `reconnectOffer` starts a new one. + Ok(Signal::Offer { sdp, reconnect: false }) if self.peer.is_some() => { + let peer = self.peer.as_ref().expect("checked above"); + match peer.renegotiate(&sdp).await { + Ok(sdp) => self.signal(Signal::Answer { sdp }, out), + Err(e) => { + self.fail(format!("cannot answer the streamer's new offer: {e}"), out) + } + } + } Ok(Signal::Offer { sdp, .. }) => self.answer(&sdp, out).await, Ok(Signal::IceCandidate { candidate, .. }) => { if let Some(peer) = &self.peer { @@ -1331,6 +1412,13 @@ impl ViewerSession { self.peer = Some(peer); self.state = WatchState::Connecting; self.signal(Signal::Answer { sdp }, out); + let layers = layer::from_sdp(offer).filter(|l| l.len() > 1); + if layers != self.layers { + self.layer = + self.layer.filter(|id| layers.iter().flatten().any(|l| l.id == *id)); + self.layers = layers; + self.event(WatchEvent::Layers(self.layers.clone().unwrap_or_default()), out); + } } Err(e) => self.fail(format!("cannot answer the streamer's offer: {e}"), out), } @@ -1361,6 +1449,36 @@ impl ViewerSession { } } + /// The layers the streamer offers to choose from (see + /// [`WatchEvent::Layers`]). + pub fn layers(&self) -> &[LayerSpec] { + self.layers.as_deref().unwrap_or_default() + } + + /// The layer we asked for ([`set_layer`](Self::set_layer)). + pub fn layer(&self) -> Option { + self.layer + } + + /// Ask the streamer for simulcast layer `layer` (`None`: let our + /// bandwidth estimate decide again). Only if its offer listed layers: + /// other streamers never get the request. + pub fn set_layer( + &mut self, + layer: Option, + out: &mut Outbox, + ) -> Result<(), SessionError> { + let layers = self.layers.as_ref().ok_or_else(|| SessionError::NoLayers(self.id.clone()))?; + if let Some(id) = layer + && !layers.iter().any(|l| l.id == id) + { + return Err(SessionError::UnknownLayer(self.id.clone(), id)); + } + self.layer = layer; + self.signal(Signal::Layer { layer }, out); + Ok(()) + } + /// Drop the connection and ask the streamer for a new offer (`reconnect`). pub fn reconnect(&mut self, out: &mut Outbox) { if matches!(self.state, WatchState::Connecting | WatchState::Connected) { @@ -1476,6 +1594,8 @@ pub struct Streams { streamer: Option, viewers: BTreeMap, out: Outbox, + /// The stream whose viewer count was asked for last. + counted: Option, } impl Streams { @@ -1489,6 +1609,7 @@ impl Streams { streamer: None, viewers: BTreeMap::new(), out: Outbox::default(), + counted: None, } } @@ -1651,6 +1772,18 @@ impl Streams { } } + /// Watch simulcast layer `layer` of a stream (`None`: as our bandwidth + /// allows); see [`ViewerSession::set_layer`]. + pub fn set_watch_layer( + &mut self, + id: &str, + layer: Option, + ) -> Result<(), SessionError> { + let viewer = + self.viewers.get_mut(id).ok_or_else(|| SessionError::NotWatching(id.into()))?; + viewer.set_layer(layer, &mut self.out) + } + /// Reconnect to a watched stream: the streamer sends a new offer. pub fn reconnect(&mut self, id: &str) -> Result<(), SessionError> { let viewer = @@ -1730,6 +1863,24 @@ impl Streams { self.discovery.add_lookup(lookup); } + /// Ask the server for the viewer count of the next stream of another + /// client in our channel, round robin: one `requeststreaminfo` per call, + /// so a few calls a minute keep the counts close without flooding the + /// server however many stream. Viewers leaving are only announced to the + /// streamer and themselves (see [`StreamDirectory::apply`]). + pub fn refresh_viewer_counts(&mut self) { + let (own, last) = (self.own, self.counted.take()); + let others = || self.directory.iter().filter(|s| s.streamer != own); + let next = others() + .find(|s| last.as_ref().is_some_and(|last| s.id > *last)) + .or_else(|| others().next()) + .map(|s| (s.id.clone(), s.streamer)); + let Some((id, streamer)) = next else { return }; + if self.discovery.ask_server(streamer, &mut self.out) { + self.counted = Some(id); + } + } + /// A request from [`Output::Request`] failed on the server. pub fn request_failed(&mut self, request: &Request, error: &str) { let watched = match request { @@ -1827,6 +1978,7 @@ mod tests { bitrate: 4608, viewer_limit: 0, audio: true, + viewers: Some(0), } } @@ -2223,6 +2375,45 @@ mod tests { assert!(!d.apply(&join(ClientId(3), false))); } + #[tokio::test] + async fn viewer_counts() { + let joined = |id: &str| StreamNotification::ViewerJoined { id: id.into(), viewer: OTHER }; + let left = |id: &str| StreamNotification::ViewerLeft { + id: id.into(), + viewer: OTHER, + reason: Some(LeaveReason::None), + }; + let mut d = StreamDirectory::default(); + assert!(d.apply(&started("a", ClientId(1), false))); + assert_eq!(d.get("a").unwrap().viewers, Some(0)); + assert!(d.apply(&joined("a")) && d.apply(&joined("a")) && d.apply(&left("a"))); + assert_eq!(d.get("a").unwrap().viewers, Some(1)); + // The server's count replaces ours; never below zero. + let counted = StreamInfo { viewers: Some(5), ..info("a", ClientId(1)) }; + assert!(d.apply(&StreamNotification::Info(counted))); + assert_eq!(d.get("a").unwrap().viewers, Some(5)); + let unknown = StreamInfo { viewers: None, ..info("a", ClientId(1)) }; + assert!(d.apply(&StreamNotification::Info(unknown))); + assert!(!d.apply(&joined("a")) && !d.apply(&left("x"))); + assert!(d.apply(&started("z", ClientId(1), false)) && !d.apply(&left("z"))); + + // Asked for one stream of another client at a time, round robin. + let mut s = Streams::new(OWN, PeerConfig::loopback()); + for (id, streamer) in [("a", OWN), ("b", ClientId(2)), ("c", ClientId(3))] { + s.handle_notification(StreamNotification::Info(info(id, streamer))).await; + } + let _ = drain(&mut s); + let mut asked = Vec::new(); + for _ in 0..3 { + s.refresh_viewer_counts(); + asked.extend(drain(&mut s).0.into_iter().map(|r| match r { + Request::StreamInfo { streamer } => streamer.0, + other => panic!("{other:?}"), + })); + } + assert_eq!(asked, [2, 3, 2]); + } + /// Layers for the simulcast tests: 0 needs 2 Mbit/s, 1 needs 600 kbit/s /// (at most 1.2 Mbit/s), 2 is the fallback. fn three_layers() -> Vec { diff --git a/crates/voelin-stream/src/signal.rs b/crates/voelin-stream/src/signal.rs index 923465c..9152f3e 100644 --- a/crates/voelin-stream/src/signal.rs +++ b/crates/voelin-stream/src/signal.rs @@ -7,6 +7,8 @@ use serde_json::{Map, Value, json}; +use crate::layer::LayerId; + /// One signalling message between streamer and viewer. #[derive(Clone, Debug, PartialEq, Eq)] pub enum Signal { @@ -18,6 +20,11 @@ pub enum Signal { IceCandidate { candidate: String, mid: Option, mline_index: Option }, /// The other side asks for a new offer. Reconnect, + /// A Voelin viewer asks for simulcast layer `layer` (`None`: let its + /// bandwidth estimate decide again). Sent only to a streamer whose offer + /// listed its layers ([`crate::layer::SDP_ATTRIBUTE`]): only Voelin + /// streamers do, so other clients never get it. + Layer { layer: Option }, /// A command this client does not know; kept for logging. Unknown { cmd: String, args: Value }, } @@ -63,6 +70,9 @@ impl Signal { .and_then(|v| u32::try_from(v).ok()), }, "reconnect" => Signal::Reconnect, + "x-voelin-layer" => Signal::Layer { + layer: args.get("layer").and_then(Value::as_u64).and_then(|v| v.try_into().ok()), + }, other => Signal::Unknown { cmd: other.to_owned(), args: Value::Object(args.clone()) }, }) } @@ -79,6 +89,9 @@ impl Signal { "args": { "candidate": candidate, "sdpMid": mid, "sdpMLineIndex": mline_index }, }), Signal::Reconnect => json!({ "cmd": "reconnect", "args": {} }), + Signal::Layer { layer } => { + json!({ "cmd": "x-voelin-layer", "args": { "layer": layer } }) + } Signal::Unknown { cmd, args } => json!({ "cmd": cmd, "args": args }), }; value.to_string() @@ -101,6 +114,8 @@ mod tests { mline_index: Some(0), }, Signal::Reconnect, + Signal::Layer { layer: Some(2) }, + Signal::Layer { layer: None }, ]; for s in signals { assert_eq!(Signal::parse(&s.to_json()).unwrap(), s); diff --git a/crates/voelin-stream/tests/browser_interop.rs b/crates/voelin-stream/tests/browser_interop.rs index 538c55c..c0093d4 100644 --- a/crates/voelin-stream/tests/browser_interop.rs +++ b/crates/voelin-stream/tests/browser_interop.rs @@ -9,7 +9,7 @@ use std::time::{Duration, Instant}; use serde_json::json; use tokio::time::timeout; use voelin_stream::{ - Codec, FrameSource, MediaKind, Peer, PeerConfig, PeerEvent, Signal, SrtpProfile, + Codec, FrameSource, LayerSpec, MediaKind, Peer, PeerConfig, PeerEvent, Signal, SrtpProfile, SyntheticSource, }; @@ -50,6 +50,14 @@ async fn rust_streams_to_browser() { let mut browser = Browser::start().await; let config = PeerConfig::loopback(); let (mut peer, offer) = Peer::offer(&config, "interop").await.unwrap(); + // As a Voelin streamer with several layers offers: with the list of its + // layers, which libwebrtc (the official client's stack) must skip. + let layers = [ + LayerSpec::single(4_000_000), + LayerSpec { id: 1, scale: 0.5, ..LayerSpec::single(1_000_000) }, + ]; + let offer = voelin_stream::layer::add_to_sdp(&offer, &layers); + assert!(offer.contains("\r\na=x-voelin-layers:0/1/4000000 1/0.5/1000000\r\n"), "{offer}"); let answer = browser.call(json!({ "op": "answer", "sdp": offer })).await; let answer = answer["sdp"].as_str().unwrap(); eprintln!("browser answer:\n{answer}"); @@ -273,3 +281,34 @@ async fn browser_streams_to_rust() { assert!(aes_cm_128_sha1_80(&stats["transport"]["srtpCipher"]), "{stats:#}"); browser.quit().await; } + +/// Chromium streams VP8, then renegotiates to VP9 on the same connection, as +/// the official client re-offers when it does not encode the codec our +/// answer chose: our viewer answers on the same peer and keeps receiving, +/// now VP9. +#[tokio::test(flavor = "multi_thread")] +async fn browser_renegotiates_with_rust() { + if !enabled() { + eprintln!("skipped: set VOELIN_INTEROP=1 (needs node, Playwright and Chromium)"); + return; + } + let _ = tracing_subscriber::fmt().with_env_filter("warn").with_test_writer().try_init(); + let mut browser = Browser::start().await; + let offer = browser.call(json!({ "op": "offer", "codec": "VP8", "trickle": false })).await; + let (mut peer, answer) = + Peer::answer(&PeerConfig::loopback(), offer["sdp"].as_str().unwrap()).await.unwrap(); + browser.call(json!({ "op": "accept", "sdp": answer })).await; + wait_connected(&mut peer).await; + let before = receive(&mut peer, Duration::from_secs(5), 30).await; + assert!(before.video.get(Codec::Vp8) >= 30, "before: {:?}", before.video); + + let offer = browser.call(json!({ "op": "reoffer", "codec": "VP9" })).await; + let again = peer.renegotiate(offer["sdp"].as_str().unwrap()).await.unwrap(); + browser.call(json!({ "op": "accept", "sdp": again })).await; + let after = receive(&mut peer, Duration::from_secs(8), 30).await; + eprintln!("after the new offer: video {:?}, audio {:?}", after.video, after.audio); + assert!(after.video.get(Codec::Vp9) >= 30, "after: {:?}", after.video); + let stats = browser.call(json!({ "op": "stats" })).await; + assert_eq!(stats["connectionState"], "connected", "{stats:#}"); + browser.quit().await; +} diff --git a/crates/voelin-stream/tests/sessions.rs b/crates/voelin-stream/tests/sessions.rs index 2c11cfb..7b74139 100644 --- a/crates/voelin-stream/tests/sessions.rs +++ b/crates/voelin-stream/tests/sessions.rs @@ -8,9 +8,9 @@ use std::time::{Duration, Instant}; use tokio::time::timeout; use tsclientlib::ClientId; use voelin_stream::{ - ClientState, EndReason, FrameSource, LeaveReason, MediaKind, Output, PeerConfig, Request, - StreamEvent, StreamInfo, StreamKind, StreamNotification, StreamSetup, StreamerEvent, - StreamerOptions, Streams, SyntheticSource, ViewerState, WatchEvent, + ClientState, EndReason, FrameSource, LayerSpec, LeaveReason, MediaKind, Output, PeerConfig, + Request, SessionError, Signal, StreamEvent, StreamInfo, StreamKind, StreamNotification, + StreamSetup, StreamerEvent, StreamerOptions, Streams, SyntheticSource, ViewerState, WatchEvent, }; const STREAMER: usize = 0; @@ -43,6 +43,7 @@ impl FakeServer { bitrate: setup.bitrate, viewer_limit: setup.viewer_limit, audio: setup.audio, + viewers: Some(0), }; self.streams.insert(info.id.clone(), info.clone()); (0..2) @@ -108,6 +109,10 @@ struct Net { source: Option, video: usize, audio: usize, + /// The layer of the last video frame the viewer got (layered sources). + layer: Option, + /// Every signal relayed, with the sender's index. + signals: Vec<(usize, Signal)>, } impl Net { @@ -120,6 +125,8 @@ impl Net { source: None, video: 0, audio: 0, + layer: None, + signals: Vec::new(), } } @@ -130,11 +137,19 @@ impl Net { for (i, client) in self.clients.iter_mut().enumerate() { while let Some(output) = client.poll_output() { match output { - Output::Request(r) => notes.extend(self.server.relay(IDS[i], r)), + Output::Request(r) => { + if let Request::Signal { signal, .. } = &r { + self.signals.push((i, signal.clone())); + } + notes.extend(self.server.relay(IDS[i], r)); + } Output::Event(StreamEvent::Watch { event: WatchEvent::Frame(f), .. }) => match f.kind { - MediaKind::Video => self.video += 1, + MediaKind::Video => { + self.video += 1; + self.layer = SyntheticSource::frame_layer(&f.data); + } MediaKind::Audio => self.audio += 1, }, Output::Event(e) => self.events.push((i, e)), @@ -184,6 +199,28 @@ impl Net { .unwrap_or_else(|_| panic!("timed out waiting for {what}; events: {:?}", self.events)); } + /// Run until the viewer's video comes from `layer` (and the streamer + /// reports it on that layer). + async fn on_layer(&mut self, layer: u8) { + let deadline = Instant::now() + Duration::from_secs(10); + loop { + let streamer = self.clients[STREAMER].streamer().unwrap().viewers(); + let reported = streamer.first().and_then(|v| v.layer) == Some(u16::from(layer)); + let video = self.video; + // Frames of the new layer, after the switch. + if self.layer == Some(layer) && reported { + while self.video < video + 5 { + self.step().await; + } + if self.layer == Some(layer) { + return; + } + } + assert!(Instant::now() < deadline, "video stays on layer {:?}", self.layer); + self.step().await; + } + } + /// Run until the viewer received `n` more video and audio frames. async fn frames(&mut self, n: usize) { let (video, audio) = (self.video + n, self.audio + n); @@ -334,3 +371,96 @@ async fn late_viewer_finds_the_stream() { }) .await; } + +/// A Voelin streamer with layers lists them in its offer; the viewer picks +/// one, and "Auto" hands the choice back to its bandwidth estimate. +#[tokio::test(flavor = "multi_thread")] +async fn viewer_picks_a_layer() { + let _ = tracing_subscriber::fmt().with_env_filter("warn").with_test_writer().try_init(); + let mut net = Net::new(); + // Without `min_bitrate`s every estimate fits the top layer. + let layers = vec![ + LayerSpec { id: 0, ..LayerSpec::single(1_500_000) }, + LayerSpec { id: 1, scale: 0.5, max_fps: Some(15), ..LayerSpec::single(400_000) }, + ]; + let options = + StreamerOptions { auto_accept: true, layers: layers.clone(), ..Default::default() }; + net.clients[STREAMER].start(options).unwrap(); + net.until("stream in the viewer's list", |i, e| { + i == VIEWER && matches!(e, StreamEvent::Streams(l) if l.len() == 1) + }) + .await; + let id = net.clients[VIEWER].directory().by_streamer(IDS[STREAMER]).unwrap().id.clone(); + net.clients[VIEWER].watch(&id, "").unwrap(); + net.until("the offer's layers", |i, e| { + i == VIEWER + && watch_event(e, |e| { + matches!(e, WatchEvent::Layers(l) + if l.iter().map(|l| (l.id, l.scale, l.max_fps)).eq([(0, 1.0, None), (1, 0.5, Some(15))])) + }) + }) + .await; + net.until("viewer connected", |i, e| { + i == VIEWER && watch_event(e, |e| matches!(e, WatchEvent::Connected)) + }) + .await; + net.source = Some(SyntheticSource::with_layers(30, 0, true, &layers)); + net.on_layer(0).await; + + net.clients[VIEWER].set_watch_layer(&id, Some(1)).unwrap(); + assert_eq!(net.clients[VIEWER].watching().next().unwrap().layer(), Some(1)); + net.on_layer(1).await; + // The estimate does not move it back while it is picked. + net.frames(20).await; + assert_eq!(net.layer, Some(1)); + + net.clients[VIEWER].set_watch_layer(&id, None).unwrap(); + net.on_layer(0).await; + let asked: Vec<_> = net + .signals + .iter() + .filter_map(|(i, s)| match s { + Signal::Layer { layer } => Some((*i, *layer)), + _ => None, + }) + .collect(); + assert_eq!(asked, [(VIEWER, Some(1)), (VIEWER, None)]); + assert_eq!( + net.clients[VIEWER].set_watch_layer(&id, Some(7)), + Err(SessionError::UnknownLayer(id.clone(), 7)) + ); +} + +/// A streamer whose offer lists no layers (one layer here; an official +/// client always) is never asked for one. +#[tokio::test(flavor = "multi_thread")] +async fn no_layer_request_without_the_offer_listing_layers() { + let _ = tracing_subscriber::fmt().with_env_filter("warn").with_test_writer().try_init(); + let mut net = Net::new(); + let options = StreamerOptions { auto_accept: true, ..Default::default() }; + net.clients[STREAMER].start(options).unwrap(); + net.until("stream in the viewer's list", |i, e| { + i == VIEWER && matches!(e, StreamEvent::Streams(l) if l.len() == 1) + }) + .await; + let id = net.clients[VIEWER].directory().by_streamer(IDS[STREAMER]).unwrap().id.clone(); + net.clients[VIEWER].watch(&id, "").unwrap(); + net.until("viewer connected", |i, e| { + i == VIEWER && watch_event(e, |e| matches!(e, WatchEvent::Connected)) + }) + .await; + net.source = Some(SyntheticSource::new(30, 4000, true)); + net.frames(10).await; + assert!( + !net.events.iter().any(|(_, e)| watch_event(e, |e| matches!(e, WatchEvent::Layers(_)))), + "{:?}", + net.events + ); + let viewer = &mut net.clients[VIEWER]; + assert!(viewer.watching().next().unwrap().layers().is_empty()); + assert_eq!(viewer.set_watch_layer(&id, Some(0)), Err(SessionError::NoLayers(id.clone()))); + assert_eq!(viewer.set_watch_layer(&id, None), Err(SessionError::NoLayers(id.clone()))); + assert!(viewer.poll_output().is_none(), "nothing sent"); + net.flush().await; + assert!(!net.signals.iter().any(|(_, s)| matches!(s, Signal::Layer { .. }))); +} diff --git a/crates/voelin-stream/tests/simulcast.rs b/crates/voelin-stream/tests/simulcast.rs index 90c8c98..9700a02 100644 --- a/crates/voelin-stream/tests/simulcast.rs +++ b/crates/voelin-stream/tests/simulcast.rs @@ -47,6 +47,7 @@ async fn rid_simulcast_over_loopback() { bitrate: 1900, viewer_limit: 0, audio: true, + viewers: Some(0), }; s.handle_notification(StreamNotification::Started { info, return_code: Some("1".into()) }) .await; diff --git a/crates/voelin-ui/src/app.rs b/crates/voelin-ui/src/app.rs index a248792..1fb09b9 100644 --- a/crates/voelin-ui/src/app.rs +++ b/crates/voelin-ui/src/app.rs @@ -438,6 +438,9 @@ pub(crate) struct App { } thread_local! { + // It is `const`; clippy for Android targets does not see that through + // the macro's expansion there. + #[allow(clippy::missing_const_for_thread_local)] static APP: RefCell> = const { RefCell::new(None) }; } @@ -669,6 +672,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 @@ -768,6 +773,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(); } self.page_setting_changed(key); } diff --git a/crates/voelin-ui/src/bind/servers.rs b/crates/voelin-ui/src/bind/servers.rs index 9680b1d..6c631e0 100644 --- a/crates/voelin-ui/src/bind/servers.rs +++ b/crates/voelin-ui/src/bind/servers.rs @@ -58,4 +58,5 @@ pub(super) fn wire(ui: &MainWindow) { bridge.on_client_audio_changed(|form| { with_app(|app| app.client_playback_changed(&form)); }); + bridge.on_invite(|| with_app(|app| app.invite_link()).unwrap_or_default().into()); } diff --git a/crates/voelin-ui/src/bind/studio.rs b/crates/voelin-ui/src/bind/studio.rs index 1d3a0c1..4ed0b1c 100644 --- a/crates/voelin-ui/src/bind/studio.rs +++ b/crates/voelin-ui/src/bind/studio.rs @@ -73,8 +73,8 @@ pub(crate) fn wire(bridge: &StudioBridge) { bridge.on_list_audio(|| { with_app(|app| app.studio_list_audio()); }); - bridge.on_add_audio(|i| { - with_app(|app| app.studio_add_audio(index(i))); + bridge.on_toggle_audio(|i| { + with_app(|app| app.studio_toggle_audio(index(i))); }); bridge.on_set_gain(|i, db, done| { with_app(|app| app.studio_set_gain(index(i), db, done)); diff --git a/crates/voelin-ui/src/chat.rs b/crates/voelin-ui/src/chat.rs index 7b59bd2..d31bff3 100644 --- a/crates/voelin-ui/src/chat.rs +++ b/crates/voelin-ui/src/chat.rs @@ -367,7 +367,17 @@ impl App { let tabs: Vec = view .tabs .iter() - .map(|t| ChatTab { + .map(|t| { + let (last, time) = t + .messages + .last() + .map(|m| vm::chat::preview(&m.message.message)) + .unwrap_or_default(); + (t, last, time) + }) + .map(|(t, last, time)| ChatTab { + last: last.into(), + time: time.into(), title: t.title.clone().into(), name: t.title.trim_start_matches(['#', '@']).into(), kind: match t.target { @@ -775,7 +785,7 @@ impl App { } /// Upload a file into a channel and link it in the chat once it is up. - fn upload(&mut self, id: i64, channel: u64, from: PathBuf) { + pub(crate) fn upload(&mut self, id: i64, channel: u64, from: PathBuf) { let Some(name) = from.file_name().map(|n| n.to_string_lossy().to_string()) else { return }; let view = self.sessions.entry(id).or_default(); let transfer = view.next_transfer; diff --git a/crates/voelin-ui/src/dev.rs b/crates/voelin-ui/src/dev.rs index 25d1181..1049d74 100644 --- a/crates/voelin-ui/src/dev.rs +++ b/crates/voelin-ui/src/dev.rs @@ -15,7 +15,10 @@ //! appearance, or 0-4), `about`, `share`, `bookmark` (add a server), //! `emoji` (the picker), `client` (the volume dialog of the first other //! client once connected), `panel` / `no-panel` (the members panel), -//! `voice` (the voice channel view), `pins`, `topics` (the drawers), +//! `voice` (the voice channel view; on the phone its own screen), +//! `members` (the phone's members page), `notification` (a tapped voice +//! notification), `shared:` (text shared to the app on Android), +//! `pins`, `topics` (the drawers), //! `topic:` (a topic's messages), `member` (the member card of the //! first other client), `watch` (the first stream; with sample data the //! local test pattern in its place), `popout` (the same, popped out), @@ -167,7 +170,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), @@ -175,6 +184,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| { @@ -480,6 +498,7 @@ fn demo_ui(app: &mut App) { bitrate: 8000, viewer_limit: 0, audio: true, + viewers: Some(12), }], }, Event::State { diff --git a/crates/voelin-ui/src/inbox.rs b/crates/voelin-ui/src/inbox.rs new file mode 100644 index 0000000..0bb05c1 --- /dev/null +++ b/crates/voelin-ui/src/inbox.rs @@ -0,0 +1,101 @@ +//! Requests from the platform around the window: on Android a tapped +//! notification or something shared to the app ("Share to Voelin"). They +//! can come from any thread and before the window runs; [`request`] keeps +//! them until the window takes them on its thread. + +use std::path::PathBuf; +use std::sync::{Mutex, PoisonError}; + +use slint::ComponentHandle; +use voelin_model::ChatTarget; + +use crate::app::{App, MobileTab, Nav, Page, with_app}; + +/// What the platform asks the window to do. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Request { + /// Show the voice channel we are in (the phone's voice screen). + ShowVoice, + /// Shared to the app: the text goes into the current chat's composer + /// (to send with one tap, or edit, as a mis-tap in the share sheet + /// should not post into a chat), the files are uploaded to the current + /// channel and linked there, as the composer's attach button does. + Share { text: Option, files: Vec }, +} + +static PENDING: Mutex> = Mutex::new(Vec::new()); + +/// Hand `request` to the window: at once if it runs, else when it starts. +pub fn request(request: Request) { + PENDING.lock().unwrap_or_else(PoisonError::into_inner).push(request); + // Fails without an event loop yet; `run` takes them then. + let _ = slint::invoke_from_event_loop(take); +} + +/// Handle what is pending, on the window's thread; kept while there is no +/// window. +pub(crate) fn take() { + let Some(ui) = with_app(|app| app.ui.upgrade()).flatten() else { return }; + let requests = std::mem::take(&mut *PENDING.lock().unwrap_or_else(PoisonError::into_inner)); + // Not inside `with_app`: navigating calls back into Rust, which borrows + // the app again. + let nav = ui.global::