<!DOCTYPE HTML>
<html>
<head>
  <script type="application/javascript" src="pc.js"></script>
  <script type="application/javascript" src="simulcast.js"></script>
  <script type="application/javascript" src="helpers_from_wpt/sdp.js"></script>
</head>
<body>
<pre id="test">
<script type="application/javascript">
createHTML({
  bug: "1401592",
  title: "Simulcast negotiation tests",
  visible: true
});

// simulcast negotiation is mostly tested in wpt, but we test a few
// implementation-specific things here.
const tests = [
  async function checkVideoEncodingLimit() {
    const pc1 = new RTCPeerConnection();
    const pc2 = new RTCPeerConnection();

    const stream = await navigator.mediaDevices.getUserMedia({video: true});
    const sender = pc1.addTrack(stream.getTracks()[0]);
    pc2.addTrack(stream.getTracks()[0]);

    await doOfferToRecvSimulcast(pc2, pc1, ["1", "2", "3", "4"]);

    const {encodings} = sender.getParameters();
    const rids = encodings.map(({rid}) => rid);
    isDeeply(rids, ["1", "2", "3"]);

    pc1.close();
    pc2.close();
    stream.getTracks().forEach(track => track.stop());
  },

  // wpt currently does not assume support for 3 encodings, which limits the
  // effectiveness of its powers-of-2 test (since it can test only for 1 and 2)
  async function checkScaleResolutionDownByAutoFillPowersOf2() {
    const pc1 = new RTCPeerConnection();
    const pc2 = new RTCPeerConnection();
    const stream = await navigator.mediaDevices.getUserMedia({video: true});
    const sender = pc1.addTrack(stream.getTracks()[0]);
    pc2.addTrack(stream.getTracks()[0]);

    await doOfferToRecvSimulcast(pc2, pc1, ["1", "2", "3"]);

    const {encodings} = sender.getParameters();
    const scaleValues = encodings.map(({scaleResolutionDownBy}) => scaleResolutionDownBy);
    isDeeply(scaleValues, [4, 2, 1]);
  },

  async function checkLibwebrtcRidLengthLimit() {
    const pc1 = new RTCPeerConnection();
    const pc2 = new RTCPeerConnection();

    const stream = await navigator.mediaDevices.getUserMedia({video: true});
    const sender = pc1.addTrack(stream.getTracks()[0]);
    pc2.addTrack(stream.getTracks()[0]);

    await doOfferToRecvSimulcast(pc2, pc1, ["foo", "wibblywobblyjeremybearimy"]);
    const {encodings} = sender.getParameters();
    const rids = encodings.map(({rid}) => rid);
    isDeeply(rids, ["foo"]);

    pc1.close();
    pc2.close();
    stream.getTracks().forEach(track => track.stop());
  },
];

runNetworkTest(async () => {
  for (const test of tests) {
    info(`Running test: ${test.name}`);
    await test();
    info(`Done running test: ${test.name}`);
  }
});

</script>
</pre>
</body>
</html>
