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 / whatsapp / call / WhatsAppCallSession.kt

WhatsAppCallSession.kt209 lines · 9.4 KiBRaw
1package com.vayunmathur.communicate.data.whatsapp.call
2
3import android.content.Context
4import android.media.AudioManager
5import org.webrtc.AudioSource
6import org.webrtc.AudioTrack
7import org.webrtc.DefaultVideoDecoderFactory
8import org.webrtc.DefaultVideoEncoderFactory
9import org.webrtc.EglBase
10import org.webrtc.IceCandidate
11import org.webrtc.MediaConstraints
12import org.webrtc.MediaStream
13import org.webrtc.PeerConnection
14import com.vayunmathur.communicate.data.call.WebRtcInit
15import org.webrtc.PeerConnectionFactory
16import org.webrtc.RtpReceiver
17import org.webrtc.RtpSender
18import org.webrtc.SdpObserver
19import org.webrtc.SessionDescription
20import kotlin.coroutines.resume
21import kotlin.coroutines.resumeWithException
22import kotlin.coroutines.suspendCoroutine
23import kotlinx.coroutines.CompletableDeferred
24
25/**
26 * WebRTC media leg of a WhatsApp call (Phase D 3d — audio; extended for video in Phase E).
27 *
28 * Forked from `data/googlevoice/call/WebRtcAudioSession`. Carries one Opus audio m-line over a
29 * single [PeerConnection]; SDP is exchanged (via the [WhatsAppCallSignaling] `<webrtc>` extension)
30 * with ICE gathered once so the SDP is self-contained for the `<call>` stanza. Exposes mute +
31 * speaker routing.
32 *
33 * The 32-byte WhatsApp call key ([WhatsAppCallCrypto]) is exchanged/verified over signaling; the
34 * actual client-to-client media confidentiality here is WebRTC's own DTLS-SRTP (WhatsApp's native
35 * SRTP schedule can't interop from Java — documented limitation).
36 */
37open class WhatsAppCallSession(protected val appContext: Context) {
38
39 protected val eglBase: EglBase = EglBase.create()
40 protected var factory: PeerConnectionFactory? = null
41 protected var peerConnection: PeerConnection? = null
42 private var audioSource: AudioSource? = null
43 private var localAudioTrack: AudioTrack? = null
44 private var audioSender: RtpSender? = null
45
46 protected val iceComplete = CompletableDeferred<Unit>()
47
48 open fun initialize() {
49 WebRtcInit.ensureInitialized(appContext)
50 val encoder = DefaultVideoEncoderFactory(eglBase.eglBaseContext, true, true)
51 val decoder = DefaultVideoDecoderFactory(eglBase.eglBaseContext)
52 factory = PeerConnectionFactory.builder()
53 .setVideoEncoderFactory(encoder)
54 .setVideoDecoderFactory(decoder)
55 .createPeerConnectionFactory()
56 }
57
58 protected open fun ensurePeerConnection() {
59 if (peerConnection != null) return
60 val f = factory ?: error("initialize() not called")
61 val iceServers = listOf(
62 PeerConnection.IceServer.builder("stun:stun.l.google.com:19302").createIceServer(),
63 )
64 val config = PeerConnection.RTCConfiguration(iceServers).apply {
65 sdpSemantics = PeerConnection.SdpSemantics.UNIFIED_PLAN
66 bundlePolicy = PeerConnection.BundlePolicy.MAXBUNDLE
67 rtcpMuxPolicy = PeerConnection.RtcpMuxPolicy.REQUIRE
68 continualGatheringPolicy = PeerConnection.ContinualGatheringPolicy.GATHER_ONCE
69 }
70 peerConnection = f.createPeerConnection(config, object : PeerConnection.Observer {
71 override fun onIceCandidate(candidate: IceCandidate?) {}
72 override fun onIceGatheringChange(state: PeerConnection.IceGatheringState?) {
73 if (state == PeerConnection.IceGatheringState.COMPLETE && !iceComplete.isCompleted) {
74 iceComplete.complete(Unit)
75 }
76 }
77 override fun onSignalingChange(p0: PeerConnection.SignalingState?) {}
78 override fun onIceConnectionChange(p0: PeerConnection.IceConnectionState?) {}
79 override fun onIceConnectionReceivingChange(p0: Boolean) {}
80 override fun onIceCandidatesRemoved(p0: Array<out IceCandidate>?) {}
81 override fun onAddStream(p0: MediaStream?) {}
82 override fun onRemoveStream(p0: MediaStream?) {}
83 override fun onDataChannel(p0: org.webrtc.DataChannel?) {}
84 override fun onRenegotiationNeeded() {}
85 override fun onAddTrack(p0: RtpReceiver?, p1: Array<out MediaStream>?) {}
86 })
87 addLocalAudio(f)
88 onPeerConnectionCreated(f)
89 }
90
91 /** Hook for subclasses (video) to add extra local tracks after the audio track. */
92 protected open fun onPeerConnectionCreated(f: PeerConnectionFactory) {}
93
94 private fun addLocalAudio(f: PeerConnectionFactory) {
95 val constraints = MediaConstraints().apply {
96 mandatory.add(MediaConstraints.KeyValuePair("googEchoCancellation", "true"))
97 mandatory.add(MediaConstraints.KeyValuePair("googAutoGainControl", "true"))
98 mandatory.add(MediaConstraints.KeyValuePair("googNoiseSuppression", "true"))
99 }
100 val source = f.createAudioSource(constraints)
101 val track = f.createAudioTrack("wa_audio", source)
102 audioSource = source
103 localAudioTrack = track
104 audioSender = peerConnection?.addTrack(track, listOf("wa_stream"))
105 }
106
107 protected open fun offerConstraints(): MediaConstraints = MediaConstraints().apply {
108 mandatory.add(MediaConstraints.KeyValuePair("OfferToReceiveAudio", "true"))
109 mandatory.add(MediaConstraints.KeyValuePair("OfferToReceiveVideo", "false"))
110 }
111
112 /** Create an SDP offer, set it locally, wait for ICE, and return the final SDP. */
113 suspend fun createOffer(): String {
114 ensurePeerConnection()
115 val pc = peerConnection ?: error("no peer connection")
116 val offer = pc.createOfferSuspend(offerConstraints())
117 pc.setLocalDescriptionSuspend(offer)
118 iceComplete.await()
119 return pc.localDescription?.description ?: offer.description
120 }
121
122 /** Apply the remote answer SDP received in the peer's `<accept>`. */
123 suspend fun setRemoteAnswer(sdp: String) {
124 val pc = peerConnection ?: error("no peer connection")
125 pc.setRemoteDescriptionSuspend(SessionDescription(SessionDescription.Type.ANSWER, sdp))
126 }
127
128 /** For an inbound call: apply the remote offer, create + set an answer, return answer SDP. */
129 suspend fun createAnswer(remoteOfferSdp: String): String {
130 ensurePeerConnection()
131 val pc = peerConnection ?: error("no peer connection")
132 pc.setRemoteDescriptionSuspend(SessionDescription(SessionDescription.Type.OFFER, remoteOfferSdp))
133 val answer = pc.createAnswerSuspend(offerConstraints())
134 pc.setLocalDescriptionSuspend(answer)
135 iceComplete.await()
136 return pc.localDescription?.description ?: answer.description
137 }
138
139 /** Add a remote ICE candidate (candidate line "candidate:..."). sdpMid/index default to audio m0. */
140 fun addRemoteCandidate(candidate: String, sdpMid: String = "0", sdpMLineIndex: Int = 0) {
141 runCatching { peerConnection?.addIceCandidate(IceCandidate(sdpMid, sdpMLineIndex, candidate)) }
142 }
143
144 fun setMuted(muted: Boolean) {
145 localAudioTrack?.setEnabled(!muted)
146 }
147
148 fun setSpeaker(on: Boolean) {
149 val am = appContext.getSystemService(Context.AUDIO_SERVICE) as AudioManager
150 @Suppress("DEPRECATION")
151 am.isSpeakerphoneOn = on
152 }
153
154 open fun close() {
155 runCatching { peerConnection?.dispose() }
156 runCatching { audioSource?.dispose() }
157 runCatching { factory?.dispose() }
158 runCatching { eglBase.release() }
159 peerConnection = null
160 audioSource = null
161 localAudioTrack = null
162 audioSender = null
163 }
164
165 // ---- SdpObserver → coroutine adapters ----
166
167 private suspend fun PeerConnection.createOfferSuspend(c: MediaConstraints): SessionDescription =
168 suspendCoroutine { cont ->
169 createOffer(object : SimpleSdpObserver() {
170 override fun onCreateSuccess(desc: SessionDescription) = cont.resume(desc)
171 override fun onCreateFailure(error: String?) =
172 cont.resumeWithException(IllegalStateException("createOffer: $error"))
173 }, c)
174 }
175
176 private suspend fun PeerConnection.createAnswerSuspend(c: MediaConstraints): SessionDescription =
177 suspendCoroutine { cont ->
178 createAnswer(object : SimpleSdpObserver() {
179 override fun onCreateSuccess(desc: SessionDescription) = cont.resume(desc)
180 override fun onCreateFailure(error: String?) =
181 cont.resumeWithException(IllegalStateException("createAnswer: $error"))
182 }, c)
183 }
184
185 private suspend fun PeerConnection.setLocalDescriptionSuspend(desc: SessionDescription) =
186 suspendCoroutine<Unit> { cont ->
187 setLocalDescription(object : SimpleSdpObserver() {
188 override fun onSetSuccess() = cont.resume(Unit)
189 override fun onSetFailure(error: String?) =
190 cont.resumeWithException(IllegalStateException("setLocal: $error"))
191 }, desc)
192 }
193
194 private suspend fun PeerConnection.setRemoteDescriptionSuspend(desc: SessionDescription) =
195 suspendCoroutine<Unit> { cont ->
196 setRemoteDescription(object : SimpleSdpObserver() {
197 override fun onSetSuccess() = cont.resume(Unit)
198 override fun onSetFailure(error: String?) =
199 cont.resumeWithException(IllegalStateException("setRemote: $error"))
200 }, desc)
201 }
202}
203
204private open class SimpleSdpObserver : SdpObserver {
205 override fun onCreateSuccess(desc: SessionDescription) {}
206 override fun onSetSuccess() {}
207 override fun onCreateFailure(error: String?) {}
208 override fun onSetFailure(error: String?) {}
209}