Async WebRTC remote datachannel logs

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="replaceTrack()" 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></td></tr></table><br>
<script src="https://webrtc.github.io/adapter/adapter-latest.js"></script>

JavaScript

const console = { log: msg => div.innerHTML += msg + "<br>" };

const iceServers = [{urls: "stun:stun.l.google.com:19302"}];
let dc, sc, pc = new RTCPeerConnection({iceServers}), live = false;
pc.ontrack = ({streams: [stream]}) => v2.srcObject = stream;
pc.ondatachannel = e => dc ? scInit(sc = e.channel) : dcInit(dc = e.channel);

const streams = [];

(async () => {
  try {
    v1.srcObject = streams[0] = await navigator.mediaDevices.getUserMedia({video: true});
    streams[1] = whiteNoise();
  } catch (e) {
    console.log(e);
  }
})();

pc.oniceconnectionstatechange = () => {
  update(pc.iceConnectionState);
  console.log(`ice = ${pc.iceConnectionState}, sig = ${pc.signalingState}, dc = ${dc.readyState}`);
}

let negotiating; // Chrome workaround
pc.onnegotiationneeded = async () => {
  try {
    if (negotiating) return;
    negotiating = true;
    await pc.setLocalDescription(await pc.createOffer());
    if (live) sc.send(JSON.stringify({sdp: pc.localDescription}));
  } catch (e) {
    console.log(e);
  } finally {
    negotiating = false;
  }
};

function scInit() {
  sc.onmessage = async ({data}) => { 
    try {
      const {sdp, candidate} = JSON.parse(data);
      if (sdp) {
        await pc.setRemoteDescription(sdp);
        if (sdp.type == "offer") {
          await pc.setLocalDescription(await pc.createAnswer());
          sc.send(JSON.stringify({sdp: pc.localDescription}));
        }
      } else if (candidate) await pc.addIceCandidate(candidate);
    } catch (e) {
      console.log(e);
    }
  };
}

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

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