<!DOCTYPE HTML>
<html>
<head>
  <script type="application/javascript" src="pc.js"></script>
  <script type="application/javascript" src="/tests/dom/canvas/test/captureStream_common.js"></script>
  <script type="application/javascript" src="/tests/dom/canvas/test/webgl-mochitest/webgl-util.js"></script>
</head>
<body>
<pre id="test">
<script id="v-shader" type="x-shader/x-vertex">
  attribute vec2 aPosition;
  void main() {
   gl_Position = vec4(aPosition, 0, 1);
}
</script>
<script id="f-shader" type="x-shader/x-fragment">
  precision mediump float;
  uniform vec4 uColor;
  void main() { gl_FragColor = uColor; }
</script>
<script type="application/javascript">
createHTML({
  bug: "1032848",
  title: "Canvas(WebGL)::CaptureStream as video-only input to peerconnection"
});

runNetworkTest(async () => {
  // [TODO] re-enable HW decoder after bug 1526207 is fixed.
  if (navigator.userAgent.includes("Android")) {
    await pushPrefs(["media.navigator.mediadatadecoder_vpx_enabled", false],
                    ["media.webrtc.hw.h264.enabled", false]);
  }

  var test = new PeerConnectionTest();
  var vremote;
  var h = new CaptureStreamTestHelperWebGL();
  var canvas = document.createElement('canvas');
  canvas.id = 'source_canvas';
  canvas.width = canvas.height = 16;
  canvas.style.display = 'none';
  document.getElementById('content').appendChild(canvas);

  var gl = canvas.getContext('webgl');
  if (!gl) {
    todo(false, "WebGL unavailable.");
    networkTestFinished();
    return;
  }

  test.setMediaConstraints([{video: true}], []);
  test.chain.replace("PC_LOCAL_GUM", [
    function WEBGL_SETUP(test) {
      var program = WebGLUtil.createProgramByIds(gl, 'v-shader', 'f-shader');

      if (!program) {
        ok(false, "Program should link");
        return Promise.reject("Program should link");
      }
      gl.useProgram(program);

      var uColorLocation = gl.getUniformLocation(program, "uColor");
      h.setFragmentColorLocation(uColorLocation);

      var squareBuffer = gl.createBuffer();
      gl.bindBuffer(gl.ARRAY_BUFFER, squareBuffer);

      var vertices = [ 0,  0,
                      -1,  0,
                       0,  1,
                      -1,  1 ];
      gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);
      squareBuffer.itemSize = 2;
      squareBuffer.numItems = 4;

      program.aPosition = gl.getAttribLocation(program, "aPosition");
      gl.enableVertexAttribArray(program.aPosition);
      gl.vertexAttribPointer(program.aPosition, squareBuffer.itemSize, gl.FLOAT, false, 0, 0);
    },
    function PC_LOCAL_CANVAS_CAPTURESTREAM(test) {
      h.drawColor(canvas, h.green);
      test.pcLocal.canvasStream = canvas.captureStream(0.0);
      is(test.pcLocal.canvasStream.canvas, canvas, "Canvas attribute is correct");
      test.pcLocal.attachLocalStream(test.pcLocal.canvasStream);
      var i = 0;
      return setInterval(function() {
        try {
          info("draw " + i ? "green" : "red");
          h.drawColor(canvas, i ? h.green : h.red);
          i = 1 - i;
          test.pcLocal.canvasStream.requestFrame();
        } catch (e) {
          // ignore; stream might have shut down, and we don't bother clearing
          // the setInterval.
        }
      }, 500);
    }
  ]);
  test.chain.append([
    function FIND_REMOTE_VIDEO() {
      vremote = test.pcRemote.remoteMediaElements[0];
      ok(!!vremote, "Should have remote video element for pcRemote");
    },
    function WAIT_FOR_REMOTE_GREEN() {
      return h.pixelMustBecome(vremote, h.green, {
        threshold: 128,
        infoString: "pcRemote's remote should become green",
      });
    },
    function REQUEST_FRAME(test) {
      // After requesting a frame it will be captured at the time of next render.
      // Next render will happen at next stable state, at the earliest,
      // i.e., this order of `requestFrame(); draw();` should work.
      test.pcLocal.canvasStream.requestFrame();
    },
    function DRAW_LOCAL_RED() {
      h.drawColor(canvas, h.red);
    },
    function WAIT_FOR_REMOTE_RED() {
      return h.pixelMustBecome(vremote, h.red, {
        threshold: 128,
        infoString: "pcRemote's remote should become red",
      });
    }
  ]);
  await test.run();
});
</script>
</pre>
</body>
</html>
