LoginSignup
28
17

More than 1 year has passed since last update.

WebRTCでビデオ通話中に映像の解像度やフレームレートを動的に変更する方法

Last updated at Posted at 2020-10-29

はじめに

WebブラウザでWebRTCによるビデオ通話を行う際は、getUserMediaで映像と音声を取得します。その際に、constraintsで制約条件を設定します。

この制約条件は一度設定したら変更出来ないと思っている方もいるかも知れませんが、実は柔軟に変更できるように、applyConstraintsというAPIが用意されています。このAPIを使うと、ビデオ通話中でも通話を途切れさせること無く映像や音声の制約条件を変更できます。例えば、通信状況が悪い時は解像度やフレームレートを小さく設定し、帯域を削減する等の機能を実装することが出来ます。

小ネタですが、便利なので紹介します。

applyConstraintsでconstraintsを柔軟に変更する

getUserMediaで以下のようにconstraintsを指定してMediaStreamを取得します。

const localStream = await navigator.mediaDevices
.getUserMedia({
  audio: true,
  video: {
    width: {ideal: width.value},
    height: {ideal: height.value},
    frameRate: {ideal: frameRate.value},
  }
})
.catch(console.error);

このlocalStreamを使ったビデオ通話を実施中に、以下のようにトラック毎に制約条件を再設定することが出来ます。以下の例では、ビデオの解像度、フレームレートを変更しています。

function applyConstraints() {
  let videoTrack = localStream.getVideoTracks()[0];
  let currentConstraints = videoTrack.getConstraints();
  console.log('変更前の値:', currentConstraints);
  videoTrack.applyConstraints({
    width: {ideal: width.value},
    height: {ideal: height.value},
    frameRate: {ideal: frameRate.value}
  })
  .then(() => {
    currentConstraints = videoTrack.getConstraints();
    console.log('変更後の値:', currentConstraints);
  })
  .catch(e => {
    console.log('制約を設定できませんでした:', e);
  });
}

コードの中で利用している、getConstraintsは現在の制約条件を取得するためのものです。applyConstraintsと組み合わせて利用するのが良いのではないでしょうか。

尚、constraintsはメディアの種類(VideoかAudioか)やブラウザによって指定できる項目が変わってきます。プログラム中で動的に設定させる場合は、該当の項目が存在しない場合の例外処理も行いましょう。getSupportedConstraintsで調べることが出来ます。

let supported = navigator.mediaDevices.getSupportedConstraints();
console.log(supported);

出力結果(Chrome M86)

aspectRatio: true,
autoGainControl: true,
brightness: true,
channelCount: true,
colorTemperature: true,
contrast: true,
deviceId: true,
echoCancellation: true,
exposureCompensation: true,
exposureMode: true,
exposureTime: true,
facingMode: true,
focusDistance: true,
focusMode: true,
frameRate: true,
groupId: true,
height: true,
iso: true,
latency: true,
noiseSuppression: true,
pan: true,
pointsOfInterest: true,
resizeMode: true,
sampleRate: true,
sampleSize: true,
saturation: true,
sharpness: true,
tilt: true,
torch: true,
videoKind: true,
whiteBalanceMode: true,
width: true,
zoom: true

余談ですが、Firefoxは昔からframeRateの指定ができません。getSupportedConstraintsでtrueが返ってきますが、指定しても動きません。罠ですね。

デモ

SkyWayで簡単なデモを作ってみました。room join後に解像度とフレームレートを変更できます。
https://codepen.io/yusuke84/pen/xxOVbVG

終わりに

applyConstraintsを始めとするMedia Stream APIの制約条件設定に関しては、MDNに最高のドキュメントがあるので、実装する方は一度読んでみてください。

能力、制約、そして設定
https://developer.mozilla.org/ja/docs/Web/API/Media_Streams_API/Constraints

28
17
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
28
17