Async WebRTC canvas

by jib1

HTML

<video id="video" width="160" height="120" autoplay></video><br>
<button id="button">Start</button>
<div id="div"></div>

JavaScript

const console = {log: msg => div.innerHTML += `${msg}<br>`};
const pc1 = new RTCPeerConnection(), pc2 = new RTCPeerConnection();

(async () => {
  try {
    const stream = whiteNoise();
    pc1.addTrack(stream.getTracks()[0], stream);
    const {track, streams} = await new Promise(r => pc2.ontrack = r);
    track.onunmute = () => {
      console.log("HERE");
      video.srcObject = streams[0];
    };
  } 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 {
    await pc1.setLocalDescription(await pc1.createOffer());
    await pc2.setRemoteDescription(pc1.localDescription);
    await pc2.setLocalDescription(await pc2.createAnswer());
    await pc1.setRemoteDescription(pc2.localDescription);
  } catch(e) {
    console.log(e);
  }
}

function whiteNoise(width = 160, height = 120) {
  const canvas = Object.assign(document.createElement("canvas"), {width, height});
  const ctx = canvas.getContext('2d');
  button.onclick = () => requestAnimationFrame(function draw(){
    ctx.fillRect(0, 0, width, height);
    const d = ctx.getImageData(0, 0, width, height);
    for (let i = 0; i < d.data.length; i++) {
      d.data[i++] = d.data[i++] = d.data[i++] = Math.random() * 255;
    }
    ctx.putImageData(d, 0, 0);
    requestAnimationFrame(draw);
  });
  return canvas.captureStream();
};