proper teardown of a WebRTC RTCPeerConnection

615 views Asked by At

I tried to do a simple WebRTC p2p video chat browser app. I setup a signal server and have two peers doing all the SDP and ICE handshakes. Some of my code snippet:

pc = new RTCPeerConnection(config);
pc.onicecandidate = (event) => {
 ...
}
pc.ontrack(event) =>{
  if (event.track.kind === 'video') {
    // add the stream as the srcObject of a video tag
  }
  event.streams[0].onremovetrack = (e) => {
    // want to remove the stream from the video tag
  }
}

When a peer is done I do the following:

pc.stop();

I simply just close the RTCPeerConnection. But I don't see the onremovetrack being triggered on the other peer.

What is the proper way to shutdown a peer so that the other peer can be notified and onremovetrack triggered?

1

There are 1 answers

0
Tamas Szoke On

I think you should use the RTCPeerConnection.removeTrack() method, it will fire the MediaStream.onremovetrack event at the other end.

To get the tracks of the connection use the RTCPeerConnection.getSenders() method.

The RTCPeerConnection method getSenders() returns an array of RTCRtpSender objects, each of which represents the RTP sender responsible for transmitting one track's data.

Example

let senders = pc.getSenders()

senders.forEach((sender) => {
  pc.removeTrack(sender)
})

This will remove all the tracks from the connection. There's an experimental method to completely close the connection, RTCPeerConnection.close(), check the compatibility table. Use it after the tracks removed, so you will get the onremovetrack events:

pc.close()

Calling this method terminates the RTCPeerConnection's ICE agent, ending any ongoing ICE processing and any active streams.

Alternative

The other way is to immediately call the close() method and listen to the RTCPeerConnection.onconnectionstatechange event at the other end, check the example.

More information