javascriptstreamwebrtcpeer-connection

WebRTC: how to detect when a stream or track gets removed from a PeerConnection, in Firefox?


onremovestream has been deprecated (and removed from Firefox), while onremovetrack is not yet implemented in Firefox.

How do I detect when a stream or track is being removed in Firefox?


Solution

  • You use onremovetrack on the receiving stream:

    pc.ontrack = ({track, streams: [stream]}) => {
      track.onunmute = () => {
        if (!video.srcObject) video.srcObject = stream;
      };
      stream.onremovetrack = ({track}) => {
        console.log(`${track.kind} track was removed.`);
        if (!stream.getTracks().length) {
          console.log(`stream ${stream.id} emptied (effectively removed).`);
        }
      };
    };
    

    The above ontrack will run when e.g. the other side adds a track (and negotiates):

    const sender = pc.addTrack(track, stream);
    

    Now, whenever that other side calls either pc.removeTrack(sender) or sets transceiver.direction = "recvonly" (and negotiates), you should see the removetrack event fire.

    Here's an example that should work in all browsers.

    Things to keep in mind

    In standard WebRTC ("unified-plan") our transceiver.receiver.track isn't ended when this happens, because it is wired to the other side's transceiver.sender, not the other side's transceiver.sender.track.

    Instead of ending, our receiving track is muted and removed from its stream(s).

    This is because pc.removeTrack(sender) only sets the sender.track to null and transceiver.direction to recvonly (requiring negotiation).

    A sender may thus resume sending data using sender.replaceTrack(newTrack) and setting transceiver.direction = "sendrecv" again. On this happening, our receiver.track would be unmuted again and reinserted into the stream(s), firing the addtrack events on the stream(s). This also fires the track event again. Explore all the events in this blog's interactive section.

    A receiving track is only truly ended by transceiver.stop() (locally or through negotiation), or pc.close().