Modern Apps git

← Modern-Apps.git

communicate: Signal - negotiate video m-lines so calls can connect

Commit
b7e9539913a3e62beb4fae87b00d30b6259e4e98
Author
vayun-mathur <[email protected]>
When
2026-08-23 00:14 UTC (3 months ago)
Parents
a25ca62

Diff

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 7e5ae74688..4d185d34be 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@@ -1299,6 +1299,18 @@ object SignalClient {             cm.hasOffer() -> {                 val offer = cm.offer                 val isVideo = offer.type == SignalServiceProtos.CallMessage.Offer.Type.OFFER_VIDEO_CALL+                // Logged in full so an inbound offer from official Signal can be compared against what we+                // send: our own offers are accepted by the server but never ring, and our side reports+                // success, so the difference has to be in the message itself.+                val ageSec = ((env.serverTimestamp - env.timestamp).coerceAtLeast(0L)) / 1000+                Log.i(+                    TAG,+                    "inbound Offer callId=${offer.id} from $senderAci:$senderDeviceId " ++                        "opaque=${offer.opaque.size()}B type=${offer.type} " ++                        "hasDestinationDeviceId=${cm.hasDestinationDeviceId()} " ++                        "destinationDeviceId=${cm.destinationDeviceId} ageSec=$ageSec " ++                        "urgent=${env.urgent}",+                )                 // Recorded before RingRTC reports Ringing, which is how the shared registry tells an                 // inbound call from an outbound one, and what `answer()` needs.                 pendingIncomingCallAci = senderAci@@ -1315,8 +1327,6 @@ object SignalClient {                 )                 // Hand the call to the system so it owns ringing, audio focus and routing.                 appContext?.let { ctx -> InAppCallTelecom.addIncoming(ctx, senderAci) }-                // Age matters: RingRTC drops offers that sat in the queue too long to still be ringing.-                val ageSec = ((env.serverTimestamp - env.timestamp).coerceAtLeast(0L)) / 1000                 manager.receivedOffer(                     callId = offer.id,                     senderAci = senderAci,
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 6cae4e5468..a71f55c5f6 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@@ -77,6 +77,16 @@ class SignalCallManager(     private var callManager: CallManager? = null     private var eglBase: EglBase? = null +    /**+     * Created per call. Present even for audio, because Signal's offer always carries a video m-line and an+     * answer must match it; only [SignalCamera.setEnabled] differs between audio and video.+     */+    private var camera: SignalCamera? = null++    /** Exposed so the call UI can attach renderers once it exists. */+    val localVideoSink = SwappableVideoSink()+    val remoteVideoSink = SwappableVideoSink()+     /** Media type per call, so an answer knows whether video was offered. */     private val callMediaTypes = java.util.concurrent.ConcurrentHashMap<Long, CallManager.CallMediaType>() @@ -117,6 +127,16 @@ class SignalCallManager(      fun hangup(): Boolean = withManager("hangup") { it.hangup() } +    /** Turn our outgoing video on or off mid-call. */+    fun setVideoEnabled(enabled: Boolean): Boolean = withManager("setVideoEnable") {+        camera?.setEnabled(enabled)+        it.setVideoEnable(enabled, false)+    }++    fun flipCamera() {+        camera?.flip()+    }+     fun setAudioEnabled(enabled: Boolean): Boolean =         withManager("setAudioEnable") { it.setAudioEnable(enabled) } @@ -230,6 +250,7 @@ class SignalCallManager(         if (iceServers.isEmpty()) {             Log.w(TAG, "proceeding with no ICE servers; expect connection failure unless both ends are local")         }+        val cameraControl = camera ?: SignalCamera(appContext, egl).also { camera = it }         try {             manager.proceed(                 CallId(callId),@@ -237,9 +258,9 @@ class SignalCallManager(                 egl,                 org.signal.ringrtc.AudioConfig(),                 org.signal.ringrtc.VideoConfig(),-                NoVideoSink,-                NoVideoSink,-                NoCameraControl,+                localVideoSink,+                remoteVideoSink,+                cameraControl,                 iceServers,                 false,                 CallManager.DataMode.NORMAL,@@ -248,7 +269,11 @@ class SignalCallManager(                 mediaType.isVideo(),                 null,             )-            Log.i(TAG, "proceed ok for call $callId with ${iceServers.size} ICE servers")+            Log.i(+                TAG,+                "proceed ok for call $callId with ${iceServers.size} ICE servers, " ++                    "camera=${cameraControl.hasCapturer()} video=${mediaType.isVideo()}",+            )         } catch (t: Throwable) {             Log.w(TAG, "proceed failed for call $callId", t)         }@@ -273,6 +298,10 @@ class SignalCallManager(      override fun onCallConcluded(remote: Remote?) {         callMediaTypes.clear()+        camera?.dispose()+        camera = null+        localVideoSink.attach(null)+        remoteVideoSink.attach(null)     }      override fun onNetworkRouteChanged(remote: Remote?, networkRoute: NetworkRoute?) = Unit@@ -489,13 +518,6 @@ class SignalCallManager(         }     } -    /** Media is audio-only for now, so nothing renders video frames. */-    private object NoVideoSink : VideoSink {-        override fun onFrame(frame: org.webrtc.VideoFrame?) {-            frame?.release()-        }-    }-     private companion object {         const val TAG = "SignalCallManager"         const val AUDIO_LEVEL_INTERVAL_MS = 500
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.ktnew file mode 100644index 0000000000..aa5adf3f83--- /dev/null+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/signal/call/SignalCamera.kt@@ -0,0 +1,146 @@+package com.vayunmathur.communicate.data.signal.call++import android.content.Context+import android.util.Log+import org.signal.ringrtc.CameraControl+import org.webrtc.Camera2Capturer+import org.webrtc.Camera2Enumerator+import org.webrtc.CameraVideoCapturer+import org.webrtc.CapturerObserver+import org.webrtc.EglBase+import org.webrtc.SurfaceTextureHelper+import org.webrtc.VideoFrame++/**+ * Camera plumbing for calls.+ *+ * Present even on an audio call, and that is the point: Signal's offer always carries a video m-line, and+ * WebRTC requires an answer's m-lines to match the offer's in number and order. With no capturer RingRTC+ * builds no video transceiver, the answer comes back audio-only, and the peer connection rejects it with+ * "The order of m-lines in answer doesn't match order in offer" - so every inbound call failed instantly.+ *+ * The capture device is therefore created for every call but only *started* when video is enabled.+ */+class SignalCamera(+    private val appContext: Context,+    private val eglBase: EglBase,+) : CameraControl, CameraVideoCapturer.CameraSwitchHandler {++    private val capturer: CameraVideoCapturer? = createCapturer()+    private var capturing = false+    private var frontFacing = true++    /** 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) {+        val capturer = this.capturer ?: return+        try {+            capturer.initialize(+                SurfaceTextureHelper.create("SignalCameraThread", eglBase.eglBaseContext),+                appContext,+                observer,+            )+        } catch (t: Throwable) {+            Log.w(TAG, "could not initialize the camera capturer", t)+        }+    }++    override fun setEnabled(enable: Boolean) {+        val capturer = this.capturer ?: return+        try {+            if (enable && !capturing) {+                capturer.startCapture(CAPTURE_WIDTH, CAPTURE_HEIGHT, CAPTURE_FPS)+                capturing = true+            } else if (!enable && capturing) {+                capturer.stopCapture()+                capturing = false+            }+        } catch (t: Throwable) {+            Log.w(TAG, "could not ${if (enable) "start" else "stop"} video capture", t)+        }+    }++    override fun flip() {+        frontFacing = !frontFacing+        try {+            capturer?.switchCamera(this)+        } catch (t: Throwable) {+            Log.w(TAG, "could not switch camera", t)+        }+    }++    override fun setOrientation(orientation: Int?) = Unit++    fun dispose() {+        try {+            if (capturing) capturer?.stopCapture()+            capturer?.dispose()+        } catch (_: Throwable) {+        }+        capturing = false+    }++    override fun onCameraSwitchDone(isFrontCamera: Boolean) {+        frontFacing = isFrontCamera+    }++    override fun onCameraSwitchError(error: String?) {+        Log.w(TAG, "camera switch failed: $error")+    }++    private fun createCapturer(): CameraVideoCapturer? {+        if (!Camera2Enumerator.isSupported(appContext)) {+            Log.w(TAG, "Camera2 unsupported; calls will negotiate without video")+            return null+        }+        val enumerator = Camera2Enumerator(appContext)+        val names = try { enumerator.deviceNames } catch (t: Throwable) {+            Log.w(TAG, "could not enumerate cameras", t)+            return null+        }+        // Front first, since that is what a video call would use; any camera is enough to negotiate.+        val preferred = names.firstOrNull { enumerator.isFrontFacing(it) } ?: names.firstOrNull()+        if (preferred == null) {+            Log.w(TAG, "no camera on this device; calls will negotiate without video")+            return null+        }+        return try {+            Camera2Capturer(appContext, preferred, null)+        } catch (t: Throwable) {+            Log.w(TAG, "could not create a camera capturer for $preferred", t)+            null+        }+    }++    private companion object {+        const val TAG = "SignalCamera"+        const val CAPTURE_WIDTH = 640+        const val CAPTURE_HEIGHT = 480+        const val CAPTURE_FPS = 30+    }+}++/**+ * Forwards frames to a renderer when one is attached, and drops them otherwise.+ *+ * 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.+ */+class SwappableVideoSink : org.webrtc.VideoSink {+    @Volatile+    private var delegate: org.webrtc.VideoSink? = null++    fun attach(sink: org.webrtc.VideoSink?) {+        delegate = sink+    }++    override fun onFrame(frame: VideoFrame?) {+        val target = delegate+        if (target == null) {+            frame?.release()+        } else {+            target.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 25fac7e4bb..808e6f384b 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@@ -34,10 +34,8 @@ class SignalRingRtcLogger : RingRtcLog.Logger { }  /**- * Camera control for audio-only calling: reports no capturer so RingRTC never tries to drive one.- *- * Video calls need a real implementation backed by `Camera2Enumerator`; until then an outgoing video- * call would negotiate video and then send nothing.+ * Camera control for a device with no usable camera. Reports no capturer, which makes RingRTC negotiate+ * without video — only safe when the peer's offer also has no video m-line, so [SignalCamera] is preferred.  */ object NoCameraControl : CameraControl {     override fun hasCapturer(): Boolean = false
communicate/src/main/java/com/vayunmathur/communicate/data/signal/transport/SignalKeysApi.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/signal/transport/SignalKeysApi.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/signal/transport/SignalKeysApi.ktindex acf37027da..bc2c3f6e84 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/signal/transport/SignalKeysApi.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/signal/transport/SignalKeysApi.kt@@ -43,13 +43,21 @@ object SignalKeysApi {      *      * @throws UnregisteredUserException on 404.      */+    /**+     * Fetch pre-key bundles for [aci].+     *+     * [allDevices] uses the `*` specifier, which is what you want for a peer — but note the server does not+     * return the **requesting** device in a `*` lookup, so checking our own keys must ask for the explicit+     * device id instead.+     */     suspend fun fetchPreKeys(         aci: String,         deviceId: Int,         authHeader: String,         sslSocketFactory: SSLSocketFactory?,+        allDevices: Boolean = true,     ): List<DeviceBundle> {-        val specifier = if (deviceId == 1) "*" else deviceId.toString()+        val specifier = if (allDevices && deviceId == 1) "*" else deviceId.toString()         val resp = NetworkClient.execute(             "https://chat.signal.org/v2/keys/$aci/$specifier",             method = "GET",