<!doctype html><!-- webkit-test-runner [ RequestVideoFrameCallbackEnabled=true ] -->
<html>
    <head>
        <meta charset="utf-8">
        <title>Testing rvfc on peer connection streams</title>
        <script src="../resources/testharness.js"></script>
        <script src="../resources/testharnessreport.js"></script>
        <script src="routines.js"></script>
    </head>
    <body>
        <video id="video" autoplay=""></video>
        <script>
async function grabNextMetadata(video)
{
    return new Promise((resolve, reject) => {
        const identifier = video.requestVideoFrameCallback((now, metadata) => {
            resolve(metadata);
        });
        setTimeout(() => reject("Timed out metadata"), 5000);
    });
}

promise_test(async (test) => {
    const localStream = await navigator.mediaDevices.getUserMedia({video: { width: 640, height: 480 } });
    const remoteStream = await new Promise((resolve, reject) => {
        createConnections((firstConnection) => {
            pc1 = firstConnection;
            const sender = firstConnection.addTrack(localStream.getVideoTracks()[0], localStream);
        }, (secondConnection) => {
            pc2 = secondConnection;
            secondConnection.ontrack = (trackEvent) => {
                resolve(trackEvent.streams[0]);
            };
        });
        setTimeout(() => reject("Test timed out"), 5000);
    });

    video.srcObject = remoteStream;
    await video.play();

    let metadata = await grabNextMetadata(video);
    assert_equals(metadata.width, 640);
    assert_equals(metadata.height, 480);
    assert_greater_than(metadata.presentedFrames, 0);
    const presentedFrames = metadata.presentedFrames;

    await localStream.getVideoTracks()[0].applyConstraints({width: 320});

    let counter = 0;
    while (++counter < 100 && metadata.width !== 320) {
        await new Promise(resolve => setTimeout(resolve, 50));
        metadata = await grabNextMetadata(video);
    }
    assert_equals(metadata.width, 320);
    assert_greater_than(metadata.presentedFrames, presentedFrames);
    assert_greater_than(metadata.processingDuration, 0);
}, "Validate callbacks and metadata for peer connection tracks");
        </script>
    </body>
</html>
