<!doctype html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Testing video being updated and changed often</title>
        <script src="../resources/gc.js"></script>
        <script src="../resources/testharness.js"></script>
        <script src="../resources/testharnessreport.js"></script>
    </head>
    <body>
        <video id="video" autoplay=""></video>
        <script src ="routines.js"></script>
        <script>
video = document.getElementById("video");
var counter =0;
var resolveFunction;

async function updateVideoElement()
{
    await video.play();
    if (++counter >= 4) {
        video.srcObject = null;
        document.body.removeChild(video);
        resolveFunction();
        return;
    }

    document.body.removeChild(video);
    video.srcObject = null;
    video = document.createElement('video');
    video.setAttribute("id", "video");
    video.autoplay = true;
    video.srcObject = await navigator.mediaDevices.getUserMedia({audio: true, video: true});
    document.body.appendChild(video);
    if (window.gc)
        gc();
    setTimeout(updateVideoElement, 0);
}

promise_test((test) => {
    if (window.testRunner)
        testRunner.setUserMediaPermission(true);

    return navigator.mediaDevices.getUserMedia({audio: true, video: true}).then((stream) => {
        video.srcObject = stream;
        return video.play();
    }).then(async () => {
        await new Promise((resolve) => {
            resolveFunction = resolve;
            updateVideoElement();
        });
    });
}, "Video element being updated did not crash");
        </script>
    </body>
</html>
