package calls.data.remote import android.content.Context import org.webrtc.* import java.util.concurrent.ConcurrentHashMap import javax.inject.Inject import javax.inject.Singleton @Singleton class GroupWebRtcManager @Inject constructor(private val context: Context) { private val peerConnections = ConcurrentHashMap() private val factory: PeerConnectionFactory by lazy { createFactory() } private fun createFactory(): PeerConnectionFactory { PeerConnectionFactory.initialize( PeerConnectionFactory.InitializationOptions.builder(context).createInitializationOptions() ) return PeerConnectionFactory.builder() .setVideoEncoderFactory(DefaultVideoEncoderFactory(EglBase.create().eglBaseContext, true, true)) .setVideoDecoderFactory(DefaultVideoDecoderFactory(EglBase.create().eglBaseContext)) .createPeerConnectionFactory() } fun addParticipant(userId: String, observer: PeerConnection.Observer): PeerConnection? { val iceServers = listOf( PeerConnection.IceServer.builder("stun:stun.l.google.com:19302").createIceServer() ) val pc = factory.createPeerConnection(iceServers, observer) if (pc != null) { peerConnections[userId] = pc } return pc } fun removeParticipant(userId: String) { peerConnections[userId]?.dispose() peerConnections.remove(userId) } fun getPeerConnection(userId: String): PeerConnection? = peerConnections[userId] fun closeAll() { peerConnections.values.forEach { it.dispose() } peerConnections.clear() } }