Mozilla's getting a new look. What do you think? https://mzl.la/brandsurvey

RTCPeerConnection

この翻訳は不完全です。英語から この記事を翻訳 してください。

これは実験段階の機能です。
この機能は複数のブラウザで開発中の状態にあります。各ブラウザで用いるために、適切なベンダー接頭辞が必要な場合があります。互換性テーブルをチェックしてください。また、実験段階の機能の構文と挙動は、仕様変更に伴い各ブラウザの将来のバージョンで変更になる可能性があることに注意してください。

RTCPeerConnection インタフェースはローカルコンピュータとリモートピア間のWebRTC コネクションを表現します。二つのピア間の効果的なデータストリーミングに用いられれます。

注釈: RTCPeerConnection と RTCSessionDescription は多くのブラウザでプレフィックスが付いており、navigator.getUserMedia() メソッドもいくつかのブラウザの多くのバージョンでプレフィックスが付いています。これらにアクエスする際は、次のようなコードを用いるべきでしょう。

var peerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || 
                       window.webkitRTCPeerConnection || window.msRTCPeerConnection;
var sessionDescription = window.RTCSessionDescription || window.mozRTCSessionDescription ||
                       window.webkitRTCSessionDescription || window.msRTCSessionDescription;

navigator.getUserMedia = navigator.getUserMedia || navigator.mozGetUserMedia ||
                       navigator.webkitGetUserMedia || navigator.msGetUserMedia;

このようにシンプルなコードによって、あなたのプロジェクトは多くのバージョンの多くのブラウザーで可能な限り動作することでしょう。

基本的な利用方法

基本的な RTCPeerConnection の使い方では、あなたのローカルマシンとリモートマシン間のコネクションのネゴシエーションするために、生成したSession Description Protocolを2点間で交換することです。呼び出し側は、リモートマシンにオファーを送信して処理を開始し、リモートマシンはその呼び出しを受理するか拒否します。

2つのパーティは(呼び出し側と被呼び出し側のパーティ) はそれぞれ自身の RTCPeerConnection インスタンスをセットアップして、ピア・ツー・ピア コネクションの末端を表現する必要があります。

var pc = new RTCPeerConnection();
pc.onaddstream = function(obj) {
  var vid = document.createElement("video");
  document.appendChild(vid);
  vid.srcObject = obj.stream;
}

// Helper functions
function endCall() {
  var videos = document.getElementsByTagName("video");
  for (var i = 0; i < videos.length; i++) {
    videos[i].pause();
  }

  pc.close();
}

function error(err) {
  endCall();
}

呼び出しの初期化

If you are the one initiating the call, you would use navigator.getUserMedia() to get a video stream, then add the stream to the RTCPeerConnection. Once that's been done, call RTCPeerConnection.createOffer() to create an offer, configure the offer, then send it to the server through which the connection is being mediated.

// Get a list of friends from a server
// User selects a friend to start a peer connection with
navigator.getUserMedia({video: true}, function(stream) {
  // Adding a local stream won't trigger the onaddstream callback,
  // so call it manually.
  pc.onaddstream({stream: stream});
  pc.addStream(stream);

  pc.createOffer(function(offer) {
    pc.setLocalDescription(new RTCSessionDescription(offer), function() {
      // send the offer to a server to be forwarded to the friend you're calling.
    }, error);
  }, error);
});

呼び出しの応答

On the opposite end, the friend will receive the offer from the server using whatever protocol is being used to do so. Once the offer arrives, navigator.getUserMedia() is once again used to create the stream, which is added to theRTCPeerConnection. An RTCSessionDescription object is created and set up as the remote description by calling RTCPeerConnection.setRemoteDescription().

Then an answer is created using RTCPeerConnection.createAnswer() and sent back to the server, which forwards it to the caller.

var offer = getOfferFromFriend();
navigator.getUserMedia({video: true}, function(stream) {
  pc.onaddstream({stream: stream});
  pc.addStream(stream);

  pc.setRemoteDescription(new RTCSessionDescription(offer), function() {
    pc.createAnswer(function(answer) {
      pc.setLocalDescription(new RTCSessionDescription(answer), function() {
        // send the answer to a server to be forwarded back to the caller (you)
      }, error);
    }, error);
  }, error);
});

