<!DOCTYPE html>
<html>
    <head>
        <video id="video" width=480px height=480px controls ></video>
        <canvas id="canvas" width=640px height=480px></canvas>
        <script src="../../resources/testharness.js"></script>
        <script src="../../resources/testharnessreport.js"></script>
        <script src="../../resources/platform-helper.js"></script>
        <script>

const canvas = document.getElementById("canvas");
const video = document.getElementById("video");

function logPixel(name, pixel)
{
    console.log(`${name}: ${pixel[0]}, ${pixel[1]}, ${pixel[2]}, ${pixel[3]}`);
}

function checkCanvas(canvas, stream)
{
    return new Promise((resolve, reject) => {
        video.srcObject = stream;
        video.oncanplay = () => {
            const ctx = canvas.getContext("2d");
            ctx.drawImage(video, 0 ,0);

            try {
                setTimeout(() => {
                    assert_false(isPixelBlack(ctx.getImageData(5, 5, 1, 1).data), "Pixel at 5x5 is not black.");
                    assert_false(isPixelBlack(ctx.getImageData(50, 200, 1, 1).data), "Pixel at 50x200 is not black.");
                    resolve();
                }, 500);
            } catch(err) {
                reject(err);
                return;
            }
        }
    });
}

promise_test(async () => {
    let stream = await navigator.mediaDevices.getUserMedia({ video: true });
    stream = null;

    const devices = await navigator.mediaDevices.enumerateDevices();
    let cameraID = undefined;
    devices.forEach(device => { if (device.label == "Mock video device 2") cameraID = device.deviceId; });
    assert_true(cameraID !== undefined, "Found camera2");
    
    stream = await navigator.mediaDevices.getUserMedia({ video: { deviceId: { exact: cameraID } } });
    
    return checkCanvas(canvas, stream);

}, "A frame from the camera is shown before playback begins.");

        </script>
    </head>
</html>
