Async WebRTC tab demo

by jib1

HTML

<script src="https://webrtchacks.github.io/adapter/adapter-latest.js"></script>
<video id="video" height="120" width="160" autoplay></video><br>
<button id="call">Call!</button><br><div id="div"></div>
<script src="https://jan-ivar.github.io/localSocket/localSocket.js"></script>

JavaScript

let pc = new RTCPeerConnection();

call.onclick = async () => {
  video.srcObject = await navigator.mediaDevices.getUserMedia({video:true, audio:true});
  for (const track of video.srcObject.getTracks()) {
    pc.addTrack(track, video.srcObject);
  }
};

pc.ontrack = e => video.srcObject = e.streams[0];
pc.oniceconnectionstatechange = e => div.innerHTML += pc.iceConnectionState + "<br>";
pc.onicecandidate = ({candidate}) => sc.send({candidate});
pc.onnegotiationneeded = async e => {
  await pc.setLocalDescription(await pc.createOffer());
  sc.send({sdp: pc.localDescription});
}

var sc = new localSocket();
sc.onmessage = async ({data: {sdp, candidate}}) => {
  if (sdp) {
    await pc.setRemoteDescription(sdp);
    if (sdp.type == "offer") {
      await pc.setLocalDescription(await pc.createAnswer());
      sc.send({sdp: pc.localDescription});
    }
  } else if (candidate) await pc.addIceCandidate(candidate);
}