<!doctype html>
<html>
<head>
    <script src="../resources/testharness.js"></script>
    <script src="../resources/testharnessreport.js"></script>
</head>
<body>
<script type="application/javascript">
window.onunhandledrejection = () => false;
promise_test(async (test) => {
    const sender = new RTCPeerConnection();
    const receiver = new RTCPeerConnection();
    try {
        const stream = await navigator.mediaDevices.getUserMedia({ audio: true, video: true });
        const localTracks = stream.getTracks();
        [[sender, receiver], [receiver, sender]].forEach(([pc1, pc2]) => {
            pc1.onicecandidate = ({ candidate }) => {
                if (candidate)
                    pc2.addIceCandidate(candidate).then(() => { }, () => { });
                pc1.close();
            };
        });
        localTracks.forEach(track => sender.addTrack(track, stream));
        receiver.addTransceiver('audio');
        receiver.addTransceiver('video');
        await new Promise (async (resolve) => {
            // RTCPeerConnection does not resolve promises when it gets closed, hence the timeout here to make sure we execute some if not all these operations.
            test.step_timeout(resolve, 100);
            try {
                const offer1 = await sender.createOffer();
                await sender.setLocalDescription(offer1);
                await receiver.setRemoteDescription(offer1);
                const answer1 = await receiver.createAnswer();
                await receiver.setLocalDescription(answer1);
                await sender.setRemoteDescription(answer1);
                const offer2 = await sender.createOffer();
                await sender.setLocalDescription(offer2);
                await receiver.setRemoteDescription(offer2);
                const answer2 = await receiver.createAnswer();
                await receiver.setLocalDescription(answer2);
                await sender.setRemoteDescription(answer2);
            } finally {
                resolve();
            }
        });
    } catch (e) {
    }
}, "Close a peer connection in the middle of gathering");
</script>
</body>
</html>
