RTCEngine.kt
10.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
package io.livekit.android.room
import com.github.ajalt.timberkt.Timber
import io.livekit.android.dagger.InjectionNames
import io.livekit.android.room.track.TrackException
import io.livekit.android.room.util.*
import io.livekit.android.util.CloseableCoroutineScope
import io.livekit.android.util.Either
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.launch
import livekit.LivekitModels
import livekit.LivekitRtc
import org.webrtc.*
import javax.inject.Inject
import javax.inject.Named
import javax.inject.Singleton
import kotlin.coroutines.Continuation
import kotlin.coroutines.resume
import kotlin.coroutines.suspendCoroutine
/**
* @suppress
*/
@Singleton
class RTCEngine
@Inject
constructor(
val client: RTCClient,
private val pctFactory: PeerConnectionTransport.Factory,
@Named(InjectionNames.DISPATCHER_IO) ioDispatcher: CoroutineDispatcher,
) : RTCClient.Listener {
var listener: Listener? = null
var rtcConnected: Boolean = false
var joinResponse: LivekitRtc.JoinResponse? = null
var iceConnected: Boolean = false
set(value) {
field = value
val savedJoinResponse = joinResponse
if (field && savedJoinResponse != null) {
listener?.onJoin(savedJoinResponse)
joinResponse = null
}
}
val pendingCandidates = mutableListOf<IceCandidate>()
private val pendingTrackResolvers: MutableMap<String, Continuation<LivekitModels.TrackInfo>> =
mutableMapOf()
private val publisherObserver = PublisherTransportObserver(this)
private val subscriberObserver = SubscriberTransportObserver(this)
internal lateinit var publisher: PeerConnectionTransport
private lateinit var subscriber: PeerConnectionTransport
private lateinit var privateDataChannel: DataChannel
private val coroutineScope = CloseableCoroutineScope(SupervisorJob() + ioDispatcher)
init {
client.listener = this
}
fun join(url: String, token: String) {
client.join(url, token)
}
suspend fun addTrack(cid: String, name: String, kind: LivekitModels.TrackType): LivekitModels.TrackInfo {
if (pendingTrackResolvers[cid] != null) {
throw TrackException.DuplicateTrackException("Track with same ID $cid has already been published!")
}
return suspendCoroutine { cont ->
pendingTrackResolvers[cid] = cont
client.sendAddTrack(cid, name, kind)
}
}
fun updateMuteStatus(sid: String, muted: Boolean) {
client.sendMuteTrack(sid, muted)
}
fun close() {
coroutineScope.close()
publisher.close()
subscriber.close()
client.close()
}
fun negotiate() {
if (!client.isConnected) {
return
}
coroutineScope.launch {
val sdpOffer =
when (val outcome = publisher.peerConnection.createOffer(OFFER_CONSTRAINTS)) {
is Either.Left -> outcome.value
is Either.Right -> {
Timber.d { "error creating offer: ${outcome.value}" }
return@launch
}
}
Timber.v { "sdp offer = $sdpOffer, description: ${sdpOffer.description}, type: ${sdpOffer.type}" }
when (val outcome = publisher.peerConnection.setLocalDescription(sdpOffer)) {
is Either.Right -> {
Timber.d { "error setting local description: ${outcome.value}" }
return@launch
}
}
client.sendOffer(sdpOffer)
}
}
private fun onRTCConnected() {
Timber.v { "RTC Connected" }
rtcConnected = true
pendingCandidates.forEach { candidate ->
client.sendCandidate(candidate, LivekitRtc.SignalTarget.PUBLISHER)
}
pendingCandidates.clear()
}
interface Listener {
fun onJoin(response: LivekitRtc.JoinResponse)
fun onAddTrack(track: MediaStreamTrack, streams: Array<out MediaStream>)
// fun onPublishLocalTrack(cid: String, track: LivekitModels.TrackInfo)
fun onAddDataChannel(channel: DataChannel)
fun onUpdateParticipants(updates: List<LivekitModels.ParticipantInfo>)
fun onUpdateSpeakers(speakers: List<LivekitRtc.SpeakerInfo>)
fun onDisconnect(reason: String)
fun onFailToConnect(error: Exception)
}
companion object {
private const val PRIVATE_DATA_CHANNEL_LABEL = "_private"
private val OFFER_CONSTRAINTS = MediaConstraints().apply {
with(mandatory) {
add(MediaConstraints.KeyValuePair("OfferToReceiveAudio", "false"))
add(MediaConstraints.KeyValuePair("OfferToReceiveVideo", "false"))
}
}
private val MEDIA_CONSTRAINTS = MediaConstraints()
internal val CONN_CONSTRAINTS = MediaConstraints().apply {
with(optional) {
add(MediaConstraints.KeyValuePair("DtlsSrtpKeyAgreement", "true"))
}
}
}
override fun onJoin(info: LivekitRtc.JoinResponse) {
joinResponse = info
val iceServers = mutableListOf<PeerConnection.IceServer>()
for(serverInfo in info.iceServersList){
val username = serverInfo.username ?: ""
val credential = serverInfo.credential ?: ""
iceServers.add(
PeerConnection.IceServer
.builder(serverInfo.urlsList)
.setUsername(username)
.setPassword(credential)
.createIceServer()
)
}
if(iceServers.isEmpty()){
iceServers.addAll(RTCClient.DEFAULT_ICE_SERVERS)
}
val rtcConfig = PeerConnection.RTCConfiguration(iceServers).apply {
sdpSemantics = PeerConnection.SdpSemantics.UNIFIED_PLAN
continualGatheringPolicy = PeerConnection.ContinualGatheringPolicy.GATHER_CONTINUALLY
}
publisher = pctFactory.create(rtcConfig, publisherObserver)
subscriber = pctFactory.create(rtcConfig, subscriberObserver)
privateDataChannel = publisher.peerConnection.createDataChannel(
PRIVATE_DATA_CHANNEL_LABEL,
DataChannel.Init()
)
coroutineScope.launch {
val sdpOffer =
when (val outcome = publisher.peerConnection.createOffer(OFFER_CONSTRAINTS)) {
is Either.Left -> outcome.value
is Either.Right -> {
Timber.d { "error creating offer: ${outcome.value}" }
return@launch
}
}
when (val outcome = publisher.peerConnection.setLocalDescription(sdpOffer)) {
is Either.Right -> {
Timber.d { "error setting local description: ${outcome.value}" }
}
}
client.sendOffer(sdpOffer)
}
}
override fun onAnswer(sessionDescription: SessionDescription) {
Timber.v { "received server answer: ${sessionDescription.type}, ${publisher.peerConnection.signalingState()}" }
coroutineScope.launch {
Timber.i { sessionDescription.toString() }
when (val outcome = publisher.setRemoteDescription(sessionDescription)) {
is Either.Left -> {
if (!rtcConnected) {
onRTCConnected()
}
}
is Either.Right -> {
Timber.e { "error setting remote description for answer: ${outcome.value} " }
}
}
}
}
override fun onOffer(sessionDescription: SessionDescription) {
Timber.v { "received server offer: ${sessionDescription.type}, ${subscriber.peerConnection.signalingState()}" }
coroutineScope.launch {
run<Unit> {
when (val outcome =
subscriber.setRemoteDescription(sessionDescription)) {
is Either.Right -> {
Timber.e { "error setting remote description for answer: ${outcome.value} " }
return@launch
}
}
}
val answer = run {
when (val outcome = subscriber.peerConnection.createAnswer(OFFER_CONSTRAINTS)) {
is Either.Left -> outcome.value
is Either.Right -> {
Timber.e { "error creating answer: ${outcome.value}" }
return@launch
}
}
}
run<Unit> {
when (val outcome = subscriber.peerConnection.setLocalDescription(answer)) {
is Either.Right -> {
Timber.e { "error setting local description for answer: ${outcome.value}" }
return@launch
}
}
}
client.sendAnswer(answer)
}
}
override fun onTrickle(candidate: IceCandidate, target: LivekitRtc.SignalTarget) {
Timber.v { "received ice candidate from peer: $candidate, $target" }
when (target) {
LivekitRtc.SignalTarget.PUBLISHER -> publisher.addIceCandidate(candidate)
LivekitRtc.SignalTarget.SUBSCRIBER -> publisher.addIceCandidate(candidate)
else -> Timber.i { "unknown ice candidate target?" }
}
}
override fun onLocalTrackPublished(response: LivekitRtc.TrackPublishedResponse) {
val signalCid = response.cid ?: run {
Timber.e { "local track published with null cid?" }
return
}
val cid = signalCid
val track = response.track
if (track == null) {
Timber.d { "local track published with null track info?" }
}
Timber.v { "local track published $cid" }
val cont = pendingTrackResolvers.remove(cid)
if (cont == null) {
Timber.d { "missing track resolver for: $cid" }
return
}
cont.resume(response.track)
// listener?.onPublishLocalTrack(cid, track)
}
override fun onParticipantUpdate(updates: List<LivekitModels.ParticipantInfo>) {
listener?.onUpdateParticipants(updates)
}
override fun onActiveSpeakersChanged(speakers: List<LivekitRtc.SpeakerInfo>) {
listener?.onUpdateSpeakers(speakers)
}
override fun onClose(reason: String, code: Int) {
Timber.i { "received close event: $reason, code: $code" }
listener?.onDisconnect(reason)
}
override fun onError(error: Exception) {
listener?.onFailToConnect(error)
}
}