応答のハンドリング

Back on the original machine, the response is received. Once that happens, call RTCPeerConnection.setRemoteDescription() to set the response as the remote end of the connection.

// pc was set up earlier when we made the original offer
var offer = getResponseFromFriend();
pc.setRemoteDescription(new RTCSessionDescription(offer), function() { }, error);

プロパティ

This interface inherits properties from its parent interface, EventTarget.

RTCPeerConnection.iceConnectionState 読取専用
Returns an enum of type RTCIceConnectionState that describes the ICE connection state for the connection. When this value changes, a iceconnectionstatechange event is fired on the object. The possible values are:
  • "new": the ICE agent is gathering addresses or waiting for remote candidates (or both).
  • "checking": the ICE agent has remote candidates, on at least one component, and is check them, though it has not found a connection yet. At the same time, it may still be gathering candidates.
  • "connected": the ICE agent has found a usable connection for each component, but is still testing more remote candidates for a better connection. At the same time, it may still be gathering candidates.
  • "completed": the ICE agent has found a usable connection for each component, and is no more testing remote candidates.
  • "failed": the ICE agent has checked all the remote candidates and didn't find a match for at least one component. Connections may have been found for some components.
  • "disconnected": liveness check has failed for at least one component. This may be a transient state, e. g. on a flaky network, that can recover by itself.
  • "closed": the ICE agent has shutdown and is not answering to requests.
RTCPeerConnection.iceGatheringState 読取専用
Returns an enum of type RTCIceGatheringState that describes the ICE gathering state for the connection. The possible values are:
  • "new": the object was just created, and no networking has occurred yet.
  • "gathering": the ICE engine is in the process of gathering candidates for this connection.
  • "complete": the ICE engine has completed gathering. Events such as adding a new interface or a new TURN server will cause the state to go back to gathering.
RTCPeerConnection.localDescription 読取専用
Returns a RTCSessionDescription describing the session for the local end of the connection. If it has not yet been set, it can be null.
RTCPeerConnection.peerIdentity 読取専用
Returns a RTCIdentityAssertion, that is a couple of a domain name (idp) and a name (name) representing the identity of the remote peer of this connection, once set and verified. If no peer has yet been set and verified, this property will return null. Once set, via the appropriate method, it can't be changed.
RTCPeerConnection.remoteDescription 読取専用
Returns a RTCSessionDescription describing the session for the remote end of the connection. If it has not yet been set, it can be null.
RTCPeerConnection.signalingState 読取専用
Returns an enum of type RTCSignalingState that describes the signaling state of the local connection. This state describes the SDP offer, that defines the configuration of the connections like the description of the locally associated objects of type MediaStream, the codec/RTP/RTCP options, the candidates gathered by the ICE Agent. When this value changes, a signalingstatechange event is fired on the object. The possible values are:
  • "stable": there is no SDP offer/answer exchange in progress. This is also the initial state of the connection.
  • "have-local-offer": the local end of the connection has locally applied a SDP offer.
  • "have-remote-offer": the remote end of the connection has locally applied a SDP offer.
  • "have-local-pranswer": a remote SDP offer has been applied, and a SDP pranswer applied locally.
  • "have-remote-pranswer": a local SDP offer has been applied, and a SDP pranswer applied remotely.
  • "closed": the connection is closed.

イベントハンドラ

