<!DOCTYPE html>
<html>
<head>
    <title>audio-session-category-track-change</title>
    <script src="../../../../media/video-test.js"></script>
    <script src="../../../../media/media-source/media-source-loader.js"></script>
    <script>
    mediaElement = video = document.createElement('video');

    loader = new MediaSourceLoader('../../../../media/media-source/content/test-fragmented-manifest.json', '../../../../media/media-source/');
    loader.onerror = () => {
        failTest('Media data loading failed');
    };

    loader.onload = () => {
        source = new MediaSource();
        waitForEvent('sourceopen', sourceOpen, false, false, source);
        waitForEventAndFail('error');
        run('video.src = URL.createObjectURL(source)');
    }

    function sourceOpen() {
        run('source.duration = loader.duration()');
        run('sourceBuffer = source.addSourceBuffer(loader.type())');
        waitForEventOn(sourceBuffer, 'update', sourceInitialized, false, true);
        run('sourceBuffer.appendBuffer(loader.initSegment())');
    }

    function sourceInitialized() {
        waitForEventOn(sourceBuffer, 'update', mediaSegmentAppended, false, true);
        run('sourceBuffer.appendBuffer(loader.mediaSegment(0))');
    }

    function mediaSegmentAppended() {
        waitForEventOn(video, 'resize', videoFrameAvailable, false, true);
    }

    function videoFrameAvailable() {
        run('canvas = document.createElement("canvas")');
        run('gl = canvas.getContext("webgl")');
        run('texture = gl.createTexture()');
        run('gl.bindTexture(gl.TEXTURE_2D, texture)');
        run('gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR)');
        run('gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR)');
        run('gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE)');
        run('gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE)');
        run('gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, video)');
        run('video.play()');
        consoleWrite('Wait for currentTime to advance beyond 0s.');
        video.addEventListener('timeupdate', timeupdate);
    }

    async function timeupdate() {
        if (video.currentTime == 0)
            return;

        // There could be a delay that a video element gets the VideoPlaybackQualityMetrics
        // from its media player (refer to RemoteMediaPlayerProxy::startUpdateCachedStateMessageTimer()).
        consoleWrite('EVENT(timeupdate)');
        await testExpectedEventually('video.getVideoPlaybackQuality().totalVideoFrames', '0', '>');
        endTest();
    }

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