communicate: Signal group calling via the RingRTC SFU client
- Commit
73dc252d6d665c6fa8a6a7ad67c86843fcf8f770- Author
- vayun-mathur <[email protected]>
- When
- 2026-08-23 05:19 UTC (3 months ago)
- Parents
a52be62
Diff
communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateRepository.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateRepository.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateRepository.ktindex 52e8b502ac..6b5f727598 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateRepository.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateRepository.kt@@ -1394,6 +1394,10 @@ object CommunicateRepository { if (target.isBlank()) false else { whatsAppPlaceCall(target, video); true } } CommunicateLine.Signal -> withContext(Dispatchers.IO) {+ // A group call goes to the SFU rather than to a single peer.+ if (remoteId != null && com.vayunmathur.communicate.data.signal.SignalProtocol.isGroupConversation(remoteId)) {+ return@withContext SignalClient.get(context).placeGroupCall(remoteId)+ } val target = remoteId?.takeIf { it.isNotBlank() } ?: toSignalRecipient(context, address) if (target.isBlank()) { false@@ -1422,6 +1426,10 @@ object CommunicateRepository { else -> false } + /** Only Signal has group calling; it routes through the SFU rather than to individual peers. */+ fun canPlaceGroupCall(line: CommunicateLine): Boolean =+ line == CommunicateLine.Signal && com.vayunmathur.communicate.data.signal.SignalFeature.enabled+ suspend fun createSignalGroup( context: Context, subject: String,
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 ede272195c..711311b3f8 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@@ -11,6 +11,7 @@ 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.SignalGroupCallManager import com.vayunmathur.communicate.data.signal.call.SignalCallMessage import com.vayunmathur.communicate.data.signal.call.toContent import com.vayunmathur.communicate.data.signal.call.toRingRtc@@ -18,7 +19,6 @@ import com.vayunmathur.communicate.data.signal.transport.SignalAttachmentUpload import com.vayunmathur.communicate.data.signal.transport.SignalCallingApi import com.vayunmathur.communicate.data.signal.transport.SignalGroupsApi import com.vayunmathur.communicate.data.signal.transport.SignalKeysApi-import org.signal.storageservice.storage.protos.groups.GroupChange import com.vayunmathur.communicate.data.signal.transport.SignalPayload import com.vayunmathur.communicate.data.signal.transport.SignalSocket import com.vayunmathur.communicate.data.signal.transport.SignalTrust@@ -28,6 +28,8 @@ import org.signal.libsignal.protocol.IdentityKey import org.signal.libsignal.protocol.UntrustedIdentityException import org.signal.libsignal.protocol.message.DecryptionErrorMessage import org.signal.libsignal.protocol.message.PlaintextContent+import org.signal.ringrtc.CallManager+import org.signal.storageservice.storage.protos.groups.GroupChange import org.webrtc.PeerConnection import com.vayunmathur.library.network.NetworkClient import kotlinx.coroutines.CoroutineScope@@ -2121,6 +2123,111 @@ object SignalClient { } } + /**+ * Group calling, created on demand. Shares the 1:1 manager's RingRTC instance and EGL context โ RingRTC+ * keeps one factory for all group calls, so a second instance would fight it for the audio device.+ */+ private val groupCallManager: SignalGroupCallManager? by lazy {+ val manager = callManager ?: return@lazy null+ val egl = manager.eglBaseForGroupCalls() ?: return@lazy null+ val ctx = appContext ?: return@lazy null+ SignalGroupCallManager(+ appContext = ctx,+ callManager = manager.ringRtcCallManager() ?: return@lazy null,+ eglBase = egl,+ signaling = object : SignalGroupCallManager.Signaling {+ override suspend fun membershipProof(groupId: ByteArray): ByteArray? =+ groupAuthorization(groupId)?.let { SignalGroupsApi.fetchMembershipProof(it, signalTls()) }++ override suspend fun groupMembers(groupId: ByteArray): List<Pair<java.util.UUID, ByteArray>> {+ val conversation = conversationForGroupId(groupId) ?: return emptyList()+ val masterKey = conversation.groupMasterKey ?: return emptyList()+ val secretParams = org.signal.libsignal.zkgroup.groups.GroupSecretParams.deriveFromMasterKey(+ org.signal.libsignal.zkgroup.groups.GroupMasterKey(masterKey),+ )+ val acis = conversation.participants.split(",")+ .map { it.trim() }+ .filter { it.isNotEmpty() }+ return SignalGroupsApi.groupMemberInfo(secretParams, acis)+ }++ override fun onGroupCallStateChanged(groupId: ByteArray, joined: Boolean, participants: Int) {+ scope.launch {+ val conversationId = SignalProtocol.groupConversationId(groupId)+ InAppCallRegistry.onPhase(+ if (joined) InAppCallPhase.Active else InAppCallPhase.Connecting,+ )+ Log.i(TAG, "group call $conversationId joined=$joined participants=$participants")+ }+ }++ override fun onGroupCallEnded(groupId: ByteArray, reason: CallManager.CallEndReason?) {+ scope.launch { InAppCallRegistry.onEnded(reason?.toString()) }+ }+ },+ )+ }++ /**+ * Start or join the group call for [conversationId].+ *+ * Needs the group's membership, which is why it refreshes first: RingRTC cannot identify participants+ * without every member's ACI ciphertext.+ */+ suspend fun placeGroupCall(conversationId: String): Boolean {+ if (!SignalProtocol.isGroupConversation(conversationId)) return false+ val manager = groupCallManager ?: run {+ Log.w(TAG, "RingRTC unavailable, cannot place a group call")+ return false+ }+ val conversation = try { db?.conversationDao()?.getConversation(conversationId) } catch (_: Exception) { null }+ val masterKey = conversation?.groupMasterKey ?: run {+ Log.w(TAG, "no master key for $conversationId, cannot place a group call")+ return false+ }+ // Membership must be current or participants cannot be matched to people.+ refreshGroup(conversationId)+ val groupIdentifier = SignalGroups.groupIdentifierBytes(masterKey) ?: return false++ InAppCallRegistry.bind(CommunicateLine.Signal, signalCallController, CallCapabilities.AudioAndVideo)+ InAppCallRegistry.onCallStarting(+ line = CommunicateLine.Signal,+ peerId = conversationId,+ peerName = conversation.name ?: conversationId,+ isVideo = false,+ incoming = false,+ capabilities = CallCapabilities.AudioAndVideo,+ )+ if (!manager.connect(groupIdentifier)) {+ InAppCallRegistry.onEnded("could not start the group call")+ return false+ }+ manager.join()+ appContext?.let { ctx -> InAppCallTelecom.addOutgoing(ctx, conversationId) }+ return true+ }++ /** The group authorization a calling request needs, derived from the group behind [groupId]. */+ private suspend fun groupAuthorization(groupId: ByteArray): String? {+ val auth = authData ?: return null+ val conversation = conversationForGroupId(groupId) ?: return null+ val masterKey = conversation.groupMasterKey ?: return null+ val secretParams = org.signal.libsignal.zkgroup.groups.GroupSecretParams.deriveFromMasterKey(+ org.signal.libsignal.zkgroup.groups.GroupMasterKey(masterKey),+ )+ val credential = SignalGroupsApi+ .fetchCredentials(basicAuthHeader(), signalTls())+ .minByOrNull { kotlin.math.abs(it.redemptionTimeSeconds - System.currentTimeMillis() / 1000) }+ ?: return null+ return SignalGroupsApi.authorizationFor(auth, secretParams, credential)+ }++ private suspend fun conversationForGroupId(groupId: ByteArray) = try {+ db?.conversationDao()?.getConversation(SignalProtocol.groupConversationId(groupId))+ } catch (_: Exception) {+ null+ }+ /** * Record a group we received a message from, so we can reply to it. *
communicate/src/main/java/com/vayunmathur/communicate/data/signal/SignalProtocol.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/signal/SignalProtocol.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/signal/SignalProtocol.ktindex 353b42d502..05922ff4d6 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/signal/SignalProtocol.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/signal/SignalProtocol.kt@@ -339,6 +339,10 @@ object SignalProtocol { fun isGroupConversation(conversationId: String): Boolean = conversationId.startsWith(GROUP_PREFIX) + /** The conversation id for a raw 32-byte group identifier, the inverse of what calling hands back. */+ fun groupConversationId(groupIdentifier: ByteArray): String =+ GROUP_PREFIX + groupIdentifier.joinToString("") { "%02x".format(it) }+ /** The raw 32-byte group identifier for a `group:<hex>` conversation id, or null. */ fun groupIdentifierOf(conversationId: String): ByteArray? { if (!isGroupConversation(conversationId)) return null
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 cc0dd1c0eb..bcc8022dca 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@@ -136,6 +136,12 @@ class SignalCallManager( fun hangup(): Boolean = withManager("hangup") { it.hangup() } + /** The EGL context group calls must share, so both call types use one GL thread. */+ fun eglBaseForGroupCalls(): EglBase? = eglBase++ /** RingRTC keeps one factory per CallManager, so group calls must reuse this instance. */+ fun ringRtcCallManager(): CallManager? = callManager+ /** The EGL context renderers must share with the decoder, so frames can be drawn. */ fun eglContext(): EglBase.Context? = eglBase?.eglBaseContext
communicate/src/main/java/com/vayunmathur/communicate/data/signal/call/SignalGroupCallManager.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/signal/call/SignalGroupCallManager.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/signal/call/SignalGroupCallManager.ktnew file mode 100644index 0000000000..f0753fe56b--- /dev/null+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/signal/call/SignalGroupCallManager.kt@@ -0,0 +1,229 @@+package com.vayunmathur.communicate.data.signal.call++import android.content.Context+import android.util.Log+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.launch+import org.signal.ringrtc.CallManager+import org.signal.ringrtc.CallSummary+import org.signal.ringrtc.GroupCall+import org.webrtc.EglBase+import java.util.UUID++/**+ * A Signal group call, via RingRTC's SFU client.+ *+ * Unlike a 1:1 call there is no offer/answer over the chat channel: everyone connects to Signal's calling+ * server, and the group's identity is proved with a short-lived membership token rather than by naming the+ * participants. The SFU never learns who is in the group โ RingRTC matches SFU-reported participants back to+ * people using each member's ACI paired with its ciphertext.+ *+ * RingRTC asks for the proof and the member list rather than being given them up front+ * ([GroupCall.Observer.requestMembershipProof] / [requestGroupMembers]), because both expire.+ */+class SignalGroupCallManager(+ private val appContext: Context,+ private val callManager: CallManager,+ private val eglBase: EglBase,+ private val signaling: Signaling,+) : GroupCall.Observer {++ /** What the group call needs from the app, and what it reports back. */+ interface Signaling {+ /** A fresh membership proof for [groupId], or null if one cannot be obtained. */+ suspend fun membershipProof(groupId: ByteArray): ByteArray?++ /** The group's members, as ACI/ciphertext pairs. */+ suspend fun groupMembers(groupId: ByteArray): List<Pair<UUID, ByteArray>>++ fun onGroupCallStateChanged(groupId: ByteArray, joined: Boolean, participants: Int)++ fun onGroupCallEnded(groupId: ByteArray, reason: CallManager.CallEndReason?)+ }++ private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)++ private var groupCall: GroupCall? = null+ private var groupId: ByteArray? = null++ val localVideoSink = SwappableVideoSink()++ /** True while a group call object exists, whether or not we have joined the media session. */+ val isActive: Boolean get() = groupCall != null++ /**+ * Create and connect a group call. [join] happens separately so the UI can show who is already on the call+ * before committing to being seen and heard.+ */+ fun connect(groupIdentifier: ByteArray): Boolean {+ if (groupCall != null) {+ Log.w(TAG, "a group call is already active")+ return false+ }+ return try {+ val call = callManager.createGroupCall(+ groupIdentifier,+ SFU_URL,+ // No extra HKDF info: the group's own key material is the whole input.+ ByteArray(0),+ AUDIO_LEVEL_INTERVAL_MS,+ null,+ org.signal.ringrtc.AudioConfig(),+ null,+ this,+ ) ?: return false+ groupCall = call+ groupId = groupIdentifier+ call.connect()+ Log.i(TAG, "connecting to the group call for ${groupIdentifier.toHex()}")+ true+ } catch (t: Throwable) {+ Log.w(TAG, "could not create the group call", t)+ groupCall = null+ groupId = null+ false+ }+ }++ /** Join the media session, so we can be heard. */+ fun join() {+ val call = groupCall ?: return+ try {+ call.setOutgoingVideoSource(localVideoSink, NoCameraControl)+ call.join()+ } catch (t: Throwable) {+ Log.w(TAG, "could not join the group call", t)+ }+ }++ fun leave() {+ val call = groupCall ?: return+ try {+ call.leave()+ call.disconnect()+ } catch (t: Throwable) {+ Log.w(TAG, "could not leave the group call", t)+ } finally {+ groupCall = null+ groupId = null+ localVideoSink.attach(null)+ }+ }++ fun setAudioMuted(muted: Boolean) {+ try {+ groupCall?.setOutgoingAudioMuted(muted)+ } catch (t: Throwable) {+ Log.w(TAG, "could not change the group call mute state", t)+ }+ }++ fun setVideoMuted(muted: Boolean, isScreenShare: Boolean = false) {+ try {+ groupCall?.setOutgoingVideoMuted(muted, isScreenShare)+ } catch (t: Throwable) {+ Log.w(TAG, "could not change the group call video state", t)+ }+ }++ // -- GroupCall.Observer. Both request callbacks must be answered or the call never establishes. --++ override fun requestMembershipProof(groupCall: GroupCall) {+ val id = groupId ?: return+ scope.launch {+ val proof = signaling.membershipProof(id)+ if (proof == null) {+ Log.w(TAG, "no membership proof; the SFU will refuse this call")+ return@launch+ }+ try {+ groupCall.setMembershipProof(proof)+ } catch (t: Throwable) {+ Log.w(TAG, "could not set the membership proof", t)+ }+ }+ }++ override fun requestGroupMembers(groupCall: GroupCall) {+ val id = groupId ?: return+ scope.launch {+ val members = signaling.groupMembers(id)+ if (members.isEmpty()) {+ Log.w(TAG, "no group members; participants cannot be identified")+ return@launch+ }+ try {+ groupCall.setGroupMembers(+ members.map { (uuid, ciphertext) -> GroupCall.GroupMemberInfo(uuid, ciphertext) },+ )+ } catch (t: Throwable) {+ Log.w(TAG, "could not set the group members", t)+ }+ }+ }++ override fun onLocalDeviceStateChanged(groupCall: GroupCall) {+ val id = groupId ?: return+ val state = try { groupCall.localDeviceState } catch (_: Throwable) { null }+ val joined = state?.joinState == GroupCall.JoinState.JOINED+ val participants = try { groupCall.remoteDeviceStates?.size() ?: 0 } catch (_: Throwable) { 0 }+ Log.i(TAG, "group call state: joinState=${state?.joinState} participants=$participants")+ signaling.onGroupCallStateChanged(id, joined, participants)+ }++ override fun onRemoteDeviceStatesChanged(groupCall: GroupCall) {+ val id = groupId ?: return+ val participants = try { groupCall.remoteDeviceStates?.size() ?: 0 } catch (_: Throwable) { 0 }+ val joined = try {+ groupCall.localDeviceState?.joinState == GroupCall.JoinState.JOINED+ } catch (_: Throwable) {+ false+ }+ signaling.onGroupCallStateChanged(id, joined, participants)+ }++ /** Who is already on the call, before joining. */+ override fun onPeekChanged(groupCall: GroupCall) {+ val peek = try { groupCall.peekInfo } catch (_: Throwable) { null }+ Log.i(TAG, "group call peek: devices=${peek?.deviceCount} creator=${peek?.creator}")+ }++ override fun onEnded(+ groupCall: GroupCall,+ reason: CallManager.CallEndReason,+ summary: CallSummary,+ ) {+ val id = groupId+ Log.i(TAG, "group call ended: $reason")+ this.groupCall = null+ this.groupId = null+ localVideoSink.attach(null)+ if (id != null) signaling.onGroupCallEnded(id, reason)+ }++ // Media-detail callbacks the UI does not surface yet. Explicit rather than absent, so it is clear they were+ // considered and are simply not wired.+ override fun onAudioLevels(groupCall: GroupCall) = Unit++ override fun onSpeakingNotification(groupCall: GroupCall, event: GroupCall.SpeechEvent?) = Unit++ override fun onLowBandwidthForVideo(groupCall: GroupCall, recovered: Boolean) = Unit++ override fun onReactions(groupCall: GroupCall, reactions: List<GroupCall.Reaction>?) = Unit++ override fun onRaisedHands(groupCall: GroupCall, raisedHands: List<Long>?) = Unit++ override fun onRemoteMuteRequest(groupCall: GroupCall, sourceDemuxId: Long) = Unit++ override fun onObservedRemoteMute(groupCall: GroupCall, sourceDemuxId: Long, targetDemuxId: Long) = Unit++ private fun ByteArray.toHex(): String = take(8).joinToString("") { "%02x".format(it) }++ private companion object {+ const val TAG = "SignalGroupCall"+ const val AUDIO_LEVEL_INTERVAL_MS = 200+ const val SFU_URL = "https://sfu.voip.signal.org"+ }+}
communicate/src/main/java/com/vayunmathur/communicate/data/signal/transport/SignalGroupsApi.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/signal/transport/SignalGroupsApi.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/signal/transport/SignalGroupsApi.ktindex a0ceda9789..b5aefa3e08 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/signal/transport/SignalGroupsApi.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/signal/transport/SignalGroupsApi.kt@@ -15,6 +15,7 @@ import org.signal.libsignal.zkgroup.auth.ClientZkAuthOperations import org.signal.libsignal.zkgroup.groups.ClientZkGroupCipher import org.signal.libsignal.zkgroup.groups.GroupSecretParams import org.signal.libsignal.zkgroup.groups.UuidCiphertext+import org.signal.storageservice.storage.protos.groups.ExternalGroupCredential import org.signal.storageservice.storage.protos.groups.Group import org.signal.storageservice.storage.protos.groups.GroupAttributeBlob import org.signal.storageservice.storage.protos.groups.GroupChange@@ -47,6 +48,12 @@ object SignalGroupsApi { private const val CREDENTIAL_PATH = "/v1/certificate/auth/group" private const val GROUP_PATH = "/v2/groups/" + /** From the official client's `PushServiceSocket.GROUPSV2_TOKEN`. */+ private const val GROUP_TOKEN_PATH = "/v2/groups/token"++ /** Signal's calling server, from the official client's `SIGNAL_SFU_URL`. */+ const val SFU_URL = "https://sfu.voip.signal.org"+ private val json = Json { ignoreUnknownKeys = true } /** A credential and the day it is valid for. The server returns seven days at a time. */@@ -294,6 +301,57 @@ object SignalGroupsApi { null } + /**+ * The membership proof RingRTC presents to the SFU (`GET /v2/groups/token`).+ *+ * This is what proves to the calling server that we belong to the group, without the SFU learning the+ * group's membership. It expires, which is why RingRTC asks for it again via `requestMembershipProof`.+ */+ suspend fun fetchMembershipProof(+ authorization: String,+ sslSocketFactory: SSLSocketFactory?,+ ): ByteArray? {+ val resp = try {+ NetworkClient.execute(+ "$STORAGE_URL$GROUP_TOKEN_PATH",+ method = "GET",+ headers = mapOf("Authorization" to "Basic $authorization"),+ sslSocketFactory = sslSocketFactory,+ )+ } catch (t: Throwable) {+ Log.w(TAG, "could not fetch a group membership proof", t)+ return null+ }+ if (!resp.isSuccess) {+ Log.w(TAG, "membership proof request failed: ${resp.status} ${resp.statusMessage}")+ return null+ }+ return try {+ val bytes = resp.bytes ?: return null+ // The token is a string in the proto but goes to RingRTC as raw bytes.+ ExternalGroupCredential.parseFrom(bytes).token.toByteArray(Charsets.UTF_8)+ } catch (t: Throwable) {+ Log.w(TAG, "could not parse the membership proof", t)+ null+ }+ }++ /**+ * Encrypt each member's ACI for the SFU. RingRTC pairs the plain UUID with its ciphertext so it can match+ * SFU-reported participants back to people without the SFU knowing who they are.+ */+ fun groupMemberInfo(secretParams: GroupSecretParams, acis: List<String>): List<Pair<java.util.UUID, ByteArray>> {+ val cipher = ClientZkGroupCipher(secretParams)+ return acis.mapNotNull { aci ->+ try {+ val serviceId = ServiceId.Aci.parseFromString(aci)+ java.util.UUID.fromString(aci) to cipher.encrypt(serviceId).serialize()+ } catch (_: Throwable) {+ null+ }+ }+ }+ /** Signal's zkgroup server public params, needed to verify credentials it issues. */ private fun serverPublicParams(): ByteArray = Base64.Default.decode(SERVER_PUBLIC_PARAMS_B64)
communicate/src/main/java/com/vayunmathur/communicate/ui/ConversationScreen.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/ui/ConversationScreen.kt b/communicate/src/main/java/com/vayunmathur/communicate/ui/ConversationScreen.ktindex 2ce0c56bdc..888fbfcd3e 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/ui/ConversationScreen.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/ui/ConversationScreen.kt@@ -290,8 +290,10 @@ fun ConversationScreen( ) } // Calling is per line: SIM and Google Voice hand off to Telecom, WhatsApp and Signal place an- // in-app WebRTC call. Groups are excluded โ group calling is not implemented on either line.- if (!isGroup && address.isNotBlank() && CommunicateRepository.canPlaceCall(line)) {+ // in-app WebRTC call. Signal groups call the SFU; other lines have no group calling.+ val canCall = address.isNotBlank() && CommunicateRepository.canPlaceCall(line) &&+ (!isGroup || CommunicateRepository.canPlaceGroupCall(line))+ if (canCall) { IconButton(onClick = { scope.launch { val placed = CommunicateRepository.placeCallForLine(