RTCPeerConnection.onaddstream
Is the event handler called when the addstream event is received. Such an event is sent when a MediaStream is added to this connection by the remote peer. The event is sent immediately after the call RTCPeerConnection.setRemoteDescription() and doesn't wait for the result of the SDP negotiation.
RTCPeerConnection.ondatachannel
Is the event handler called when the datachannel event is received. Such an event is sent when a RTCDataChannel is added to this connection.
RTCPeerConnection.onicecandidate
Is the event handler called when the icecandidate event is received. Such an event is sent when a RTCICECandidate object is added to the script.
RTCPeerConnection.oniceconnectionstatechange
Is the event handler called when the iceconnectionstatechange event is received. Such an event is sent when the value of iceConnectionState changes.
RTCPeerConnection.onidentityresult
Is the event handler called when the identityresult event is received. Such an event is sent when an identity assertion is generated, via getIdentityAssertion(), or during the creation of an offer or an answer.
RTCPeerConnection.onidpassertionerror
Is the event handler called when the idpassertionerror event is received. Such an event is sent when the associated identity provider (IdP) encounters an error while generating an identity assertion.
RTCPeerConnection.onidpvalidationerror
Is the event handler alled when the idpvalidationerror event is received. Such an event is sent when the associated identity provider (IdP) encounters an error while validating an identity assertion.
RTCPeerConnection.onnegotiationneeded
Is the event handler called when the negotiationneeded event, sent by the browser to inform that negotiation will be required at some point in the future, is received.
RTCPeerConnection.onpeeridentity
Is the event handler called when the peeridentity event, sent when a peer identity has been set and verified on this connection, is received.
RTCPeerConnection.onremovestream
Is the event handler called when the removestream event, sent when a MediaStream is removed from this connection, is received.
RTCPeerConnection.onsignalingstatechange
Is the event handler called when the signalingstatechange event, sent when the value of signalingState changes, is received.

メソッド

RTCPeerConnection()
Constructor; returns a new RTCPeerConnection object.
RTCPeerConnection.createOffer()
Creates an offer that is a request to find a remote peer with a specific configuration. The two first parameters of this methods are respectively success and error callbacks, the optional third one are options the user want to have, like audio or video streams.
RTCPeerConnection.createAnswer()
Creates an answer to the offer received by the remote peer, in a two-part offer/answer negotiation of a connection. The two first parameters are respectively success and error callbacks, the optional third one represent options for the answer to be created.
RTCPeerConnection.setLocalDescription()
Changes the local description associated with the connection. The description defines the properties of the connection like its codec. The connection is affected by this change and must be able to support both old and new descriptions. The method takes three parameters, a RTCSessionDescription object to set, and two callbacks, one called if the change of description succeeds, another called if it failed.
RTCPeerConnection.setRemoteDescription()
Changes the remote description associated with the connection. The description defines the properties of the connection like its codec. The connection is affected by this change and must be able to support both old and new descriptions. The method takes three parameters, a RTCSessionDescription object to set, and two callbacks, one called if the change of description succeeds, another called if it failed.
RTCPeerConnection.updateIce()
 
RTCPeerConnection.addIceCandidate()
 
RTCPeerConnection.getConfiguration()
 
RTCPeerConnection.getLocalStreams()
Returns an array of MediaStream associated with the local end of the connection. The array may be empty.
RTCPeerConnection.getRemoteStreams()
Returns an array of MediaStream associated with the remote end of the connection. The array may be empty.
RTCPeerConnection.getStreamById()
Returns the MediaStream with the given id that is associated with local or remote end of the connection. If no stream matches, it returns null.
RTCPeerConnection.addStream()
Adds a MediaStream as a local source of audio or video. If the negotiation already happened, a new one will be needed for the remote peer to be able to use it.
RTCPeerConnection.removeStream()
Removes a MediaStream as a local source of audio or video. If the negotiation already happened, a new one will be needed for the remote peer to stop using it.
RTCPeerConnection.close()
Abruptly closes a connection.
RTCPeerConnection.createDataChannel()
Creates a new RTCDataChannel associated with this connection. The method takes a dictionary as parameter, with the configuration required for the underlying data channel, like its reliability.
RTCPeerConnection.createDTMFSender()
Creates a new RTCDTMFSender, associated to a specific MediaStreamTrack, that will be able to send DTMF phone signaling over the connection.
RTCPeerConnection.getStats()
Creates a new RTCStatsReport that contains and allows access to statistics regarding the connection.
RTCPeerConnection.setIdentityProvider()
Sets the Identity Provider (IdP) to the triplet given in parameter: its name, the protocol used to communicate with it (optional) and an optional username. The IdP will be used only when an assertion will be needed.
RTCPeerConnection.getIdentityAssertion()
Initiates the gathering of an identity assertion. This has an effect only if the signalingState is not "closed". It is not expected for the application dealing with the RTCPeerConnection: this is automatically done; an explicit call only allows to anticipate the need.

