Screensharing applyConstraints

by munrochiang

HTML

<button id="b1" onclick="apply(160,120)">160</button>
<button id="b2" onclick="apply(320,240)">320</button>
<button id="b3" onclick="apply(640,480)">640</button>
<button id="b4" onclick="apply(1280,720)">1280</button>
<button id="b5" onclick="apply(1980,1024)">1980</button>
<button id="b6" onclick="apply(2880,1800)">2880</button>
<div id="div2"><p>0 x 0 x 0.0</p></div>
<video id="video" autoplay></video><br><div id="div"></div>

JavaScript

let gUM = c => navigator.mediaDevices.getUserMedia(c);

(async () => {
  try {
    video.srcObject = await gUM({video: true});
    await new Promise(resolve => video.onloadedmetadata = resolve);
  } catch(e) {
    failed(e);
  }

  let t1 = video.currentTime, f1 = video.mozPaintedFrames, t2, f2;
  while (true) {
    await wait(1000);
    t2 = video.currentTime; f2 = video.mozPaintedFrames;
    let hz = (f2 - f1) / (t2 - t1), v = video;
    update(`${v.videoWidth} x ${v.videoHeight} x ${hz.toFixed(2)}`);
    t1 = t2; f1 = f2;
  }
})().catch(failed);

var apply = async (width, height)  => {
  try {
    let track = video.srcObject.getVideoTracks()[0];
    await track.applyConstraints({width, height});
    log(`Applied ${width} x ${height}`);
  } catch(e) {
    failed(e);
  }
};

var wait = ms => new Promise(resolve => setTimeout(resolve, ms));
var log = msg => div.innerHTML += "<p>" + msg + "</p>";
var update = msg => div2.innerHTML = "<p>" + msg + "</p>";
var failed = e => log(e +" constraint="+ e.constraint);