<!DOCTYPE html>
<html>
<head><meta charset="UTF-8"></head>
<body>
<div id="message"></div>
<script>
// Specifies whether we are using fake streams to run this automation
var useFakeStreams = true;
try {
  var audioDevice = SpecialPowers.getCharPref("media.audio_loopback_dev");
  var videoDevice = SpecialPowers.getCharPref("media.video_loopback_dev");
  dump("TEST DEVICES: Using media devices:\n");
  dump("audio: " + audioDevice + "\nvideo: " + videoDevice + "\n");
  useFakeStreams = false;
} catch (e) {
  dump("TEST DEVICES: No test devices found (in media.{audio,video}_loopback_dev, using fake streams.\n");
  useFakeStreams = true;
}

function message(m) {
  // eslint-disable-next-line no-unsanitized/property
  document.getElementById("message").innerHTML += `${m}<br>`;
  window.parent.postMessage(m, "*");
}

var gStreams = [];

function requestDevice(aAudio, aVideo, aShare) {
  var opts = {video: aVideo, audio: aAudio};
  if (aShare) {
    opts.video = { mediaSource: aShare };
  } else if (useFakeStreams) {
    opts.fake = true;
  }

  window.navigator.mediaDevices.getUserMedia(opts)
    .then(stream => {
      gStreams.push(stream);
      message("ok");
    }, err => message("error: " + err));
}
message("pending");

function stopTracks(aKind) {
  for (let stream of gStreams) {
    for (let track of stream.getTracks()) {
      if (track.kind == aKind) {
        track.stop();
        stream.removeTrack(track);
      }
    }
  }
  gStreams = gStreams.filter(s => !!s.getTracks().length);
}

function closeStream() {
  for (let stream of gStreams) {
    for (let track of stream.getTracks()) {
      track.stop();
    }
  }
  gStreams = [];
  message("closed");
}
</script>
<iframe id="frame1" allow="camera;microphone;display-capture" src="https://test1.example.com/browser/browser/base/content/test/webrtc/get_user_media.html"></iframe>
<iframe id="frame2" allow="camera;microphone" src="https://test1.example.com/browser/browser/base/content/test/webrtc/get_user_media.html"></iframe>
<iframe id="frame3" src="https://test1.example.com/browser/browser/base/content/test/webrtc/get_user_media.html"></iframe>
<iframe id="frame4" allow="camera *;microphone *;display-capture *" src="https://test1.example.com/browser/browser/base/content/test/webrtc/get_user_media.html"></iframe>
</body>
</html>
