4.4.1 Operation
Calling new [`RTCPeerConnection`](#dom-rtcpeerconnection)(configuration)
creates an RTCPeerConnection
object.
configuration. 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 is represented by an ICE agent [RFC5245]. Certain methods involve interactions with the ICE Agent, namely , setConfiguration
, , setRemoteDescription
and . These interactions are described in the relevant sections in this document and in [RFC8829]. The also provides indications to the user agent when the state of its internal representation of an RTCIceTransport
changes, as described in .
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 and the internal variables [[CurrentLocalDescription]], , [[PendingLocalDescription]] and . These are only set inside the setLocalDescription
and operations, and modified by the addIceCandidate
operation and the 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 .
For each
RTCPeerConnection
object connection whose 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, an
UnknownError
with the attribute set to an appropriate description.Let connection be a newly created
RTCPeerConnection
object.Let connection have a [[DocumentOrigin]] internal slot, initialized to the ‘s origin.
Let configuration be the method’s first argument.
If the 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, anInvalidAccessError
.If certificate. is not same origin with connection., throw an .
Store certificate.
Else, generate one or more new
RTCCertificate
instances with this 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 [], 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. is
undefined
, set it to “all
“.If the value of configuration. is
undefined
, set it to “balanced
“.If the value of configuration. is
undefined
, set it to “require
“.Let connection have a [[Configuration]] internal slot. 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 to “
stable
“.Set connection’s to “
new
“.Set connection’s to “
new
“.Set connection’s 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 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 , 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 object’s operations chain, run the following steps:
Let connection be the object.
If connection.[[IsClosed]] is
true
, return a promise with a newly created .Let operation be the operation to be chained.
Let p be a new promise.
Append operation to [[Operations]].
If the length of is exactly 1, execute operation.
Upon fulfillment or 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 with a value, fulfill p with that value.
If the promise returned by operation was with a value, reject p with that value.
Upon or rejection of p, execute the following steps:
If connection. is
true
, abort these steps.Remove the first element of [[Operations]].
If is non-empty, execute the operation represented by the first element of [[Operations]], and abort these steps.
If connection. is
false
, abort these steps.Set connection.[[UpdateNegotiationNeededFlagOnEmptyChain]] to
false
.for connection.
Return p.
4.4.1.3 Update the connection state
An RTCPeerConnection
object has an aggregated . Whenever the state of an RTCDtlsTransport
changes or when the 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 enum.
If connection’s connection state is equal to newState, abort these steps.
Let connection’s be newState.
Fire an event named at connection.
4.4.1.4 Update the ICE gathering state
To update the ICE gathering state of an 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 enum.
If connection’s ICE gathering state is equal to newState, abort these steps.
Set connection’s to newState.
Fire an event named at connection.
If newState is “
complete
“, namedicecandidate
using the 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/or .
4.4.1.5 Set the session description
To set a local session description description on an RTCPeerConnection
object connection, description on connection with the additional value false
.
To set a remote session description description on an RTCPeerConnection
object connection, 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. is “
rollback
“ and connection’s is either “stable
“, ““, or “have-remote-pranswer
“, then p with a newly created 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 [] (section 5.5. and ), 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..[[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. is
true
, then abort these steps.If description.
type
is invalid for the current of connection as described in [RFC8829] ( and section 5.6.), then p with a newly created and abort these steps.If the content of description is not valid SDP syntax, then reject p with an (with
errorDetail
set to ““ 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’s isrequire
and the description does not use RTCP mux, then p with a newly created and abort these steps.If the description attempted to renegotiate RIDs, as described above, then reject p with a newly
InvalidAccessError
and abort these steps.If the content of description is invalid, then p with a newly created and abort these steps.
For all other errors, reject p with a newly
OperationError
.
If description is applied successfully, the user agent MUST queue a task that runs the following steps:
If connection. is
true
, then abort these steps.If remote is
true
and description is of type “offer
“, then if any()
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 of connection is “stable
“ then for each transceiver in connection’s , run the following steps:Set transceiver.[[Sender]]. to transceiver.[[Sender]]..
Set transceiver.[[Receiver]]. to transceiver.[[Receiver]]..
Set transceiver.[[Receiver]]. to transceiver.[[Receiver]]..
Set transceiver.[[Receiver]]. to transceiver.[[Receiver]]..
If remote is
false
, then run one of the following steps:If description is of type “
offer
“, set connection. to a newRTCSessionDescription
object constructed from description, set connection’s to “have-local-offer
“, and .If description is of type “
answer
“, then this completes an offer answer negotiation. Set connection. to a newRTCSessionDescription
object constructed from description, and set connection. to connection.[[PendingRemoteDescription]]. Set both connection. and connection.[[PendingLocalDescription]] tonull
. Set both connection. and connection.[[LastCreatedAnswer]] to""
, set connection’s to “stable
“, and . 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 ““, then set connection.[[PendingLocalDescription]] to a new object constructed from description, set connection’s signaling state to ““, and release early candidates.
Otherwise, (if remote is
true
) run one of the following steps:If description is of type ““, set connection.[[PendingRemoteDescription]] attribute to a new object constructed from description, and set connection’s signaling state to ““.
If description is of type “
answer
“, then this completes an offer answer negotiation. Set connection. to a newRTCSessionDescription
object constructed from description, and set connection. to connection.[[PendingLocalDescription]]. Set both connection. and connection.[[PendingLocalDescription]] tonull
. Set both connection. and connection.[[LastCreatedAnswer]] to""
, and set connection’s to “stable
“. Finally, if none of the ICE credentials in connection.[[LocalIceCredentialsToReplace]] are present in the newly set connection., then set connection.[[LocalIceCredentialsToReplace]] to an empty set.If description is of type ““, then set connection.[[PendingRemoteDescription]] to a new object constructed from description and set connection’s signaling state to ““.
If description is of type “
answer
“, and it initiates the closure of an existing SCTP association, as defined in [], 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 ““ or “
pranswer
“, then run the following steps:If description initiates the establishment of a new SCTP association, as defined in [], Sections 10.3 and 10.4, create an RTCSctpTransport with an initial state of ““ and assign the result to the [[SctpTransport]] slot. Otherwise, if an SCTP association is established, but the
max-message-size
SDP attribute is updated, of connection.[[SctpTransport]].If description negotiates the DTLS role of the SCTP transport, then for each , channel, with a
null
id
, run the following step:- Give channel a new ID generated according to []. If no available ID could be generated, set channel.[[ReadyState]] to ““, and add channnel to errorList.
If description is not of type “
rollback
“, then run the following steps:If remote is
false
, then run the following steps for each in description:If the media description was not yet with an
RTCRtpTransceiver
object then run the following steps:Let transceiver be the used to create the media description.
Set transceiver. to transceiver.[[JsepMid]].
If transceiver. is
true
, abort these sub steps.If the media description is indicated as using an existing according to [RFC8843], let transport be the object representing the RTP/RTCP component of that transport.
Otherwise, let transport be a newly created
RTCDtlsTransport
object with a new underlying .Set transceiver.[[Sender]]. to transport.
Let transceiver be the
RTCRtpTransceiver
with the media description.If transceiver. is
true
, abort these sub steps.Let direction be an
RTCRtpTransceiverDirection
value representing the direction from the .If direction is “
sendrecv
“ or ““, set transceiver.[[Receptive]] totrue
, otherwise set it tofalse
.Set transceiver..[[ReceiveCodecs]] to the codecs that description negotiates for receiving and which the user agent is currently prepared to receive.
Note
If the direction is ““ or “
inactive
“, the receiver is not prepared to receive anything, and the list will be empty.If description is of type ““ or “
pranswer
“, then run the following steps:Set transceiver..[[SendCodecs]] to the codecs that description negotiates for sending and which the user agent is currently capable of sending, and set transceiver..[[LastReturnedParameters]] to
null
.If direction is ““ or “
inactive
“, and transceiver. is either “sendrecv
“ or ““, then run the following steps:Set the associated remote streams given transceiver., an empty list, another empty list, and removeList.
process the removal of a remote track for the , given transceiver and muteTracks.
Set transceiver.[[CurrentDirection]] and transceiver. to direction.
Otherwise, (if remote is
true
) run the following steps for each media description in description:If the description is of type ““ 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 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 [] (section 5.10.), attempt to find an existing object, transceiver, to represent the media description.
If a suitable transceiver was found (transceiver is set) and sendEncodings is non-empty, set transceiver..[[SendEncodings]] to sendEncodings, and set transceiver..[[LastReturnedParameters]] to
null
.If no suitable transceiver was found (transceiver is unset), run the following steps:
, sender, from the media description using sendEncodings.
, receiver, from the media description.
with sender, receiver and an
RTCRtpTransceiverDirection
value of ““, and let transceiver be the result.Add transceiver to the connection’s set of transceivers.
If description is of type ““ or “
pranswer
“, and transceiver. .[[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..[[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..[[SendEncodings]].
Update the paused status as indicated by [] of each simulcast layer by setting the
active
member on the corresponding dictionaries in transceiver..[[SendEncodings]] totrue
for unpaused or tofalse
for paused.
Set transceiver. to transceiver.[[JsepMid]].
Let direction be an 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 is rejected, set direction to “
inactive
“.If direction is ““ or “
recvonly
“, let msids be a list of the MSIDs that the media description indicates transceiver..[[ReceiverTrack]] is to be associated with. Otherwise, let msids be an empty list.Note
msids will be an empty list here if is rejected.
Process remote tracks with transceiver, direction, msids, addList, removeList, and trackEventInits.
Set transceiver..[[ReceiveCodecs]] to the codecs that description negotiates for receiving and which the user agent is currently prepared to receive.
If description is of type ““ or “
pranswer
“, then run the following steps:Set transceiver..[[SendCodecs]] to the codecs that description negotiates for sending and which the user agent is currently capable of sending.
Set transceiver. and transceiver.[[Direction]]s to direction.
Let transport be the object representing the RTP/RTCP component of the media transport used by transceiver’s media description, according to [].
Set transceiver.[[Sender]]. to transport.
Set transceiver.[[Receiver]]. to transport.
Set the [[IceRole]] of transport according to the rules of [].
The rules of [RFC8445] that apply here are:
- If is not
unknown
, do not modify . - If description is a local offer, set it to
controlling
. - If description is a remote offer, and contains
a=ice-lite
, set tocontrolling
. - If description is a remote offer, and does not contain
a=ice-lite
, set tocontrolled
.
This ensures that always has a value after the first offer is processed.
- If is not
If the media description is rejected, and transceiver. is
false
, then stop the RTCRtpTransceiver transceiver.
Otherwise, (if description is of type ““) run the following steps:
Let pendingDescription be either connection.[[PendingLocalDescription]] or connection., whichever one is not
null
.For each transceiver in the connection’s set of transceivers run the following steps:
If transceiver was not with a media description prior to pendingDescription being set, disassociate it and set both transceiver. and transceiver.[[Mid]] to
null
.Set transceiver..[[SenderTransport]] to transceiver..[[LastStableStateSenderTransport]].
Set transceiver..[[ReceiverTransport]] to transceiver..[[LastStableStateReceiverTransport]].
Set transceiver..[[ReceiveCodecs]] to transceiver..[[LastStableStateReceiveCodecs]].
If the of connection is “
have-remote-offer
“, run the following sub steps:Let msids be a list of the
id
s of all objects in transceiver.[[Receiver]]., or an empty list if there are none.Process remote tracks with transceiver, transceiver., 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 transceiver, and remove it from connection’s set of transceivers.
Set connection. and connection.[[PendingRemoteDescription]] to
null
, and set connection’s to “stable
“.
If description is of type ““, then run the following steps:
For each transceiver in the connection’s set of transceivers run the following steps:
- If transceiver is , associated with an m= section and the associated m= section is rejected in connection. or connection.[[CurrentRemoteDescription]], remove the transceiver from the connection’s .
If connection’s signaling state is now ““, 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..[[SenderTransport]] or transceiver..[[ReceiverTransport]]) are still not closed and they’re no longer referenced by a non-stopped transceiver, close the s and their associated s. This results in events firing on these objects in a queued task.
If connection’s changed above, fire an event named at connection.
For each channel in errorList, fire an event named using the
RTCErrorEvent
interface with the attribute set to “data-channel-failure
“ at channel.For each track in muteTracks, 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, track to stream.
For each entry entry in trackEventInits, fire an event named using the
RTCTrackEvent
interface with its attribute initialized to entry.receiver
, its attribute initialized to entry.track
, its attribute initialized to entry.streams
and its attribute initialized to entry.transceiver
at the connection object.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 object.
If configuration.
certificates
is set, run the following steps:If the length of configuration. is different from the length of connection.[[Configuration]]., throw an .
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. at index is not the same as the ECMAScript object represented by the value of connection.[[Configuration]]. at index, throw an .
Increment index by 1.
If the value of configuration.
bundlePolicy
is set and its value differs from the connection’s bundle policy, anInvalidModificationError
.If the value of configuration. is set and its value differs from the connection’s rtcpMux policy, throw an .
If the value of configuration.
iceCandidatePoolSize
is set and its value differs from the connection’s previously set , andsetLocalDescription
has already been called, anInvalidModificationError
.Set the ‘s ICE transports setting to the value of configuration.
iceTransportPolicy
. As defined in [] (section 4.1.18.), if the new 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 [] (section 3.5.4. and ) to the value of configuration.
iceCandidatePoolSize
. If the new 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.
iceServers
is defined, then run the following steps for each element:Let server be the current list element.
Let urls be server..
If urls is a string, set urls to a list consisting of just that string.
If urls is empty, throw a .
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 [] fails, throw a . If the scheme name is not implemented by the browser throw a . If scheme name is
turn
orturns
, and parsing the url using the syntax defined in [RFC7065] fails, aSyntaxError
. If scheme name isstun
orstuns
, and parsing the url using the syntax defined in [] fails, throw a .If scheme name is
turn
orturns
, and either of server.username
or server. are omitted, then throw an .If scheme name is
turn
orturns
, and server.credentialType
is ““, and server.credential
is not a DOMString, then anInvalidAccessError
.
Append server to validatedServers.
Set the ‘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 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 section, which adds the APIs to send and receive MediaStreamTrack
objects.
Attributes
localDescription
of type , readonly, nullable
The localDescription
attribute MUST return if it is not null
and otherwise it MUST return [[CurrentLocalDescription]].
Note that .sdp
and .sdp
need not be string-wise identical to the value passed to the corresponding setLocalDescription
call (i.e. SDP may be parsed and reformatted, and ICE candidates may be added).
currentLocalDescription
of type , readonly, nullable
The currentLocalDescription
attribute MUST return .
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 since the offer or answer was created.
pendingLocalDescription
of type RTCSessionDescription
, readonly, nullable
The 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 since the offer or answer was created. If the RTCPeerConnection
is in the stable state, the value is null
.
remoteDescription
of type , readonly, nullable
The remoteDescription
attribute MUST return if it is not null
and otherwise it MUST return [[CurrentRemoteDescription]].
Note that .sdp
and .sdp
need not be string-wise identical to the value passed to the corresponding setRemoteDescription
call (i.e. SDP may be parsed and reformatted, and ICE candidates may be added).
currentRemoteDescription
of type , readonly, nullable
The currentRemoteDescription
attribute MUST return .
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 ()
since the offer or answer was created.
pendingRemoteDescription
of type RTCSessionDescription
, readonly, nullable
The 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 ()
since the offer or answer was created. If the RTCPeerConnection
is in the stable state, the value is null
.
signalingState
of type , readonly
The signalingState
attribute MUST return the object’s signaling state.
iceGatheringState
of type , readonly
The iceGatheringState
attribute MUST return the of the RTCPeerConnection
instance.
iceConnectionState
of type , readonly
The iceConnectionState
attribute MUST return the of the RTCPeerConnection
instance.
connectionState
of type , readonly
The connectionState
attribute MUST return the of the RTCPeerConnection
instance.
canTrickleIceCandidates
of type boolean, readonly, nullable
The 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 [] (section 4.1.17.). Prior to the completion of , 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 .
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 .
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 .
onconnectionstatechange
of type EventHandler
The event type of this event handler is connectionstatechange
.
Methods
createOffer
The 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 , 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), 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 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 [], except the user agent MUST treat a stopping
transceiver as 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, 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 , password
and ICE options (as defined in [], Section 14) and may also contain any local candidates that have been gathered by the agent.
The certificates
value in configuration for the 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 object on which the method was invoked.
If connection.[[IsClosed]] is
true
, return a promise with a newly created .Return the result of chaining the result of with connection to connection’s operations chain.
To create an offer given connection run the following steps:
If connection’s is neither “
stable
“ nor ““, return a promise rejected with a newlyInvalidStateError
.Let p be a new promise.
In parallel, begin the 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
OperationError
and abort these steps.Queue a task that runs the 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 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, was called when only an audio
RTCRtpTransceiver
was added to connection, but while performing the , 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 s, generate an SDP offer, sdpString, as described in [RFC8829] ().
As described in [RFC8843] (Section 7), if bundling is used (see ) 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 ‘s associated transceiver is said to be the value of the .[[PreferredCodecs]] with the following filtering applied (or said not to be set if is empty):
If the
direction
is ““, exclude any codecs not included in the intersection ofRTCRtpSender
.(kind).codecs
and .getCapabilities
(kind)..If the
direction
is ““, exclude any codecs not included inRTCRtpSender
.(kind).codecs
.If the is “
recvonly
“, exclude any codecs not included in .getCapabilities
(kind)..
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 its member initialized to the string “offer
“ and its member initialized to sdpString.Set the [[LastCreatedOffer]] internal slot to sdpString.
p with offer.
createAnswer
The createAnswer
method generates an [] 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 s attached to this RTCPeerConnection
, the codec/RTP/RTCP options negotiated for this session, and any candidates that have been gathered by the . 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 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 [].
The generated SDP will also contain the ICE agent‘s , password
and ICE options (as defined in [], Section 14) and may also contain any local candidates that have been gathered by the agent.
The certificates
value in configuration for the 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 [] (section 4.1.10.1.), by setting the to “pranswer
“.
When the method is called, the user agent MUST run the following steps:
Let connection be the object on which the method was invoked.
If connection.[[IsClosed]] is
true
, return a promise with a newly created .Return the result of chaining the result of with connection to connection’s operations chain.
To create an answer given connection run the following steps:
If connection’s is neither “
have-remote-offer
“ nor ““, return a promise rejected with a newlyInvalidStateError
.Let p be a new promise.
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 [] (section 4.1.9.).
If this inspection failed for any reason, p with a newly created 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. 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 again given connection and p, and abort these steps.
Note
This may be necessary if, for example,
createAnswer
was called when an ‘s direction was “recvonly
“, but while performing the , the direction was changed to ““, requiring additional inspection of video encoding resources.Given the information that was obtained from previous inspection and the current state of connection and its 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
. with the following filtering applied (or said not to be set if [[PreferredCodecs]] is empty):If the is “
sendrecv
“, exclude any codecs not included in the intersection of .getCapabilities
(kind). andRTCRtpReceiver
.(kind).codecs
.If the is “
sendonly
“, exclude any codecs not included in .getCapabilities
(kind)..If the
direction
is ““, exclude any codecs not included inRTCRtpReceiver
.(kind).codecs
.
Let answer be a newly created dictionary with its
type
member initialized to the string ““ and itssdp
member initialized to sdpString.p with answer.
setLocalDescription
The setLocalDescription
method instructs the 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 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 will implicitly create an offer or , 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 .
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..
Return the result of chaining the following steps to connection’s :
Let type be description.
type
if present, or ““ if not present and connection’s signaling state is either ““, “have-local-offer
“, or ““; otherwise “answer
“.If type is ““, and sdp is not the empty string and not equal to connection.[[LastCreatedOffer]], then return a promise with a newly created and abort these steps.
If type is “
answer
“ or ““, and sdp is not the empty string and not equal to connection.[[LastCreatedAnswer]], then return a promise with a newly created 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..
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 with connection, and return the result of reacting to p with a fulfillment step that indicated by its first argument.
If sdp is the empty string, and type is “
answer
“ or ““, 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 of connection, then let p be the result of creating an answer with connection, and return the result of 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 indicated by
{type, sdp}
.
Note
As noted in [RFC8829] (), calling this method may trigger the ICE candidate gathering process by the ICE Agent.
setRemoteDescription
The method instructs the RTCPeerConnection
to apply the supplied 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 the following steps to connection’s operations chain:
If description. is “
offer
“ and is invalid for the current of connection as described in [RFC8829] ( and section 5.6.), then run the following sub steps:Let p be the result of indicated by
{type: "[`rollback`](#dom-rtcsdptype-rollback)"}
.Return the result of reacting to p with a fulfillment step that description, and abort these steps.
Return the result of setting the remote session description description.
addIceCandidate
The 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 member. The only members of the argument used by this method are candidate
, , sdpMLineIndex
, and ; 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. is not an empty string and both candidate.
sdpMid
and candidate. arenull
, return a promise rejected with a newlyTypeError
.Return the result of the following steps to connection’s operations chain:
If is
null
return a promise rejected with a newlyInvalidStateError
.If candidate. is not
null
, run the following steps:- If candidate.
sdpMid
is not equal to the mid of any media description in , return a promise rejected with a newlyOperationError
.
- If candidate.
Else, if candidate. is not
null
, run the following steps:- If candidate.
sdpMLineIndex
is equal to or larger than the number of media descriptions in , return a promise rejected with a newlyOperationError
.
- If candidate.
If either candidate. or candidate.
sdpMLineIndex
indicate a media description in whose associated transceiver isstopped
, return a promise withundefined
.If candidate.
usernameFragment
is notnull
, and is not equal to any username fragment present in the corresponding of an applied remote description, return a promise rejected with a newlyOperationError
.Let p be a new promise.
In parallel, if the candidate is not , add the ICE candidate candidate as described in [RFC8829] (). Use candidate.
usernameFragment
to identify the ICE ; ifusernameFragment
isnull
, process the candidate for the most recent ICE .If candidate.
candidate
is an empty string, process candidate as an end-of-candidates indication for the corresponding and ICE candidate generation. If both candidate. and candidate.sdpMLineIndex
arenull
, then this end-of-candidates indication applies to all s.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.p with a newly created 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. is
true
, then abort these steps.If connection.[[PendingRemoteDescription]] is not
null
, and represents the ICE for which candidate was processed, add candidate to connection.[[PendingRemoteDescription]].sdp.If connection. is not
null
, and represents the ICE generation for which candidate was processed, add candidate to connection..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 [] block bad port list, and MAY choose to prohibit connections to other addresses.
If the member of the RTCConfiguration
is , 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 method tells the RTCPeerConnection
that ICE should be restarted. Subsequent calls to 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 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 []) found in connection.[[CurrentLocalDescription]], as well as all ICE credentials found in connection..
Update the negotiation-needed flag for connection.
getConfiguration
Returns an object representing the current configuration of this RTCPeerConnection
object.
When this method is called, the user agent MUST return the object stored in the [[Configuration]] internal slot.
setConfiguration
The method updates the configuration of this RTCPeerConnection
object. This includes changing the configuration of the . 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 on which the method was invoked.
If connection.[[IsClosed]] is
true
, anInvalidStateError
.specified by configuration.
close
When the close
method is invoked, the user agent MUST run the following steps:
Let connection be the 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. is
true
, abort these steps.Set connection.[[IsClosed]] to
true
.Set connection’s to “
closed
“. This does not fire any event.Let transceivers be the result of executing the algorithm. For every
RTCRtpTransceiver
transceiver in transceivers, run the following steps:If transceiver. is
true
, abort these sub steps.Stop the RTCRtpTransceiver with transceiver and disappear.
Set the slot of each of connection’s
RTCDataChannel
s to ““.Note
The
RTCDataChannel
s will be closed abruptly and the closing procedure will not be invoked.If connection. is not
null
, tear down the underlying SCTP association by sending an SCTP ABORT chunk and set the [[SctpTransportState]] to ““.Set the [[DtlsTransportState]] slot of each of connection’s s to “
closed
“.Destroy connection’s , abruptly ending any active ICE processing and releasing any relevant resources (e.g. TURN permissions).
Set the [[IceTransportState]] slot of each of connection’s s to “
closed
“.Set connection’s to “
closed
“. This does not fire any event.Set connection’s to “
closed
“. This does not fire any event.
4.4.3 Legacy Interface Extensions
Note
The 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 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
‘s()
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 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 ‘s
setLocalDescription
method with description as the sole argument, and let p be the resulting promise.Upon 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 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 ‘s
createAnswer
()
method with no arguments, and let p be the resulting promise.Upon 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 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
‘s 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 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 ‘s
addIceCandidate
()
method with candidate as the sole argument, and let p be the resulting promise.Upon 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 with
undefined
.
Callback Definitions
These callbacks are only used on the legacy APIs.
RTCPeerConnectionErrorCallback
Callback Parameters
error
of type
An error object encapsulating information about what went wrong.
RTCSessionDescriptionCallback
Callback Parameters
description of type
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 . Developers are encouraged to use the RTCRtpTransceiver
API instead.
When 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 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 kind, set transceiver.[[Direction]] to ““.For each non-stopped “
recvonly
“ transceiver of kind, set transceiver.[[Direction]] to ““.
- Run the steps specified by
createOffer
to create the offer.
- partial dictionary
RTCOfferOptions
{offerToReceiveAudio
;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 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 and MediaStreamTrack
objects that are connected to an have a strong reference to the RTCPeerConnection
object.