Modern WebRTC remote add/remove track

Shows modern WebRTC use with cut'n'paste Offer/Answer exchange in Firefox w/add/remove renegotiation through datachannel.

by jib1

HTML

<video id="v1" width="160" height="120" autoplay muted></video>
<video id="v2" width="160" height="120" autoplay></video><br>
<button id="button" onclick="createOffer()">Offer:</button>
<textarea id="offer" placeholder="Paste offer here"></textarea><br>
Answer: <textarea id="answer"></textarea><br>
<button id="button" onclick="addTrack()">AddTrack</button>
<button id="removeAddButton" onclick="removeAdd()" disabled>Remove+Add</button>
<button id="flipButton" onclick="flip()" disabled>ReplaceTrack (FF only)</button>
<div id="div"><p></div><br>
<table><tr><td><div id="div2">Not connected</div></td>
  <td><input id="chat" disabled></input></td></tr></table><br>
<script src="https://webrtc.github.io/adapter/adapter-latest.js"></script>

JavaScript

var config = { iceServers: [{ urls: "stun:stun.l.google.com:19302" }] };
var signalingDelayMs = 0;

var dc, sc, pc = new RTCPeerConnection(config), live = false;
pc.onaddstream = e => v2.srcObject = e.stream;
pc.ondatachannel = e => dc? scInit(sc = e.channel) : dcInit(dc = e.channel);

var streams = [];
var haveGum = navigator.mediaDevices.getUserMedia({fake:true, video:true})
.then(stream => streams[1] = stream)
.then(() => navigator.mediaDevices.getUserMedia({ video: true }))
.then(stream => v1.srcObject = streams[0] = stream);

pc.oniceconnectionstatechange = () => update(pc.iceConnectionState);

var negotiating; // Chrome workaround
pc.onnegotiationneeded = () => {
  if (negotiating) return;
  negotiating = true;
  pc.createOffer().then(d => pc.setLocalDescription(d))
  .then(() => live && sc.send(JSON.stringify({ sdp: pc.localDescription })))
  .catch(log);
};
pc.onsignalingstatechange = () => negotiating = pc.signalingState != "stable";

function scInit() {
  sc.onmessage = e => wait(signalingDelayMs).then(() => { 
    var msg = JSON.parse(e.data);
    if (msg.sdp) {
      var desc = new RTCSessionDescription(JSON.parse(e.data).sdp);
      if (desc.type == "offer") {
        pc.setRemoteDescription(desc).then(() => pc.createAnswer())
        .then(answer => pc.setLocalDescription(answer)).then(() => {
          sc.send(JSON.stringify({ sdp: pc.localDescription }));
        }).catch(log);
      } else {
        pc.setRemoteDescription(desc).catch(log);
      }
    } else if (msg.candidate) {
      pc.addIceCandidate(new RTCIceCandidate(msg.candidate)).catch(log);
    }
  }).catch(log);
}

function dcInit() {
  dc.onopen = () => {
    live = true; update("Chat:"); chat.disabled = false; chat.select();
  };
  dc.onmessage = e => log(e.data);
}

function createOffer() {
  button.disabled = true;
  pc.onicecandidate = e => {
    if (live) {
      sc.send(JSON.stringify({ "candidate": e.candidate }));
    } else if (!e.candidate) {
      offer.value =...