Async WebRTC legacy Demo

by jib1

HTML

<video id="video1" height="120" width="160" autoplay muted></video>
<video id="video2" height="120" width="160" autoplay></video><br>
<div id="div"></div>
<script src="https://webrtc.github.io/adapter/adapter-latest.js"></script>

JavaScript

var console = { log: msg => div.innerHTML += msg + "<br>" };
let pc1 = new RTCPeerConnection(), pc2 = new RTCPeerConnection();

(async () => {
  try {
    let stream = await navigator.mediaDevices.getUserMedia({video: true, audio: true});
    for (let track of stream.getTracks()) {
      pc1.addTrack(track, stream);
    }
    video1.srcObject = stream;
  } catch (e) {
    console.log(e);
  }
})();

pc1.onicecandidate = e => pc2.addIceCandidate(e.candidate);
pc2.onicecandidate = e => pc1.addIceCandidate(e.candidate);
pc1.oniceconnectionstatechange = e => console.log(pc1.iceConnectionState);

pc1.onnegotiationneeded = async e => {
  try {
    const offer = await new Promise((r, e) => pc1.createOffer(r, e));
    await new Promise((r, e) => pc1.setLocalDescription(offer, r, e));
    await new Promise((r, e) => pc2.setRemoteDescription(pc1.localDescription, r, e));
    const answer = await new Promise((r, e) => pc2.createAnswer(r, e));
    await new Promise((r, e) => pc2.setLocalDescription(answer, r, e));
    await new Promise((r, e) => pc1.setRemoteDescription(pc2.localDescription, r, e));
  } catch (e) {
    console.log(e);
  }
}
pc2.ontrack = e => video2.srcObject = e.streams[0];