4.4 RTCPeerConnection Interface
The [RFC8829] specification, as a whole, describes the details of how the RTCPeerConnection
operates. References to specific subsections of [RFC8829] are provided as appropriate.
4.4.1 Operation
Calling new [`RTCPeerConnection`](#dom-rtcpeerconnection)(configuration)
creates an RTCPeerConnection
object.
configuration.iceServers
contains information used to find and access the servers used by ICE. The application can supply multiple servers of each type, and any TURN server MAY also be used as a STUN server for the purposes of gathering server reflexive candidates.
An RTCPeerConnection
object has a signaling state, a connection state, an ICE gathering state, and an ICE connection state. These are initialized when the object is created.
The ICE protocol implementation of an RTCPeerConnection
is represented by an ICE agent [RFC5245]. Certain RTCPeerConnection
methods involve interactions with the ICE Agent, namely addIceCandidate
, setConfiguration
, setLocalDescription
, setRemoteDescription
and close
. These interactions are described in the relevant sections in this document and in [RFC8829]. The ICE Agent also provides indications to the user agent when the state of its internal representation of an RTCIceTransport
changes, as described in § 5.6 RTCIceTransport
Interface .
The task source for the tasks listed in this section is the networking task source.
Note
The state of the SDP negotiation is represented by the signaling state and the internal variables [[CurrentLocalDescription]], [[CurrentRemoteDescription]], [[PendingLocalDescription]] and [[PendingRemoteDescription]]. These are only set inside the setLocalDescription
and setRemoteDescription
operations, and modified by the addIceCandidate
operation and the surface a candidate procedure. In each case, all the modifications to all the five variables are completed before the procedures fire any events or invoke any callbacks, so the modifications are made visible at a single point in time.
As one of the unloading document cleanup steps, run the following 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 valuetrue
.
4.4.1.1 Constructor
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, throw an
UnknownError
with themessage
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 origin.
Let configuration be the method’s first argument.
If the
certificates
value in configuration is non-empty, run the following steps for each certificate in certificates:If the value of certificate.
expires
is less than the current time, throw anInvalidAccessError
.If certificate.[[Origin]] is not same origin with connection.[[DocumentOrigin]], throw an
InvalidAccessError
.Store certificate.
Else, generate one or more new
RTCCertificate
instances with thisRTCPeerConnection
instance and store them. This MAY happen asynchronously and the value ofcertificates
remainsundefined
for the subsequent steps. As noted in Section 4.3.2.3 of [RFC8826], WebRTC utilizes self-signed rather than Public Key Infrastructure (PKI) certificates, so that the expiration check is to ensure that keys are not used indefinitely and additional certificate checks are unnecessary.Initialize connection’s ICE Agent.
If the value of configuration.
iceTransportPolicy
isundefined
, set it to “all
“.If the value of configuration.
bundlePolicy
isundefined
, set it to “balanced
“.If the value of configuration.
rtcpMuxPolicy
isundefined
, set it to “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 “
stable
“.Set connection’s ICE connection state to “
new
“.Set connection’s ICE gathering state to “
new
“.Set connection’s connection state to “
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.
4.4.1.2 Chain an asynchronous operation
An RTCPeerConnection
object has an operations chain, [[Operations]], which ensures that only one asynchronous operation in the chain executes concurrently. If subsequent calls are made while the returned promise of a previous call is still not settled, they are added to the chain and executed when all the previous calls have finished executing and their promises have settled.
To chain an operation to an RTCPeerConnection
object’s operations chain, run the following steps:
Let connection be the
RTCPeerConnection
object.If connection.[[IsClosed]] is
true
, return a promise rejected with a newly createdInvalidStateError
.Let operation be the operation to be chained.
Let p be a new promise.
Append operation to [[Operations]].
If the length of [[Operations]] is exactly 1, execute operation.
Upon fulfillment or rejection of the promise returned by the operation, run the following steps:
If connection.[[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.[[IsClosed]] is
true
, abort these steps.Remove the first element of [[Operations]].
If [[Operations]] is non-empty, execute the operation represented by the first element of [[Operations]], and abort these steps.
If connection.[[UpdateNegotiationNeededFlagOnEmptyChain]] is
false
, abort these steps.Set connection.[[UpdateNegotiationNeededFlagOnEmptyChain]] to
false
.Update the negotiation-needed flag for connection.
Return p.
4.4.1.3 Update the connection state
An RTCPeerConnection
object has an aggregated connection state. Whenever the state of an RTCDtlsTransport
changes or when the [[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
connectionstatechange
at connection.
4.4.1.4 Update the ICE gathering state
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.[[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
icegatheringstatechange
at connection.If newState is “
complete
“, fire an event namedicecandidate
using theRTCPeerConnectionIceEvent
interface with the candidate attribute set tonull
at connection.Note
The null candidate event is fired to ensure legacy compatibility. New code should monitor the gathering state of
RTCIceTransport
and/orRTCPeerConnection
.
4.4.1.5 Set the session description
To set a local session description description on an RTCPeerConnection
object connection, 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 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.
type
is “rollback
“ and connection’s signaling state is either “stable
“, “have-local-pranswer
“, or “have-remote-pranswer
“, then reject p with a newly createdInvalidStateError
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] (section 5.5. and section 5.6.), with these additional restrictions:
Use jsepSetOfTransceivers as the source of truth with regard to what “RtpTransceivers” exist, and their [[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.[[Sender]].[[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.[[IsClosed]] is
true
, then abort these steps.If description.
type
is invalid for the current signaling state of connection as described in [RFC8829] (section 5.5. and section 5.6.), then reject p with a newly createdInvalidStateError
and abort these steps.If the content of description is not valid SDP syntax, then reject p with an
RTCError
(witherrorDetail
set to “sdp-syntax-error
“ and thesdpLineNumber
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’sRTCRtcpMuxPolicy
isrequire
and the description does not use RTCP mux, then reject p with a newly createdInvalidAccessError
and abort these steps.If the description attempted to renegotiate RIDs, as described above, then reject p with a newly created
InvalidAccessError
and abort these steps.If the content of description is invalid, then reject p with a newly created
InvalidAccessError
and abort these steps.For all other errors, reject p with a newly created
OperationError
.
If description is applied successfully, the user agent MUST queue a task that runs the following steps:
If connection.[[IsClosed]] is
true
, then abort these steps.If remote is
true
and description is of type “offer
“, then if anyaddTrack
()
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 “
offer
“ and the signaling state of connection is “stable
“ then for each transceiver in connection’s set of transceivers, run the following steps:Set transceiver.[[Sender]].[[LastStableStateSenderTransport]] to transceiver.[[Sender]].[[SenderTransport]].
Set transceiver.[[Receiver]].[[LastStableStateReceiverTransport]] to transceiver.[[Receiver]].[[ReceiverTransport]].
Set transceiver.[[Receiver]].[[LastStableStateAssociatedRemoteMediaStreams]] to transceiver.[[Receiver]].[[AssociatedRemoteMediaStreams]].
Set transceiver.[[Receiver]].[[LastStableStateReceiveCodecs]] to transceiver.[[Receiver]].[[ReceiveCodecs]].
If remote is
false
, then run one of the following steps:If description is of type “
offer
“, set connection.[[PendingLocalDescription]] to a newRTCSessionDescription
object constructed from description, set connection’s signaling state to “have-local-offer
“, and release early candidates.If description is of type “
answer
“, then this completes an offer answer negotiation. Set connection.[[CurrentLocalDescription]] to a newRTCSessionDescription
object constructed from description, and set connection.[[CurrentRemoteDescription]] to connection.[[PendingRemoteDescription]]. Set both connection.[[PendingRemoteDescription]] and connection.[[PendingLocalDescription]] tonull
. Set both connection.[[LastCreatedOffer]] and connection.[[LastCreatedAnswer]] to""
, set connection’s signaling state to “stable
“, and release early candidates. Finally, if none of the ICE credentials in connection.[[LocalIceCredentialsToReplace]] are present in description, then set connection.[[LocalIceCredentialsToReplace]] to an empty set.If description is of type “
pranswer
“, then set connection.[[PendingLocalDescription]] to a newRTCSessionDescription
object constructed from description, set connection’s signaling state to “have-local-pranswer
“, and release early candidates.
Otherwise, (if remote is
true
) run one of the following steps:If description is of type “
offer
“, set connection.[[PendingRemoteDescription]] attribute to a newRTCSessionDescription
object constructed from description, and set connection’s signaling state to “have-remote-offer
“.If description is of type “
answer
“, then this completes an offer answer negotiation. Set connection.[[CurrentRemoteDescription]] to a newRTCSessionDescription
object constructed from description, and set connection.[[CurrentLocalDescription]] to connection.[[PendingLocalDescription]]. Set both connection.[[PendingRemoteDescription]] and connection.[[PendingLocalDescription]] tonull
. Set both connection.[[LastCreatedOffer]] and connection.[[LastCreatedAnswer]] to""
, and set connection’s signaling state to “stable
“. Finally, if none of the ICE credentials in connection.[[LocalIceCredentialsToReplace]] are present in the newly set connection.[[CurrentLocalDescription]], then set connection.[[LocalIceCredentialsToReplace]] to an empty set.If description is of type “
pranswer
“, then set connection.[[PendingRemoteDescription]] to a newRTCSessionDescription
object constructed from description and set connection’s signaling state to “have-remote-pranswer
“.
If description is of type “
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.[[SctpTransport]] tonull
.Let trackEventInits, muteTracks, addList, removeList and errorList be empty lists.
If description is of type “
answer
“ or “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 “
connecting
“ and assign the result to the [[SctpTransport]] slot. Otherwise, if an SCTP association is established, but themax-message-size
SDP attribute is updated, update the data max message size of connection.[[SctpTransport]].If description negotiates the DTLS role of the SCTP transport, then for each
RTCDataChannel
, channel, with anull
id
, run the following step:- Give channel a new ID generated according to [RFC8832]. If no available ID could be generated, set channel.[[ReadyState]] to “
closed
“, and add channnel to errorList.
- Give channel a new ID generated according to [RFC8832]. If no available ID could be generated, set channel.[[ReadyState]] to “
If description is not of type “
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.[[Mid]] to transceiver.[[JsepMid]].
If transceiver.[[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 underlyingRTCIceTransport
.Set transceiver.[[Sender]].[[SenderTransport]] to transport.
Set transceiver.[[Receiver]].[[ReceiverTransport]] to transport.
Let transceiver be the
RTCRtpTransceiver
associated with the media description.If transceiver.[[Stopped]] is
true
, abort these sub steps.Let direction be an
RTCRtpTransceiverDirection
value representing the direction from the media description.If direction is “
sendrecv
“ or “recvonly
“, set transceiver.[[Receptive]] totrue
, otherwise set it tofalse
.Set transceiver.[[Receiver]].[[ReceiveCodecs]] to the codecs that description negotiates for receiving and which the user agent is currently prepared to receive.
Note
If the direction is “
sendonly
“ or “inactive
“, the receiver is not prepared to receive anything, and the list will be empty.If description is of type “
answer
“ or “pranswer
“, then run the following steps:Set transceiver.[[Sender]].[[SendCodecs]] to the codecs that description negotiates for sending and which the user agent is currently capable of sending, and set transceiver.[[Sender]].[[LastReturnedParameters]] to
null
.If direction is “
sendonly
“ or “inactive
“, and transceiver.[[FiredDirection]] is either “sendrecv
“ or “recvonly
“, then run the following steps:Set the associated remote streams given transceiver.[[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.[[CurrentDirection]] and transceiver.[[FiredDirection]] to direction.
Otherwise, (if remote is
true
) run the following steps for each media description in description:If the description is of type “
offer
“ and contains a request to receive simulcast, use the order of the rid values specified in the simulcast attribute to create anRTCRtpEncodingParameters
dictionary for each of the simulcast layers, populating therid
member according to the corresponding rid value, and let sendEncodings be the list containing the created dictionaries. Otherwise, let sendEncodings be an empty list.Let supportedEncodings be the maximum number of encodings that the implementation can support. If the length of sendEncodings is greater than supportedEncodings, truncate sendEncodings so that its length is supportedEncodings.
- If sendEncodings is non-empty, set each encoding’s
scaleResolutionDownBy
to2^(length of sendEncodings - encoding index - 1)
. As described by [RFC8829] (section 5.10.), 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.[[Sender]].[[SendEncodings]] to sendEncodings, and set transceiver.[[Sender]].[[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 “recvonly
“, and let transceiver be the result.Add transceiver to the connection’s set of transceivers.
If description is of type “
answer
“ or “pranswer
“, and transceiver. [[Sender]].[[SendEncodings]] .length is greater than1
, then run the following steps:If description indicates that simulcast is not supported or desired, then remove all dictionaries in transceiver.[[Sender]].[[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.[[Sender]].[[SendEncodings]].
Update the paused status as indicated by [RFC8853] of each simulcast layer by setting the
active
member on the corresponding dictionaries in transceiver.[[Sender]].[[SendEncodings]] totrue
for unpaused or tofalse
for paused.
Set transceiver.[[Mid]] to transceiver.[[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 “inactive
“.If direction is “
sendrecv
“ or “recvonly
“, let msids be a list of the MSIDs that the media description indicates transceiver.[[Receiver]].[[ReceiverTrack]] is to be associated with. Otherwise, let msids be an empty list.Note
msids will be an empty list here if media description is rejected.
Process remote tracks with transceiver, direction, msids, addList, removeList, and trackEventInits.
Set transceiver.[[Receiver]].[[ReceiveCodecs]] to the codecs that description negotiates for receiving and which the user agent is currently prepared to receive.
If description is of type “
answer
“ or “pranswer
“, then run the following steps:Set transceiver.[[Sender]].[[SendCodecs]] to the codecs that description negotiates for sending and which the user agent is currently capable of sending.
Set transceiver.[[CurrentDirection]] and transceiver.[[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.[[Sender]].[[SenderTransport]] to transport.
Set transceiver.[[Receiver]].[[ReceiverTransport]] to transport.
Set the [[IceRole]] of transport according to the rules of [RFC8445].
Note
The rules of [RFC8445] that apply here are:
- If [[IceRole]] is not
unknown
, do not modify [[IceRole]]. - If description is a local offer, set it to
controlling
. - If description is a remote offer, and contains
a=ice-lite
, set [[IceRole]] tocontrolling
. - If description is a remote offer, and does not contain
a=ice-lite
, set [[IceRole]] tocontrolled
.
This ensures that [[IceRole]] always has a value after the first offer is processed.
- If [[IceRole]] is not
If the media description is rejected, and transceiver.[[Stopped]] is
false
, then stop the RTCRtpTransceiver transceiver.
Otherwise, (if description is of type “
rollback
“) run the following steps:Let pendingDescription be either connection.[[PendingLocalDescription]] or connection.[[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.[[JsepMid]] and transceiver.[[Mid]] to
null
.Set transceiver.[[Sender]].[[SenderTransport]] to transceiver.[[Sender]].[[LastStableStateSenderTransport]].
Set transceiver.[[Receiver]].[[ReceiverTransport]] to transceiver.[[Receiver]].[[LastStableStateReceiverTransport]].
Set transceiver.[[Receiver]].[[ReceiveCodecs]] to transceiver.[[Receiver]].[[LastStableStateReceiveCodecs]].
If the signaling state of connection is “
have-remote-offer
“, run the following sub steps:Let msids be a list of the
id
s of allMediaStream
objects in transceiver.[[Receiver]].[[LastStableStateAssociatedRemoteMediaStreams]], or an empty list if there are none.Process remote tracks with transceiver, transceiver.[[CurrentDirection]], msids, addList, removeList, and trackEventInits.
If transceiver was created when pendingDescription was set, and a track has never been attached to it via
addTrack
()
, then stop the RTCRtpTransceiver transceiver, and remove it from connection’s set of transceivers.
Set connection.[[PendingLocalDescription]] and connection.[[PendingRemoteDescription]] to
null
, and set connection’s signaling state to “stable
“.
If description is of type “
answer
“, then run the following steps:For each transceiver in the connection’s set of transceivers run the following steps:
- If transceiver is
stopped
, associated with an m= section and the associated m= section is rejected in connection.[[CurrentLocalDescription]] or connection.[[CurrentRemoteDescription]], remove the transceiver from the connection’s set of transceivers.
- If transceiver is
If connection’s signaling state is now “
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.[[Sender]].[[SenderTransport]] or transceiver.[[Receiver]].[[ReceiverTransport]]) are still not closed and they’re no longer referenced by a non-stopped transceiver, close the
RTCDtlsTransport
s and their associatedRTCIceTransport
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
signalingstatechange
at connection.For each channel in errorList, fire an event named
error
using theRTCErrorEvent
interface with theerrorDetail
attribute set to “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
track
using theRTCTrackEvent
interface with itsreceiver
attribute initialized to entry.receiver
, itstrack
attribute initialized to entry.track
, itsstreams
attribute initialized to entry.streams
and itstransceiver
attribute initialized to entry.transceiver
at the connection object.Resolve p with
undefined
.
Return p.
4.4.1.6 Set the configuration
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.
certificates
is set, run the following steps:If the length of configuration.
certificates
is different from the length of connection.[[Configuration]].certificates
, throw anInvalidModificationError
.Let index be initialized to 0.
Let size be initialized to the length of configuration.
certificates
.While index is less than size, run the following steps:
If the ECMAScript object represented by the value of configuration.
certificates
at index is not the same as the ECMAScript object represented by the value of connection.[[Configuration]].certificates
at index, throw anInvalidModificationError
.Increment index by 1.
If the value of configuration.
bundlePolicy
is set and its value differs from the connection’s bundle policy, throw anInvalidModificationError
.If the value of configuration.
rtcpMuxPolicy
is set and its value differs from the connection’s rtcpMux policy, throw anInvalidModificationError
.If the value of configuration.
iceCandidatePoolSize
is set and its value differs from the connection’s previously seticeCandidatePoolSize
, andsetLocalDescription
has already been called, throw anInvalidModificationError
.Set the ICE Agent‘s ICE transports setting to the value of configuration.
iceTransportPolicy
. As defined in [RFC8829] (section 4.1.18.), 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] (section 3.5.4. and section 4.1.1.) to the value of configuration.
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] (section 4.1.18.).Let validatedServers be an empty list.
If configuration.
iceServers
is defined, then run the following steps for each element:Let server be the current list element.
Let urls be server.
urls
.If urls is a string, set urls to a list consisting of just that string.
If urls is empty, 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, throw a
SyntaxError
. If the scheme name is not implemented by the browser throw aNotSupportedError
. If scheme name isturn
orturns
, and parsing the url using the syntax defined in [RFC7065] fails, throw aSyntaxError
. If scheme name isstun
orstuns
, and parsing the url using the syntax defined in [RFC7064] fails, throw aSyntaxError
.If scheme name is
turn
orturns
, and either of server.username
or server.credential
are omitted, then throw anInvalidAccessError
.If scheme name is
turn
orturns
, and server.credentialType
is “password
“, and server.credential
is not a DOMString, then throw anInvalidAccessError
.
Append server to validatedServers.
Set the ICE Agent‘s ICE servers list to validatedServers.
As defined in [RFC8829] (section 4.1.18.), 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 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 [[Configuration]] internal slot.
4.4.2 Interface Definition
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.
- WebIDL[Exposed=Window]
- interface
RTCPeerConnection
: EventTarget {constructor
(optionalRTCConfiguration
configuration = {});- Promise<
RTCSessionDescriptionInit
>createOffer
(optionalRTCOfferOptions
options = {});- Promise<
RTCSessionDescriptionInit
>createAnswer
(optionalRTCAnswerOptions
options = {});- Promise<undefined>
setLocalDescription
(optionalRTCLocalSessionDescriptionInit
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
(optionalRTCIceCandidateInit
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
(optionalRTCConfiguration
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);- };
Attributes
localDescription
of type RTCSessionDescription
, readonly, nullable
The localDescription
attribute MUST return [[PendingLocalDescription]] if it is not null
and otherwise it MUST return [[CurrentLocalDescription]].
Note that [[CurrentLocalDescription]].sdp
and [[PendingLocalDescription]].sdp
need not be string-wise identical to the sdp
value passed to the corresponding setLocalDescription
call (i.e. SDP may be parsed and reformatted, and ICE candidates may be added).
currentLocalDescription
of type RTCSessionDescription
, readonly, nullable
The currentLocalDescription
attribute MUST return [[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.
pendingLocalDescription
of type RTCSessionDescription
, readonly, nullable
The pendingLocalDescription
attribute MUST return [[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
.
remoteDescription
of type RTCSessionDescription
, readonly, nullable
The remoteDescription
attribute MUST return [[PendingRemoteDescription]] if it is not null
and otherwise it MUST return [[CurrentRemoteDescription]].
Note that [[CurrentRemoteDescription]].sdp
and [[PendingRemoteDescription]].sdp
need not be string-wise identical to the sdp
value passed to the corresponding setRemoteDescription
call (i.e. SDP may be parsed and reformatted, and ICE candidates may be added).
currentRemoteDescription
of type RTCSessionDescription
, readonly, nullable
The currentRemoteDescription
attribute MUST return [[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 addIceCandidate
()
since the offer or answer was created.
pendingRemoteDescription
of type RTCSessionDescription
, readonly, nullable
The pendingRemoteDescription
attribute MUST return [[PendingRemoteDescription]].
It represents a remote description that is in the process of being negotiated, complete with any remote candidates that have been supplied via addIceCandidate
()
since the offer or answer was created. If the RTCPeerConnection
is in the stable state, the value is null
.
signalingState
of type RTCSignalingState
, readonly
The signalingState
attribute MUST return the RTCPeerConnection
object’s signaling state.
iceGatheringState
of type RTCIceGatheringState
, readonly
The iceGatheringState
attribute MUST return the ICE gathering state of the RTCPeerConnection
instance.
iceConnectionState
of type RTCIceConnectionState
, readonly
The iceConnectionState
attribute MUST return the ICE connection state of the RTCPeerConnection
instance.
connectionState
of type RTCPeerConnectionState
, readonly
The connectionState
attribute MUST return the connection state of the RTCPeerConnection
instance.
canTrickleIceCandidates
of type boolean, readonly, nullable
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] (section 4.1.17.). Prior to the completion of setRemoteDescription
, this value is null
.
onnegotiationneeded
of type EventHandler
The event type of this event handler is negotiationneeded
.
onicecandidate
of type EventHandler
The event type of this event handler is icecandidate
.
onicecandidateerror
of type EventHandler
The event type of this event handler is icecandidateerror
.
onsignalingstatechange
of type EventHandler
The event type of this event handler is signalingstatechange
.
oniceconnectionstatechange
of type EventHandler
The event type of this event handler is iceconnectionstatechange
onicegatheringstatechange
of type EventHandler
The event type of this event handler is icegatheringstatechange
.
onconnectionstatechange
of type EventHandler
The event type of this event handler is connectionstatechange
.
Methods
createOffer
The createOffer
method generates a blob of SDP that contains an RFC 3264 offer with the supported configurations for the session, including descriptions of the local MediaStreamTrack
s attached to this RTCPeerConnection
, the codec/RTP/RTCP capabilities supported by this implementation, and parameters of the ICE agent and the DTLS connection. The options parameter may be supplied to provide additional control over the offer generated.
If a system has limited resources (e.g. a finite number of decoders), createOffer
needs to return an offer that reflects the current state of the system, so that setLocalDescription
will succeed when it attempts to acquire those resources. 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.
Creating the SDP MUST follow the appropriate process for generating an offer described in [RFC8829], except the user agent MUST treat a stopping
transceiver as stopped
for the purposes of RFC8829 in this case.
As an offer, the generated SDP will contain the full set of codec/RTP/RTCP capabilities supported or preferred by the session (as opposed to an answer, which will include only a specific negotiated subset to use). In the event createOffer
is called after the session is established, createOffer
will generate an offer that is compatible with the current session, incorporating any changes that have been made to the session since the last complete offer-answer exchange, such as addition or removal of tracks. If no changes have been made, the offer will include the capabilities of the current local description as well as any additional capabilities that could be negotiated in an updated offer.
The generated SDP will also contain the ICE agent‘s usernameFragment
, 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 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.
The process of generating an SDP exposes a subset of the media capabilities of the underlying system, which provides generally persistent cross-origin information on the device. It thus increases the fingerprinting surface of the application. In privacy-sensitive contexts, browsers can consider mitigations such as generating SDP matching only a common subset of the capabilities.
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.[[IsClosed]] is
true
, return a promise rejected with a newly createdInvalidStateError
.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 “
stable
“ nor “have-local-offer
“, return a promise rejected with a newly createdInvalidStateError
.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] (section 4.1.8.).
If this inspection failed for any reason, reject p with a newly 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.[[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.
Note
This may be necessary if, for example,
createOffer
was called when only an audioRTCRtpTransceiver
was added to connection, but while performing the in-parallel steps to create an offer, a videoRTCRtpTransceiver
was added, requiring additional inspection of video system resources.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] (section 5.2.).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
.[[PreferredCodecs]] with the following filtering applied (or said not to be set if [[PreferredCodecs]] is empty):If the
direction
is “sendrecv
“, exclude any codecs not included in the intersection ofRTCRtpSender
.getCapabilities
(kind).codecs
andRTCRtpReceiver
.getCapabilities
(kind).codecs
.If the
direction
is “sendonly
“, exclude any codecs not included inRTCRtpSender
.getCapabilities
(kind).codecs
.If the
direction
is “recvonly
“, exclude any codecs not included inRTCRtpReceiver
.getCapabilities
(kind).codecs
.
The filtering *MUST NOT* change the order of the codec preferences.
3. If the length of the [\[\[SendEncodings\]\]](#dfn-sendencodings) slot of the [`RTCRtpSender`](#dom-rtcrtpsender) is larger than 1, then for each encoding given in [\[\[SendEncodings\]\]](#dfn-sendencodings) of the [`RTCRtpSender`](#dom-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 [`encodings`](#dom-rtcrtpsendparameters-encodings) field. No RID restrictions are set.
Note
\[[RFC8853](#bib-rfc8853 "Using Simulcast in Session Description Protocol (SDP) and RTP Sessions")\] 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 itstype
member initialized to the string “offer
“ and itssdp
member initialized to sdpString.Set the [[LastCreatedOffer]] internal slot to sdpString.
Resolve p with offer.
createAnswer
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 usernameFragment
, 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 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] (section 4.1.10.1.), by setting the type
to “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.[[IsClosed]] is
true
, return a promise rejected with a newly createdInvalidStateError
.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 “
have-remote-offer
“ nor “have-local-pranswer
“, return a promise rejected with a newly createdInvalidStateError
.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] (section 4.1.9.).
If this inspection failed for any reason, reject p with a newly 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.[[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.
Note
This may be necessary if, for example,
createAnswer
was called when anRTCRtpTransceiver
‘s direction was “recvonly
“, but while performing the in-parallel steps to create an answer, the direction was changed to “sendrecv
“, requiring additional inspection of video encoding resources.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] (section 5.3.).The codec preferences of an m= section’s associated transceiver is said to be the value of the
RTCRtpTransceiver
.[[PreferredCodecs]] with the following filtering applied (or said not to be set if [[PreferredCodecs]] is empty):If the
direction
is “sendrecv
“, exclude any codecs not included in the intersection ofRTCRtpSender
.getCapabilities
(kind).codecs
andRTCRtpReceiver
.getCapabilities
(kind).codecs
.If the
direction
is “sendonly
“, exclude any codecs not included inRTCRtpSender
.getCapabilities
(kind).codecs
.If the
direction
is “recvonly
“, exclude any codecs not included inRTCRtpReceiver
.getCapabilities
(kind).codecs
.
The filtering *MUST NOT* change the order of the codec preferences.
2. If the length of the [\[\[SendEncodings\]\]](#dfn-sendencodings) slot of the [`RTCRtpSender`](#dom-rtcrtpsender) is larger than 1, then for each encoding given in [\[\[SendEncodings\]\]](#dfn-sendencodings) of the [`RTCRtpSender`](#dom-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 [`encodings`](#dom-rtcrtpsendparameters-encodings) field. No RID restrictions are set.
Let answer be a newly created
RTCSessionDescriptionInit
dictionary with itstype
member initialized to the string “answer
“ and itssdp
member initialized to sdpString.Set the [[LastCreatedAnswer]] internal slot to sdpString.
Resolve p with answer.
setLocalDescription
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] (section 5.4.), 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.
sdp
.Return the result of chaining the following steps to connection’s operations chain:
Let type be description.
type
if present, or “offer
“ if not present and connection’s signaling state is either “stable
“, “have-local-offer
“, or “have-remote-pranswer
“; otherwise “answer
“.If type is “
offer
“, and sdp is not the empty string and not equal to connection.[[LastCreatedOffer]], then return a promise rejected with a newly createdInvalidModificationError
and abort these steps.If type is “
answer
“ or “pranswer
“, and sdp is not the empty string and not equal to connection.[[LastCreatedAnswer]], then return a promise rejected with a newly createdInvalidModificationError
and abort these steps.If sdp is the empty string, and type is “
offer
“, then run the following sub steps:Set sdp to the value of connection.[[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 reacting to p with a fulfillment step that sets the local session description indicated by its first argument.
If sdp is the empty string, and type is “
answer
“ or “pranswer
“, then run the following sub steps:Set sdp to the value of connection.[[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 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.[`sdp`](#dom-rtcsessiondescriptioninit-sdp)}
.
Return the result of setting the local session description indicated by
{type, sdp}
.
Note
As noted in [RFC8829] (section 5.9.), calling this method may trigger the ICE candidate gathering process by the ICE Agent.
setRemoteDescription
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.
type
is “offer
“ and is invalid for the current signaling state of connection as described in [RFC8829] (section 5.5. and section 5.6.), then run the following sub steps:Let p be the result of setting the local session description indicated by
{type: "[`rollback`](#dom-rtcsdptype-rollback)"}
.Return the result of reacting to p with a fulfillment step that sets the remote session description description, and abort these steps.
Return the result of setting the remote session description description.
addIceCandidate
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 candidate
member. The only members of the argument used by this method are candidate
, sdpMid
, sdpMLineIndex
, and 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.
candidate
is not an empty string and both candidate.sdpMid
and candidate.sdpMLineIndex
arenull
, return a promise rejected with a newly createdTypeError
.Return the result of chaining the following steps to connection’s operations chain:
If
remoteDescription
isnull
return a promise rejected with a newly createdInvalidStateError
.If candidate.
sdpMid
is notnull
, run the following steps:- If candidate.
sdpMid
is not equal to the mid of any media description inremoteDescription
, return a promise rejected with a newly createdOperationError
.
- If candidate.
Else, if candidate.
sdpMLineIndex
is notnull
, run the following steps:- If candidate.
sdpMLineIndex
is equal to or larger than the number of media descriptions inremoteDescription
, return a promise rejected with a newly createdOperationError
.
- If candidate.
If either candidate.
sdpMid
or candidate.sdpMLineIndex
indicate a media description inremoteDescription
whose associated transceiver isstopped
, return a promise resolved withundefined
.If candidate.
usernameFragment
is notnull
, 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 createdOperationError
.Let p be a new promise.
In parallel, if the candidate is not administratively prohibited, add the ICE candidate candidate as described in [RFC8829] (section 4.1.19.). Use candidate.
usernameFragment
to identify the ICE generation; ifusernameFragment
isnull
, process the candidate for the most recent ICE generation.If candidate.
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.sdpMid
and candidate.sdpMLineIndex
arenull
, then this end-of-candidates indication applies to all media descriptions.If candidate could not be successfully added the user agent MUST queue a task that runs the following steps:
If connection.[[IsClosed]] is
true
, then abort these steps.Reject p with a newly 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.[[IsClosed]] is
true
, then abort these steps.If connection.[[PendingRemoteDescription]] is not
null
, and represents the ICE generation for which candidate was processed, add candidate to connection.[[PendingRemoteDescription]].sdp.If connection.[[CurrentRemoteDescription]] is not
null
, and represents the ICE generation for which candidate was processed, add candidate to connection.[[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 iceTransportPolicy
member of the RTCConfiguration
is relay
, candidates requiring external resolution, such as mDNS candidates and DNS candidates, MUST be prohibited.
Note
Due to WebIDL processing, 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.
restartIce
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.[[LocalIceCredentialsToReplace]], and populate it with all ICE credentials (ice-ufrag and ice-pwd as defined in section 15.4 of [RFC5245]) found in connection.[[CurrentLocalDescription]], as well as all ICE credentials found in connection.[[PendingLocalDescription]].
Update the negotiation-needed flag for connection.
getConfiguration
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 [[Configuration]] internal slot.
setConfiguration
The setConfiguration
method updates the configuration of this RTCPeerConnection
object. This includes changing the configuration of the ICE Agent. As noted in [RFC8829] (section 3.5.1.), 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.[[IsClosed]] is
true
, throw anInvalidStateError
.Set the configuration specified by configuration.
close
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.close the connection with connection and the value
false
.
The close the connection algorithm given a connection and a disappear boolean, is as follows:
If connection.[[IsClosed]] is
true
, abort these steps.Set connection.[[IsClosed]] to
true
.Set connection’s signaling state to “
closed
“. This does not fire any event.Let transceivers be the result of executing the
CollectTransceivers
algorithm. For everyRTCRtpTransceiver
transceiver in transceivers, run the following steps:If transceiver.[[Stopped]] is
true
, abort these sub steps.Stop the RTCRtpTransceiver with transceiver and disappear.
Set the [[ReadyState]] slot of each of connection’s
RTCDataChannel
s to “closed
“.Note
The
RTCDataChannel
s will be closed abruptly and the closing procedure will not be invoked.If connection.[[SctpTransport]] is not
null
, tear down the underlying SCTP association by sending an SCTP ABORT chunk and set the [[SctpTransportState]] to “closed
“.Set the [[DtlsTransportState]] slot of each of connection’s
RTCDtlsTransport
s to “closed
“.Destroy connection’s ICE Agent, abruptly ending any active ICE processing and releasing any relevant resources (e.g. TURN permissions).
Set the [[IceTransportState]] slot of each of connection’s
RTCIceTransport
s to “closed
“.Set connection’s ICE connection state to “
closed
“. This does not fire any event.Set connection’s connection state to “
closed
“. This does not fire any event.
4.4.3 Legacy Interface Extensions
Note
The IDL definition of these methods are documented in the main definition of the RTCPeerConnection
interface since overloaded functions are not allowed to be defined in partial interfaces.
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.
Note
The 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));
};
4.4.3.1 Method extensions
Methods
createOffer
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
‘screateOffer
()
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
.
setLocalDescription
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
‘ssetLocalDescription
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
Note
The legacy 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
‘screateAnswer
()
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
.
setRemoteDescription
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
‘ssetRemoteDescription
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
.
addIceCandidate
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
‘saddIceCandidate
()
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
.
Callback Definitions
These callbacks are only used on the legacy APIs.
RTCPeerConnectionErrorCallback
- WebIDLcallback
RTCPeerConnectionErrorCallback
= undefined (DOMException error);
Callback RTCPeerConnectionErrorCallback
Parameters
error
of type DOMException
An error object encapsulating information about what went wrong.
RTCSessionDescriptionCallback
- WebIDLcallback
RTCSessionDescriptionCallback
= undefined (RTCSessionDescriptionInit
description);
Callback RTCSessionDescriptionCallback
Parameters
description of type RTCSessionDescriptionInit
The object containing the SDP [SDP].
4.4.3.2 Legacy configuration extensions
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 createOffer
is called with any of the legacy options specified in this section, run the followings steps instead of the regular 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:If the value of the dictionary member is false,
For each non-stopped “
sendrecv
“ transceiver of transceiver kind kind, set transceiver.[[Direction]] to “sendonly
“.For each non-stopped “
recvonly
“ transceiver of transceiver kind kind, set transceiver.[[Direction]] to “inactive
“.
Continue with the next option, if any.
2. If connection has any non-stopped "[`sendrecv`](#dom-rtcrtptransceiverdirection-sendrecv)" or "[`recvonly`](#dom-rtcrtptransceiverdirection-recvonly)" transceivers of [transceiver kind](#dfn-transceiver-kind) kind, continue with the next option, if any.
3. Let transceiver be the result of invoking the equivalent of connection.[`addTransceiver`](#dom-rtcpeerconnection-addtransceiver)(kind), except that this operation *MUST NOT* [update the negotiation-needed flag](#dfn-update-the-negotiation-needed-flag).
4. If transceiver is unset because the previous operation threw an error, abort these steps.
5. Set transceiver.[\[\[Direction\]\]](#dfn-direction) to "[`recvonly`](#dom-rtcrtptransceiverdirection-recvonly)".
- Run the steps specified by
createOffer
to create the offer.
- WebIDLpartial dictionary
RTCOfferOptions
{- boolean
offerToReceiveAudio
;- boolean
offerToReceiveVideo
;- };
Attributes
offerToReceiveAudio
of type boolean
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.
offerToReceiveVideo
of type boolean
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.
4.4.4 Garbage collection
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 [[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.