LocalParticipant.kt
10.4 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
package io.livekit.android.room.participant
import android.content.Context
import android.media.MediaCodecInfo
import com.google.protobuf.ByteString
import dagger.assisted.Assisted
import dagger.assisted.AssistedFactory
import dagger.assisted.AssistedInject
import io.livekit.android.room.RTCEngine
import io.livekit.android.room.track.*
import io.livekit.android.util.LKLog
import livekit.LivekitModels
import org.webrtc.*
import kotlin.math.abs
class LocalParticipant
@AssistedInject
internal constructor(
@Assisted
info: LivekitModels.ParticipantInfo,
internal val engine: RTCEngine,
private val peerConnectionFactory: PeerConnectionFactory,
private val context: Context,
private val eglBase: EglBase,
) :
Participant(info.sid, info.identity) {
init {
updateFromInfo(info)
}
private val localTrackPublications
get() = tracks.values.toList()
fun createAudioTrack(
name: String = "",
options: LocalAudioTrackOptions = LocalAudioTrackOptions(),
): LocalAudioTrack {
val audioConstraints = MediaConstraints()
val items = listOf(
MediaConstraints.KeyValuePair("googEchoCancellation", options.echoCancellation.toString()),
MediaConstraints.KeyValuePair("googAutoGainControl", options.autoGainControl.toString()),
MediaConstraints.KeyValuePair("googHighpassFilter", options.highPassFilter.toString()),
MediaConstraints.KeyValuePair("googNoiseSuppression", options.noiseSuppression.toString()),
MediaConstraints.KeyValuePair("googTypingNoiseDetection", options.typingNoiseDetection.toString()),
)
audioConstraints.optional.addAll(items)
return LocalAudioTrack.createTrack(peerConnectionFactory, audioConstraints, name)
}
fun createVideoTrack(
name: String = "",
options: LocalVideoTrackOptions = LocalVideoTrackOptions(),
): LocalVideoTrack {
return LocalVideoTrack.createTrack(
peerConnectionFactory,
context,
name,
options,
eglBase
)
}
suspend fun publishAudioTrack(
track: LocalAudioTrack,
publishListener: PublishListener? = null
) {
if (localTrackPublications.any { it.track == track }) {
publishListener?.onPublishFailure(TrackException.PublishException("Track has already been published"))
return
}
val cid = track.rtcTrack.id()
val trackInfo =
engine.addTrack(cid = cid, name = track.name, kind = track.kind.toProto())
val transInit = RtpTransceiver.RtpTransceiverInit(
RtpTransceiver.RtpTransceiverDirection.SEND_ONLY,
listOf(this.sid)
)
// TODO: sendEncodings to customize
val transceiver = engine.publisher.peerConnection.addTransceiver(track.rtcTrack, transInit)
track.transceiver = transceiver
if (transceiver == null) {
publishListener?.onPublishFailure(TrackException.PublishException("null sender returned from peer connection"))
return
}
val publication = LocalTrackPublication(trackInfo, track, this)
addTrackPublication(publication)
publishListener?.onPublishSuccess(publication)
}
suspend fun publishVideoTrack(
track: LocalVideoTrack,
options: VideoTrackPublishOptions = VideoTrackPublishOptions(),
publishListener: PublishListener? = null
) {
if (localTrackPublications.any { it.track == track }) {
publishListener?.onPublishFailure(TrackException.PublishException("Track has already been published"))
return
}
val cid = track.rtcTrack.id()
val trackInfo = engine.addTrack(
cid = cid,
name = track.name,
kind = LivekitModels.TrackType.VIDEO,
dimensions = track.dimensions
)
val encodings = computeVideoEncodings(track.dimensions, options)
val transInit = RtpTransceiver.RtpTransceiverInit(
RtpTransceiver.RtpTransceiverDirection.SEND_ONLY,
listOf(this.sid),
encodings
)
val transceiver = engine.publisher.peerConnection.addTransceiver(track.rtcTrack, transInit)
track.transceiver = transceiver
if (transceiver == null) {
publishListener?.onPublishFailure(TrackException.PublishException("null sender returned from peer connection"))
return
}
// TODO: enable setting preferred codec
val publication = LocalTrackPublication(trackInfo, track, this)
addTrackPublication(publication)
publishListener?.onPublishSuccess(publication)
}
private fun computeVideoEncodings(
dimensions: Track.Dimensions,
options: VideoTrackPublishOptions
): List<RtpParameters.Encoding> {
val (width, height) = dimensions
var encoding = options.videoEncoding
val simulcast = options.simulcast
if ((encoding == null && !simulcast) || width == 0 || height == 0) {
return emptyList()
}
if (encoding == null) {
encoding = determineAppropriateEncoding(width, height)
LKLog.d { "using video encoding: $encoding" }
}
val encodings = mutableListOf<RtpParameters.Encoding>()
if (simulcast) {
encodings.add(encoding.toRtpEncoding("f"))
val presets = presetsForResolution(width, height)
val midPreset = presets[1]
val lowPreset = presets[0]
// if resolution is high enough, we send both h and q res.
// otherwise only send h
if (width >= 960) {
encodings.add(midPreset.encoding.toRtpEncoding("h", 2.0))
encodings.add(lowPreset.encoding.toRtpEncoding("q", 4.0))
} else {
encodings.add(lowPreset.encoding.toRtpEncoding("h", 2.0))
}
} else {
encodings.add(encoding.toRtpEncoding())
}
return encodings
}
private fun determineAppropriateEncoding(width: Int, height: Int): VideoEncoding {
val presets = presetsForResolution(width, height)
return presets
.last { width >= it.capture.width && height >= it.capture.height }
.encoding
}
private fun presetsForResolution(width: Int, height: Int): List<VideoPreset> {
val aspectRatio = width.toFloat() / height
if (abs(aspectRatio - 16f / 9f) < abs(aspectRatio - 4f / 3f)) {
return PRESETS_16_9
} else {
return PRESETS_4_3
}
}
fun unpublishTrack(track: Track) {
val publication = localTrackPublications.firstOrNull { it.track == track }
if (publication === null) {
LKLog.d { "this track was never published." }
return
}
val sid = publication.sid
tracks.remove(sid)
when (publication.kind) {
Track.Kind.AUDIO -> audioTracks.remove(sid)
Track.Kind.VIDEO -> videoTracks.remove(sid)
else -> {}
}
val senders = engine.publisher.peerConnection.senders ?: return
for (sender in senders) {
val t = sender.track() ?: continue
if (t.id() == track.rtcTrack.id()) {
engine.publisher.peerConnection.removeTrack(sender)
}
}
track.stop()
}
/**
* Publish a new data payload to the room. Data will be forwarded to each participant in the room.
* Each payload must not exceed 15k in size
*
* @param data payload to send
* @param reliability for delivery guarantee, use RELIABLE. for fastest delivery without guarantee, use LOSSY
* @param destination list of participant SIDs to deliver the payload, null to deliver to everyone
*/
@Suppress("unused")
suspend fun publishData(data: ByteArray, reliability: DataPublishReliability, destination: List<String>?) {
if (data.size > RTCEngine.MAX_DATA_PACKET_SIZE) {
throw IllegalArgumentException("cannot publish data larger than " + RTCEngine.MAX_DATA_PACKET_SIZE)
}
val kind = when (reliability) {
DataPublishReliability.RELIABLE -> LivekitModels.DataPacket.Kind.RELIABLE
DataPublishReliability.LOSSY -> LivekitModels.DataPacket.Kind.LOSSY
}
val packetBuilder = LivekitModels.UserPacket.newBuilder().
setPayload(ByteString.copyFrom(data)).
setParticipantSid(sid)
if (destination != null) {
packetBuilder.addAllDestinationSids(destination)
}
val dataPacket = LivekitModels.DataPacket.newBuilder().
setUser(packetBuilder).
setKind(kind).
build()
engine.sendData(dataPacket)
}
override fun updateFromInfo(info: LivekitModels.ParticipantInfo) {
super.updateFromInfo(info)
// detect tracks that have been muted on the server side, apply those changes
for (ti in info.tracksList) {
val publication = this.tracks[ti.sid] as? LocalTrackPublication ?: continue
if (ti.muted != publication.muted) {
publication.setMuted(ti.muted)
}
}
}
fun onRemoteMuteChanged(trackSid: String, muted: Boolean) {
val pub = tracks[trackSid]
pub?.muted = muted
}
interface PublishListener {
fun onPublishSuccess(publication: TrackPublication) {}
fun onPublishFailure(exception: Exception) {}
}
@AssistedFactory
interface Factory {
fun create(info: LivekitModels.ParticipantInfo): LocalParticipant
}
companion object {
private val PRESETS_16_9 = listOf(
VideoPreset169.QVGA,
VideoPreset169.VGA,
VideoPreset169.QHD,
VideoPreset169.HD,
VideoPreset169.FHD
)
private val PRESETS_4_3 = listOf(
VideoPreset43.QVGA,
VideoPreset43.VGA,
VideoPreset43.QHD,
VideoPreset43.HD,
VideoPreset43.FHD
)
}
}
interface TrackPublishOptions {
val name: String?
}
data class VideoTrackPublishOptions(
override val name: String? = null,
val videoEncoding: VideoEncoding? = null,
//val videoCodec: VideoCodec? = null,
val simulcast: Boolean = false
) : TrackPublishOptions
data class AudioTrackPublishOptions(
override val name: String? = null,
val audioBitrate: Int? = null,
) : TrackPublishOptions