Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
translate ▾

Modern-Apps.git / communicate-dev / src / main / java / com / vayunmathur / communicate / data / signal / call / SignalCallManager.kt

SignalCallManager.kt445 lines · 16.7 KiBRaw
1package com.vayunmathur.communicate.data.signal.call
2
3import android.content.Context
4import com.vayunmathur.library.log.Log
5import com.vayunmathur.communicate.data.call.WebRtcInit
6import com.vayunmathur.library.network.NetworkClient
7import kotlinx.coroutines.CoroutineScope
8import kotlinx.coroutines.Dispatchers
9import kotlinx.coroutines.SupervisorJob
10import kotlinx.coroutines.launch
11import org.signal.ringrtc.CallId
12import org.signal.ringrtc.CallManager
13import org.signal.ringrtc.CallSummary
14import org.signal.ringrtc.HttpHeader
15import org.signal.ringrtc.NetworkRoute
16import org.signal.ringrtc.Remote
17import org.webrtc.EglBase
18import org.webrtc.PeerConnection
19import org.webrtc.VideoSink
20import java.time.Instant
21import java.util.UUID
22import java.util.concurrent.atomic.AtomicBoolean
23import javax.net.ssl.SSLSocketFactory
24
25/**
26 * Signal 1:1 calling, driven by RingRTC.
27 *
28 * RingRTC owns the call state machine and the media; this class is the seam to the app. Two directions:
29 * - RingRTC asks us to put signaling on the wire ([Observer.onSendOffer] and friends), which becomes a
30 * `CallMessage` sent through [signaling].
31 * - Inbound `CallMessage`s are fed back in via `received*`.
32 *
33 * Offers and answers carry **opaque V4 protobuf bytes**, never SDP — modern Signal removed the `sdp`
34 * fields entirely, and RingRTC synthesises SDP locally on both ends.
35 *
36 * [CallManager.messageSent]/[CallManager.messageSendFailure] are not optional: RingRTC serialises
37 * signaling one message at a time and will not proceed until one of them is called.
38 *
39 * Scope is 1:1 audio. Group calls, call links and video capture are not implemented; the group and
40 * ad-hoc observer callbacks are refused rather than silently dropped.
41 */
42class SignalCallManager(
43 internal val appContext: Context,
44 internal val signaling: SignalCallSignaling,
45 private val sslSocketFactory: () -> SSLSocketFactory?,
46) : CallManager.Observer {
47
48 /** The lifecycle phase of the current Signal call. */
49 enum class CallState { Ringing, Connecting, Connected, Ended }
50
51 internal val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
52
53 /**
54 * Single-threaded lane for outbound signaling: RingRTC invokes the
55 * observer sequentially (offer, answer, ICE, ...), and that order is
56 * meaningful on the wire. Launching each send on the parallel IO pool
57 * let a later message overtake an earlier one under load.
58 */
59 private val signalingLane = Dispatchers.IO.limitedParallelism(1)
60 internal val initialized = AtomicBoolean(false)
61
62 internal var callManager: CallManager? = null
63 internal var eglBase: EglBase? = null
64
65 /**
66 * Created per call. Present even for audio, because Signal's offer always carries a video m-line and an
67 * answer must match it; only [SignalCamera.setEnabled] differs between audio and video.
68 */
69 internal var camera: SignalCamera? = null
70
71 /** Tracked so a later video toggle keeps telling RingRTC the source is a screencast. */
72 var screenSharing = false
73
74 /** Exposed so the call UI can attach renderers once it exists. */
75 val localVideoSink = SwappableVideoSink()
76 val remoteVideoSink = SwappableVideoSink()
77
78 /** Media type per call, so an answer knows whether video was offered. */
79 val callMediaTypes = java.util.concurrent.ConcurrentHashMap<Long, CallManager.CallMediaType>()
80
81 @Synchronized
82
83
84 /** The EGL context group calls must share, so both call types use one GL thread. */
85
86 /** RingRTC keeps one factory per CallManager, so group calls must reuse this instance. */
87
88 /** The EGL context renderers must share with the decoder, so frames can be drawn. */
89
90 override fun onStartCall(
91 remote: Remote?,
92 callId: CallId?,
93 isOutgoing: Boolean?,
94 callMediaType: CallManager.CallMediaType?,
95 ) {
96 val aci = (remote as? SignalRemote)?.aci ?: return
97 val id = callId?.longValue() ?: return
98 val mediaType = callMediaType ?: CallManager.CallMediaType.AUDIO_CALL
99 callMediaTypes[id] = mediaType
100 signaling.onCallStateChanged(aci, id, CallState.Ringing, mediaType.isVideo())
101 // RingRTC waits for proceed() before touching media, and proceed() needs relays, so both happen
102 // off the callback thread.
103 scope.launch { proceed(id, mediaType) }
104 }
105
106 private suspend fun proceed(callId: Long, mediaType: CallManager.CallMediaType) {
107 val manager = callManager ?: return
108 val egl = eglBase ?: return
109 val iceServers = try {
110 signaling.iceServers()
111 } catch (expected: Throwable) {
112 Log.status(TAG, "could not fetch ICE servers; the call will likely fail behind NAT", expected)
113 emptyList()
114 }
115 if (iceServers.isEmpty()) {
116 Log.status(TAG, "proceeding with no ICE servers; expect connection failure unless both ends are local")
117 }
118 val cameraControl = camera ?: SignalCamera(appContext, egl).also { camera = it }
119 try {
120 manager.proceed(
121 CallId(callId),
122 appContext,
123 egl,
124 org.signal.ringrtc.AudioConfig(),
125 org.signal.ringrtc.VideoConfig(),
126 localVideoSink,
127 remoteVideoSink,
128 cameraControl,
129 iceServers,
130 false,
131 CallManager.DataMode.NORMAL,
132 AUDIO_LEVEL_INTERVAL_MS,
133 null,
134 mediaType.isVideo(),
135 null,
136 )
137 Log.status(
138 TAG,
139 "proceed ok for call $callId with ${iceServers.size} ICE servers, " +
140 "camera=${cameraControl.hasCapturer()} video=${mediaType.isVideo()}",
141 )
142 // proceed()'s enableCamera only starts the local track: it calls the inner
143 // CallContext.setVideoEnabled, not ringrtcSetVideoEnable, so the peer is never told we are
144 // sending video and shows nothing. The public setVideoEnable is what emits the sender status.
145 if (mediaType.isVideo()) assertOutgoingVideo(true)
146 } catch (expected: Throwable) {
147 Log.status(TAG, "proceed failed for call $callId", expected)
148 }
149 }
150
151 /**
152 * Tell the peer whether we are sending video.
153 *
154 * The sender status travels over the RTP data channel, so it only reaches the peer once the connection is
155 * up — which is why it is re-asserted on connect rather than only when the call is set up.
156 */
157 private fun assertOutgoingVideo(enabled: Boolean) {
158 withManager("setVideoEnable") { it.setVideoEnable(enabled, screenSharing) }
159 }
160
161 internal fun signalRemoteVideo(enabled: Boolean) {
162 signaling.onRemoteVideo(enabled)
163 }
164
165 override fun onCallEnded(remote: Remote?, reason: CallManager.CallEndReason, summary: CallSummary) {
166 val aci = (remote as? SignalRemote)?.aci ?: return
167 Log.status(TAG, "call with $aci ended: $reason")
168 signaling.onCallStateChanged(aci, 0, CallState.Ended, false)
169 }
170
171 override fun onCallEvent(remote: Remote?, event: CallManager.CallEvent?) {
172 val aci = (remote as? SignalRemote)?.aci ?: return
173 Log.status(TAG, "call event for $aci: $event")
174 // Media-state events change what the UI renders without changing the call phase.
175 when (event) {
176 CallManager.CallEvent.REMOTE_VIDEO_ENABLE -> {
177 signalRemoteVideo(true)
178 return
179 }
180 CallManager.CallEvent.REMOTE_VIDEO_DISABLE -> {
181 signalRemoteVideo(false)
182 return
183 }
184 CallManager.CallEvent.REMOTE_SHARING_SCREEN_ENABLE -> {
185 signaling.onRemoteScreenShare(true)
186 return
187 }
188 CallManager.CallEvent.REMOTE_SHARING_SCREEN_DISABLE -> {
189 signaling.onRemoteScreenShare(false)
190 return
191 }
192 else -> Unit
193 }
194 val state = when (event) {
195 // Either side accepting is what makes a call active; missing these leaves the UI on "dialing"
196 // while media is already flowing.
197 CallManager.CallEvent.LOCAL_CONNECTED,
198 CallManager.CallEvent.REMOTE_CONNECTED,
199 CallManager.CallEvent.RECONNECTED,
200 -> {
201 // The data channel exists now, so re-state what we are sending. Without this a video call
202 // that was set up before the connection came up shows no video at the far end.
203 if (callMediaTypes.values.any { it.isVideo() } || screenSharing) assertOutgoingVideo(true)
204 CallState.Connected
205 }
206 CallManager.CallEvent.LOCAL_RINGING, CallManager.CallEvent.REMOTE_RINGING -> CallState.Ringing
207 CallManager.CallEvent.RECONNECTING -> CallState.Connecting
208 else -> {
209 // Media-state and screen-share events do not change the call phase.
210 return
211 }
212 }
213 signaling.onCallStateChanged(aci, 0, state, false)
214 }
215
216 override fun onCallConcluded(remote: Remote?) {
217 callMediaTypes.clear()
218 screenSharing = false
219 camera?.dispose()
220 camera = null
221 localVideoSink.attach(null)
222 remoteVideoSink.attach(null)
223 }
224
225 override fun onNetworkRouteChanged(remote: Remote?, networkRoute: NetworkRoute?) = Unit
226
227 override fun onAudioLevels(remote: Remote?, capturedLevel: Int, receivedLevel: Int) = Unit
228
229 override fun onLowBandwidthForVideo(remote: Remote?, recovered: Boolean) = Unit
230
231 // -- Observer: outbound signaling --
232
233 override fun onSendOffer(
234 callId: CallId?,
235 remote: Remote?,
236 remoteDeviceId: Int?,
237 broadcast: Boolean?,
238 opaque: ByteArray,
239 callMediaType: CallManager.CallMediaType?,
240 ) {
241 val id = callId?.longValue() ?: return
242 // Offers are urgent so the callee's device wakes and rings.
243 dispatch(
244 id,
245 remote,
246 remoteDeviceId,
247 broadcast,
248 urgent = true,
249 message = SignalCallMessage.Offer(
250 callId = id,
251 opaque = opaque,
252 video = (callMediaType ?: CallManager.CallMediaType.AUDIO_CALL).isVideo(),
253 ),
254 )
255 }
256
257 override fun onSendAnswer(
258 callId: CallId?,
259 remote: Remote?,
260 remoteDeviceId: Int?,
261 broadcast: Boolean?,
262 opaque: ByteArray,
263 ) {
264 val id = callId?.longValue() ?: return
265 dispatch(id, remote, remoteDeviceId, broadcast, urgent = false, message = SignalCallMessage.Answer(id, opaque))
266 }
267
268 override fun onSendIceCandidates(
269 callId: CallId?,
270 remote: Remote?,
271 remoteDeviceId: Int?,
272 broadcast: Boolean?,
273 iceCandidates: List<ByteArray>?,
274 ) {
275 val id = callId?.longValue() ?: return
276 val candidates = iceCandidates ?: emptyList()
277 dispatch(id, remote, remoteDeviceId, broadcast, urgent = false, message = SignalCallMessage.Ice(id, candidates))
278 }
279
280 override fun onSendHangup(
281 callId: CallId?,
282 remote: Remote?,
283 remoteDeviceId: Int?,
284 broadcast: Boolean?,
285 hangupType: CallManager.HangupType?,
286 deviceId: Int?,
287 ) {
288 val id = callId?.longValue() ?: return
289 dispatch(
290 id,
291 remote,
292 remoteDeviceId,
293 broadcast,
294 urgent = true,
295 message = SignalCallMessage.Hangup(
296 callId = id,
297 type = hangupType ?: CallManager.HangupType.NORMAL,
298 deviceId = deviceId ?: 0,
299 ),
300 )
301 }
302
303 override fun onSendBusy(callId: CallId?, remote: Remote?, remoteDeviceId: Int?, broadcast: Boolean?) {
304 val id = callId?.longValue() ?: return
305 dispatch(id, remote, remoteDeviceId, broadcast, urgent = false, message = SignalCallMessage.Busy(id))
306 }
307
308 /**
309 * Send one signaling message and report the outcome back. RingRTC blocks its signaling queue until
310 * [CallManager.messageSent] or [CallManager.messageSendFailure] is called, so every path must end in
311 * one of them.
312 */
313 private fun dispatch(
314 callId: Long,
315 remote: Remote?,
316 remoteDeviceId: Int?,
317 broadcast: Boolean?,
318 urgent: Boolean,
319 message: SignalCallMessage,
320 ) {
321 val aci = (remote as? SignalRemote)?.aci
322 if (aci == null) {
323 reportSendResult(callId, false)
324 return
325 }
326 // broadcast means "every device"; otherwise the message is addressed to one.
327 val deviceId = if (broadcast == true) null else remoteDeviceId
328 scope.launch(signalingLane) {
329 val ok = try {
330 signaling.sendCallMessage(aci, deviceId, message, urgent)
331 } catch (expected: Throwable) {
332 Log.status(TAG, "call signaling send failed", expected)
333 false
334 }
335 Log.status(
336 TAG,
337 "sent ${message::class.simpleName} callId=$callId to $aci device=${deviceId ?: "all"} " +
338 "urgent=$urgent ok=$ok" +
339 when (message) {
340 is SignalCallMessage.Offer -> " opaque=${message.opaque.size}B video=${message.video}"
341 is SignalCallMessage.Answer -> " opaque=${message.opaque.size}B"
342 is SignalCallMessage.Ice -> " candidates=${message.candidates.size}"
343 else -> ""
344 },
345 )
346 reportSendResult(callId, ok)
347 }
348 }
349
350 private fun reportSendResult(callId: Long, ok: Boolean) {
351 val manager = callManager ?: return
352 try {
353 if (ok) manager.messageSent(CallId(callId)) else manager.messageSendFailure(CallId(callId))
354 } catch (expected: Throwable) {
355 Log.status(TAG, "could not report the signaling send result", expected)
356 }
357 }
358
359 // -- Observer: RingRTC uses the app as its HTTP stack --
360
361 override fun onSendHttpRequest(
362 requestId: Long,
363 url: String,
364 method: CallManager.HttpMethod,
365 headers: List<HttpHeader>?,
366 body: ByteArray?,
367 ) {
368 val manager = callManager ?: return
369 scope.launch {
370 try {
371 val resp = NetworkClient.execute(
372 url,
373 method = when (method) {
374 CallManager.HttpMethod.GET -> "GET"
375 CallManager.HttpMethod.PUT -> "PUT"
376 CallManager.HttpMethod.POST -> "POST"
377 CallManager.HttpMethod.DELETE -> "DELETE"
378 },
379 headers = headers?.associate { it.name to it.value }.orEmpty(),
380 body = body,
381 sslSocketFactory = sslSocketFactory(),
382 )
383 manager.receivedHttpResponse(requestId, resp.status, resp.bytes)
384 } catch (expected: Throwable) {
385 Log.status(TAG, "RingRTC HTTP request failed", expected)
386 try { manager.httpRequestFailed(requestId) } catch (_: Throwable) {}
387 }
388 }
389 }
390
391 // -- Observer: group calling, out of scope --
392
393 override fun onSendCallMessage(
394 recipientUuid: UUID,
395 message: ByteArray,
396 urgency: CallManager.CallMessageUrgency,
397 ) {
398 Log.status(TAG, "onSendCallMessage is only used by group calling, which is not implemented")
399 }
400
401 override fun onSendCallMessageToGroup(
402 groupId: ByteArray,
403 message: ByteArray,
404 urgency: CallManager.CallMessageUrgency,
405 overrideRecipients: List<UUID>,
406 ) {
407 Log.status(TAG, "group calling is not implemented")
408 }
409
410 override fun onSendCallMessageToAdhocGroup(
411 message: ByteArray,
412 urgency: CallManager.CallMessageUrgency,
413 expiration: Instant,
414 recipientsToEndorsements: Map<UUID, ByteArray>,
415 ) {
416 Log.status(TAG, "ad-hoc call groups are not implemented")
417 }
418
419 override fun onGroupCallRingUpdate(
420 groupId: ByteArray,
421 ringId: Long,
422 sender: UUID,
423 update: CallManager.RingUpdate?,
424 ) {
425 Log.status(TAG, "group call ring updates are not implemented")
426 }
427
428 // Non-inline: making this cross-module public would otherwise force
429 // the internal RingRTC manager property public too.
430 fun withManager(what: String, block: (CallManager) -> Unit): Boolean {
431 val manager = callManager ?: return false
432 return try {
433 block(manager)
434 true
435 } catch (expected: Throwable) {
436 Log.status(TAG, "$what failed", expected)
437 false
438 }
439 }
440
441 internal companion object {
442 internal const val TAG = "SignalCallManager"
443 const val AUDIO_LEVEL_INTERVAL_MS = 500
444 }
445}