Initial Author of this Specification was Ian Hickson, Google Inc., with
the following copyright statement:
© Copyright 2004-2011 Apple Computer, Inc., Mozilla Foundation, and Opera
Software ASA. You are granted a license to use, reproduce and create
derivative works of this document. All subsequent changes since 26 July
2011 done by the W3C WebRTC Working Group are under the following
Copyright:
© 2011-2018 W3C® (MIT, ERCIM,
Keio, Beihang). W3C liability,
trademark and permissive document license rules
apply.
ドキュメントでは、適切なリアルタイムプロトコル群を実装した他のブラウザやデバイスとの間で、メディアや一般的なアプリケーションデータの送受信を可能にする、WebIDL による一連の ECMAScript API を定義する。本仕様は、IETF RTCWEB グループが策定したプロトコル仕様や、ローカルメディアデバイスにアクセスするための API 仕様と併せて策定されています。
この API は、WHATWG で行われた予備的な作業に基づいています。
この仕様は機能的に完成しており、これ以上の実質的な変更はなく安定していることが期待されています。前回の Candidate Recommendation 以降、以下のような実質的な変更が仕様にもたらされました。
voiceActivityFlag
は、実装されていないため、リスクがあると判断されました
PeerConnection
を閉じるときのステートマシンが明確になりました。
その関連するテストスイートは、 API の実装レポートを構築するために使用されます。
提案型勧告のステータスに移行するために、グループは少なくとも2つの導入済みブラウザで各機能の実装を実証し、各オプション機能の実装を少なくとも1つ行うことを期待している。 実装が1つしかない必須機能は、必要に応じて改訂された勧告候補の中でオプションとしてマークすることができる。
この仕様で扱う HTML でのピアツーピア通信やビデオ会議には、さまざまな側面があります:
本ドキュメントでは、これらの機能に使用される API を定義しています。本仕様は、 IETF RTCWEB グループが策定したプロトコル仕様と、 WebRTC ワーキンググループが策定したローカルメディアデバイスへのアクセスを取得するための API 仕様 [[GETUSERMEDIA]] と併せて策定されています。このシステムの概要は、 [[RFC8825]] および [[RFC8826]] に記載されています。
この仕様は、この仕様に含まれるインターフェースを実装した user agent という単一の製品に適用される適合性基準を定義しています。
アルゴリズムや特定のステップで表現された適合性要件は、最終結果が同等である限り、どのような方法で実装しても構いません。(特に、本仕様書で定義されているアルゴリズムは、簡単に実行できることを目的としており、パフォーマンスの向上を目的としていません)。
本仕様で定義されている API を ECMAScript で実装する場合、本仕様では Web IDL仕様 [[!WEBIDL]] で定義されている ECMAScript Bindings と一貫性のある方法で実装しなければなりません(本仕様ではその仕様と用語を使用しています)。
イベントハンドラーに使用されるコールバックを表す{{EventHandler}}インターフェイスは、[[!HTML]]で定義されています。
[= queue a task =] と [= networking task source =] という概念は [[!HTML]] で定義されています。
[= fire an event =] という概念は [[!DOM]] で定義されています。
[= event =] 、 [= event handlers =] 、 [= event handler event types =] という用語は、 [[!HTML]] で定義されています。
{{Performance.timeOrigin}} と {{Performance.now()}} は [[!hr-time]] で定義されています。
serializable objects、[= serialization steps= ]、[= deserialization steps =] という用語は [[! HTML]] で定義されています。
{{MediaStream}}、{{MediaStreamTrack}}、{{MediaStreamConstraints}} という用語は、[[!GETUSERMEDIA]] で定義されています。なお、{{MediaStream}} はこのドキュメントの で、{{MediaStreamTrack}} はこのドキュメントの で拡張されています。
{{Blob}} という用語は、[[!FILEAPI]] で定義されています。
media description という用語は [[!RFC4566]] で定義されています。
media transportという用語は [[!RFC7656]] で定義されています。
generation という用語は、[[RFC8838]] のセクション2で定義されています。
stats オブジェクトとmonitored オブジェクトという用語は [[!WEBRTC-STATS]] で定義されています。
例外に言及する場合、[= exception/throw =] および [= exception/created =] という用語は [[! WEBIDL]] で定義されています。
コールバック {{VoidFunction}} は [[!WEBIDL]] で定義されています。
throw "という用語は、 [[!INFRA]] で規定されているように、現在の処理ステップを終了させます。
プロミスの文脈で使われる fulfilled 、 rejected 、resolved 、 pending 、 settled という用語は、 [[!ECMASCRIPT-6.0]] で定義されています。
bundle、bundle-only、bundle-policy という用語は、[[!RFC8829]] で定義されています。
AlgorithmIdentifier は、[[!WebCryptoAPI]] に定義されています。
[[API-DESIGN-PRINCIPLES]] で定義されている run-to-completion と no-data-races の原則を含む、 Javascript の API の一般的な原則が適用されます。つまり、タスクが実行されている間は、外部のイベントが Javascript アプリケーションに表示される内容に影響を与えることはありません。
アプリケーションに表示される値のセットが一貫していることを確認するのはユーザーエージェントの責任です。例えば、 getContributingSources() (これは同期的です)は、同時に測定されたすべてのソースの値を返します。
{{RTCPeerConnection}} インスタンスは、アプリケーションが別のブラウザの別の {{RTCPeerConnection}} インスタンスや、必要なプロトコルを実装している別のエンドポイントとの間でピアツーピア通信を確立できるようにします。通信は、不特定の手段で提供されるシグナリングチャネル上での制御メッセージ(シグナリングプロトコルと呼ばれる)の交換によって調整されますが、一般的にはサーバー経由でページ内のスクリプトによって行われます。例えば、Web Sockets や XMLHttpRequest
[[?xhr]] を使用します。
{{RTCConfiguration}} は、{{RTCPeerConnection}} を介して確立されたピアツーピア通信がどのように確立または再確立されるかを設定するための一連のパラメータを定義します。
dictionary RTCConfiguration { sequence<RTCIceServer> iceServers; RTCIceTransportPolicy iceTransportPolicy; RTCBundlePolicy bundlePolicy; RTCRtcpMuxPolicy rtcpMuxPolicy; sequence<RTCCertificate> certificates; [EnforceRange] octet iceCandidatePoolSize = 0; };
STUN サーバーや TURN サーバーなど、ICE が使用できるサーバーを表すオブジェクトの配列です。
[= ICE Agent =] がどの候補を使用することができるかを示します。
ICE 候補を集める際に、どの media-bundling policy を使用するかを示します。
ICE 候補を集める際に、どの rtcp-mux policy を使用するかを示します。
{{RTCPeerConnection}} が認証に使用する証明書のセットです。
このパラメータの有効な値は、{{RTCPeerConnection/generateCertificate()}} 関数の呼び出しによって作成されます。
任意の DTLS 接続では、1つの証明書しか使用しませんが、この属性を使用することで、呼び出し側が異なるアルゴリズムをサポートする複数の証明書を提供することができます。 最終的な証明書は、どの証明書が許可されているかを確立する DTLS ハンドシェイクに基づいて選択されます。{{RTCPeerConnection}} の実装は、特定の接続にどの証明書を使用するかを選択します。
既存の実装では、提供された最初の証明書のみが利用され、他の証明書は無視されます。
この値がない場合、各 {{RTCPeerConnection}} インスタンスにデフォルトの証明書のセットが生成されます。
このオプションにより、アプリケーションは鍵の継続性を確立することができます。{{RTCCertificate}}は [[?INDEXEDDB]] に永続化され、再利用することができます。また、永続化と再利用により、鍵生成のコストを回避することができます。
この設定オプションの値は、最初に選択された後は変更できません。
0
[[!RFC8829]] で定義されている、プリフェッチされた ICE プールのサイズ。
enum RTCIceCredentialType { "password" };
列挙の説明 | |
---|---|
password | クレデンシャルは、[[!RFC5389]] のセクション 10.2 で説明されているように、長期認証のユーザー名とパスワードです。 |
{{RTCIceServer}} 辞書は、[= ICE Agent =] がピアとの接続を確立するために使用できる STUN および TURN サーバーを記述するために使用されます。
dictionary RTCIceServer { required (DOMString or sequence<DOMString>) urls; DOMString username; DOMString credential; RTCIceCredentialType credentialType = "password"; };
[[!RFC7064]] および [[!RFC7065]] で定義されている STUN または TURN の URI(s)、またはその他の URI タイプ。
この {{RTCIceServer}} オブジェクトが TURN サーバーを表し、{{credentialType}} が {{RTCIceCredentialType/"password"}} の場合、この属性は、その TURN サーバーで使用するユーザー名を指定します。
この {{RTCIceServer}} オブジェクトが TURN サーバーを表す場合、この属性はその TURN サーバーで使用するクレデンシャルを指定します。
{{credentialType}} が {{RTCIceCredentialType/"password"}} の場合、{{credential}} は [[!RFC5389]] の 10.2 項に記載されている長期認証用パスワードを表します。
{{credentialType}}の追加の値をサポートするために、{{credential}} は将来的にユニオンとして進化する可能性があります。
この {{RTCIceServer}} オブジェクトが TURN サーバーを表している場合、この属性は、その TURN サーバーが認証を要求する際に、credential がどのように使用されるべきかを指定します。
{{RTCIceServer}} オブジェクトの配列例:
[ {urls: 'stun:stun1.example.net'}, {urls: ['turns:turn.example.org', 'turn:turn.example.net'], username: 'user', credential: 'myPassword', credentialType: 'password'}, ];
[[!RFC8829]] に記載されているように、 {{RTCConfiguration/iceTransportPolicy}} のメンバが指定されている場合、ブラウザがアプリケーションに許可された候補を表示するために使用する ICE 候補ポリシー[[!RFC8829]] が定義されます。
enum RTCIceTransportPolicy { "relay", "all" };
Enumeration description (non-normative) | |
---|---|
relay |
[= ICE Agent =] は、TURNサーバーを経由する候補者など、メディアリレー候補者のみを使用します。
これにより、リモートエンドポイントがユーザーのIPアドレスを知ることを防ぐことができますが、これは特定のユースケースで必要となる場合があります。例えば、「通話」を基本とするアプリケーションでは、着呼側が何らかの方法で同意するまで、未知の着呼側が着呼側のIPアドレスを知ることを防ぎたい場合があります。
|
all |
この値が指定されている場合、[= ICE Agent =] はどのタイプの候補でも使用できます。
実装では、 {{RTCIceCandidate}}.{{RTCIceCandidate/address}} の説明に記載されているように、アプリケーションに公開されるIPアドレスを制限するために、独自の候補フィルタリングポリシーを使用することができます。
|
[[!RFC8829]] に記載されているように、バンドルポリシーは、リモートエンドポイントがバンドルを認識していない場合にどのメディアトラックをネゴシエートするか、どの ICE 候補を収集するかに影響します。リモートエンドポイントがバンドルを認識している場合、すべてのメディアトラックとデータチャンネルが同じトランスポートにバンドルされます。
enum RTCBundlePolicy { "balanced", "max-compat", "max-bundle" };
Enumeration description (non-normative) | |
---|---|
balanced | 使用するメディアタイプ(オーディオ、ビデオ、データ)ごとに ICE の候補を集めます。リモートエンドポイントがバンドルを意識していない場合は、オーディオとビデオのトラックを別々のトランスポートで1つだけネゴシエートします。 |
max-compat | 各トラックの ICE 候補を集めます。リモートエンドポイントがバンドルを認識していない場合、すべてのメディアトラックを別々のトランスポートでネゴシエートします。 |
max-bundle | 1つのトラックのみの ICE 候補を集めます。リモートエンドポイントがバンドルを認識していない場合、1つのメディアトラックのみをネゴシエートします。 |
[[!RFC8829]] に記載されているように、 {{RTCRtcpMuxPolicy}} は、非多重化 RTCP をサポートするために集められる ICE 候補に影響を与えます。この仕様で定義されている値は {{RTCRtcpMuxPolicy/"require"}} のみです。
enum RTCRtcpMuxPolicy { "require" };
Enumeration description (non-normative) | |
---|---|
require | RTP のみの ICE 候補を集め、 RTP 候補に RTCP を多重化します。リモートエンドポイントが rtcp-mux に対応していない場合、セッションネゴシエーションは失敗します。 |
これらの辞書には、オファー/アンサー作成プロセスを制御するために使用できるオプションが記載されています。
dictionary RTCOfferAnswerOptions {};
dictionary RTCOfferOptions : RTCOfferAnswerOptions { boolean iceRestart = false; };
false
です。
この辞書のメンバの値が true
である場合、または関連する {{RTCPeerConnection}} オブジェクトの {{RTCPeerConnection/[[LocalIceCredentialsToReplace]]}} スロットが空でない場合、生成された記述は、現在の資格情報とは異なるICE資格情報を持つことになります( {{RTCPeerConnection/currentLocalDescription}} 属性の SDP で確認できます)。生成された記述を適用すると、 [[RFC5245]] のセクション 9.1.1.1 で説明されているように、 ICE が再起動されます。
この辞書のメンバの値がfalse
で、関連する {{RTCPeerConnection}} オブジェクトの {{RTCPeerConnection/[[LocalIceCredentialsToReplace]]}} スロットが空のときかつ、 {{RTCPeerConnection/currentLocalDescription}} 属性に有効な ICE 認証情報がある場合、生成された Description は {{RTCPeerConnection/currentLocalDescription}} 属性からの現在の値と同じ ICE 認証情報を持つことになります。
ICE の再起動は、 {{RTCPeerConnection/iceConnectionState}} が {{RTCIceConnectionState/"failed"}} に遷移したときに行うことが推奨されます。アプリケーションはさらに、 {{RTCPeerConnection/iceConnectionState}} が {{RTCIceConnectionState/"disconnected"}} に遷移するのを待ち、他の情報源を使用して( {{RTCPeerConnection/getStats}} を使用して、今後数秒間に送受信されるバイト数が増加するかどうかを測定するなど)、 ICE 再起動が望ましいかどうかを判断することもできます。
RTCAnswerOptions 辞書は、 {{RTCSdpType/"answer"}} タイプのセッション記述に固有のオプションを記述します。(このバージョンの仕様ではなし)。
dictionary RTCAnswerOptions : RTCOfferAnswerOptions {};
enum RTCSignalingState { "stable", "have-local-offer", "have-remote-offer", "have-local-pranswer", "have-remote-pranswer", "closed" };
Enumeration description | |
---|---|
stable | オファー/アンサーの交換は行われていません。これは初期状態でもあり、この場合、ローカルおよびリモートの記述は空です。 |
have-local-offer | タイプ {{RTCSdpType/"offer"}} のローカル記述が、正常に適用されました。 |
have-remote-offer | タイプ {{RTCSdpType/"offer"}} のリモート記述が、正常に適用されました。 |
have-local-pranswer | タイプ {{RTCSdpType/"offer"}} のリモート記述が正常に適用され、タイプ {{RTCSdpType/"pranswer"}} のローカル記述が正常に適用されました。 |
have-remote-pranswer | タイプ {{RTCSdpType/"offer"}} のローカル記述が正常に適用され、タイプ {{RTCSdpType/"pranswer"}} のリモート記述が正常に適用されました。 |
closed |
{{RTCPeerConnection}} は閉じられました。{{RTCPeerConnection/[[IsClosed]]}} スロットは true です。
|
遷移の例として、次のようなものがあります:
enum RTCIceGatheringState { "new", "gathering", "complete" };
Enumeration description | |
---|---|
new | いずれかの {{RTCIceTransport}} が {{RTCIceGathererState/"new"}} の集まりの状態にあり、いずれのトランスポートも {{RTCIceGathererState/"gathering"}} の状態にないか、トランスポートが存在しません。 |
gathering | いずれかの {{RTCIceTransport}} が {{RTCIceGathererState/"gathering"}} 状態になっています。 |
complete | 少なくとも1つの {{RTCIceTransport}} が存在し、すべての {{RTCIceGathererState/"complete"}} の採集状態にあります。 |
考慮されるトランスポートのセットは PeerConnection の [= set of transceivers =] と PeerConnection の [[\SctpTransport]] の内部スロットが null
でなければ、現在参照されているものです。
enum RTCPeerConnectionState { "closed", "failed", "disconnected", "new", "connecting", "connected" };
Enumeration description | |
---|---|
closed |
{{RTCPeerConnection}} オブジェクトの {{RTCPeerConnection/[[IsClosed]]}} スロットは true です。
|
failed | 前の状態が適用されず、任意の {{RTCIceTransport}} が {{RTCIceTransportState/"failed"}} 状態になっているか、任意の {{RTCDtlsTransport}} が {{RTCDtlsTransportState/"failed"}} 状態になっていることがあります。 |
disconnected | これまでのどの状態も適用されず、どの {{RTCIceTransportState/"disconnected"}} も {{RTCIceTransportState/"disconnected"}} 状態になっています。 |
new | これまでの状態がいずれも適用されず、すべての {{RTCIceTransport}} が {{RTCIceTransportState/"new"}} または {{RTCIceTransportState/"closed"}} の状態にあり、すべての {{RTCDtlsTransport}} が {{RTCDtlsTransportState/"new"}} または {{RTCDtlsTransportState/"closed"}} の状態にあるか、またはトランスポートが存在しない状態にあります。 |
connecting | 前述の状態がいずれも適用されておらず、任意の {{RTCIceTransportState/"checking"}} 状態、または任意の {{RTCDtlsTransportState/"connecting"}} 状態にある {{RTCIceTransport}。 |
connected | これまでの状態がいずれも適用されず、すべての {{RTCIceTransportState/"connected"}} 、 {{RTCIceTransportState/"completed"}} または {{RTCIceTransportState/"closed"}} の状態にあり、すべての {{RTCDtlsTransport}} が {{RTCDtlsTransportState/"connected"}} または {{RTCDtlsTransportState/"closed"}} の状態にあります。 |
考慮されるトランスポートのセットは、 PeerConnection の [= set of transceivers =] と PeerConnection の [[\SctpTransport]] の内部スロットが null
でなければ、現在参照されているものです。
enum RTCIceConnectionState { "closed", "failed", "disconnected", "new", "checking", "completed", "connected" };
Enumeration description | |
---|---|
closed |
{{RTCPeerConnection}} オブジェクトの {{RTCPeerConnection/[[IsClosed]]}} スロットは true です。
|
failed | 前の状態は適用されず、すべての {{RTCIceTransportState/"failed"}} 状態になります。 |
disconnected | これまでの状態は一切適用されず、どの {{RTCIceTransportState/"disconnected"}} も {{RTCIceTransportState/"disconnected"}} 状態になっています。 |
new | これまでの状態がいずれも適用されず、すべての {{RTCIceTransportState/"new"}} または {{RTCIceTransportState/"closed"}} の状態にあるか、またはトランスポートが存在しない状態にあります。 |
checking | 以前の状態はいずれも適用されず、すべての {{RTCIceTransportState/"new"}} または {{RTCIceTransportState/"checking"}} の状態にあります。 |
completed | これまでの状態はいずれも適用されず、すべての {{RTCIceTransportState/"completed"}} または {{RTCIceTransportState/"closed"}} の状態になっています。 |
connected | これまでの状態はいずれも適用されず、すべての {{RTCIceTransportState/"connected"}}、{{RTCIceTransportState/"completed"}}、{{RTCIceTransportState/"closed"}} のいずれかの状態にあります。 |
考慮されるトランスポートのセットは、PeerConnectionの [= set of transceivers =] と PeerConnection の [[\SctpTransport]] の内部スロットが null
でない場合に、現在参照されているものです。
なお、{{RTCIceTransport}} がシグナリングの結果(RTCP muxやbundlingなど)として破棄されたり、シグナリングの結果(新しい [= media description =] の追加など)として作成されたりした場合は、状態がある状態から別の状態に直接進むことがある。
[[!RFC8829]] 仕様は、全体として {{RTCPeerConnection}} の動作方法の詳細を記述しています。必要に応じて、[[!RFC8829]] の特定のサブセクションへの参照が提供されます。
new {{RTCPeerConnection}}(configuration)
を呼び出すと、{{RTCPeerConnection}} オブジェクトが生成されます。
configuration.{{RTCConfiguration/iceServers}} には、ICE が使用するサーバーを見つけてアクセスするための情報が含まれています。アプリケーションは各タイプの複数のサーバーを提供することができ、任意の TURN サーバーは、サーバーの反射候補を収集する目的で STUN サーバーとしても使用できます(MAY)。
{{RTCPeerConnection}} オブジェクトは、signaling state、connection state、ICE gathering state、ICE connection stateを持っています。これらは、オブジェクトが作成されたときに初期化されます。
{{RTCPeerConnection}} の ICE プロトコル実装は、ICE agent [[RFC5245]] によって表されます。特定の {{RTCPeerConnection}} メソッドは、{{addIceCandidate}}、{{setConfiguration}}、{{setLocalDescription}}、{{setRemoteDescription}}、{{close}} という [= ICE Agent =] との相互作用を伴います。これらのインタラクションについては、本ドキュメントの関連セクションおよび [[!RFC8829]] に記載されています。また、[= ICE Agent =] は,で説明されているように、{{RTCIceTransport}} の内部表現の状態が変化したときに,ユーザエージェントに指示を与える。
このセクションに記載されているタスクのタスクソースは、[= networking task source =]です。
SDPネゴシエーションの状態は、[= signaling state =] と内部変数 {{RTCPeerConnection/[[CurrentLocalDescription]]}}、{{RTCPeerConnection/[[CurrentRemoteDescription]]}}、{{RTCPeerConnection/[[PendingLocalDescription]]}} と {{RTCPeerConnection/[[PendingRemoteDescription]]}} で表されます。これらは、{{setLocalDescription}} と {{setRemoteDescription}} の操作の中でのみ設定され、{{addIceCandidate}} の操作と [= surface a candidate =] の手順で修正されます。いずれの場合も、5つの変数に対するすべての変更は、プロシージャがイベントを発生させたりコールバックを呼び出したりする前に完了しているので、変更内容は1つの時点で可視化されます。
unloading document cleanup steps の一つとして、以下の手順を実行します。
Let window be document's [=relevant global object=].
For each {{RTCPeerConnection}} object connection
whose [=relevant global object=] is window, [= close the connection
=] with connection and the value true
.
When the RTCPeerConnection.constructor() is invoked, the user agent MUST run the following steps:
If any of the steps enumerated below fails for a reason not specified here, [= exception/throw =] an {{UnknownError}} with the {{DOMException/message}} attribute set to an appropriate description.
Let connection be a newly created {{RTCPeerConnection}} object.
Let connection have a [[\DocumentOrigin]] internal slot, initialized to the [= relevant settings object =]'s [=environment settings object/origin=].
If the {{RTCConfiguration/certificates}} value in configuration is non-empty, run the following steps for each certificate in certificates:
If the value of certificate.{{RTCCertificate/expires}} is less than the current time, [= exception/throw =] an {{InvalidAccessError}}.
If certificate.{{RTCCertificate/[[Origin]]}} is not same origin with connection.{{RTCPeerConnection/[[DocumentOrigin]]}}, [= exception/throw =] an {{InvalidAccessError}}.
Store certificate.
または、この {{RTCPeerConnection}} インスタンスで 1 つ以上の新しい {{RTCCertificate}} インスタンスを生成し、それらを保存します。これは非同期に行ってもよく、 {{RTCConfiguration/certificates}} の値は後続のステップで undefined
のままになります。 [[RFC8826]] のセクション 4.3.2.3 に記載されているように、 WebRTC は PKI(Public Key Infrastructure) 証明書ではなく自己署名証明書を利用するため、有効期限チェックは鍵が無期限に使用されないようにするためのものであり、追加の証明書チェックは不要です。
Initialize connection's [= ICE Agent =].
If the value of
configuration.{{RTCConfiguration/iceTransportPolicy}}
is undefined
, set it to
{{RTCIceTransportPolicy/"all"}}.
If the value of
configuration.{{RTCConfiguration/bundlePolicy}} is
undefined
, set it to
{{RTCBundlePolicy/"balanced"}}.
If the value of
configuration.{{RTCConfiguration/rtcpMuxPolicy}}
is undefined
, set it to
{{RTCRtcpMuxPolicy/"require"}}.
Let connection have a [[\Configuration]] internal slot. [= Set the configuration =] specified by configuration.
Let connection have an [[\IsClosed]]
internal slot, initialized to false
.
Let connection have a
[[\NegotiationNeeded]] internal slot, initialized
to false
.
Let connection have an
[[\SctpTransport]] internal slot, initialized to
null
.
Let connection have an [[\Operations]] internal slot, representing an [= operations chain =], initialized to an empty list.
Let connection have a
[[\UpdateNegotiationNeededFlagOnEmptyChain]]
internal slot, initialized to false
.
Let connection have an
[[\LastCreatedOffer]] internal slot, initialized
to ""
.
Let connection have an
[[\LastCreatedAnswer]] internal slot, initialized
to ""
.
Let connection have an [[\EarlyCandidates]] internal slot, initialized to an empty list.
Set connection's [= signaling state =] to {{RTCSignalingState/"stable"}}.
Set connection's [= ICE connection state =] to {{RTCIceConnectionState/"new"}}.
Set connection's [= ICE gathering state =] to {{RTCIceGatheringState/"new"}}.
Set connection's [= connection state =] to {{RTCPeerConnectionState/"new"}}.
Let connection have a
[[\PendingLocalDescription]] internal slot,
initialized to null
.
Let connection have a
[[\CurrentLocalDescription]] internal slot,
initialized to null
.
Let connection have a
[[\PendingRemoteDescription]] internal slot,
initialized to null
.
Let connection have a
[[\CurrentRemoteDescription]] internal slot,
initialized to null
.
Let connection have a [[\LocalIceCredentialsToReplace]] internal slot, initialized to an empty set.
Return connection.
{{RTCPeerConnection}} オブジェクトには、 {{RTCPeerConnection/[[Operations]]}} という operations chain があり、チェーン内の1つの非同期オペレーションのみが同時に実行されるようになっています。前のコールの返された約束がまだ [= settled =]で ない間に後続のコールが行われた場合、それらはチェーンに追加され、すべての前のコールの実行が終了し、それらの約束が [= settled =] になったときに実行されます。
To chain an operation to an {{RTCPeerConnection}} object's [= operations chain =], run the following steps:
Let connection be the {{RTCPeerConnection}} object.
If connection.{{RTCPeerConnection/[[IsClosed]]}} is
true
, return a promise [= rejected =] with a
newly [= exception/created =] {{InvalidStateError}}.
Let operation be the operation to be chained.
Let p be a new promise.
Append operation to {{RTCPeerConnection/[[Operations]]}}.
If the length of {{RTCPeerConnection/[[Operations]]}} is exactly 1, execute operation.
Upon [= fulfillment =] or [= rejection =] of the promise returned by the operation, run the following steps:
If connection.{{RTCPeerConnection/[[IsClosed]]}} is
true
, abort these steps.
If the promise returned by operation was [= fulfilled =] with a value, [= fulfill =] p with that value.
If the promise returned by operation was [= rejected =] with a value, [= reject =] p with that value.
Upon [= fulfillment =] or [= rejection =] of p, execute the following steps:
If connection.{{RTCPeerConnection/[[IsClosed]]}} is
true
, abort these steps.
Remove the first element of {{RTCPeerConnection/[[Operations]]}}.
If {{RTCPeerConnection/[[Operations]]}} is non-empty, execute the operation represented by the first element of {{RTCPeerConnection/[[Operations]]}}, and abort these steps.
If
connection.{{RTCPeerConnection/[[UpdateNegotiationNeededFlagOnEmptyChain]]}}
is false
, abort these steps.
Set
connection.{{RTCPeerConnection/[[UpdateNegotiationNeededFlagOnEmptyChain]]}}
to false
.
Update the negotiation-needed flag for connection.
Return p.
An {{RTCPeerConnection}} object has an aggregated [= connection
state =]. Whenever the state of an {{RTCDtlsTransport}} changes
or when the {{RTCPeerConnection/[[IsClosed]]}} slot turns true
,
the user agent MUST update the connection state by queueing a
task that runs the following steps:
Let connection be this {{RTCPeerConnection}} object.
Let newState be the value of deriving a new state value as described by the {{RTCPeerConnectionState}} enum.
If connection's [= connection state =] is equal to newState, abort these steps.
Let connection's [= connection state =] be newState.
[= Fire an event =] named {{RTCPeerConnection/connectionstatechange}} at connection.
To update the [= ICE gathering state =] of an {{RTCPeerConnection}} instance connection, the user agent MUST queue a task that runs the following steps:
If connection.{{RTCPeerConnection/[[IsClosed]]}} is
true
, abort these steps.
Let newState be the value of deriving a new state value as described by the {{RTCIceGatheringState}} enum.
If connection's [= ICE gathering state =] is equal to newState, abort these steps.
Set connection's [= ICE gathering state =] to newState.
[= Fire an event =] named {{RTCPeerConnection/icegatheringstatechange}} at connection.
If newState is
{{RTCIceGatheringState/"complete"}}, [= fire an event =]
named {{RTCPeerConnection/icecandidate}} using the
{{RTCPeerConnectionIceEvent}} interface with the candidate
attribute set to null
at connection.
To
set a local session description description on
an {{RTCPeerConnection}} object connection, [=
set a session description | set the session description =]
description on connection with the additional
value false
.
To
set a remote session description description
on an {{RTCPeerConnection}} object connection, [=
set a session description | set the session description =]
description on connection with the additional
value true
.
To set a session description description on an {{RTCPeerConnection}} object connection, given a remote boolean, run the following steps:
Let p be a new promise.
If description.{{RTCSessionDescriptionInit/type}} is {{RTCSdpType/"rollback"}} and connection's [= signaling state =] is either {{RTCSignalingState/"stable"}}, {{RTCSignalingState/"have-local-pranswer"}}, or {{RTCSignalingState/"have-remote-pranswer"}}, then [= reject =] p with a newly [= exception/created =] {{InvalidStateError}} and abort these steps.
Let jsepSetOfTransceivers be a shallow copy of connection's [= set of transceivers =].
In parallel, start the process to apply description as described in [[!RFC8829]], with these additional restrictions:
Use jsepSetOfTransceivers as the source of truth with regard to what "RtpTransceivers" exist, and their {{RTCRtpTransceiver/[[JsepMid]]}} internal slot as their "mid property".
If remote is true
, validate
back-to-back offers as if answers were applied in
between, by running the check for subsequent offers as if
it were in stable state.
If applying description leads to modifying a transceiver transceiver, and transceiver.{{RTCRtpTransceiver/[[Sender]]}}.{{RTCRtpSender/[[SendEncodings]]}} is non-empty, and not equal to the encodings that would result from processing description, the process of applying description fails. This specification does not allow remotely initiated RID renegotiation.
If the process to apply description fails for any reason, then the user agent MUST queue a task that runs the following steps:
If connection.{{RTCPeerConnection/[[IsClosed]]}} is
true
, then abort these steps.
If description.{{RTCSessionDescriptionInit/type}} is invalid for the current [= signaling state =] of connection as described in [[!RFC8829]], then [= reject =] p with a newly [= exception/created =] {{InvalidStateError}} and abort these steps.
If the content of description is not valid SDP syntax, then [= reject =] p with an {{RTCError}} (with {{RTCError/errorDetail}} set to {{RTCErrorDetailType/"sdp-syntax-error"}} and the {{RTCError/sdpLineNumber}} attribute set to the line number in the SDP where the syntax error was detected) and abort these steps.
If remote is true
, the
connection's {{RTCRtcpMuxPolicy}} is
{{RTCRtcpMuxPolicy/require}} and the description does
not use RTCP mux, then [= reject =] p with
a newly [= exception/created =]
{{InvalidAccessError}} and abort these steps.
If the description attempted to renegotiate RIDs, as described above, then [= reject =] p with a newly [= exception/created =] {{InvalidAccessError}} and abort these steps.
If the content of description is invalid, then [= reject =] p with a newly [= exception/created =] {{InvalidAccessError}} and abort these steps.
For all other errors, [= reject =] p with a newly [= exception/created =] {{OperationError}}.
If description is applied successfully, the user agent MUST queue a task that runs the following steps:
If connection.{{RTCPeerConnection/[[IsClosed]]}} is
true
, then abort these steps.
If remote is true
and
description is of type
{{RTCSdpType/"offer"}}, then if any
{{RTCPeerConnection/addTrack()}} methods succeeded
during the process to apply description,
abort these steps and start the process over as if
they had succeeded prior, to include the extra
transceiver(s) in the process.
If description is of type {{RTCSdpType/"offer"}} and the [= signaling state =] of connection is {{RTCSignalingState/"stable"}} then for each transceiver in connection's [= set of transceivers =], run the following steps:
Set transceiver.{{RTCRtpTransceiver/[[Sender]]}}.{{RTCRtpSender/[[LastStableStateSenderTransport]]}} to transceiver.{{RTCRtpTransceiver/[[Sender]]}}.{{RTCRtpSender/[[SenderTransport]]}}.
Set transceiver.{{RTCRtpTransceiver/[[Receiver]]}}.{{RTCRtpReceiver/[[LastStableStateReceiverTransport]]}} to transceiver.{{RTCRtpTransceiver/[[Receiver]]}}.{{RTCRtpReceiver/[[ReceiverTransport]]}}.
Set transceiver.{{RTCRtpTransceiver/[[Receiver]]}}.{{RTCRtpReceiver/[[LastStableStateAssociatedRemoteMediaStreams]]}} to transceiver.{{RTCRtpTransceiver/[[Receiver]]}}.{{RTCRtpReceiver/[[AssociatedRemoteMediaStreams]]}}.
Set transceiver.{{RTCRtpTransceiver/[[Receiver]]}}.{{RTCRtpReceiver/[[LastStableStateReceiveCodecs]]}} to transceiver.{{RTCRtpTransceiver/[[Receiver]]}}.{{RTCRtpReceiver/[[ReceiveCodecs]]}}.
If remote is false
, then run
one of the following steps:
If description is of type {{RTCSdpType/"offer"}}, set connection.{{RTCPeerConnection/[[PendingLocalDescription]]}} to a new {{RTCSessionDescription}} object constructed from description, set connection's [= signaling state =] to {{RTCSignalingState/"have-local-offer"}}, and [= release early candidates =].
If description is of type
{{RTCSdpType/"answer"}}, then this completes an
offer answer negotiation. Set
connection.{{RTCPeerConnection/[[CurrentLocalDescription]]}}
to a new {{RTCSessionDescription}} object
constructed from description, and set
connection.{{RTCPeerConnection/[[CurrentRemoteDescription]]}}
to
connection.{{RTCPeerConnection/[[PendingRemoteDescription]]}}.
Set both
connection.{{RTCPeerConnection/[[PendingRemoteDescription]]}}
and
connection.{{RTCPeerConnection/[[PendingLocalDescription]]}}
to null
. Set both
connection.{{RTCPeerConnection/[[LastCreatedOffer]]}}
and
connection.{{RTCPeerConnection/[[LastCreatedAnswer]]}}
to ""
, set connection's
[= signaling state =] to
{{RTCSignalingState/"stable"}}, and [= release
early candidates =]. Finally, if none of the ICE
credentials in
connection.{{RTCPeerConnection/[[LocalIceCredentialsToReplace]]}}
are present in description, then set
connection.{{RTCPeerConnection/[[LocalIceCredentialsToReplace]]}}
to an empty set.
If description is of type {{RTCSdpType/"pranswer"}}, then set connection.{{RTCPeerConnection/[[PendingLocalDescription]]}} to a new {{RTCSessionDescription}} object constructed from description, set connection's [= signaling state =] to {{RTCSignalingState/"have-local-pranswer"}}, and [= release early candidates =].
Otherwise, (if remote is
true
) run one of the following steps:
If description is of type {{RTCSdpType/"offer"}}, set connection.{{RTCPeerConnection/[[PendingRemoteDescription]]}} attribute to a new {{RTCSessionDescription}} object constructed from description, and set connection's [= signaling state =] to {{RTCSignalingState/"have-remote-offer"}}.
If description is of type
{{RTCSdpType/"answer"}}, then this completes an
offer answer negotiation. Set
connection.{{RTCPeerConnection/[[CurrentRemoteDescription]]}}
to a new {{RTCSessionDescription}} object
constructed from description, and set
connection.{{RTCPeerConnection/[[CurrentLocalDescription]]}}
to
connection.{{RTCPeerConnection/[[PendingLocalDescription]]}}.
Set both
connection.{{RTCPeerConnection/[[PendingRemoteDescription]]}}
and
connection.{{RTCPeerConnection/[[PendingLocalDescription]]}}
to null
. Set both
connection.{{RTCPeerConnection/[[LastCreatedOffer]]}}
and
connection.{{RTCPeerConnection/[[LastCreatedAnswer]]}}
to ""
, and set
connection's [= signaling state =] to
{{RTCSignalingState/"stable"}}. Finally, if none
of the ICE credentials in
connection.{{RTCPeerConnection/[[LocalIceCredentialsToReplace]]}}
are present in the newly set
connection.{{RTCPeerConnection/[[CurrentLocalDescription]]}},
then set
connection.{{RTCPeerConnection/[[LocalIceCredentialsToReplace]]}}
to an empty set.
If description is of type {{RTCSdpType/"pranswer"}}, then set connection.{{RTCPeerConnection/[[PendingRemoteDescription]]}} to a new {{RTCSessionDescription}} object constructed from description and set connection's [= signaling state =] to {{RTCSignalingState/"have-remote-pranswer"}}.
If description is of type
{{RTCSdpType/"answer"}}, and it initiates the closure
of an existing SCTP association, as defined in
[[RFC8841]], Sections 10.3 and 10.4, set the value
of connection.{{RTCPeerConnection/[[SctpTransport]]}} to
null
.
Let trackEventInits, muteTracks, addList, removeList and errorList be empty lists.
If description is of type {{RTCSdpType/"answer"}} or {{RTCSdpType/"pranswer"}}, then run the following steps:
If description initiates the
establishment of a new SCTP association, as
defined in [[RFC8841]], Sections 10.3 and 10.4,
[= create an RTCSctpTransport =] with an initial
state of {{RTCSctpTransportState/"connecting"}}
and assign the result to the
{{RTCPeerConnection/[[SctpTransport]]}} slot. Otherwise, if an
SCTP association is established, but the
max-message-size
SDP
attribute is updated, [= update the data max
message size =] of
connection.{{RTCPeerConnection/[[SctpTransport]]}}.
If description negotiates the DTLS
role of the SCTP transport, then for each
{{RTCDataChannel}}, channel, with a
null
{{RTCDataChannel/id}}, run the
following step:
If description is not of type {{RTCSdpType/"rollback"}}, then run the following steps:
If remote is false
, then
run the following steps for each [= media
description =] in description:
If the [= media description =] was not yet [= associated =] with an {{RTCRtpTransceiver}} object then run the following steps:
Let transceiver be the {{RTCRtpTransceiver}} used to create the [= media description =].
Set transceiver.{{RTCRtpTransceiver/[[Mid]]}} to transceiver.{{RTCRtpTransceiver/[[JsepMid]]}}.
If
transceiver.{{RTCRtpTransceiver/[[Stopped]]}}
is true
, abort these sub
steps.
If the [= media description =] is indicated as using an existing [= media transport =] according to [[RFC8843]], let transport be the {{RTCDtlsTransport}} object representing the RTP/RTCP component of that transport.
Otherwise, let transport be a newly created {{RTCDtlsTransport}} object with a new underlying {{RTCIceTransport}}.
Set transceiver.{{RTCRtpTransceiver/[[Sender]]}}.{{RTCRtpSender/[[SenderTransport]]}} to transport.
Set transceiver.{{RTCRtpTransceiver/[[Receiver]]}}.{{RTCRtpReceiver/[[ReceiverTransport]]}} to transport.
Let transceiver be the {{RTCRtpTransceiver}} [= associated =] with the [= media description =].
If transceiver.{{RTCRtpTransceiver/[[Stopped]]}}
is true
, abort these sub steps.
Let direction be an {{RTCRtpTransceiverDirection}} value representing the direction from the [= media description =].
If direction is
{{RTCRtpTransceiverDirection/"sendrecv"}} or
{{RTCRtpTransceiverDirection/"recvonly"}},
set
transceiver.{{RTCRtpTransceiver/[[Receptive]]}}
to true
, otherwise set it to
false
.
Set transceiver.{{RTCRtpTransceiver/[[Receiver]]}}.{{RTCRtpReceiver/[[ReceiveCodecs]]}} to the codecs that description negotiates for receiving and which the user agent is currently prepared to receive.
If the direction is {{RTCRtpTransceiverDirection/"sendonly"}} or {{RTCRtpTransceiverDirection/"inactive"}}, the receiver is not prepared to receive anything, and the list will be empty.
If description is of type {{RTCSdpType/"answer"}} or {{RTCSdpType/"pranswer"}}, then run the following steps:
Set
transceiver.{{RTCRtpTransceiver/[[Sender]]}}.{{RTCRtpSender/[[SendCodecs]]}}
to the codecs that description
negotiates for sending and which the user
agent is currently capable of sending,
and set
transceiver.{{RTCRtpTransceiver/[[Sender]]}}.{{RTCRtpSender/[[LastReturnedParameters]]}}
to null
.
If direction is {{RTCRtpTransceiverDirection/"sendonly"}} or {{RTCRtpTransceiverDirection/"inactive"}}, and transceiver.{{RTCRtpTransceiver/[[FiredDirection]]}} is either {{RTCRtpTransceiverDirection/"sendrecv"}} or {{RTCRtpTransceiverDirection/"recvonly"}}, then run the following steps:
[= Set the associated remote streams =] given transceiver.{{RTCRtpTransceiver/[[Receiver]]}}, an empty list, another empty list, and removeList.
[= process the removal of a remote track =] for the [= media description =], given transceiver and muteTracks.
Set transceiver.{{RTCRtpTransceiver/[[CurrentDirection]]}} and transceiver.{{RTCRtpTransceiver/[[FiredDirection]]}} to direction.
Otherwise, (if remote is
true
) run the following steps for
each [= media description =] in
description:
If the description is of type {{RTCSdpType/"offer"}} and contains a request to receive simulcast, use the order of the rid values specified in the simulcast attribute to create an {{RTCRtpEncodingParameters}} dictionary for each of the simulcast layers, populating the {{RTCRtpCodingParameters/rid}} member according to the corresponding rid value, and let sendEncodings be the list containing the created dictionaries. Otherwise, let sendEncodings be an empty list.
2^(length of sendEncodings -
encoding index - 1)
.
As described by [[!RFC8829]], attempt to find an existing {{RTCRtpTransceiver}} object, transceiver, to represent the [= media description =].
If a suitable transceiver was found
(transceiver is set) and
sendEncodings is non-empty, set
transceiver.{{RTCRtpTransceiver/[[Sender]]}}.{{RTCRtpSender/[[SendEncodings]]}}
to sendEncodings, and set
transceiver.{{RTCRtpTransceiver/[[Sender]]}}.{{RTCRtpSender/[[LastReturnedParameters]]}}
to null
.
If no suitable transceiver was found (transceiver is unset), run the following steps:
[= Create an RTCRtpSender =], sender, from the [= media description =] using sendEncodings.
[= Create an RTCRtpReceiver =], receiver, from the [= media description =].
[= Create an RTCRtpTransceiver =] with sender, receiver and an {{RTCRtpTransceiverDirection}} value of {{RTCRtpTransceiverDirection/"recvonly"}}, and let transceiver be the result.
Add transceiver to the connection's [= set of transceivers =].
If description is of type
{{RTCSdpType/"answer"}} or
{{RTCSdpType/"pranswer"}}, and
transceiver.
{{RTCRtpTransceiver/[[Sender]]}}.{{RTCRtpSender/[[SendEncodings]]}}
.length is greater than 1
, then
run the following steps:
If description indicates that simulcast is not supported or desired, then remove all dictionaries in transceiver.{{RTCRtpTransceiver/[[Sender]]}}.{{RTCRtpSender/[[SendEncodings]]}} except the first one and abort these sub steps.
If description rejects any of the offered layers, then remove the dictionaries that correspond to rejected layers from transceiver.{{RTCRtpTransceiver/[[Sender]]}}.{{RTCRtpSender/[[SendEncodings]]}}.
Update the paused status as indicated by
[[RFC8853]] of each simulcast
layer by setting the
{{RTCRtpEncodingParameters/active}}
member on the corresponding dictionaries
in
transceiver.{{RTCRtpTransceiver/[[Sender]]}}.{{RTCRtpSender/[[SendEncodings]]}}
to true
for unpaused or to
false
for paused.
Set transceiver.{{RTCRtpTransceiver/[[Mid]]}} to transceiver.{{RTCRtpTransceiver/[[JsepMid]]}}.
Let direction be an {{RTCRtpTransceiverDirection}} value representing the direction from the [= media description =], but with the send and receive directions reversed to represent this peer's point of view. If the [= media description =] is rejected, set direction to {{RTCRtpTransceiverDirection/"inactive"}}.
If direction is {{RTCRtpTransceiverDirection/"sendrecv"}} or {{RTCRtpTransceiverDirection/"recvonly"}}, let msids be a list of the MSIDs that the media description indicates transceiver.{{RTCRtpTransceiver/[[Receiver]]}}.{{RTCRtpReceiver/[[ReceiverTrack]]}} is to be associated with. Otherwise, let msids be an empty list.
[= Process remote tracks =] with transceiver, direction, msids, addList, removeList, and trackEventInits.
Set transceiver.{{RTCRtpTransceiver/[[Receiver]]}}.{{RTCRtpReceiver/[[ReceiveCodecs]]}} to the codecs that description negotiates for receiving and which the user agent is currently prepared to receive.
If description is of type {{RTCSdpType/"answer"}} or {{RTCSdpType/"pranswer"}}, then run the following steps:
Set transceiver.{{RTCRtpTransceiver/[[Sender]]}}.{{RTCRtpSender/[[SendCodecs]]}} to the codecs that description negotiates for sending and which the user agent is currently capable of sending.
Set transceiver.{{RTCRtpTransceiver/[[CurrentDirection]]}} and transceiver.{{RTCRtpTransceiver/[[Direction]]}}s to direction.
Let transport be the {{RTCDtlsTransport}} object representing the RTP/RTCP component of the [= media transport =] used by transceiver's [= associated =] [= media description =], according to [[RFC8843]].
Set transceiver.{{RTCRtpTransceiver/[[Sender]]}}.{{RTCRtpSender/[[SenderTransport]]}} to transport.
Set transceiver.{{RTCRtpTransceiver/[[Receiver]]}}.{{RTCRtpReceiver/[[ReceiverTransport]]}} to transport.
Set the {{RTCIceTransport/[[IceRole]]}} of transport according to the rules of [[RFC8445]].
a=ice-lite
,
set {{RTCIceTransport/[[IceRole]]}} to
{{RTCIceRole/controlling}}.
a=ice-lite
,
set {{RTCIceTransport/[[IceRole]]}} to
{{RTCIceRole/controlled}}.
If the [= media description =] is rejected,
and
transceiver.{{RTCRtpTransceiver/[[Stopped]]}} is
false
, then [= stop the
RTCRtpTransceiver =] transceiver.
Otherwise, (if description is of type {{RTCSdpType/"rollback"}}) run the following steps:
Let pendingDescription be either
connection.{{RTCPeerConnection/[[PendingLocalDescription]]}}
or
connection.{{RTCPeerConnection/[[PendingRemoteDescription]]}},
whichever one is not null
.
For each transceiver in the connection's [= set of transceivers =] run the following steps:
If transceiver was not [=
associated =] with a [= media description =]
prior to pendingDescription being set,
disassociate it and set both
transceiver.{{RTCRtpTransceiver/[[JsepMid]]}}
and transceiver.{{RTCRtpTransceiver/[[Mid]]}} to
null
.
Set transceiver.{{RTCRtpTransceiver/[[Sender]]}}.{{RTCRtpSender/[[SenderTransport]]}} to transceiver.{{RTCRtpTransceiver/[[Sender]]}}.{{RTCRtpSender/[[LastStableStateSenderTransport]]}}.
Set transceiver.{{RTCRtpTransceiver/[[Receiver]]}}.{{RTCRtpReceiver/[[ReceiverTransport]]}} to transceiver.{{RTCRtpTransceiver/[[Receiver]]}}.{{RTCRtpReceiver/[[LastStableStateReceiverTransport]]}}.
Set transceiver.{{RTCRtpTransceiver/[[Receiver]]}}.{{RTCRtpReceiver/[[ReceiveCodecs]]}} to transceiver.{{RTCRtpTransceiver/[[Receiver]]}}.{{RTCRtpReceiver/[[LastStableStateReceiveCodecs]]}}.
If the signaling state of connection is {{RTCSignalingState/"have-remote-offer"}}, run the following sub steps:
Let msids be a list of the
id
s of all
{{MediaStream}} objects in
transceiver.{{RTCRtpTransceiver/[[Receiver]]}}.{{RTCRtpReceiver/[[LastStableStateAssociatedRemoteMediaStreams]]}},
or an empty list if there are none.
Process remote tracks with transceiver, transceiver.{{RTCRtpTransceiver/[[CurrentDirection]]}}, msids, addList, removeList, and trackEventInits.
If transceiver was created when pendingDescription was set, and a track has never been attached to it via {{RTCPeerConnection/addTrack()}}, then [= stop the RTCRtpTransceiver =] transceiver, and remove it from connection's [= set of transceivers =].
Set
connection.{{RTCPeerConnection/[[PendingLocalDescription]]}}
and
connection.{{RTCPeerConnection/[[PendingRemoteDescription]]}}
to null
, and set
connection's [= signaling state =] to
{{RTCSignalingState/"stable"}}.
If description is of type {{RTCSdpType/"answer"}}, then run the following steps:
For each transceiver in the connection's [= set of transceivers =] run the following steps:
If transceiver is {{RTCRtpTransceiver/stopped}}, [= associated =] with an m= section and the associated m= section is rejected in connection.{{RTCPeerConnection/[[CurrentLocalDescription]]}} or connection.{{RTCPeerConnection/[[CurrentRemoteDescription]]}}, remove the transceiver from the connection's [= set of transceivers =].
If connection's [= signaling state =] is now {{RTCSignalingState/"stable"}}, run the following steps:
For any transceiver that was removed from the [= set of transceivers =] in a previous step, if any of its transports (transceiver.{{RTCRtpTransceiver/[[Sender]]}}.{{RTCRtpSender/[[SenderTransport]]}} or transceiver.{{RTCRtpTransceiver/[[Receiver]]}}.{{RTCRtpReceiver/[[ReceiverTransport]]}}) are still not closed and they're no longer referenced by a non-stopped transceiver, close the {{RTCDtlsTransport}}s and their associated {{RTCIceTransport}}s. This results in events firing on these objects in a queued task.
[= Clear the negotiation-needed flag =] and [= update the negotiation-needed flag =].
If connection's [= signaling state =] changed above, [= fire an event =] named {{RTCPeerConnection/signalingstatechange}} at connection.
For each channel in errorList, [= fire an event =] named {{RTCDataChannel/error}} using the {{RTCErrorEvent}} interface with the {{RTCError/errorDetail}} attribute set to {{RTCErrorDetailType/"data-channel-failure"}} at channel.
For each track in muteTracks,
[= set the muted state =] of track to the
value true
.
For each stream and track pair in removeList, [= remove the track =] track from stream.
For each stream and track pair in addList, [= add the track =] track to stream.
For each entry entry in trackEventInits, [= fire an event =] named {{RTCPeerConnection/track}} using the {{RTCTrackEvent}} interface with its {{RTCTrackEvent/receiver}} attribute initialized to entry.{{RTCTrackEventInit/receiver}}, its {{RTCTrackEvent/track}} attribute initialized to entry.{{RTCTrackEventInit/track}}, its {{RTCTrackEvent/streams}} attribute initialized to entry.{{RTCTrackEventInit/streams}} and its {{RTCTrackEvent/transceiver}} attribute initialized to entry.{{RTCTrackEventInit/transceiver}} at the connection object.
[= Resolve =] p with
undefined
.
Return p.
To set a configuration, run the following steps:
Let configuration be the {{RTCConfiguration}} dictionary to be processed.
Let connection be the target {{RTCPeerConnection}} object.
If configuration.{{RTCConfiguration/certificates}} is set, run the following steps:
If the length of configuration.{{RTCConfiguration/certificates}} is different from the length of connection.{{RTCPeerConnection/[[Configuration]]}}.{{RTCConfiguration/certificates}}, [= exception/throw =] an {{InvalidModificationError}}.
Let index be initialized to 0.
Let size be initialized to the length of configuration.{{RTCConfiguration/certificates}}.
While index is less than size, run the following steps:
If the ECMAScript object represented by the value of configuration.{{RTCConfiguration/certificates}} at index is not the same as the ECMAScript object represented by the value of connection.{{RTCPeerConnection/[[Configuration]]}}.{{RTCConfiguration/certificates}} at index, [= exception/throw =] an {{InvalidModificationError}}.
Increment index by 1.
If the value of configuration.{{RTCConfiguration/bundlePolicy}} is set and its value differs from the connection's bundle policy, [= exception/throw =] an {{InvalidModificationError}}.
If the value of configuration.{{RTCConfiguration/rtcpMuxPolicy}} is set and its value differs from the connection's rtcpMux policy, [= exception/throw =] an {{InvalidModificationError}}.
If the value of configuration.{{RTCConfiguration/iceCandidatePoolSize}} is set and its value differs from the connection's previously set {{RTCConfiguration/iceCandidatePoolSize}}, and {{RTCPeerConnection/setLocalDescription}} has already been called, [= exception/throw =] an {{InvalidModificationError}}.
Set the [= ICE Agent =]'s ICE transports setting to the value of configuration.{{RTCConfiguration/iceTransportPolicy}}. As defined in [[!RFC8829]], if the new [= ICE transports setting =] changes the existing setting, no action will be taken until the next gathering phase. If a script wants this to happen immediately, it should do an ICE restart.
Set the [= ICE Agent =]'s prefetched ICE candidate pool size as defined in [[!RFC8829]] to the value of configuration.{{RTCConfiguration/iceCandidatePoolSize}}. If the new [= ICE candidate pool size =] changes the existing setting, this may result in immediate gathering of new pooled candidates, or discarding of existing pooled candidates, as defined in [[!RFC8829]].
Let validatedServers be an empty list.
If configuration.{{RTCConfiguration/iceServers}} is defined, then run the following steps for each element:
Let server be the current list element.
Let urls be server.{{RTCIceServer/urls}}.
If urls is a string, set urls to a list consisting of just that string.
If urls is empty, [= exception/throw =] a {{SyntaxError}}.
For each url in urls run the following steps:
Parse the url using the generic URI syntax
defined in [[!RFC3986]] and obtain the scheme
name. If the parsing based on the syntax
defined in [[!RFC3986]] fails, [= exception/throw =]
a {{SyntaxError}}. If the scheme name is
not implemented by the browser [= exception/throw =]
a {{NotSupportedError}}. If scheme name is
turn
or turns
, and parsing the url
using the syntax defined in [[!RFC7065]] fails, [=
exception/throw =] a {{SyntaxError}}. If scheme
name is stun
or
stuns
, and parsing the
url using the syntax defined in
[[!RFC7064]] fails, [= exception/throw =] a
{{SyntaxError}}.
If scheme name is turn
or turns
, and either of
server.{{RTCIceServer/username}} or
server.{{RTCIceServer/credential}} are
omitted, then [= exception/throw =] an
{{InvalidAccessError}}.
If scheme name is turn
or turns
, and
server.{{RTCIceServer/credentialType}} is
{{RTCIceCredentialType/"password"}}, and
server.{{RTCIceServer/credential}} is not
a DOMString, then
[= exception/throw =] an {{InvalidAccessError}}.
Append server to validatedServers.
Set the [= ICE Agent =]'s ICE servers list to validatedServers.
As defined in [[!RFC8829]], if a new list of servers replaces the [= ICE Agent =]'s existing ICE servers list, no action will be taken until the next gathering phase. If a script wants this to happen immediately, it should do an ICE restart. However, if the [= ICE candidate pool size | ICE candidate pool =] has a nonzero size, any existing pooled candidates will be discarded, and new candidates will be gathered from the new servers.
Store configuration in the {{RTCPeerConnection/[[Configuration]]}} internal slot.
The RTCPeerConnection interface presented in this section is extended by several partial interfaces throughout this specification. Notably, the [= RTP Media API =] section, which adds the APIs to send and receive {{MediaStreamTrack}} objects.
[Exposed=Window] interface RTCPeerConnection : EventTarget { constructor(optional RTCConfiguration configuration = {}); Promise<RTCSessionDescriptionInit> createOffer(optional RTCOfferOptions options = {}); Promise<RTCSessionDescriptionInit> createAnswer(optional RTCAnswerOptions options = {}); Promise<undefined> setLocalDescription(optional RTCLocalSessionDescriptionInit description = {}); readonly attribute RTCSessionDescription? localDescription; readonly attribute RTCSessionDescription? currentLocalDescription; readonly attribute RTCSessionDescription? pendingLocalDescription; Promise<undefined> setRemoteDescription(RTCSessionDescriptionInit description); readonly attribute RTCSessionDescription? remoteDescription; readonly attribute RTCSessionDescription? currentRemoteDescription; readonly attribute RTCSessionDescription? pendingRemoteDescription; Promise<undefined> addIceCandidate(optional RTCIceCandidateInit candidate = {}); readonly attribute RTCSignalingState signalingState; readonly attribute RTCIceGatheringState iceGatheringState; readonly attribute RTCIceConnectionState iceConnectionState; readonly attribute RTCPeerConnectionState connectionState; readonly attribute boolean? canTrickleIceCandidates; undefined restartIce(); RTCConfiguration getConfiguration(); undefined setConfiguration(optional RTCConfiguration configuration = {}); undefined close(); attribute EventHandler onnegotiationneeded; attribute EventHandler onicecandidate; attribute EventHandler onicecandidateerror; attribute EventHandler onsignalingstatechange; attribute EventHandler oniceconnectionstatechange; attribute EventHandler onicegatheringstatechange; attribute EventHandler onconnectionstatechange; // Legacy Interface Extensions // Supporting the methods in this section is optional. // If these methods are supported // they must be implemented as defined // in section "Legacy Interface Extensions" Promise<undefined> createOffer(RTCSessionDescriptionCallback successCallback, RTCPeerConnectionErrorCallback failureCallback, optional RTCOfferOptions options = {}); Promise<undefined> setLocalDescription(RTCLocalSessionDescriptionInit description, VoidFunction successCallback, RTCPeerConnectionErrorCallback failureCallback); Promise<undefined> createAnswer(RTCSessionDescriptionCallback successCallback, RTCPeerConnectionErrorCallback failureCallback); Promise<undefined> setRemoteDescription(RTCSessionDescriptionInit description, VoidFunction successCallback, RTCPeerConnectionErrorCallback failureCallback); Promise<undefined> addIceCandidate(RTCIceCandidateInit candidate, VoidFunction successCallback, RTCPeerConnectionErrorCallback failureCallback); };
The {{localDescription}} attribute MUST return
{{RTCPeerConnection/[[PendingLocalDescription]]}} if it is not
null
and otherwise it MUST return
{{RTCPeerConnection/[[CurrentLocalDescription]]}}.
Note that {{RTCPeerConnection/[[CurrentLocalDescription]]}}.{{RTCSessionDescription/sdp}} and {{RTCPeerConnection/[[PendingLocalDescription]]}}.{{RTCSessionDescription/sdp}} need not be string-wise identical to the {{RTCSessionDescriptionInit/sdp}} value passed to the corresponding {{setLocalDescription}} call (i.e. SDP may be parsed and reformatted, and ICE candidates may be added).
The {{currentLocalDescription}} attribute MUST return {{RTCPeerConnection/[[CurrentLocalDescription]]}}.
It represents the local description that was successfully negotiated the last time the {{RTCPeerConnection}} transitioned into the stable state plus any local candidates that have been generated by the [= ICE Agent =] since the offer or answer was created.
The {{pendingLocalDescription}} attribute MUST return {{RTCPeerConnection/[[PendingLocalDescription]]}}.
It represents a local description that is in the process of
being negotiated plus any local candidates that have been
generated by the [= ICE Agent =] since the offer or answer
was created. If the {{RTCPeerConnection}} is in the stable
state, the value is null
.
The {{remoteDescription}} attribute MUST return
{{RTCPeerConnection/[[PendingRemoteDescription]]}} if it is not
null
and otherwise it MUST return
{{RTCPeerConnection/[[CurrentRemoteDescription]]}}.
Note that {{RTCPeerConnection/[[CurrentRemoteDescription]]}}.{{RTCSessionDescription/sdp}} and {{RTCPeerConnection/[[PendingRemoteDescription]]}}.{{RTCSessionDescription/sdp}} need not be string-wise identical to the {{RTCSessionDescriptionInit/sdp}} value passed to the corresponding {{setRemoteDescription}} call (i.e. SDP may be parsed and reformatted, and ICE candidates may be added).
The {{currentRemoteDescription}} attribute MUST return {{RTCPeerConnection/[[CurrentRemoteDescription]]}}.
It represents the last remote description that was successfully negotiated the last time the {{RTCPeerConnection}} transitioned into the stable state plus any remote candidates that have been supplied via {{RTCPeerConnection/addIceCandidate()}} since the offer or answer was created.
The {{pendingRemoteDescription}} attribute MUST return {{RTCPeerConnection/[[PendingRemoteDescription]]}}.
It represents a remote description that is in the process
of being negotiated, complete with any remote candidates
that have been supplied via
{{RTCPeerConnection/addIceCandidate()}} since the offer or
answer was created. If the {{RTCPeerConnection}} is in the
stable state, the value is null
.
The {{signalingState}} attribute MUST return the {{RTCPeerConnection/RTCPeerConnection}} object's [= signaling state =].
The {{iceGatheringState}} attribute MUST return the [= ICE gathering state =] of the {{RTCPeerConnection}} instance.
The {{iceConnectionState}} attribute MUST return the [= ICE connection state =] of the {{RTCPeerConnection}} instance.
The {{connectionState}} attribute MUST return the [= connection state =] of the {{RTCPeerConnection}} instance.
The {{canTrickleIceCandidates}} attribute indicates whether
the remote peer is able to accept trickled ICE candidates
[[RFC8838]]. The value is determined based on whether a
remote description indicates support for trickle ICE, as
defined in [[!RFC8829]].
Prior to the completion of
{{RTCPeerConnection/setRemoteDescription}}, this value is
null
.
{{createOffer}} メソッドは、この {{RTCPeerConnection}} に接続されているローカルの {{MediaStreamTrack}} の説明、この実装でサポートされているコーデック/RTP/RTCP 機能、[= ICE agent =] と DTLS 接続のパラメータなど、セッションでサポートされている設定を含む RFC 3264 オファーを含む SDP の blob を生成します。生成されたオファーをさらに制御するために、options パラメータを指定することができます。
システムのリソースが限られている場合(例:デコーダの数が限られている)、{{createOffer}} はシステムの現在の状態を反映したオファーを返す必要があり、{{setLocalDescription}} がそれらのリソースを取得しようとするときに成功するようにします。セッション記述は、少なくとも返されたプロミスの [= fulfillment =] コールバックが終了するまで、エラーを起こすことなく {{setLocalDescription}} で使用可能なままでなければなりません (MUST)。
SDP の作成は、[[!RFC8829]] に記載されているオファーを生成するための適切なプロセスに従わなければならない(MUST)。ただし、ユーザーエージェントはこの場合、RFC8829 の目的のために {{RTCRtpTransceiver/stopping}} トランシーバーを {{RTCRtpTransceiver/stopped}} として扱わなければなりません(MUST)。
オファーの場合、生成された SDP には、セッションでサポートまたは優先される コーデック/RTP/RTCP 機能のフルセットが含まれる(アンサーの場合は、使 用する特定のネゴシエート済みサブセットのみが含まれる)が、これとは対照的である。セッションが確立された後に {{createOffer}} が呼び出された場合、{{createOffer}} は現在のセッションと互換性のあるオファーを生成し、最後の完全なオファーとアンサーの交換以降に行われた変更(トラックの追加や削除など)を反映します。変更がない場合、オファーには現在のローカル記述の機能に加えて、更新されたオファーで交渉可能な追加機能が含まれます。
生成された SDP には、[= ICE agent =] の {{RTCIceParameters/usernameFragment}}、{{RTCIceParameters/password}、ICE オプション([[RFC5245]]のセクション 14 で定義されているもの)も含まれており、エージェントが収集したローカル候補も含まれている可能性があります。
{{RTCPeerConnection}} の configuration にある {{RTCConfiguration/certificates}} の値は、{{RTCPeerConnection}} のためにアプリケーションが構成した証明書を提供します。これらの証明書は、デフォルトの証明書とともに、一連の証明書フィンガープリントを生成するために使用されます。これらの証明書フィンガープリントは、SDP の構築に使用されます。
SDP を生成するプロセスでは、基礎となるシステムのメディア機能のサブセットが公開され、デバイス上の一般的に永続的なクロスオリジン情報が提供されます。そのため、アプリケーションのフィンガープリントの対象が増えることになる。プライバシーが重視されるコンテキストでは、ブラウザは、能力の共通サブセットのみに一致する SDP を生成するなどの緩和策を検討することができます。
When the method is called, the user agent MUST run the following steps:
Let connection be the {{RTCPeerConnection}} object on which the method was invoked.
If connection.{{RTCPeerConnection/[[IsClosed]]}} is
true
, return a promise [= rejected =] with
a newly [= exception/created =] {{InvalidStateError}}.
Return the result of [= chaining =] the result of [= creating an offer =] with connection to connection's [= operations chain =].
To create an offer given connection run the following steps:
If connection's [= signaling state =] is neither {{RTCSignalingState/"stable"}} nor {{RTCSignalingState/"have-local-offer"}}, return a promise [= rejected =] with a newly [= exception/created =] {{InvalidStateError}}.
Let p be a new promise.
In parallel, begin the [= in-parallel steps to create an offer =] given connection and p.
Return p.
The in-parallel steps to create an offer given connection and a promise p are as follows:
If connection was not constructed with a set of certificates, and one has not yet been generated, wait for it to be generated.
Inspect the offerer's system state to determine the currently available resources as necessary for generating the offer, as described in [[!RFC8829]].
If this inspection failed for any reason, [= reject =] p with a newly [= exception/created =] {{OperationError}} and abort these steps.
Queue a task that runs the [= final steps to create an offer =] given connection and p.
The final steps to create an offer given connection and a promise p are as follows:
If connection.{{RTCPeerConnection/[[IsClosed]]}} is
true
, then abort these steps.
If connection was modified in such a way that additional inspection of the [= offerer's system state =] is necessary, then in parallel begin the [= in-parallel steps to create an offer =] again, given connection and p, and abort these steps.
Given the information that was obtained from previous inspection, the current state of connection and its {{RTCRtpTransceiver}}s, generate an SDP offer, sdpString, as described in [[!RFC8829]].
As described in [[RFC8843]] (Section 7), if bundling is used (see {{RTCBundlePolicy}}) an offerer tagged m= section must be selected in order to negotiate a BUNDLE group. The user agent MUST choose the m= section that corresponds to the first non-stopped transceiver in the [= set of transceivers =] as the offerer tagged m= section. This allows the remote endpoint to predict which transceiver is the offerer tagged m= section without having to parse the SDP.
The codec preferences of a [= media description =]'s [= associated =] transceiver is said to be the value of the {{RTCRtpTransceiver}}.{{RTCRtpTransceiver/[[PreferredCodecs]]}} with the following filtering applied (or said not to be set if {{RTCRtpTransceiver/[[PreferredCodecs]]}} is empty):
If the {{RTCRtpTransceiver/direction}} is {{RTCRtpTransceiverDirection/"sendrecv"}}, exclude any codecs not included in the intersection of {{RTCRtpSender}}.{{RTCRtpSender/getCapabilities}}(kind).{{RTCRtpCapabilities/codecs}} and {{RTCRtpReceiver}}.{{RTCRtpReceiver/getCapabilities}}(kind).{{RTCRtpCapabilities/codecs}}.
If the {{RTCRtpTransceiver/direction}} is {{RTCRtpTransceiverDirection/"sendonly"}}, exclude any codecs not included in {{RTCRtpSender}}.{{RTCRtpSender/getCapabilities}}(kind).{{RTCRtpCapabilities/codecs}}.
If the {{RTCRtpTransceiver/direction}} is {{RTCRtpTransceiverDirection/"recvonly"}}, exclude any codecs not included in {{RTCRtpReceiver}}.{{RTCRtpReceiver/getCapabilities}}(kind).{{RTCRtpCapabilities/codecs}}.
The filtering MUST NOT change the order of the codec preferences.
If the length of the {{RTCRtpSender/[[SendEncodings]]}} slot
of the {{RTCRtpSender}} is larger than 1, then for
each encoding given in {{RTCRtpSender/[[SendEncodings]]}} of
the {{RTCRtpSender}}, add an a=rid send
line to the corresponding
media section, and add an a=simulcast:send
line giving the RIDs
in the same order as given in the
{{RTCRtpSendParameters/encodings}} field. No RID
restrictions are set.
[[RFC8853]] section 5.2 specifies that the order of RIDs in the a=simulcast line suggests a proposed order of preference. If the browser decides not to transmit all encodings, one should expect it to stop sending the last encoding in the list first.
Let offer be a newly created {{RTCSessionDescriptionInit}} dictionary with its {{RTCSessionDescriptionInit/type}} member initialized to the string {{RTCSdpType/"offer"}} and its {{RTCSessionDescriptionInit/sdp}} member initialized to sdpString.
Set the {{RTCPeerConnection/[[LastCreatedOffer]]}} internal slot to sdpString.
[= Resolve =] p with offer.
The {{createAnswer}} method generates an [[!SDP]] answer with the supported configuration for the session that is compatible with the parameters in the remote configuration. Like {{createOffer}}, the returned blob of SDP contains descriptions of the local {{MediaStreamTrack}}s attached to this {{RTCPeerConnection}}, the codec/RTP/RTCP options negotiated for this session, and any candidates that have been gathered by the [= ICE Agent =]. The options parameter may be supplied to provide additional control over the generated answer.
Like {{createOffer}}, the returned description SHOULD reflect the current state of the system. The session descriptions MUST remain usable by {{setLocalDescription}} without causing an error until at least the end of the [= fulfillment =] callback of the returned promise.
As an answer, the generated SDP will contain a specific codec/RTP/RTCP configuration that, along with the corresponding offer, specifies how the media plane should be established. The generation of the SDP MUST follow the appropriate process for generating an answer described in [[!RFC8829]].
The generated SDP will also contain the [= ICE agent =]'s {{RTCIceParameters/usernameFragment}}, {{RTCIceParameters/password}} and ICE options (as defined in [[RFC5245]], Section 14) and may also contain any local candidates that have been gathered by the agent.
The {{RTCConfiguration/certificates}} value in configuration for the {{RTCPeerConnection}} provides the certificates configured by the application for the {{RTCPeerConnection}}. These certificates, along with any default certificates are used to produce a set of certificate fingerprints. These certificate fingerprints are used in the construction of SDP.
An answer can be marked as provisional, as described in [[!RFC8829]], by setting the {{RTCSessionDescriptionInit/type}} to {{RTCSdpType/"pranswer"}}.
When the method is called, the user agent MUST run the following steps:
Let connection be the {{RTCPeerConnection}} object on which the method was invoked.
If connection.{{RTCPeerConnection/[[IsClosed]]}} is
true
, return a promise [= rejected =] with
a newly [= exception/created =] {{InvalidStateError}}.
Return the result of [= chaining =] the result of [= creating an answer =] with connection to connection's [= operations chain =].
To create an answer given connection run the following steps:
If connection's [= signaling state =] is neither {{RTCSignalingState/"have-remote-offer"}} nor {{RTCSignalingState/"have-local-pranswer"}}, return a promise [= rejected =] with a newly [= exception/created =] {{InvalidStateError}}.
Let p be a new promise.
In parallel, begin the [= in-parallel steps to create an answer =] given connection and p.
Return p.
The in-parallel steps to create an answer given connection and a promise p are as follows:
If connection was not constructed with a set of certificates, and one has not yet been generated, wait for it to be generated.
Inspect the answerer's system state to determine the currently available resources as necessary for generating the answer, as described in [[!RFC8829]].
If this inspection failed for any reason, [= reject =] p with a newly [= exception/created =] {{OperationError}} and abort these steps.
Queue a task that runs the [= final steps to create an answer =] given p.
The final steps to create an answer given a promise p are as follows:
If connection.{{RTCPeerConnection/[[IsClosed]]}} is
true
, then abort these steps.
If connection was modified in such a way that additional inspection of the [= answerer's system state =] is necessary, then in parallel begin the [= in-parallel steps to create an answer =] again given connection and p, and abort these steps.
Given the information that was obtained from previous inspection and the current state of connection and its {{RTCRtpTransceiver}}s, generate an SDP answer, sdpString, as described in [[!RFC8829]].
The codec preferences of an m= section's associated transceiver is said to be the value of the {{RTCRtpTransceiver}}.{{RTCRtpTransceiver/[[PreferredCodecs]]}} with the following filtering applied (or said not to be set if {{RTCRtpTransceiver/[[PreferredCodecs]]}} is empty):
If the {{RTCRtpTransceiver/direction}} is {{RTCRtpTransceiverDirection/"sendrecv"}}, exclude any codecs not included in the intersection of {{RTCRtpSender}}.{{RTCRtpSender/getCapabilities}}(kind).{{RTCRtpCapabilities/codecs}} and {{RTCRtpReceiver}}.{{RTCRtpReceiver/getCapabilities}}(kind).{{RTCRtpCapabilities/codecs}}.
If the {{RTCRtpTransceiver/direction}} is {{RTCRtpTransceiverDirection/"sendonly"}}, exclude any codecs not included in {{RTCRtpSender}}.{{RTCRtpSender/getCapabilities}}(kind).{{RTCRtpCapabilities/codecs}}.
If the {{RTCRtpTransceiver/direction}} is {{RTCRtpTransceiverDirection/"recvonly"}}, exclude any codecs not included in {{RTCRtpReceiver}}.{{RTCRtpReceiver/getCapabilities}}(kind).{{RTCRtpCapabilities/codecs}}.
The filtering MUST NOT change the order of the codec preferences.
If the length of the {{RTCRtpSender/[[SendEncodings]]}} slot
of the {{RTCRtpSender}} is larger than 1, then for
each encoding given in {{RTCRtpSender/[[SendEncodings]]}} of
the {{RTCRtpSender}}, add an a=rid send
line to the corresponding
media section, and add an a=simulcast:send
line giving the RIDs
in the same order as given in the
{{RTCRtpSendParameters/encodings}} field. No RID
restrictions are set.
Let answer be a newly created {{RTCSessionDescriptionInit}} dictionary with its {{RTCSessionDescriptionInit/type}} member initialized to the string {{RTCSdpType/"answer"}} and its {{RTCSessionDescriptionInit/sdp}} member initialized to sdpString.
Set the {{RTCPeerConnection/[[LastCreatedAnswer]]}} internal slot to sdpString.
[= Resolve =] p with answer.
The {{setLocalDescription}} method instructs the {{RTCPeerConnection}} to apply the supplied {{RTCLocalSessionDescriptionInit}} as the local description.
This API changes the local media state. In order to successfully handle scenarios where the application wants to offer to change from one media format to a different, incompatible format, the {{RTCPeerConnection}} MUST be able to simultaneously support use of both the current and pending local descriptions (e.g. support codecs that exist in both descriptions) until a final answer is received, at which point the {{RTCPeerConnection}} can fully adopt the pending local description, or rollback to the current description if the remote side rejected the change.
Passing in a description is optional. If left out, then {{setLocalDescription}} will implicitly [= create an offer =] or [= create an answer =], as needed. As noted in [[!RFC8829]], if a description with SDP is passed in, that SDP is not allowed to have changed from when it was returned from either {{createOffer}} or {{createAnswer}}.
When the method is invoked, the user agent MUST run the following steps:
Let description be the method's first argument.
Let connection be the {{RTCPeerConnection}} object on which the method was invoked.
Let sdp be description.{{RTCSessionDescriptionInit/sdp}}.
Return the result of [= chaining =] the following steps to connection's [= operations chain =]:
Let type be description.{{RTCSessionDescriptionInit/type}} if present, or {{RTCSdpType/"offer"}} if not present and connection's [= signaling state =] is either {{RTCSignalingState/"stable"}}, {{RTCSignalingState/"have-local-offer"}}, or {{RTCSignalingState/"have-remote-pranswer"}}; otherwise {{RTCSdpType/"answer"}}.
If type is {{RTCSdpType/"offer"}}, and sdp is not the empty string and not equal to connection.{{RTCPeerConnection/[[LastCreatedOffer]]}}, then return a promise [= rejected =] with a newly [= exception/created =] {{InvalidModificationError}} and abort these steps.
If type is {{RTCSdpType/"answer"}} or {{RTCSdpType/"pranswer"}}, and sdp is not the empty string and not equal to connection.{{RTCPeerConnection/[[LastCreatedAnswer]]}}, then return a promise [= rejected =] with a newly [= exception/created =] {{InvalidModificationError}} and abort these steps.
If sdp is the empty string, and type is {{RTCSdpType/"offer"}}, then run the following sub steps:
Set sdp to the value of connection.{{RTCPeerConnection/[[LastCreatedOffer]]}}.
If sdp is the empty string, or if it no longer accurately represents the [= offerer's system state =] of connection, then let p be the result of [= creating an offer =] with connection, and return the result of [= promise/reacting =] to p with a fulfillment step that [= set a local session description | sets the local session description =] indicated by its first argument.
If sdp is the empty string, and type is {{RTCSdpType/"answer"}} or {{RTCSdpType/"pranswer"}}, then run the following sub steps:
Set sdp to the value of connection.{{RTCPeerConnection/[[LastCreatedAnswer]]}}.
If sdp is the empty string, or if it no longer accurately represents the [= answerer's system state =] of connection, then let p be the result of [= creating an answer =] with connection, and return the result of [= promise/reacting =] to p with the following fulfillment steps:
Let answer be the first argument to these fulfillment steps.
Return the result of [= setting the local
session description =] indicated by
{type,
answer.{{RTCSessionDescriptionInit/sdp}}}
.
Return the result of [= setting the local
session description =] indicated by {type, sdp}
.
As noted in [[!RFC8829]], calling this method may trigger the ICE candidate gathering process by the [= ICE Agent =].
The {{setRemoteDescription}} method instructs the {{RTCPeerConnection}} to apply the supplied {{RTCSessionDescriptionInit}} as the remote offer or answer. This API changes the local media state.
When the method is invoked, the user agent MUST run the following steps:
Let description be the method's first argument.
Let connection be the {{RTCPeerConnection}} object on which the method was invoked.
Return the result of [= chaining =] the following steps to connection's [= operations chain =]:
If description.{{RTCSessionDescriptionInit/type}} is {{RTCSdpType/"offer"}} and is invalid for the current [= signaling state =] of connection as described in [[!RFC8829]], then run the following sub steps:
Let p be the result of [= setting
the local session description =] indicated by
{type:
{{RTCSdpType/"rollback"}}}
.
Return the result of [= promise/reacting =] to p with a fulfillment step that [= set a remote session description | sets the remote session description =] description, and abort these steps.
Return the result of [= setting the remote session description =] description.
The {{addIceCandidate}} method provides a remote candidate to the [= ICE Agent =]. This method can also be used to indicate the end of remote candidates when called with an empty string for the {{RTCIceCandidate/candidate}} member. The only members of the argument used by this method are {{RTCIceCandidate/candidate}}, {{RTCIceCandidate/sdpMid}}, {{RTCIceCandidate/sdpMLineIndex}}, and {{RTCIceCandidate/usernameFragment}}; the rest are ignored. When the method is invoked, the user agent MUST run the following steps:
Let candidate be the method's argument.
Let connection be the {{RTCPeerConnection}} object on which the method was invoked.
If candidate.{{RTCIceCandidate/candidate}}
is not an empty string and both
candidate.{{RTCIceCandidate/sdpMid}} and
candidate.{{RTCIceCandidate/sdpMLineIndex}}
are null
, return a promise [= rejected =]
with a newly [= exception/created =] {{TypeError}}.
Return the result of [= chaining =] the following steps to connection's [= operations chain =]:
If {{RTCPeerConnection/remoteDescription}} is
null
return a promise [= rejected =]
with a newly [= exception/created =]
{{InvalidStateError}}.
If candidate.{{RTCIceCandidate/sdpMid}}
is not null
, run the following steps:
If candidate.{{RTCIceCandidate/sdpMid}} is not equal to the mid of any media description in {{RTCPeerConnection/remoteDescription}}, return a promise [= rejected =] with a newly [= exception/created =] {{OperationError}}.
Else, if
candidate.{{RTCIceCandidate/sdpMLineIndex}}
is not null
, run the following steps:
If candidate.{{RTCIceCandidate/sdpMLineIndex}} is equal to or larger than the number of media descriptions in {{RTCPeerConnection/remoteDescription}}, return a promise [= rejected =] with a newly [= exception/created =] {{OperationError}}.
If either
candidate.{{RTCIceCandidate/sdpMid}} or
candidate.{{RTCIceCandidate/sdpMLineIndex}}
indicate a media description in
{{RTCPeerConnection/remoteDescription}} whose
associated transceiver is {{RTCRtpTransceiver/
stopped}}, return a promise [= resolved =] with
undefined
.
If
candidate.{{RTCIceCandidate/usernameFragment}}
is not null
, and is not equal to any
username fragment present in the corresponding [=
media description =] of an applied remote
description, return a promise [= rejected =] with a
newly [= exception/created =] {{OperationError}}.
Let p be a new promise.
In parallel, if the candidate is not [=
administratively prohibited =], add the ICE
candidate candidate as described in
[[!RFC8829]].
Use
candidate.{{RTCIceCandidate/usernameFragment}}
to identify the ICE [= generation =]; if
{{RTCIceCandidate/usernameFragment}} is
null
, process the candidate
for the most recent ICE [= generation =].
If
candidate.{{RTCIceCandidate/candidate}}
is an empty string, process candidate as
an end-of-candidates indication for the
corresponding [= media description =] and ICE
candidate [= generation =]. If both
candidate.{{RTCIceCandidate/sdpMid}} and
candidate.{{RTCIceCandidate/sdpMLineIndex}}
are null
, then this end-of-candidates
indication applies to all [=
media description =]s.
If candidate could not be successfully added the user agent MUST queue a task that runs the following steps:
If
connection.{{RTCPeerConnection/[[IsClosed]]}}
is true
, then abort these
steps.
[= Reject =] p with a newly [= exception/created =] {{OperationError}} and abort these steps.
If candidate is applied successfully, or if the candidate was [= administratively prohibited =] the user agent MUST queue a task that runs the following steps:
If
connection.{{RTCPeerConnection/[[IsClosed]]}}
is true
, then abort these
steps.
If
connection.{{RTCPeerConnection/[[PendingRemoteDescription]]}}
is not null
, and represents
the ICE [= generation =] for which
candidate was processed, add
candidate to
connection.{{RTCPeerConnection/[[PendingRemoteDescription]]}}.sdp.
If
connection.{{RTCPeerConnection/[[CurrentRemoteDescription]]}}
is not null
, and represents
the ICE [= generation =] for which
candidate was processed, add
candidate to
connection.{{RTCPeerConnection/[[CurrentRemoteDescription]]}}.sdp.
[= Resolve =] p with
undefined
.
Return p.
A candidate is administratively prohibited if the UA has decided not to allow connection attempts to this address.
For privacy reasons, there is no indication to the developer about whether or not an address/port is blocked; it behaves exactly as if there was no response from the address.
The UA MUST prohibit connections to addresses on the [[!Fetch]] [= block bad port =] list, and MAY choose to prohibit connections to other addresses.
If the {{RTCConfiguration/iceTransportPolicy}} member of the {{RTCConfiguration}} is {{RTCIceTransportPolicy/relay}}, candidates requiring external resolution, such as mDNS candidates and DNS candidates, MUST be prohibited.
Due to WebIDL processing,
{{RTCPeerConnection/addIceCandidate}}(null
) is
interpreted as a call with the default dictionary present,
which, in the above algorithm, indicates end-of-candidates
for all media descriptions and ICE candidate generation.
This is by design for legacy reasons.
The {{restartIce}} method tells the {{RTCPeerConnection}} that ICE should be restarted. Subsequent calls to {{createOffer}} will create descriptions that will restart ICE, as described in section 9.1.1.1 of [[RFC5245]].
When this method is invoked, the user agent MUST run the following steps:
Let connection be the {{RTCPeerConnection}} on which the method was invoked.
Empty connection.{{RTCPeerConnection/[[LocalIceCredentialsToReplace]]}}, and populate it with all ICE credentials (ice-ufrag and ice-pwd as defined in section 15.4 of [[RFC5245]]) found in connection.{{RTCPeerConnection/[[CurrentLocalDescription]]}}, as well as all ICE credentials found in connection.{{RTCPeerConnection/[[PendingLocalDescription]]}}.
[= Update the negotiation-needed flag =] for connection.
Returns an {{RTCConfiguration}} object representing the current configuration of this {{RTCPeerConnection}} object.
When this method is called, the user agent MUST return the {{RTCConfiguration}} object stored in the {{RTCPeerConnection/[[Configuration]]}} internal slot.
The {{setConfiguration}} method updates the configuration of this {{RTCPeerConnection}} object. This includes changing the configuration of the [= ICE Agent =]. As noted in [[!RFC8829]], when the ICE configuration changes in a way that requires a new gathering phase, an ICE restart is required.
When the {{setConfiguration}} method is invoked, the user agent MUST run the following steps:
Let connection be the {{RTCPeerConnection}} on which the method was invoked.
If connection.{{RTCPeerConnection/[[IsClosed]]}} is
true
, [= exception/throw =] an
{{InvalidStateError}}.
[= Set the configuration =] specified by configuration.
When the {{close}} method is invoked, the user agent MUST run the following steps:
Let connection be the {{RTCPeerConnection}} object on which the method was invoked.
false
.
The close the connection algorithm given a connection and a disappear boolean, is as follows:
If connection.{{RTCPeerConnection/[[IsClosed]]}} is
true
, abort these steps.
Set connection.{{RTCPeerConnection/[[IsClosed]]}} to
true
.
Set connection's [= signaling state =] to {{RTCSignalingState/"closed"}}. This does not fire any event.
Let transceivers be the result of executing the {{CollectTransceivers}} algorithm. For every {{RTCRtpTransceiver}} transceiver in transceivers, run the following steps:
If transceiver.{{RTCRtpTransceiver/[[Stopped]]}} is
true
, abort these sub steps.
[= Stop the RTCRtpTransceiver =] with transceiver and disappear.
Set the {{RTCDataChannel/[[ReadyState]]}} slot of each of connection's {{RTCDataChannel}}s to {{RTCDataChannelState/"closed"}}.
If connection.{{RTCPeerConnection/[[SctpTransport]]}} is
not null
, tear down the underlying SCTP
association by sending an SCTP ABORT chunk and set the
{{RTCSctpTransport/[[SctpTransportState]]}} to
{{RTCSctpTransportState/"closed"}}.
Set the {{RTCDtlsTransport/[[DtlsTransportState]]}} slot of each of connection's {{RTCDtlsTransport}}s to {{RTCDtlsTransportState/"closed"}}.
Destroy connection's [= ICE Agent =], abruptly ending any active ICE processing and releasing any relevant resources (e.g. TURN permissions).
Set the {{RTCIceTransport/[[IceTransportState]]}} slot of each of connection's {{RTCIceTransport}}s to {{RTCIceTransportState/"closed"}}.
Set connection's [= ICE connection state =] to {{RTCIceConnectionState/"closed"}}. This does not fire any event.
Set connection's [= connection state =] to {{RTCPeerConnectionState/"closed"}}. This does not fire any event.
Supporting the methods in this section is optional. However, if these methods are supported it is mandatory to implement according to what is specified here.
addStream
method that used to exist on
{{RTCPeerConnection}} is easy to polyfill as:
RTCPeerConnection.prototype.addStream = function(stream) { stream.getTracks().forEach((track) => this.addTrack(track, stream)); };
When the createOffer
method
is called, the user agent MUST run the following steps:
Let successCallback be the method's first argument.
Let failureCallback be the callback indicated by the method's second argument.
Let options be the callback indicated by the method's third argument.
Run the steps specified by {{RTCPeerConnection}}'s {{RTCPeerConnection/createOffer()}} method with options as the sole argument, and let p be the resulting promise.
Upon [= fulfillment =] of p with value offer, invoke successCallback with offer as the argument.
Upon [= rejection =] of p with reason r, invoke failureCallback with r as the argument.
Return a promise [= resolved =] with
undefined
.
When the setLocalDescription
method is called,
the user agent MUST run the following steps:
Let description be the method's first argument.
Let successCallback be the callback indicated by the method's second argument.
Let failureCallback be the callback indicated by the method's third argument.
Run the steps specified by {{RTCPeerConnection}}'s {{RTCPeerConnection/setLocalDescription}} method with description as the sole argument, and let p be the resulting promise.
Upon [= fulfillment =] of p, invoke
successCallback with
undefined
as the argument.
Upon [= rejection =] of p with reason r, invoke failureCallback with r as the argument.
Return a promise [= resolved =] with
undefined
.
createAnswer
method does not take an {{RTCAnswerOptions}} parameter,
since no known legacy createAnswer
implementation ever
supported it.
When the createAnswer
method is called, the user agent MUST run the following
steps:
Let successCallback be the method's first argument.
Let failureCallback be the callback indicated by the method's second argument.
Run the steps specified by {{RTCPeerConnection}}'s {{RTCPeerConnection/createAnswer()}} method with no arguments, and let p be the resulting promise.
Upon [= fulfillment =] of p with value answer, invoke successCallback with answer as the argument.
Upon [= rejection =] of p with reason r, invoke failureCallback with r as the argument.
Return a promise [= resolved =] with
undefined
.
When the setRemoteDescription
method is called,
the user agent MUST run the following steps:
Let description be the method's first argument.
Let successCallback be the callback indicated by the method's second argument.
Let failureCallback be the callback indicated by the method's third argument.
Run the steps specified by {{RTCPeerConnection}}'s {{RTCPeerConnection/setRemoteDescription}} method with description as the sole argument, and let p be the resulting promise.
Upon [= fulfillment =] of p, invoke
successCallback with
undefined
as the argument.
Upon [= rejection =] of p with reason r, invoke failureCallback with r as the argument.
Return a promise [= resolved =] with
undefined
.
When the addIceCandidate
method is called, the user agent MUST run the following
steps:
Let candidate be the method's first argument.
Let successCallback be the callback indicated by the method's second argument.
Let failureCallback be the callback indicated by the method's third argument.
Run the steps specified by {{RTCPeerConnection}}'s {{RTCPeerConnection/addIceCandidate()}} method with candidate as the sole argument, and let p be the resulting promise.
Upon [= fulfillment =] of p, invoke
successCallback with
undefined
as the argument.
Upon [= rejection =] of p with reason r, invoke failureCallback with r as the argument.
Return a promise [= resolved =] with
undefined
.
These callbacks are only used on the legacy APIs.
callback RTCPeerConnectionErrorCallback = undefined (DOMException error);
error
of type
{{DOMException}}
callback RTCSessionDescriptionCallback = undefined (RTCSessionDescriptionInit description);
This section describes a set of legacy extensions that may be used to influence how an offer is created, in addition to the media added to the {{RTCPeerConnection}}. Developers are encouraged to use the {{RTCRtpTransceiver}} API instead.
When {{RTCPeerConnection/createOffer}} is called with any of the legacy options specified in this section, run the followings steps instead of the regular {{RTCPeerConnection/createOffer}} steps:
Let options be the methods first argument.
Let connection be the current {{RTCPeerConnection}} object.
For each offerToReceive<Kind>
member in options with kind, kind, run
the following steps:
For each non-stopped {{RTCRtpTransceiverDirection/"sendrecv"}} transceiver of [= transceiver kind =] kind, set transceiver.{{RTCRtpTransceiver/[[Direction]]}} to {{RTCRtpTransceiverDirection/"sendonly"}}.
For each non-stopped {{RTCRtpTransceiverDirection/"recvonly"}} transceiver of [= transceiver kind =] kind, set transceiver.{{RTCRtpTransceiver/[[Direction]]}} to {{RTCRtpTransceiverDirection/"inactive"}}.
Continue with the next option, if any.
If connection has any non-stopped {{RTCRtpTransceiverDirection/"sendrecv"}} or {{RTCRtpTransceiverDirection/"recvonly"}} transceivers of [= transceiver kind =] kind, continue with the next option, if any.
Let transceiver be the result of invoking the equivalent of connection.{{RTCPeerConnection/addTransceiver}}(kind), except that this operation MUST NOT [= update the negotiation-needed flag =].
If transceiver is unset because the previous operation threw an error, abort these steps.
Set transceiver.{{RTCRtpTransceiver/[[Direction]]}} to {{RTCRtpTransceiverDirection/"recvonly"}}.
Run the steps specified by {{RTCPeerConnection/createOffer}} to create the offer.
partial dictionary RTCOfferOptions { boolean offerToReceiveAudio; boolean offerToReceiveVideo; };
This setting provides additional control over the directionality of audio. For example, it can be used to ensure that audio can be received, regardless if audio is sent or not.
This setting provides additional control over the directionality of video. For example, it can be used to ensure that video can be received, regardless if video is sent or not.
An {{RTCPeerConnection}} object MUST not be garbage collected as
long as any event can cause an event handler to be triggered on the
object. When the object's {{RTCPeerConnection/[[IsClosed]]}} internal slot is
true
, no such event handler can be triggered and it is
therefore safe to garbage collect the object.
All {{RTCDataChannel}} and {{MediaStreamTrack}} objects that are connected to an {{RTCPeerConnection}} have a strong reference to the {{RTCPeerConnection}} object.
All methods that return promises are governed by the standard error handling rules of promises. Methods that do not return promises may throw exceptions to indicate errors.
The {{RTCSdpType}} enum describes the type of an {{RTCSessionDescriptionInit}}, {{RTCLocalSessionDescriptionInit}}, or {{RTCSessionDescription}} instance.
enum RTCSdpType { "offer", "pranswer", "answer", "rollback" };
Enumeration description | |
---|---|
offer |
An {{RTCSdpType}} of {{RTCSdpType/"offer"}} indicates that a description MUST be treated as an [[!SDP]] offer. |
pranswer |
An {{RTCSdpType}} of {{RTCSdpType/"pranswer"}} indicates that a description MUST be treated as an [[!SDP]] answer, but not a final answer. A description used as an SDP pranswer may be applied as a response to an SDP offer, or an update to a previously sent SDP pranswer. |
answer |
An {{RTCSdpType}} of {{RTCSdpType/"answer"}} indicates that a description MUST be treated as an [[!SDP]] final answer, and the offer-answer exchange MUST be considered complete. A description used as an SDP answer may be applied as a response to an SDP offer or as an update to a previously sent SDP pranswer. |
rollback |
An {{RTCSdpType}} of {{RTCSdpType/"rollback"}} indicates
that a description MUST be treated as canceling the
current SDP negotiation and moving the SDP [[!SDP]] offer
back to what it was in the previous stable state. Note
the local or remote SDP descriptions in the previous
stable state could be |
The {{RTCSessionDescription}} class is used by {{RTCPeerConnection}} to expose local and remote session descriptions.
[Exposed=Window] interface RTCSessionDescription { constructor(RTCSessionDescriptionInit descriptionInitDict); readonly attribute RTCSdpType type; readonly attribute DOMString sdp; [Default] object toJSON(); };
The RTCSessionDescription()
constructor takes a dictionary argument,
description, whose content is used to initialize
the new {{RTCSessionDescription}} object. This constructor
is deprecated; it exists for legacy compatibility reasons
only.
""
dictionary RTCSessionDescriptionInit { required RTCSdpType type; DOMString sdp = ""; };
dictionary RTCLocalSessionDescriptionInit { RTCSdpType type; DOMString sdp = ""; };
Many changes to state of an {{RTCPeerConnection}} will require communication with the remote side via the signaling channel, in order to have the desired effect. The app can be kept informed as to when it needs to do signaling, by listening to the {{RTCPeerConnection/negotiationneeded}} event. This event is fired according to the state of the connection's negotiation-needed flag, represented by a {{RTCPeerConnection/[[NegotiationNeeded]]}} internal slot.
If an operation is performed on an {{RTCPeerConnection}} that requires signaling, the connection will be marked as needing negotiation. Examples of such operations include adding or stopping an {{RTCRtpTransceiver}}, or adding the first {{ RTCDataChannel}}.
Internal changes within the implementation can also result in the connection being marked as needing negotiation.
Note that the exact procedures for [= update the negotiation-needed flag | updating the negotiation-needed flag =] are specified below.
The negotiation-needed flag is cleared when a session description of type {{RTCSdpType/"answer"}} [= set a session description | is set =] successfully, and the supplied description matches the state of the {{RTCRtpTransceiver}}s and {{RTCDataChannel}}s that currently exist on the {{RTCPeerConnection}}. Specifically, this means that all non-{{RTCRtpTransceiver/stopped}} transceivers have an [= associated =] section in the local description with matching properties, and, if any data channels have been created, a data section exists in the local description.
Note that the exact procedures for [= update the negotiation-needed flag | updating the negotiation-needed flag =] are specified below.
The process below occurs where referenced elsewhere in this document. It also may occur as a result of internal changes within the implementation that affect negotiation. If such changes occur, the user agent MUST [= update the negotiation-needed flag =].
To update the negotiation-needed flag for connection, run the following steps:
If the length of connection.{{RTCPeerConnection/[[Operations]]}}
is not 0
, then set
connection.{{RTCPeerConnection/[[UpdateNegotiationNeededFlagOnEmptyChain]]}}
to true
, and abort these steps.
Queue a task to run the following steps:
If connection.{{RTCPeerConnection/[[IsClosed]]}} is
true
, abort these steps.
If the length of
connection.{{RTCPeerConnection/[[Operations]]}} is not
0
, then set
connection.{{RTCPeerConnection/[[UpdateNegotiationNeededFlagOnEmptyChain]]}}
to true
, and abort these steps.
If connection's [= signaling state =] is not {{RTCSignalingState/"stable"}}, abort these steps.
The negotiation-needed flag will be updated once the state transitions to {{RTCSignalingState/"stable"}}, as part of the steps for [= setting a session description =].
If the result of [= check if negotiation is needed |
checking if negotiation is needed =] is false
,
clear the negotiation-needed flag by setting
connection.{{RTCPeerConnection/[[NegotiationNeeded]]}} to
false
, and abort these steps.
If connection.{{RTCPeerConnection/[[NegotiationNeeded]]}} is
already true
, abort these steps.
Set connection.{{RTCPeerConnection/[[NegotiationNeeded]]}} to
true
.
[= Fire an event =] named {{RTCPeerConnection/negotiationneeded}} at connection.
The task queueing prevents {{RTCPeerConnection/negotiationneeded}} from firing prematurely, in the common situation where multiple modifications to connection are being made at once.
Additionally, we avoid racing with negotiation methods by only firing {{RTCPeerConnection/negotiationneeded}} when the [= operations chain =] is empty.
To check if negotiation is needed for connection, perform the following checks:
If any implementation-specific negotiation is required, as
described at the start of this section, return
true
.
If
connection.{{RTCPeerConnection/[[LocalIceCredentialsToReplace]]}}
is not empty, return true
.
Let description be connection.{{RTCPeerConnection/[[CurrentLocalDescription]]}}.
If connection has created any {{RTCDataChannel}}s,
and no m= section in description has been negotiated
yet for data, return true
.
For each transceiver in connection's [= set of transceivers =], perform the following checks:
If transceiver.{{RTCRtpTransceiver/[[Stopping]]}} is
true
and
transceiver.{{RTCRtpTransceiver/[[Stopped]]}} is
false
, return true
.
If transceiver isn't {{RTCRtpTransceiver/
stopped}} and isn't yet [= associated =] with an m= section
in description, return true
.
If transceiver isn't {{RTCRtpTransceiver/ stopped}} and is [= associated =] with an m= section in description then perform the following checks:
If transceiver.{{RTCRtpTransceiver/[[Direction]]}} is
{{RTCRtpTransceiverDirection/"sendrecv"}} or
{{RTCRtpTransceiverDirection/"sendonly"}}, and the [=
associated =] m= section in description
either doesn't contain a single a=msid
line, or the number of MSIDs from
the a=msid
lines in this
m=
section, or the MSID values
themselves, differ from what is in
transceiver.sender.{{RTCRtpSender/[[AssociatedMediaStreamIds]]}},
return true
.
If description is of type
{{RTCSdpType/"offer"}}, and the direction of the [=
associated =] m= section in neither
connection.{{RTCPeerConnection/[[CurrentLocalDescription]]}}
nor
connection.{{RTCPeerConnection/[[CurrentRemoteDescription]]}}
matches transceiver.{{RTCRtpTransceiver/[[Direction]]}},
return true
. In this step, when the
direction is compared with a direction found in
{{RTCPeerConnection/[[CurrentRemoteDescription]]}}, the description's
direction must be reversed to represent the peer's
point of view.
If description is of type
{{RTCSdpType/"answer"}}, and the direction of the [=
associated =] m= section in the description
does not match
transceiver.{{RTCRtpTransceiver/[[Direction]]}}
intersected with the offered direction (as described in
[[!RFC8829]]),
return true
.
If transceiver is {{RTCRtpTransceiver/ stopped}}
and is [= associated =] with an m= section, but the
associated m= section is not yet rejected in
connection.{{RTCPeerConnection/[[CurrentLocalDescription]]}}
or
connection.{{RTCPeerConnection/[[CurrentRemoteDescription]]}},
return true
.
If all the preceding checks were performed and
true
was not returned, nothing remains to be
negotiated; return false
.
This interface describes an ICE candidate, described in [[RFC5245]] Section 2. Other than {{RTCIceCandidateInit/candidate}}, {{RTCIceCandidateInit/sdpMid}}, {{RTCIceCandidateInit/sdpMLineIndex}}, and {{RTCIceCandidateInit/usernameFragment}}, the remaining attributes are derived from parsing the {{RTCIceCandidateInit/candidate}} member in candidateInitDict, if it is well formed.
[Exposed=Window] interface RTCIceCandidate { constructor(optional RTCIceCandidateInit candidateInitDict = {}); readonly attribute DOMString candidate; readonly attribute DOMString? sdpMid; readonly attribute unsigned short? sdpMLineIndex; readonly attribute DOMString? foundation; readonly attribute RTCIceComponent? component; readonly attribute unsigned long? priority; readonly attribute DOMString? address; readonly attribute RTCIceProtocol? protocol; readonly attribute unsigned short? port; readonly attribute RTCIceCandidateType? type; readonly attribute RTCIceTcpCandidateType? tcpType; readonly attribute DOMString? relatedAddress; readonly attribute unsigned short? relatedPort; readonly attribute DOMString? usernameFragment; RTCIceCandidateInit toJSON(); };
The RTCIceCandidate()
constructor
takes a dictionary argument, candidateInitDict,
whose content is used to initialize the new
{{RTCIceCandidate}} object.
When invoked, run the following steps:
null
, [=
exception/throw =] a {{TypeError}}.
Return the result of [= creating an RTCIceCandidate =] with candidateInitDict.
To create an RTCIceCandidate with a candidateInitDict dictionary, run the following steps:
null
:
{{foundation}}, {{component}}, {{priority}}, {{address}},
{{protocol}}, {{port}}, {{type}}, {{tcpType}},
{{relatedAddress}}, and {{relatedPort}}.
The constructor for {{RTCIceCandidate}} only does basic parsing and type checking for the dictionary members in candidateInitDict. Detailed validation on the well-formedness of {{RTCIceCandidateInit/candidate}}, {{RTCIceCandidateInit/sdpMid}}, {{RTCIceCandidateInit/sdpMLineIndex}}, {{RTCIceCandidateInit/usernameFragment}} with the corresponding session description is done when passing the {{RTCIceCandidate}} object to {{RTCPeerConnection/addIceCandidate()}}.
To maintain backward compatibility, any error on parsing
the candidate attribute is ignored. In such
case, the {{candidate}} attribute holds the raw
{{RTCIceCandidateInit/candidate}} string given in
candidateInitDict, but derivative attributes
such as {{foundation}}, {{priority}}, etc are set to
null
.
Most attributes below are defined in section 15.1 of [[RFC5245]].
null
, this contains the media stream
"identification-tag" defined in [[!RFC5888]] for the
media component this candidate is associated with.
null
, this indicates the index (starting
at zero) of the [= media description =] in the SDP this
candidate is associated with.
component-id
field in [= candidate-attribute =], decoded to the string
representation as defined in {{RTCIceComponent}}.
The address of the candidate, allowing for IPv4 addresses,
IPv6 addresses, and fully qualified domain names (FQDNs).
This corresponds to the connection-address
field in [=
candidate-attribute =].
Remote candidates may be exposed, for instance via
{{RTCIceTransport/[[SelectedCandidatePair]]}}.{{RTCIceCandidatePair/remote}}.
By default, the user agent MUST leave the
{{RTCIceCandidate/address}} attribute as null
for any exposed remote candidate. Once a
{{RTCPeerConnection}} instance learns on an address by the
web application using
{{RTCPeerConnection/addIceCandidate}}, the user agent can
expose the {{address}} attribute value in any
{{RTCIceCandidate}} of the {{RTCPeerConnection}} instance
representing a remote candidate with that newly learnt
address.
The addresses exposed in candidates gathered via ICE and made visibile to the application in {{RTCIceCandidate}} instances can reveal more information about the device and the user (e.g. location, local network topology) than the user might have expected in a non-WebRTC enabled browser.
These addresses are always exposed to the application, and potentially exposed to the communicating party, and can be exposed without any specific user consent (e.g. for peer connections used with data channels, or to receive media only).
These addresses can also be used as temporary or persistent cross-origin states, and thus contribute to the fingerprinting surface of the device.
Applications can avoid exposing addresses to the communicating party, either temporarily or permanently, by forcing the [= ICE Agent =] to report only relay candidates via the {{RTCConfiguration/iceTransportPolicy}} member of {{RTCConfiguration}}.
To limit the addresses exposed to the application itself, browsers can offer their users different policies regarding sharing local addresses, as defined in [[RFC8828]].
transport
field
in [= candidate-attribute =].
candidate-types
field in [=
candidate-attribute =].
null
. This corresponds to the tcp-type
field in [= candidate-attribute =].
null
. This
corresponds to the rel-address
field
in [= candidate-attribute =].
null
. This corresponds to
the rel-port
field in [=
candidate-attribute =].
ufrag
as defined in
section 15.4 of [[RFC5245]].
json[attr]
to value.
dictionary RTCIceCandidateInit { DOMString candidate = ""; DOMString? sdpMid = null; unsigned short? sdpMLineIndex = null; DOMString? usernameFragment = null; };
""
null
null
, this contains the [= media stream
"identification-tag" =] defined in [[!RFC5888]] for the media
component this candidate is associated with.
null
null
, this indicates the index (starting
at zero) of the [= media description =] in the SDP this
candidate is associated with.
null
null
, this carries the ufrag
as defined in section 15.4 of [[RFC5245]].
candidate-attribute
Grammar
The [= candidate-attribute =] grammar is used to parse the {{RTCIceCandidateInit/candidate}} member of candidateInitDict in the {{RTCIceCandidate()}} constructor.
The primary grammar for [= candidate-attribute =] is defined in section 15.1 of [[RFC5245]]. In addition, the browser MUST support the grammar extension for ICE TCP as defined in section 4.5 of [[!RFC6544]].
The browser MAY support other grammar extensions for [= candidate-attribute =] as defined in other RFCs.
The {{RTCIceProtocol}} represents the protocol of the ICE candidate.
enum RTCIceProtocol { "udp", "tcp" };
Enumeration description | |
---|---|
udp | A UDP candidate, as described in [[RFC5245]]. |
tcp | A TCP candidate, as described in [[!RFC6544]]. |
The {{RTCIceTcpCandidateType}} represents the type of the ICE TCP candidate, as defined in [[!RFC6544]].
enum RTCIceTcpCandidateType { "active", "passive", "so" };
Enumeration description | |
---|---|
active | An {{RTCIceTcpCandidateType/"active"}} TCP candidate is one for which the transport will attempt to open an outbound connection but will not receive incoming connection requests. |
passive | A {{RTCIceTcpCandidateType/"passive"}} TCP candidate is one for which the transport will receive incoming connection attempts but not attempt a connection. |
so | An {{RTCIceTcpCandidateType/"so"}} candidate is one for which the transport will attempt to open a connection simultaneously with its peer. |
The user agent will typically only gather {{RTCIceTcpCandidateType/active}} ICE TCP candidates.
The {{RTCIceCandidateType}} represents the type of the ICE candidate, as defined in [[RFC5245]] section 15.1.
enum RTCIceCandidateType { "host", "srflx", "prflx", "relay" };
Enumeration description | |
---|---|
host | A host candidate, as defined in Section 4.1.1.1 of [[RFC5245]]. |
srflx | A server reflexive candidate, as defined in Section 4.1.1.2 of [[RFC5245]]. |
prflx | A peer reflexive candidate, as defined in Section 4.1.1.2 of [[RFC5245]]. |
relay | A relay candidate, as defined in Section 7.1.3.2.1 of [[RFC5245]]. |
The {{RTCPeerConnection/icecandidate}} event of the {{RTCPeerConnection}} uses the {{RTCPeerConnectionIceEvent}} interface.
When firing an {{RTCPeerConnectionIceEvent}} event that contains an {{RTCIceCandidate}} object, it MUST include values for both {{RTCIceCandidate/sdpMid}} and {{RTCIceCandidate/sdpMLineIndex}}. If the {{RTCIceCandidate}} is of type {{RTCIceCandidateType/"srflx"}} or type {{RTCIceCandidateType/"relay"}}, the {{RTCPeerConnectionIceEvent/url}} property of the event MUST be set to the URL of the ICE server from which the candidate was obtained.
A candidate has been gathered. The {{RTCPeerConnectionIceEvent/candidate}} member of the event will be populated normally. It should be signaled to the remote peer and passed into {{RTCPeerConnection/addIceCandidate}}.
An {{RTCIceTransport}} has finished gathering a [= generation =] of candidates, and is providing an end-of-candidates indication as defined by Section 8.2 of [[RFC8838]]. This is indicated by {{RTCPeerConnectionIceEvent/candidate}}.{{RTCIceCandidate/candidate}} being set to an empty string. The {{RTCPeerConnectionIceEvent/candidate}} object should be signaled to the remote peer and passed into {{RTCPeerConnection/addIceCandidate}} like a typical ICE candidate, in order to provide the end-of-candidates indication to the remote peer.
All {{RTCIceTransport}}s have finished gathering candidates,
and the {{RTCPeerConnection}}'s {{RTCIceGatheringState}} has
transitioned to {{RTCIceGatheringState/"complete"}}. This is
indicated by the {{RTCPeerConnectionIceEvent/candidate}}
member of the event being set to null
. This only
exists for backwards compatibility, and this event does not
need to be signaled to the remote peer. It's equivalent to an
{{RTCPeerConnection/icegatheringstatechange}} event with the
{{RTCIceGatheringState/"complete"}} state.
[Exposed=Window] interface RTCPeerConnectionIceEvent : Event { constructor(DOMString type, optional RTCPeerConnectionIceEventInit eventInitDict = {}); readonly attribute RTCIceCandidate? candidate; readonly attribute DOMString? url; };
The {{candidate}} attribute is the {{RTCIceCandidate}} object with the new ICE candidate that caused the event.
This attribute is set to null
when an event is
generated to indicate the end of candidate gathering.
Even where there are multiple media components, only one
event containing a null
candidate is fired.
The {{url}} attribute is the STUN or TURN URL that
identifies the STUN or TURN server used to gather this
candidate. If the candidate was not gathered from a STUN or
TURN server, this parameter will be set to
null
.
dictionary RTCPeerConnectionIceEventInit : EventInit { RTCIceCandidate? candidate; DOMString? url; };
See the {{RTCPeerConnectionIceEvent/candidate}} attribute of the {{RTCPeerConnectionIceEvent}} interface.
The {{RTCPeerConnection/icecandidateerror}} event of the {{RTCPeerConnection}} uses the {{RTCPeerConnectionIceErrorEvent}} interface.
[Exposed=Window] interface RTCPeerConnectionIceErrorEvent : Event { constructor(DOMString type, RTCPeerConnectionIceErrorEventInit eventInitDict); readonly attribute DOMString? address; readonly attribute unsigned short? port; readonly attribute DOMString url; readonly attribute unsigned short errorCode; readonly attribute USVString errorText; };
The {{address}} attribute is the local IP address used to communicate with the STUN or TURN server.
On a multihomed system, multiple interfaces may be used to contact the server, and this attribute allows the application to figure out on which one the failure occurred.
If the local IP address value is not already exposed as
part of a local candidate, the {{address}} attribute will
be set to null
.
The {{port}} attribute is the port used to communicate with the STUN or TURN server.
If the {{address}} attribute is null
, the
{{port}} attribute is also set to null
.
The {{url}} attribute is the STUN or TURN URL that identifies the STUN or TURN server for which the failure occurred.
The {{errorCode}} attribute is the numeric STUN error code returned by the STUN or TURN server [[STUN-PARAMETERS]].
If no host candidate can reach the server, {{errorCode}} will be set to the value 701 which is outside the STUN error code range. This error is only fired once per server URL while in the {{RTCIceGatheringState}} of {{RTCIceGatheringState/"gathering"}}.
The {{errorText}} attribute is the STUN reason text returned by the STUN or TURN server [[STUN-PARAMETERS]].
If the server could not be reached, {{errorText}} will be set to an implementation-specific value providing details about the error.
dictionary RTCPeerConnectionIceErrorEventInit : EventInit { DOMString? address; unsigned short? port; DOMString url; required unsigned short errorCode; USVString errorText; };
The local address used to communicate with the STUN or TURN
server, or null
.
The local port used to communicate with the STUN or TURN
server, or null
.
The STUN or TURN URL that identifies the STUN or TURN server for which the failure occurred.
The numeric STUN error code returned by the STUN or TURN server.
The STUN reason text returned by the STUN or TURN server.
The certificates that {{RTCPeerConnection}} instances use to authenticate with peers use the {{RTCCertificate}} interface. These objects can be explicitly generated by applications using the {{RTCPeerConnection/generateCertificate}} method and can be provided in the {{RTCConfiguration}} when constructing a new {{RTCPeerConnection}} instance.
The explicit certificate management functions provided here are optional. If an application does not provide the {{RTCConfiguration/certificates}} configuration option when constructing an {{RTCPeerConnection}} a new set of certificates MUST be generated by the user agent. That set MUST include an ECDSA certificate with a private key on the P-256 curve and a signature with a SHA-256 hash.
partial interface RTCPeerConnection { static Promise<RTCCertificate> generateCertificate(AlgorithmIdentifier keygenAlgorithm); };
The {{generateCertificate}} function causes the user agent to create an X.509 certificate [[!X509V3]] and corresponding private key. A handle to information is provided in the form of the {{RTCCertificate}} interface. The returned {{RTCCertificate}} can be used to control the certificate that is offered in the DTLS sessions established by {{RTCPeerConnection}}.
The keygenAlgorithm argument is used to control how the private key associated with the certificate is generated. The keygenAlgorithm argument uses the WebCrypto [[!WebCryptoAPI]] AlgorithmIdentifier type.
The following values MUST be supported by a user
agent: { name: "RSASSA-PKCS1-v1_5",
modulusLength: 2048, publicExponent: new Uint8Array([1, 0,
1]), hash: "SHA-256" }
, and { name:
"ECDSA", namedCurve:
"P-256"
}
.
It is expected that a user agent will have a small or even fixed set of values that it will accept.
The certificate produced by this process also contains a signature. The validity of this signature is only relevant for compatibility reasons. Only the public key and the resulting certificate fingerprint are used by {{RTCPeerConnection}}, but it is more likely that a certificate will be accepted if the certificate is well formed. The browser selects the algorithm used to sign the certificate; a browser SHOULD select SHA-256 [[!FIPS-180-4]] if a hash algorithm is needed.
The resulting certificate MUST NOT include information that can be linked to a user or user agent. Randomized values for distinguished name and serial number SHOULD be used.
When the method is called, the user agent MUST run the following steps:
Let keygenAlgorithm be the first argument to {{generateCertificate}}.
Let expires be a {{DOMTimeStamp}} value of 2592000000.
This means the certificate will by default expire in 30 days from the time of the {{generateCertificate}} call.
If keygenAlgorithm is an object, run the following steps:
Let certificateExpiration be the result of converting the ECMAScript object represented by keygenAlgorithm to an {{RTCCertificateExpiration}} dictionary.
If the conversion fails with an error, return a promise that is [= rejected =] with error.
If
certificateExpiration.{{RTCCertificateExpiration/expires}}
is not undefined
, set expires
to
certificateExpiration.{{RTCCertificateExpiration/expires}}.
If expires is greater than 31536000000, set expires to 31536000000.
This means the certificate cannot be valid for longer than 365 days from the time of the {{generateCertificate}} call.
A user agent MAY further cap the value of expires.
Let normalizedKeygenAlgorithm be the result of
normalizing an
algorithm with an operation name of generateKey
and a supportedAlgorithms
value specific to production of certificates for
{{RTCPeerConnection}}.
If the above normalization step fails with an error, return a promise that is [= rejected =] with error.
If the normalizedKeygenAlgorithm parameter identifies an algorithm that the user agent cannot or will not use to generate a certificate for {{RTCPeerConnection}}, return a promise that is [= rejected =] with a {{DOMException}} of type {{NotSupportedError}}. In particular, normalizedKeygenAlgorithm MUST be an asymmetric algorithm that can be used to produce a signature used to authenticate DTLS connections.
Let p be a new promise.
Run the following steps in parallel:
Perform the generate key operation specified by normalizedKeygenAlgorithm using keygenAlgorithm.
Let generatedKeyingMaterial and generatedKeyCertificate be the private keying material and certificate generated by the above step.
Let certificate be a new {{RTCCertificate}} object.
Set certificate.[[\Expires]] to the current time plus expires value.
Set certificate.{{RTCCertificate/[[Origin]]}} to the [= relevant settings object =]'s [=environment settings object/origin=].
Store the generatedKeyingMaterial in a secure module, and let handle be a reference identifier to it.
Set certificate.{{RTCCertificate/[[KeyingMaterialHandle]]}} to handle.
Set certificate.{{RTCCertificate/[[Certificate]]}} to generatedCertificate.
Resolve p with certificate.
Return p.
{{RTCCertificateExpiration}} is used to set an expiration date on certificates generated by {{RTCPeerConnection/generateCertificate}}.
dictionary RTCCertificateExpiration { [EnforceRange] DOMTimeStamp expires; };
An optional {{expires}} attribute MAY be added to the definition of the algorithm that is passed to {{RTCPeerConnection/generateCertificate}}. If this parameter is present it indicates the maximum time that the {{RTCCertificate}} is valid for relative to the current time.
The {{RTCCertificate}} interface represents a certificate used to authenticate WebRTC communications. In addition to the visible properties, internal slots contain a handle to the generated private keying materal ([[\KeyingMaterialHandle]]), a certificate ([[\Certificate]]) that {{RTCPeerConnection}} uses to authenticate with a peer, and the origin ([[\Origin]]) that created the object.
[Exposed=Window, Serializable] interface RTCCertificate { readonly attribute DOMTimeStamp expires; sequence<RTCDtlsFingerprint> getFingerprints(); };
The expires attribute indicates the date and time in milliseconds relative to 1970-01-01T00:00:00Z after which the certificate will be considered invalid by the browser. After this time, attempts to construct an {{RTCPeerConnection}} using this certificate fail.
Note that this value might not be reflected in a
notAfter
parameter in the
certificate itself.
Returns the list of certificate fingerprints, one of which is computed with the digest algorithm used in the certificate signature.
For the purposes of this API, the {{RTCCertificate/[[Certificate]]}} slot contains unstructured binary data. No mechanism is provided for applications to access the {{RTCCertificate/[[KeyingMaterialHandle]]}} internal slot or the keying material it references. Implementations MUST support applications storing and retrieving {{RTCCertificate}} objects from persistent storage, in a manner that also preserves the keying material referenced by {{RTCCertificate/[[KeyingMaterialHandle]]}}. Implementations SHOULD store the sensitive keying material in a secure module safe from same-process memory attacks. This allows the private key to be stored and used, but not easily read using a memory attack.
{{RTCCertificate}} objects are [= serializable objects =] [[!HTML]]. Their [= serialization steps =], given value and serialized, are:
Their deserialization steps, given serialized and value, are:
Supporting structured cloning in this manner allows {{RTCCertificate}} instances to be persisted to stores. It also allows instances to be passed to other origins using APIs like {{MessagePort/postMessage(message, options)}} [[html]]. However, the object cannot be used by any other origin than the one that originally created it.
The RTP media API lets a web application send and receive {{MediaStreamTrack}}s over a peer-to-peer connection. Tracks, when added to an {{RTCPeerConnection}}, result in signaling; when this signaling is forwarded to a remote peer, it causes corresponding tracks to be created on the remote side.
There is not an exact 1:1 correspondence between tracks sent by one {{RTCPeerConnection}} and received by the other. For one, IDs of tracks sent have no mapping to the IDs of tracks received. Also, {{RTCRtpSender/replaceTrack}} changes the track sent by an {{RTCRtpSender}} without creating a new track on the receiver side; the corresponding {{RTCRtpReceiver}} will only have a single track, potentially representing multiple sources of media stitched together. Both {{RTCPeerConnection/addTransceiver}} and {{RTCRtpSender/replaceTrack}} can be used to cause the same track to be sent multiple times, which will be observed on the receiver side as multiple receivers each with its own separate track. Thus it's more accurate to think of a 1:1 relationship between an {{RTCRtpSender}} on one side and an {{RTCRtpReceiver}}'s track on the other side, matching senders and receivers using the {{RTCRtpTransceiver}}'s {{RTCRtpTransceiver/mid}} if necessary.
When sending media, the sender may need to rescale or resample the media to meet various requirements including the envelope negotiated by SDP.
Following the rules in [[!RFC8829]], the video MAY be downscaled in order to fit the SDP constraints. The media MUST NOT be upscaled to create fake data that did not occur in the input source, the media MUST NOT be cropped except as needed to satisfy constraints on pixel counts, and the aspect ratio MUST NOT be changed.
The WebRTC Working Group is seeking implementation feedback on the need and timeline for a more complex handling of this situation. Some possible designs have been discussed in GitHub issue 1283.
When video is rescaled, for example for certain combinations of width or height and {{RTCRtpEncodingParameters/ scaleResolutionDownBy}} values, situations when the resulting width or height is not an integer may occur. In such situations the user agent MUST use the integer part of the result. What to transmit if the integer part of the scaled width or height is zero is implementation-specific.
The actual encoding and transmission of {{MediaStreamTrack}}s is managed through objects called {{RTCRtpSender}}s. Similarly, the reception and decoding of {{MediaStreamTrack}}s is managed through objects called {{RTCRtpReceiver}}s. Each {{RTCRtpSender}} is associated with at most one track, and each track to be received is associated with exactly one {{RTCRtpReceiver}}.
The encoding and transmission of each {{MediaStreamTrack}} SHOULD be
made such that its characteristics (width
,
height
and frameRate
for video tracks; sampleSize
, sampleRate
and
channelCount
for audio tracks) are to a
reasonable degree retained by the track created on the remote side.
There are situations when this does not apply, there may for example be
resource constraints at either endpoint or in the network or there may
be {{RTCRtpSender}} settings applied that instruct the implementation
to act differently.
An {{RTCPeerConnection}} object contains a set of {{RTCRtpTransceiver}}s, representing the paired senders and receivers with some shared state. This set is initialized to the empty set when the {{RTCPeerConnection}} object is created. {{RTCRtpSender}}s and {{RTCRtpReceiver}}s are always created at the same time as an {{RTCRtpTransceiver}}, which they will remain attached to for their lifetime. {{RTCRtpTransceiver}}s are created implicitly when the application attaches a {{MediaStreamTrack}} to an {{RTCPeerConnection}} via the {{RTCPeerConnection/addTrack()}} method, or explicitly when the application uses the {{RTCPeerConnection/addTransceiver}} method. They are also created when a remote description is applied that includes a new media description. Additionally, when a remote description is applied that indicates the remote endpoint has media to send, the relevant {{MediaStreamTrack}} and {{RTCRtpReceiver}} are surfaced to the application via the {{RTCPeerConnection/track}} event.
In order for an {{RTCRtpTransceiver}} to send and/or receive media with another endpoint this must be negotiated with SDP such that both endpoints have an {{RTCRtpTransceiver}} object that is [= associated =] with the same [= media description =].
When creating an offer, enough media descriptions will be generated to cover all transceivers on that end. When this offer is set as the local description, any disassociated transceivers get associated with media descriptions in the offer.
When an offer is set as the remote description, any media descriptions in it not yet associated with a transceiver get associated with a new or existing transceiver. In this case, only disassociated transceivers that were created via the {{RTCPeerConnection/addTrack()}} method may be associated. Disassociated transceivers created via the {{RTCPeerConnection/addTransceiver()}} method, however, won't get associated even if media descriptions are available in the remote offer. Instead, new transceivers will be created and associated if there aren't enough {{RTCPeerConnection/addTrack()}}-created transceivers. This sets {{RTCPeerConnection/addTrack()}}-created and {{RTCPeerConnection/addTransceiver()}}-created transceivers apart in a critical way that is not observable from inspecting their attributes.
When creating an answer, only media descriptions that were present in the offer may be listed in the answer. As a consequence, any transceivers that were not associated when setting the remote offer remain disassociated after setting the local answer. This can be remedied by the answerer creating a follow-up offer, initiating another offer/answer exchange, or in the case of using {{RTCPeerConnection/addTrack()}}-created transceivers, making sure that enough media descriptions are offered in the initial exchange.
The RTP media API extends the {{RTCPeerConnection}} interface as described below.
partial interface RTCPeerConnection { sequence<RTCRtpSender> getSenders(); sequence<RTCRtpReceiver> getReceivers(); sequence<RTCRtpTransceiver> getTransceivers(); RTCRtpSender addTrack(MediaStreamTrack track, MediaStream... streams); undefined removeTrack(RTCRtpSender sender); RTCRtpTransceiver addTransceiver((MediaStreamTrack or DOMString) trackOrKind, optional RTCRtpTransceiverInit init = {}); attribute EventHandler ontrack; };
The event type of this event handler is {{RTCPeerConnection/track}}.
Returns a sequence of {{RTCRtpSender}} objects representing the RTP senders that belong to non-stopped {{RTCRtpTransceiver}} objects currently attached to this {{RTCPeerConnection}} object.
When the {{getSenders}} method is invoked, the user agent MUST return the result of executing the {{CollectSenders}} algorithm.
We define the CollectSenders algorithm as follows:
false
, add
transceiver.{{RTCRtpTransceiver/[[Sender]]}} to
senders.
Returns a sequence of {{RTCRtpReceiver}} objects representing the RTP receivers that belong to non-stopped {{RTCRtpTransceiver}} objects currently attached to this {{RTCPeerConnection}} object.
When the {{getReceivers}} method is invoked, the user agent MUST run the following steps:
false
, add
transceiver.{{RTCRtpTransceiver/[[Receiver]]}} to
receivers.
Returns a sequence of {{RTCRtpTransceiver}} objects representing the RTP transceivers that are currently attached to this {{RTCPeerConnection}} object.
The {{getTransceivers}} method MUST return the result of executing the {{CollectTransceivers}} algorithm.
We define the CollectTransceivers algorithm as follows:
Adds a new track to the {{RTCPeerConnection}}, and indicates that it is contained in the specified {{MediaStream}}s.
When the {{addTrack}} method is invoked, the user agent MUST run the following steps:
Let connection be the {{RTCPeerConnection}} object on which this method was invoked.
Let track be the {{MediaStreamTrack}} object indicated by the method's first argument.
Let kind be track.kind.
Let streams be a list of {{MediaStream}} objects constructed from the method's remaining arguments, or an empty list if the method was called with a single argument.
If connection.{{RTCPeerConnection/[[IsClosed]]}} is
true
, [= exception/throw =] an
{{InvalidStateError}}.
Let senders be the result of executing the {{CollectSenders}} algorithm. If an {{RTCRtpSender}} for track already exists in senders, [= exception/throw =] an {{InvalidAccessError}}.
The steps below describe how to determine if an existing
sender can be reused. Doing so will cause future calls to
{{RTCPeerConnection/createOffer}} and
{{RTCPeerConnection/createAnswer}} to mark the
corresponding [= media description =] as sendrecv
or sendonly
and add the MSID of the sender's
streams, as defined in [[!RFC8829]].
If any {{RTCRtpSender}} object in senders
matches all the following criteria, let sender
be that object, or null
otherwise:
The sender's track is null.
The transceiver kind of the {{RTCRtpTransceiver}}, associated with the sender, matches kind.
The {{RTCRtpTransceiver/[[Stopping]]}} slot of the
{{RTCRtpTransceiver}} associated with the sender is
false
.
The sender has never been used to send. More precisely, the {{RTCRtpTransceiver/[[CurrentDirection]]}} slot of the {{RTCRtpTransceiver}} associated with the sender has never had a value of {{RTCRtpTransceiverDirection/"sendrecv"}} or {{RTCRtpTransceiverDirection/"sendonly"}}.
If sender is not null
, run the
following steps to use that sender:
Set sender.{{RTCRtpSender/[[SenderTrack]]}} to track.
Set sender.{{RTCRtpSender/[[AssociatedMediaStreamIds]]}} to an empty set.
For each stream in streams, add stream.id to {{RTCRtpSender/[[AssociatedMediaStreamIds]]}} if it's not already there.
Let transceiver be the {{RTCRtpTransceiver}} associated with sender.
If transceiver.{{RTCRtpTransceiver/[[Direction]]}} is {{RTCRtpTransceiverDirection/"recvonly"}}, set transceiver.{{RTCRtpTransceiver/[[Direction]]}} to {{RTCRtpTransceiverDirection/"sendrecv"}}.
If transceiver.{{RTCRtpTransceiver/[[Direction]]}} is {{RTCRtpTransceiverDirection/"inactive"}}, set transceiver.{{RTCRtpTransceiver/[[Direction]]}} to {{RTCRtpTransceiverDirection/"sendonly"}}.
If sender is null
, run the
following steps:
Create an RTCRtpSender with track, kind and streams, and let sender be the result.
Create an RTCRtpReceiver with kind, and let receiver be the result.
Create an RTCRtpTransceiver with sender, receiver and an {{RTCRtpTransceiverDirection}} value of {{RTCRtpTransceiverDirection/"sendrecv"}}, and let transceiver be the result.
Add transceiver to connection's [= set of transceivers =].
A track could have contents that are inaccessible to the application. This can be due to anything that would make a track CORS cross-origin. These tracks can be supplied to the {{RTCPeerConnection/addTrack()}} method, and have an {{RTCRtpSender}} created for them, but content MUST NOT be transmitted. Silence (audio), black frames (video) or equivalently absent content is sent in place of track content.
Note that this property can change over time.
[= Update the negotiation-needed flag =] for connection.
Return sender.
Stops sending media from sender. The {{RTCRtpSender}} will still appear in {{getSenders}}. Doing so will cause future calls to {{createOffer}} to mark the [= media description =] for the corresponding transceiver as {{RTCRtpTransceiverDirection/"recvonly"}} or {{RTCRtpTransceiverDirection/"inactive"}}, as defined in [[!RFC8829]].
When the other peer stops sending a track in this manner, the
track is removed from any remote {{MediaStream}}s that were
initially revealed in the {{RTCPeerConnection/track}}
event, and if the {{MediaStreamTrack}} is not already muted,
a mute
event is fired at the
track.
When the {{removeTrack}} method is invoked, the user agent MUST run the following steps:
Let sender be the argument to {{removeTrack}}.
Let connection be the {{RTCPeerConnection}} object on which the method was invoked.
If connection.{{RTCPeerConnection/[[IsClosed]]}} is
true
, [= exception/throw =] an
{{InvalidStateError}}.
If sender was not created by connection, [= exception/throw =] an {{InvalidAccessError}}.
Let senders be the result of executing the {{CollectSenders}} algorithm.
If sender is not in senders (which indicates its transceiver was stopped or removed due to [= setting a session description =] of {{RTCSessionDescriptionInit/type}} {{RTCSdpType/"rollback"}}), then abort these steps.
If sender.{{RTCRtpSender/[[SenderTrack]]}} is null, abort these steps.
Set sender.{{RTCRtpSender/[[SenderTrack]]}} to null.
Let transceiver be the {{RTCRtpTransceiver}} object corresponding to sender.
If transceiver.{{RTCRtpTransceiver/[[Direction]]}} is {{RTCRtpTransceiverDirection/"sendrecv"}}, set transceiver.{{RTCRtpTransceiver/[[Direction]]}} to {{RTCRtpTransceiverDirection/"recvonly"}}.
If transceiver.{{RTCRtpTransceiver/[[Direction]]}} is {{RTCRtpTransceiverDirection/"sendonly"}}, set transceiver.{{RTCRtpTransceiver/[[Direction]]}} to {{RTCRtpTransceiverDirection/"inactive"}}.
[= Update the negotiation-needed flag =] for connection.
Create a new {{RTCRtpTransceiver}} and add it to the [= set of transceivers =].
Adding a transceiver will cause future calls to {{createOffer}} to add a [= media description =] for the corresponding transceiver, as defined in [[!RFC8829]].
The initial value of {{RTCRtpTransceiver/mid}} is null. [= Setting a session description =] may later change it to a non-null value.
The {{RTCRtpTransceiverInit/sendEncodings}} argument can be used to specify the number of offered simulcast encodings, and optionally their RIDs and encoding parameters.
When this method is invoked, the user agent MUST run the following steps:
Let init be the second argument.
Let streams be init.{{RTCRtpTransceiverInit/streams}}.
Let sendEncodings be init.{{RTCRtpTransceiverInit/sendEncodings}}.
Let direction be init.{{RTCRtpTransceiverInit/direction}}.
If the first argument is a string, let it be kind and run the following steps:
If kind is not a legal
{{MediaStreamTrack}} kind
,
[= exception/throw =] a {{TypeError}}.
Let track be null
.
If the first argument is a {{MediaStreamTrack}}, let it be track and let kind be track.kind.
If connection.{{RTCPeerConnection/[[IsClosed]]}} is
true
, [= exception/throw =] an
{{InvalidStateError}}.
Verify that each {{RTCRtpCodingParameters/rid}} value in sendEncodings conforms to the grammar specified in Section 10 of [[RFC8851]]. If one of the RIDs does not meet these requirements, [= exception/throw =] a {{TypeError}}.
If any {{RTCRtpEncodingParameters}} dictionary in sendEncodings contains a read-only parameter other than {{RTCRtpCodingParameters/rid}}, [= exception/throw =] an {{InvalidAccessError}}.
Verify that the value of each {{RTCRtpEncodingParameters/scaleResolutionDownBy}} member in sendEncodings that is defined is greater than or equal to 1.0. If one of the {{RTCRtpEncodingParameters/scaleResolutionDownBy}} values does not meet this requirement, [= exception/throw =] a {{RangeError}}.
Let maxN be the maximum number of total
simultaneous encodings the user agent may support for
this kind, at minimum 1
.This
should be an optimistic number since the codec to be
used is not known yet.
If sendEncodings contains any encoding whose {{RTCRtpEncodingParameters/scaleResolutionDownBy}} attribute is defined, set any undefined {{RTCRtpEncodingParameters/scaleResolutionDownBy}} of the other encodings to 1.0.
If the number of {{RTCRtpEncodingParameters}} stored in sendEncodings exceeds maxN, then trim sendEncodings from the tail until its length is maxN.
2^(length of sendEncodings - encoding
index - 1)
. This results in smaller-to-larger
resolutions where the last encoding has no scaling
applied to it, e.g. 4:2:1 if the length is 3.
If the number of {{RTCRtpEncodingParameters}} now
stored in sendEncodings is 1
,
then remove any {{RTCRtpCodingParameters/rid}} member
from the lone entry.
Create an RTCRtpSender with track, kind, streams and sendEncodings and let sender be the result.
If sendEncodings is set, then subsequent calls to {{createOffer}} will be configured to send multiple RTP encodings as defined in [[!RFC8829]]. When {{RTCPeerConnection/setRemoteDescription}} is called with a corresponding remote description that is able to receive multiple RTP encodings as defined in [[!RFC8829]], the {{RTCRtpSender}} may send multiple RTP encodings and the parameters retrieved via the transceiver's {{RTCRtpTransceiver/sender}}.{{RTCRtpSender/getParameters()}} will reflect the encodings negotiated.
Create an RTCRtpReceiver with kind and let receiver be the result.
Create an RTCRtpTransceiver with sender, receiver and direction, and let transceiver be the result.
Add transceiver to connection's [= set of transceivers =].
[= Update the negotiation-needed flag =] for connection.
Return transceiver.
dictionary RTCRtpTransceiverInit { RTCRtpTransceiverDirection direction = "sendrecv"; sequence<MediaStream> streams = []; sequence<RTCRtpEncodingParameters> sendEncodings = []; };
When the remote PeerConnection's track event fires corresponding to the {{RTCRtpReceiver}} being added, these are the streams that will be put in the event.
A sequence containing parameters for sending RTP encodings of media.
enum RTCRtpTransceiverDirection { "sendrecv", "sendonly", "recvonly", "inactive", "stopped" };
RTCRtpTransceiverDirection Enumeration description | |
---|---|
sendrecv |
The {{RTCRtpTransceiver}}'s {{RTCRtpSender}}
sender will offer to send RTP, and will send RTP
if the remote peer accepts and
sender.{{RTCRtpSender/getParameters()}}.{{RTCRtpSendParameters/encodings}}[i].{{RTCRtpEncodingParameters/active}}
is true for any value of i. The
{{RTCRtpTransceiver}}'s {{RTCRtpReceiver}} will offer to
receive RTP, and will receive RTP if the remote peer accepts.
|
sendonly |
The {{RTCRtpTransceiver}}'s {{RTCRtpSender}}
sender will offer to send RTP, and will send RTP
if the remote peer accepts and
sender.{{RTCRtpSender/getParameters()}}.{{RTCRtpSendParameters/encodings}}[i].{{RTCRtpEncodingParameters/active}}
is true for any value of i. The
{{RTCRtpTransceiver}}'s {{RTCRtpReceiver}} will not offer to
receive RTP, and will not receive RTP.
|
recvonly | The {{RTCRtpTransceiver}}'s {{RTCRtpSender}} will not offer to send RTP, and will not send RTP. The {{RTCRtpTransceiver}}'s {{RTCRtpReceiver}} will offer to receive RTP, and will receive RTP if the remote peer accepts. |
inactive | The {{RTCRtpTransceiver}}'s {{RTCRtpSender}} will not offer to send RTP, and will not send RTP. The {{RTCRtpTransceiver}}'s {{RTCRtpReceiver}} will not offer to receive RTP, and will not receive RTP. |
stopped | The {{RTCRtpTransceiver}} will neither send nor receive RTP. It will generate a zero port in the offer. In answers, its {{RTCRtpSender}} will not offer to send RTP, and its {{RTCRtpReceiver}} will not offer to receive RTP. This is a terminal state. |
An application can reject incoming media descriptions by setting the transceiver's direction to either {{RTCRtpTransceiverDirection/"inactive"}} to turn off both directions temporarily, or to {{RTCRtpTransceiverDirection/"sendonly"}} to reject only the incoming side. To permanently reject an m-line in a manner that makes it available for reuse, the application would need to call {{RTCRtpTransceiver}}.{{RTCRtpTransceiver/stop()}} and subsequently initiate negotiation from its end.
To process remote tracks given an {{RTCRtpTransceiver}} transceiver, direction, msids, addList, removeList, and trackEventInits, run the following steps:
Set the associated remote streams with transceiver.{{RTCRtpTransceiver/[[Receiver]]}}, msids, addList, and removeList.
If direction is {{RTCRtpTransceiverDirection/"sendrecv"}} or {{RTCRtpTransceiverDirection/"recvonly"}} and transceiver.{{RTCRtpTransceiver/[[FiredDirection]]}} is neither {{RTCRtpTransceiverDirection/"sendrecv"}} nor {{RTCRtpTransceiverDirection/"recvonly"}}, or the previous step increased the length of addList, process the addition of a remote track with transceiver and trackEventInits.
If direction is
{{RTCRtpTransceiverDirection/"sendonly"}} or
{{RTCRtpTransceiverDirection/"inactive"}}, set
transceiver.{{RTCRtpTransceiver/[[Receptive]]}} to
false
.
If direction is {{RTCRtpTransceiverDirection/"sendonly"}} or {{RTCRtpTransceiverDirection/"inactive"}}, and transceiver.{{RTCRtpTransceiver/[[FiredDirection]]}} is either {{RTCRtpTransceiverDirection/"sendrecv"}} or {{RTCRtpTransceiverDirection/"recvonly"}}, process the removal of a remote track for the media description, with transceiver and muteTracks.
Set transceiver.{{RTCRtpTransceiver/[[FiredDirection]]}} to direction.
To process the addition of a remote track given an {{RTCRtpTransceiver}} transceiver and trackEventInits, run the following steps:
Let receiver be transceiver.{{RTCRtpTransceiver/[[Receiver]]}}.
Let track be receiver.{{RTCRtpReceiver/[[ReceiverTrack]]}}.
Let streams be receiver.{{RTCRtpReceiver/[[AssociatedRemoteMediaStreams]]}}.
Create a new {{RTCTrackEventInit}} dictionary with receiver, track, streams and transceiver as members and add it to trackEventInits.
To process the removal of a remote track with an {{RTCRtpTransceiver}} transceiver and muteTracks, run the following steps:
Let receiver be transceiver.{{RTCRtpTransceiver/[[Receiver]]}}.
Let track be receiver.{{RTCRtpReceiver/[[ReceiverTrack]]}}.
If track.muted is false
, add
track to muteTracks.
To set the associated remote streams given {{RTCRtpReceiver}} receiver, msids, addList, and removeList, run the following steps:
Let connection be the {{RTCPeerConnection}} object associated with receiver.
For each MSID in msids, unless a {{MediaStream}}
object has previously been created with that id
for this connection, create a
{{MediaStream}} object with that id
.
Let streams be a list of the {{MediaStream}} objects
created for this connection with the id
s corresponding to msids.
Let track be receiver.{{RTCRtpReceiver/[[ReceiverTrack]]}}.
For each stream in receiver.{{RTCRtpReceiver/[[AssociatedRemoteMediaStreams]]}} that is not present in streams, add stream and track as a pair to removeList.
For each stream in streams that is not present in receiver.{{RTCRtpReceiver/[[AssociatedRemoteMediaStreams]]}}, add stream and track as a pair to addList.
Set receiver.{{RTCRtpReceiver/[[AssociatedRemoteMediaStreams]]}} to streams.
The {{RTCRtpSender}} interface allows an application to control how a given {{MediaStreamTrack}} is encoded and transmitted to a remote peer. When {{RTCRtpSender/setParameters}} is called on an {{RTCRtpSender}} object, the encoding is changed appropriately.
To create an RTCRtpSender with a {{MediaStreamTrack}}, track, a string, kind, a list of {{MediaStream}} objects, streams, and optionally a list of {{RTCRtpEncodingParameters}} objects, sendEncodings, run the following steps:
Let sender be a new {{RTCRtpSender}} object.
Let sender have a [[\SenderTrack]] internal slot initialized to track.
Let sender have a [[\SenderTransport]]
internal slot initialized to null
.
Let sender have a
[[\LastStableStateSenderTransport]] internal slot
initialized to null
.
Let sender have a [[\Dtmf]] internal slot
initialized to null
.
If kind is "audio"
then create an
RTCDTMFSender dtmf and set the {{RTCRtpSender/[[Dtmf]]}}
internal slot to dtmf.
Let sender have an [[\AssociatedMediaStreamIds]] internal slot, representing a list of Ids of {{MediaStream}} objects that this sender is to be associated with. The {{RTCRtpSender/[[AssociatedMediaStreamIds]]}} slot is used when sender is represented in SDP as described in [[!RFC8829]].
Set sender.{{RTCRtpSender/[[AssociatedMediaStreamIds]]}} to an empty set.
For each stream in streams, add stream.id to {{RTCRtpSender/[[AssociatedMediaStreamIds]]}} if it's not already there.
Let sender have a [[\SendEncodings]] internal slot, representing a list of {{RTCRtpEncodingParameters}} dictionaries.
If sendEncodings is given as input to this algorithm,
and is non-empty, set the {{RTCRtpSender/[[SendEncodings]]}} slot to
sendEncodings. Otherwise, set it to a list containing
a single {{RTCRtpEncodingParameters}} with
{{RTCRtpEncodingParameters/active}} set to true
.
Let sender have a [[\SendCodecs]] internal slot, representing a list of {{RTCRtpCodecParameters}} dictionaries, and initialized to an empty list.
Let sender have a [[\LastReturnedParameters]] internal slot, which will be used to match {{RTCRtpSender/getParameters}} and {{RTCRtpSender/setParameters}} transactions.
Return sender.
[Exposed=Window] interface RTCRtpSender { readonly attribute MediaStreamTrack? track; readonly attribute RTCDtlsTransport? transport; static RTCRtpCapabilities? getCapabilities(DOMString kind); Promise<undefined> setParameters(RTCRtpSendParameters parameters); RTCRtpSendParameters getParameters(); Promise<undefined> replaceTrack(MediaStreamTrack? withTrack); undefined setStreams(MediaStream... streams); Promise<RTCStatsReport> getStats(); };
The {{track}} attribute is the track that is associated with
this {{RTCRtpSender}} object. If {{track}} is ended, or if
the track's output is disabled, i.e. the track is disabled
and/or muted, the {{RTCRtpSender}} MUST send black frames
(video) and MUST NOT send (audio). In the case of video, the
{{RTCRtpSender}} SHOULD send one black frame per second. If
{{track}} is null
then the {{RTCRtpSender}} does
not send. On getting, the attribute MUST return the value of
the {{RTCRtpSender/[[SenderTrack]]}} slot.
The {{transport}} attribute is the transport over which media from {{track}} is sent in the form of RTP packets. Prior to construction of the {{RTCDtlsTransport}} object, the {{transport}} attribute will be null. When bundling is used, multiple {{RTCRtpSender}} objects will share one {{transport}} and will all send RTP and RTCP over the same transport.
On getting, the attribute MUST return the value of the {{RTCRtpSender/[[SenderTransport]]}} slot.
The {{getCapabilities()}} method returns the most optimistic
view of the capabilities of the system for sending media of
the given kind. It does not reserve any resources, ports, or
other state but is meant to provide a way to discover the
types of capabilities of the browser including which codecs
may be supported. User agents MUST support kind
values of "audio"
and "video"
. If
the system has no capabilities corresponding to the value of
the kind argument, {{getCapabilities}} returns
null
.
These capabilities provide generally persistent cross-origin information on the device and thus increases the fingerprinting surface of the application. In privacy-sensitive contexts, browsers can consider mitigations such as reporting only a common subset of the capabilities.
The codec capabilities returned affect the {{RTCRtpTransceiver/setCodecPreferences()}} algorithm and what inputs it throws {{InvalidModificationError}} on, and should also be consistent with information revealed by {{RTCPeerConnection/createOffer()}} and {{RTCPeerConnection/createAnswer()}} about codecs negotiated for sending, to ensure any privacy mitigations are effective.
The {{setParameters}} method updates how {{track}} is encoded and transmitted to a remote peer.
When the {{setParameters}} method is called, the user agent MUST run the following steps:
true
, return a promise [= rejected =] with a
newly [= exception/created =] {{InvalidStateError}}.
null
, return a promise [= rejected =] with a
newly [= exception/created =] {{InvalidStateError}}.
encodings.length
is
different from N.
Verify that each encoding in encodings has a {{RTCRtpEncodingParameters/scaleResolutionDownBy}} member whose value is greater than or equal to 1.0. If one of the {{RTCRtpEncodingParameters/scaleResolutionDownBy}} values does not meet this requirement, return a promise [= rejected =] with a newly [= exception/created =] {{RangeError}}.
null
.
undefined
.
{{setParameters}} does not cause SDP renegotiation and can only be used to change what the media stack is sending or receiving within the envelope negotiated by Offer/Answer. The attributes in the {{RTCRtpSendParameters}} dictionary are designed to not enable this, so attributes like {{RTCRtcpParameters/cname}} that cannot be changed are read-only. Other things, like bitrate, are controlled using limits such as {{RTCRtpEncodingParameters/maxBitrate}}, where the user agent needs to ensure it does not exceed the maximum bitrate specified by {{RTCRtpEncodingParameters/maxBitrate}}, while at the same time making sure it satisfies constraints on bitrate specified in other places such as the SDP.
The {{getParameters()}} method returns the {{RTCRtpSender}} object's current parameters for how {{track}} is encoded and transmitted to a remote {{RTCRtpReceiver}}.
When {{getParameters}} is called, the user agent MUST run the following steps:
Let sender be the {{RTCRtpSender}} object on which the getter was invoked.
If sender.{{RTCRtpSender/[[LastReturnedParameters]]}}
is not null
, return
sender.{{RTCRtpSender/[[LastReturnedParameters]]}}, and
abort these steps.
Let result be a new {{RTCRtpSendParameters}} dictionary constructed as follows:
true
if reduced-size RTCP has been
negotiated for sending, and false
otherwise.
Set sender.{{RTCRtpSender/[[LastReturnedParameters]]}} to result.
Queue a task that sets
sender.{{RTCRtpSender/[[LastReturnedParameters]]}} to
null
.
Return result.
{{getParameters}} may be used with {{setParameters}} to change the parameters in the following way:
async function updateParameters() { try { const params = sender.getParameters(); // ... make changes to parameters params.encodings[0].active = false; await sender.setParameters(params); } catch (err) { console.error(err); } }
After a completed call to {{setParameters}}, subsequent calls to {{getParameters}} will return the modified set of parameters.
Attempts to replace the {{RTCRtpSender}}'s current {{track}}
with another track provided (or with a null
track), without renegotiation.
When the {{replaceTrack}} method is invoked, the user agent MUST run the following steps:
Let sender be the {{RTCRtpSender}} object on which {{replaceTrack}} is invoked.
Let transceiver be the {{RTCRtpTransceiver}} object associated with sender.
Let connection be the {{RTCPeerConnection}} object associated with sender.
Let withTrack be the argument to this method.
If withTrack is non-null and
withTrack.kind
differs from the
transceiver kind of transceiver, return
a promise [= rejected =] with a newly [=
exception/created =] {{TypeError}}.
Return the result of [= chaining =] the following steps to connection's [= operations chain =]:
If transceiver.{{RTCRtpTransceiver/[[Stopped]]}} is
true
, return a promise [= rejected =]
with a newly [= exception/created =]
{{InvalidStateError}}.
Let p be a new promise.
Let sending be true
if
transceiver.{{RTCRtpTransceiver/[[CurrentDirection]]}}
is {{RTCRtpTransceiverDirection/"sendrecv"}} or
{{RTCRtpTransceiverDirection/"sendonly"}}, and
false
otherwise.
Run the following steps in parallel:
If sending is true
, and
withTrack is null
, have
the sender stop sending.
If sending is true
, and
withTrack is not null
,
determine if withTrack can be sent
immediately by the sender without violating the
sender's already-negotiated envelope, and if it
cannot, then [= reject =] p with a
newly [= exception/created =]
{{InvalidModificationError}}, and abort these
steps.
If sending is true
, and
withTrack is not null
,
have the sender switch seamlessly to transmitting
withTrack instead of the sender's
existing track.
Queue a task that runs the following steps:
If connection.{{RTCPeerConnection/[[IsClosed]]}}
is true
, abort these steps.
Set sender.{{RTCRtpSender/[[SenderTrack]]}} to withTrack.
[= Resolve =] p with
undefined
.
Return p.
Changing dimensions and/or frame rates might not require negotiation. Cases that may require negotiation include:
Sets the {{MediaStream}}s to be associated with this sender's track.
When the {{setStreams}} method is invoked, the user agent MUST run the following steps:
Let sender be the {{RTCRtpSender}} object on which this method was invoked.
Let connection be the {{RTCPeerConnection}} object on which this method was invoked.
If connection.{{RTCPeerConnection/[[IsClosed]]}} is
true
, [= exception/throw =] an
{{InvalidStateError}}.
Let streams be a list of {{MediaStream}} objects constructed from the method's arguments, or an empty list if the method was called without arguments.
Set sender.{{RTCRtpSender/[[AssociatedMediaStreamIds]]}} to an empty set.
For each stream in streams, add stream.id to {{RTCRtpSender/[[AssociatedMediaStreamIds]]}} if it's not already there.
[= Update the negotiation-needed flag =] for connection.
Gathers stats for this sender only and reports the result asynchronously.
When the {{getStats()}} method is invoked, the user agent MUST run the following steps:
Let selector be the {{RTCRtpSender}} object on which the method was invoked.
Let p be a new promise, and run the following steps in parallel:
Gather the stats indicated by selector according to the [= stats selection algorithm =].
[= Resolve =] p with the resulting {{RTCStatsReport}} object, containing the gathered stats.
Return p.
dictionary RTCRtpParameters { required sequence<RTCRtpHeaderExtensionParameters> headerExtensions; required RTCRtcpParameters rtcp; required sequence<RTCRtpCodecParameters> codecs; };
A sequence containing parameters for RTP header extensions. Read-only parameter.
Parameters used for RTCP. Read-only parameter.
A sequence containing the media codecs that an
{{RTCRtpSender}} will choose from, as well as entries for
RTX, RED and FEC mechanisms. Corresponding to each media
codec where retransmission via RTX is enabled, there will
be an entry in {{codecs}} with a
{{RTCRtpCodecParameters/mimeType}} attribute indicating
retransmission via audio/rtx
or
video/rtx
, and an
{{RTCRtpCodecParameters/sdpFmtpLine}} attribute (providing
the "apt" and "rtx-time" parameters). Read-only
parameter.
dictionary RTCRtpSendParameters : RTCRtpParameters { required DOMString transactionId; required sequence<RTCRtpEncodingParameters> encodings; };
A unique identifier for the last set of parameters applied. Ensures that {{RTCRtpSender/setParameters}} can only be called based on a previous {{RTCRtpSender/getParameters}}, and that there are no intervening changes. [= Read-only parameter =].
A sequence containing parameters for RTP encodings of media.
dictionary RTCRtpReceiveParameters : RTCRtpParameters { };
dictionary RTCRtpCodingParameters { DOMString rid; };
If set, this RTP encoding will be sent with the RID header extension as defined by [[!RFC8829]]. The RID is not modifiable via {{RTCRtpSender/setParameters}}. It can only be set or modified in {{RTCPeerConnection/addTransceiver}} on the sending side. Read-only parameter.
dictionary RTCRtpDecodingParameters : RTCRtpCodingParameters {};
dictionary RTCRtpEncodingParameters : RTCRtpCodingParameters { boolean active = true; unsigned long maxBitrate; double scaleResolutionDownBy; };
true
Indicates that this encoding is actively being sent.
Setting it to false
causes this encoding to no
longer be sent. Setting it to true
causes this
encoding to be sent. Since setting the value to
false
does not cause the SSRC to be removed,
an RTCP BYE is not sent.
When present, indicates the maximum bitrate that can be used to send this encoding. The user agent is free to allocate bandwidth between the encodings, as long as the {{maxBitrate}} value is not exceeded. The encoding may also be further constrained by other limits (such as per-transport or per-session bandwidth limits) below the maximum specified here. {{maxBitrate}} is computed the same way as the Transport Independent Application Specific Maximum (TIAS) bandwidth defined in [[RFC3890]] Section 6.2.2, which is the maximum bandwidth needed without counting IP or other transport layers like TCP or UDP. The unit of {{maxBitrate}} is bits per second.
How the bitrate is achieved is media and encoding dependent. For video, a frame will always be sent as fast as possible, but frames may be dropped until bitrate is low enough. Thus, even a bitrate of zero will allow sending one frame. For audio, it might be necessary to stop playing if the bitrate does not allow the chosen encoding enough bandwidth to be sent.
This member is only present if the sender's kind
is "video"
. The video's
resolution will be scaled down in each dimension by the
given value before sending. For example, if the value is
2.0, the video will be scaled down by a factor of 2 in each
dimension, resulting in sending a video of one quarter the
size. If the value is 1.0, the video will not be affected.
The value must be greater than or equal to 1.0. By default,
scaling is applied by a factor of two to the power of the
layer's number, in order of smaller to higher resolutions,
e.g. 4:2:1. If there is only one layer, the sender will by
default not apply any scaling, (i.e.
{{RTCRtpEncodingParameters/scaleResolutionDownBy}} will be
1.0).
dictionary RTCRtcpParameters { DOMString cname; boolean reducedSize; };
The Canonical Name (CNAME) used by RTCP (e.g. in SDES messages). Read-only parameter.
Whether reduced size RTCP [[RFC5506]] is configured (if true) or compound RTCP as specified in [[RFC3550]] (if false). Read-only parameter.
dictionary RTCRtpHeaderExtensionParameters { required DOMString uri; required unsigned short id; boolean encrypted = false; };
The URI of the RTP header extension, as defined in [[RFC5285]]. Read-only parameter.
The value put in the RTP packet to identify the header extension. Read-only parameter.
Whether the header extension is encrypted or not. Read-only parameter.
The {{RTCRtpHeaderExtensionParameters}} dictionary enables an application to determine whether a header extension is configured for use within an {{RTCRtpSender}} or {{RTCRtpReceiver}}. For an {{RTCRtpTransceiver}} transceiver, an application can determine the "direction" parameter (defined in Section 5 of [[RFC5285]]) of a header extension as follows without having to parse SDP:
dictionary RTCRtpCodecParameters { required octet payloadType; required DOMString mimeType; required unsigned long clockRate; unsigned short channels; DOMString sdpFmtpLine; };
The RTP payload type used to identify this codec. Read-only parameter.
The codec MIME media type/subtype. Valid media types and subtypes are listed in [[IANA-RTP-2]]. Read-only parameter.
The codec clock rate expressed in Hertz. Read-only parameter.
When present, indicates the number of channels (mono=1, stereo=2). Read-only parameter.
The "format specific parameters" field from the
a=fmtp
line in the SDP
corresponding to the codec, if one exists, as defined by
[[!RFC8829]]. For an
{{RTCRtpSender}}, these parameters come from the remote
description, and for an {{RTCRtpReceiver}}, they come from
the local description. Read-only parameter.
dictionary RTCRtpCapabilities { required sequence<RTCRtpCodecCapability> codecs; required sequence<RTCRtpHeaderExtensionCapability> headerExtensions; };
Supported media codecs as well as entries for RTX, RED and FEC mechanisms. There will only be a single entry in {{codecs}} for retransmission via RTX, with {{RTCRtpCodecCapability/sdpFmtpLine}} not present.
Supported RTP header extensions.
dictionary RTCRtpCodecCapability { required DOMString mimeType; required unsigned long clockRate; unsigned short channels; DOMString sdpFmtpLine; };
The {{RTCRtpCodecCapability}} dictionary provides information about codec capabilities. Only capability combinations that would utilize distinct payload types in a generated SDP offer are provided. For example:
The codec MIME media type/subtype. Valid media types and subtypes are listed in [[IANA-RTP-2]].
The codec clock rate expressed in Hertz.
If present, indicates the maximum number of channels (mono=1, stereo=2).
The "format specific parameters" field from the
a=fmtp
line in the SDP
corresponding to the codec, if one exists.
dictionary RTCRtpHeaderExtensionCapability { DOMString uri; };
The URI of the RTP header extension, as defined in [[RFC5285]].
The {{RTCRtpReceiver}} interface allows an application to inspect the receipt of a {{MediaStreamTrack}}.
To create an RTCRtpReceiver with a string, kind, run the following steps:
Let receiver be a new {{RTCRtpReceiver}} object.
Let track be a new {{MediaStreamTrack}} object
[[!GETUSERMEDIA]]. The source of track is a
remote source provided by receiver. Note
that the track.id
is
generated by the user agent and does not map to any track
IDs on the remote side.
Initialize track.kind to kind.
Initialize track.label to the result of concatenating
the string "remote "
with kind.
Initialize track.readyState to live
.
Initialize track.muted to true
. See the
MediaStreamTrack
section about how the muted
attribute
reflects if a {{MediaStreamTrack}} is receiving media data or
not.
Let receiver have a [[\ReceiverTrack]] internal slot initialized to track.
Let receiver have a [[\ReceiverTransport]]
internal slot initialized to null
.
Let receiver have a
[[\LastStableStateReceiverTransport]] internal slot
initialized to null
.
Let receiver have an [[\AssociatedRemoteMediaStreams]] internal slot, representing a list of {{MediaStream}} objects that the {{MediaStreamTrack}} object of this receiver is associated with, and initialized to an empty list.
Let receiver have a [[\LastStableStateAssociatedRemoteMediaStreams]] internal slot and initialize it to an empty list.
Let receiver have a [[\ReceiveCodecs]] internal slot, representing a list of {{RTCRtpCodecParameters}} dictionaries, and initialized to an empty list.
Let receiver have a [[\LastStableStateReceiveCodecs]] internal slot and initialize it to an empty list.
Return receiver.
[Exposed=Window] interface RTCRtpReceiver { readonly attribute MediaStreamTrack track; readonly attribute RTCDtlsTransport? transport; static RTCRtpCapabilities? getCapabilities(DOMString kind); RTCRtpReceiveParameters getParameters(); sequence<RTCRtpContributingSource> getContributingSources(); sequence<RTCRtpSynchronizationSource> getSynchronizationSources(); Promise<RTCStatsReport> getStats(); };
The {{track}} attribute is the track that is associated with this {{RTCRtpReceiver}} object receiver.
Note that {{track}}.stop()
is final,
although clones are not affected. Since
receiver.{{track}}.stop()
does not implicitly stop receiver, Receiver
Reports continue to be sent. On getting, the attribute MUST
return the value of the {{RTCRtpReceiver/[[ReceiverTrack]]}} slot.
The {{transport}} attribute is the transport over which media
for the receiver's {{RTCRtpReceiver/track}} is received in
the form of RTP packets. Prior to construction of the
{{RTCDtlsTransport}} object, the {{transport}} attribute will
be null
. When bundling is used, multiple
{{RTCRtpReceiver}} objects will share one {{transport}} and
will all receive RTP and RTCP over the same transport.
On getting, the attribute MUST return the value of the {{RTCRtpReceiver/[[ReceiverTransport]]}} slot.
The {{getCapabilities()}} method returns the most optimistic
view of the capabilities of the system for receiving media of
the given kind. It does not reserve any resources, ports, or
other state but is meant to provide a way to discover the
types of capabilities of the browser including which codecs
may be supported. User agents MUST support kind
values of "audio"
and "video"
. If
the system has no capabilities corresponding to the value of
the kind argument, {{getCapabilities}} returns
null
.
These capabilities provide generally persistent cross-origin information on the device and thus increases the fingerprinting surface of the application. In privacy-sensitive contexts, browsers can consider mitigations such as reporting only a common subset of the capabilities.
The codec capabilities returned affect the {{RTCRtpTransceiver/setCodecPreferences()}} algorithm and what inputs it throws {{InvalidModificationError}} on, and should also be consistent with information revealed by {{RTCPeerConnection/createOffer()}} and {{RTCPeerConnection/createAnswer()}} about codecs negotiated for reception, to ensure any privacy mitigations are effective.
The {{getParameters()}} method returns the {{RTCRtpReceiver}} object's current parameters for how {{track}} is decoded.
When {{getParameters}} is called, the {{RTCRtpReceiveParameters}} dictionary is constructed as follows:
{{RTCRtpParameters/codecs}} には、{{RTCRtpReceiver/[[ReceiveCodecs]]}} 内部スロットの値が設定されます。
true
に設定され、そうでない場合は false
に設定されます。{{RTCRtpParameters/rtcp}}.{{RTCRtcpParameters/cname}} は省略されます。
Returns an {{RTCRtpContributingSource}} for each unique CSRC identifier received by this {{RTCRtpReceiver}} in the last 10 seconds, in descending {{RTCRtpContributingSource/timestamp}} order.
Returns an {{RTCRtpSynchronizationSource}} for each unique SSRC identifier received by this {{RTCRtpReceiver}} in the last 10 seconds, in descending {{RTCRtpContributingSource/timestamp}} order.
Gathers stats for this receiver only and reports the result asynchronously.
When the {{getStats()}} method is invoked, the user agent MUST run the following steps:
Let selector be the {{RTCRtpReceiver}} object on which the method was invoked.
Let p be a new promise, and run the following steps in parallel:
Gather the stats indicated by selector according to the [= stats selection algorithm =].
[= Resolve =] p with the resulting {{RTCStatsReport}} object, containing the gathered stats.
Return p.
The RTCRtpContributingSource and RTCRtpSynchronizationSource dictionaries contain information about a given contributing source (CSRC) or synchronization source (SSRC) respectively. When an audio or video frame from one or more RTP packets is delivered to the {{RTCRtpReceiver}}'s {{MediaStreamTrack}}, the user agent MUST queue a task to update the relevant information for the {{RTCRtpContributingSource}} and {{RTCRtpSynchronizationSource}} dictionaries based on the content of those packets. The information relevant to the {{RTCRtpSynchronizationSource}} dictionary corresponding to the SSRC identifier, is updated each time, and if an RTP packet contains CSRC identifiers, then the information relevant to the {{RTCRtpContributingSource}} dictionaries corresponding to those CSRC identifiers is also updated. The user agent MUST process RTP packets in order of ascending RTP timestamps. The user agent MUST keep information from RTP packets delivered to the {{RTCRtpReceiver}}'s {{MediaStreamTrack}} in the previous 10 seconds.
dictionary RTCRtpContributingSource { required DOMHighResTimeStamp timestamp; required unsigned long source; double audioLevel; required unsigned long rtpTimestamp; };
The {{timestamp}} indicating the most recent time a frame from an RTP packet, originating from this source, was delivered to the {{RTCRtpReceiver}}'s {{MediaStreamTrack}}. The {{timestamp}} is defined as {{Performance.timeOrigin}} + {{Performance.now()}} at that time.
The CSRC or SSRC identifier of the contributing or synchronization source.
Only present for audio receivers. This is a value between 0..1 (linear), where 1.0 represents 0 dBov, 0 represents silence, and 0.5 represents approximately 6 dBSPL change in the sound pressure level from 0 dBov.
For CSRCs, this MUST be converted from the level value defined in [[!RFC6465]] if the RFC 6465 header extension is present, otherwise this member MUST be absent.
For SSRCs, this MUST be converted from the level value defined in [[!RFC6464]]. If the RFC 6464 header extension is not present in the received packets (such as if the other endpoint is not a user agent or is a legacy endpoint), this value SHOULD be absent.
Both RFCs define the level as an integral value from 0 to 127 representing the audio level in negative decibels relative to the loudest signal that the system could possibly encode. Thus, 0 represents the loudest signal the system could possibly encode, and 127 represents silence.
To convert these values to the linear 0..1 range, a value of
127 is converted to 0, and all other values are converted
using the equation: 10^(-rfc_level/20)
.
The RTP timestamp, as defined in [[!RFC3550]] Section 5.1, of the media played out at timestamp.
dictionary RTCRtpSynchronizationSource : RTCRtpContributingSource { };
The {{RTCRtpSynchronizationSource}} dictionary is expected to serve as an extension point for the specification to surface data only available in SSRCs.
The {{RTCRtpTransceiver}} interface represents a combination of an {{RTCRtpSender}} and an {{RTCRtpReceiver}} that share a common [= media stream "identification-tag" =]. As defined in [[!RFC8829]], an {{RTCRtpTransceiver}} is said to be associated with a [= media description =] if its "mid" property is non-null and matches a [= media stream "identification-tag" =] in the [= media description =]; otherwise it is said to be disassociated with that [= media description =].
A {{RTCRtpTransceiver}} may become associated with a new pending description in RFC8829 while still being disassociated with the current description. This may happen in [= check if negotiation is needed =].
The transceiver kind of an {{RTCRtpTransceiver}} is defined by the kind of the associated {{RTCRtpReceiver}}'s {{MediaStreamTrack}} object.
To create an RTCRtpTransceiver with an {{RTCRtpReceiver}} object, receiver, {{RTCRtpSender}} object, sender, and an {{RTCRtpTransceiverDirection}} value, direction, run the following steps:
Let transceiver be a new {{RTCRtpTransceiver}} object.
Let transceiver have a [[\Sender]] internal slot, initialized to sender.
Let transceiver have a [[\Receiver]] internal slot, initialized to receiver.
Let transceiver have a [[\Stopping]]
internal slot, initialized to false
.
Let transceiver have a [[\Stopped]]
internal slot, initialized to false
.
Let transceiver have a [[\Direction]] internal slot, initialized to direction.
Let transceiver have a [[\Receptive]]
internal slot, initialized to false
.
Let transceiver have a
[[\CurrentDirection]] internal slot, initialized to
null
.
Let transceiver have a [[\FiredDirection]]
internal slot, initialized to null
.
Let transceiver have a [[\PreferredCodecs]] internal slot, initialized to an empty list.
Let transceiver have a [[\JsepMid]]
internal slot, initialized to null
. This is the
"RtpTransceiver mid property" defined in [[!RFC8829]], and is only
modified there.
Let transceiver have a [[\Mid]] internal
slot, initialized to null
.
Return transceiver.
[Exposed=Window] interface RTCRtpTransceiver { readonly attribute DOMString? mid; [SameObject] readonly attribute RTCRtpSender sender; [SameObject] readonly attribute RTCRtpReceiver receiver; attribute RTCRtpTransceiverDirection direction; readonly attribute RTCRtpTransceiverDirection? currentDirection; undefined stop(); undefined setCodecPreferences(sequence<RTCRtpCodecCapability> codecs); };
The {{mid}} attribute is the [= media stream "identification-tag" =] negotiated and present in the local and remote descriptions. On getting, the attribute MUST return the value of the {{RTCRtpTransceiver/[[Mid]]}} slot.
The {{sender}} attribute exposes the {{RTCRtpSender}} corresponding to the RTP media that may be sent with mid = {{RTCRtpTransceiver/[[Mid]]}}. On getting, the attribute MUST return the value of the {{RTCRtpTransceiver/[[Sender]]}} slot.
The {{receiver}} attribute is the {{RTCRtpReceiver}} corresponding to the RTP media that may be received with mid = {{RTCRtpTransceiver/[[Mid]]}}. On getting the attribute MUST return the value of the {{RTCRtpTransceiver/[[Receiver]]}} slot.
As defined in [[!RFC8829]], the
direction attribute indicates the preferred
direction of this transceiver, which will be used in calls to
{{RTCPeerConnection/createOffer}} and
{{RTCPeerConnection/createAnswer}}. An update of
directionality does not take effect immediately. Instead,
future calls to {{RTCPeerConnection/createOffer}} and
{{RTCPeerConnection/createAnswer}} mark the corresponding [=
media description =] as sendrecv
,
sendonly
, recvonly
or inactive
as
defined in [[!RFC8829]]
On getting, the user agent MUST run the following steps:
Let transceiver be the {{RTCRtpTransceiver}} object on which the getter is invoked.
If transceiver.{{RTCRtpTransceiver/[[Stopping]]}} is
true
, return
{{RTCRtpTransceiverDirection/"stopped"}}.
Otherwise, return the value of the {{RTCRtpTransceiver/[[Direction]]}} slot.
On setting, the user agent MUST run the following steps:
Let transceiver be the {{RTCRtpTransceiver}} object on which the setter is invoked.
Let connection be the {{RTCPeerConnection}} object associated with transceiver.
If transceiver.{{RTCRtpTransceiver/[[Stopping]]}} is
true
, [= exception/throw =] an
{{InvalidStateError}}.
Let newDirection be the argument to the setter.
If newDirection is equal to transceiver.{{RTCRtpTransceiver/[[Direction]]}}, abort these steps.
If newDirection is equal to {{RTCRtpTransceiverDirection/"stopped"}}, [= exception/throw =] a {{TypeError}}.
Set transceiver.{{RTCRtpTransceiver/[[Direction]]}} to newDirection.
Update the negotiation-needed flag for connection.
As defined in [[!RFC8829]], the
currentDirection attribute indicates the current
direction negotiated for this transceiver. The value of
currentDirection is independent of the value of
{{RTCRtpEncodingParameters}}.{{RTCRtpEncodingParameters/active}}
since one cannot be deduced from the other. If this
transceiver has never been represented in an offer/answer
exchange, the value is null
. If the transceiver
is {{stopped}}, the value is
{{RTCRtpTransceiverDirection/"stopped"}}.
On getting, the user agent MUST run the following steps:
Let transceiver be the {{RTCRtpTransceiver}} object on which the getter is invoked.
If transceiver.{{RTCRtpTransceiver/[[Stopped]]}} is
true
, return
{{RTCRtpTransceiverDirection/"stopped"}}.
Otherwise, return the value of the {{RTCRtpTransceiver/[[CurrentDirection]]}} slot.
Irreversibly marks the transceiver as {{stopping}}, unless it is already {{stopped}}. This will immediately cause the transceiver's sender to no longer send, and its receiver to no longer receive. Calling {{stop()}} also [= update the negotiation-needed flag | updates the negotiation-needed flag =] for the {{RTCRtpTransceiver}}'s associated {{RTCPeerConnection}}.
A stopping transceiver will cause future calls to {{RTCPeerConnection/createOffer}} to generate a zero port in the [= media description =] for the corresponding transceiver, as defined in [[!RFC8829]] (The user agent MUST treat a {{stopping}} transceiver as {{stopped}} for the purposes of RFC8829 only in this case). However, to avoid problems with [[RFC8843]], a transceiver that is {{stopping}}, but not {{stopped}}, will not affect {{RTCPeerConnection/createAnswer}}.
A stopped transceiver will cause future calls to {{RTCPeerConnection/createOffer}} or {{RTCPeerConnection/createAnswer}} to generate a zero port in the [= media description =] for the corresponding transceiver, as defined in [[!RFC8829]].
The transceiver will remain in the {{stopping}} state, unless it becomes {{stopped}} by {{RTCPeerConnection/setRemoteDescription}} processing a rejected m-line in a remote offer or answer.
A transceiver that is {{stopping}} but not {{stopped}} will always need negotiation. In practice, this means that calling {{stop()}} on a transceiver will cause the transceiver to become {{stopped}} eventually, provided negotiation is allowed to complete on both ends.
When the {{stop}} method is invoked, the user agent MUST run the following steps:
Let transceiver be the {{RTCRtpTransceiver}} object on which the method is invoked.
Let connection be the {{RTCPeerConnection}} object associated with transceiver.
If connection.{{RTCPeerConnection/[[IsClosed]]}} is
true
, [= exception/throw =] an
{{InvalidStateError}}.
If transceiver.{{RTCRtpTransceiver/[[Stopping]]}} is
true
, abort these steps.
[= Stop sending and receiving =] with transceiver.
Update the negotiation-needed flag for connection.
The stop sending and receiving algorithm given a
transceiver and, optionally, a
disappear boolean defaulting to
false
, is as follows:
Let sender be transceiver.{{RTCRtpTransceiver/[[Sender]]}}.
Let receiver be transceiver.{{RTCRtpTransceiver/[[Receiver]]}}.
Stop sending media with sender.
Send an RTCP BYE for each RTP stream that was being sent by sender, as specified in [[!RFC3550]].
Stop receiving media with receiver.
If disappear is false
, execute
the steps for
receiver.{{RTCRtpReceiver/[[ReceiverTrack]]}} to be
ended. This
fires an event.
Set transceiver.{{RTCRtpTransceiver/[[Direction]]}} to {{RTCRtpTransceiverDirection/"inactive"}}.
Set transceiver.{{RTCRtpTransceiver/[[Stopping]]}} to
true
.
The stop the RTCRtpTransceiver algorithm given a
transceiver and, optionally, a
disappear boolean defaulting to
false
, is as follows:
If transceiver.{{RTCRtpTransceiver/[[Stopping]]}} is
false
, [= stop sending and receiving =] with
transceiver and disappear.
Set transceiver.{{RTCRtpTransceiver/[[Stopped]]}} to
true
.
Set transceiver.{{RTCRtpTransceiver/[[Receptive]]}} to
false
.
Set transceiver.{{RTCRtpTransceiver/[[CurrentDirection]]}}
to null
.
The {{setCodecPreferences}} method overrides the default codec preferences used by the user agent. When generating a session description using either {{RTCPeerConnection/createOffer}} or {{RTCPeerConnection/createAnswer}}, the user agent MUST use the indicated codecs, in the order specified in the codecs argument, for the media section corresponding to this {{RTCRtpTransceiver}}.
This method allows applications to disable the negotiation of specific codecs (including RTX/RED/FEC). It also allows an application to cause a remote peer to prefer the codec that appears first in the list for sending.
Codec preferences remain in effect for all calls to {{RTCPeerConnection/createOffer}} and {{RTCPeerConnection/createAnswer}} that include this {{RTCRtpTransceiver}} until this method is called again. Setting codecs to an empty sequence resets codec preferences to any default value.
Codecs have their payload types listed under each m= section in the SDP, defining the mapping between payload types and codecs. These payload types are referenced by the m=video or m=audio lines in the order of preference, and codecs that are not negotiated do not appear in this list as defined in section 5.2.1 of [[!RFC8829]]. A previously negotiated codec that is subsequently removed disappears from the m=video or m=audio line, and while its codec payload type is not to be reused in future offers or answers, its payload type may also be removed from the mapping of payload types in the SDP.
The codecs sequence passed into {{setCodecPreferences}} can only contain codecs that are returned by {{RTCRtpSender}}.{{RTCRtpSender/getCapabilities}}(kind) or {{RTCRtpReceiver}}.{{RTCRtpReceiver/getCapabilities}}(kind), where kind is the kind of the {{RTCRtpTransceiver}} on which the method is called. Additionally, the {{RTCRtpCodecCapability}} dictionary members cannot be modified. If codecs does not fulfill these requirements, the user agent MUST [= exception/throw =] an {{InvalidModificationError}}.
Due to a recommendation in [[!SDP]], calls to {{RTCPeerConnection/createAnswer}} SHOULD use only the common subset of the codec preferences and the codecs that appear in the offer. For example, if codec preferences are "C, B, A", but only codecs "A, B" were offered, the answer should only contain codecs "B, A". However, [[!RFC8829]] allows adding codecs that were not in the offer, so implementations can behave differently.
When {{setCodecPreferences()}} is invoked, the user agent MUST run the following steps:
Let transceiver be the {{RTCRtpTransceiver}} object this method was invoked on.
Let codecs be the first argument.
If codecs is an empty list, set transceiver.{{RTCRtpTransceiver/[[PreferredCodecs]]}} to codecs and abort these steps.
Remove any duplicate values in codecs. Start at the back of the list such that the priority of the codecs is maintained; the index of the first occurrence of a codec within the list is the same before and after this step.
Let kind be the transceiver's [= transceiver kind =].
If the intersection between codecs and {{RTCRtpSender}}.{{RTCRtpSender/getCapabilities}}(kind).{{RTCRtpParameters/codecs}} or the intersection between codecs and {{RTCRtpReceiver}}.{{RTCRtpReceiver/getCapabilities}}(kind).{{RTCRtpParameters/codecs}} only contains RTX, RED or FEC codecs or is an empty set, throw {{InvalidModificationError}}. This ensures that we always have something to offer, regardless of transceiver.{{RTCRtpTransceiver/direction}}.
Let codecCapabilities be the union of {{RTCRtpSender}}.{{RTCRtpSender/getCapabilities}}(kind).{{RTCRtpParameters/codecs}} and {{RTCRtpReceiver}}.{{RTCRtpReceiver/getCapabilities}}(kind).{{RTCRtpParameters/codecs}}.
For each codec in codecs,
Set transceiver.{{RTCRtpTransceiver/[[PreferredCodecs]]}} to codecs.
If set, the offerer's codec preferences will decide the order of the codecs in the offer. If the answerer does not have any codec preferences then the same order will be used in the answer. However, if the answerer also has codec preferences, these preferences override the order in the answer. In this case, the offerer's preferences would affect which codecs were on offer but not the final order.
サイマルキャスト機能は、{{RTCPeerConnection}} オブジェクトの {{RTCPeerConnection/addTransceiver}} メソッドと、{{RTCRtpSender}} オブジェクトの {{RTCRtpSender/setParameters}} メソッドによって提供されます。
{{RTCPeerConnection/addTransceiver}} メソッドは、送信可能なサイマルキャストストリームの最大数や、{{RTCRtpSendParameters/encodings}} の順序を含む simulcast envelope を確立します。個々のサイマルキャストストリームの特性は {{RTCRtpSender/setParameters}} メソッドを使って変更できますが、[= simulcast envelope =] は変更できません。このモデルの意味するところは、{{RTCRtpTransceiverInit/sendEncodings}} を引数として取らないため、{{RTCRtpTransceiver}} がサイマルキャストを送信するように設定することができないので、{{RTCPeerConnection/addTrack()}} メソッドがサイマルキャスト機能を提供できないことです。
もう1つの意味は、回答者が [= simulcast envelope =] を直接設定できないということです。{{RTCPeerConnection}} オブジェクトの {{RTCPeerConnection/setRemoteDescription}} メソッドを呼び出すと、{{RTCRtpTransceiver}} 上で、指定されたセッション記述で記述されたレイヤーを含むように [= simulcast envelope =] が設定されます。エンベロープが決定すると、レイヤーは削除できません。{{RTCRtpEncodingParameters/active}} メンバを false
に設定することで、レイヤーを非アクティブにすることができます。
{{RTCRtpSender/setParameters}} は [= simulcast envelope =] を変更することはできませんが、送信されるストリームの数やストリームの特性を制御することは可能です。{{RTCRtpSender/setParameters}} を使用して、{{RTCRtpEncodingParameters/active}} メンバを false
に設定することで、サイマルキャスト・ストリームを非アクティブにしたり、{{RTCRtpEncodingParameters/active}} メンバを true
に設定することで、再アクティブにすることができます。{{RTCRtpSender/setParameters}} を使用して、{{RTCRtpEncodingParameters/maxBitrate}} などの属性を変更することで、ストリームの特性を変更することができます。
サイマルキャストは、複数のエンコーディングをSFUに送信し、SFUがそのうちの1つのサイマルキャストストリームをエンドユーザーに転送するためによく使われます。たとえば、2つのサイマルキャストストリームの {{RTCRtpEncodingParameters/maxBitrate}} が同じであれば、両方のストリームに同じようなビットレートが表示されることが期待されます。帯域幅がすべてのサイマルキャストストリームを使用可能な形で送信することを許可しない場合、ユーザーエージェントはサイマルキャストストリームの一部の送信を停止することが期待されます。
[[!RFC8829]] で定義されているように、ユーザーエージェントからのオファーは、a=simulcast
の行に "send" の記述のみを含み、"recv" の記述はありません。代替案や制限([[RFC8853]] に記載)はサポートされていません。
本仕様では、{{RTCPeerConnection/createOffer}}、{{RTCPeerConnection/createAnswer}}、{{RTCPeerConnection/addTransceiver}} を使用して複数の RTP エンコーディングの受信を設定する方法は定義されていません。ただし、{{RTCPeerConnection/setRemoteDescription}} が、[[!RFC8829]] で定義されている複数の RTP エンコーディングを送信できる対応するリモート記述で {{RTCRtpReceiver}} が呼び出され、ブラウザが複数の RTP エンコーディングの受信をサポートしている場合、{{RTCRtpReceiver} は複数の RTP エンコーディングを受信することができ、トランシーバの {{RTCRtpTransceiver/receiver}.{{RTCRtpReceiver/getParameters()}} を介して取得されるパラメータには、ネゴシエートされたエンコーディングが反映されます。
Selective Forwarding Unit(SFU)がユーザーエージェントから受信するサイマルキャストストリームを切り替えるシナリオでは、{{RTCRtpReceiver}}は複数のRTPストリームを受信することができます。SFUが転送前に、切り替わったストリームを単一の RTP ストリームにまとめるようにRTPヘッダーを書き換えない場合、{{RTCRtpReceiver}} は、それぞれが独自の SSRC とシーケンス番号スペースを持つ、異なる RTP ストリームからのパケットを受信することになります。SFU は常に単一の RTP ストリームのみを転送することができますが、複数の RTP ストリームからのパケットは、並び替えにより受信機で混ざり合う可能性があります。そのため、複数の RTP ストリームを受信するために装備された {{RTCRtpReceiver}} は、受信したパケットを正しく順序付け、潜在的な損失イベントを認識し、それに対応することができる必要があります。このシナリオでの正しい操作は自明ではないため、本仕様の実装ではオプションとなります。
エンコーディングパラメータを用いて実装されたサイマル放送のシナリオの例:
// 最低解像度のレイヤー以外を無効にした 3 レイヤーの空間サイマルキャストの例 var encodings = [ {rid: 'q', active: true, scaleResolutionDownBy: 4.0} {rid: 'h', active: false, scaleResolutionDownBy: 2.0}, {rid: 'f', active: false}, ];
Together, the {{RTCRtpTransceiver/direction}} attribute and the {{RTCRtpSender/replaceTrack}} method enable developers to implement "hold" scenarios.
To send music to a peer and cease rendering received audio (music-on-hold):
async function playMusicOnHold() { try { // Assume we have an audio transceiver and a music track named musicTrack await audio.sender.replaceTrack(musicTrack); // Mute received audio audio.receiver.track.enabled = false; // Set the direction to send-only (requires negotiation) audio.direction = 'sendonly'; } catch (err) { console.error(err); } }
To respond to a remote peer's "sendonly" offer:
async function handleSendonlyOffer() { try { // Apply the sendonly offer first, // to ensure the receiver is ready for ICE candidates. await pc.setRemoteDescription(sendonlyOffer); // Stop sending audio await audio.sender.replaceTrack(null); // Align our direction to avoid further negotiation audio.direction = 'recvonly'; // Call createAnswer and send a recvonly answer await doAnswer(); } catch (err) { // handle signaling error } }
To stop sending music and send audio captured from a microphone, as well to render received audio:
async function stopOnHoldMusic() { // Assume we have an audio transceiver and a microphone track named micTrack await audio.sender.replaceTrack(micTrack); // Unmute received audio audio.receiver.track.enabled = true; // Set the direction to sendrecv (requires negotiation) audio.direction = 'sendrecv'; }
To respond to being taken off hold by a remote peer:
async function onOffHold() { try { // Apply the sendrecv offer first, to ensure receiver is ready for ICE candidates. await pc.setRemoteDescription(sendrecvOffer); // Start sending audio await audio.sender.replaceTrack(micTrack); // Set the direction sendrecv (just in time for the answer) audio.direction = 'sendrecv'; // Call createAnswer and send a sendrecv answer await doAnswer(); } catch (err) { // handle signaling error } }
{{RTCDtlsTransport}} インターフェースは、{{RTCRtpSender}} と {{RTCRtpReceiver}} オブジェクトが RTP パケットと RTCP パケットを送受信する際の DTLS(Datagram Transport Layer Security)トランスポートに関する情報へのアプリケーションのアクセスを可能にします。特に、DTLS は基礎となるトランスポートにセキュリティを追加します。{{RTCDtlsTransport}} インターフェースは、基礎となるトランスポートと追加されたセキュリティに関する情報へのアクセスを可能にします。{{RTCDtlsTransport}} オブジェクトは、{{RTCPeerConnection/setLocalDescription()}} と {{RTCPeerConnection/setRemoteDescription()}} の呼び出しの結果として構築されます。各 {{RTCDtlsTransport}} オブジェクトは、特定の {{RTCRtpTransceiver}} の RTP または RTCP {{RTCIceTransport/component}}、または [[RFC8843]] でネゴシエートされた {{RTCRtpTransceiver}} のグループの DTLS トランスポート層を表します。
{{RTCDtlsTransport}} は、{{RTCDtlsTransportState/"new"}} に初期化された [[\DtlsTransportState]] の内部スロットと、空のリストに初期化された [[\RemoteCertificates]] のスロットを持っています。
基礎となる DTLS トランスポートに、証明書の検証失敗や致命的な警告([[RFC5246]] セクション 7.2 参照)などのエラーが発生した場合、ユーザーエージェントは、以下のステップを実行するタスクをキューに入れなければならない(MUST)とされています。
transport を、状態の更新やエラー通知を受け取る {{RTCDtlsTransport}} オブジェクトとします。
transport の状態がすでに {{RTCDtlsTransportState/"failed"}} である場合、これらのステップを中止します。
transport.{{RTCDtlsTransport/[[DtlsTransportState]]}} を {{RTCDtlsTransportState/"failed"}} に設定します。
[= Fire an event = ] {{RTCDtlsTransport/error}} という名前のイベントを、{{RTCErrorEvent}} を使用して、その errorDetail 属性を {{RTCErrorDetailType/"dtls-failure"}} または {{RTCErrorDetailType/"fingerprint-failure"}} に設定し、その他のフィールドを {{RTCErrorDetailType} enum description で説明されているように設定して、transport に配置したインターフェース。
[= Fire an event =] named {{RTCDtlsTransport/statechange}} at transport.
基礎となるDTLSトランスポートが他の理由で対応する {{RTCDtlsTransport}} オブジェクトの状態を更新する必要がある場合、ユーザーエージェントは以下のステップを実行するタスクをキューに入れなければなりません(MUST):
Let transport be the {{RTCDtlsTransport}} object to receive the state update.
Let newState be the new state.
Set transport.{{RTCDtlsTransport/[[DtlsTransportState]]}} to newState.
If newState is {{RTCDtlsTransportState/connected}} then let newRemoteCertificates be the certificate chain in use by the remote side, with each certificate encoded in binary Distinguished Encoding Rules (DER) [[!X690]], and set transport.{{RTCDtlsTransport/[[RemoteCertificates]]}} to newRemoteCertificates.
[= Fire an event =] named {{RTCDtlsTransport/statechange}} at transport.
[Exposed=Window] interface RTCDtlsTransport : EventTarget { [SameObject] readonly attribute RTCIceTransport iceTransport; readonly attribute RTCDtlsTransportState state; sequence<ArrayBuffer> getRemoteCertificates(); attribute EventHandler onstatechange; attribute EventHandler onerror; };
The {{iceTransport}} attribute is the underlying transport that is used to send and receive packets. The underlying transport may not be shared between multiple active {{RTCDtlsTransport}} objects.
The {{state}} attribute MUST, on getting, return the value of the {{RTCDtlsTransport/[[DtlsTransportState]]}} slot.
Returns the value of {{RTCDtlsTransport/[[RemoteCertificates]]}}.
enum RTCDtlsTransportState { "new", "connecting", "connected", "closed", "failed" };
Enumeration description | |
---|---|
new | DTLS has not started negotiating yet. |
connecting | DTLS is in the process of negotiating a secure connection and verifying the remote fingerprint. |
connected | DTLS has completed negotiation of a secure connection and verified the remote fingerprint. |
closed | The transport has been closed intentionally as the result of receipt of a close_notify alert, or calling {{RTCPeerConnection/close()}}. |
failed | The transport has failed as the result of an error (such as receipt of an error alert or failure to validate the remote fingerprint). |
The {{RTCDtlsFingerprint}} dictionary includes the hash function algorithm and certificate fingerprint as described in [[!RFC4572]].
dictionary RTCDtlsFingerprint { DOMString algorithm; DOMString value; };
One of the the hash function algorithms defined in the 'Hash function Textual Names' registry [[!IANA-HASH-FUNCTION]].
The value of the certificate fingerprint in lowercase hex string as expressed utilizing the syntax of 'fingerprint' in [[!RFC4572]] Section 5.
The {{RTCIceTransport}} interface allows an application access to information about the ICE transport over which packets are sent and received. In particular, ICE manages peer-to-peer connections which involve state which the application may want to access. {{RTCIceTransport}} objects are constructed as a result of calls to {{RTCPeerConnection/setLocalDescription()}} and {{RTCPeerConnection/setRemoteDescription()}}. The underlying ICE state is managed by the ICE agent; as such, the state of an {{RTCIceTransport}} changes when the [= ICE Agent =] provides indications to the user agent as described below. Each {{RTCIceTransport}} object represents the ICE transport layer for the RTP or RTCP {{RTCIceTransport/component}} of a specific {{RTCRtpTransceiver}}, or a group of {{RTCRtpTransceiver}}s if such a group has been negotiated via [[RFC8843]].
When the [= ICE Agent =] indicates that it began gathering a [= generation =] of candidates for an {{RTCIceTransport}}, the user agent MUST queue a task that runs the following steps:
Let connection be the {{RTCPeerConnection}} object associated with this [= ICE Agent =].
If connection.{{RTCPeerConnection/[[IsClosed]]}} is
true
, abort these steps.
Let transport be the {{RTCIceTransport}} for which candidate gathering began.
Set transport.{{RTCIceTransport/[[IceGathererState]]}} to {{RTCIceGathererState/gathering}}.
[= Fire an event =] named {{RTCIceTransport/gatheringstatechange}} at transport.
Update the ICE gathering state of connection.
When the [= ICE Agent =] is finished gathering a [= generation =] of candidates for an {{RTCIceTransport}}, and those candidates have been surfaced to the application, the user agent MUST queue a task that runs the following steps:
Let connection be the {{RTCPeerConnection}} object associated with this [= ICE Agent =].
If connection.{{RTCPeerConnection/[[IsClosed]]}} is
true
, abort these steps.
Let transport be the {{RTCIceTransport}} for which candidate gathering finished.
Let newCandidate be the result of [= creating an RTCIceCandidate =] with a new dictionary whose {{RTCIceCandidateInit/sdpMid}} and {{RTCIceCandidateInit/sdpMLineIndex}} are set to the values associated with this {{RTCIceTransport}}, {{RTCIceCandidateInit/usernameFragment}} is set to the username fragment of the [= generation =] of candidates for which gathering finished, and {{RTCIceCandidateInit/candidate}} is set to an empty string.
[= Fire an event =] named {{RTCPeerConnection/icecandidate}} using the {{RTCPeerConnectionIceEvent}} interface with the candidate attribute set to newCandidate at connection.
If another [= generation =] of candidates is still being gathered, abort these steps.
Set transport.{{RTCIceTransport/[[IceGathererState]]}} to {{RTCIceGathererState/complete}}.
[= Fire an event =] named {{RTCIceTransport/gatheringstatechange}} at transport.
Update the ICE gathering state of connection.
When the [= ICE Agent =] indicates that a new ICE candidate is available for an {{RTCIceTransport}}, either by taking one from the [= ICE candidate pool size | ICE candidate pool =] or gathering it from scratch, the user agent MUST queue a task that runs the following steps:
Let candidate be the available ICE candidate.
Let connection be the {{RTCPeerConnection}} object associated with this [= ICE Agent =].
If connection.{{RTCPeerConnection/[[IsClosed]]}} is
true
, abort these steps.
If either
connection.{{RTCPeerConnection/[[PendingLocalDescription]]}} or
connection.{{RTCPeerConnection/[[CurrentLocalDescription]]}} are not
null
, and represent the ICE [= generation =] for
which candidate was gathered, [= surface the candidate
=] with candidate and connection, and abort
these steps.
Otherwise, append candidate to connection.{{RTCPeerConnection/[[EarlyCandidates]]}}.
When the [= ICE Agent =] signals that the ICE role has changed due to an ICE binding request with a role collision per [[RFC8445]] section 7.3.1.1, the UA will queue a task to set the value of {{RTCIceTransport/[[IceRole]]}} to the new value.
To release early candidates of a connection, run the following steps:
For each candidate, candidate, in connection.{{RTCPeerConnection/[[EarlyCandidates]]}}, queue a task to [= surface the candidate =] with candidate and connection.
Set connection.{{RTCPeerConnection/[[EarlyCandidates]]}} to an empty list.
To surface a candidate with candidate and connection, run the following steps:
If connection.{{RTCPeerConnection/[[IsClosed]]}} is
true
, abort these steps.
Let transport be the {{RTCIceTransport}} for which candidate is being made available.
If connection.{{RTCPeerConnection/[[PendingLocalDescription]]}} is
not null
, and represents the ICE [= generation =]
for which candidate was gathered, add
candidate to
connection.{{RTCPeerConnection/[[PendingLocalDescription]]}}.sdp.
If connection.{{RTCPeerConnection/[[CurrentLocalDescription]]}} is
not null
, and represents the ICE [= generation =]
for which candidate was gathered, add
candidate to
connection.{{RTCPeerConnection/[[CurrentLocalDescription]]}}.sdp.
Let newCandidate be the result of [= creating an RTCIceCandidate =] with a new dictionary whose {{RTCIceCandidateInit/sdpMid}} and {{RTCIceCandidateInit/sdpMLineIndex}} are set to the values associated with this {{RTCIceTransport}}, {{RTCIceCandidateInit/usernameFragment}} is set to the username fragment of the candidate, and {{RTCIceCandidateInit/candidate}} is set to a string encoded using the [= candidate-attribute =] grammar to represent candidate.
Add newCandidate to transport's set of local candidates.
[= Fire an event =] named {{RTCPeerConnection/icecandidate}} using the {{RTCPeerConnectionIceEvent}} interface with the candidate attribute set to newCandidate at connection.
The {{RTCIceTransportState}} of an {{RTCIceTransport}} may change because a candidate pair with a usable connection was found and selected or it may change without the selected candidate pair changing. The selected pair and {{RTCIceTransportState}} are related and are handled in the same task.
When the [= ICE Agent =] indicates that an {{RTCIceTransport}} has changed either the selected candidate pair, the {{RTCIceTransportState}} or both, the user agent MUST queue a task that runs the following steps:
Let connection be the {{RTCPeerConnection}} object associated with this [= ICE Agent =].
If connection.{{RTCPeerConnection/[[IsClosed]]}} is
true
, abort these steps.
Let transport be the {{RTCIceTransport}} whose state is changing.
Let selectedCandidatePairChanged be
false
.
Let transportIceConnectionStateChanged be
false
.
Let connectionIceConnectionStateChanged be
false
.
Let connectionStateChanged be false
.
If transport's selected candidate pair was changed, run the following steps:
Let newCandidatePair be a newly created
{{RTCIceCandidatePair}} representing the indicated pair if
one is selected, and null
otherwise.
Set transport.{{RTCIceTransport/[[SelectedCandidatePair]]}} to newCandidatePair.
Set selectedCandidatePairChanged to
true
.
If transport's {{RTCIceTransportState}} was changed, run the following steps:
Set transport.{{RTCIceTransport/[[IceTransportState]]}} to the new indicated {{RTCIceTransportState}}.
Set transportIceConnectionStateChanged to
true
.
Set connection's [= ICE connection state =] to the value of deriving a new state value as described by the {{RTCIceConnectionState}} enum.
If the ice connection state changed in the previous
step, set connectionIceConnectionStateChanged to
true
.
Set connection's [= connection state =] to the value of deriving a new state value as described by the {{RTCPeerConnectionState}} enum.
If the [= connection state =] changed in the previous step,
set connectionStateChanged to true
.
If selectedCandidatePairChanged is true
,
[= fire an event =] named {{RTCIceTransport/selectedcandidatepairchange}} at
transport.
If transportIceConnectionStateChanged is
true
, [= fire an event =] named {{RTCIceTransport/statechange}} at
transport.
If connectionIceConnectionStateChanged is
true
, [= fire an event =] named
{{RTCPeerConnection/iceconnectionstatechange}} at connection.
If connectionStateChanged is true
, [=
fire an event =] named {{RTCPeerConnection/connectionstatechange}} at
connection.
An {{RTCIceTransport}} object has the following internal slots:
null
[Exposed=Window] interface RTCIceTransport : EventTarget { readonly attribute RTCIceRole role; readonly attribute RTCIceComponent component; readonly attribute RTCIceTransportState state; readonly attribute RTCIceGathererState gatheringState; sequence<RTCIceCandidate> getLocalCandidates(); sequence<RTCIceCandidate> getRemoteCandidates(); RTCIceCandidatePair? getSelectedCandidatePair(); RTCIceParameters? getLocalParameters(); RTCIceParameters? getRemoteParameters(); attribute EventHandler onstatechange; attribute EventHandler ongatheringstatechange; attribute EventHandler onselectedcandidatepairchange; };
The {{role}} attribute MUST, on getting, return the value of the [[\IceRole]] internal slot.
The {{component}} attribute MUST return the ICE component of the transport. When RTCP mux is used, a single {{RTCIceTransport}} transports both RTP and RTCP and {{component}} is set to {{RTCIceComponent/"rtp"}}.
The {{state}} attribute MUST, on getting, return the value of the {{RTCIceTransport/[[IceTransportState]]}} slot.
The {{gatheringState}} attribute MUST, on getting, return the value of the {{RTCIceTransport/[[IceGathererState]]}} slot.
Returns a sequence describing the local ICE candidates gathered for this {{RTCIceTransport}} and sent in {{RTCPeerConnection/onicecandidate}}.
Returns a sequence describing the remote ICE candidates received by this {{RTCIceTransport}} via {{RTCPeerConnection/addIceCandidate()}}.
Returns the selected candidate pair on which packets are
sent. This method MUST return the value of the
{{RTCIceTransport/[[SelectedCandidatePair]]}} slot. When
{{RTCIceTransport}}.{{RTCIceTransport/state}} is
{{RTCIceTransportState/"new"}} or
{{RTCIceTransportState/"closed"}}
{{getSelectedCandidatePair}} returns null
.
Returns the local ICE parameters received by this
{{RTCIceTransport}} via
{{RTCPeerConnection/setLocalDescription}}, or
null
if the parameters have not yet been
received.
Returns the remote ICE parameters received by this
{{RTCIceTransport}} via
{{RTCPeerConnection/setRemoteDescription}} or
null
if the parameters have not yet been
received.
dictionary RTCIceParameters { DOMString usernameFragment; DOMString password; };
The ICE username fragment as defined in [[RFC5245]], Section 7.1.2.3.
The ICE password as defined in [[RFC5245]], Section 7.1.2.3.
dictionary RTCIceCandidatePair { RTCIceCandidate local; RTCIceCandidate remote; };
The local ICE candidate.
The remote ICE candidate.
enum RTCIceGathererState { "new", "gathering", "complete" };
{{RTCIceGathererState}} Enumeration description | |
---|---|
new | The {{RTCIceTransport}} was just created, and has not started gathering candidates yet. |
gathering | The {{RTCIceTransport}} is in the process of gathering candidates. |
complete | The {{RTCIceTransport}} has completed gathering and the end-of-candidates indication for this transport has been sent. It will not gather candidates again until an ICE restart causes it to restart. |
enum RTCIceTransportState { "new", "checking", "connected", "completed", "disconnected", "failed", "closed" };
{{RTCIceTransportState}} Enumeration description | |
---|---|
new | The {{RTCIceTransport}} is gathering candidates and/or waiting for remote candidates to be supplied, and has not yet started checking. |
checking | The {{RTCIceTransport}} has received at least one remote candidate and is checking candidate pairs and has either not yet found a connection or consent checks [[!RFC7675]] have failed on all previously successful candidate pairs. In addition to checking, it may also still be gathering. |
connected | The {{RTCIceTransport}} has found a usable connection, but is still checking other candidate pairs to see if there is a better connection. It may also still be gathering and/or waiting for additional remote candidates. If consent checks [[!RFC7675]] fail on the connection in use, and there are no other successful candidate pairs available, then the state transitions to {{RTCIceTransportState/"checking"}} (if there are candidate pairs remaining to be checked) or {{RTCIceTransportState/"disconnected"}} (if there are no candidate pairs to check, but the peer is still gathering and/or waiting for additional remote candidates). |
completed | The {{RTCIceTransport}} has finished gathering, received an indication that there are no more remote candidates, finished checking all candidate pairs and found a connection. If consent checks [[!RFC7675]] subsequently fail on all successful candidate pairs, the state transitions to {{RTCIceTransportState/"failed"}}. |
disconnected |
The [= ICE Agent =] has determined that connectivity is
currently lost for this {{RTCIceTransport}}. This is a
transient state that may trigger intermittently (and
resolve itself without action) on a flaky network. The way
this state is determined is implementation dependent.
Examples include:
|
failed | The {{RTCIceTransport}} has finished gathering, received an indication that there are no more remote candidates, finished checking all candidate pairs, and all pairs have either failed connectivity checks or have lost consent. This is a terminal state until ICE is restarted. Since an ICE restart may cause connectivity to resume, entering the {{RTCIceTransportState/"failed"}} state does not cause DTLS transports, SCTP associations or the data channels that run over them to close, or tracks to mute. |
closed | The {{RTCIceTransport}} has shut down and is no longer responding to STUN requests. |
The most common transitions for a successful call will be new -> checking -> connected -> completed, but under specific circumstances (only the last checked candidate succeeds, and gathering and the no-more candidates indication both occur prior to success), the state can transition directly from {{RTCIceTransportState/"checking"}} to {{RTCIceTransportState/"completed"}}.
An ICE restart causes candidate gathering and connectivity checks to begin anew, causing a transition to {{RTCIceTransportState/"connected"}} if begun in the {{RTCIceTransportState/"completed"}} state. If begun in the transient {{RTCIceTransportState/"disconnected"}} state, it causes a transition to {{RTCIceTransportState/"checking"}}, effectively forgetting that connectivity was previously lost.
The {{RTCIceTransportState/"failed"}} and
{{RTCIceTransportState/"completed"}} states require an indication
that there are no additional remote candidates. This can be
indicated by calling {{RTCPeerConnection/addIceCandidate}} with a
candidate value whose {{RTCIceCandidate/candidate}} property is set
to an empty string or by
{{RTCPeerConnection/canTrickleIceCandidates}} being set to
false
.
Some example state transitions are:
enum RTCIceRole { "unknown", "controlling", "controlled" };
{{RTCIceRole}} Enumeration description | |
---|---|
unknown | An agent whose role as defined by [[RFC5245]], Section 3, has not yet been determined. |
controlling | A controlling agent as defined by [[RFC5245]], Section 3. |
controlled | A controlled agent as defined by [[RFC5245]], Section 3. |
enum RTCIceComponent { "rtp", "rtcp" };
{{RTCIceComponent}} Enumeration description | |
---|---|
rtp |
The ICE Transport is used for RTP (or RTCP multiplexing),
as defined in [[RFC5245]], Section 4.1.1.1. Protocols
multiplexed with RTP (e.g. data channel) share its
component ID. This represents the component-id value 1 when encoded
in [= candidate-attribute =].
|
rtcp |
The ICE Transport is used for RTCP as defined by [[RFC5245]],
Section 4.1.1.1. This represents the component-id value 2 when encoded
in [= candidate-attribute =].
|
The {{RTCPeerConnection/track}} event uses the {{RTCTrackEvent}} interface.
[Exposed=Window] interface RTCTrackEvent : Event { constructor(DOMString type, RTCTrackEventInit eventInitDict); readonly attribute RTCRtpReceiver receiver; readonly attribute MediaStreamTrack track; [SameObject] readonly attribute FrozenArray<MediaStream> streams; readonly attribute RTCRtpTransceiver transceiver; };
The {{receiver}} attribute represents the {{RTCRtpReceiver}} object associated with the event.
The {{track}} attribute represents the {{MediaStreamTrack}} object that is associated with the {{RTCRtpReceiver}} identified by {{receiver}}.
The {{streams}} attribute returns an array of {{MediaStream}} objects representing the {{MediaStream}}s that this event's {{track}} is a part of.
The {{transceiver}} attribute represents the {{RTCRtpTransceiver}} object associated with the event.
dictionary RTCTrackEventInit : EventInit { required RTCRtpReceiver receiver; required MediaStreamTrack track; sequence<MediaStream> streams = []; required RTCRtpTransceiver transceiver; };
The {{receiver}} member represents the {{RTCRtpReceiver}} object associated with the event.
The {{track}} member represents the {{MediaStreamTrack}} object that is associated with the {{RTCRtpReceiver}} identified by {{RTCTrackEventInit/receiver}}.
[]
The {{streams}} member is an array of {{MediaStream}} objects representing the {{MediaStream}}s that this event's {{track}} is a part of.
The {{transceiver}} attribute represents the {{RTCRtpTransceiver}} object associated with the event.
The Peer-to-peer Data API lets a web application send and receive generic application data peer-to-peer. The API for sending and receiving data models the behavior of Web Sockets.
The Peer-to-peer data API extends the {{RTCPeerConnection}} interface as described below.
partial interface RTCPeerConnection { readonly attribute RTCSctpTransport? sctp; RTCDataChannel createDataChannel(USVString label, optional RTCDataChannelInit dataChannelDict = {}); attribute EventHandler ondatachannel; };
The SCTP transport over which SCTP data is sent and received. If SCTP has not been negotiated, the value is null. This attribute MUST return the {{RTCSctpTransport}} object stored in the {{RTCPeerConnection/[[SctpTransport]]}} internal slot.
Creates a new {{RTCDataChannel}} object with the given label. The {{RTCDataChannelInit}} dictionary can be used to configure properties of the underlying channel such as data reliability.
When the {{createDataChannel}} method is invoked, the user agent MUST run the following steps.
Let connection be the {{RTCPeerConnection}} object on which the method is invoked.
If connection.{{RTCPeerConnection/[[IsClosed]]}} is
true
, [= exception/throw =] an
{{InvalidStateError}}.
[= Create an RTCDataChannel =], channel.
Initialize channel.{{RTCDataChannel/[[DataChannelLabel]]}} to the value of the first argument.
If the UTF-8 representation of {{RTCDataChannel/[[DataChannelLabel]]}} is longer than 65535 bytes, [= exception/throw =] a {{TypeError}}.
Let options be the second argument.
Initialize
channel.{{RTCDataChannel/[[MaxPacketLifeTime]]}} to
option.{{RTCDataChannelInit/maxPacketLifeTime}},
if present, otherwise null
.
Initialize channel.{{RTCDataChannel/[[MaxRetransmits]]}}
to
option.{{RTCDataChannelInit/maxRetransmits}},
if present, otherwise null
.
Initialize channel.{{RTCDataChannel/[[Ordered]]}} to option.{{RTCDataChannelInit/ordered}}.
Initialize channel.{{RTCDataChannel/[[DataChannelProtocol]]}} to option.{{RTCDataChannelInit/protocol}}.
If the UTF-8 representation of {{RTCDataChannel/[[DataChannelProtocol]]}} is longer than 65535 bytes, [= exception/throw =] a {{TypeError}}.
Initialize channel.{{RTCDataChannel/[[Negotiated]]}} to option.{{RTCDataChannelInit/negotiated}}.
Initialize channel.{{RTCDataChannel/[[DataChannelId]]}}
to the value of
option.{{RTCDataChannelInit/id}}, if it is
present and {{RTCDataChannel/[[Negotiated]]}} is true, otherwise
null
.
If {{RTCDataChannel/[[Negotiated]]}} is true
and
{{RTCDataChannel/[[DataChannelId]]}} is null
, [=
exception/throw =] a {{TypeError}}.
If both {{RTCDataChannel/[[MaxPacketLifeTime]]}} and {{RTCDataChannel/[[MaxRetransmits]]}} attributes are set (not null), [= exception/throw =] a {{TypeError}}.
If a setting, either {{RTCDataChannel/[[MaxPacketLifeTime]]}} or {{RTCDataChannel/[[MaxRetransmits]]}}, has been set to indicate unreliable mode, and that value exceeds the maximum value supported by the user agent, the value MUST be set to the user agents maximum value.
If {{RTCDataChannel/[[DataChannelId]]}} is equal to 65535, which is greater than the maximum allowed ID of 65534 but still qualifies as an unsigned short, [= exception/throw =] a {{TypeError}}.
If the {{RTCDataChannel/[[DataChannelId]]}} slot is
null
(due to no ID being passed into
{{createDataChannel}}, or {{RTCDataChannel/[[Negotiated]]}} being
false), and the DTLS role of the SCTP transport has
already been negotiated, then initialize
{{RTCDataChannel/[[DataChannelId]]}} to a value generated by the
user agent, according to [[RFC8832]], and
skip to the next step. If no available ID could be
generated, or if the value of the
{{RTCDataChannel/[[DataChannelId]]}} slot is being used by an
existing {{RTCDataChannel}}, [= exception/throw =] an
{{OperationError}} exception.
null
after this step, it will be populated
during the [= RTCSctpTransport connected =] procedure.
Let transport be connection.{{RTCPeerConnection/[[SctpTransport]]}}.
If the {{RTCDataChannel/[[DataChannelId]]}} slot is not
null
, transport is in the
{{RTCSctpTransportState/"connected"}} state and
{{RTCDataChannel/[[DataChannelId]]}} is greater or equal to
transport.{{RTCSctpTransport/[[MaxChannels]]}}, [=
exception/throw =] an {{OperationError}}.
If channel is the first {{RTCDataChannel}} created on connection, [= update the negotiation-needed flag =] for connection.
Return channel and continue the following steps in parallel.
Create channel's associated [= underlying data transport =] and configure it according to the relevant properties of channel.
The {{RTCSctpTransport}} interface allows an application access to information about the SCTP data channels tied to a particular SCTP association.
To create an {{RTCSctpTransport}} with an initial state, initialState, run the following steps:
Let transport be a new {{RTCSctpTransport}} object.
Let transport have a [[\SctpTransportState]] internal slot initialized to initialState.
Let transport have a [[\MaxMessageSize]] internal slot and run the steps labeled [= update the data max message size =] to initialize it.
Let transport have a [[\MaxChannels]]
internal slot initialized to null
.
Return transport.
To update the data max message size of an {{RTCSctpTransport}} run the following steps:
Let transport be the {{RTCSctpTransport}} object to be updated.
Let remoteMaxMessageSize be the value of the
max-message-size
SDP attribute read
from the remote description, as described in [[RFC8841]]
(section 6), or 65536 if the attribute is missing.
Let canSendSize be the number of bytes that this client can send (i.e. the size of the local send buffer) or 0 if the implementation can handle messages of any size.
If both remoteMaxMessageSize and canSendSize are 0, set {{RTCSctpTransport/[[MaxMessageSize]]}} to the positive Infinity value.
Else, if either remoteMaxMessageSize or canSendSize is 0, set {{RTCSctpTransport/[[MaxMessageSize]]}} to the larger of the two.
Else, set {{RTCSctpTransport/[[MaxMessageSize]]}} to the smaller of remoteMaxMessageSize or canSendSize.
Once an SCTP transport is connected, meaning the SCTP association of an {{ RTCSctpTransport}} has been established, run the following steps:
Let transport be the {{RTCSctpTransport}} object.
Let connection be the {{RTCPeerConnection}} object associated with transport.
Set {{RTCSctpTransport/[[MaxChannels]]}} to the minimum of the negotiated amount of incoming and outgoing SCTP streams.
For each of connection's {{RTCDataChannel}}:
Let channel be the {{RTCDataChannel}} object.
If channel.{{RTCDataChannel/[[DataChannelId]]}} is
null
, initialize {{RTCDataChannel/[[DataChannelId]]}}
to the value generated by the underlying sctp data
channel, according to [[RFC8832]].
If channel.{{RTCDataChannel/[[DataChannelId]]}} is greater or equal to transport.{{RTCSctpTransport/[[MaxChannels]]}}, or the previous step failed to assign an id, [= unable to create an RTCDataChannel | close =] the channel due to a failure. Otherwise, [= announce the rtcdatachannel as open | announce the channel as open =].
[= Fire an event =] named {{RTCSctpTransport/statechange}} at transport.
This event is fired before the {{RTCDataChannel/open}} events fired by [= announce the rtcdatachannel as open | announcing the channel as open =]; the {{RTCDataChannel/open}} events are fired from a queued task.
[Exposed=Window] interface RTCSctpTransport : EventTarget { readonly attribute RTCDtlsTransport transport; readonly attribute RTCSctpTransportState state; readonly attribute unrestricted double maxMessageSize; readonly attribute unsigned short? maxChannels; attribute EventHandler onstatechange; };
The transport over which all SCTP packets for data channels will be sent and received.
The current state of the SCTP transport. On getting, this attribute MUST return the value of the {{RTCSctpTransport/[[SctpTransportState]]}} slot.
The maximum size of data that can be passed to {{RTCDataChannel}}'s {{RTCDataChannel/send()}} method. The attribute MUST, on getting, return the value of the {{RTCSctpTransport/[[MaxMessageSize]]}} slot.
The maximum amount of {{RTCDataChannel}}'s that can be used simultaneously. The attribute MUST, on getting, return the value of the {{RTCSctpTransport/[[MaxChannels]]}} slot.
null
until the
SCTP transport goes into the
{{RTCSctpTransportState/"connected"}} state.
The event type of this event handler is {{RTCSctpTransport/statechange}}.
{{RTCSctpTransportState}} indicates the state of the SCTP transport.
enum RTCSctpTransportState { "connecting", "connected", "closed" };
Enumeration description | |
---|---|
connecting |
The {{RTCSctpTransport}} is in the process of negotiating an association. This is the initial state of the [[\SctpTransportState]] slot when an {{RTCSctpTransport}} is created. |
connected |
When the negotiation of an association is completed, a task is queued to update the [[\SctpTransportState]] slot to {{RTCSctpTransportState/"connected"}}. |
closed |
A task is queued to update the [[\SctpTransportState]] slot to {{RTCSctpTransportState/"closed"}} when:
Note that the last transition is logical due to the fact that an SCTP association requires an established DTLS connection - [[RFC8261]] section 6.1 specifies that SCTP over DTLS is single-homed - and that no way of of switching to an alternate transport is defined in this API. |
The {{RTCDataChannel}} interface represents a bi-directional data channel between two peers. An {{RTCDataChannel}} is created via a factory method on an {{RTCPeerConnection}} object. The messages sent between the browsers are described in [[RFC8831]] and [[RFC8832]].
There are two ways to establish a connection with {{RTCDataChannel}}. The first way is to simply create an {{RTCDataChannel}} at one of the peers with the {{RTCDataChannelInit/negotiated}} {{RTCDataChannelInit}} dictionary member unset or set to its default value false. This will announce the new channel in-band and trigger an {{RTCDataChannelEvent}} with the corresponding {{RTCDataChannel}} object at the other peer. The second way is to let the application negotiate the {{RTCDataChannel}}. To do this, create an {{RTCDataChannel}} object with the {{RTCDataChannelInit/negotiated}} {{RTCDataChannelInit}} dictionary member set to true, and signal out-of-band (e.g. via a web server) to the other side that it SHOULD create a corresponding {{RTCDataChannel}} with the {{RTCDataChannelInit/negotiated}} {{RTCDataChannelInit}} dictionary member set to true and the same {{RTCDataChannel/id}}. This will connect the two separately created {{RTCDataChannel}} objects. The second way makes it possible to create channels with asymmetric properties and to create channels in a declarative way by specifying matching {{RTCDataChannelInit/id}}s.
Each {{RTCDataChannel}} has an associated underlying data transport that is used to transport actual data to the other peer. In the case of SCTP data channels utilizing an {{RTCSctpTransport}} (which represents the state of the SCTP association), the underlying data transport is the SCTP stream pair. The transport properties of the [= underlying data transport =], such as in order delivery settings and reliability mode, are configured by the peer as the channel is created. The properties of a channel cannot change after the channel has been created. The actual wire protocol between the peers is specified by the WebRTC DataChannel Protocol specification [[RFC8831]].
An {{RTCDataChannel}} can be configured to operate in different reliability modes. A reliable channel ensures that the data is delivered at the other peer through retransmissions. An unreliable channel is configured to either limit the number of retransmissions ( {{RTCDataChannelInit/maxRetransmits}} ) or set a time during which transmissions (including retransmissions) are allowed ( {{RTCDataChannelInit/maxPacketLifeTime}} ). These properties can not be used simultaneously and an attempt to do so will result in an error. Not setting any of these properties results in a reliable channel.
An {{RTCDataChannel}}, created with {{RTCPeerConnection/createDataChannel}} or dispatched via an {{RTCDataChannelEvent}}, MUST initially be in the {{RTCDataChannelState/"connecting"}} state. When the {{RTCDataChannel}} object's [= underlying data transport =] is ready, the user agent MUST [= announce the RTCDataChannel as open =].
To create an {{RTCDataChannel}}, run the following steps:
Let channel be a newly created {{RTCDataChannel}} object.
Let channel have a [[\ReadyState]] internal slot initialized to {{RTCDataChannelState/"connecting"}}.
Let channel have a [[\BufferedAmount]]
internal slot initialized to 0
.
Let channel have internal slots named [[\DataChannelLabel]], [[\Ordered]], [[\MaxPacketLifeTime]], [[\MaxRetransmits]], [[\DataChannelProtocol]], [[\Negotiated]], and [[\DataChannelId]].
Return channel.
When the user agent is to announce an {{RTCDataChannel}} as open, the user agent MUST queue a task to run the following steps:
If the associated {{RTCPeerConnection}} object's
{{RTCPeerConnection/[[IsClosed]]}} slot is true
, abort these
steps.
Let channel be the {{RTCDataChannel}} object to be announced.
If channel.{{RTCDataChannel/[[ReadyState]]}} is {{RTCDataChannelState/"closing"}} or {{RTCDataChannelState/"closed"}}, abort these steps.
Set channel.{{RTCDataChannel/[[ReadyState]]}} to {{RTCDataChannelState/"open"}}.
[= Fire an event =] named {{RTCDataChannel/open}} at channel.
When an [= underlying data transport =] is to be announced (the other peer created a channel with {{RTCDataChannelInit/negotiated}} unset or set to false), the user agent of the peer that did not initiate the creation process MUST queue a task to run the following steps:
Let connection be the {{RTCPeerConnection}} object associated with the [= underlying data transport =].
If connection.{{RTCPeerConnection/[[IsClosed]]}} is
true
, abort these steps.
[= Create an RTCDataChannel =], channel.
Let configuration be an information bundle received from the other peer as a part of the process to establish the [= underlying data transport =] described by the WebRTC DataChannel Protocol specification [[RFC8832]].
Initialize channel.{{RTCDataChannel/[[DataChannelLabel]]}}, {{RTCDataChannel/[[Ordered]]}}, {{RTCDataChannel/[[MaxPacketLifeTime]]}}, {{RTCDataChannel/[[MaxRetransmits]]}}, {{RTCDataChannel/[[DataChannelProtocol]]}}, and {{RTCDataChannel/[[DataChannelId]]}} internal slots to the corresponding values in configuration.
Initialize channel.{{RTCDataChannel/[[Negotiated]]}} to
false
.
Set channel.{{RTCDataChannel/[[ReadyState]]}} to {{RTCDataChannelState/"open"}} (but do not fire the {{RTCDataChannel/open}} event, yet).
[= Fire an event =] named {{RTCPeerConnection/datachannel}} using the {{RTCDataChannelEvent}} interface with the {{RTCDataChannelEvent/channel}} attribute set to channel at connection.
[= announce the rtcdatachannel as open | Announce the data channel as open =].
An {{RTCDataChannel}} object's [= underlying data transport =] may be torn down in a non-abrupt manner by running the closing procedure. When that happens the user agent MUST queue a task to run the following steps:
Let channel be the {{RTCDataChannel}} object whose [= underlying data transport =] was closed.
Unless the procedure was initiated by channel.{{RTCDataChannel/close}}, set channel.{{RTCDataChannel/[[ReadyState]]}} to {{RTCDataChannelState/"closing"}} and [= fire an event =] named {{RTCDataChannel/closing}} at channel.
Run the following steps in parallel:
Finish sending all currently pending messages of the channel.
Follow the closing procedure defined for the channel's [= underlying data transport =] :
In the case of an SCTP-based [= underlying data transport | transport =], follow [[RFC8831]], section 6.7.
Render the channel's [= data transport =] [=closed=] by following the associated procedure.
When an {{RTCDataChannel}} object's [= underlying data transport =] has been closed, the user agent MUST queue a task to run the following steps:
Let channel be the {{RTCDataChannel}} object whose [= underlying data transport =] was closed.
Set channel.{{RTCDataChannel/[[ReadyState]]}} to {{RTCDataChannelState/"closed"}}.
If the [= underlying data transport | transport =] was closed with an error, [= fire an event =] named {{RTCDataChannel/error}} using the {{RTCErrorEvent}} interface with its {{RTCError/errorDetail}} attribute set to {{RTCErrorDetailType/"sctp-failure"}} at channel.
[= Fire an event =] named close at channel.
In some cases, the user agent may be unable to create an {{RTCDataChannel}} 's [= underlying data transport =]. For example, the data channel's {{RTCDataChannel/id}} may be outside the range negotiated by the [[RFC8831]] implementations in the SCTP handshake. When the user agent determines that an {{RTCDataChannel}}'s [= underlying data transport =] cannot be created, the user agent MUST queue a task to run the following steps:
Let channel be the {{RTCDataChannel}} object for which the user agent could not create an [= underlying data transport =].
Set channel.{{RTCDataChannel/[[ReadyState]]}} to {{RTCDataChannelState/"closed"}}.
[= Fire an event =] named {{RTCDataChannel/error}} using the {{RTCErrorEvent}} interface with the {{RTCError/errorDetail}} attribute set to {{RTCErrorDetailType/"data-channel-failure"}} at channel.
[= Fire an event =] named close at channel.
When an {{RTCDataChannel}} message has been received via the [= underlying data transport =] with type type and data rawData, the user agent MUST queue a task to run the following steps:
Let channel be the {{RTCDataChannel}} object for which the user agent has received a message.
Let connection be the {{RTCPeerConnection}} object associated with channel.
If channel.{{RTCDataChannel/[[ReadyState]]}} is not {{RTCDataChannelState/"open"}}, abort these steps and discard rawData.
Execute the sub step by switching on type and channel.{{RTCDataChannel/binaryType}}:
If type indicates that rawData is a
string
:
Let data be a DOMString that represents the result of decoding rawData as UTF-8.
If type indicates that rawData is
binary and {{RTCDataChannel/binaryType}} is "blob"
:
Let data be a new {{Blob}} object containing rawData as its raw data source.
If type indicates that rawData is
binary and {{RTCDataChannel/binaryType}} is "arraybuffer"
:
Let data be a new {{ArrayBuffer}} object containing rawData as its raw data source.
[= Fire an event =] named {{RTCDataChannel/message}} using the
{{MessageEvent}} interface with its origin
attribute initialized to the
serialization of an origin of
connection.{{RTCPeerConnection/[[DocumentOrigin]]}}, and the
data
attribute initialized to
data at channel.
[Exposed=Window] interface RTCDataChannel : EventTarget { readonly attribute USVString label; readonly attribute boolean ordered; readonly attribute unsigned short? maxPacketLifeTime; readonly attribute unsigned short? maxRetransmits; readonly attribute USVString protocol; readonly attribute boolean negotiated; readonly attribute unsigned short? id; readonly attribute RTCDataChannelState readyState; readonly attribute unsigned long bufferedAmount; [EnforceRange] attribute unsigned long bufferedAmountLowThreshold; attribute EventHandler onopen; attribute EventHandler onbufferedamountlow; attribute EventHandler onerror; attribute EventHandler onclosing; attribute EventHandler onclose; undefined close(); attribute EventHandler onmessage; attribute BinaryType binaryType; undefined send(USVString data); undefined send(Blob data); undefined send(ArrayBuffer data); undefined send(ArrayBufferView data); };
The {{label}} attribute represents a label that can be used to distinguish this {{RTCDataChannel}} object from other {{RTCDataChannel}} objects. Scripts are allowed to create multiple {{RTCDataChannel}} objects with the same label. On getting, the attribute MUST return the value of the {{RTCDataChannel/[[DataChannelLabel]]}} slot.
The {{ordered}} attribute returns true if the {{RTCDataChannel}} is ordered, and false if out of order delivery is allowed. On getting, the attribute MUST return the value of the {{RTCDataChannel/[[Ordered]]}} slot.
The {{maxPacketLifeTime}} attribute returns the length of the time window (in milliseconds) during which transmissions and retransmissions may occur in unreliable mode. On getting, the attribute MUST return the value of the {{RTCDataChannel/[[MaxPacketLifeTime]]}} slot.
The {{maxRetransmits}} attribute returns the maximum number of retransmissions that are attempted in unreliable mode. On getting, the attribute MUST return the value of the {{RTCDataChannel/[[MaxRetransmits]]}} slot.
The {{protocol}} attribute returns the name of the sub-protocol used with this {{RTCDataChannel}}. On getting, the attribute MUST return the value of the {{RTCDataChannel/[[DataChannelProtocol]]}} slot.
The {{negotiated}} attribute returns true if this {{RTCDataChannel}} was negotiated by the application, or false otherwise. On getting, the attribute MUST return the value of the {{RTCDataChannel/[[Negotiated]]}} slot.
The {{id}} attribute returns the ID for this {{RTCDataChannel}}. The value is initially null, which is what will be returned if the ID was not provided at channel creation time, and the DTLS role of the SCTP transport has not yet been negotiated. Otherwise, it will return the ID that was either selected by the script or generated by the user agent according to [[RFC8832]]. After the ID is set to a non-null value, it will not change. On getting, the attribute MUST return the value of the {{RTCDataChannel/[[DataChannelId]]}} slot.
The {{readyState}} attribute represents the state of the {{RTCDataChannel}} object. On getting, the attribute MUST return the value of the {{RTCDataChannel/[[ReadyState]]}} slot.
The {{bufferedAmount}} attribute MUST, on getting, return the value of the {{RTCDataChannel/[[BufferedAmount]]}} slot. The attribute exposes the number of bytes of application data (UTF-8 text and binary data) that have been queued using {{RTCDataChannel/send()}}. Even though the data transmission can occur in parallel, the returned value MUST NOT be decreased before the current task yielded back to the event loop to prevent race conditions. The value does not include framing overhead incurred by the protocol, or buffering done by the operating system or network hardware. The value of the {{RTCDataChannel/[[BufferedAmount]]}} slot will only increase with each call to the {{RTCDataChannel/send()}} method as long as the {{RTCDataChannel/[[ReadyState]]}} slot is {{RTCDataChannelState/"open"}}; however, the slot does not reset to zero once the channel closes. When the [= underlying data transport =] sends data from its queue, the user agent MUST queue a task that reduces {{RTCDataChannel/[[BufferedAmount]]}} with the number of bytes that was sent.
The {{bufferedAmountLowThreshold}} attribute sets the threshold at which the {{RTCDataChannel/bufferedAmount}} is considered to be low. When the {{RTCDataChannel/bufferedAmount}} decreases from above this threshold to equal or below it, the {{bufferedamountlow}} event fires. The {{RTCDataChannel/bufferedAmountLowThreshold}} is initially zero on each new {{RTCDataChannel}}, but the application may change its value at any time.
The event type of this event handler is {{RTCErrorEvent}}. {{RTCError/errorDetail}} contains "sctp-failure", {{RTCError/sctpCauseCode}} contains the SCTP Cause Code value, and {{DOMException/message}} contains the SCTP Cause-Specific-Information, possibly with additional text.
The event type of this event handler is {{RTCDataChannel/closing}}.
The event type of this event handler is close.
The event type of this event handler is {{RTCDataChannel/message}}.
The {{binaryType}} attribute MUST, on getting, return the
value to which it was last set. On setting, if the new value
is either the string "blob"
or the
string "arraybuffer"
, then set the
IDL attribute to this new value. Otherwise, [=
exception/throw =] a {{SyntaxError}}. When an
{{RTCDataChannel}} object is created, the
{{RTCDataChannel/binaryType}} attribute MUST be initialized
to the string "blob"
.
This attribute controls how binary data is exposed to scripts. See Web Socket's {{WebSocket/binaryType}}.
Closes the {{RTCDataChannel}}. It may be called regardless of whether the {{RTCDataChannel}} object was created by this peer or the remote peer.
When the {{close}} method is called, the user agent MUST run the following steps:
Let channel be the {{RTCDataChannel}} object which is about to be closed.
If channel.{{RTCDataChannel/[[ReadyState]]}} is {{RTCDataChannelState/"closing"}} or {{RTCDataChannelState/"closed"}}, then abort these steps.
Set channel.{{RTCDataChannel/[[ReadyState]]}} to {{RTCDataChannelState/"closing"}}.
If the [= closing procedure =] has not started yet, start it.
Run the steps described by the [= send() algorithm =] with
argument type string
object.
Run the steps described by the [= send() algorithm =] with argument type {{Blob}} object.
Run the steps described by the [= send() algorithm =] with argument type {{ArrayBuffer}} object.
Run the steps described by the [= send() algorithm =] with argument type {{ArrayBufferView}} object.
The send()
method is overloaded to
handle different data argument types. When any version of the
method is called, the user agent MUST run the following
steps:
Let channel be the {{RTCDataChannel}} object on which data is to be sent.
If channel.{{RTCDataChannel/[[ReadyState]]}} is not {{RTCDataChannelState/"open"}}, [= exception/throw =] an {{InvalidStateError}}.
Execute the sub step that corresponds to the type of the methods argument:
string
object:
Let data be a byte buffer that represents the result of encoding the method's argument as UTF-8.
{{Blob}} object:
Let data be the raw data represented by the {{Blob}} object.
{{ArrayBuffer}} object:
Let data be the data stored in the buffer described by the {{ArrayBuffer}} object.
{{ArrayBufferView}} object:
Let data be the data stored in the section of the buffer described by the {{ArrayBuffer}} object that the {{ArrayBufferView}} object references.
null
and undefined
.
If the byte size of data exceeds the value of {{RTCSctpTransport/maxMessageSize}} on channel's associated {{RTCSctpTransport}}, [= exception/throw =] a {{TypeError}}.
Queue data for transmission on channel's [= underlying data transport =]. If queuing data is not possible because not enough buffer space is available, [= exception/throw =] an {{OperationError}}.
Increase the value of the {{RTCDataChannel/[[BufferedAmount]]}} slot by the byte size of data.
dictionary RTCDataChannelInit { boolean ordered = true; [EnforceRange] unsigned short maxPacketLifeTime; [EnforceRange] unsigned short maxRetransmits; USVString protocol = ""; boolean negotiated = false; [EnforceRange] unsigned short id; };
true
If set to false, data is allowed to be delivered out of order. The default value of true, guarantees that data will be delivered in order.
Limits the time (in milliseconds) during which the channel will transmit or retransmit data if not acknowledged. This value may be clamped if it exceeds the maximum value supported by the user agent.
Limits the number of times a channel will retransmit data if not successfully delivered. This value may be clamped if it exceeds the maximum value supported by the user agent.
""
Subprotocol name used for this channel.
false
The default value of false tells the user agent to announce the channel in-band and instruct the other peer to dispatch a corresponding {{RTCDataChannel}} object. If set to true, it is up to the application to negotiate the channel and create an {{RTCDataChannel}} object with the same {{RTCDataChannel/id}} at the other peer.
Sets the channel ID when {{RTCDataChannelInit/negotiated}} is true. Ignored when {{RTCDataChannelInit/negotiated}} is false.
enum RTCDataChannelState { "connecting", "open", "closing", "closed" };
RTCDataChannelState Enumeration description | |
---|---|
connecting |
The user agent is attempting to establish the [= underlying data transport =]. This is the initial state of an {{RTCDataChannel}} object, whether created with {{RTCPeerConnection/createDataChannel}}, or dispatched as a part of an {{RTCDataChannelEvent}}. |
open |
The [= underlying data transport =] is established and communication is possible. |
closing |
The [= closing procedure | procedure =] to close down the [= underlying data transport =] has started. |
closed |
The [= underlying data transport =] has been {{closed}} or could not be established. |
The {{RTCPeerConnection/datachannel}} event uses the {{RTCDataChannelEvent}} interface.
[Exposed=Window] interface RTCDataChannelEvent : Event { constructor(DOMString type, RTCDataChannelEventInit eventInitDict); readonly attribute RTCDataChannel channel; };
The {{channel}} attribute represents the {{RTCDataChannel}} object associated with the event.
dictionary RTCDataChannelEventInit : EventInit { required RTCDataChannel channel; };
The {{RTCDataChannel}} object to be announced by the event.
An {{RTCDataChannel}} object MUST not be garbage collected if its
{{RTCDataChannel/[[ReadyState]]}} slot is {{RTCDataChannelState/"connecting"}} and at least one event listener is registered for {{RTCDataChannel/open}} events, {{RTCDataChannel/message}} events, {{RTCDataChannel/error}} events, {{RTCDataChannel/closing}} events, or close events.
{{RTCDataChannel/[[ReadyState]]}} slot is {{RTCDataChannelState/"open"}} and at least one event listener is registered for {{RTCDataChannel/message}} events, {{RTCDataChannel/error}} events, {{RTCDataChannel/closing}} events, or close events.
{{RTCDataChannel/[[ReadyState]]}} slot is {{RTCDataChannelState/"closing"}} and at least one event listener is registered for {{RTCDataChannel/error}} events, or close events.
[= underlying data transport =] is established and data is queued to be transmitted.
This section describes an interface on {{RTCRtpSender}} to send DTMF (phone keypad) values across an {{RTCPeerConnection}}. Details of how DTMF is sent to the other peer are described in [[RFC7874]].
The Peer-to-peer DTMF API extends the {{RTCRtpSender}} interface as described below.
partial interface RTCRtpSender { readonly attribute RTCDTMFSender? dtmf; };
On getting, the {{dtmf}} attribute returns the value of the
{{RTCRtpSender/[[Dtmf]]}} internal slot, which represents a
{{RTCDTMFSender}} which can be used to send DTMF, or
null
if unset. The {{RTCRtpSender/[[Dtmf]]}} internal
slot is set when the kind of an {{RTCRtpSender}}'s
{{RTCRtpSender/[[SenderTrack]]}} is "audio"
.
To create an RTCDTMFSender, the user agent MUST run the following steps:
Let dtmf be a newly created {{RTCDTMFSender}} object.
Let dtmf have a [[\Duration]] internal slot.
Let dtmf have a [[\InterToneGap]] internal slot.
Let dtmf have a [[\ToneBuffer]] internal slot.
[Exposed=Window] interface RTCDTMFSender : EventTarget { undefined insertDTMF(DOMString tones, optional unsigned long duration = 100, optional unsigned long interToneGap = 70); attribute EventHandler ontonechange; readonly attribute boolean canInsertDTMF; readonly attribute DOMString toneBuffer; };
The event type of this event handler is {{RTCDTMFSender/tonechange}}.
Whether the {{RTCDTMFSender}} dtmfSender is capable of sending DTMF. On getting, the user agent MUST return the result of running [= determine if DTMF can be sent =] for dtmfSender.
The {{toneBuffer}} attribute MUST return a list of the tones remaining to be played out. For the syntax, content, and interpretation of this list, see {{insertDTMF}}.
An {{RTCDTMFSender}} object's {{insertDTMF}} method is used to send DTMF tones.
The tones parameter is treated as a series of characters. The characters 0 through 9, A through D, #, and * generate the associated DTMF tones. The characters a to d MUST be normalized to uppercase on entry and are equivalent to A to D. As noted in [[RTCWEB-AUDIO]] Section 3, support for the characters 0 through 9, A through D, #, and * are required. The character ',' MUST be supported, and indicates a delay of 2 seconds before processing the next character in the tones parameter. All other characters (and only those other characters) MUST be considered unrecognized.
The duration parameter indicates the duration in ms to use for each character passed in the tones parameters. The duration cannot be more than 6000 ms or less than 40 ms. The default duration is 100 ms for each tone.
The interToneGap parameter indicates the gap between tones in ms. The user agent clamps it to at least 30 ms and at most 6000 ms. The default value is 70 ms.
The browser MAY increase the duration and interToneGap times to cause the times that DTMF start and stop to align with the boundaries of RTP packets but it MUST not increase either of them by more than the duration of a single RTP audio packet.
When the {{insertDTMF()}} method is invoked, the user agent MUST run the following steps:
Let transceiver be the {{RTCRtpTransceiver}} object associated with sender.
false
, [=
exception/throw =] an {{InvalidStateError}}.
","
delay sending
tones for 2000
ms on the associated RTP
media stream, and queue a task to be executed in
2000
ms from now that runs the steps
labelled Playout task.
","
start
playout of tone for {{RTCDTMFSender/[[Duration]]}} ms on
the associated RTP media stream, using the appropriate
codec, then queue a task to be executed in
{{RTCDTMFSender/[[Duration]]}} + {{RTCDTMFSender/[[InterToneGap]]}} ms from
now that runs the steps labelled Playout task.
Since {{insertDTMF}} replaces the tone buffer, in order to add to the DTMF tones being played, it is necessary to call {{insertDTMF}} with a string containing both the remaining tones (stored in the {{RTCDTMFSender/[[ToneBuffer]]}} slot) and the new tones appended together. Calling {{insertDTMF}} with an empty tones parameter can be used to cancel all tones queued to play after the currently playing tone.
To determine if DTMF can be sent for an {{RTCDTMFSender}} instance dtmfSender, the user agent MUST queue a task that runs the following steps:
false
.
null
return false
.
false
.
[0]
.{{RTCRtpEncodingParameters/active}}
is false
return false
.
"audio/telephone-event"
has been negotiated for sending
with this sender, return false
.
true
.
The {{RTCDTMFSender/tonechange}} event uses the {{RTCDTMFToneChangeEvent}} interface.
[Exposed=Window] interface RTCDTMFToneChangeEvent : Event { constructor(DOMString type, optional RTCDTMFToneChangeEventInit eventInitDict = {}); readonly attribute DOMString tone; };
The {{tone}} attribute contains the character for the tone
(including ","
) that has just begun playout (see
{{RTCDTMFSender/insertDTMF}} ). If the value is the empty
string, it indicates that the {{RTCDTMFSender/[[ToneBuffer]]}} slot is
an empty string and that the previous tones have completed
playback.
dictionary RTCDTMFToneChangeEventInit : EventInit { DOMString tone = ""; };
""
The {{tone}} attribute contains the character for the tone
(including ","
) that has just begun playout (see
{{RTCDTMFSender/insertDTMF}} ). If the value is the empty
string, it indicates that the {{RTCDTMFSender/[[ToneBuffer]]}} slot is
an empty string and that the previous tones have completed
playback.
The basic statistics model is that the browser maintains a set of statistics for [= monitored object =]s, in the form of [= stats object =]s.
A group of related objects may be referenced by a selector. The selector may, for example, be a {{MediaStreamTrack}}. For a track to be a valid selector, it MUST be a {{MediaStreamTrack}} that is sent or received by the {{RTCPeerConnection}} object on which the stats request was issued. The calling Web application provides the selector to the {{RTCPeerConnection/getStats()}} method and the browser emits (in the JavaScript) a set of statistics that are relevant to the selector, according to the [= stats selection algorithm =]. Note that that algorithm takes the sender or receiver of a selector.
The statistics returned in [= stats object =]s are designed in such a way that repeated queries can be linked by the {{RTCStats}} {{RTCStats/id}} dictionary member. Thus, a Web application can make measurements over a given time period by requesting measurements at the beginning and end of that period.
With a few exceptions, [= monitored object =]s, once created, exist for the duration of their associated {{RTCPeerConnection}}. This ensures statistics from them are available in the result from {{RTCPeerConnection/getStats()}} even past the associated peer connection being {{RTCPeerConnection/close}}d.
Only a few monitored objects have shorter lifetimes. Statistics from these objects are no longer available in subsequent getStats() results. The object descriptions in [[!WEBRTC-STATS]] describe when these monitored objects are deleted.
The Statistics API extends the {{RTCPeerConnection}} interface as described below.
partial interface RTCPeerConnection { Promise<RTCStatsReport> getStats(optional MediaStreamTrack? selector = null); };
Gathers stats for the given [= selector =] and reports the result asynchronously.
When the {{getStats()}} method is invoked, the user agent MUST run the following steps:
Let selectorArg be the method's first argument.
Let connection be the {{RTCPeerConnection}} object on which the method was invoked.
If selectorArg is null
, let
selector be null
.
If selectorArg is a {{MediaStreamTrack}} let selector be an {{RTCRtpSender}} or {{RTCRtpReceiver}} on connection which {{RTCRtpSender/track}} attribute matches selectorArg. If no such sender or receiver exists, or if more than one sender or receiver fit this criteria, return a promise [= rejected =] with a newly [= exception/created =] {{InvalidAccessError}}.
Let p be a new promise.
Run the following steps in parallel:
Gather the stats indicated by selector according to the [= stats selection algorithm =].
[= Resolve =] p with the resulting {{RTCStatsReport}} object, containing the gathered stats.
Return p.
The {{RTCPeerConnection/getStats()}} method delivers a successful result in the form of an {{RTCStatsReport}} object. An {{RTCStatsReport}} object is a map between strings that identify the inspected objects ({{RTCStats/id}} attribute in {{RTCStats}} instances), and their corresponding {{RTCStats}}-derived dictionaries.
An {{RTCStatsReport}} may be composed of several {{RTCStats}}-derived dictionaries, each reporting stats for one underlying object that the implementation thinks is relevant for the [= selector =]. One achieves the total for the [= selector =] by summing over all the stats of a certain type; for instance, if an {{RTCRtpSender}} uses multiple SSRCs to carry its track over the network, the {{RTCStatsReport}} may contain one {{RTCStats}}-derived dictionary per SSRC (which can be distinguished by the value of the {{RTCRtpStreamStats/ssrc}} stats attribute).
[Exposed=Window] interface RTCStatsReport { readonly maplike<DOMString, object>; };
Use these to retrieve the various dictionaries descended from {{RTCStats}} that this stats report is composed of. The set of supported property names [[!WEBIDL]] is defined as the ids of all the {{RTCStats}}-derived dictionaries that have been generated for this stats report.
An {{RTCStats}} dictionary represents the [= stats object =] constructed by inspecting a specific [= monitored object =]. The {{RTCStats}} dictionary is a base type that specifies as set of default attributes, such as {{RTCStats/timestamp}} and {{RTCStats/type}}. Specific stats are added by extending the {{RTCStats}} dictionary.
Note that while stats names are standardized, any given implementation may be using experimental values or values not yet known to the Web application. Thus, applications MUST be prepared to deal with unknown stats.
Statistics need to be synchronized with each other in order to yield reasonable values in computation; for instance, if {{RTCSentRtpStreamStats/bytesSent}} and {{RTCSentRtpStreamStats/packetsSent}} are both reported, they both need to be reported over the same interval, so that "average packet size" can be computed as "bytes / packets" - if the intervals are different, this will yield errors. Thus implementations MUST return synchronized values for all stats in an {{RTCStats}}-derived dictionary.
dictionary RTCStats { required DOMHighResTimeStamp timestamp; required RTCStatsType type; required DOMString id; };
The {{timestamp}}, of type {{DOMHighResTimeStamp}}, associated with this object. The time is relative to the UNIX epoch (Jan 1, 1970, UTC). For statistics that came from a remote source (e.g., from received RTCP packets), {{timestamp}} represents the time at which the information arrived at the local endpoint. The remote timestamp can be found in an additional field in an {{RTCStats}}-derived dictionary, if applicable.
The type of this object.
The {{type}} attribute MUST be initialized to the name of the most specific type this {{RTCStats}} dictionary represents.
A unique {{id}} that is associated with the object that was inspected to produce this {{RTCStats}} object. Two {{RTCStats}} objects, extracted from two different {{RTCStatsReport}} objects, MUST have the same id if they were produced by inspecting the same underlying object.
Stats ids MUST NOT be predictable by an application. This prevents applications from depending on a particular user agent's way of generating ids, since this prevents an application from getting stats objects by their id unless they have already read the id of that specific stats object.
User agents are free to pick any format for the id as long as it meets the requirements above.
A user agent can turn a predictably generated string into an unpredictable string using a hash function, as long as it uses a salt that is unique to the peer connection. This allows an implementation to have predictable ids internally, which may make it easier to guarantee that stats objects have stable ids across getStats() calls.
The set of valid values for {{RTCStatsType}}, and the dictionaries derived from RTCStats that they indicate, are documented in [[!WEBRTC-STATS]].
The stats selection algorithm is as follows:
null
,
gather stats for the whole connection, add them to
result, return result, and abort these steps.
The stats listed in [[WEBRTC-STATS]] are intended to cover a wide range of use cases. Not all of them have to be implemented by every WebRTC implementation.
An implementation MUST support generating statistics of the following {{RTCStats/type}}s when the corresponding objects exist on a {{RTCPeerConnection}}, with the fields that are listed when they are valid for that object in addition to the generic fields defined in the {{RTCStats}} dictionary:
{{RTCStatsType}} | Dictionary | Fields |
---|---|---|
{{RTCStatsType/"codec"}} | {{RTCCodecStats}} | {{RTCCodecStats/payloadType}}, {{RTCCodecStats/codecType}}, {{RTCCodecStats/mimeType}}, {{RTCCodecStats/clockRate}}, {{RTCCodecStats/channels}}, {{RTCCodecStats/sdpFmtpLine}} |
{{RTCStatsType/"inbound-rtp"}} | {{RTCRtpStreamStats}} | {{RTCRtpStreamStats/ssrc}}, {{RTCRtpStreamStats/kind}}, {{RTCRtpStreamStats/transportId}}, {{RTCRtpStreamStats/codecId}} |
{{RTCReceivedRtpStreamStats}} | {{RTCReceivedRtpStreamStats/packetsReceived}}, {{RTCReceivedRtpStreamStats/packetsLost}}, {{RTCReceivedRtpStreamStats/jitter}}, {{RTCReceivedRtpStreamStats/packetsDiscarded}}, {{RTCReceivedRtpStreamStats/framesDropped}} | |
{{RTCInboundRtpStreamStats}} | {{RTCInboundRtpStreamStats/receiverId}}, {{RTCInboundRtpStreamStats/remoteId}}, {{RTCInboundRtpStreamStats/framesDecoded}}, {{RTCInboundRtpStreamStats/nackCount}}, {{RTCInboundRtpStreamStats/framesReceived}}, {{RTCInboundRtpStreamStats/bytesReceived}}, {{RTCInboundRtpStreamStats/totalAudioEnergy}}, {{RTCInboundRtpStreamStats/totalSamplesDuration}} | |
{{RTCStatsType/"outbound-rtp"}} | {{RTCRtpStreamStats}} | {{RTCRtpStreamStats/ssrc}}, {{RTCRtpStreamStats/kind}}, {{RTCRtpStreamStats/transportId}}, {{RTCRtpStreamStats/codecId}} |
{{RTCSentRtpStreamStats}} | {{RTCSentRtpStreamStats/packetsSent}}, {{RTCSentRtpStreamStats/bytesSent}} | |
{{RTCOutboundRtpStreamStats}} | {{RTCOutboundRtpStreamStats/senderId}}, {{RTCOutboundRtpStreamStats/remoteId}}, {{RTCOutboundRtpStreamStats/framesEncoded}}, {{RTCOutboundRtpStreamStats/nackCount}}, {{RTCOutboundRtpStreamStats/framesSent}} | |
{{RTCStatsType/"remote-inbound-rtp"}} | {{RTCRtpStreamStats}} | {{RTCRtpStreamStats/ssrc}}, {{RTCRtpStreamStats/kind}}, {{RTCRtpStreamStats/transportId}}, {{RTCRtpStreamStats/codecId}} |
{{RTCReceivedRtpStreamStats}} | {{RTCReceivedRtpStreamStats/packetsReceived}}, {{RTCReceivedRtpStreamStats/packetsLost}}, {{RTCReceivedRtpStreamStats/jitter}}, {{RTCReceivedRtpStreamStats/packetsDiscarded}}, {{RTCReceivedRtpStreamStats/framesDropped}} | |
{{RTCRemoteInboundRtpStreamStats}} | {{RTCRemoteInboundRtpStreamStats/localId}}, {{RTCRemoteInboundRtpStreamStats/roundTripTime}} | |
{{RTCStatsType/"remote-outbound-rtp"}} | {{RTCRtpStreamStats}} | {{RTCRtpStreamStats/ssrc}}, {{RTCRtpStreamStats/kind}}, {{RTCRtpStreamStats/transportId}}, {{RTCRtpStreamStats/codecId}} |
{{RTCSentRtpStreamStats}} | {{RTCSentRtpStreamStats/packetsSent}}, {{RTCSentRtpStreamStats/bytesSent}} | |
{{RTCRemoteOutboundRtpStreamStats}} | {{RTCRemoteOutboundRtpStreamStats/localId}}, {{RTCRemoteOutboundRtpStreamStats/remoteTimestamp}} | |
{{RTCStatsType/"media-source"}} | {{RTCMediaSourceStats}} | {{RTCMediaSourceStats/trackIdentifier}}, {{RTCMediaSourceStats/kind}} |
{{RTCAudioSourceStats}} | {{RTCAudioSourceStats/totalAudioEnergy}}, {{RTCAudioSourceStats/totalSamplesDuration}} (for audio tracks attached to senders) | |
{{RTCVideoSourceStats}} | {{RTCVideoSourceStats/width}}, {{RTCVideoSourceStats/height}}, {{RTCVideoSourceStats/framesPerSecond}} (for video tracks attached to senders) | |
{{RTCStatsType/"peer-connection"}} | {{RTCPeerConnectionStats}} | {{RTCPeerConnectionStats/dataChannelsOpened}}, {{RTCPeerConnectionStats/dataChannelsClosed}} |
{{RTCStatsType/"data-channel"}} | {{RTCDataChannelStats}} | {{RTCDataChannelStats/label}} , {{RTCDataChannelStats/protocol}}, {{RTCDataChannelStats/dataChannelIdentifier}}, {{RTCDataChannelStats/state}}, {{RTCDataChannelStats/messagesSent}}, {{RTCDataChannelStats/bytesSent}}, {{RTCDataChannelStats/messagesReceived}}, {{RTCDataChannelStats/bytesReceived}} |
{{RTCStatsType/"sender"}} | {{RTCMediaHandlerStats}} | {{RTCMediaHandlerStats/trackIdentifier}} |
{{RTCStatsType/"receiver"}} | ||
{{RTCStatsType/"transport"}} | {{RTCTransportStats}} | {{RTCTransportStats/bytesSent}}, {{RTCTransportStats/bytesReceived}}, {{RTCTransportStats/selectedCandidatePairId}}, {{RTCTransportStats/localCertificateId}}, {{RTCTransportStats/remoteCertificateId}} |
{{RTCStatsType/"candidate-pair"}} | {{RTCIceCandidatePairStats}} | {{RTCIceCandidatePairStats/transportId}}, {{RTCIceCandidatePairStats/localCandidateId}}, {{RTCIceCandidatePairStats/remoteCandidateId}}, {{RTCIceCandidatePairStats/state}}, {{RTCIceCandidatePairStats/nominated}}, {{RTCIceCandidatePairStats/bytesSent}}, {{RTCIceCandidatePairStats/bytesReceived}}, {{RTCIceCandidatePairStats/totalRoundTripTime}}, {{RTCIceCandidatePairStats/currentRoundTripTime}} |
{{RTCStatsType/"local-candidate"}} | {{RTCIceCandidateStats}} | {{RTCIceCandidateStats/address}}, {{RTCIceCandidateStats/port}}, {{RTCIceCandidateStats/protocol}}, {{RTCIceCandidateStats/candidateType}}, {{RTCIceCandidateStats/url}} |
{{RTCStatsType/"remote-candidate"}} | ||
{{RTCStatsType/"certificate"}} | {{RTCCertificateStats}} | {{RTCCertificateStats/fingerprint}}, {{RTCCertificateStats/fingerprintAlgorithm}}, {{RTCCertificateStats/base64Certificate}}, {{RTCCertificateStats/issuerCertificateId}} |
An implementation MAY support generating any other statistic defined in [[!WEBRTC-STATS]], and MAY generate statistics that are not documented.
Consider the case where the user is experiencing bad sound and the application wants to determine if the cause of it is packet loss. The following example code might be used:
async function gatherStats(pc) { try { const [sender] = pc.getSenders(); const baselineReport = await sender.getStats(); await new Promise(resolve => setTimeout(resolve, aBit)); // wait a bit const currentReport = await sender.getStats(); // compare the elements from the current report with the baseline for (const now of currentReport.values()) { if (now.type != 'outbound-rtp') continue; // get the corresponding stats from the baseline report const base = baselineReport.get(now.id); if (!base) continue; const remoteNow = currentReport.get(now.remoteId); const remoteBase = baselineReport.get(base.remoteId); const packetsSent = now.packetsSent - base.packetsSent; const packetsReceived = remoteNow.packetsReceived - remoteBase.packetsReceived; const fractionLost = (packetsSent - packetsReceived) / packetsSent; if (fractionLost > 0.3) { // if fractionLost is > 0.3, we have probably found the culprit } } } catch (err) { console.error(err); } }
[[!GETUSERMEDIA]] 仕様で定義されている {{MediaStreamTrack}} インターフェースは、通常、オーディオまたはビデオのデータのストリームを表します。1つまたは複数の {{MediaStreamTrack}} を {{MediaStream}} に集めることができます。(厳密には、[[!GETUSERMEDIA]] で定義されている {{MediaStream}} には、0個以上の {{MediaStreamTrack}} オブジェクトを含めることができます)。
{{MediaStreamTrack}} は(ローカルカメラだけではなく)リモートピアから来る、またはリモートピアに送られるメディアフローを表すように拡張することができます。このセクションでは、{{MediaStreamTrack}} オブジェクトでこの機能を有効にするために必要な拡張機能について説明します。メディアを相手に送信する方法は、[[RFC8834]]、[[RFC7874]]、[[RFC8835]] に記載されています。
他のピアに送信された {{MediaStreamTrack}} は、受信者には 1 つだけの {{MediaStreamTrack}} として表示されます。ピアとは、本仕様をサポートするユーザーエージェントと定義します。さらに、送信側のアプリケーションは、{{MediaStreamTrack}} がどの {{MediaStream}} オブジェクトのメンバであるかを示すことができます。受信側の対応する {{MediaStream}} オブジェクトは(まだ存在していなければ)作成され、それに応じて入力されます。
このドキュメントの前半でも述べたように、{{RTCRtpSender}} と {{RTCRtpReceiver}} というオブジェクトをアプリケーションが使用することで、{{MediaStreamTrack}} の送受信をより細かく制御することができます。
チャンネルは、Media Capture and Streams 仕様で考慮されている最小の単位です。チャンネルは、例えば RTP ペイロードタイプとして送信するために一緒にエンコードされることを意図しています。コーデックが共同でエンコードする必要のあるすべてのチャンネルは、同じ {{MediaStreamTrack}} 内になければならず(MUST)、コーデックはトラック内のすべてのチャンネルをエンコード、または破棄できるべきである(SHOULD)とされています。
ある {{MediaStreamTrack}} への入力と出力の概念は、ネットワーク上で送信される {{MediaStreamTrack}} オブジェクトの場合にも適用されます。{{RTCPeerConnection}} オブジェクトによって作成された {{MediaStreamTrack}} は、リモートピアから受信したデータを入力として受け取ります。 同様に、[[!GETUSERMEDIA]] 経由のカメラなどのローカルソースからの {{MediaStreamTrack}} は、オブジェクトが {{RTCPeerConnection}} オブジェクトと一緒に使用されている場合、リモートピアに送信されるものを表す出力を持ちます。
[[!GETUSERMEDIA]] で説明されている {{MediaStream}} と {{MediaStreamTrack}} オブジェクトの複製の概念は、ここでも適用できます。 この機能は、例えば、ビデオ会議のシナリオにおいて、ユーザーのカメラとマイクからのローカルビデオをローカルモニターに表示し、音声のみをリモートピアに送信するために使用できます(例えば、ユーザーが「ビデオミュート」機能を使用したことに対応しています)。異なる {{MediaStreamTrack}} オブジェクトを新しい {{MediaStream}} オブジェクトに結合することは、特定の状況で有用です。
このドキュメントでは、{{RTCPeerConnection}} と一緒に使用する際に関連する以下のオブジェクトの側面のみを指定しています。{{MediaStream}} と {{MediaStreamTrack}} の使用に関する一般的な情報は、[[!GETUSERMEDIA]] ドキュメントのオブジェクトのオリジナルの定義を参照してください。
{{MediaStream}} で指定された {{MediaStream/id}} 属性は、{{RTCPeerConnection}} APIのリモート側でストリームを認識できるように、このストリームに固有の id を返します。
リモートピアから取得したストリームを表す {{MediaStream}} が作成されると、{{MediaStream/id}} 属性はリモートソースから提供された情報で初期化されます。
{{MediaStream/id}} オブジェクトの {{MediaStream/id}} は、ストリームのソースに固有のものですが、だからといって重複してしまう可能性がないわけではありません。例えば、ローカルに生成されたストリームのトラックは、あるユーザーエージェントから {{RTCPeerConnection}} を使用してリモートピアに送信され、その後同じ方法で元のユーザーエージェントに送り返される可能性があります。この場合、元のユーザーエージェントは同じ id を持つ複数のストリーム(ローカルに生成されたものとリモートピアから受信したもの)を持つことになります。
{{MediaStreamTrack}} オブジェクトの {{MediaStream}} への参照は、非ローカルメディアソースの場合({{RTCRtpReceiver}} に関連付けられた各 {{MediaStreamTrack}} のように、RTP ソースの場合)には、常に強力です。
対応する {{MediaStreamTrack}} がミュートされているが終了していない RTP ソースのデータを {{RTCRtpReceiver}} が受信するたびに。また、{{RTCRtpTransceiver/[[Receptive]]}} スロットが true
である {{RTCRtpReceiver}}オブジェクトのメンバーである場合、対応する {{MediaStreamTrack}} のミュート状態を false
に設定する [= set the muted state =] タスクをキューに入れなければならない(MUST)。
{{RTCRtpReceiver}} が受信した RTP ソースメディアストリームの SSRC の1つが、BYE の受信またはタイムアウトによって削除された場合、{{MediaStreamTrack}} の対応する {{MediaStreamTrack}} の [= set the muted state =] を true
にするタスクをキューに入れなければならない(MUST)。なお、{{RTCPeerConnection/setRemoteDescription}} は、{{RTCRtpReceiver/track}} の [= set the muted state | the setting of the muted state =] を true
の値にすることにもつながる。
トラックを追加する、トラックを削除する、トラックのミュート状態を設定するの手順は、[[!GETUSERMEDIA]] で指定されています。
{{RTCRtpReceiver}} receiver によって生成された {{MediaStreamTrack}} トラックが終了した場合 [[!GETUSERMEDIA]](receiver.{{RTCRtpReceiver/track}}.stop
への呼び出しなど)、ユーザエージェントは、receiverのデコーダをオフにするなどして、受信ストリームに割り当てられたリソースを解放することを選択してもよい(MAY)。
制約の概念と制約可能なプロパティ({{MediaTrackConstraints}} を含む。({{MediaStreamTrack}}.getConstraints()
, {{MediaStreamTrack}}.applyConstraints()
)や {{MediaTrackSettings}} などの制約や制約可能なプロパティの概念があります。({{MediaStreamTrack}}.getSettings()
)の概要は [[!GETUSERMEDIA]] に記載されています。しかし、ピア接続からソースされたトラックの制約可能なプロパティは、getUserMedia()
でソースされたものとは異なります。[= remote source =]からソースされた {{MediaStreamTrack}} に適用される制約と設定はここで定義されます。リモートトラックの設定は、受信した最新のフレームを表します。
{{MediaStreamTrack}}.getCapabilities()
は、常に空のセットを返さなければならず、{{MediaStreamTrack}}.applyConstraints()
は、ここで定義された制約に対して、リモートトラック上で常にOverconstrainedError
で拒否しなければなりません。
The following constrainable properties are defined to apply to video {{MediaStreamTrack}}s sourced from a [= remote source =]:
Property Name | Values | Notes |
---|---|---|
width | {{ConstrainULong}} | As a setting, this is the width, in pixels, of the latest frame received. |
height | {{ConstrainULong}} | As a setting, this is the height, in pixels, of the latest frame received. |
frameRate | {{ConstrainDouble}} | As a setting, this is an estimate of the frame rate based on recently received frames. |
aspectRatio | {{ConstrainDouble}} | As a setting, this is the aspect ratio of the latest frame; this is the width in pixels divided by height in pixels as a double rounded to the tenth decimal place. |
This document does not define any constrainable properties to apply to audio {{MediaStreamTrack}}s sourced from a [= remote source =].
When two peers decide they are going to set up a connection to each other, they both go through these steps. The STUN/TURN server configuration describes a server they can use to get things like their public IP address or to set up NAT traversal. They also have to send data for the signaling channel to each other using the same out-of-band mechanism they used to establish that they were going to communicate in the first place.
const signaling = new SignalingChannel(); // handles JSON.stringify/parse const constraints = {audio: true, video: true}; const configuration = {iceServers: [{urls: 'stun:stun.example.org'}]}; const pc = new RTCPeerConnection(configuration); // send any ice candidates to the other peer pc.onicecandidate = ({candidate}) => signaling.send({candidate}); // let the "negotiationneeded" event trigger offer generation pc.onnegotiationneeded = async () => { try { await pc.setLocalDescription(); // send the offer to the other peer signaling.send({description: pc.localDescription}); } catch (err) { console.error(err); } }; pc.ontrack = ({track, streams}) => { // once media for a remote track arrives, show it in the remote video element track.onunmute = () => { // don't set srcObject again if it is already set. if (remoteView.srcObject) return; remoteView.srcObject = streams[0]; }; }; // call start() to initiate function start() { addCameraMic(); } // add camera and microphone to connection async function addCameraMic() { try { // get a local stream, show it in a self-view and add it to be sent const stream = await navigator.mediaDevices.getUserMedia(constraints); for (const track of stream.getTracks()) { pc.addTrack(track, stream); } selfView.srcObject = stream; } catch (err) { console.error(err); } } signaling.onmessage = async ({data: {description, candidate}}) => { try { if (description) { await pc.setRemoteDescription(description); // if we got an offer, we need to reply with an answer if (description.type == 'offer') { if (!selfView.srcObject) { // blocks negotiation on permission (not recommended in production code) await addCameraMic(); } await pc.setLocalDescription(); signaling.send({description: pc.localDescription}); } } else if (candidate) { await pc.addIceCandidate(candidate); } } catch (err) { console.error(err); } };
When two peers decide they are going to set up a connection to each other and want to have the ICE, DTLS, and media connections "warmed up" such that they are ready to send and receive media immediately, they both go through these steps.
const signaling = new SignalingChannel(); // handles JSON.stringify/parse const constraints = {audio: true, video: true}; const configuration = {iceServers: [{urls: 'stun:stun.example.org'}]}; let pc; let audio; let video; let started = false; // Call warmup() before media is ready, to warm-up ICE, DTLS, and media. async function warmup(isAnswerer) { pc = new RTCPeerConnection(configuration); if (!isAnswerer) { audio = pc.addTransceiver('audio'); video = pc.addTransceiver('video'); } // send any ice candidates to the other peer pc.onicecandidate = ({candidate}) => signaling.send({candidate}); // let the "negotiationneeded" event trigger offer generation pc.onnegotiationneeded = async () => { try { await pc.setLocalDescription(); // send the offer to the other peer signaling.send({description: pc.localDescription}); } catch (err) { console.error(err); } }; pc.ontrack = async ({track, transceiver}) => { try { // once media for the remote track arrives, show it in the video element event.track.onunmute = () => { // don't set srcObject again if it is already set. if (!remoteView.srcObject) { remoteView.srcObject = new MediaStream(); } remoteView.srcObject.addTrack(track); } if (isAnswerer) { if (track.kind == 'audio') { audio = transceiver; } else if (track.kind == 'video') { video = transceiver; } if (started) await addCameraMicWarmedUp(); } } catch (err) { console.error(err); } }; try { // get a local stream, show it in a self-view and add it to be sent selfView.srcObject = await navigator.mediaDevices.getUserMedia(constraints); if (started) await addCameraMicWarmedUp(); } catch (err) { console.error(err); } } // call start() after warmup() to begin transmitting media from both ends function start() { signaling.send({start: true}); signaling.onmessage({data: {start: true}}); } // add camera and microphone to already warmed-up connection async function addCameraMicWarmedUp() { const stream = selfView.srcObject; if (audio && video && stream) { await Promise.all([ audio.sender.replaceTrack(stream.getAudioTracks()[0]), video.sender.replaceTrack(stream.getVideoTracks()[0]), ]); } } signaling.onmessage = async ({data: {start, description, candidate}}) => { if (!pc) warmup(true); try { if (start) { started = true; await addCameraMicWarmedUp(); } else if (description) { await pc.setRemoteDescription(description); // if we got an offer, we need to reply with an answer if (description.type == 'offer') { await pc.setLocalDescription(); signaling.send({description: pc.localDescription}); } } else { await pc.addIceCandidate(candidate); } } catch (err) { console.error(err); } };
A client wants to send multiple RTP encodings (simulcast) to a server.
const signaling = new SignalingChannel(); // handles JSON.stringify/parse const constraints = {audio: true, video: true}; const configuration = {'iceServers': [{'urls': 'stun:stun.example.org'}]}; let pc; // call start() to initiate async function start() { pc = new RTCPeerConnection(configuration); // let the "negotiationneeded" event trigger offer generation pc.onnegotiationneeded = async () => { try { await pc.setLocalDescription(); // send the offer to the other peer signaling.send({description: pc.localDescription}); } catch (err) { console.error(err); } }; try { // get a local stream, show it in a self-view and add it to be sent const stream = await navigator.mediaDevices.getUserMedia(constraints); selfView.srcObject = stream; pc.addTransceiver(stream.getAudioTracks()[0], {direction: 'sendonly'}); pc.addTransceiver(stream.getVideoTracks()[0], { direction: 'sendonly', sendEncodings: [ {rid: 'q', scaleResolutionDownBy: 4.0} {rid: 'h', scaleResolutionDownBy: 2.0}, {rid: 'f'}, ] }); } catch (err) { console.error(err); } } signaling.onmessage = async ({data: {description, candidate}}) => { try { if (description) { await pc.setRemoteDescription(description); // if we got an offer, we need to reply with an answer if (description.type == 'offer') { await pc.setLocalDescription(); signaling.send({description: pc.localDescription}); } } else if (candidate) { await pc.addIceCandidate(candidate); } } catch (err) { console.error(err); } };
This example shows how to create an {{RTCDataChannel}} object and
perform the offer/answer exchange required to connect the channel
to the other peer. The {{RTCDataChannel}} is used in the context of
a simple chat application using an input
field for
user input.
const signaling = new SignalingChannel(); // handles JSON.stringify/parse const configuration = {iceServers: [{urls: 'stun:stun.example.org'}]}; let pc, channel; // call start() to initiate function start() { pc = new RTCPeerConnection(configuration); // send any ice candidates to the other peer pc.onicecandidate = ({candidate}) => signaling.send({candidate}); // let the "negotiationneeded" event trigger offer generation pc.onnegotiationneeded = async () => { try { await pc.setLocalDescription(); // send the offer to the other peer signaling.send({description: pc.localDescription}); } catch (err) { console.error(err); } }; // create data channel and setup chat using "negotiated" pattern channel = pc.createDataChannel('chat', {negotiated: true, id: 0}); channel.onopen = () => input.disabled = false; channel.onmessage = ({data}) => showChatMessage(data); input.onkeypress = ({keyCode}) => { // only send when user presses enter if (keyCode != 13) return; channel.send(input.value); } } signaling.onmessage = async ({data: {description, candidate}}) => { if (!pc) start(false); try { if (description) { await pc.setRemoteDescription(description); // if we got an offer, we need to reply with an answer if (description.type == 'offer') { await pc.setLocalDescription(); signaling.send({description: pc.localDescription}); } } else if (candidate) { await pc.addIceCandidate(candidate); } } catch (err) { console.error(err); } };
This shows an example of one possible call flow between two browsers. This does not show the procedure to get access to local media or every callback that gets fired but instead tries to reduce it down to only show the key events and messages.
Examples assume that sender is an {{RTCRtpSender}}.
Sending the DTMF signal "1234" with 500 ms duration per tone:
if (sender.dtmf.canInsertDTMF) { const duration = 500; sender.dtmf.insertDTMF('1234', duration); } else { console.log('DTMF function not available'); }
Send the DTMF signal "123" and abort after sending "2".
async function sendDTMF() { if (sender.dtmf.canInsertDTMF) { sender.dtmf.insertDTMF('123'); await new Promise(r => sender.dtmf.ontonechange = e => e.tone == '2' && r()); // empty the buffer to not play any tone after "2" sender.dtmf.insertDTMF(''); } else { console.log('DTMF function not available'); } }
Send the DTMF signal "1234", and light up the active key using
lightKey(key)
while the tone is playing
(assuming that lightKey("")
will darken
all the keys):
const wait = ms => new Promise(resolve => setTimeout(resolve, ms)); if (sender.dtmf.canInsertDTMF) { const duration = 500; // ms sender.dtmf.insertDTMF(sender.dtmf.toneBuffer + '1234', duration); sender.dtmf.ontonechange = async ({tone}) => { if (!tone) return; lightKey(tone); // light up the key when playout starts await wait(duration); lightKey(''); // turn off the light after tone duration }; } else { console.log('DTMF function not available'); }
It is always safe to append to the tone buffer. This example appends before any tone playout has started as well as during playout.
if (sender.dtmf.canInsertDTMF) { sender.dtmf.insertDTMF('123'); // append more tones to the tone buffer before playout has begun sender.dtmf.insertDTMF(sender.dtmf.toneBuffer + '456'); sender.dtmf.ontonechange = ({tone}) => { // append more tones when playout has begun if (tone != '1') return; sender.dtmf.insertDTMF(sender.dtmf.toneBuffer + '789'); }; } else { console.log('DTMF function not available'); }
Send a 1-second "1" tone followed by a 2-second "2" tone:
if (sender.dtmf.canInsertDTMF) { sender.dtmf.ontonechange = ({tone}) => { if (tone == '1') { sender.dtmf.insertDTMF(sender.dtmf.toneBuffer + '2', 2000); } }; sender.dtmf.insertDTMF(sender.dtmf.toneBuffer + '1', 1000); } else { console.log('DTMF function not available'); }
パーフェクトネゴシエーションは、ネゴシエーションを透過的に管理するための推奨パターンで、この非対称なタスクをアプリケーションの他の部分から抽象化します。このパターンには、一方が常にオファー側である場合に比べて、アプリケーションがグレア({{RTCSignalingState/"stable"}} 状態の外に入ってきたオファー)のリスクなしに両方のピア接続オブジェクトを同時に操作できるという利点があります。アプリケーションの残りの部分は、シグナリング状態の競合を気にすることなく、すべてのモディフィケーション・メソッドとアトリビュートを使用することができます。
2つのピアに異なる役割を指定し、ピア間のシグナリングの衝突を解決するための動作を行います:
The polite peer uses rollback to avoid collision with an incoming offer.
The impolite peer ignores an incoming offer when this would collide with its own.
Together, they manage signaling for the rest of the application in a
manner that doesn't deadlock. The example assumes a
polite
boolean variable indicating the designated role:
const signaling = new SignalingChannel(); // handles JSON.stringify/parse const constraints = {audio: true, video: true}; const configuration = {iceServers: [{urls: 'stun:stun.example.org'}]}; const pc = new RTCPeerConnection(configuration); // call start() anytime on either end to add camera and microphone to connection async function start() { try { const stream = await navigator.mediaDevices.getUserMedia(constraints); for (const track of stream.getTracks()) { pc.addTrack(track, stream); } selfView.srcObject = stream; } catch (err) { console.error(err); } } pc.ontrack = ({track, streams}) => { // once media for a remote track arrives, show it in the remote video element track.onunmute = () => { // don't set srcObject again if it is already set. if (remoteView.srcObject) return; remoteView.srcObject = streams[0]; }; }; // - The perfect negotiation logic, separated from the rest of the application --- // keep track of some negotiation state to prevent races and errors let makingOffer = false; let ignoreOffer = false; let isSettingRemoteAnswerPending = false; // send any ice candidates to the other peer pc.onicecandidate = ({candidate}) => signaling.send({candidate}); // let the "negotiationneeded" event trigger offer generation pc.onnegotiationneeded = async () => { try { makingOffer = true; await pc.setLocalDescription(); signaling.send({description: pc.localDescription}); } catch (err) { console.error(err); } finally { makingOffer = false; } }; signaling.onmessage = async ({data: {description, candidate}}) => { try { if (description) { // An offer may come in while we are busy processing SRD(answer). // In this case, we will be in "stable" by the time the offer is processed // so it is safe to chain it on our Operations Chain now. const readyForOffer = !makingOffer && (pc.signalingState == "stable" || isSettingRemoteAnswerPending); const offerCollision = description.type == "offer" && !readyForOffer; ignoreOffer = !polite && offerCollision; if (ignoreOffer) { return; } isSettingRemoteAnswerPending = description.type == "answer"; await pc.setRemoteDescription(description); // SRD rolls back as needed isSettingRemoteAnswerPending = false; if (description.type == "offer") { await pc.setLocalDescription(); signaling.send({description: pc.localDescription}); } } else if (candidate) { try { await pc.addIceCandidate(candidate); } catch (err) { if (!ignoreOffer) throw err; // Suppress ignored offer's candidates } } } catch (err) { console.error(err); } }
Note that this is timing sensitive, and deliberately uses versions of {{RTCPeerConnection/setLocalDescription}} (without arguments) and {{RTCPeerConnection/setRemoteDescription}} (with implicit rollback) to avoid races with other signaling messages being serviced.
The ignoreOffer variable is needed, because the {{RTCPeerConnection}} object on the impolite side is never told about ignored offers. We must therefore suppress errors from incoming candidates belonging to such offers.
Some operations throw or fire {{RTCError}}. This is an extension of {{DOMException}} that carries additional WebRTC-specific information.
[Exposed=Window] interface RTCError : DOMException { constructor(RTCErrorInit init, optional DOMString message = ""); readonly attribute RTCErrorDetailType errorDetail; readonly attribute long? sdpLineNumber; readonly attribute long? sctpCauseCode; readonly attribute unsigned long? receivedAlert; readonly attribute unsigned long? sentAlert; };
Run the following steps:
Let init be the constructor's first argument.
Let message be the constructor's second argument.
Let e be a new {{RTCError}} object.
Invoke the {{DOMException}} constructor of e
with the {{DOMException/message}} argument set to
message and the {{DOMException/name}} argument
set to "OperationError"
.
This name does not have a mapping to a legacy code so e.{{DOMException/code}} will return 0.
Set all {{RTCError}} attributes of e to the
value of the corresponding attribute in init if
it is present, otherwise set it to null
.
Return e.
The WebRTC-specific error code for the type of error that occurred.
If {{RTCError/errorDetail}} is {{RTCErrorDetailType/"sdp-syntax-error"}} this is the line number where the error was detected (the first line has line number 1).
If {{RTCError/errorDetail}} is {{RTCErrorDetailType/"sctp-failure"}} this is the SCTP cause code of the failed SCTP negotiation.
If {{RTCError/errorDetail}} is {{RTCErrorDetailType/"dtls-failure"}} and a fatal DTLS alert was received, this is the value of the DTLS alert received.
If {{RTCError/errorDetail}} is {{RTCErrorDetailType/"dtls-failure"}} and a fatal DTLS alert was sent, this is the value of the DTLS alert sent.
All attributes defined in {{RTCError}} are marked at risk due to lack of implementation ({{errorDetail}}, {{sdpLineNumber}}, {{sctpCauseCode}}, {{receivedAlert}} and {{sentAlert}}). This does not include attributes inherited from {{DOMException}}.
dictionary RTCErrorInit { required RTCErrorDetailType errorDetail; long sdpLineNumber; long sctpCauseCode; unsigned long receivedAlert; unsigned long sentAlert; };
The errorDetail, sdpLineNumber, sctpCauseCode, receivedAlert and sentAlert members of {{RTCErrorInit}} have the same definitions as the attributes of the same name of {{RTCError}}.
RTCErrorDetailType
Enum
enum RTCErrorDetailType { "data-channel-failure", "dtls-failure", "fingerprint-failure", "sctp-failure", "sdp-syntax-error", "hardware-encoder-not-available", "hardware-encoder-error" };
Enumeration description | |
---|---|
data-channel-failure | The data channel has failed. |
dtls-failure | The DTLS negotiation has failed or the connection has been terminated with a fatal error. The {{DOMException/message}} contains information relating to the nature of error. If a fatal DTLS alert was received, the {{RTCError/receivedAlert}} attribute is set to the value of the DTLS alert received. If a fatal DTLS alert was sent, the {{RTCError/sentAlert}} attribute is set to the value of the DTLS alert sent. |
fingerprint-failure | The {{RTCDtlsTransport}}'s remote certificate did not match any of the fingerprints provided in the SDP. If the remote peer cannot match the local certificate against the provided fingerprints, this error is not generated. Instead a "bad_certificate" (42) DTLS alert might be received from the remote peer, resulting in a {{RTCErrorDetailType/"dtls-failure"}}. |
sctp-failure | The SCTP negotiation has failed or the connection has been terminated with a fatal error. The {{RTCError/sctpCauseCode}} attribute is set to the SCTP cause code. |
sdp-syntax-error | The SDP syntax is not valid. The {{RTCError/sdpLineNumber}} attribute is set to the line number in the SDP where the syntax error was detected. |
hardware-encoder-not-available | The hardware encoder resources required for the requested operation are not available. |
hardware-encoder-error | The hardware encoder does not support the provided parameters. |
The {{RTCErrorEvent}} interface is defined for cases when an {{RTCError}} is raised as an event:
[Exposed=Window] interface RTCErrorEvent : Event { constructor(DOMString type, RTCErrorEventInit eventInitDict); [SameObject] readonly attribute RTCError error; };
Constructs a new {{RTCErrorEvent}}.
The {{RTCError}} describing the error that triggered the event.
dictionary RTCErrorEventInit : EventInit { required RTCError error; };
The {{RTCError}} describing the error associated with the event (if any).
The following events fire on {{RTCDataChannel}} objects:
Event name | Interface | Fired when... |
---|---|---|
open | {{Event}} | The {{RTCDataChannel}} object's [= underlying data transport =] has been established (or re-established). |
message | {{MessageEvent}} [[html]] | A message was successfully received. |
bufferedamountlow | {{Event}} | The {{RTCDataChannel}} object's {{RTCDataChannel/bufferedAmount}} decreases from above its {{RTCDataChannel/bufferedAmountLowThreshold}} to less than or equal to its {{RTCDataChannel/bufferedAmountLowThreshold}}. |
error | {{RTCErrorEvent}} | An error occurred on the data channel. |
closing | {{Event}} | The {{RTCDataChannel}} object transitions to the {{RTCDataChannelState/"closing"}} state |
close | {{Event}} | The {{RTCDataChannel}} object's [= underlying data transport =] has been closed. |
The following events fire on {{RTCPeerConnection}} objects:
Event name | Interface | Fired when... |
---|---|---|
track | {{RTCTrackEvent}} | New incoming media has been negotiated for a specific {{RTCRtpReceiver}}, and that receiver's {{RTCRtpReceiver/track}} has been added to any associated remote {{MediaStream}}s. |
negotiationneeded | {{Event}} | The browser wishes to inform the application that session negotiation needs to be done (i.e. a createOffer call followed by setLocalDescription). |
signalingstatechange | {{Event}} | The [= signaling state =] has changed. This state change is the result of either {{RTCPeerConnection/setLocalDescription}} or {{RTCPeerConnection/setRemoteDescription}} being invoked. |
iceconnectionstatechange | {{Event}} | The {{RTCPeerConnection}}'s [= ICE connection state =] has changed. |
icegatheringstatechange | {{Event}} | The {{RTCPeerConnection}}'s [= ICE gathering state =] has changed. |
icecandidate | {{RTCPeerConnectionIceEvent}} | A new {{RTCIceCandidate}} is made available to the script. |
connectionstatechange | {{Event}} | The {{RTCPeerConnection}}.{{RTCPeerConnection/connectionState}} has changed. |
icecandidateerror | {{RTCPeerConnectionIceErrorEvent}} | A failure occured when gathering ICE candidates. |
datachannel | {{RTCDataChannelEvent}} | A new {{RTCDataChannel}} is dispatched to the script in response to the other peer creating a channel. |
The following events fire on {{RTCDTMFSender}} objects:
Event name | Interface | Fired when... |
---|---|---|
tonechange | {{RTCDTMFToneChangeEvent}} | The {{RTCDTMFSender}} object has either just begun playout of a tone (returned as the {{RTCDTMFToneChangeEvent/tone}} attribute) or just ended the playout of tones in the {{RTCDTMFSender/toneBuffer}} (returned as an empty value in the {{RTCDTMFToneChangeEvent/tone}} attribute). |
The following events fire on {{RTCIceTransport}} objects:
Event name | Interface | Fired when... |
---|---|---|
statechange | {{Event}} | The {{RTCIceTransport}} state changes. |
gatheringstatechange | {{Event}} | The {{RTCIceTransport}} gathering state changes. |
selectedcandidatepairchange | {{Event}} | The {{RTCIceTransport}}'s selected candidate pair changes. |
The following events fire on {{RTCDtlsTransport}} objects:
Event name | Interface | Fired when... |
---|---|---|
statechange | {{Event}} | The {{RTCDtlsTransport}} state changes. |
error | {{RTCErrorEvent}} | An error occurred on the {{RTCDtlsTransport}} (either {{RTCErrorDetailType/"dtls-failure"}} or {{RTCErrorDetailType/"fingerprint-failure"}}). |
The following events fire on {{RTCSctpTransport}} objects:
Event name | Interface | Fired when... |
---|---|---|
statechange | {{Event}} | The {{RTCSctpTransport}} state changes. |
このセクションは規範ではありません。新しい動作を規定するのではなく、仕様書の他の部分にすでに存在する情報を要約しています。WebRTCで使用されているAPIとプロトコルの一般的なセットの全体的なセキュリティに関する考察は、[[?RFC8827]]に記載されています。
このドキュメントは、Webプラットフォームを拡張し、ブラウザと他のブラウザを含む他のデバイスとの間にリアルタイムで直接通信を設定する機能を備えています。
これは、異なるブラウザで動作するアプリケーション間、あるいは同じブラウザで動作するアプリケーションとブラウザではないものとの間で、データやメディアを共有できることを意味しています。これは、異なるオリジンを持つエンティティ間でデータを送信することに対するWebモデルの通常の障壁を拡張したものです。
WebRTCの仕様では、通信のためのユーザへのプロンプトやクロームインジケーターは用意されておらず、Webページがメディアへのアクセスを許可された後は、そのメディアを他のエンティティと自由に共有できることを前提としています。WebRTC のデータチャネルを介したピアツーピアのデータ交換は、ユーザーの明示的な同意や関与なしに行うことができます。これは、サーバーを介した交換(例:Web ソケットを介した交換)がユーザーの関与なしに行われるのと同様です。
WebRTC がなくても、ウェブアプリケーションを提供するウェブサーバーは、アプリケーションの配信先であるパブリック IP アドレスを知っています。 通信を設定すると、ブラウザのネットワークコンテキストに関する追加情報がウェブアプリケーションに公開され、ブラウザが WebRTC の使用に利用できる(おそらくプライベートな)IP アドレスのセットが含まれる場合もあります。この情報の一部は、通信セッションの確立を可能にするために、対応する当事者に渡される必要があります。
IP アドレスを公開すると、位置情報や接続手段が漏洩し、機密情報となる可能性があります。また、ネットワーク環境によっては、フィンガープリントの対象となる範囲が広がり、ユーザーが簡単に解除できない永続的なクロスオリジン状態が発生する可能性があります。
接続すると、通信に提案されたIPアドレスが常に対応する相手に公開されます。アプリケーションは、 {{RTCIceTransportPolicy}} 辞書で公開されている設定を使用して特定のアドレスを使用しないことを選択したり、参加者間の直接接続ではなくリレー(TURN サーバーなど)を使用したりすることで、この公開を制限することができます。通常、TURN サーバーの IP アドレスは機密情報ではないと考えられます。これらの選択は、例えば、ユーザーが相手とのメディア接続を開始することに同意しているかどうかに基づいて、アプリケーションが行うことができます。
IP アドレスのアプリケーションへの公開を緩和するには、使用できる IP アドレスを制限する必要があります。これは、エンドポイント間の最も直接的なパスでの通信能力に影響を与えます。ブラウザは、ユーザが希望するセキュリティ態勢に基づいて、どの IP アドレスをアプリケーションに利用させるかを決定するための適切なコントロールを提供することが推奨されます。どのアドレスを公開するかの選択は、ローカルポリシーによって制御されます(詳細は [[RFC8828]] を参照してください)。
ブラウザは、信頼されたネットワーク環境(ファイアウォールの内側)で実行されるアクティブなプラットフォームであるため、ブラウザがローカルネットワーク上の他の要素に与えるダメージを制限することが重要であり、信頼されていない参加者による傍受、操作、変更からデータを保護することが重要です。
緩和策は以下の通りです。
これらの対策は、関連する IETF のドキュメントに明記されています。
通信が行われているという事実は、ネットワークを観測できる敵からは隠すことができないため、これを公開情報とみなす必要があるのです。
通信証明書は、将来の必要性を見越して、{{MessagePort/postMessage(message, options)}} を使って不透明に共有することができます。ユーザーエージェントは、メモリの攻撃対象を減らすために、{{RTCCertificate}} オブジェクトにアクセスするプロセスから、これらのオブジェクトがハンドルを保持するプライベートキーイングマテリアルを分離することを強く推奨します。
上述したように、WebRTC API で公開されている IP アドレスのリストは、永続的なクロスオリジンの状態として使用することができます。
IP アドレス以外にも、WebRTC API は、{{RTCRtpSender}}.{{RTCRtpSender/getCapabilities}} および {{RTCRtpReceiver}}.{{RTCRtpReceiver/getCapabilities}} メソッドを介して、基礎となるメディアシステムに関する情報を公開しています。これには、システムが生成および消費できるコーデックに関する詳細かつ順序付けられた情報が含まれます。そのような情報の一部は、セッションネゴシエーション中に生成、公開、送信される SDP セッション記述で表現される可能性があります。この情報は、ほとんどの場合、時間や起源を超えて永続的であり、特定のデバイスの指紋の表面を増やします。
DTLS 接続を確立する際、WebRTC API はアプリケーションが永続化できる証明書を生成できます(例: IndexedDB )。これらの証明書は、オリジン間で共有されることはなく、オリジンの永続的なストレージがクリアされるとクリアされます。
{{RTCPeerConnection/setRemoteDescription}} は、例外をスローすることで、不正な SDP や無効な SDP をガードしますが、アプリケーションが予期しない SDP をガードしようとはしません。リモート記述を設定すると、重要なリソースが割り当てられたり(画像バッファやネットワークポートなど)、メディアが流れ始めたり(プライバシーや帯域幅に影響する可能性があります)することがあります。悪意のある SDP を防止していないアプリケーションは、リソースを奪われたり、意図せずに受信メディアを許可したり、相手のエンドポイントが送信をネゴシエートしない場合に {{RTCPeerConnection/ontrack}} などの特定のイベントが発生しないリスクがあります。アプリケーションは、悪意のある SDP に対して警戒する必要があります。
The WebRTC 1.0 specification exposes an API to control protocols (defined within the IETF) necessary to establish real-time audio, video and data exchange.
The Telecommunications Device for the Deaf (TDD/TTY) enables individuals who are hearing or speech impaired (among others) to communicate over telephone lines. Real-Time Text, defined in [[RFC4103]], utilizes T.140 encapsulated in RTP to enable the transition from TDD/TTY devices to IP-based communications, including emergency communication with Public Safety Access Points (PSAP).
Since Real-Time Text requires the ability to send and receive data in near real time, it can be best supported via the WebRTC 1.0 data channel API. As defined by the IETF, the data channel protocol utilizes the SCTP/DTLS/UDP protocol stack, which supports both reliable and unreliable data channels. The IETF chose to standardize SCTP/DTLS/UDP over proposals for an RTP data channel which relied on SRTP key management and were focused on unreliable communications.
Since the IETF chose a different approach than the RTP data channel as part of the WebRTC suite of protocols, as of the time of this publication there is no standardized way for the WebRTC APIs to directly support Real-Time Text as defined at IETF and implemented in U.S. (FCC) regulations. The WebRTC working Group will evaluate whether the developing IETF protocols in this space warrant direct exposure in the browser APIs and is looking for input from the relevant user communities on this potential gap.
Within the IETF MMUSIC Working Group, work is ongoing to enable Real-time text to be sent over the WebRTC data channel, allowing gateways to be deployed to translate between the SCTP data channel protocol and RFC 4103 Real-Time Text. This work, once completed, is expected to enable a unified and interoperable approach for integrating real-time text in WebRTC user-agents (including browsers) - through a gateway or otherwise.
At the time of this publication, gateways that enable effective RTT support in WebRTC clients can be developed e.g. through a custom WebRTC data channel. This is deemed sufficient until such time as future standardized gateways are enabled via IETF protocols such as the SCTP data channel protocol and RFC 4103 Real-Time Text. This will need to be defined at IETF in conjunction with related work at W3C groups to effectively and consistently standardise RTT support internationally.
The editors wish to thank the Working Group chairs and Team Contact, Harald Alvestrand, Stefan Håkansson, Erik Lagerway and Dominique Hazaël-Massieux, for their support. Substantial text in this specification was provided by many people including Martin Thomson, Harald Alvestrand, Justin Uberti, Eric Rescorla, Peter Thatcher, Jan-Ivar Bruaroey and Peter Saint-Andre. Dan Burnett would like to acknowledge the significant support received from Voxeo and Aspect during the development of this specification.
The {{RTCRtpSender}} and {{RTCRtpReceiver}} objects were initially described in the W3C ORTC CG, and have been adapted for use in this specification.