Modern Apps git

← Modern-Apps.git

communicate: add video calling, and stop double-releasing video frames

Commit
a77250436e5628186936327c8411417eb10a853e
Author
vayun-mathur <[email protected]>
When
2026-08-23 00:57 UTC (3 months ago)
Parents
2833c8f

Diff

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 a590dcbb6f..b2c7f64d91 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@@ -22,6 +22,10 @@ data class InAppCallState(     val peerId: String = "",     val peerName: String = "",     val isVideo: Boolean = false,+    /** Whether the peer is currently sending video, which is independent of whether we are. */+    val remoteVideoEnabled: Boolean = false,+    /** Whether our own camera is on. */+    val localVideoEnabled: Boolean = false,     val muted: Boolean = false,     val speaker: Boolean = false,     /** When the call became [InAppCallPhase.Active], for the duration readout. 0 until then. */@@ -49,9 +53,25 @@ interface InAppCallController { /** Implemented by the Telecom `Connection` so a line's manager can drive the system call surface. */ interface InAppCallConnectionBridge {     fun onCallActive()+     fun onCallEnded() } +/**+ * Video capability, separate from [InAppCallController] because not every line has it and the shared screen+ * should only offer the control when something can act on it.+ */+interface InAppCallVideoController {+    fun setVideoEnabled(enabled: Boolean)++    fun flipCamera()++    /** 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?)+}+ /**  * The one place that knows whether a call is up, regardless of line.  *@@ -68,6 +88,10 @@ object InAppCallRegistry {     @Volatile     private var controller: InAppCallController? = null +    /** Set only by lines that can carry video, so the UI can offer the control. */+    @Volatile+    var videoController: InAppCallVideoController? = null+     /** Set by the Telecom ConnectionService so state changes can be reflected into the system UI. */     @Volatile     var connection: InAppCallConnectionBridge? = null@@ -129,11 +153,34 @@ object InAppCallRegistry {         _state.value = _state.value.copy(speaker = on)     } +    fun onRemoteVideo(enabled: Boolean) {+        if (_state.value.phase == InAppCallPhase.Idle) return+        android.util.Log.i(TAG, "remote video enabled=$enabled")+        _state.value = _state.value.copy(remoteVideoEnabled = enabled)+    }++    fun onLocalVideo(enabled: Boolean) {+        if (_state.value.phase == InAppCallPhase.Idle) return+        _state.value = _state.value.copy(localVideoEnabled = enabled, isVideo = _state.value.isVideo || enabled)+    }++    /** Turn our own camera on or off mid-call. */+    fun toggleVideo() {+        val next = !_state.value.localVideoEnabled+        videoController?.setVideoEnabled(next)+        onLocalVideo(next)+    }++    fun flipCamera() {+        videoController?.flipCamera()+    }+     /** Called by the UI once a terminal state has been shown, returning to Idle. */     fun clearEnded() {         if (_state.value.phase == InAppCallPhase.Ended) {             _state.value = InAppCallState()             controller = null+            videoController = null             connection = null         }     }
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 e444ce9bf4..088f06edfd 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@@ -8,6 +8,7 @@ import com.vayunmathur.communicate.data.CommunicateLine import com.vayunmathur.communicate.data.call.InAppCallController import com.vayunmathur.communicate.data.call.InAppCallPhase import com.vayunmathur.communicate.data.call.InAppCallRegistry+import com.vayunmathur.communicate.data.call.InAppCallVideoController import com.vayunmathur.communicate.data.signal.call.SignalCallManager import com.vayunmathur.communicate.data.signal.call.SignalCallMessage import com.vayunmathur.communicate.data.signal.call.toContent@@ -1263,6 +1264,10 @@ object SignalClient {                 override suspend fun iceServers(): List<PeerConnection.IceServer> =                     SignalCallingApi.fetchIceServers(basicAuthHeader(), signalTls()) +                override fun onRemoteVideo(enabled: Boolean) {+                    InAppCallRegistry.onRemoteVideo(enabled)+                }+                 override fun onCallStateChanged(                     aci: String,                     callId: Long,@@ -1392,6 +1397,7 @@ object SignalClient {         val current = InAppCallRegistry.state.value         if (current.phase == InAppCallPhase.Idle && state != SignalCallManager.CallState.Ended) {             InAppCallRegistry.bind(CommunicateLine.Signal, signalCallController)+            InAppCallRegistry.videoController = signalVideoController             InAppCallRegistry.onCallStarting(                 line = CommunicateLine.Signal,                 peerId = aci,@@ -1418,6 +1424,24 @@ object SignalClient {         }     } +    /** Video capability for the shared call screen. */+    private val signalVideoController = object : InAppCallVideoController {+        override fun setVideoEnabled(enabled: Boolean) {+            callManager?.setVideoEnabled(enabled)+        }++        override fun flipCamera() {+            callManager?.flipCamera()+        }++        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)+        }+    }+     /** Bridges the shared call UI and the system call surface onto RingRTC. */     private val signalCallController = object : InAppCallController {         override fun answer() {
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 4a37dd2b17..058ca306c0 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@@ -58,6 +58,9 @@ class SignalCallManager(         /** The identity keys RingRTC binds the SRTP key derivation to. */         suspend fun identityKeys(aci: String): IdentityKeyPairBytes? +        /** The peer turned their camera on or off. */+        fun onRemoteVideo(enabled: Boolean)+         /**          * TURN/STUN relays for the call. Without them only host candidates are available, so a call fails          * behind NAT.@@ -127,6 +130,9 @@ class SignalCallManager(      fun hangup(): Boolean = withManager("hangup") { it.hangup() } +    /** The EGL context renderers must share with the decoder, so frames can be drawn. */+    fun eglContext(): EglBase.Context? = eglBase?.eglBaseContext+     /** Turn our outgoing video on or off mid-call. */     fun setVideoEnabled(enabled: Boolean): Boolean = withManager("setVideoEnable") {         camera?.setEnabled(enabled)@@ -288,6 +294,18 @@ class SignalCallManager(     override fun onCallEvent(remote: Remote?, event: CallManager.CallEvent?) {         val aci = (remote as? SignalRemote)?.aci ?: return         Log.i(TAG, "call event for $aci: $event")+        // Media-state events change what the UI renders without changing the call phase.+        when (event) {+            CallManager.CallEvent.REMOTE_VIDEO_ENABLE -> {+                onRemoteVideo(true)+                return+            }+            CallManager.CallEvent.REMOTE_VIDEO_DISABLE -> {+                onRemoteVideo(false)+                return+            }+            else -> Unit+        }         val state = when (event) {             // Either side accepting is what makes a call active; missing these leaves the UI on "dialing"             // while media is already flowing.@@ -305,6 +323,10 @@ class SignalCallManager(         signaling.onCallStateChanged(aci, 0, state, false)     } +    private fun onRemoteVideo(enabled: Boolean) {+        signaling.onRemoteVideo(enabled)+    }+     override fun onCallConcluded(remote: Remote?) {         callMediaTypes.clear()         camera?.dispose()
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 aa5adf3f83..6577d97338 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@@ -126,6 +126,11 @@ class SignalCamera(  *  * RingRTC needs a sink at `proceed()` time, but the UI that renders video does not exist until later (and  * not at all for an audio call), so the destination is swappable.+ *+ * Note it must **not** release frames: the producer (`SurfaceTextureHelper`) releases its own reference+ * once `onFrame` returns, so releasing here drops the refcount below zero and crashes the decoder thread+ * with "release() called on an object with refcount < 1". A sink that wants to keep a frame calls+ * `retain()`; a sink that wants to drop one simply returns.  */ class SwappableVideoSink : org.webrtc.VideoSink {     @Volatile@@ -136,11 +141,6 @@ class SwappableVideoSink : org.webrtc.VideoSink {     }      override fun onFrame(frame: VideoFrame?) {-        val target = delegate-        if (target == null) {-            frame?.release()-        } else {-            target.onFrame(frame)-        }+        delegate?.onFrame(frame)     } }
communicate/src/main/java/com/vayunmathur/communicate/data/signal/call/SignalRingRtcSupport.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/signal/call/SignalRingRtcSupport.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/signal/call/SignalRingRtcSupport.ktindex 808e6f384b..6d3c52633f 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/signal/call/SignalRingRtcSupport.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/signal/call/SignalRingRtcSupport.kt@@ -48,8 +48,6 @@ object NoCameraControl : CameraControl {      override fun setOrientation(orientation: Int?) = Unit }--/** Field trials RingRTC expects; `initialize` merges its own defaults over these. */ internal fun ringRtcFieldTrials(): Map<String, String> = emptyMap()  internal fun CallManager.CallMediaType.isVideo(): Boolean =
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 5fbcbef5c2..be297c736d 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@@ -22,20 +22,26 @@ import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp+import androidx.compose.ui.viewinterop.AndroidView import com.vayunmathur.communicate.R import com.vayunmathur.communicate.data.CommunicateLine import com.vayunmathur.communicate.data.call.InAppCallPhase import com.vayunmathur.communicate.data.call.InAppCallRegistry import com.vayunmathur.library.ui.FilledIconButton import com.vayunmathur.library.ui.IconCall+import com.vayunmathur.library.ui.IconCameraOff import com.vayunmathur.library.ui.IconClose+import com.vayunmathur.library.ui.IconFlipCamera import com.vayunmathur.library.ui.IconMic import com.vayunmathur.library.ui.IconMicOff+import com.vayunmathur.library.ui.IconVideoCamera import com.vayunmathur.library.ui.IconVolumeUp import com.vayunmathur.library.ui.MaterialTheme import com.vayunmathur.library.ui.Surface import com.vayunmathur.library.ui.Text import kotlinx.coroutines.delay+import org.webrtc.RendererCommon+import org.webrtc.SurfaceViewRenderer  /**  * Full-screen UI for an in-app WhatsApp or Signal call, driven by [InAppCallRegistry].@@ -59,37 +65,100 @@ fun InAppCallScreen(onClose: () -> Unit) {     }      Surface(modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.surface) {-        Column(-            modifier = Modifier-                .fillMaxSize()-                .padding(24.dp),-            horizontalAlignment = Alignment.CenterHorizontally,-        ) {-            Spacer(Modifier.height(48.dp))-            Text(-                state.peerName,-                style = MaterialTheme.typography.headlineSmall,-                fontWeight = FontWeight.SemiBold,-            )-            Spacer(Modifier.height(8.dp))-            Text(-                phaseLabel(state.phase, state.line, state.endReason),-                style = MaterialTheme.typography.bodyMedium,-                color = MaterialTheme.colorScheme.onSurfaceVariant,-            )-            if (state.phase == InAppCallPhase.Active && state.connectedAtMs > 0L) {-                Spacer(Modifier.height(4.dp))-                CallDuration(state.connectedAtMs)+        Box(modifier = Modifier.fillMaxSize()) {+            // Video fills the screen behind the controls when either side has a camera on.+            if (state.remoteVideoEnabled || state.localVideoEnabled) {+                CallVideo(+                    showRemote = state.remoteVideoEnabled,+                    showLocal = state.localVideoEnabled,+                )             }+            Column(+                modifier = Modifier+                    .fillMaxSize()+                    .padding(24.dp),+                horizontalAlignment = Alignment.CenterHorizontally,+            ) {+                Spacer(Modifier.height(48.dp))+                Text(+                    state.peerName,+                    style = MaterialTheme.typography.headlineSmall,+                    fontWeight = FontWeight.SemiBold,+                )+                Spacer(Modifier.height(8.dp))+                Text(+                    phaseLabel(state.phase, state.line, state.endReason),+                    style = MaterialTheme.typography.bodyMedium,+                    color = MaterialTheme.colorScheme.onSurfaceVariant,+                )+                if (state.phase == InAppCallPhase.Active && state.connectedAtMs > 0L) {+                    Spacer(Modifier.height(4.dp))+                    CallDuration(state.connectedAtMs)+                } -            Spacer(Modifier.weight(1f))+                Spacer(Modifier.weight(1f)) -            when (state.phase) {-                InAppCallPhase.Incoming -> IncomingControls()-                InAppCallPhase.Ended -> Unit-                else -> InCallControls(muted = state.muted, speaker = state.speaker)+                when (state.phase) {+                    InAppCallPhase.Incoming -> IncomingControls()+                    InAppCallPhase.Ended -> Unit+                    else -> InCallControls(+                        muted = state.muted,+                        video = state.localVideoEnabled,+                        canVideo = InAppCallRegistry.videoController != null,+                    )+                }+                Spacer(Modifier.height(32.dp))             }-            Spacer(Modifier.height(32.dp))+        }+    }+}++/**+ * Renders the call's video.+ *+ * The renderers share the decoder's EGL context and are attached to the line's sinks for as long as they+ * are composed, then detached — a renderer that outlives its composition would be handed frames after+ * release.+ */+@Composable+private fun CallVideo(showRemote: Boolean, showLocal: Boolean) {+    val controller = InAppCallRegistry.videoController ?: return+    val eglContext = remember(controller) { controller.eglContext() } ?: return++    Box(modifier = Modifier.fillMaxSize()) {+        if (showRemote) {+            AndroidView(+                factory = { context ->+                    SurfaceViewRenderer(context).apply {+                        init(eglContext, null)+                        setScalingType(RendererCommon.ScalingType.SCALE_ASPECT_FILL)+                        setEnableHardwareScaler(true)+                    }+                },+                modifier = Modifier.fillMaxSize(),+                onRelease = { renderer ->+                    controller.attachRenderers(local = null, remote = null)+                    renderer.release()+                },+                update = { renderer -> controller.attachRenderers(local = null, remote = renderer) },+            )+        }+        if (showLocal) {+            AndroidView(+                factory = { context ->+                    SurfaceViewRenderer(context).apply {+                        init(eglContext, null)+                        setScalingType(RendererCommon.ScalingType.SCALE_ASPECT_FILL)+                        setMirror(true)+                    }+                },+                modifier = Modifier+                    .align(Alignment.TopEnd)+                    .padding(16.dp)+                    .size(width = 108.dp, height = 144.dp),+                onRelease = { renderer -> renderer.release() },+                update = { renderer -> controller.attachRenderers(local = renderer, remote = null) },+            )         }     } }@@ -125,7 +194,7 @@ private fun IncomingControls() { }  @Composable-private fun InCallControls(muted: Boolean, speaker: Boolean) {+private fun InCallControls(muted: Boolean, video: Boolean, canVideo: Boolean) {     Row(         modifier = Modifier.fillMaxWidth(),         horizontalArrangement = Arrangement.SpaceEvenly,@@ -134,6 +203,14 @@ private fun InCallControls(muted: Boolean, speaker: Boolean) {             if (muted) IconMicOff() else IconMic()         }         CallActionButton(onClick = { InAppCallRegistry.toggleSpeaker() }) { IconVolumeUp() }+        if (canVideo) {+            CallActionButton(onClick = { InAppCallRegistry.toggleVideo() }) {+                if (video) IconCameraOff() else IconVideoCamera()+            }+            if (video) {+                CallActionButton(onClick = { InAppCallRegistry.flipCamera() }) { IconFlipCamera() }+            }+        }         CallActionButton(onClick = { InAppCallRegistry.hangup() }) { IconClose() }     } }