Modern Apps git

← Modern-Apps.git

communicate: screen sharing, and stop the two renderers clearing each other

Commit
7a7ce3096abf2fd331704681f997afd838aa46c5
Author
vayun-mathur <[email protected]>
When
2026-08-23 02:31 UTC (3 months ago)
Parents
d146208

Diff

communicate/src/main/AndroidManifest.xml
diff --git a/communicate/src/main/AndroidManifest.xml b/communicate/src/main/AndroidManifest.xmlindex b225c7ddba..5e1b36835f 100644--- a/communicate/src/main/AndroidManifest.xml+++ b/communicate/src/main/AndroidManifest.xml@@ -28,6 +28,8 @@     <uses-permission android:name="android.permission.CAMERA" />     <uses-permission android:name="android.permission.FOREGROUND_SERVICE_MICROPHONE" />     <uses-permission android:name="android.permission.FOREGROUND_SERVICE_CAMERA" />+    <!-- Screen sharing during a call: the capture must run under a mediaProjection foreground service. -->+    <uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PROJECTION" />      <uses-feature         android:name="android.hardware.camera.any"@@ -214,7 +216,7 @@         <service             android:name=".telephony.InAppCallForegroundService"             android:exported="false"-            android:foregroundServiceType="phoneCall" />+            android:foregroundServiceType="phoneCall|mediaProjection" />          <provider             android:name="androidx.core.content.FileProvider"
communicate/src/main/java/com/vayunmathur/communicate/data/call/InAppCall.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/call/InAppCall.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/call/InAppCall.ktindex 5037496ac9..0a39e90b29 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/call/InAppCall.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/call/InAppCall.kt@@ -17,10 +17,11 @@ data class CallCapabilities(     val speaker: Boolean = true,     val video: Boolean = false,     val dtmf: Boolean = false,+    val screenShare: Boolean = false, ) {     companion object {         val AudioOnly = CallCapabilities()-        val AudioAndVideo = CallCapabilities(video = true)+        val AudioAndVideo = CallCapabilities(video = true, screenShare = true)         val AudioAndKeypad = CallCapabilities(dtmf = true)     } }@@ -47,6 +48,10 @@ data class InAppCallState(     val remoteVideoEnabled: Boolean = false,     /** Whether our own camera is on. */     val localVideoEnabled: Boolean = false,+    /** Whether we are sending the screen rather than the camera. */+    val screenSharing: Boolean = false,+    /** Whether the peer is sharing their screen. */+    val remoteScreenSharing: Boolean = false,     val muted: Boolean = false,     val speaker: Boolean = false,     /** When the call became [InAppCallPhase.Active], for the duration readout. 0 until then. */@@ -98,7 +103,17 @@ interface InAppCallVideoController {     /** EGL context the renderers must share with the decoder, or null if video is unavailable. */     fun eglContext(): org.webrtc.EglBase.Context? -    fun attachRenderers(local: org.webrtc.VideoSink?, remote: org.webrtc.VideoSink?)+    /**+     * Attached separately rather than as a pair: the two renderers are created and disposed independently by+     * the UI, and a combined setter meant whichever recomposed last cleared the other's sink — which showed up+     * as remote video freezing when the self-view appeared.+     */+    fun attachLocalRenderer(sink: org.webrtc.VideoSink?)++    fun attachRemoteRenderer(sink: org.webrtc.VideoSink?)++    /** Share the screen instead of the camera. */+    fun setScreenShareEnabled(enabled: Boolean, permission: android.content.Intent?) }  /**@@ -202,6 +217,26 @@ object InAppCallRegistry {         _state.value = _state.value.copy(remoteVideoEnabled = enabled)     } +    fun onRemoteScreenShare(enabled: Boolean) {+        if (_state.value.phase == InAppCallPhase.Idle) return+        android.util.Log.i(TAG, "remote screen share enabled=$enabled")+        _state.value = _state.value.copy(remoteScreenSharing = enabled)+    }++    /**+     * Start or stop sharing the screen. [permission] is the result of the MediaProjection consent dialog and+     * is required to start; stopping needs nothing.+     */+    fun setScreenShare(enabled: Boolean, permission: android.content.Intent?) {+        if (enabled && permission == null) return+        videoController?.setScreenShareEnabled(enabled, permission)+        _state.value = _state.value.copy(+            screenSharing = enabled,+            // Sharing the screen is sending video, so the peer-facing state has to agree.+            localVideoEnabled = enabled || _state.value.localVideoEnabled,+        )+    }+     fun onLocalVideo(enabled: Boolean) {         if (_state.value.phase == InAppCallPhase.Idle) return         _state.value = _state.value.copy(localVideoEnabled = enabled, isVideo = _state.value.isVideo || enabled)
communicate/src/main/java/com/vayunmathur/communicate/data/signal/SignalClient.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/signal/SignalClient.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/signal/SignalClient.ktindex 10b2a61a08..a58441e5b1 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/signal/SignalClient.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/signal/SignalClient.kt@@ -1269,6 +1269,10 @@ object SignalClient {                     InAppCallRegistry.onRemoteVideo(enabled)                 } +                override fun onRemoteScreenShare(enabled: Boolean) {+                    InAppCallRegistry.onRemoteScreenShare(enabled)+                }+                 override fun onCallStateChanged(                     aci: String,                     callId: Long,@@ -1442,9 +1446,16 @@ object SignalClient {          override fun eglContext(): org.webrtc.EglBase.Context? = callManager?.eglContext() -        override fun attachRenderers(local: org.webrtc.VideoSink?, remote: org.webrtc.VideoSink?) {-            callManager?.localVideoSink?.attach(local)-            callManager?.remoteVideoSink?.attach(remote)+        override fun attachLocalRenderer(sink: org.webrtc.VideoSink?) {+            callManager?.localVideoSink?.attach(sink)+        }++        override fun attachRemoteRenderer(sink: org.webrtc.VideoSink?) {+            callManager?.remoteVideoSink?.attach(sink)+        }++        override fun setScreenShareEnabled(enabled: Boolean, permission: android.content.Intent?) {+            callManager?.setScreenShareEnabled(enabled, permission)         }     } 
communicate/src/main/java/com/vayunmathur/communicate/data/signal/call/SignalCallManager.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/signal/call/SignalCallManager.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/signal/call/SignalCallManager.ktindex 058ca306c0..1877cd8cc4 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/signal/call/SignalCallManager.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/signal/call/SignalCallManager.kt@@ -61,6 +61,9 @@ class SignalCallManager(         /** The peer turned their camera on or off. */         fun onRemoteVideo(enabled: Boolean) +        /** The peer started or stopped sharing their screen. */+        fun onRemoteScreenShare(enabled: Boolean)+         /**          * TURN/STUN relays for the call. Without them only host candidates are available, so a call fails          * behind NAT.@@ -86,6 +89,9 @@ class SignalCallManager(      */     private var camera: SignalCamera? = null +    /** Tracked so a later video toggle keeps telling RingRTC the source is a screencast. */+    private var screenSharing = false+     /** Exposed so the call UI can attach renderers once it exists. */     val localVideoSink = SwappableVideoSink()     val remoteVideoSink = SwappableVideoSink()@@ -136,7 +142,20 @@ class SignalCallManager(     /** Turn our outgoing video on or off mid-call. */     fun setVideoEnabled(enabled: Boolean): Boolean = withManager("setVideoEnable") {         camera?.setEnabled(enabled)-        it.setVideoEnable(enabled, false)+        it.setVideoEnable(enabled, screenSharing)+    }++    /**+     * Share the screen instead of the camera. RingRTC is told the outgoing video is a screencast so it adapts+     * the encoder for static content rather than treating it as camera motion.+     */+    fun setScreenShareEnabled(enabled: Boolean, permission: android.content.Intent?): Boolean {+        val started = camera?.setScreenShare(enabled, permission) ?: false+        if (enabled && !started) return false+        screenSharing = enabled && started+        return withManager("setVideoEnable(screenShare)") {+            it.setVideoEnable(true, screenSharing)+        }     }      fun flipCamera() {@@ -304,6 +323,14 @@ class SignalCallManager(                 onRemoteVideo(false)                 return             }+            CallManager.CallEvent.REMOTE_SHARING_SCREEN_ENABLE -> {+                signaling.onRemoteScreenShare(true)+                return+            }+            CallManager.CallEvent.REMOTE_SHARING_SCREEN_DISABLE -> {+                signaling.onRemoteScreenShare(false)+                return+            }             else -> Unit         }         val state = when (event) {@@ -329,6 +356,7 @@ class SignalCallManager(      override fun onCallConcluded(remote: Remote?) {         callMediaTypes.clear()+        screenSharing = false         camera?.dispose()         camera = null         localVideoSink.attach(null)
communicate/src/main/java/com/vayunmathur/communicate/data/signal/call/SignalCamera.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/signal/call/SignalCamera.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/signal/call/SignalCamera.ktindex 6577d97338..20facbcbf6 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/signal/call/SignalCamera.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/signal/call/SignalCamera.kt@@ -1,6 +1,7 @@ package com.vayunmathur.communicate.data.signal.call  import android.content.Context+import android.media.projection.MediaProjection import android.util.Log import org.signal.ringrtc.CameraControl import org.webrtc.Camera2Capturer@@ -8,7 +9,9 @@ import org.webrtc.Camera2Enumerator import org.webrtc.CameraVideoCapturer import org.webrtc.CapturerObserver import org.webrtc.EglBase+import org.webrtc.ScreenCapturerAndroid import org.webrtc.SurfaceTextureHelper+import org.webrtc.VideoCapturer import org.webrtc.VideoFrame  /**@@ -30,23 +33,32 @@ class SignalCamera(     private var capturing = false     private var frontFacing = true +    /**+     * RingRTC's sink for captured frames, kept so the capture *source* can be swapped between the camera and+     * the screen without tearing down the call's video track.+     */+    private var observer: CapturerObserver? = null+    private var surfaceHelper: SurfaceTextureHelper? = null+    private var screenCapturer: VideoCapturer? = null+     /** True whenever the device has a usable camera, matching what the offer expects to negotiate. */     override fun hasCapturer(): Boolean = capturer != null      override fun initCapturer(observer: CapturerObserver) {+        this.observer = observer         val capturer = this.capturer ?: return         try {-            capturer.initialize(-                SurfaceTextureHelper.create("SignalCameraThread", eglBase.eglBaseContext),-                appContext,-                observer,-            )+            val helper = SurfaceTextureHelper.create("SignalCameraThread", eglBase.eglBaseContext)+            surfaceHelper = helper+            capturer.initialize(helper, appContext, observer)         } catch (t: Throwable) {             Log.w(TAG, "could not initialize the camera capturer", t)         }     }      override fun setEnabled(enable: Boolean) {+        // While sharing the screen the camera stays off; the screen capturer is the source.+        if (screenCapturer != null) return         val capturer = this.capturer ?: return         try {             if (enable && !capturing) {@@ -61,6 +73,66 @@ class SignalCamera(         }     } +    /**+     * Swap the capture source between the camera and the screen.+     *+     * Screen capture reuses RingRTC's existing [CapturerObserver], so the outgoing video track and the+     * negotiated media stay exactly as they were — only the frames' origin changes. [permission] is the+     * `MediaProjection` consent result and is required to start.+     */+    fun setScreenShare(enabled: Boolean, permission: android.content.Intent?): Boolean {+        val observer = this.observer ?: run {+            Log.w(TAG, "no capturer observer yet; cannot share the screen")+            return false+        }+        return if (enabled) startScreenShare(observer, permission) else stopScreenShare()+    }++    private fun startScreenShare(observer: CapturerObserver, permission: android.content.Intent?): Boolean {+        if (permission == null) return false+        if (screenCapturer != null) return true+        return try {+            // Stop the camera first: one source at a time feeds the track.+            if (capturing) {+                capturer?.stopCapture()+                capturing = false+            }+            val capturer = ScreenCapturerAndroid(+                permission,+                object : MediaProjection.Callback() {+                    override fun onStop() {+                        Log.i(TAG, "screen capture stopped by the system")+                    }+                },+            )+            val helper = SurfaceTextureHelper.create("SignalScreenThread", eglBase.eglBaseContext)+            capturer.initialize(helper, appContext, observer)+            val metrics = appContext.resources.displayMetrics+            capturer.startCapture(metrics.widthPixels, metrics.heightPixels, SCREEN_FPS)+            screenCapturer = capturer+            Log.i(TAG, "sharing the screen at ${metrics.widthPixels}x${metrics.heightPixels}")+            true+        } catch (t: Throwable) {+            Log.w(TAG, "could not start screen capture", t)+            screenCapturer = null+            false+        }+    }++    private fun stopScreenShare(): Boolean {+        val capturer = screenCapturer ?: return true+        return try {+            capturer.stopCapture()+            capturer.dispose()+            screenCapturer = null+            true+        } catch (t: Throwable) {+            Log.w(TAG, "could not stop screen capture", t)+            screenCapturer = null+            false+        }+    }+     override fun flip() {         frontFacing = !frontFacing         try {@@ -73,12 +145,16 @@ class SignalCamera(     override fun setOrientation(orientation: Int?) = Unit      fun dispose() {+        stopScreenShare()         try {             if (capturing) capturer?.stopCapture()             capturer?.dispose()+            surfaceHelper?.dispose()         } catch (_: Throwable) {         }         capturing = false+        observer = null+        surfaceHelper = null     }      override fun onCameraSwitchDone(isFrontCamera: Boolean) {@@ -118,6 +194,9 @@ class SignalCamera(         const val CAPTURE_WIDTH = 640         const val CAPTURE_HEIGHT = 480         const val CAPTURE_FPS = 30++        /** Screen content is mostly static, so a lower rate keeps text legible at the same bitrate. */+        const val SCREEN_FPS = 15     } } 
communicate/src/main/java/com/vayunmathur/communicate/telephony/InAppCallForegroundService.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/telephony/InAppCallForegroundService.kt b/communicate/src/main/java/com/vayunmathur/communicate/telephony/InAppCallForegroundService.ktindex 90a715121e..6609bea491 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/telephony/InAppCallForegroundService.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/telephony/InAppCallForegroundService.kt@@ -67,8 +67,15 @@ class InAppCallForegroundService : Service() {         } else {             buildOngoingCallNotification(state.phase, state.peerName)         }+        // Screen capture is only permitted while a mediaProjection-typed service is in the foreground.+        val types = if (state.screenSharing) {+            ServiceInfo.FOREGROUND_SERVICE_TYPE_PHONE_CALL or+                ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PROJECTION+        } else {+            ServiceInfo.FOREGROUND_SERVICE_TYPE_PHONE_CALL+        }         if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {-            startForeground(NOTIFICATION_ID, notification, ServiceInfo.FOREGROUND_SERVICE_TYPE_PHONE_CALL)+            startForeground(NOTIFICATION_ID, notification, types)         } else {             startForeground(NOTIFICATION_ID, notification)         }
communicate/src/main/java/com/vayunmathur/communicate/ui/call/InAppCallScreen.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/ui/call/InAppCallScreen.kt b/communicate/src/main/java/com/vayunmathur/communicate/ui/call/InAppCallScreen.ktindex e596866340..32ebf19114 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/ui/call/InAppCallScreen.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/ui/call/InAppCallScreen.kt@@ -1,5 +1,9 @@ package com.vayunmathur.communicate.ui.call +import android.app.Activity+import android.media.projection.MediaProjectionManager+import androidx.activity.compose.rememberLauncherForActivityResult+import androidx.activity.result.contract.ActivityResultContracts import androidx.compose.foundation.background import androidx.compose.foundation.gestures.detectTransformGestures import androidx.compose.foundation.layout.Arrangement@@ -33,6 +37,7 @@ import androidx.compose.ui.draw.clip import androidx.compose.ui.geometry.Offset import androidx.compose.ui.graphics.Color import androidx.compose.ui.input.pointer.pointerInput+import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.font.FontWeight@@ -55,6 +60,7 @@ import com.vayunmathur.library.ui.IconDialpad import com.vayunmathur.library.ui.IconFlipCamera import com.vayunmathur.library.ui.IconMic import com.vayunmathur.library.ui.IconMicOff+import com.vayunmathur.library.ui.IconScreenShare import com.vayunmathur.library.ui.IconVideoCamera import com.vayunmathur.library.ui.IconVolumeUp import com.vayunmathur.library.ui.MaterialTheme@@ -82,6 +88,17 @@ fun InAppCallScreen(onClose: () -> Unit) {     val state by InAppCallRegistry.state.collectAsState()     var showKeypad by remember { mutableStateOf(false) } +    // MediaProjection consent must be granted per share; the result Intent is the capture token.+    val screenShareConsent = rememberLauncherForActivityResult(+        ActivityResultContracts.StartActivityForResult(),+    ) { result ->+        val permission = result.data+        if (result.resultCode == Activity.RESULT_OK && permission != null) {+            InAppCallRegistry.setScreenShare(true, permission)+        }+    }+    val context = LocalContext.current+     // A terminal state is held briefly so the outcome is readable, then dismissed.     LaunchedEffect(state.phase) {         when (state.phase) {@@ -129,6 +146,14 @@ fun InAppCallScreen(onClose: () -> Unit) {                         state = state,                         keypadShown = showKeypad,                         onToggleKeypad = { showKeypad = !showKeypad },+                        onToggleScreenShare = {+                            if (state.screenSharing) {+                                InAppCallRegistry.setScreenShare(false, null)+                            } else {+                                val manager = context.getSystemService(MediaProjectionManager::class.java)+                                manager?.createScreenCaptureIntent()?.let(screenShareConsent::launch)+                            }+                        },                     )                 }                 Spacer(Modifier.height(Spacing.xl))@@ -224,6 +249,7 @@ private fun OngoingControls(     state: InAppCallState,     keypadShown: Boolean,     onToggleKeypad: () -> Unit,+    onToggleScreenShare: () -> Unit, ) {     val caps = state.capabilities     Column(horizontalAlignment = Alignment.CenterHorizontally) {@@ -256,13 +282,21 @@ private fun OngoingControls(                     if (state.localVideoEnabled) IconVideoCamera(tint = tint) else IconCameraOff(tint = tint)                 }             }-            if (caps.video && state.localVideoEnabled) {+            // Flipping the camera is meaningless while the source is the screen.+            if (caps.video && state.localVideoEnabled && !state.screenSharing) {                 CallToggle(                     label = stringResource(R.string.call_flip_camera),                     active = false,                     onClick = { InAppCallRegistry.flipCamera() },                 ) { tint -> IconFlipCamera(tint = tint) }             }+            if (caps.screenShare) {+                CallToggle(+                    label = stringResource(R.string.call_screen_share),+                    active = state.screenSharing,+                    onClick = onToggleScreenShare,+                ) { tint -> IconScreenShare(tint = tint) }+            }             if (caps.dtmf) {                 CallToggle(                     label = stringResource(R.string.call_keypad),@@ -398,17 +432,18 @@ private fun CallVideo(showRemote: Boolean, showLocal: Boolean) {                 },                 modifier = Modifier.fillMaxSize(),                 onRelease = { renderer ->-                    controller.attachRenderers(local = null, remote = null)+                    controller.attachRemoteRenderer(null)                     renderer.release()                 },-                update = { renderer -> controller.attachRenderers(local = null, remote = renderer) },+                update = { renderer -> controller.attachRemoteRenderer(renderer) },             )         }         if (showLocal) {             SelfView(                 eglContext = eglContext,                 bounds = DpSize(maxWidth, maxHeight),-                onRenderer = { renderer -> controller.attachRenderers(local = renderer, remote = null) },+                onRenderer = { renderer -> controller.attachLocalRenderer(renderer) },+                onRelease = { controller.attachLocalRenderer(null) },             )         }     }@@ -426,6 +461,7 @@ private fun SelfView(     eglContext: org.webrtc.EglBase.Context,     bounds: DpSize,     onRenderer: (SurfaceViewRenderer) -> Unit,+    onRelease: () -> Unit, ) {     val density = LocalDensity.current     var scale by remember { mutableFloatStateOf(1f) }@@ -474,7 +510,10 @@ private fun SelfView(                 }             },             modifier = Modifier.fillMaxSize(),-            onRelease = { renderer -> renderer.release() },+            onRelease = { renderer ->+                onRelease()+                renderer.release()+            },             update = onRenderer,         )     }
communicate/src/main/res/values/strings.xml
diff --git a/communicate/src/main/res/values/strings.xml b/communicate/src/main/res/values/strings.xmlindex d5d3c62f71..94bc038a46 100644--- a/communicate/src/main/res/values/strings.xml+++ b/communicate/src/main/res/values/strings.xml@@ -118,6 +118,7 @@     <string name="call_state_incoming_generic">Incoming call</string>     <string name="call_video">Video</string>     <string name="call_flip_camera">Flip</string>+    <string name="call_screen_share">Share screen</string>     <string name="contact_create_new">Create new contact</string>     <string name="contact_add_to_existing">Add to existing contact</string>     <string name="deep_link_group_unsupported">Group invite links are not supported yet</string>