Search code examples
multithreadingthread-safetywebrtcjanus-gatewaywebrtc-ios

How to properly close WebRTC peerConnection in iOS?


I'm using 'GoogleWebRTC' pod with version '1.1.29400'. I've been facing issues in closing peer connections. Whichever thread tries to close the connection gets stuck with the following line forever.

self.peerConnection?.close()

So I chose not to close peer connection, instead, I manually destroyed the capturer, tracks, renderers, transceivers and set the reference to nil. Thought I solved the issue but I didn't.

Now started facing problems with 'RTCPeerConnectionFactory'. After generating a few peer connections from the factory, the thread which requests a new peerConnection from the factory gets stuck forever.

Here's how I initialize the factory,

static let factory: RTCPeerConnectionFactory = {
    RTCInitializeSSL()
    let videoEncoderFactory = RTCDefaultVideoEncoderFactory()
    let videoDecoderFactory = RTCDefaultVideoDecoderFactory()
    return RTCPeerConnectionFactory(encoderFactory: videoEncoderFactory, decoderFactory: videoDecoderFactory)
}()

Here's how I initialize the peer connection,

let config = RTCConfiguration()
config.iceServers = iceServers
config.sdpSemantics = .unifiedPlan
config.continualGatheringPolicy = .gatherOnce
config.iceTransportPolicy = iceTransportPolicy

let constraints = RTCMediaConstraints(mandatoryConstraints: nil, optionalConstraints: ["DtlsSrtpKeyAgreement": kRTCMediaConstraintsValueTrue])

let factory = WebRtcClient.factory
self.peerConnection = factory.peerConnection(with: config, constraints: constraints, delegate: nil)

What could've gone wrong?

Are there limitations on the number of parallel peerConnections?

Are there any restrictions on the types of threads that create/manipulate/destroy the peerConnection?

Should I set up synchronous access to these objects?


Solution

  • Seems I'm not alone!

    I managed to solve it in 2020 itself. Was away from SO for some time, sorry for the late answer. Though I'm not currently working on WebRTC let me recollect and answer my issue. Hope it helps someone or at least gives a direction.

    I found that there was some sort of port limit in the number of open peerConnections. That's why the thread which requested a new peerConnection from the factory got stuck after a certain limit.

    We have to close the peerConnections properly by using the peerConnection.close() API.

    The root issue which prevented me from closing the peerConnections was that I was closing the peerConnection from one of the callbacks of peerConnection which ran on the WebRTC signalling thread. It resulted in a deadlock.

    Switching to a thread other than WebRTC's to close the connection seems to be the fix.