<!DOCTYPE html>
<html>
    <head>
        <script src="../../resources/js-test-pre.js"></script>
        <script>
            let tabState;
            let streamCount = 4;
            let streams = 0;

            function gotStream(s)
            {
                debug('<br>** getUserMedia() promise resolved **')
                shouldBe('tabState', "'foreground'");
                stream = s;
                shouldBe('stream.getAudioTracks().length', '1');
                if (++streams == streamCount)
                    finishJSTest();
            }

            function fail(error)
            {
                testFailed(`getUserMedia() failed, error = ${error}`);
                finishJSTest();
            }

            function checkState()
            {
                debug('<br>** timer fired **')
                shouldBe('tabState', "'background'");
                evalAndLog(`tabState = 'foreground'`);
                if (internals)
                    internals.settings.setCanStartMedia(true);
            }

            function start()
            {
                description("Tests getUserMedia called from a background thread.");
                evalAndLog(`tabState = 'background'`);
                if (window.testRunner) {
                    internals.settings.setCanStartMedia(false);
                    testRunner.setUserMediaPermission(true);
                }
                for (var i = 0; i < streamCount; i++)
                    shouldNotThrow('navigator.mediaDevices.getUserMedia({audio:true}).then(gotStream).catch(fail)');
                setTimeout(checkState, 200);
            }

            window.jsTestIsAsync = true;
            window.successfullyParsed = true;

        </script>
        <script src="../../resources/js-test-post.js"></script>
    </head>
    <body onload="start()">
    </body>
</html>
