WebRTC getStats dump

by jib1

HTML

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

CSS

body { white-space: pre; font-family: monospace; }

JavaScript

const console = { log: msg => div.innerHTML += msg + "<br>" };
const wait = ms => new Promise(resolve => setTimeout(resolve, ms));
const pc1 = new RTCPeerConnection(), pc2 = new RTCPeerConnection();

(async () => {
  const stream = await navigator.mediaDevices.getUserMedia({video: true, audio: true});
  for (const track of stream.getTracks()) {
    pc1.addTrack(track, stream);
  }
  video1.srcObject = stream;
  video2.srcObject = (await new Promise(r => pc2.ontrack = r)).streams[0];
  const p = new Promise(r => video2.srcObject.getVideoTracks()[0].onunmute = r);
  const connected = pc => pc.iceConnectionState == "connected";
  await Promise.all([pc1, pc2].map(
    pc => new Promise(r => pc.oniceconnectionstatechange = () => connected(pc) && r())
  ));
  await p;

  // comment out this line to see rtp stats immediately
  console.log("wait 5 seconds for rtcp packets..."); await wait(5000);

  const statsPair = await Promise.all([pc1, pc2].map(pc => pc.getStats()));
  for (const stats of statsPair) {
    for (const stat of stats.values()) {
      console.log(JSON.stringify(stat, null, 2));
    }
  }
})();

pc1.onicecandidate = e => pc2.addIceCandidate(e.candidate);
pc2.onicecandidate = e => pc1.addIceCandidate(e.candidate);

pc1.onnegotiationneeded = async () => {
  try {
    await pc1.setLocalDescription();
    await pc2.setRemoteDescription(pc1.localDescription);
    await pc2.setLocalDescription();
    await pc1.setRemoteDescription(pc2.localDescription);
  } catch (e) {
    console.log(e);
  }
}