Search code examples
javascriptwebrtcpeer-connection

Leaking RTCPeerConnections. Even after page refresh


I have a pretty simple RTCPeerConnection app running. Uses Firebase for signaling. The RTCPeerConnections get established, and then I take the stream, and do the following with it:

let streamURL = window.URL.createObjectURL(stream);

Then I take that streamURL and set the video.src = streamURL. That is how I get it to see the remote users' video. Then, when I am done with the connection (I want to end the conversation) I do the following:

peerConnection.getLocalStreams().forEach(stream=>{
    stream.getTracks().forEach(t=>{
        t.stop();
        stream.removeTrack(t);
    });
});
peerConnection.close();

This ends the connection, including turns off the green light for my local webcam. This tells me that things have ended for the most part.

Then I check chrome://webrtc-internals and the connection is still there. Even after I refresh, the connection is there. That seems odd. How can it still be there, even after a refresh? Please help. Am I not ending the RTCPeerConnection correctly? I thought this was the right way. I just can't figure out how the webrtc internals can still show it EVEN AFTER a page refresh. PLEASE HELP!


Solution

  • You're doing it right. The only thing missing is:

    peerConnection = null;
    

    to let the peer connection itself be garbage collected.

    As I've mentioned elsewhere I'd avoid createObjectURL and use video.srcObject = stream directly instead, but that has to do with releasing the camera should you forget to stop all tracks.

    I wouldn't read too much into Chrome's webrtc-internals page, because looking at peer connections is useful for debugging, even after the fact. The important question is: Are there any JavaScript or wire observable signs of a connection being open?

    Example

    You can try this https fiddle in two different tabs or windows and see things failing remotely.

    Make sure you can see both fiddles at once, and click the [Start!] button in one of them to connect. You should see video in both places. Now when you click the [Stop!] button, you should see the following output on the other end (it may take a few seconds for all three to appear):

    disconnected
    failed
    closed
    

    Because I check for the "failed" state and close the connection on it (though in production it's more common to use data channels to communicate hangups).

    Chrome

    That said, I won't fully rule out a bug in Chrome, in that it may hang on to resources longer than it should, as I see the same thing you're describing (but note that e.g. "packets sent" drops to zero when I click "Stop!", which is the important part).

    Contrast with Firefox, where, when I go to about:webrtc (its equivalent to chrome://webrtc-internals) and hit refresh and the [Clear History] button, my peer connections are gone from the list.