Modern WebRTC offerToReceive

by jib1

HTML

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

JavaScript

var pc1 = new RTCPeerConnection(), pc2 = new RTCPeerConnection();

var haveGum = navigator.mediaDevices.getUserMedia({video: true, audio: true});

pc1.ontrack = e => video1.srcObject = e.streams[0];
pc1.onicecandidate = e => pc2.addIceCandidate(e.candidate).catch(log);
pc2.onicecandidate = e => pc1.addIceCandidate(e.candidate).catch(log);
pc1.oniceconnectionstatechange = e => log(pc1.iceConnectionState);

pc1.createOffer({offerToReceiveAudio: true, offerToReceiveVideo: true})
  .then(d => pc1.setLocalDescription(d))
  .then(() => pc2.setRemoteDescription(pc1.localDescription))
  .then(() => haveGum)
  .then(stream => pc2.addStream(video2.srcObject = stream))
  .then(() => pc2.createAnswer()).then(d => pc2.setLocalDescription(d))
  .then(() => pc1.setRemoteDescription(pc2.localDescription))
  .catch(log);

var log = msg => div.innerHTML += "<br>" + msg;