<!DOCTYPE HTML>
<html>
<head>
  <script type="application/javascript" src="pc.js"></script>
  <script type="application/javascript" src="stats.js"></script>
</head>
<body>
<pre id="test">
<script type="application/javascript">
  createHTML({
    bug: "1355220",
    title: "RTCRtpSender.getStats() and RTCRtpReceiver.getStats()",
    visible: true
  });

  const checkStats = (sndReport, rcvReport, kind) => {
    ok(sndReport instanceof window.RTCStatsReport, "sender stats are a RTCStatsReport");
    ok(rcvReport instanceof window.RTCStatsReport, "receiver stats are a RTCStatsReport");
    // Returns SSRCs and performs some checks
    let getSsrcs = (report, kind) => {
      return [...report.values()]
        .filter(stat => stat.type.endsWith("bound-rtp")).map(stat =>{
          isnot(parseInt(stat.id, 16), NaN,
            `id ${stat.id} is an opaque (hex) number`);
          is(stat.kind, kind, "kind of " + stat.id
              + " is expected type " + kind);
          return stat.ssrc;
      }).sort().join("|");
    };
    let sndSsrcs = getSsrcs(sndReport, kind);
    let rcvSsrcs = getSsrcs(rcvReport, kind);
    ok(sndSsrcs, "sender SSRCs is not empty");
    ok(rcvSsrcs, "receiver SSRCs is not empty");
    is(sndSsrcs, rcvSsrcs, "sender SSRCs match receiver SSRCs");
  };

  // This MUST be run after PC_*_WAIT_FOR_MEDIA_FLOW to ensure that we have RTP
  // before checking for RTCP.
  // It will throw UnsyncedRtcpError if it times out waiting for sync.

  runNetworkTest(function (options) {
    test = new PeerConnectionTest(options);
    test.chain.insertAfter("PC_REMOTE_WAIT_FOR_MEDIA_FLOW",
      async function PC_LOCAL_AND_REMOTE_CHECK_SENDER_RECEIVER_STATS(test) {
        await Promise.all([
          waitForSyncedRtcp(test.pcLocal._pc),
          waitForSyncedRtcp(test.pcRemote._pc),
        ]);
        let senders = test.pcLocal.getSenders();
        let receivers = test.pcRemote.getReceivers();
        is(senders.length, 2, "Have exactly two senders.");
        is(receivers.length, 2, "Have exactly two receivers.");
        for(let kind of ["audio", "video"]) {
          let senderStats =
              await senders.find(s => s.track.kind == kind).getStats();
          is(senders.filter(s => s.track.kind == kind).length, 1,
              "Exactly 1 sender of kind " + kind);
          let receiverStats =
              await receivers.find(r => r.track.kind == kind).getStats();
          is(receivers.filter(r => r.track.kind == kind).length, 1,
              "Exactly 1 receiver of kind " + kind);

          checkStats(senderStats, receiverStats, kind);
        }
      }
    );
    test.setMediaConstraints([{audio: true}, {video: true}], []);
    return test.run();
  });
</script>
</pre>
</body>
</html>