コンストラクタ

new RTCPeerConnection(RTCConfiguration configuration, optional MediaConstraints constraints);

注釈: While the PeerConnection specification reads like passing an RTCConfiguration object is required, Firefox will supply a default if you don't.

メソッド

createOffer

void createOffer(RTCSessionDescriptionCallback successCallback, RTCPeerConnectionErrorCallback failureCallback, optional MediaConstraints constraints);

オファーの作成は、ローカルマシンのPeerConnectionを容易に扱えるようにするためのディスクリプションデータのblobを生成します。リモートのピアコネクションを得たときローカルピアコネクションをセットアップしたい場合に使用してください。

var pc = new PeerConnection();
pc.addStream(video);
pc.createOffer(function(desc){
  pc.setLocalDescription(desc, function() {
    // リモートクライアントとネゴシエーション可能なオファーをサーバーへ送信します。
  });
}

引数

successCallback
RTCSessionDescriptionCallback は1つの RTCSessionDescription オブジェクトを渡します。
errorCallback
RTCPeerConnectionErrorCallback は1つの DOMError オブジェクトを渡します。
[optional] constraints
任意の {domxref("MediaConstraints")}} オブジェクトです。

createAnswer

void createAnswer(RTCSessionDescriptionCallback successCallback, RTCPeerConnectionErrorCallback failureCallback, optional MediaConstraints constraints)")

リモートコネクションから送信されたオファーに対して応答します。

var pc = new PeerConnection();
pc.setRemoteDescription(new RTCSessionDescription(offer), function() {
  pc.createAnswer(function(answer) {
    pc.setLocalDescription(answer, function() {
      // リモートコネクションにアンサーを送信します。
    })
  })
});

引数

successCallback
RTCSessionDescriptionCallback は1つの RTCSessionDescription オブジェクトを渡します。
errorCallback
RTCPeerConnectionErrorCallback は1つの DOMError オブジェクトを渡します。
[optional] constraints
任意の MediaConstraints オブジェクトです。

updateIce()

updateIce(optional RTCConfiguration configuration, optional MediaConstraints constraints)

updateIce メソッドは、 ICEエージェントのローカル候補の収集とリモート候補のパイピングの処理を更新します。"IceTransports"と呼ばれる必須の制約が存在する場合、ICEエンジンがどのように動作するかを制御します。被受信者によって位置情報が漏れるのを防ぐため、呼び出しが受理される前に、TURN候補の使用を制限することができます。このメソッドの呼び出しは、ICEエージェントの状態を変更し、また接続可能性が確立された場合はメディア状態を変更するでしょう。

 

addIceCandidate()

addIceCandidate (RTCIceCandidate candidate, Function successCallback, RTCPeerConnectionErrorCallback failureCallback);

addIceCandidate() メソッドはICEエージェントのリモート候補を提供します。加えて、リモートディスクリプションの追加、"IceTransports"制約が"none"に設定されていない場合、接続可能性の確認は新しい候補として送信されるでしょう。これはICEエージェントの接続状態を変更し、異なる接続可能性が確立された場合メディアの状態を変更するでしょう。

pc.addIceCandidate(new RTCIceCandidate(candidate));

createDataChannel

RTCDataChannel createDataChannel (DOMString label, optional RTCDataChannelInit dataChannelDict);

ピアコネクション上で動画や音声でないデータを送信するためのデータチャンネルを作成します。

var pc = new PeerConnection();
var channel = pc.createDataChannel("Mydata");
channel.onopen = function(event) {
  channel.send('sending a message');
}
channel.onmessage = function(event) { console.log(event.data); }

その他の記事

ドキュメントのタグと貢献者

 このページの貢献者: dreissig.jahrhundert
 最終更新者: dreissig.jahrhundert,