<body>
<video id="localVideo" autoplay playsInline></video>
<script src="../../resources/testharness.js"></script>
<script src="../../resources/testharnessreport.js"></script>
<script>

promise_test(async() => {
    if (!window.internals)
       return Promise.reject("Test requires internals API");

    if (!window.internals.supportsAudioSession)
        return;

    internals.settings.setShouldManageAudioSessionCategory(true);

    const defaultCategory = internals.audioSessionCategory();

    let stream = await navigator.mediaDevices.getUserMedia({audio : true});

    localVideo.srcObject = stream;
    await localVideo.play();

    assert_equals(internals.audioSessionCategory(), "PlayAndRecord");

    stream.getAudioTracks()[0].enabled = false;
    await new Promise(resolve => setTimeout(resolve, 10));
    assert_equals(internals.audioSessionCategory(), "PlayAndRecord");

    const audioTrack = stream.getAudioTracks()[0];
    stream.removeTrack(audioTrack);
    await new Promise(resolve => setTimeout(resolve, 10));
    assert_equals(internals.audioSessionCategory(), "PlayAndRecord");

    audioTrack.stop();
    const maxTries = 300;
    let counter = 0;
    while (++counter < maxTries) {
        if (internals.audioSessionCategory() == defaultCategory)
            break;
        await new Promise(resolve => setTimeout(resolve, 10));
    }
    assert_less_than(counter, maxTries);
    assert_equals(internals.audioSessionCategory(), defaultCategory);
}, "Check audio session state in case of disabled and stopped audio tracks");
</script>
</body>
