Initial Author of this Specification was Ian Hickson, Google Inc., with the following copyright statement:
 © Copyright 2004-2011 Apple Computer, Inc., Mozilla Foundation, and Opera Software ASA. You are granted a license to use, reproduce and create derivative works of this document. All subsequent changes since 26 July 2011 done by the W3C WebRTC Working Group are under the following Copyright:
© 2011-2018 W3C® (MIT, ERCIM, Keio, Beihang). Document use  rules apply. For the entire publication on the W3C site the liability and trademark rules apply.
This document defines a set of ECMAScript APIs in WebIDL to allow media to be sent to and received from another browser or device implementing the appropriate set of real-time protocols. This specification is being developed in conjunction with a protocol specification developed by the IETF RTCWEB group and an API specification to get access to local media devices.
This section describes the status of this document at the time of its publication. Other documents may supersede this document. A list of current W3C publications and the latest revision of this technical report can be found in the W3C technical reports index at https://www.w3.org/TR/.
The API is based on preliminary work done in the WHATWG.
The specification is feature complete and is expected to be stable with no further substantive change. Since the previous Candidate Recommendation, the following substantive changes have been brought to the specification:
voiceActivityFlag has been marked at risk for lack of implementationPeerConnection has been clarifiedIts associated test suite will be used to build an implementation report of the API.
To go into Proposed Recommendation status, the group expects to demonstrate implementation of each feature in at least two deployed browsers, and at least one implementation of each optional feature. Mandatory feature with only one implementation may be marked as optional in a revised Candidate Recommendation where applicable.
This document was published by the Web Real-Time Communications Working Group as a Candidate Recommendation. This document is intended to become a W3C Recommendation.
GitHub Issues are preferred for discussion of this specification. Alternatively, you can send comments to our mailing list. Please send them to public-webrtc@w3.org (archives).
W3C publishes a Candidate Recommendation to indicate that the document is believed to be stable and to encourage implementation by the developer community. This Candidate Recommendation is expected to advance to Proposed Recommendation no earlier than 24 September 2020.
Please see the Working Group's implementation report.
Publication as a Candidate Recommendation does not imply endorsement by the W3C Membership. This is a draft document and may be updated, replaced or obsoleted by other documents at any time. It is inappropriate to cite this document as other than work in progress.
This document was produced by a group operating under the W3C Patent Policy. W3C maintains a public list of any patent disclosures made in connection with the deliverables of the group; that page also includes instructions for disclosing a patent. An individual who has actual knowledge of a patent which the individual believes contains Essential Claim(s) must disclose the information in accordance with section 6 of the W3C Patent Policy.
This document is governed by the 1 March 2019 W3C Process Document.
This section is non-normative.
There are a number of facets to peer-to-peer communications and video-conferencing in HTML covered by this specification:
This document defines the APIs used for these features. This specification is being developed in conjunction with a protocol specification developed by the IETF RTCWEB group and an API specification to get access to local media devices [GETUSERMEDIA] developed by the WebRTC Working Group. An overview of the system can be found in [RTCWEB-OVERVIEW] and [RTCWEB-SECURITY].
As well as sections marked as non-normative, all authoring guidelines, diagrams, examples, and notes in this specification are non-normative. Everything else in this specification is normative.
The key words MAY, MUST, MUST NOT, and SHOULD in this document are to be interpreted as described in BCP 14 [RFC2119] [RFC8174] when, and only when, they appear in all capitals, as shown here.
This specification defines conformance criteria that apply to a single product: the user agent that implements the interfaces that it contains.
Conformance requirements phrased as algorithms or specific steps may be implemented in any manner, so long as the end result is equivalent. (In particular, the algorithms defined in this specification are intended to be easy to follow, and not intended to be performant.)
Implementations that use ECMAScript to implement the APIs defined in this specification MUST implement them in a manner consistent with the ECMAScript Bindings defined in the Web IDL specification [WEBIDL], as this specification uses that specification and terminology.
The EventHandler
    interface, representing a callback used for event handlers, is defined in [HTML].
The concepts queue a task and networking task source are defined in [HTML].
The concept fire an event is defined in [DOM].
The terms event, event handlers and event handler event types are defined in [HTML].
Performance.timeOrigin and Performance.now() are defined in [hr-time].
The terms serializable objects, serialization steps, and deserialization steps are defined in [HTML].
The terms MediaStream, MediaStreamTrack, and
    MediaStreamConstraints are defined in [GETUSERMEDIA].
    Note that MediaStream is extended in § 9.2 MediaStream in this document while MediaStreamTrack
    is extended in § 9.3 MediaStreamTrack
     in this document.
The term Blob is defined in [FILEAPI].
The term media description is defined in [RFC4566].
The term media transport is defined in [RFC7656].
The term generation is defined in [TRICKLE-ICE] Section 2.
The terms stats object and monitored object are defined in [WEBRTC-STATS].
When referring to exceptions, the terms throw and created are defined in [WEBIDL].
The callback VoidFunction is defined in [WEBIDL].
The term "throw" is used as specified in [INFRA]: it terminates the current processing steps.
The terms fulfilled, rejected, resolved, pending and settled used in the context of Promises are defined in [ECMASCRIPT-6.0].
The terms bundle, bundle-only and bundle-policy are defined in [JSEP].
The AlgorithmIdentifier is defined in [WebCryptoAPI].
      The general principles for Javascript APIs apply, including the principle
      of 
        run-to-completion and no-data-races as defined in [API-DESIGN-PRINCIPLES].
      That is, while a task is running, external events do
      not influence what's visible to the Javascript application. For example,
      the amount of data buffered on a data channel will increase due to
      "send" calls while Javascript is executing, and the decrease due to
      packets being sent will be visible after a task checkpoint.
      
      It is the responsibility of the user agent to make sure the set of
      values presented to the application is consistent - for instance that
      getContributingSources() (which is synchronous) returns values for all
      sources measured at the same time.
    
An RTCPeerConnectionRTCPeerConnectionXMLHttpRequest [xhr].
RTCConfiguration DictionaryThe RTCConfigurationRTCPeerConnection
WebIDLdictionaryRTCConfiguration{ sequence<RTCIceServer>iceServers;RTCIceTransportPolicyiceTransportPolicy;RTCBundlePolicybundlePolicy;RTCRtcpMuxPolicyrtcpMuxPolicy; sequence<RTCCertificate>certificates; [EnforceRange] octeticeCandidatePoolSize= 0; };
RTCConfigurationiceServers of type sequence<RTCIceServerAn array of objects describing servers available to be used by ICE, such as STUN and TURN servers.
iceTransportPolicy of type
              RTCIceTransportPolicyIndicates which candidates the ICE Agent is allowed to use.
bundlePolicy of type RTCBundlePolicyIndicates which media-bundling policy to use when gathering ICE candidates.
rtcpMuxPolicy of type RTCRtcpMuxPolicyIndicates which rtcp-mux policy to use when gathering ICE candidates.
certificates of type sequence<RTCCertificateA set of certificates that the
                RTCPeerConnection
Valid values for this parameter are created through calls to
                the generateCertificate()
                function.
Although any given DTLS connection will use only one
                certificate, this attribute allows the caller to provide
                multiple certificates that support different algorithms. The
                final certificate will be selected based on the DTLS handshake,
                which establishes which certificates are allowed. The
                RTCPeerConnection
Existing implementations only utilize the first certificate provided; the others are ignored.
If this value is absent, then a default set of certificates
                is generated for each RTCPeerConnection
This option allows applications to establish key continuity.
                An RTCCertificate
The value for this configuration option cannot change after its value is initially selected.
iceCandidatePoolSize of type
              octet, defaulting to
              0Size of the prefetched ICE pool as defined in [JSEP] (section 3.5.4. and section 4.1.1.).
RTCIceCredentialType EnumWebIDLenumRTCIceCredentialType{ "password" };
| Enumeration description | |
|---|---|
| password | The credential is a long-term authentication username and password, as described in [RFC5389], Section 10.2. | 
RTCIceServer DictionaryThe RTCIceServer
WebIDLdictionaryRTCIceServer{ required (DOMString or sequence<DOMString>)urls; DOMStringusername; DOMStringcredential;RTCIceCredentialTypecredentialType= "password"; };
RTCIceServerurls of type (DOMString or
              sequence<DOMString>), requiredSTUN or TURN URI(s) as defined in [RFC7064] and [RFC7065] or other URI types.
username of type DOMStringIf this RTCIceServercredentialTypepassword
credential of type DOMStringIf this RTCIceServer
If credentialTypepasswordcredential
To support additional values of
                credentialTypecredential
credentialType of type RTCIceCredentialTypepasswordIf this RTCIceServer
An example array of RTCIceServer
[
  {urls: 'stun:stun1.example.net'},
  {urls: ['turns:turn.example.org', 'turn:turn.example.net'],
    username: 'user',
    credential: 'myPassword',
    credentialType: 'password'},
];RTCIceTransportPolicy EnumAs described in [JSEP] (section 4.1.1.), if the
        iceTransportPolicyRTCConfiguration
WebIDLenumRTCIceTransportPolicy{ "relay", "all" };
| Enumeration description (non-normative) | |
|---|---|
| relay | The ICE Agent uses only media relay candidates such as candidates passing through a TURN server. Note 
                    This can be used to prevent the remote endpoint from learning
                    the user's IP addresses, which may be desired in certain
                    use cases. For example, in a "call"-based application, the
                    application may want to prevent an unknown caller from
                    learning the callee's IP addresses until the callee has
                    consented in some way.
                   | 
| all | The ICE Agent can use any type of candidate when this value is specified. Note 
                    The implementation can still use its own candidate
                    filtering policy in order to limit the IP addresses exposed
                    to the application, as noted in the description of
                     .. | 
RTCBundlePolicy EnumAs described in [JSEP] (section 4.1.1.), bundle policy affects which media tracks are negotiated if the remote endpoint is not bundle-aware, and what ICE candidates are gathered. If the remote endpoint is bundle-aware, all media tracks and data channels are bundled onto the same transport.
WebIDLenumRTCBundlePolicy{ "balanced", "max-compat", "max-bundle" };
| Enumeration description (non-normative) | |
|---|---|
| balanced | Gather ICE candidates for each media type in use (audio, video, and data). If the remote endpoint is not bundle-aware, negotiate only one audio and video track on separate transports. | 
| max-compat | Gather ICE candidates for each track. If the remote endpoint is not bundle-aware, negotiate all media tracks on separate transports. | 
| max-bundle | Gather ICE candidates for only one track. If the remote endpoint is not bundle-aware, negotiate only one media track. | 
RTCRtcpMuxPolicy EnumAs described in [JSEP] (section 4.1.1.), the
        RTCRtcpMuxPolicyrequire
WebIDLenumRTCRtcpMuxPolicy{ "require" };
| Enumeration description (non-normative) | |
|---|---|
| require | Gather ICE candidates only for RTP and multiplex RTCP on the RTP candidates. If the remote endpoint is not capable of rtcp-mux, session negotiation will fail. | 
These dictionaries describe the options that can be used to control the offer/answer creation process.
WebIDLdictionary RTCOfferAnswerOptions {};
          RTCOfferAnswerOptions
            MembersWebIDLdictionaryRTCOfferOptions:RTCOfferAnswerOptions{ booleaniceRestart= false; };
RTCOfferOptions MembersiceRestart of type boolean, defaulting to
              falseWhen the value of this dictionary member is true,
                or the relevant RTCPeerConnectioncurrentLocalDescription
When the value of this dictionary member is false,
                and the relevant RTCPeerConnectioncurrentLocalDescriptioncurrentLocalDescription
Performing an ICE restart is recommended when
                iceConnectionStatefailediceConnectionStatedisconnectedgetStats
The RTCAnswerOptions dictionary describe options specific to session description of type "answer
WebIDLdictionaryRTCAnswerOptions:RTCOfferAnswerOptions{};
RTCSignalingState EnumWebIDLenumRTCSignalingState{ "stable", "have-local-offer", "have-remote-offer", "have-local-pranswer", "have-remote-pranswer", "closed" };
| Enumeration description | |
|---|---|
| stable | There is no offer/answer exchange in progress. This is also the initial state, in which case the local and remote descriptions are empty. | 
| have-local-offer | A local description, of type " ", has been successfully
                applied. | 
| have-remote-offer | A remote description, of type " ", has been
                successfully applied. | 
| have-local-pranswer | A remote description of type " " has been successfully
                applied and a local description of type "" has been
                successfully applied. | 
| have-remote-pranswer | A local description of type " " has been successfully
                applied and a remote description of type "" has been
                successfully applied. | 
| closed | The has been closed;
                  its [[IsClosed]] slot istrue. | 
An example set of transitions might be:
stablehave-local-offerhave-remote-pranswerstablestablehave-remote-offerhave-local-pranswerstableRTCIceGatheringState EnumWebIDLenumRTCIceGatheringState{ "new", "gathering", "complete" };
| Enumeration description | |
|---|---|
| new | Any of the s are in the
                "" gathering state and none of the transports are
                in the "" state, or there are no
                transports. | 
| gathering | Any of the s are in the
                "" state. | 
| complete | At least one exists,
                and alls are in the
                "" gathering state. | 
RTCPeerConnectionState EnumWebIDLenumRTCPeerConnectionState{ "closed", "failed", "disconnected", "new", "connecting", "connected" };
| Enumeration description | |
|---|---|
| closed | The object's
                  [[IsClosed]] slot istrue. | 
| failed | The previous state doesn't apply and any s are in the
                "" state or anys are in the
                "" state. | 
| disconnected | None of the previous states apply and any s are in the
                "" state. | 
| new | None of the previous states apply and all s are in the ""
                or "" state, and alls are in the ""
                or "" state, or there are no
                transports. | 
| connecting | None of the previous states apply and any is in the
                "" state or anyis in the
                "" state. | 
| connected | None of the previous states apply and all s are in the
                "",
                "" or
                "" state, and alls are in the
                "" or
                "" state. | 
RTCIceConnectionState EnumWebIDLenumRTCIceConnectionState{ "closed", "failed", "disconnected", "new", "checking", "completed", "connected" };
| Enumeration description | |
|---|---|
| closed | The object's
                  [[IsClosed]] slot istrue. | 
| failed | The previous state doesn't apply and any s are in the
                "" state. | 
| disconnected | None of the previous states apply and any s are in the
                "" state. | 
| new | None of the previous states apply and all s are in the
                "" or "" state,
                or there are no transports. | 
| checking | None of the previous states apply and any s are in the
                "" or "" state. | 
| completed | None of the previous states apply and all s are in the
                "" or "" state. | 
| connected | None of the previous states apply and all s are in the
                "", "" or
                "" state. | 
Note that if an RTCIceTransport
The [JSEP] specification, as a whole, describes the details of how
      the RTCPeerConnection
Calling new  creates an RTCPeerConnectionRTCPeerConnection
configuration.iceServers
An RTCPeerConnection
The ICE protocol implementation of
        an RTCPeerConnectionRTCPeerConnectionaddIceCandidatesetConfigurationsetLocalDescriptionsetRemoteDescriptioncloseRTCIceTransportRTCIceTransport Interface.
The task source for the tasks listed in this section is the networking task source.
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 setLocalDescriptionsetRemoteDescriptionaddIceCandidate
As one of the unloading document cleanup steps, run the following steps:
Let window be document's relevant global object.
For each RTCPeerConnectiontrue.
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 the message
Let connection be a newly created
            RTCPeerConnection
Let connection have a [[DocumentOrigin]] internal slot, initialized to the current settings object's origin.
If the certificates
If the value of certificate.expiresInvalidAccessError.
If certificate.[[Origin]] is not same
                origin with connection.[[DocumentOrigin]],
                throw an InvalidAccessError.
Store certificate.
Else, generate one or more new RTCCertificateRTCPeerConnectioncertificatesundefined for the subsequent steps. As noted in Section 4.3.2.3 of
            [RTCWEB-SECURITY], 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.iceTransportPolicyundefined, set it to "all
If the value of configuration.bundlePolicyundefined, set it to "balanced
If the value of configuration.rtcpMuxPolicyundefined, 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.
An RTCPeerConnection
To chain an operation to an
        RTCPeerConnection
Let connection be the
            RTCPeerConnection
If connection.[[IsClosed]] is
            true, return a promise rejected with a newly
            created
            InvalidStateError.
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.
An RTCPeerConnectionRTCDtlsTransporttrue, the user agent MUST
        update the connection state by queueing a task that runs the
        following steps:
Let connection be this
            RTCPeerConnection
Let newState be the value of deriving a new state
            value as described by the
            RTCPeerConnectionState
If connection's connection state is equal to newState, abort these steps.
Let connection's connection state be newState.
Fire an event named
            connectionstatechange
To update the ICE gathering
        state of an RTCPeerConnection
If connection.[[IsClosed]] is
            true, abort these steps.
Let newState be the value of deriving a new state
            value as described by the RTCIceGatheringState
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
If newState is "completeicecandidateRTCPeerConnectionIceEventnull at connection.
RTCIceTransportRTCPeerConnectionTo set a local RTCSessionDescription
        description on an RTCPeerConnectionfalse.
To set a remote RTCSessionDescription
        description on an RTCPeerConnectiontrue.
To set an RTCSessionDescription
        description on an RTCPeerConnection
Let p be a new promise.
If description.typerollbackstablehave-local-pranswerhave-remote-pranswerInvalidStateError 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 [JSEP] (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.typeInvalidStateError and abort these steps.
If the content of description is not
                    valid SDP syntax, then reject p with an
                    RTCErrorerrorDetailsdp-syntax-errorsdpLineNumber
If remote is true,
                    the connection's RTCRtcpMuxPolicyrequireInvalidAccessError 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 "offeraddTrack() 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 "offerstable
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 "offerRTCSessionDescriptionhave-local-offer
If description is of type "answerRTCSessionDescriptionnull. Set both
                        connection.[[LastCreatedOffer]] and
                        connection.[[LastCreatedAnswer]] to
                        "", set connection's
                        signaling state to "stable
If description is of type "pranswerRTCSessionDescriptionhave-local-pranswer
Otherwise, (if remote is true) run
                    one of the following steps:
If description is of type "offerRTCSessionDescriptionhave-remote-offer
If description is of type "answerRTCSessionDescriptionnull. Set both
                        connection.[[LastCreatedOffer]] and
                        connection.[[LastCreatedAnswer]] to
                        "", and set connection's
                        signaling state to "stable
If description is of type "pranswerRTCSessionDescriptionhave-remote-pranswer
If description is of type "answernull.
Let trackEventInits, muteTracks, addList, removeList and errorList be empty lists.
If description is of type "answerpranswer
If description initiates the
                        establishment of a new SCTP association, as defined in
                        [SCTP-SDP], Sections 10.3 and 10.4, create an
                        RTCSctpTransport with an initial state of
                        "connectingmax-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
                        RTCDataChannelnull
                        id
closedIf description is not of type "rollback
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
Let transceiver be the
                                RTCRtpTransceiver
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
                                  [BUNDLE], let transport be the
                                  RTCDtlsTransport
                                  Otherwise, let transport
                                  be a newly created
                                  RTCDtlsTransportRTCIceTransport
Set transceiver.[[Sender]].[[SenderTransport]] to transport.
Set transceiver.[[Receiver]].[[ReceiverTransport]] to transport.
Let transceiver be the
                            RTCRtpTransceiver
If transceiver.[[Stopped]]
                            is true, abort these sub steps.
Let direction be an
                            RTCRtpTransceiverDirection
If direction is "sendrecvrecvonlytrue, otherwise set it to false.
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
                            "answerpranswer
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
                                "sendonlyinactivesendrecvrecvonly
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 "offerRTCRtpEncodingParametersrid
scaleResolutionDownBy2^(length of sendEncodings -
                            encoding index - 1).
                          As described by [JSEP] (section 5.10.), attempt to
                            find an existing RTCRtpTransceiver
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 RTCRtpTransceiverDirectionrecvonly
Add transceiver to the connection's set of transceivers.
If description is of type "answerpranswer1, 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 [MMUSIC-SIMULCAST] of
                                each simulcast layer by setting the
                                activetrue for unpaused or to false for paused.
Set transceiver.[[Mid]] to transceiver.[[JsepMid]].
Let direction be an
                            RTCRtpTransceiverDirectioninactive
If direction is "sendrecvrecvonly
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
                            "answerpranswer
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
Set transceiver.[[Sender]].[[SenderTransport]] to transport.
Set transceiver.[[Receiver]].[[ReceiverTransport]] to transport.
Set the [[IceRole]] of transport according to the rules of [RFC8445].
unknowncontrollinga=ice-lite, set [[IceRole]] to controllinga=ice-lite, set [[IceRole]] to controlledIf the media description is rejected, and
                            transceiver.[[Stopped]] is
                            false, then
                            stop the RTCRtpTransceiver
                            transceiver.
Otherwise, (if description is of type "rollback
For each transceiver in the connection's set of transceivers run the following steps:
If the transceiver was not associated with
                            a media description prior to applying the
                            RTCSessionDescriptionnull.
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
Let msids be a list of the ids
                                of all MediaStream 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 the transceiver was created by applying the
                            RTCSessionDescriptionaddTrack(), 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
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 connection's signaling state is now
                    "stable
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
                        RTCDtlsTransportRTCIceTransport
Clear the negotiation-needed flag and update the negotiation-needed flag.
If connection's signaling state
                    changed above, fire an event named
                    signalingstatechange
For each channel in errorList,
                    fire an event named errorRTCErrorEventerrorDetaildata-channel-failure
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 trackRTCTrackEventreceiverreceivertracktrackstreamsstreamstransceivertransceiver
Resolve p with undefined.
Return p.
To set a configuration, run the following steps:
Let configuration be the
            RTCConfiguration
Let connection be the target
            RTCPeerConnection
If configuration.certificates
If the length of configuration.certificatescertificatesInvalidModificationError.
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.certificatescertificatesInvalidModificationError.
Increment index by 1.
If the value of configuration.bundlePolicyInvalidModificationError.
If the value of configuration.rtcpMuxPolicyInvalidModificationError.
If the value of configuration.iceCandidatePoolSizeiceCandidatePoolSizesetLocalDescriptionInvalidModificationError.
Set the ICE Agent's ICE transports setting to
              the value of configuration.iceTransportPolicy
Set the ICE Agent's prefetched ICE candidate
              pool size as defined in [JSEP] (section 3.5.4. and section 4.1.1.) to the
              value of configuration.iceCandidatePoolSize
Let validatedServers be an empty list.
If configuration.iceServers
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 a
                      NotSupportedError. If
                      scheme name is turn or
                      turns, and parsing the
                      url using the syntax defined in
                      [RFC7065] fails, throw a
                      SyntaxError. If scheme
                      name is stun or
                      stuns, and parsing the
                      url using the syntax defined in
                      [RFC7064] fails, throw a
                      SyntaxError. 
If scheme name is turn or
                      turns, and either of
                      server.usernamecredentialInvalidAccessError.
If scheme name is turn or
                      turns, and
                      server.credentialTypepasswordcredentialInvalidAccessError.
Append server to validatedServers.
Set the ICE Agent's ICE servers list to validatedServers.
As defined in [JSEP] (section 4.1.16.), 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.
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] interfaceRTCPeerConnection: EventTarget {constructor(optionalRTCConfigurationconfiguration = {}); Promise<RTCSessionDescriptionInit>createOffer(optionalRTCOfferOptionsoptions = {}); Promise<RTCSessionDescriptionInit>createAnswer(optionalRTCAnswerOptionsoptions = {}); Promise<undefined>setLocalDescription(optionalRTCLocalSessionDescriptionInitdescription = {}); readonly attributeRTCSessionDescription?localDescription; readonly attributeRTCSessionDescription?currentLocalDescription; readonly attributeRTCSessionDescription?pendingLocalDescription; Promise<undefined>setRemoteDescription(RTCSessionDescriptionInitdescription); readonly attributeRTCSessionDescription?remoteDescription; readonly attributeRTCSessionDescription?currentRemoteDescription; readonly attributeRTCSessionDescription?pendingRemoteDescription; Promise<undefined>addIceCandidate(optionalRTCIceCandidateInitcandidate = {}); readonly attributeRTCSignalingStatesignalingState; readonly attributeRTCIceGatheringStateiceGatheringState; readonly attributeRTCIceConnectionStateiceConnectionState; readonly attributeRTCPeerConnectionStateconnectionState; readonly attribute boolean?canTrickleIceCandidates; undefinedrestartIce();RTCConfigurationgetConfiguration(); undefinedsetConfiguration(optionalRTCConfigurationconfiguration = {}); undefinedclose(); attribute EventHandleronnegotiationneeded; attribute EventHandleronicecandidate; attribute EventHandleronicecandidateerror; attribute EventHandleronsignalingstatechange; attribute EventHandleroniceconnectionstatechange; attribute EventHandleronicegatheringstatechange; attribute EventHandleronconnectionstatechange; // 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(RTCSessionDescriptionCallbacksuccessCallback,RTCPeerConnectionErrorCallbackfailureCallback, optionalRTCOfferOptionsoptions = {}); Promise<undefined>setLocalDescription(optionalRTCLocalSessionDescriptionInitdescription = {}, VoidFunction successCallback,RTCPeerConnectionErrorCallbackfailureCallback); Promise<undefined>createAnswer(RTCSessionDescriptionCallbacksuccessCallback,RTCPeerConnectionErrorCallbackfailureCallback); Promise<undefined>setRemoteDescription(RTCSessionDescriptionInitdescription, VoidFunction successCallback,RTCPeerConnectionErrorCallbackfailureCallback); Promise<undefined>addIceCandidate(RTCIceCandidateInitcandidate, VoidFunction successCallback,RTCPeerConnectionErrorCallbackfailureCallback); };
localDescription of type RTCSessionDescriptionThe localDescriptionnull and otherwise it MUST return
                [[CurrentLocalDescription]].
Note that [[CurrentLocalDescription]].sdpsdpsetLocalDescription
currentLocalDescription of type RTCSessionDescriptionThe currentLocalDescription
It represents the local description that was successfully
                negotiated the last time the RTCPeerConnection
pendingLocalDescription of type RTCSessionDescriptionThe 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 RTCPeerConnectionnull.
remoteDescription of type RTCSessionDescriptionThe remoteDescriptionnull and otherwise it MUST return
                [[CurrentRemoteDescription]].
Note that [[CurrentRemoteDescription]].sdpsdpsetRemoteDescription
currentRemoteDescription of type RTCSessionDescriptionThe currentRemoteDescription
It represents the last remote description that was successfully
                negotiated the last time the RTCPeerConnectionaddIceCandidate() since the
                offer or answer was created.
pendingRemoteDescription of type RTCSessionDescriptionThe 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
                RTCPeerConnectionnull.
signalingState of type RTCSignalingStateThe signalingStateRTCPeerConnection
iceGatheringState of type RTCIceGatheringStateThe iceGatheringStateRTCPeerConnection
iceConnectionState of type RTCIceConnectionStateThe iceConnectionStateRTCPeerConnection
connectionState of type RTCPeerConnectionStateThe connectionStateRTCPeerConnection
canTrickleIceCandidates of type boolean, readonly, nullableThe canTrickleIceCandidatessetRemoteDescriptionnull.
onnegotiationneeded of type
              EventHandlernegotiationneededonicecandidate of type EventHandlericecandidateonicecandidateerror of type
              EventHandlericecandidateerroronsignalingstatechange of type
              EventHandlersignalingstatechangeoniceconnectionstatechange of type
              EventHandlericeconnectionstatechangeonicegatheringstatechange of type
              EventHandlericegatheringstatechangeonconnectionstatechange of type
              EventHandlerconnectionstatechangecreateOfferThe createOfferMediaStreamTracks attached to this
                RTCPeerConnection
If a system has limited resources (e.g. a finite number of
                decoders), createOffersetLocalDescriptionsetLocalDescription
Creating the SDP
                MUST follow the appropriate process for generating an offer
                described in [JSEP], except the user agent MUST treat a
                stopping transceiver as
                stopped for the
                purposes of JSEP 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
                createOffercreateOffer
The generated SDP will also contain the ICE agent's
                usernameFragmentpassword
The certificatesRTCPeerConnectionRTCPeerConnection
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
If connection.[[IsClosed]] is
                    true, return a promise rejected with a newly
                    created
                    InvalidStateError.
Return the result of chaining the result of creating an offer with connection to connection's operations chain.
To create an offer given connection run the following steps:
If connection's signaling state is
                    neither "stablehave-local-offerInvalidStateError.
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 [JSEP] (section 4.1.6.).
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.
createOfferRTCRtpTransceiverRTCRtpTransceiverGiven the information that was obtained from previous
                    inspection, the current state of connection
                    and its RTCRtpTransceiver
As described in [BUNDLE] (Section 7), if bundling
                        is used (see RTCBundlePolicy
The codec preferences of a media description's
                        associated transceiver is said to be the value of the
                        RTCRtpTransceiver
If the directionsendrecvRTCRtpSendergetCapabilitiescodecsRTCRtpReceivergetCapabilitiescodecs
If the directionsendonlyRTCRtpSendergetCapabilitiescodecs
If the directionrecvonlyRTCRtpReceivergetCapabilitiescodecs
The filtering MUST NOT change the order of the codec preferences.
If the length of the [[SendEncodings]] slot
                          of the RTCRtpSenderRTCRtpSendera=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
[SDP-SIMULCAST] 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
                    RTCSessionDescriptionInittypeoffersdp
Set the [[LastCreatedOffer]] internal slot to sdpString.
Resolve p with offer.
createAnswerThe createAnswercreateOfferMediaStreamTracks
                attached to this RTCPeerConnection
Like createOffersetLocalDescription
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 [JSEP].
The generated SDP will also contain the ICE agent's
                usernameFragmentpassword
The certificatesRTCPeerConnectionRTCPeerConnection
An answer can be marked as provisional, as described in
                [JSEP] (section 4.1.8.1.),
                by setting the typepranswer
When the method is called, the user agent MUST run the following steps:
Let connection be the
                    RTCPeerConnection
If connection.[[IsClosed]] is
                    true, return a promise rejected with a newly
                    created
                    InvalidStateError.
Return the result of chaining the result of creating an answer with connection to connection's operations chain.
To create an answer given connection run the following steps:
If connection's signaling state
                    is neither "have-remote-offerhave-local-pranswerInvalidStateError.
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 [JSEP] (section 4.1.7.).
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.
createAnswerRTCRtpTransceiverrecvonlysendrecvGiven the information that was obtained from previous
                    inspection and the current state of connection
                    and its RTCRtpTransceiver
The codec preferences of an m= section's
                        associated transceiver is said to be the value of the
                        RTCRtpTransceiver
If the directionsendrecvRTCRtpSendergetCapabilitiescodecsRTCRtpReceivergetCapabilitiescodecs
If the directionsendonlyRTCRtpSendergetCapabilitiescodecs
If the directionrecvonlyRTCRtpReceivergetCapabilitiescodecs
The filtering MUST NOT change the order of the codec preferences.
If the length of the [[SendEncodings]] slot
                          of the RTCRtpSenderRTCRtpSendera=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
Let answer be a newly created
                    RTCSessionDescriptionInittypeanswersdp
Set the [[LastCreatedAnswer]] internal slot to sdpString.
Resolve p with answer.
setLocalDescriptionThe setLocalDescriptionRTCPeerConnectionRTCLocalSessionDescriptionInit
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 RTCPeerConnectionRTCPeerConnection
Passing in a description is optional. If left out, then
                setLocalDescriptioncreateOffercreateAnswer
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
Let sdp be
                    description.sdp
Return the result of chaining the following steps to connection's operations chain:
Let type be
                        description.typeofferstablehave-local-offerhave-remote-pransweranswer
If type is "offerInvalidModificationError and abort these
                        steps.
If type is "answerpranswerInvalidModificationError and abort these
                        steps.
If sdp is the empty string, and
                          type is "offer
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 RTCSessionDescription indicated by its first argument.
If sdp is the empty string, and
                          type is "answerpranswer
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 RTCSessionDescription
                                indicated by
                                {type, answer..
                                sdp
Return the result of setting the local RTCSessionDescription
                        indicated by
                        {type, sdp}.
As noted in [JSEP] (section 5.9.), calling this method may trigger the ICE candidate gathering process by the ICE Agent.
setRemoteDescriptionThe setRemoteDescriptionRTCPeerConnectionRTCSessionDescriptionInit
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
Return the result of chaining the following steps to connection's operations chain:
If description.typeoffer
Let p be the result of setting the local RTCSessionDescription
                            indicated by {type: ".rollback
Return the result of reacting to p with a fulfillment step that sets the remote RTCSessionDescription description, and abort these steps.
Return the result of setting the remote RTCSessionDescription description.
addIceCandidateThe addIceCandidatecandidatecandidatesdpMidsdpMLineIndexusernameFragment
Let candidate be the method's argument.
Let connection be the
                    RTCPeerConnection
If candidate.candidatesdpMidsdpMLineIndexnull, return a promise rejected with a newly
                    created
                    TypeError.
Return the result of chaining the following steps to connection's operations chain:
If remoteDescriptionnull return a promise rejected with a newly
                        created
                        InvalidStateError.
If candidate.sdpMidnull, run the
                        following steps:
If candidate.sdpMidremoteDescriptionOperationError.
Else, if candidate.sdpMLineIndexnull, run the following steps:
If candidate.sdpMLineIndexremoteDescriptionOperationError.
If either candidate.sdpMidsdpMLineIndexremoteDescriptionstopped, return a promise resolved with
                        undefined.
                        
If candidate.usernameFragmentnull, 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
                        created
                        OperationError.
                        
Let p be a new promise.
In parallel, if the candidate is not
                          administratively prohibited, add the ICE candidate
                        candidate as described in [JSEP] (section 4.1.17.). Use
                        candidate.usernameFragmentusernameFragmentnull, process the
                        candidate for the most recent ICE
                        generation. If
                        candidate.candidatesdpMidsdpMLineIndexnull, then
                        this 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 iceTransportPolicyRTCConfigurationrelay
Due to WebIDL processing, addIceCandidatenull)
                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.
restartIceThe restartIceRTCPeerConnectioncreateOffer
When this method is invoked, the user agent MUST run the following steps:
Let connection be the
                    RTCPeerConnection
Empty connection.[[LocalIceCredentialsToReplace]], and populate it with all ICE credentials (ice-ufrag and ice-pwd as defined in section 15.4 of [ICE]) found in connection.[[CurrentLocalDescription]], as well as all ICE credentials found in connection.[[PendingLocalDescription]].
Update the negotiation-needed flag for connection.
getConfigurationReturns an RTCConfigurationRTCPeerConnection
                When this method is called, the user agent MUST return the
                RTCConfiguration
setConfigurationThe setConfigurationRTCPeerConnection
When the setConfiguration
Let connection be the
                    RTCPeerConnection
If connection.[[IsClosed]] is
                    true, throw an
                    InvalidStateError.
Set the configuration specified by configuration.
closeWhen the close
Let connection be the
                    RTCPeerConnection
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
Let transceivers be the result of executing the
                    CollectTransceivers algorithm. For every
                    RTCRtpTransceiver
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 RTCDataChannelclosed
RTCDataChannelIf 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 RTCDtlsTransportclosed
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 RTCIceTransportclosed
Set connection's ICE connection state to
                      "closed
Set connection's connection state to
                    "closed
RTCPeerConnectionSupporting the methods in this section is optional. However, if these methods are supported it is mandatory to implement according to what is specified here.
addStream method that used to exist on
          RTCPeerConnectionRTCPeerConnection.prototype.addStream = function(stream) {
  stream.getTracks().forEach((track) => this.addTrack(track, stream));
};createOfferWhen 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
                    RTCPeerConnectioncreateOffer() 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.
setLocalDescriptionWhen 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
                    RTCPeerConnectionsetLocalDescription
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.
createAnswercreateAnswer method
                does not take an RTCAnswerOptionscreateAnswer
                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
                    RTCPeerConnectioncreateAnswer() 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.
setRemoteDescriptionWhen 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
                    RTCPeerConnectionsetRemoteDescription
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.
addIceCandidateWhen 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
                    RTCPeerConnectionaddIceCandidate() method with
                    candidate as the sole argument, and let
                    p be the resulting promise.
Upon fulfillment of p, invoke
                    successCallback with undefined as
                    the argument.
Upon rejection of p with reason r, invoke failureCallback with r as the argument.
Return a promise resolved with
                    undefined.
These callbacks are only used on the legacy APIs.
RTCPeerConnectionErrorCallbackWebIDLcallback RTCPeerConnectionErrorCallback = undefined (DOMException error);
                RTCPeerConnectionErrorCallbackerror of type
                    DOMExceptionRTCSessionDescriptionCallbackWebIDLcallbackRTCSessionDescriptionCallback= undefined (RTCSessionDescriptionInitdescription);
RTCSessionDescriptionCallbackRTCSessionDescriptionInitThis 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 RTCPeerConnectionRTCRtpTransceiver
When createOffercreateOffer
Let options be the methods first argument.
Let connection be the current
            RTCPeerConnection
For each offerToReceive<Kind> member in options with
            kind, kind, run the following steps:
For each non-stopped "sendrecvsendonly
For each non-stopped "recvonlyinactive
Continue with the next option, if any.
If connection has any non-stopped "sendrecvrecvonly
Let transceiver be the result of invoking the
                equivalent of
                connection.addTransceiver
If transceiver is unset because the previous operation threw an error, abort these steps.
Set transceiver.[[Direction]]
                to "recvonly
Run the steps specified by createOffer
WebIDLpartial dictionaryRTCOfferOptions{ booleanofferToReceiveAudio; booleanofferToReceiveVideo; };
offerToReceiveAudio of type booleanThis 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 booleanThis setting provides additional control over the directionality of video. For example, it can be used to ensure that video can be received, regardless if video is sent or not.
An RTCPeerConnectiontrue, no such event handler can be triggered and
        it is therefore safe to garbage collect the object.
All RTCDataChannelMediaStreamTrack objects that are connected to an
        RTCPeerConnectionRTCPeerConnection
All methods that return promises are governed by the standard error handling rules of promises. Methods that do not return promises may throw exceptions to indicate errors.
RTCSdpTypeThe RTCSdpTypeRTCSessionDescriptionInitRTCLocalSessionDescriptionInitRTCSessionDescription
WebIDLenumRTCSdpType{ "offer", "pranswer", "answer", "rollback" };
| Enumeration description | |
|---|---|
| offer | An  | 
| pranswer | An  | 
| answer | An  | 
| rollback | An  | 
RTCSessionDescription ClassThe RTCSessionDescriptionRTCPeerConnection
WebIDL[Exposed=Window] interfaceRTCSessionDescription{constructor(RTCSessionDescriptionInitdescriptionInitDict); readonly attributeRTCSdpTypetype; readonly attribute DOMStringsdp; [Default] objecttoJSON(); };
constructor()The RTCSessionDescription()
                constructor takes a dictionary argument,
                description, whose content is used to
                initialize the new RTCSessionDescription
type of type RTCSdpTypesdp of type DOMString, readonly, defaulting to ""toJSON()WebIDLdictionaryRTCSessionDescriptionInit{ requiredRTCSdpTypetype; DOMStringsdp= ""; };
RTCSessionDescriptionInit
            Memberstype of type RTCSdpTypesdp of type DOMStringtyperollbackWebIDLdictionaryRTCLocalSessionDescriptionInit{RTCSdpTypetype; DOMStringsdp= ""; };
RTCLocalSessionDescriptionInit
            Memberstype of type RTCSdpTypesetLocalDescriptionRTCPeerConnectionsdp of type DOMStringtyperollbackMany changes to state of an RTCPeerConnectionnegotiationneeded event. This event is fired according to
      the state of the connection's negotiation-needed flag,
      represented by a [[NegotiationNeeded]] internal slot.
This section is non-normative.
If an operation is performed on an
        RTCPeerConnectionRTCRtpTransceiverRTCDataChannel
Internal changes within the implementation can also result in the connection being marked as needing negotiation.
Note that the exact procedures for updating the negotiation-needed flag are specified below.
This section is non-normative.
The negotiation-needed flag is cleared when an
        RTCSessionDescriptionanswerRTCRtpTransceiverRTCDataChannelRTCPeerConnectionstopped transceivers have an
        associated section in the local description with matching properties,
        and, if any data channels have been created, a data section exists in
        the local description.
Note that the exact procedures for updating the negotiation-needed flag are specified below.
The process below occurs where referenced elsewhere in this document. It also may occur as a result of internal changes within the implementation that affect negotiation. If such changes occur, the user agent MUST update the negotiation-needed flag.
To update the negotiation-needed flag for connection, run the following steps:
If the length of connection.[[Operations]]
            is not 0, then set
            connection.[[UpdateNegotiationNeededFlagOnEmptyChain]]
            to true, and abort these steps.
Queue a task to run the following steps:
If connection.[[IsClosed]] is
                true, abort these steps.
If the length of connection.[[Operations]]
                is not 0, then set
                connection.[[UpdateNegotiationNeededFlagOnEmptyChain]]
                to true, and abort these steps.
If connection's signaling state is not
                "stable
The negotiation-needed flag will be
                updated once the state transitions to "stable
If the result of checking if negotiation is needed is false,
                clear the negotiation-needed flag by setting
                connection.[[NegotiationNeeded]] to
                false, and abort these steps.
If connection.[[NegotiationNeeded]] is
                already true, abort these steps.
Set connection.[[NegotiationNeeded]] to
                true.
Fire an event named negotiationneeded
The task queueing prevents negotiationneeded
Additionally, we avoid racing with negotiation methods by only
              firing negotiationneeded
To check if negotiation is needed for connection, perform the following checks:
If any implementation-specific negotiation is required, as
            described at the start of this section, return true.
            
If connection.[[LocalIceCredentialsToReplace]]
            is not empty, return true.
Let description be connection.[[CurrentLocalDescription]].
If connection has created any
            RTCDataChanneltrue.
For each transceiver in connection's set of transceivers, perform the following checks:
If transceiver.[[Stopping]] is
                true and transceiver.[[Stopped]]
                is false, return true.
If transceiver isn't stopped and isn't yet associated with an m= section
                in description, return true.
If transceiver isn't stopped and is associated with an m= section
                in description then perform the following checks:
If transceiver.[[Direction]] is
                    "sendrecvsendonlya=msid line, or the number
                    of MSIDs from the a=msid lines in this m= section,
                    or the MSID values themselves, differ from what is in
                    transceiver.sender.[[AssociatedMediaStreamIds]],
                    return true.
                    
If description is of type "offertrue. In this step, when the direction
                    is compared with a direction found in
                    [[CurrentRemoteDescription]], the description's
                    direction must be reversed to represent the peer's point of
                    view.
If description is of type "answertrue.
If transceiver is stopped and is associated with an m= section, but the
                associated m= section is not yet rejected in
                connection.[[CurrentLocalDescription]] or
                connection.[[CurrentRemoteDescription]],
                return true.
If all the preceding checks were performed and true
            was not returned, nothing remains to be negotiated; return
            false.
RTCIceCandidate InterfaceThis interface describes an ICE candidate, described in
        [ICE] Section 2. Other than
        candidatesdpMidsdpMLineIndexusernameFragmentcandidate
WebIDL[Exposed=Window] interfaceRTCIceCandidate{constructor(optionalRTCIceCandidateInitcandidateInitDict = {}); readonly attribute DOMStringcandidate; readonly attribute DOMString?sdpMid; readonly attribute unsigned short?sdpMLineIndex; readonly attribute DOMString?foundation; readonly attributeRTCIceComponent?component; readonly attribute unsigned long?priority; readonly attribute DOMString?address; readonly attributeRTCIceProtocol?protocol; readonly attribute unsigned short?port; readonly attributeRTCIceCandidateType?type; readonly attributeRTCIceTcpCandidateType?tcpType; readonly attribute DOMString?usernameFragment;RTCIceCandidateInittoJSON(); };
constructor()The RTCIceCandidate() constructor takes
                a dictionary argument, candidateInitDict, whose
                content is used to initialize the new RTCIceCandidate
When invoked, run the following steps:
sdpMidsdpMLineIndexnull,
                  throw a TypeError.Return the result of creating an RTCIceCandidate with candidateInitDict.
To create an RTCIceCandidate with a candidateInitDict dictionary, run the following steps:
RTCIceCandidatenull: foundationcomponentpriorityaddressprotocolporttypetcpTyperelatedAddressrelatedPortcandidatesdpMidsdpMLineIndexusernameFragmentcandidatecandidate-attribute
                     grammar.candidate-attribute has failed, abort
                      these steps.The constructor for RTCIceCandidatecandidatesdpMidsdpMLineIndexusernameFragmentRTCIceCandidateaddIceCandidate().
To maintain backward compatibility, any error on parsing the
                  candidate attribute is ignored. In such case, the
                  candidatecandidatefoundationprioritynull.
Most attributes below are defined in section 15.1 of [ICE].
candidate of type DOMString, readonlycandidate-attribute as defined
              in section 15.1 of [ICE]. If this RTCIceCandidatecandidatesdpMid of type DOMString, readonly, nullablenull, this contains the media stream
              "identification-tag" defined in [RFC5888] for the
              media component this candidate is associated with.sdpMLineIndex of type unsigned short, readonly,
              nullablenull, this indicates the index (starting at
                zero) of the media description in the SDP this candidate
                is associated with.
              foundation of type DOMString, readonly, nullableRTCIceTransportcomponent of type RTCIceComponentrtprtcpcomponent-id field in candidate-attribute,
              decoded to the string representation as defined in
              RTCIceComponentpriority of type unsigned long, readonly, nullableaddress of type DOMString, readonly, nullableThe address of the candidate, allowing for IPv4 addresses,
                IPv6 addresses, and fully qualified domain names (FQDNs). This
                corresponds to the connection-address field in
                candidate-attribute.
Remote candidates may be exposed, for instance
                via [[SelectedCandidatePair]].remoteaddressnull for any exposed remote candidate.
                Once a RTCPeerConnectionaddIceCandidateaddressRTCIceCandidateRTCPeerConnection
The addresses exposed in candidates gathered via ICE
                  and made visibile to the application in
                  RTCIceCandidate
These addresses are always exposed to the application, and potentially exposed to the communicating party, and can be exposed without any specific user consent (e.g. for peer connections used with data channels, or to receive media only).
These addresses can also be used as
                  temporary or persistent cross-origin states, and thus
                  contribute to the fingerprinting surface of the device.
Applications can avoid exposing addresses to the
                  communicating party, either temporarily or permanently, by
                  forcing the ICE Agent to report only relay candidates
                  via the iceTransportPolicyRTCConfiguration
To limit the addresses exposed to the application itself, browsers can offer their users different policies regarding sharing local addresses, as defined in [RTCWEB-IP-HANDLING].
protocol of type RTCIceProtocoludptcptransport field in candidate-attribute.port of type unsigned short, readonly, nullabletype of type RTCIceCandidateTypecandidate-types field in candidate-attribute.tcpType of type RTCIceTcpCandidateTypeprotocoltcptcpTypetcpTypenull. This corresponds
              to the tcp-type field in candidate-attribute.relatedAddress of type DOMString, readonly, nullablerelatedAddressrelatedAddressnull. This corresponds to the rel-address
              field in candidate-attribute.relatedPort of type unsigned short, readonly,
              nullablerelatedPortrelatedPortnull. This corresponds to
              the rel-port field in candidate-attribute.usernameFragment of type DOMString, readonly, nullableufrag as defined in section
              15.4 of [ICE].toJSON()toJSON() operation of the RTCIceCandidateRTCIceCandidateInitcandidatesdpMidsdpMLineIndexusernameFragmentRTCIceCandidatejson[attr] to value.WebIDLdictionaryRTCIceCandidateInit{ DOMStringcandidate= ""; DOMString?sdpMid= null; unsigned short?sdpMLineIndex= null; DOMString?usernameFragment= null; };
RTCIceCandidateInit
            Memberscandidate of type DOMString, defaulting to
              ""candidate-attribute as defined
              in section 15.1 of [ICE]. If this represents an
              end-of-candidates indication, candidatesdpMid of type DOMString, nullable, defaulting to
              nullnull, this contains the media stream
              "identification-tag" defined in [RFC5888] for the
              media component this candidate is associated with.sdpMLineIndex of type unsigned short, nullable,
              defaulting to nullnull, this indicates the index (starting at
              zero) of the media description in the SDP this candidate
              is associated with.usernameFragment of type DOMString, nullable,
              defaulting to nullnull, this carries the ufrag
              as defined in section 15.4 of [ICE].candidate-attribute GrammarThe candidate-attribute grammar is used to parse
          the candidateRTCIceCandidate() constructor.
The primary grammar for candidate-attribute
          is defined in section 15.1 of [ICE]. In addition, the browser
          MUST support the grammar extension for ICE TCP as defined in
          section 4.5 of [RFC6544].
The browser MAY support other grammar extensions for
          candidate-attribute as defined in other RFCs.
RTCIceProtocol EnumThe RTCIceProtocol
RTCIceTcpCandidateType EnumThe RTCIceTcpCandidateType
WebIDLenumRTCIceTcpCandidateType{ "active", "passive", "so" };
| Enumeration description | |
|---|---|
| active | An " " TCP candidate is one for which the
                  transport will attempt to open an outbound connection but
                  will not receive incoming connection requests. | 
| passive | A " " TCP candidate is one for which the
                  transport will receive incoming connection attempts but not
                  attempt a connection. | 
| so | An " " candidate is one for which the
                  transport will attempt to open a connection simultaneously
                  with its peer. | 
The user agent will typically only gather active
RTCIceCandidateType EnumThe RTCIceCandidateType
WebIDLenumRTCIceCandidateType{ "host", "srflx", "prflx", "relay" };
| Enumeration description | |
|---|---|
| host | A host candidate, as defined in Section 4.1.1.1 of [ICE]. | 
| srflx | A server reflexive candidate, as defined in Section 4.1.1.2 of [ICE]. | 
| prflx | A peer reflexive candidate, as defined in Section 4.1.1.2 of [ICE]. | 
| relay | A relay candidate, as defined in Section 7.1.3.2.1 of [ICE]. | 
RTCPeerConnectionIceEventThe icecandidate event of the RTCPeerConnectionRTCPeerConnectionIceEvent
When firing an RTCPeerConnectionIceEventRTCIceCandidatesdpMidsdpMLineIndexRTCIceCandidatesrflxrelayurl
icecandidateA candidate has been gathered. The candidateaddIceCandidate
An RTCIceTransportcandidatecandidatecandidateaddIceCandidate
All RTCIceTransportRTCPeerConnectionRTCIceGatheringStatecompletecandidatenull. This only
              exists for backwards compatibility, and this event does not need
              to be signaled to the remote peer. It's equivalent to an
              icegatheringstatechangecomplete
WebIDL[Exposed=Window] interfaceRTCPeerConnectionIceEvent: Event {constructor(DOMString type, optionalRTCPeerConnectionIceEventIniteventInitDict = {}); readonly attributeRTCIceCandidate?candidate; readonly attribute DOMString?url; };
RTCPeerConnectionIceEvent.constructor()candidate of type RTCIceCandidateThe candidateRTCIceCandidate
This attribute is set to null when an event is
                generated to indicate the end of candidate gathering.
Even where there are multiple media components,
                only one event containing a null candidate is
                fired.
url of type DOMString, readonly, nullableThe urlnull.
WebIDLdictionaryRTCPeerConnectionIceEventInit: EventInit {RTCIceCandidate?candidate; DOMString?url; };
RTCPeerConnectionIceEventInit
            Memberscandidate of type RTCIceCandidateSee the
                  candidateRTCPeerConnectionIceEvent
url of type DOMString, nullableurlRTCPeerConnectionIceErrorEventThe icecandidateerror event of the RTCPeerConnectionRTCPeerConnectionIceErrorEvent
WebIDL[Exposed=Window] interfaceRTCPeerConnectionIceErrorEvent: Event {constructor(DOMString type,RTCPeerConnectionIceErrorEventIniteventInitDict); readonly attribute DOMString?address; readonly attribute unsigned short?port; readonly attribute DOMStringurl; readonly attribute unsigned shorterrorCode; readonly attribute USVStringerrorText; };
RTCPeerConnectionIceErrorEvent.constructor()address of type DOMString, readonly, nullableThe address
On a multihomed system, multiple interfaces may be used to contact the server, and this attribute allows the application to figure out on which one the failure occurred.
If the local IP address value is not already exposed
                as part of a local candidate, the addressnull.
port of type unsigned short, readonly, nullableThe port
If the addressnull,
                 the portnull.
url of type DOMString, readonlyThe url
errorCode of type unsigned short, readonlyThe errorCode
If no host candidate can reach the server,
                errorCodeRTCIceGatheringStategathering
errorText of type USVString, readonlyThe errorText
If the server could not be reached, errorText
WebIDLdictionaryRTCPeerConnectionIceErrorEventInit: EventInit { DOMString?address; unsigned short?port; DOMStringurl; required unsigned shorterrorCode; USVStringstatusText; };
RTCPeerConnectionIceErrorEventInit
              Membersaddress of type DOMString, nullableThe local address used to communicate with the STUN or TURN
                server, or null.
port of type unsigned short, nullableThe local port used to communicate with the STUN or TURN
                server, or null.
url of type DOMStringThe STUN or TURN URL that identifies the STUN or TURN server for which the failure occurred.
errorCode of type unsigned short, requiredThe numeric STUN error code returned by the STUN or TURN server.
statusText of type USVStringThe STUN reason text returned by the STUN or TURN server.
The certificates that RTCPeerConnectionRTCCertificategenerateCertificateRTCConfigurationRTCPeerConnection
The explicit certificate management functions provided here are
      optional. If an application does not provide the
      certificatesRTCPeerConnection
WebIDLpartial interfaceRTCPeerConnection{ static Promise<RTCCertificate>generateCertificate(AlgorithmIdentifier keygenAlgorithm); };
generateCertificate, staticThe generateCertificateRTCCertificateRTCCertificateRTCPeerConnection
The keygenAlgorithm argument is used to control how the private key associated with the certificate is generated. The keygenAlgorithm argument uses the WebCrypto [WebCryptoAPI] AlgorithmIdentifier type.
The following values MUST be supported by a user agent:
              { name: "RSASSA-PKCS1-v1_5",
              modulusLength: 2048, publicExponent: new Uint8Array([1, 0, 1]),
              hash: "SHA-256" }, and { name: "ECDSA",
              namedCurve: "P-256"
              }.
It is expected that a user agent will have a small or even fixed set of values that it will accept.
The certificate produced by this process also contains a
              signature. The validity of this signature is only relevant for
              compatibility reasons. Only the public key and the resulting
              certificate fingerprint are used by
              RTCPeerConnection
The resulting certificate MUST NOT include information that can be linked to a user or user agent. Randomized values for distinguished name and serial number SHOULD be used.
When the method is called, the user agent MUST run the following steps:
Let keygenAlgorithm be the first argument to
                  generateCertificate
Let expires be a DOMTimeStamp value
                  of 2592000000.
This means the certificate will by default expire in 30 days
                    from the time of the generateCertificate
If keygenAlgorithm is an object, run the following steps:
Let certificateExpiration be the result of
                      converting
                      the ECMAScript object represented by keygenAlgorithm to an
                      RTCCertificateExpiration
If the conversion fails with an error, return a promise that is rejected with error.
If certificateExpiration.expiresundefined, set expires to
                      certificateExpiration.expires
If expires is greater than 31536000000, set expires to 31536000000.
This means the certificate cannot be valid for longer than 365 days
                        from the time of the generateCertificate
A user agent MAY further cap the value of expires.
Let normalizedKeygenAlgorithm be the result of
                  normalizing an algorithm
                  with an operation name of generateKey and a
                  supportedAlgorithms
                  value specific to production of certificates for
                  RTCPeerConnection
If the above normalization step fails with an error, return a promise that is rejected with error.
If the normalizedKeygenAlgorithm parameter
                  identifies an algorithm that the user agent cannot
                  or will not use to generate a certificate for
                  RTCPeerConnectionDOMException of type NotSupportedError. In
                  particular, normalizedKeygenAlgorithm MUST be an
                  asymmetric algorithm that can be used to produce a signature
                  used to authenticate DTLS connections.
Let p be a new promise.
Run the following steps in parallel:
Perform the generate key operation specified by normalizedKeygenAlgorithm using keygenAlgorithm.
Let generatedKeyingMaterial and generatedKeyCertificate be the private keying material and certificate generated by the above step.
Let certificate be a new
                      RTCCertificate
Set certificate.[[Expires]] to the current time plus expires value.
Set certificate.[[Origin]] to the current settings object's origin.
Store the generatedKeyingMaterial in a secure module, and let handle be a reference identifier to it.
Set certificate.[[KeyingMaterialHandle]] to handle.
Set certificate.[[Certificate]] to generatedCertificate.
Resolve p with certificate.
Return p.
RTCCertificateExpiration DictionaryRTCCertificateExpirationgenerateCertificate
WebIDLdictionaryRTCCertificateExpiration{ [EnforceRange] DOMTimeStampexpires; };
expires, of type DOMTimeStampAn optional expiresgenerateCertificateRTCCertificate
RTCCertificate InterfaceThe RTCCertificateRTCPeerConnection
WebIDL[Exposed=Window, Serializable] interfaceRTCCertificate{ readonly attribute DOMTimeStampexpires; sequence<RTCDtlsFingerprint>getFingerprints(); };
expires of type DOMTimeStamp, readonlyThe expires attribute indicates the date and time
                in milliseconds relative to 1970-01-01T00:00:00Z after which
                the certificate will be considered invalid by the browser.
                After this time, attempts to construct an
                RTCPeerConnection
Note that this value might not be reflected in a
                notAfter parameter in the certificate itself.
getFingerprintsReturns the list of certificate fingerprints, one of which is computed with the digest algorithm used in the certificate signature.
For the purposes of this API, the [[Certificate]] slot
        contains unstructured binary data. No mechanism is provided for
        applications to access the [[KeyingMaterialHandle]] internal
        slot or the keying material it references.
        Implementations MUST support applications storing and retrieving
        RTCCertificate
RTCCertificate
expiresTheir deserialization steps, given serialized and value, are:
expiresSupporting structured cloning in this manner
        allows RTCCertificatepostMessage() [html].  However, the object cannot
        be used by any other origin than the one that originally created it.
The RTP media API lets a web application send and receive
    MediaStreamTracks over a peer-to-peer connection. Tracks, when
    added to an RTCPeerConnection
There is not an exact 1:1 correspondence between tracks sent
    by one RTCPeerConnectionreplaceTrackRTCRtpSenderRTCRtpReceiveraddTransceiverreplaceTrackRTCRtpSenderRTCRtpReceiverRTCRtpTransceivermid
When sending media, the sender may need to rescale or resample the media to meet various requirements including the envelope negotiated by SDP.
Following the rules in [JSEP] (section 3.6.), the video MAY be downscaled in order to fit the SDP constraints. The media MUST NOT be upscaled to create fake data that did not occur in the input source, the media MUST NOT be cropped except as needed to satisfy constraints on pixel counts, and the aspect ratio MUST NOT be changed.
The WebRTC Working Group is seeking implementation feedback on the need and timeline for a more complex handling of this situation. Some possible designs have been discussed in GitHub issue 1283.
When video is rescaled, for example for certain combinations
    of width or height and
    scaleResolutionDownBy
The actual encoding and transmission of MediaStreamTracks
    is managed through objects called RTCRtpSenderMediaStreamTracks is
    managed through objects called RTCRtpReceiverRTCRtpSenderRTCRtpReceiver
The encoding and transmission of each MediaStreamTrack
    SHOULD be made such that its characteristics (width, height and frameRate
    for video tracks; volume, sampleSize, sampleRate and channelCount for audio
    tracks) are to a reasonable degree retained by the track created on the
    remote side. There are situations when this does not apply, there may for
    example be resource constraints at either endpoint or in the network or
    there may be RTCRtpSender
      An RTCPeerConnectionRTCRtpTransceiverRTCPeerConnectionRTCRtpSenderRTCRtpReceiverRTCRtpTransceiverRTCRtpTransceiverMediaStreamTrack to an
      RTCPeerConnectionaddTrack()
      method, or explicitly when the application uses the
      addTransceiverMediaStreamTrack and RTCRtpReceivertrack
      In order for an RTCRtpTransceiverRTCRtpTransceiver
When creating an offer, enough media descriptions will be generated to cover all transceivers on that end. When this offer is set as the local description, any disassociated transceivers get associated with media descriptions in the offer.
      When an offer is set as the remote description, any media descriptions
      in it not yet associated with a transceiver get associated with a new or
      existing transceiver. In this case, only disassociated transceivers that were
      created via the addTrack() method may be associated.
      Disassociated transceivers created via the
      addTransceiver() method, however, won't get associated
      even if media descriptions are available in the remote offer. Instead,
      new transceivers will be created and associated if there aren't
      enough addTrack()-created transceivers. This sets
      addTrack()-created and
      addTransceiver()-created transceivers apart in a
      critical way that is not observable from inspecting their attributes.
    
      When creating an answer, only media media descriptions that were
      present in the offer may be listed in the
      answer. As a consequence, any transceivers that were not associated when
      setting the remote offer remain disassociated after setting the local
      answer. This can be remedied by the answerer creating a follow-up offer,
      initiating another offer/answer exchange, or in the case of using
      addTrack()-created transceivers, making sure that
      enough media descriptions are offered in the initial exchange.
    
The RTP media API extends the RTCPeerConnection
WebIDLpartial interfaceRTCPeerConnection{ sequence<RTCRtpSender>getSenders(); sequence<RTCRtpReceiver>getReceivers(); sequence<RTCRtpTransceiver>getTransceivers();RTCRtpSenderaddTrack(MediaStreamTrack track, MediaStream... streams); undefinedremoveTrack(RTCRtpSendersender);RTCRtpTransceiveraddTransceiver((MediaStreamTrack or DOMString) trackOrKind, optionalRTCRtpTransceiverInitinit = {}); attribute EventHandlerontrack; };
ontrack of type EventHandlerThe event type of this event handler is
              track
getSendersReturns a sequence of RTCRtpSenderRTCRtpTransceiverRTCPeerConnection
When the getSendersCollectSenders algorithm.
We define the CollectSenders algorithm as follows:
CollectTransceivers algorithm.false add
                      transceiver.[[Sender]] to
                      senders.getReceiversReturns a sequence of RTCRtpReceiverRTCRtpTransceiverRTCPeerConnection
When the getReceivers
CollectTransceivers algorithm.false add
                      transceiver.[[Receiver]] to
                      receivers.getTransceiversReturns a sequence of RTCRtpTransceiverRTCPeerConnection
The getTransceiversCollectTransceivers algorithm.
We define the CollectTransceivers algorithm as follows:
RTCRtpTransceiverRTCPeerConnectionaddTrackAdds a new track to the RTCPeerConnectionMediaStreams.
When the addTrack
Let connection be the
                  RTCPeerConnection
Let track be the
                  MediaStreamTrack object indicated by the
                  method's first argument.
Let kind be track.kind.
Let streams be a list of
                  MediaStream objects constructed from the
                  method's remaining arguments, or an empty list if the method
                  was called with a single argument.
If connection.[[IsClosed]] is
                  true, throw an
                  InvalidStateError.
Let senders be the result of executing the
                  CollectSenders algorithm. If an
                  RTCRtpSenderInvalidAccessError.
The steps below describe how to determine if an existing
                  sender can be reused. Doing so will cause future calls to
                  createOffercreateAnswersendrecv or sendonly and add the
                  MSID of the sender's streams, as defined in [JSEP] (section 5.2.2. and section 5.3.2.).
If any RTCRtpSendernull
                  otherwise:
The sender's track is null.
The transceiver kind of the
                      RTCRtpTransceiver
The [[Stopping]] slot of the
                      RTCRtpTransceiverfalse.
The sender has never been used to send. More
                      precisely, the [[CurrentDirection]] slot of the
                      RTCRtpTransceiversendrecvsendonly
If sender is not null, run the
                  following steps to use that sender:
Set sender.[[SenderTrack]] to track.
Set sender.[[AssociatedMediaStreamIds]] to an empty set.
For each stream in streams, add stream.id to [[AssociatedMediaStreamIds]] if it's not already there.
Let transceiver be the
                      RTCRtpTransceiver
If transceiver.[[Direction]] is
                      "recvonlysendrecv
If transceiver.[[Direction]]
                      is "inactivesendonly
If sender is null, run the
                  following steps:
Create an RTCRtpSender with track, kind and streams, and let sender be the result.
Create an RTCRtpReceiver with kind, and let receiver be the result.
Create an RTCRtpTransceiver with
                      sender, receiver and
                      an RTCRtpTransceiverDirectionsendrecv
Add transceiver to connection's set of transceivers.
A track could have contents that are inaccessible to the
                  application. This can be due to anything that would make
                  a track 
                  CORS cross-origin. These tracks can be supplied to the
                  addTrack() method, and have an
                  RTCRtpSender
Note that this property can change over time.
Update the negotiation-needed flag for connection.
Return sender.
removeTrackStops sending media from sender. The
              RTCRtpSendergetSenderscreateOfferrecvonlyinactive
When the other peer stops sending a track in this manner, the
              track is removed from any remote MediaStreams
              that were initially revealed in the track event, and
              if the MediaStreamTrack is not already muted,
              a mute event is
              fired at the track.
removeTrack()
              can be achieved by setting the
              RTCRtpTransceiverdirectionRTCRtpSenderreplaceTrackreplaceTrack() is
              asynchronous and removeTrack() is synchronous.When the removeTrack
Let sender be the argument to
                  removeTrack
Let connection be the
                  RTCPeerConnection
If connection.[[IsClosed]] is
                  true, throw an
                  InvalidStateError.
If sender was not created by
                  connection, throw an
                  InvalidAccessError.
Let senders be the result of executing the
                  CollectSenders algorithm.
If sender is not in senders (which
                  indicates its transceiver was stopped or removed due to
                  setting an RTCSessionDescription
                  of type "rollback
If sender.[[SenderTrack]] is null, abort these steps.
Set sender.[[SenderTrack]] to null.
Let transceiver be the
                  RTCRtpTransceiver
If transceiver.[[Direction]] is
                  "sendrecvrecvonly
If transceiver.[[Direction]]
                  is "sendonlyinactive
Update the negotiation-needed flag for connection.
addTransceiverCreate a new RTCRtpTransceiver
Adding a transceiver will cause future calls to
              createOffer
The initial value of midRTCSessionDescription
The sendEncodings
When this method is invoked, the user agent MUST run the following steps:
Let init be the second argument.
Let streams be init.streams
Let sendEncodings be init.sendEncodings
Let direction be init.direction
If the first argument is a string, let it be kind and run the following steps:
If kind is not a legal
                      MediaStreamTrack kind,
                      throw a TypeError.
Let track be null.
If the first argument is a
                  MediaStreamTrack, let it be
                  track and let kind be
                  track.kind.
If connection.[[IsClosed]] is
                  true, throw an
                  InvalidStateError.
Verify that each ridTypeError.
If any RTCRtpEncodingParametersridInvalidAccessError.
Verify that each scaleResolutionDownByscaleResolutionDownByRangeError.
Let maxN be the maximum number of total simultaneous
                    encodings the user agent may support for this kind, at
                    minimum 1.This should be an optimistic number since the
                    codec to be used is not known yet.
If sendEncodings contains any encoding whose
                    scaleResolutionDownByscaleResolutionDownBy
If the number of RTCRtpEncodingParameters
scaleResolutionDownByscaleResolutionDownBy2^(length of sendEncodings - encoding
                     index - 1). This results in smaller-to-larger
                     resolutions where the last encoding has no scaling applied
                     to it, e.g. 4:2:1 if the length is 3.
                   If the number of RTCRtpEncodingParameters1, then remove any
                     rid
RTCRtpEncodingParameterssetParametersCreate an RTCRtpSender with track, kind, streams and sendEncodings and let sender be the result.
If sendEncodings is set, then subsequent calls
                  to createOffersetRemoteDescriptionRTCRtpSendersendergetParameters() will reflect the
                  encodings negotiated.
Create an RTCRtpReceiver with kind and let receiver be the result.
Create an RTCRtpTransceiver with sender, receiver and direction, and let transceiver be the result.
Add transceiver to connection's set of transceivers.
Update the negotiation-needed flag for connection.
Return transceiver.
WebIDLdictionaryRTCRtpTransceiverInit{RTCRtpTransceiverDirectiondirection= "sendrecv"; sequence<MediaStream>streams= []; sequence<RTCRtpEncodingParameters>sendEncodings= []; };
RTCRtpTransceiverInit
          Membersdirection of type RTCRtpTransceiverDirectionsendrecvRTCRtpTransceiverstreams of type sequence<MediaStream>When the remote PeerConnection's track event fires
              corresponding to the RTCRtpReceiver
sendEncodings of type sequence<RTCRtpEncodingParametersA sequence containing parameters for sending RTP encodings of media.
WebIDLenumRTCRtpTransceiverDirection{ "sendrecv", "sendonly", "recvonly", "inactive", "stopped" };
| RTCRtpTransceiverDirectionEnumeration description | |
|---|---|
| sendrecv | The 'ssender will offer to
              send RTP, and will send RTP if the remote peer accepts and
              sender.().[i].istruefor any value of i. The'swill offer to receive RTP, and
              will receive RTP if the remote peer accepts. | 
| sendonly | The 'ssender will offer to
              send RTP, and will send RTP if the remote peer accepts and
              sender.().[i].istruefor any value of i. The'swill not offer to receive RTP,
              and will not receive RTP. | 
| recvonly | The 'swill not offer to send RTP, and
              will not send RTP. The'swill offer to receive RTP, and
              will receive RTP if the remote peer accepts. | 
| inactive | The 'swill not offer to send RTP, and
              will not send RTP. The'swill not offer to receive RTP,
              and will not receive RTP. | 
| stopped | The will neither send
              nor receive RTP. It will generate a zero port in the offer. In
              answers, itswill not offer to
              send RTP, and itswill not
              offer to receive RTP. This is a terminal state. | 
An application can reject incoming media descriptions by setting
        the transceiver's direction to either "inactivesendonlyRTCRtpTransceiverstop()
        and subsequently initiate negotiation from its end.
To 
        process remote tracks given an RTCRtpTransceiver
Set the associated remote streams with transceiver.[[Receiver]], msids, addList, and removeList.
If direction is "sendrecvrecvonlysendrecvrecvonly
If direction is "sendonlyinactivefalse.
If direction is "sendonlyinactivesendrecvrecvonly
Set transceiver.[[FiredDirection]] to direction.
To 
        process the addition of a remote track given an
        RTCRtpTransceiver
Let receiver be transceiver.[[Receiver]].
Let track be receiver.[[ReceiverTrack]].
Let streams be receiver.[[AssociatedRemoteMediaStreams]].
Create a new RTCTrackEventInit
To 
        process the removal of a remote track with an
        RTCRtpTransceiver
Let receiver be transceiver.[[Receiver]].
Let track be receiver.[[ReceiverTrack]].
If track.muted is false,
            add track to muteTracks.
To set the associated remote streams given
        RTCRtpReceiver
Let connection be the
            RTCPeerConnection
For each MSID in msids, unless a
            MediaStream object has previously been created
            with that id for this connection, create a
            MediaStream object with that
            id.
Let streams be a list of the
            MediaStream objects created for this
            connection with the ids corresponding to
            msids.
Let track be receiver.[[ReceiverTrack]].
For each stream in receiver.[[AssociatedRemoteMediaStreams]] that is not present in streams, add stream and track as a pair to removeList.
For each stream in streams that is not present in receiver.[[AssociatedRemoteMediaStreams]], add stream and track as a pair to addList.
Set receiver.[[AssociatedRemoteMediaStreams]] to streams.
RTCRtpSender InterfaceThe RTCRtpSenderMediaStreamTrack is
      encoded and transmitted to a remote peer. When setParametersRTCRtpSender
To create an RTCRtpSender with a
      MediaStreamTrack, track, a string,
      kind, a list of
      MediaStream objects, streams, and
      optionally a list of RTCRtpEncodingParameters
Let sender be a new RTCRtpSender
Let sender have a [[SenderTrack]] internal slot initialized to track.
Let sender have a [[SenderTransport]] internal
          slot initialized to null.
Let sender have a
          [[LastStableStateSenderTransport]] internal slot initialized
          to null.
Let sender have a [[Dtmf]] internal
          slot initialized to null.
If kind is "audio" then
          create an RTCDTMFSender dtmf and set
          the [[Dtmf]] internal slot to dtmf.
        
Let sender have an
          [[AssociatedMediaStreamIds]] internal slot, representing a
          list of Ids of MediaStream objects that this
          sender is to be associated with. The
          [[AssociatedMediaStreamIds]] slot is used when
          sender is represented in SDP as described in
          [JSEP] (section 5.2.1.).
Set sender.[[AssociatedMediaStreamIds]] to an empty set.
For each stream in streams, add stream.id to [[AssociatedMediaStreamIds]] if it's not already there.
Let sender have a [[SendEncodings]]
          internal slot, representing a list of
          RTCRtpEncodingParameters
If sendEncodings is given as input to this algorithm,
          and is non-empty, set the [[SendEncodings]] slot to
          sendEncodings. Otherwise, set it to a list containing a
          single RTCRtpEncodingParametersactivetrue.
Let sender have a [[SendCodecs]]
          internal slot, representing a list of
          RTCRtpCodecParameters
Let sender have a [[LastReturnedParameters]]
          internal slot, which will be used to match
          getParameterssetParameters
Return sender.
WebIDL[Exposed=Window] interfaceRTCRtpSender{ readonly attribute MediaStreamTrack?track; readonly attributeRTCDtlsTransport?transport; staticRTCRtpCapabilities?getCapabilities(DOMString kind); Promise<undefined>setParameters(RTCRtpSendParametersparameters);RTCRtpSendParametersgetParameters(); Promise<undefined>replaceTrack(MediaStreamTrack? withTrack); undefinedsetStreams(MediaStream... streams); Promise<RTCStatsReport>getStats(); };
track of type MediaStreamTrack, readonly,
            nullableThe trackRTCRtpSendertrackRTCRtpSenderRTCRtpSendertracknull then
              the RTCRtpSender
transport of type RTCDtlsTransportThe transporttrackRTCDtlsTransporttransportRTCRtpSendertransport
On getting, the attribute MUST return the value of the [[SenderTransport]] slot.
getCapabilities, staticThe getCapabilities()
              method returns the most optimistic view of the capabilities of the
              system for sending media of the given kind. It does not reserve
              any resources, ports, or other state but is meant to provide a
              way to discover the types of capabilities of the browser
              including which codecs may be supported. User agents
              MUST support kind values of "audio"
              and "video". If the system has no capabilities
              corresponding to the value of the kind
              argument, getCapabilitiesnull.
These capabilities provide generally
              persistent cross-origin information on the device and thus
              increases the fingerprinting surface of the application. In
              privacy-sensitive contexts, browsers can consider mitigations
              such as reporting only a common subset of the capabilities.
setParametersThe setParameterstrack
When the setParameters
RTCRtpSendersetParametersRTCRtpTransceivertrue, return a promise rejected with a newly
                created
                InvalidStateError.null, return a promise
                rejected with a newly
                created
                InvalidStateError.encodingscodecsRTCRtpEncodingParametersInvalidModificationError:
                   encodings.length is different from N.
                     Verify that each scaleResolutionDownByscaleResolutionDownByRangeError.
null.encodingsundefined.
                      RTCErrorerrorDetailhardware-encoder-not-availableRTCErrorerrorDetailhardware-encoder-errorOperationError.setParametersRTCRtpSendParameterscnamemaxBitratemaxBitrate
getParametersThe getParameters() method
              returns the RTCRtpSendertrackRTCRtpReceiver
When getParameters
Let sender be the RTCRtpSender
If sender.[[LastReturnedParameters]] is
                  not null, return
                  sender.[[LastReturnedParameters]], and abort
                  these steps.
Let result be a new
                  RTCRtpSendParameters
transactionIdencodingsheaderExtensionscodecsrtcpcnameRTCPeerConnectionrtcpreducedSizetrue if reduced-size RTCP has been negotiated
                      for sending, and false otherwise.
                    Set sender.[[LastReturnedParameters]] to result.
Queue a task that sets
                  sender.[[LastReturnedParameters]] to
                  null.
Return result.
getParameterssetParameters
async function updateParameters() {
  try {
    const params = sender.getParameters();
    // ... make changes to parameters
    params.encodings[0].active = false;
    await sender.setParameters(params);
  } catch (err) {
    console.error(err);
  }
}After a completed call to setParametersgetParameters
replaceTrackAttempts to replace the RTCRtpSendertracknull track), without renegotiation.
When the replaceTrack
Let sender be the
                  RTCRtpSenderreplaceTrack
Let transceiver be the
                  RTCRtpTransceiver
Let connection be the
                  RTCPeerConnection
Let withTrack be the argument to this method.
If withTrack is non-null and
                  withTrack.kind differs from the
                  transceiver kind of transceiver, return a
                  promise rejected with a newly
                  created
                  TypeError.
Return the result of chaining the following steps to connection's operations chain:
If transceiver.[[Stopped]] is
                    true, return a promise rejected
                    with a newly created
                    InvalidStateError.
Let p be a new promise.
Let sending be true if
                      transceiver.[[CurrentDirection]]
                      is "sendrecvsendonlyfalse otherwise.
Run the following steps in parallel:
If sending is true, and
                          withTrack is null, have the
                          sender stop sending.
If sending is true, and
                          withTrack is not null,
                          determine if withTrack can be sent
                          immediately by the sender without violating the
                          sender's already-negotiated envelope, and if it
                          cannot, then reject p with a newly
                          created
                          InvalidModificationError, and abort these
                          steps.
If sending is true, and
                          withTrack is not null, have
                          the sender switch seamlessly to transmitting
                          withTrack instead of the sender's existing
                          track.
Queue a task that runs the following steps:
If connection.[[IsClosed]]
                              is true, abort these steps.
Set sender.[[SenderTrack]] to withTrack.
Resolve p with
                              undefined.
Return p.
Changing dimensions and/or frame rates might not require negotiation. Cases that may require negotiation include:
setStreamsSets the MediaStreams to be associated with this
              sender's track.
When the setStreams
Let sender be the
                  RTCRtpSender
Let connection be the
                  RTCPeerConnection
If connection.[[IsClosed]] is
                  true, throw an
                  InvalidStateError.
Let streams be a list of
                  MediaStream objects constructed from the
                  method's arguments, or an empty list if the method was called
                  without arguments.
Set sender.[[AssociatedMediaStreamIds]] to an empty set.
For each stream in streams, add stream.id to [[AssociatedMediaStreamIds]] if it's not already there.
Update the negotiation-needed flag for connection.
getStatsGathers stats for this sender only and reports the result asynchronously.
When the 
              getStats() method is invoked, the user
              agent MUST run the following steps:
Let selector be the
                  RTCRtpSender
Let p be a new promise, and run the following steps in parallel:
Gather the stats indicated by selector according to the stats selection algorithm.
Resolve p with the resulting
                      RTCStatsReport
Return p.
RTCRtpParameters DictionaryWebIDLdictionaryRTCRtpParameters{ required sequence<RTCRtpHeaderExtensionParameters>headerExtensions; requiredRTCRtcpParametersrtcp; required sequence<RTCRtpCodecParameters>codecs; };
RTCRtpParametersheaderExtensions of type sequence<RTCRtpHeaderExtensionParametersA sequence containing parameters for RTP header extensions. Read-only parameter.
rtcp of type RTCRtcpParametersParameters used for RTCP. Read-only parameter.
codecs of type sequence<RTCRtpCodecParametersA sequence containing the media codecs that an
              RTCRtpSendercodecsmimeTypeaudio/rtx or
              video/rtx, and an sdpFmtpLine
RTCRtpSendParameters DictionaryWebIDLdictionaryRTCRtpSendParameters:RTCRtpParameters{ required DOMStringtransactionId; required sequence<RTCRtpEncodingParameters>encodings; };
RTCRtpSendParameterstransactionId of type DOMString, requiredA unique identifier for the last set of parameters applied.
              Ensures that setParametersgetParameters
encodings of type sequence<RTCRtpEncodingParametersA sequence containing parameters for RTP encodings of media.
RTCRtpReceiveParameters DictionaryWebIDLdictionaryRTCRtpReceiveParameters:RTCRtpParameters{ };
RTCRtpCodingParameters DictionaryWebIDLdictionaryRTCRtpCodingParameters{ DOMStringrid; };
RTCRtpCodingParametersrid of type DOMStringIf set, this RTP encoding will be sent with the RID header
              extension as defined by [JSEP] (section 5.2.1.). The RID is not modifiable via
              setParametersaddTransceiver
RTCRtpDecodingParameters DictionaryWebIDLdictionaryRTCRtpDecodingParameters:RTCRtpCodingParameters{};
RTCRtpEncodingParameters DictionaryWebIDLdictionaryRTCRtpEncodingParameters:RTCRtpCodingParameters{ booleanactive= true; unsigned longmaxBitrate; doublescaleResolutionDownBy; };
RTCRtpEncodingParametersactive of type boolean, defaulting to
            trueIndicates that this
              encoding is actively being sent. Setting it to false
              causes this encoding to no longer be sent. Setting it to true
              causes this encoding to be sent. Since setting the value to false
              does not cause the SSRC to be removed, an RTCP BYE is not sent.
maxBitrate of type unsigned longWhen present, indicates the maximum bitrate that can be used to send this
              encoding. The user agent is free to allocate bandwidth between the encodings,
              as long as the maxBitratemaxBitratemaxBitrate
How the bitrate is achieved is media and encoding dependent. For video, a frame will always be sent as fast as possible, but frames may be dropped until bitrate is low enough. Thus, even a bitrate of zero will allow sending one frame. For audio, it might be necessary to stop playing if the bitrate does not allow the chosen encoding enough bandwidth to be sent.
scaleResolutionDownBy of type
            doubleThis member is only present if the sender's kind
              is "video". The video's
              resolution will be scaled down in each dimension by the given
              value before sending. For example, if the value is 2.0, the video
              will be scaled down by a factor of 2 in each dimension, resulting
              in sending a video of one quarter the size. If the value is 1.0,
              the video will not be affected. The value must be greater than or
              equal to 1.0. By default, scaling is applied by a factor of two to
              the power of the layer's number, in order of smaller to higher
              resolutions, e.g. 4:2:1. If there is only one layer, the sender
              will by default not apply any scaling, (i.e.
              scaleResolutionDownBy
RTCRtcpParameters DictionaryWebIDLdictionaryRTCRtcpParameters{ DOMStringcname; booleanreducedSize; };
RTCRtcpParameterscname of type DOMStringThe Canonical Name (CNAME) used by RTCP (e.g. in SDES messages). Read-only parameter.
reducedSize of type booleanWhether reduced size RTCP [RFC5506] is configured (if true) or compound RTCP as specified in [RFC3550] (if false). Read-only parameter.
RTCRtpHeaderExtensionParameters DictionaryWebIDLdictionaryRTCRtpHeaderExtensionParameters{ required DOMStringuri; required unsigned shortid; booleanencrypted= false; };
RTCRtpHeaderExtensionParametersuri of type DOMString, requiredThe URI of the RTP header extension, as defined in [RFC5285]. Read-only parameter.
id of type unsigned short, requiredThe value put in the RTP packet to identify the header extension. Read-only parameter.
encrypted of type booleanWhether the header extension is encrypted or not. Read-only parameter.
The RTCRtpHeaderExtensionParametersRTCRtpSenderRTCRtpReceiverRTCRtpTransceiver
sendergetParameters().headerExtensionsreceivergetParameters().headerExtensionssendergetParameters().headerExtensionsreceivergetParameters().headerExtensionssendergetParameters().headerExtensionsreceivergetParameters().headerExtensionsRTCRtpCodecParameters DictionaryWebIDLdictionaryRTCRtpCodecParameters{ required octetpayloadType; required DOMStringmimeType; required unsigned longclockRate; unsigned shortchannels; DOMStringsdpFmtpLine; };
RTCRtpCodecParameterspayloadType of type octet, requiredThe RTP payload type used to identify this codec. Read-only parameter.
mimeType of type DOMString, requiredThe codec MIME media type/subtype. Valid media types and subtypes are listed in [IANA-RTP-2]. Read-only parameter.
clockRate of type unsigned long, requiredThe codec clock rate expressed in Hertz. Read-only parameter.
channels of type unsigned shortWhen present, indicates the number of channels (mono=1, stereo=2). Read-only parameter.
sdpFmtpLine of type DOMStringThe "format specific parameters" field from the a=fmtp line
              in the SDP corresponding to the codec, if one exists, as defined
              by [JSEP] (section 5.8.). For an
              RTCRtpSenderRTCRtpReceiver
RTCRtpCapabilities DictionaryWebIDLdictionaryRTCRtpCapabilities{ required sequence<RTCRtpCodecCapability>codecs; required sequence<RTCRtpHeaderExtensionCapability>headerExtensions; };
RTCRtpCapabilitiescodecs of type sequence<RTCRtpCodecCapabilitySupported media codecs as well as entries for RTX, RED and FEC
              mechanisms. There will only be a single entry in
              codecssdpFmtpLine
headerExtensions of type sequence<RTCRtpHeaderExtensionCapabilitySupported RTP header extensions.
RTCRtpCodecCapability DictionaryWebIDLdictionaryRTCRtpCodecCapability{ required DOMStringmimeType; required unsigned longclockRate; unsigned shortchannels; DOMStringsdpFmtpLine; };
RTCRtpCodecCapabilityThe RTCRtpCodecCapability
mimeType of type DOMString, requiredThe codec MIME media type/subtype. Valid media types and subtypes are listed in [IANA-RTP-2].
clockRate of type unsigned long, requiredThe codec clock rate expressed in Hertz.
channels of type unsigned shortIf present, indicates the maximum number of channels (mono=1, stereo=2).
sdpFmtpLine of type DOMStringThe "format specific parameters" field from the a=fmtp line
              in the SDP corresponding to the codec, if one exists.
RTCRtpHeaderExtensionCapability DictionaryWebIDLdictionaryRTCRtpHeaderExtensionCapability{ DOMStringuri; };
RTCRtpHeaderExtensionCapabilityuri of type DOMStringThe URI of the RTP header extension, as defined in [RFC5285].
RTCRtpReceiver InterfaceThe RTCRtpReceiverMediaStreamTrack.
To create an RTCRtpReceiver with a string, kind, run the following steps:
Let receiver be a new RTCRtpReceiver
Let track be a new MediaStreamTrack
          object [GETUSERMEDIA]. The source of track is a
          remote source provided by receiver. Note that
          the track.id is generated by the user agent and does
          not map to any track IDs on the remote side.
Initialize track.kind to kind.
Initialize track.label to the result of concatenating
          the string "remote " with kind.
Initialize track.readyState to live.
Initialize track.muted to true. See the
          MediaStreamTrack section
          about how the muted attribute reflects if a
          MediaStreamTrack is receiving media data or
          not.
Let receiver have a [[ReceiverTrack]] internal slot initialized to track.
Let receiver have a [[ReceiverTransport]] internal
          slot initialized to null.
Let receiver have a
          [[LastStableStateReceiverTransport]] internal slot initialized
          to null.
Let receiver have an
          [[AssociatedRemoteMediaStreams]] internal slot,
          representing a list of MediaStream objects that
          the MediaStreamTrack object of this receiver is
          associated with, and initialized to an empty list.
Let receiver have a [[LastStableStateAssociatedRemoteMediaStreams]] internal slot and initialize it to an empty list.
Let receiver have a [[ReceiveCodecs]]
          internal slot, representing a list of
          RTCRtpCodecParameters
Let receiver have a [[LastStableStateReceiveCodecs]] internal slot and initialize it to an empty list.
Return receiver.
WebIDL[Exposed=Window] interfaceRTCRtpReceiver{ readonly attribute MediaStreamTracktrack; readonly attributeRTCDtlsTransport?transport; staticRTCRtpCapabilities?getCapabilities(DOMString kind);RTCRtpReceiveParametersgetParameters(); sequence<RTCRtpContributingSource>getContributingSources(); sequence<RTCRtpSynchronizationSource>getSynchronizationSources(); Promise<RTCStatsReport>getStats(); };
track of type MediaStreamTrack, readonlyThe trackRTCRtpReceiver
Note that trackstop() is final, although
              clones are not affected. Since
              receiver.trackstop()
              does not implicitly stop receiver, Receiver
              Reports continue to be sent. On getting, the attribute MUST
              return the value of the [[ReceiverTrack]] slot.
transport of type RTCDtlsTransportThe transporttrackRTCDtlsTransporttransportnull. When bundling is
              used, multiple RTCRtpReceivertransport
On getting, the attribute MUST return the value of the [[ReceiverTransport]] slot.
getCapabilities, staticThe getCapabilities()
              method returns the most optimistic view of the capabilities of
              the system for receiving media of the given kind. It does not
              reserve any resources, ports, or other state but is meant to
              provide a way to discover the types of capabilities of the
              browser including which codecs may be supported. User agents
              MUST support kind values of "audio"
              and "video". If the system has no capabilities
              corresponding to the value of the kind argument,
              getCapabilitiesnull.
These capabilities provide generally
              persistent cross-origin information on the device and thus
              increases the fingerprinting surface of the application. In
              privacy-sensitive contexts, browsers can consider mitigations
              such as reporting only a common subset of the capabilities.
getParametersThe getParameters() method returns the
              RTCRtpReceivertrack
When getParametersRTCRtpReceiveParameters
headerExtensionscodecs
getParametersgetParametersrtcpreducedSizetrue if the receiver is currently prepared to
                  receive reduced-size RTCP packets, and false otherwise.
                  rtcpcnamegetContributingSourcesReturns an RTCRtpContributingSourceRTCRtpReceivertimestamp
getSynchronizationSourcesReturns an RTCRtpSynchronizationSourceRTCRtpReceivertimestamp
getStatsGathers stats for this receiver only and reports the result asynchronously.
When the getStats() method is invoked, the user
              agent MUST run the following steps:
Let selector be the
                  RTCRtpReceiver
Let p be a new promise, and run the following steps in parallel:
Gather the stats indicated by selector according to the stats selection algorithm.
Resolve p with the resulting
                      RTCStatsReport
Return p.
The RTCRtpContributingSource and
      RTCRtpSynchronizationSource dictionaries contain information
      about a given contributing source (CSRC) or synchronization source (SSRC)
      respectively. When an audio or video frame from one or more RTP packets
      is delivered to the RTCRtpReceiverMediaStreamTrack, the user agent MUST queue a task to
      update the relevant information for the
      RTCRtpContributingSourceRTCRtpSynchronizationSourceRTCRtpSynchronizationSourceRTCRtpContributingSourceRTCRtpReceiverMediaStreamTrack in the previous 10 seconds.
MediaStreamTrack is not attached to
      any sink for playout, getSynchronizationSourcesgetContributingSourcesRTCRtpSynchronizationSourceRTCRtpContributingSourceRTCRtpReceiverWebIDLdictionaryRTCRtpContributingSource{ required DOMHighResTimeStamptimestamp; required unsigned longsource; doubleaudioLevel; required unsigned longrtpTimestamp; };
timestamp of type DOMHighResTimeStamp, requiredThe timestampRTCRtpReceiverMediaStreamTrack. The timestampPerformance.timeOrigin +
              Performance.now() at that time.
source of type unsigned long, requiredThe CSRC or SSRC identifier of the contributing or synchronization source.
audioLevel of type doubleOnly present for audio receivers. This is a value between 0..1 (linear), where 1.0 represents 0 dBov, 0 represents silence, and 0.5 represents approximately 6 dBSPL change in the sound pressure level from 0 dBov.
For CSRCs, this MUST be converted from the level value defined in [RFC6465] if the RFC 6465 header extension is present, otherwise this member MUST be absent.
For SSRCs, this MUST be converted from the level value defined in [RFC6464]. If the RFC 6464 header extension is not present in the received packets (such as if the other endpoint is not a user agent or is a legacy endpoint), this value SHOULD be absent.
Both RFCs define the level as an integral value from 0 to 127 representing the audio level in negative decibels relative to the loudest signal that the system could possibly encode. Thus, 0 represents the loudest signal the system could possibly encode, and 127 represents silence.
To convert these values to the linear 0..1 range, a value of
              127 is converted to 0, and all other values are converted using
              the equation: 10^(-rfc_level/20).
rtpTimestamp of type
                unsigned long, requiredThe last RTP timestamp, as defined in [RFC3550] Section 5.1, of the media played out at timestamp.
WebIDLdictionaryRTCRtpSynchronizationSource:RTCRtpContributingSource{ booleanvoiceActivityFlag; };
voiceActivityFlag of type booleanOnly present for audio receivers. Whether the last RTP packet,
              delivered from this source, contains voice activity (true) or not
              (false). If the RFC 6464 extension header was not present, or if
              the peer has signaled that it is not using the V bit by setting the
              "vad" extension attribute to "off", as described in [RFC6464],
              Section 4, voiceActivityFlag
voiceActivityFlag
RTCRtpTransceiver InterfaceThe RTCRtpTransceiverRTCRtpSenderRTCRtpReceiverRTCRtpTransceiver
A RTCRtpTransceiver
The transceiver kind of an
      RTCRtpTransceiverRTCRtpReceiverMediaStreamTrack object.
To create an RTCRtpTransceiver with an
      RTCRtpReceiverRTCRtpSenderRTCRtpTransceiverDirection
Let transceiver be a new
          RTCRtpTransceiver
Let transceiver have a [[Sender]] internal slot, initialized to sender.
Let transceiver have a [[Receiver]] internal slot, initialized to receiver.
Let transceiver have a [[Stopping]] internal
          slot, initialized to false.
Let transceiver have a [[Stopped]] internal
          slot, initialized to false.
Let transceiver have a [[Direction]] internal slot, initialized to direction.
Let transceiver have a [[Receptive]] internal slot,
          initialized to false.
Let transceiver have a [[CurrentDirection]] internal slot,
          initialized to null.
Let transceiver have a [[FiredDirection]] internal slot,
          initialized to null.
Let transceiver have a [[PreferredCodecs]] internal slot, initialized to an empty list.
Let transceiver have a [[JsepMid]] internal slot,
          initialized to null. This is the "RtpTransceiver mid property" defined in
          [JSEP] (section 5.2.1. and section 5.3.1.), and is only modified
          there.
Let transceiver have a [[Mid]] internal slot,
          initialized to null.
Return transceiver.
RTCDtlsTransportRTCIceTransportWebIDL[Exposed=Window] interfaceRTCRtpTransceiver{ readonly attribute DOMString?mid; [SameObject] readonly attributeRTCRtpSendersender; [SameObject] readonly attributeRTCRtpReceiverreceiver; attributeRTCRtpTransceiverDirectiondirection; readonly attributeRTCRtpTransceiverDirection?currentDirection; undefinedstop(); undefinedsetCodecPreferences(sequence<RTCRtpCodecCapability> codecs); };
mid of type DOMString, readonly, nullableThe mid
sender of type RTCRtpSenderThe senderRTCRtpSender
receiver of type RTCRtpReceiverThe receiverRTCRtpReceiver
direction of type RTCRtpTransceiverDirectionAs defined in [JSEP] (section 4.2.4.), the
              direction attribute indicates the preferred direction
              of this transceiver, which will be used in calls to createOffercreateAnswercreateOffercreateAnswersendrecv, sendonly,
               recvonly or inactive as defined in
              [JSEP] (section 5.2.2. and section 5.3.2.)
On getting, the user agent MUST run the following steps:
Let transceiver be the
                  RTCRtpTransceiver
If transceiver.[[Stopping]] is
                  true, return "stopped
Otherwise, return the value of the [[Direction]] slot.
On setting, the user agent MUST run the following steps:
Let transceiver be the
                  RTCRtpTransceiver
Let connection be the
                  RTCPeerConnection
If transceiver.[[Stopping]] is
                  true, throw an
                  InvalidStateError.
Let newDirection be the argument to the setter.
If newDirection is equal to transceiver.[[Direction]], abort these steps.
Set transceiver.[[Direction]] to newDirection.
Update the negotiation-needed flag for connection.
currentDirection of type RTCRtpTransceiverDirectionAs defined in [JSEP] (section 4.2.5.), the
              currentDirection attribute indicates the current
              direction negotiated for this transceiver. The value of
              currentDirection is independent of the value of
              RTCRtpEncodingParametersactivenull. If the transceiver is
              stopped, the value is "stopped
On getting, the user agent MUST run the following steps:
Let transceiver be the
                  RTCRtpTransceiver
If transceiver.[[Stopped]] is
                  true, return "stopped
Otherwise, return the value of the [[CurrentDirection]] slot.
stopIrreversibly marks the transceiver as stopping, unless
              it is already stopped. This will immediately cause the
              transceiver's sender to no longer send, and its receiver to no
              longer receive. Calling stop() also updates the
              negotiation-needed flag for the
              RTCRtpTransceiverRTCPeerConnection
A stopping transceiver will cause future calls to
              createOfferstopping transceiver as stopped for the
              purposes of JSEP only in this case). However, to avoid problems
              with [BUNDLE], a transceiver that is stopping, but not
              stopped, will not affect createAnswer
A stopped transceiver will cause future calls to
              createOffercreateAnswer
The transceiver will remain in the stopping state,
              unless it becomes stopped by setRemoteDescription
A transceiver that is stopping but not
              stopped will always need negotiation. In practice, this
              means that calling stop() on a transceiver will cause
              the transceiver to become stopped eventually, provided
              negotiation is allowed to complete on both ends.
When the stop
Let transceiver be the
                  RTCRtpTransceiver
Let connection be the
                  RTCPeerConnection
If connection.[[IsClosed]] is
                  true, throw an
                  InvalidStateError.
If transceiver.[[Stopping]] is
                  true, abort these steps.
Stop sending and receiving with transceiver.
Update the negotiation-needed flag for connection.
The stop sending and receiving algorithm given a
              transceiver and, optionally, a disappear
              boolean defaulting to false, is as follows:
Let sender be transceiver.[[Sender]].
Let receiver be transceiver.[[Receiver]].
Stop sending media with sender.
Send an RTCP BYE for each RTP stream that was being sent by sender, as specified in [RFC3550].
Stop receiving media with receiver.
If disappear is false, execute the
                  steps for receiver.[[ReceiverTrack]]
                  to be ended.
                  This fires an event.
Set transceiver.[[Direction]]
                  to "inactive
Set transceiver.[[Stopping]]
                  to true.
The stop the RTCRtpTransceiver algorithm given a
              transceiver and, optionally, a disappear
              boolean defaulting to false, is as follows:
If transceiver.[[Stopping]] is
                  false, stop sending and receiving with
                  transceiver and disappear.
Set transceiver.[[Stopped]] to
                  true.
Set transceiver.[[Receptive]]
                  to false.
Set transceiver.[[CurrentDirection]]
                  to null.
setCodecPreferencesThe setCodecPreferencescreateOffercreateAnswerRTCRtpTransceiver
This method allows applications to disable the negotiation of specific codecs (including RTX/RED/FEC). It also allows an application to cause a remote peer to prefer the codec that appears first in the list for sending.
Codec preferences remain in effect for all calls to
              createOffercreateAnswerRTCRtpTransceiver
Codecs have their payload types listed under each m= section in the SDP, defining the mapping between payload types and codecs. These payload types are referenced by the m=video or m=audio lines in the order of preference, and codecs that are not negotiated do not apear in this list as defined in section 5.2.1 of [JSEP]. A previously negotiated codec that is subsequently removed disappears from the m=video or m=audio line, and while its codec payload type is not to be reused in future offers or answers, its payload type may also be removed from the mapping of payload types in the SDP.
The codecs sequence passed into
              setCodecPreferencesRTCRtpSendergetCapabilitiesRTCRtpReceivergetCapabilitiesRTCRtpTransceiverRTCRtpCodecCapabilityInvalidModificationError.
              Due to a recommendation in [SDP], calls to
              createAnswer
When setCodecPreferences() in invoked, the user agent
              MUST run the following steps:
Let transceiver be the RTCRtpTransceiver
Let codecs be the first argument.
If codecs is an empty list, set transceiver.[[PreferredCodecs]] to codecs and abort these steps.
Remove any duplicate values in codecs. Start at the back of the list such that the priority of the codecs is maintained; the index of the first occurrence of a codec within the list is the same before and after this step.
Let kind be the transceiver's transceiver kind.
If the intersection between codecs and
                  RTCRtpSendergetCapabilitiescodecsRTCRtpReceivergetCapabilitiescodecsInvalidModificationError. This ensures that we always have
                  something to offer, regardless of transceiver.direction
Let codecCapabilities be the union of
                  RTCRtpSendergetCapabilitiescodecsRTCRtpReceivergetCapabilitiescodecs
For each codec in codecs,
InvalidModificationError.Set transceiver.[[PreferredCodecs]] to codecs.
If set, the offerer's codec preferences will decide the order of the codecs in the offer. If the answerer does not have any codec preferences then the same order will be used in the answer. However, if the answerer also has codec preferences, these preferences override the order in the answer. In this case, the offerer's preferences would affect which codecs were on offer but not the final order.
Simulcast functionality is provided via the addTransceiverRTCPeerConnectionsetParametersRTCRtpSender
The addTransceiverencodingssetParametersaddTrack() method cannot provide simulcast
        functionality since it does not take sendEncodingsRTCRtpTransceiver
Another implication is that the answerer cannot set the simulcast envelope directly.
        Upon calling the setRemoteDescriptionRTCPeerConnectionRTCRtpTransceiverRTCSessionDescriptionactivefalse effectively disabling the layer.
While setParameterssetParametersactivefalse, or can be reactivated by setting the activetrue.  Using setParametersmaxBitrate
          Simulcast is frequently used to send multiple encodings to
          an SFU, which will then forward one of the simulcast streams to the
          end user. The user agent is therefore expected to allocate bandwidth
          between encodings in such a way that all simulcast streams are
          usable on their own; for instance, if two simulcast streams
          have the same maxBitrate
As defined in [JSEP] (section 3.7.), an offer from a user-agent
        will only contain a "send" description and no "recv" description on the
        a=simulcast line. Alternatives and restrictions (described
        in [MMUSIC-SIMULCAST]) are not supported.
This specification does not define how to configure reception of multiple
        RTP encodings using createOffercreateAnsweraddTransceiversetRemoteDescriptionRTCRtpReceiverreceivergetParameters()
        will reflect the encodings negotiated.
An RTCRtpReceiverRTCRtpReceiverRTCRtpReceiver
This section is non-normative.
Examples of simulcast scenarios implemented with encoding parameters:
// Example of 3-layer spatial simulcast with all but the lowest resolution layer disabled
var encodings = [
  {rid: 'q', active: true, scaleResolutionDownBy: 4.0}
  {rid: 'h', active: false, scaleResolutionDownBy: 2.0},
  {rid: 'f', active: false},
];This section is non-normative.
Together, the directionreplaceTrack
To send music to a peer and cease rendering received audio (music-on-hold):
async function playMusicOnHold() {
  try {
    // Assume we have an audio transceiver and a music track named musicTrack
    await audio.sender.replaceTrack(musicTrack);
    // Mute received audio
    audio.receiver.track.enabled = false;
    // Set the direction to send-only (requires negotiation)
    audio.direction = 'sendonly';
  } catch (err) {
    console.error(err);
  }
}To respond to a remote peer's "sendonly" offer:
async function handleSendonlyOffer() {
  try {
    // Apply the sendonly offer first,
    // to ensure the receiver is ready for ICE candidates.
    await pc.setRemoteDescription(sendonlyOffer);
    // Stop sending audio
    await audio.sender.replaceTrack(null);
    // Align our direction to avoid further negotiation
    audio.direction = 'recvonly';
    // Call createAnswer and send a recvonly answer
    await doAnswer();
  } catch (err) {
    // handle signaling error
  }
}To stop sending music and send audio captured from a microphone, as well to render received audio:
async function stopOnHoldMusic() {
  // Assume we have an audio transceiver and a microphone track named micTrack
  await audio.sender.replaceTrack(micTrack);
  // Unmute received audio
  audio.receiver.track.enabled = true;
  // Set the direction to sendrecv (requires negotiation)
  audio.direction = 'sendrecv';
}To respond to being taken off hold by a remote peer:
async function onOffHold() {
  try {
    // Apply the sendrecv offer first, to ensure receiver is ready for ICE candidates.
    await pc.setRemoteDescription(sendrecvOffer);
    // Start sending audio
    await audio.sender.replaceTrack(micTrack);
    // Set the direction sendrecv (just in time for the answer)
    audio.direction = 'sendrecv';
    // Call createAnswer and send a sendrecv answer
    await doAnswer();
  } catch (err) {
    // handle signaling error
  }
}RTCDtlsTransport InterfaceThe RTCDtlsTransportRTCRtpSenderRTCRtpReceiverRTCDtlsTransportRTCDtlsTransportsetLocalDescription() and
      setRemoteDescription(). Each
      RTCDtlsTransportcomponentRTCRtpTransceiverRTCRtpTransceiver
RTCRtpTransceiverRTCDtlsTransportstateAn RTCDtlsTransportnew
When the underlying DTLS transport experiences an error, such as a certificate validation failure, or a fatal alert (see [RFC5246] section 7.2), the user agent MUST queue a task that runs the following steps:
Let transport be the
              RTCDtlsTransport
If the state of transport is
          already "failed
Set transport.[[DtlsTransportState]]
            to "failed
            Fire an event named
            errorRTCErrorEventdtls-failurefingerprint-failureRTCErrorDetailType
Fire an event
          named statechange
When the underlying DTLS transport needs to update the state of the
        corresponding RTCDtlsTransport
Let transport be the
          RTCDtlsTransport
Let newState be the new state.
Set transport.[[DtlsTransportState]] to newState.
If newState is
          connected
Fire an event named statechange
WebIDL[Exposed=Window] interfaceRTCDtlsTransport: EventTarget { [SameObject] readonly attributeRTCIceTransporticeTransport; readonly attributeRTCDtlsTransportStatestate; sequence<ArrayBuffer>getRemoteCertificates(); attribute EventHandleronstatechange; attribute EventHandleronerror; };
iceTransport of type RTCIceTransportThe iceTransportRTCDtlsTransport
state of type RTCDtlsTransportStateThe state
onstatechange of type EventHandler
              statechange.
            onerror of type
              EventHandlererrorgetRemoteCertificatesReturns the value of [[RemoteCertificates]].
RTCDtlsTransportState EnumWebIDLenumRTCDtlsTransportState{ "new", "connecting", "connected", "closed", "failed" };
| Enumeration description | |
|---|---|
| new | DTLS has not started negotiating yet. | 
| connecting | DTLS is in the process of negotiating a secure connection and verifying the remote fingerprint. | 
| connected | DTLS has completed negotiation of a secure connection and verified the remote fingerprint. | 
| closed | The transport has been closed intentionally as the result of
              receipt of a close_notify alert, or calling (). | 
| failed | The transport has failed as the result of an error (such as receipt of an error alert or failure to validate the remote fingerprint). | 
RTCDtlsFingerprint DictionaryThe RTCDtlsFingerprint
WebIDLdictionaryRTCDtlsFingerprint{ DOMStringalgorithm; DOMStringvalue; };
algorithm of type DOMStringOne of the the hash function algorithms defined in the 'Hash function Textual Names' registry [IANA-HASH-FUNCTION].
value of type DOMStringThe value of the certificate fingerprint in lowercase hex string as expressed utilizing the syntax of 'fingerprint' in [RFC4572] Section 5.
RTCIceTransport InterfaceThe RTCIceTransportRTCIceTransportsetLocalDescription() and
      setRemoteDescription(). The underlying ICE state is managed
      by the ICE agent; as such, the state of an
      RTCIceTransportRTCIceTransportcomponentRTCRtpTransceiverRTCRtpTransceiver
RTCRtpTransceiverRTCIceTransportstateWhen the ICE Agent indicates that it began gathering a
      generation of candidates for an RTCIceTransport
Let connection be the
          RTCPeerConnection
If connection.[[IsClosed]] is
          true, abort these steps.
Let transport be the RTCIceTransport
Set transport.[[IceGathererState]]
          to gathering
Fire an event named gatheringstatechange
Update the ICE gathering state of connection.
When the ICE Agent is finished gathering a generation of
      candidates for an RTCIceTransport
Let connection be the
          RTCPeerConnection
If connection.[[IsClosed]] is
          true, abort these steps.
Let transport be the RTCIceTransport
Let newCandidate be the result of
          creating an RTCIceCandidate
          with a new dictionary whose
          sdpMidsdpMLineIndexRTCIceTransportusernameFragmentcandidate
Fire an event named icecandidateRTCPeerConnectionIceEvent
If another generation of candidates is still being gathered, abort these steps.
Set transport.[[IceGathererState]]
          to complete
Fire an event named gatheringstatechange
Update the ICE gathering state of connection.
When the ICE Agent indicates that a new ICE candidate is
      available for an RTCIceTransport
Let candidate be the available ICE candidate.
Let connection be the
          RTCPeerConnection
If connection.[[IsClosed]] is
          true, abort these steps.
If either connection.[[PendingLocalDescription]]
          or connection.[[CurrentLocalDescription]] are not
          null, and represent the ICE generation for which
          candidate was gathered,
          surface the candidate with
          candidate and connection, and abort these steps.
          
Otherwise, append candidate to connection.[[EarlyCandidates]].
When the ICE Agent signals that the ICE role has changed due to an ICE binding request with a role collision per [RFC8445] section 7.3.1.1, the UA will queue a task to set the value of [[IceRole]] to the new value.
To release early candidates of a connection, run the following steps:
For each candidate, candidate, in connection.[[EarlyCandidates]], queue a task to surface the candidate with candidate and connection.
Set connection.[[EarlyCandidates]] to an empty list.
To surface a candidate with candidate and connection, run the following steps:
If connection.[[IsClosed]] is
          true, abort these steps.
Let transport be the RTCIceTransport
If connection.[[PendingLocalDescription]] is
          not null, and represents the ICE generation for
          which candidate was gathered, add candidate to
          connection.[[PendingLocalDescription]].sdp.
If connection.[[CurrentLocalDescription]]
          is not null, and represents the ICE generation for
          which candidate was gathered, add candidate to
          connection.[[CurrentLocalDescription]].sdp.
Let newCandidate be the result of
          creating an RTCIceCandidate
          with a new dictionary whose
          sdpMidsdpMLineIndexRTCIceTransportusernameFragmentcandidatecandidate-attribute
          grammar to represent candidate.
Add newCandidate to transport's set of local candidates.
Fire an event named icecandidateRTCPeerConnectionIceEvent
The RTCIceTransportStateRTCIceTransportRTCIceTransportState
When the ICE Agent indicates that an RTCIceTransportRTCIceTransportState
Let connection be the
          RTCPeerConnection
If connection.[[IsClosed]] is
          true, abort these steps.
Let transport be the RTCIceTransport
Let selectedCandidatePairChanged be
          false.
Let transportIceConnectionStateChanged be
          false.
Let connectionIceConnectionStateChanged be
          false.
Let connectionStateChanged be false.
If transport's selected candidate pair was changed, run the following steps:
Let newCandidatePair be a newly created
              RTCIceCandidatePairnull otherwise.
Set transport.[[SelectedCandidatePair]] to newCandidatePair.
Set selectedCandidatePairChanged to
              true.
If transport's RTCIceTransportState
Set transport.[[IceTransportState]] to the
              new indicated RTCIceTransportState
Set transportIceConnectionStateChanged to
              true.
Set connection's ICE connection state to the
              value of deriving a new state value as described by the
              RTCIceConnectionState
If the ice connection state changed in the previous
              step, set connectionIceConnectionStateChanged to
              true.
Set connection's connection state to the value
              of deriving a new state value as described by the
              RTCPeerConnectionState
If the connection state changed in the previous step, set
              connectionStateChanged to true.
If selectedCandidatePairChanged is true,
          fire an event named selectedcandidatepairchange
If transportIceConnectionStateChanged is
          true, fire an event named statechange
If connectionIceConnectionStateChanged is
          true, fire an event named
          iceconnectionstatechange
If connectionStateChanged is true,
          fire an event named connectionstatechange
An RTCIceTransport
newnewnullunknownWebIDL[Exposed=Window] interfaceRTCIceTransport: EventTarget { readonly attributeRTCIceRolerole; readonly attributeRTCIceComponentcomponent; readonly attributeRTCIceTransportStatestate; readonly attributeRTCIceGathererStategatheringState; sequence<RTCIceCandidate>getLocalCandidates(); sequence<RTCIceCandidate>getRemoteCandidates();RTCIceCandidatePair?getSelectedCandidatePair();RTCIceParameters?getLocalParameters();RTCIceParameters?getRemoteParameters(); attribute EventHandleronstatechange; attribute EventHandlerongatheringstatechange; attribute EventHandleronselectedcandidatepairchange; };
role of type RTCIceRoleThe role
component of type RTCIceComponentThe componentRTCIceTransportcomponentrtp
state of type RTCIceTransportStateThe state
gatheringState of type RTCIceGathererStateThe gatheringState
onstatechange of type EventHandlerstatechangeRTCIceTransportstateongatheringstatechange of type
            EventHandlergatheringstatechangeRTCIceTransportonselectedcandidatepairchange of type
            EventHandlerselectedcandidatepairchangeRTCIceTransportgetLocalCandidatesReturns a sequence describing the local ICE candidates
              gathered for this RTCIceTransportonicecandidate
getRemoteCandidatesReturns a sequence describing the remote ICE candidates
              received by this RTCIceTransportaddIceCandidate().
getRemoteCandidatesaddIceCandidate().
              getSelectedCandidatePairReturns the selected candidate pair on which packets are sent. This
              method MUST return the value of the [[SelectedCandidatePair]]
              slot. When RTCIceTransportstatenewclosedgetSelectedCandidatePairnull.
getLocalParametersReturns the local ICE parameters received by this
              RTCIceTransportsetLocalDescriptionnull if the parameters have not yet been
              received.
getRemoteParametersReturns the remote ICE parameters received by this
              RTCIceTransportsetRemoteDescriptionnull if the parameters have not yet been
              received.
RTCIceParameters DictionaryWebIDLdictionaryRTCIceParameters{ DOMStringusernameFragment; DOMStringpassword; };
RTCIceParametersRTCIceCandidatePair DictionaryWebIDLdictionaryRTCIceCandidatePair{RTCIceCandidatelocal;RTCIceCandidateremote; };
RTCIceCandidatePairlocal of type RTCIceCandidateThe local ICE candidate.
remote of type RTCIceCandidateThe remote ICE candidate.
RTCIceGathererState EnumWebIDLenumRTCIceGathererState{ "new", "gathering", "complete" };
| Enumeration description | |
|---|---|
| new | The was just created, and
              has not started gathering candidates yet. | 
| gathering | The is in the process of
              gathering candidates. | 
| complete | The has completed
              gathering and the end-of-candidates indication for this transport
              has been sent. It will not gather candidates again until an ICE
              restart causes it to restart. | 
RTCIceTransportState EnumWebIDLenumRTCIceTransportState{ "new", "checking", "connected", "completed", "disconnected", "failed", "closed" };
| Enumeration description | |
|---|---|
| new | The is gathering
              candidates and/or waiting for remote candidates to be supplied,
              and has not yet started checking. | 
| checking | The has received at least
              one remote candidate and is checking candidate pairs and has
              either not yet found a connection or consent checks [RFC7675]
              have failed on all previously successful candidate pairs. In
              addition to checking, it may also still be gathering. | 
| connected | The has found a usable
              connection, but is still checking other candidate pairs to see if
              there is a better connection. It may also still be gathering
              and/or waiting for additional remote candidates. If consent
              checks [RFC7675] fail on the connection in use, and there are
              no other successful candidate pairs available, then the state
              transitions to "" (if there are candidate pairs remaining
              to be checked) or "" (if there are no candidate pairs
              to check, but the peer is still gathering and/or waiting for
              additional remote candidates). | 
| completed | The has finished
              gathering, received an indication that there are no more remote
              candidates, finished checking all candidate pairs and found a
              connection. If consent checks [RFC7675] subsequently fail on
              all successful candidate pairs, the state transitions to
              "". | 
| disconnected | The ICE Agent has determined that connectivity is
                currently lost for this .
                This is a transient state that may
                trigger intermittently (and resolve itself without action) on a
                flaky network. The way this state is determined is
                implementation dependent. Examples include:
 has
                finished checking all existing candidates pairs and not found a
                connection (or consent checks [RFC7675] once
                successful, have now failed), but it is still gathering and/or
                waiting for additional remote candidates. | 
| failed | The has finished
              gathering, received an indication that there are no more remote
              candidates, finished checking all candidate pairs, and all pairs
              have either failed connectivity checks or have lost consent.
              This is a terminal state until ICE is restarted. Since an ICE
              restart may cause connectivity to resume, entering the
              "" state does not cause DTLS transports, SCTP
              associations or the data channels that run over them to close, or
              tracks to mute. | 
| closed | The has shut down and is
              no longer responding to STUN requests. | 
        The most common transitions for a successful call will be new ->
        checking -> connected -> completed, but under specific circumstances
        (only the last checked candidate succeeds, and gathering and the
        no-more candidates indication both occur prior to success), the
        state can transition directly from "checkingcompleted
An ICE restart causes candidate gathering and connectity checks to
      begin anew, causing a transition to "connectedcompleteddisconnectedchecking
The "failedcompletedaddIceCandidatecandidatecanTrickleIceCandidatesfalse.
Some example state transitions are:
RTCIceTransportsetLocalDescriptionsetRemoteDescriptionnewnewcheckingcheckingconnectedcheckingdisconnectedcheckingfaileddisconnectedcheckingconnectedcompletedcompleteddisconnecteddisconnectedfailedcheckingcompletedconnectedRTCPeerConnectionclose(): "closedRTCIceRole EnumWebIDLenumRTCIceRole{ "unknown", "controlling", "controlled" };
| Enumeration description | |
|---|---|
| unknown | An agent whose role as defined by [ICE], Section 3, has not yet been determined. | 
| controlling | A controlling agent as defined by [ICE], Section 3. | 
| controlled | A controlled agent as defined by [ICE], Section 3. | 
RTCIceComponent EnumWebIDLenumRTCIceComponent{ "rtp", "rtcp" };
| Enumeration description | |
|---|---|
| rtp | The ICE Transport is used for RTP (or RTCP multiplexing),
              as defined in [ICE], Section 4.1.1.1. Protocols multiplexed
              with RTP (e.g. data channel) share its component ID. This represents
              the component-idvalue1when encoded
              incandidate-attribute. | 
| rtcp | The ICE Transport is used for RTCP as defined by [ICE],
              Section 4.1.1.1. This represents the component-idvalue2when encoded incandidate-attribute. | 
RTCTrackEventThe trackRTCTrackEvent
WebIDL[Exposed=Window] interfaceRTCTrackEvent: Event {constructor(DOMString type,RTCTrackEventIniteventInitDict); readonly attributeRTCRtpReceiverreceiver; readonly attribute MediaStreamTracktrack; [SameObject] readonly attribute FrozenArray<MediaStream>streams; readonly attributeRTCRtpTransceivertransceiver; };
RTCTrackEvent.constructor()receiver of type RTCRtpReceiverThe receiverRTCRtpReceiver
track of type MediaStreamTrack, readonlyThe trackMediaStreamTrack object that is associated
              with the RTCRtpReceiverreceiver
streams of type FrozenArray<MediaStream>,
            readonlyThe streamsMediaStream objects representing the
              MediaStreams that this event's
              track
transceiver of type RTCRtpTransceiverThe transceiverRTCRtpTransceiver
WebIDLdictionaryRTCTrackEventInit: EventInit { requiredRTCRtpReceiverreceiver; required MediaStreamTracktrack; sequence<MediaStream>streams= []; requiredRTCRtpTransceivertransceiver; };
RTCTrackEventInit Membersreceiver of type RTCRtpReceiverThe receiverRTCRtpReceiver
track of type MediaStreamTrack, requiredThe trackMediaStreamTrack object that is associated
              with the RTCRtpReceiverreceiver
streams of type sequence<MediaStream>,
            defaulting to []The streamsMediaStream objects representing the
              MediaStreams that this event's
              track
transceiver of type RTCRtpTransceiverThe transceiverRTCRtpTransceiver
The Peer-to-peer Data API lets a web application send and receive generic application data peer-to-peer. The API for sending and receiving data models the behavior of Web Sockets.
The Peer-to-peer data API extends the
      RTCPeerConnection
WebIDLpartial interfaceRTCPeerConnection{ readonly attributeRTCSctpTransport?sctp;RTCDataChannelcreateDataChannel(USVString label, optionalRTCDataChannelInitdataChannelDict = {}); attribute EventHandlerondatachannel; };
sctp of type RTCSctpTransportThe SCTP transport over which SCTP data is sent and received.
              If SCTP has not been negotiated, the value is null. This
              attribute MUST return the RTCSctpTransport
ondatachannel of type EventHandlerdatachannel.createDataChannelCreates a new RTCDataChannelRTCDataChannelInit
When the createDataChannel
Let connection be the
                  RTCPeerConnection
If connection.[[IsClosed]] is
                  true, throw an
                  InvalidStateError.
Create an RTCDataChannel, channel.
Initialize channel.[[DataChannelLabel]] to the value of the first argument.
If the UTF-8 representation of [[DataChannelLabel]]
                  is longer than 65535 bytes, throw a
                  TypeError.
Let options be the second argument.
Initialize channel.[[MaxPacketLifeTime]]
                  to option.maxPacketLifeTimenull.
Initialize channel.[[MaxRetransmits]]
                  to option.maxRetransmitsnull.
Initialize channel.[[Ordered]]
                  to option.ordered
Initialize channel.[[DataChannelProtocol]] to option.protocol
If the UTF-8 representation of
                  [[DataChannelProtocol]] is longer than 65535 bytes,
                  throw a TypeError.
Initialize channel.[[Negotiated]]
                  to option.negotiated
Initialize channel.[[DataChannelId]]
                  to the value of option.idnull.
idIf [[Negotiated]] is true and
                  [[DataChannelId]] is null, throw
                  a TypeError.
If both [[MaxPacketLifeTime]] and
                  [[MaxRetransmits]]
                  attributes are set (not null), throw a
                  TypeError.
If a setting, either [[MaxPacketLifeTime]] or [[MaxRetransmits]], has been set to indicate unreliable mode, and that value exceeds the maximum value supported by the user agent, the value MUST be set to the user agents maximum value.
If [[DataChannelId]] is
                  equal to 65535, which is greater than the maximum allowed ID
                  of 65534 but still qualifies as an unsigned short, throw a
                  TypeError.
If the [[DataChannelId]]
                  slot is null (due to no ID being passed into
                  createDataChannelRTCDataChannelOperationError exception.
null after this step, it will be
                    populated during the
                    RTCSctpTransport connected procedure.
                  Let transport be connection.[[SctpTransport]].
If the [[DataChannelId]] slot is not
                  null, transport is in the
                  "connectedOperationError.
If channel is the first
                  RTCDataChannel
Return channel and continue the following steps in parallel.
Create channel's associated underlying data transport and configure it according to the relevant properties of channel.
RTCSctpTransport InterfaceThe RTCSctpTransport
To create an RTCSctpTransport
Let transport be a new
              RTCSctpTransport
Let transport have a [[SctpTransportState]] internal slot initialized to initialState.
Let transport have a [[MaxMessageSize]] internal slot and run the steps labeled update the data max message size to initialize it.
Let transport have a [[MaxChannels]]
              internal slot initialized to null.
Return transport.
To update the data max message size of an
          RTCSctpTransport
Let transport be the RTCSctpTransport
Let remoteMaxMessageSize be the value of the
              max-message-size SDP attribute read from the remote description,
              as described in [SCTP-SDP] (section 6), or 65536 if the
              attribute is missing.
Let canSendSize be the number of bytes that this client can send (i.e. the size of the local send buffer) or 0 if the implementation can handle messages of any size.
If both remoteMaxMessageSize and canSendSize are 0, set [[MaxMessageSize]] to the positive Infinity value.
Else, if either remoteMaxMessageSize or canSendSize is 0, set [[MaxMessageSize]] to the larger of the two.
Else, set [[MaxMessageSize]] to the smaller of remoteMaxMessageSize or canSendSize.
Once an SCTP transport
          is connected, meaning the SCTP association of an RTCSctpTransport
Let transport be the RTCSctpTransport
Let connection be the
              RTCPeerConnection
Set [[MaxChannels]] to the minimum of the negotiated amount of incoming and outgoing SCTP streams.
For each of connection's RTCDataChannel
Let channel be the RTCDataChannel
If channel.[[DataChannelId]] is
                    null, initialize [[DataChannelId]]
                    to the value generated by the
                    underlying sctp data channel, according to
                    [RTCWEB-DATA-PROTOCOL].
                  
If channel.[[DataChannelId]] is greater or equal to transport.[[MaxChannels]], or the previous step failed to assign an id, close the channel due to a failure. Otherwise, announce the channel as open.
Fire an event named statechange
This event is fired before the open events
                fired by announcing the channel as open; the open
                events are fired from a queued task.
WebIDL[Exposed=Window] interfaceRTCSctpTransport: EventTarget { readonly attributeRTCDtlsTransporttransport; readonly attributeRTCSctpTransportStatestate; readonly attribute unrestricted doublemaxMessageSize; readonly attribute unsigned short?maxChannels; attribute EventHandleronstatechange; };
transport of type RTCDtlsTransportThe transport over which all SCTP packets for data channels will be sent and received.
state of type RTCSctpTransportStateThe current state of the SCTP transport. On getting, this attribute MUST return the value of the [[SctpTransportState]] slot.
maxMessageSize of type unrestricted double, readonlyThe maximum size of data that can be passed to
                RTCDataChannelsend() method. The attribute MUST,
                on getting, return the value of the [[MaxMessageSize]]
                slot.
maxChannels of type
              unsigned short
              , readonly, nullableThe maximum amount of RTCDataChannel
null until the SCTP transport goes into the
                "connectedonstatechange of type EventHandlerThe event type of this event handler is
                statechange
RTCSctpTransportState EnumRTCSctpTransportState
WebIDLenumRTCSctpTransportState{ "connecting", "connected", "closed" };
| Enumeration description | |
|---|---|
| connecting | The  | 
| connected | When the negotiation of an association is completed, a task is
                  queued to update the [[SctpTransportState]] slot to
                  " | 
| closed | A task is queued to update the [[SctpTransportState]]
                    slot to " 
 Note that the last transition is logical due to the fact that an SCTP association requires an established DTLS connection - [RFC8261] section 6.1 specifies that SCTP over DTLS is single-homed - and that no way of of switching to an alternate transport is defined in this API. | 
RTCDataChannelThe RTCDataChannelRTCDataChannelRTCPeerConnection
There are two ways to establish a connection with
      RTCDataChannelRTCDataChannelnegotiatedRTCDataChannelInitRTCDataChannelEventRTCDataChannelRTCDataChannelRTCDataChannelnegotiatedRTCDataChannelInitRTCDataChannelnegotiatedRTCDataChannelInitidRTCDataChannelid
Each RTCDataChannelRTCSctpTransport
An RTCDataChannelmaxRetransmitsmaxPacketLifeTime
An RTCDataChannelcreateDataChannelRTCDataChannelEventconnectingRTCDataChannel
To create an RTCDataChannel
Let channel be a newly created
          RTCDataChannel
Let channel have a [[ReadyState]] internal
          slot initialized to "connecting
Let channel have a [[BufferedAmount]]
          internal slot initialized to 0.
Let channel have internal slots named [[DataChannelLabel]], [[Ordered]], [[MaxPacketLifeTime]], [[MaxRetransmits]], [[DataChannelProtocol]], [[Negotiated]], and [[DataChannelId]].
Return channel.
When the user agent is to announce an RTCDataChannel
If the associated RTCPeerConnectiontrue, abort these steps.
Let channel be the RTCDataChannel
If channel.[[ReadyState]] is "closingclosed
Set channel.[[ReadyState]] to
          "open
Fire an event named open
When an underlying data transport is to be announced (the other
      peer created a channel with negotiated
Let connection be the
          RTCPeerConnection
If connection.[[IsClosed]] is
          true, abort these steps.
Create an RTCDataChannel, channel.
Let configuration be an information bundle received from the other peer as a part of the process to establish the underlying data transport described by the WebRTC DataChannel Protocol specification [RTCWEB-DATA-PROTOCOL].
Initialize channel.[[DataChannelLabel]], [[Ordered]], [[MaxPacketLifeTime]], [[MaxRetransmits]], [[DataChannelProtocol]], and [[DataChannelId]] internal slots to the corresponding values in configuration.
Initialize channel.[[Negotiated]] to false.
Set channel.[[ReadyState]] to
          "openopen
datachannel event handler prior to the
          openFire an event named
          datachannel using the
          RTCDataChannelEventchannel
An RTCDataChannel
Let channel be the RTCDataChannel
Unless the procedure was initiated by channel.closeclosingclosing
Run the following steps in parallel:
Finish sending all currently pending messages of the channel.
Follow the closing procedure defined for the channel's underlying data transport :
In the case of an SCTP-based transport, follow [RTCWEB-DATA], section 6.7.
Render the channel's data transport closed by following
              the associated procedure.
            
When an RTCDataChannel
Let channel be the RTCDataChannel
closedSet channel.[[ReadyState]] to
          "closed
If the transport was closed
          with an error, fire
          an event named errorRTCErrorEventerrorDetailsctp-failure
Fire an event named close
In some cases, the user agent may be 
      unable to create an RTCDataChannelidRTCDataChannel
Let channel be the RTCDataChannel
Set channel.[[ReadyState]] to
          "closed
Fire an event named errorRTCErrorEventerrorDetaildata-channel-failure
Fire an event named close
When an 
      RTCDataChannel
Let channel be the RTCDataChannel
Let connection be the
          RTCPeerConnection
If channel.[[ReadyState]] is not
          "open
Execute the sub step by switching on type and
          channel.binaryType
If type indicates that rawData is a
              string:
Let data be a DOMString that represents the result of decoding rawData as UTF-8.
If type indicates that rawData is binary
              and binaryType"blob":
Let data be a new Blob object
              containing rawData as its raw data source.
If type indicates that rawData is binary
              and binaryType"arraybuffer":
Let data be a new ArrayBuffer object
              containing rawData as its raw data source.
Fire an event named messageMessageEvent
          interface with its origin attribute initialized to the
          serialization of an origin
          of connection.[[DocumentOrigin]],
          and the data attribute initialized to data at
          channel.
WebIDL[Exposed=Window] interfaceRTCDataChannel: EventTarget { readonly attribute USVStringlabel; readonly attribute booleanordered; readonly attribute unsigned short?maxPacketLifeTime; readonly attribute unsigned short?maxRetransmits; readonly attribute USVStringprotocol; readonly attribute booleannegotiated; readonly attribute unsigned short?id; readonly attributeRTCDataChannelStatereadyState; readonly attribute unsigned longbufferedAmount; [EnforceRange] attribute unsigned longbufferedAmountLowThreshold; attribute EventHandleronopen; attribute EventHandleronbufferedamountlow; attribute EventHandleronerror; attribute EventHandleronclosing; attribute EventHandleronclose; undefinedclose(); attribute EventHandleronmessage; attribute DOMStringbinaryType; undefinedsend(USVString data); undefinedsend(Blob data); undefinedsend(ArrayBuffer data); undefinedsend(ArrayBufferView data); };
label of type USVString, readonlyThe labelRTCDataChannelRTCDataChannelRTCDataChannel
ordered of type boolean, readonlyThe orderedRTCDataChannel
maxPacketLifeTime of type unsigned short, readonly,
            nullableThe maxPacketLifeTime
maxRetransmits of type unsigned short, readonly,
            nullableThe maxRetransmits
protocol of type USVString, readonlyThe protocolRTCDataChannel
negotiated of type boolean, readonlyThe negotiatedRTCDataChannel
id of type unsigned short, readonly, nullableThe idRTCDataChannel
readyState of type RTCDataChannelStateThe readyStateRTCDataChannel
bufferedAmount of type unsigned long, readonlyThe bufferedAmountsend(). Even
              though the data transmission can occur in parallel, the returned
              value MUST NOT be decreased before the current task yielded back
              to the event loop to prevent race conditions.
              The value does not include framing overhead incurred by the
              protocol, or buffering done by the operating system or network
              hardware. The value of the [[BufferedAmount]] slot will
              only increase with each call to the send() method as long as the 
              [[ReadyState]] slot is "open
bufferedAmountLowThreshold of type unsigned longThe bufferedAmountLowThresholdbufferedAmountbufferedAmountbufferedamountlowbufferedAmountLowThresholdRTCDataChannel
onopen of type EventHandleropenonbufferedamountlow of type
            EventHandlerbufferedamountlowonerror of type EventHandlerThe event type of this event handler is RTCErrorEventerrorDetailsctpCauseCodemessage
onclosing of type EventHandlerThe event type of this event handler is
            closing
onclose of type EventHandlerThe event type of this event handler is
            close
onmessage of type EventHandlerThe event type of this event handler is
            message
binaryType of type DOMStringThe binaryType"blob" or the string "arraybuffer",
              then set the IDL attribute to this new value. Otherwise,
              throw a SyntaxError. When an
              RTCDataChannelbinaryType"blob".
This attribute controls how binary data is exposed to scripts.
              See Web Socket's binaryType.
closeCloses the RTCDataChannelRTCDataChannel
When the close
Let channel be the
                  RTCDataChannel
If channel.[[ReadyState]] is
                  "closingclosed
Set channel.[[ReadyState]] to
                  "closing
If the closing procedure has not started yet, start it.
sendRun the steps described by the send()
              algorithm with argument type
              string object.
sendRun the steps described by the send()
              algorithm with argument type
              Blob object.
sendRun the steps described by the send() algorithm with argument type
              ArrayBuffer object.
sendRun the steps described by the send()
              algorithm with argument type
              ArrayBufferView object.
The send() method is overloaded to handle
      different data argument types. When any version of the method is called,
      the user agent MUST run the following steps:
Let channel be the RTCDataChannel
If channel.[[ReadyState]] is not
          "openInvalidStateError.
Execute the sub step that corresponds to the type of the methods argument:
string object:
Let data be a byte buffer that represents the result of encoding the method's argument as UTF-8.
Blob object:
Let data be the raw data represented by the
              Blob object.
Blob object
              can happen asynchronously, the user agent will make sure to queue the data on
              the channel's underlying data transport in the same order
              as the send method is called. The byte size of data needs to be known
              synchronously.ArrayBuffer object:
Let data be the data stored in the buffer described
              by the ArrayBuffer object.
ArrayBufferView object:
Let data be the data stored in the section of the
              buffer described by the ArrayBuffer object that the
              ArrayBufferView object references.
TypeError. This includes
          null and undefined.If the byte size of data exceeds the value of
          maxMessageSizeRTCSctpTransportTypeError.
Queue data for transmission on channel's
          underlying data transport. If queuing data is not
          possible because not enough buffer space is available, throw
          an OperationError.
onerrorIncrease the value of the [[BufferedAmount]] slot by the byte size of data.
WebIDLdictionaryRTCDataChannelInit{ booleanordered= true; [EnforceRange] unsigned shortmaxPacketLifeTime; [EnforceRange] unsigned shortmaxRetransmits; USVStringprotocol= ""; booleannegotiated= false; [EnforceRange] unsigned shortid; };
RTCDataChannelInit Membersordered of type boolean, defaulting to
            trueIf set to false, data is allowed to be delivered out of order. The default value of true, guarantees that data will be delivered in order.
maxPacketLifeTime of type unsigned shortLimits the time (in milliseconds) during which the channel will transmit or retransmit data if not acknowledged. This value may be clamped if it exceeds the maximum value supported by the user agent.
maxRetransmits of type unsigned shortLimits the number of times a channel will retransmit data if not successfully delivered. This value may be clamped if it exceeds the maximum value supported by the user agent.
protocol of type USVString, defaulting to
            ""Subprotocol name used for this channel.
negotiated of type boolean, defaulting to
            falseThe default value of false tells the user agent to announce
              the channel in-band and instruct the other peer to dispatch a
              corresponding RTCDataChannelRTCDataChannelid
id of type unsigned shortSets the channel ID when negotiatednegotiated
WebIDLenumRTCDataChannelState{ "connecting", "open", "closing", "closed" };
| RTCDataChannelStateEnumeration description | |
|---|---|
| connecting | The user agent is attempting to establish the underlying
                data transport. This is the initial state of an
                 | 
| open | The underlying data transport is established and communication is possible. | 
| closing | The procedure to close down the underlying data transport has started. | 
| closed | The underlying data transport has been
                 | 
RTCDataChannelEventThe datachannel event uses the
      RTCDataChannelEvent
WebIDL[Exposed=Window] interfaceRTCDataChannelEvent: Event {constructor(DOMString type,RTCDataChannelEventIniteventInitDict); readonly attributeRTCDataChannelchannel; };
RTCDataChannelEvent.constructor()channel of type RTCDataChannelThe channelRTCDataChannel
WebIDLdictionaryRTCDataChannelEventInit: EventInit { requiredRTCDataChannelchannel; };
RTCDataChannelEventInit
          Memberschannel of type RTCDataChannelThe RTCDataChannel
An RTCDataChannel
[[ReadyState]] slot is
          "connectingopen events, message events,
          error events, closing events, or close events.
[[ReadyState]] slot is
          "openmessage events, error events, closing events, or
          close events.
[[ReadyState]] slot is
          "closingerror events, or close events.
underlying data transport is established and data is queued to be transmitted.
This section describes an interface on RTCRtpSenderRTCPeerConnection
The Peer-to-peer DTMF API extends the RTCRtpSender
WebIDLpartial interfaceRTCRtpSender{ readonly attributeRTCDTMFSender?dtmf; };
dtmf of type RTCDTMFSenderOn getting, the dtmfRTCDTMFSendernull if unset. The [[Dtmf]] internal slot
              is set when the kind of an RTCRtpSender"audio".
RTCDTMFSenderTo create an RTCDTMFSender, the user agent MUST run the following steps:
Let dtmf be a newly created
            RTCDTMFSender
Let dtmf have a [[Duration]] internal slot.
Let dtmf have a [[InterToneGap]] internal slot.
Let dtmf have a [[ToneBuffer]] internal slot.
WebIDL[Exposed=Window] interfaceRTCDTMFSender: EventTarget { undefinedinsertDTMF(DOMString tones, optional unsigned long duration = 100, optional unsigned long interToneGap = 70); attribute EventHandlerontonechange; readonly attribute booleancanInsertDTMF; readonly attribute DOMStringtoneBuffer; };
ontonechange of type EventHandlerThe event type of this event handler is
              tonechange
canInsertDTMF of type boolean, readonlyWhether the RTCDTMFSender
toneBuffer of type DOMString, readonlyThe toneBufferinsertDTMF
insertDTMFAn RTCDTMFSenderinsertDTMF
The tones parameter is treated as a series of characters. The characters 0 through 9, A through D, #, and * generate the associated DTMF tones. The characters a to d MUST be normalized to uppercase on entry and are equivalent to A to D. As noted in [RTCWEB-AUDIO] Section 3, support for the characters 0 through 9, A through D, #, and * are required. The character ',' MUST be supported, and indicates a delay of 2 seconds before processing the next character in the tones parameter. All other characters (and only those other characters) MUST be considered unrecognized.
The duration parameter indicates the duration in ms to use for each character passed in the tones parameters. The duration cannot be more than 6000 ms or less than 40 ms. The default duration is 100 ms for each tone.
The interToneGap parameter indicates the gap between tones in ms. The user agent clamps it to at least 30 ms and at most 6000 ms. The default value is 70 ms.
The browser MAY increase the duration and interToneGap times to cause the times that DTMF start and stop to align with the boundaries of RTP packets but it MUST not increase either of them by more than the duration of a single RTP audio packet.
When the insertDTMF() method is invoked,
              the user agent MUST run the following steps:
RTCRtpSenderLet transceiver be the
                  RTCRtpTransceiver
RTCDTMFSenderfalse, throw an InvalidStateError.unrecognized
                characters, throw an InvalidCharacterError.
                sendrecvsendonlytonechangeRTCDTMFToneChangeEventtoneRTCDTMFSender"," delay sending tones for
                    2000 ms on
                    the associated RTP media stream, and queue a task to
                    be executed in 2000 ms from now that
                    runs the steps labelled Playout task."," start playout of
                    tone for [[Duration]] ms on the associated
                    RTP media stream, using the appropriate codec, then
                    queue a task to be executed in [[Duration]]
                    + [[InterToneGap]] ms from now that
                    runs the steps labelled Playout task.tonechangeRTCDTMFToneChangeEventtoneRTCDTMFSenderSince insertDTMFinsertDTMFinsertDTMF
To determine if DTMF can be sent for an RTCDTMFSender
RTCRtpSenderRTCRtpTransceiverRTCPeerConnectionRTCPeerConnectionStateconnectedfalse.null
        return false.sendrecvsendonlyfalse.[0].activefalse return false."audio/telephone-event" has been
        negotiated for sending with this sender, return false.true.RTCDTMFToneChangeEventThe tonechangeRTCDTMFToneChangeEvent
WebIDL[Exposed=Window] interfaceRTCDTMFToneChangeEvent: Event {constructor(DOMString type, optionalRTCDTMFToneChangeEventIniteventInitDict = {}); readonly attribute DOMStringtone; };
RTCDTMFToneChangeEvent.constructor()tone of type
              DOMString, readonlyThe tone",") that has just
              begun playout (see insertDTMF
WebIDLdictionaryRTCDTMFToneChangeEventInit: EventInit { DOMStringtone= ""; };
RTCDTMFToneChangeEventInit
          Memberstone of type DOMString, defaulting to
              ""The tone",") that has just
              begun playout (see insertDTMF
The basic statistics model is that the browser maintains a set of statistics for monitored objects, in the form of stats objects.
A group of related objects may be
        referenced by a selector. The
      selector may, for example, be a MediaStreamTrack. For a
      track to be a valid selector, it MUST be a MediaStreamTrack
      that is sent or received by the RTCPeerConnectiongetStats() method and the browser emits
      (in the JavaScript) a set of statistics that are relevant to the selector,
      according to the stats selection algorithm. Note that that
      algorithm takes the sender or receiver of a selector.
The statistics returned in stats objects are designed in such a
      way that repeated queries can be linked by the
      RTCStatsid
        With a few exceptions, monitored objects, once created, exist for
        the duration of their associated RTCPeerConnectiongetStats()
        even past the associated peer connection being close
Only a few monitored objects have shorter lifetimes. Statistics from these objects are no longer available in subsequent getStats() results. The object descriptions in [WEBRTC-STATS] describe when these monitored objects are deleted.
The Statistics API extends the RTCPeerConnection
WebIDLpartial interfaceRTCPeerConnection{ Promise<RTCStatsReport>getStats(optional MediaStreamTrack? selector = null); };
getStatsGathers stats for the given selector and reports the result asynchronously.
When the getStats() method is invoked, the user agent
              MUST run the following steps:
Let selectorArg be the method's first argument.
Let connection be the
                  RTCPeerConnection
If selectorArg is null, let
                  selector be null.
If selectorArg is a MediaStreamTrack
                  let selector be an RTCRtpSenderRTCRtpReceivertrackInvalidAccessError.
Let p be a new promise.
Run the following steps in parallel:
Gather the stats indicated by selector according to the stats selection algorithm.
Resolve p with the resulting
                      RTCStatsReport
Return p.
RTCStatsReport ObjectThe getStats() method
      delivers a successful result in the form of an
      RTCStatsReportRTCStatsReportidRTCStatsRTCStats
An RTCStatsReportRTCStatsRTCRtpSenderRTCStatsReportRTCStatsssrc stats attribute).
WebIDL[Exposed=Window]
interface RTCStatsReport {
  readonly maplike<DOMString, object>;
};
        Use these to retrieve the various dictionaries descended from
        RTCStatsRTCStats
RTCStats DictionaryAn RTCStatsRTCStatstimestamptypeRTCStats
Note that while stats names are standardized, any given implementation may be using experimental values or values not yet known to the Web application. Thus, applications MUST be prepared to deal with unknown stats.
Statistics need to be synchronized with each other in order to yield
      reasonable values in computation; for instance, if bytesSent and
      packetsSent are both reported, they both need to be reported over the
      same interval, so that "average packet size" can be computed as "bytes /
      packets" - if the intervals are different, this will yield errors. Thus
      implementations MUST return synchronized values for all stats in an
      RTCStats
WebIDLdictionaryRTCStats{ required DOMHighResTimeStamptimestamp; required RTCStatsTypetype; required DOMStringid; };
RTCStatstimestamp of type DOMHighResTimeStampThe timestampDOMHighResTimeStamp, associated
              with this object. The time is relative to the UNIX epoch (Jan 1,
              1970, UTC). For statistics that came from a remote source (e.g.,
              from received RTCP packets), timestampRTCStats
type of type RTCStatsTypeThe type of this object.
The typeRTCStats
id of type DOMStringA unique idRTCStatsRTCStatsRTCStatsReport
Stats ids MUST NOT be predictable by an application. This prevents applications from depending on a particular user agent's way of generating ids, since this prevents an application from getting stats objects by their id unless they have already read the id of that specific stats object.
User agents are free to pick any format for the id as long as it meets the requirements above.
A user agent can turn a predictably generated string into an unpredictable string using a hash function, as long as it uses a salt that is unique to the peer connection. This allows an implementation to have predictable ids internally, which may make it easier to guarantee that stats objects have stable ids across getStats() calls.
The set of valid values for RTCStatsType, and the dictionaries derived
      from RTCStats that they indicate, are documented in
      [WEBRTC-STATS].
The stats selection algorithm is as follows:
RTCStatsReportnull, gather stats for the
          whole connection, add them to result, return
          result, and abort these steps.
        RTCRtpSenderRTCOutboundRtpStreamStats objects representing RTP
            streams being sent by selector.
            RTCOutboundRtpStreamStats objects added.
            RTCRtpReceiverRTCInboundRtpStreamStats objects representing RTP
            streams being received by selector.
            RTCInboundRtpStreamStats added.
            The stats listed in [WEBRTC-STATS] are intended to cover a wide range of use cases. Not all of them have to be implemented by every WebRTC implementation.
An implementation MUST support generating statistics of the following
      typeRTCPeerConnectionRTCStats
An implementation MAY support generating any other statistic defined in [WEBRTC-STATS], and MAY generate statistics that are not documented.
Consider the case where the user is experiencing bad sound and the application wants to determine if the cause of it is packet loss. The following example code might be used:
async function gatherStats(pc) {
  try {
    const [sender] = pc.getSenders();
    const baselineReport = await sender.getStats();
    await new Promise(resolve => setTimeout(resolve, aBit)); // wait a bit
    const currentReport = await sender.getStats();
    // compare the elements from the current report with the baseline
    for (const now of currentReport.values()) {
      if (now.type != 'outbound-rtp') continue;
      // get the corresponding stats from the baseline report
      const base = baselineReport.get(now.id);
      if (!base) continue;
      const remoteNow = currentReport.get(now.remoteId);
      const remoteBase = baselineReport.get(base.remoteId);
      const packetsSent = now.packetsSent - base.packetsSent;
      const packetsReceived = remoteNow.packetsReceived -
                              remoteBase.packetsReceived;
      const fractionLost = (packetsSent - packetsReceived) / packetsSent;
      if (fractionLost > 0.3) {
        // if fractionLost is > 0.3, we have probably found the culprit
      }
    }
  } catch (err) {
    console.error(err);
  }
}The MediaStreamTrack interface, as defined in the
      [GETUSERMEDIA] specification, typically represents a stream of data of
      audio or video. One or more MediaStreamTracks can be
      collected in a MediaStream (strictly speaking, a
      MediaStream as defined in [GETUSERMEDIA] may contain zero
      or more MediaStreamTrack objects).
A MediaStreamTrack may be extended to represent a media
      flow that either comes from or is sent to a remote peer (and not just the
      local camera, for instance). The extensions required to enable this
      capability on the MediaStreamTrack object will be described
      in this section. How the media is transmitted to the peer is described in
      [RTCWEB-RTP], [RTCWEB-AUDIO], and [RTCWEB-TRANSPORT].
A MediaStreamTrack sent to another peer will appear as
      one and only one MediaStreamTrack to the recipient. A peer
      is defined as a user agent that supports this specification. In addition,
      the sending side application can indicate what MediaStream
      object(s) the MediaStreamTrack is a member of. The
      corresponding MediaStream object(s) on the receiver side
      will be created (if not already present) and populated accordingly.
As also described earlier in this document, the objects
      RTCRtpSenderRTCRtpReceiverMediaStreamTracks.
Channels are the smallest unit considered in the
      Media Capture and Streams specification. Channels are intended to be
      encoded together for transmission as, for instance, an RTP payload type.
      All of the channels that a codec needs to encode jointly MUST be in the
      same MediaStreamTrack and the codecs SHOULD be able to
      encode, or discard, all the channels in the track.
The concepts of an input and output to a given
      MediaStreamTrack apply in the case of
      MediaStreamTrack objects transmitted over the network as
      well. A MediaStreamTrack created by an
      RTCPeerConnectionMediaStreamTrack from a local source, for
      instance a camera via [GETUSERMEDIA], will have an output that
      represents what is transmitted to a remote peer if the object is used
      with an RTCPeerConnection
The concept of duplicating MediaStream and
      MediaStreamTrack objects as described in [GETUSERMEDIA]
      is also applicable here. This feature can be used, for instance, in a
      video-conferencing scenario to display the local video from the user's
      camera and microphone in a local monitor, while only transmitting the
      audio to the remote peer (e.g. in response to the user using a "video
      mute" feature). Combining different MediaStreamTrack objects
      into new MediaStream objects is useful in certain
      situations.
In this document, we only specify aspects of the
      following objects that are relevant when used along with an
      RTCPeerConnectionMediaStream and
      MediaStreamTrack.
The id
        attribute specified in MediaStream returns an id that is
        unique to this stream, so that streams can be recognized at the remote
        end of the RTCPeerConnection
When a MediaStream is created to represent a
        stream obtained from a remote peer, the id
        attribute is initialized from information provided by the remote
        source.
The id of a MediaStream object is
        unique to the source of the stream, but that does not mean it is not
        possible to end up with duplicates. For example, the tracks of a
        locally generated stream could be sent from one user agent to a remote
        peer using RTCPeerConnection
A MediaStreamTrack object's reference to its
      MediaStream in the non-local media source case (an RTP
      source, as is the case for each MediaStreamTrack
      associated with an RTCRtpReceiver
Whenever an RTCRtpReceiverMediaStreamTrack is muted,
      but not ended, and the [[Receptive]] slot of the
      RTCRtpTransceiverRTCRtpReceivertrue,
      it MUST queue a task to set the muted state of the corresponding
      MediaStreamTrack to false.
      
When one of the SSRCs for RTP source media streams received
      by an RTCRtpReceiverMediaStreamTrack to
      true. Note that setRemoteDescriptiontracktrue.
The procedures add a track, remove a track and set a track's muted state are specified in [GETUSERMEDIA].
When a MediaStreamTrack track produced by
        an RTCRtpReceiverended [GETUSERMEDIA] (such as via a call to
        receiver.trackstop), the user agent MAY
        choose to free resources allocated for the incoming stream, by
        for instance turning off the decoder of receiver.
The concept of constraints and constrainable properties, including
        MediaTrackConstraints
        (MediaStreamTrack.getConstraints(),
        MediaStreamTrack.applyConstraints()), and
        MediaTrackSettings
        (MediaStreamTrack.getSettings()) are outlined in
        [GETUSERMEDIA]. However, the constrainable properties of tracks
        sourced from a peer connection are different than those sourced by
        getUserMedia(); the constraints and settings applicable to
        MediaStreamTracks sourced from a remote
        source are defined here. The settings of a remote track represent
        the latest frame received.
MediaStreamTrack.getCapabilities() MUST always return the
        empty set and MediaStreamTrack.applyConstraints() MUST
        always reject with OverconstrainedError on remote tracks
        for constraints defined here.
The following constrainable properties are defined to apply to video
        MediaStreamTracks sourced from a remote
        source:
| Property Name | Values | Notes | 
|---|---|---|
| width | ConstrainULong | As a setting, this is the width, in pixels, of the latest frame received. | 
| height | ConstrainULong | As a setting, this is the height, in pixels, of the latest frame received. | 
| frameRate | ConstrainDouble | As a setting, this is an estimate of the frame rate based on recently received frames. | 
| aspectRatio | ConstrainDouble | As a setting, this is the aspect ratio of the latest frame; this is the width in pixels divided by height in pixels as a double rounded to the tenth decimal place. | 
This document does not define any constrainable properties to apply
        to audio MediaStreamTracks sourced from a remote
        source.
This section is non-normative.
When two peers decide they are going to set up a connection to each other, they both go through these steps. The STUN/TURN server configuration describes a server they can use to get things like their public IP address or to set up NAT traversal. They also have to send data for the signaling channel to each other using the same out-of-band mechanism they used to establish that they were going to communicate in the first place.
const signaling = new SignalingChannel(); // handles JSON.stringify/parse
const constraints = {audio: true, video: true};
const configuration = {iceServers: [{urls: 'stun:stun.example.org'}]};
const pc = new RTCPeerConnection(configuration);
// send any ice candidates to the other peer
pc.onicecandidate = ({candidate}) => signaling.send({candidate});
// let the "negotiationneeded" event trigger offer generation
pc.onnegotiationneeded = async () => {
  try {
    await pc.setLocalDescription();
    // send the offer to the other peer
    signaling.send({description: pc.localDescription});
  } catch (err) {
    console.error(err);
  }
};
pc.ontrack = ({track, streams}) => {
  // once media for a remote track arrives, show it in the remote video element
  track.onunmute = () => {
    // don't set srcObject again if it is already set.
    if (remoteView.srcObject) return;
    remoteView.srcObject = streams[0];
  };
};
// call start() to initiate
function start() {
  addCameraMic();
}
// add camera and microphone to connection
async function addCameraMic() {
  try {
    // get a local stream, show it in a self-view and add it to be sent
    const stream = await navigator.mediaDevices.getUserMedia(constraints);
    for (const track of stream.getTracks()) {
      pc.addTrack(track, stream);
    }
    selfView.srcObject = stream;
  } catch (err) {
    console.error(err);
  }
}
signaling.onmessage = async ({data: {description, candidate}}) => {
  try {
    if (description) {
      await pc.setRemoteDescription(description);
      // if we got an offer, we need to reply with an answer
      if (description.type == 'offer') {
        if (!selfView.srcObject) {
          // blocks negotiation on permission (not recommended in production code)
          await addCameraMic();
        }
        await pc.setLocalDescription();
        signaling.send({description: pc.localDescription});
      }
    } else if (candidate) {
      await pc.addIceCandidate(candidate);
    }
  } catch (err) {
    console.error(err);
  }
};When two peers decide they are going to set up a connection to each other and want to have the ICE, DTLS, and media connections "warmed up" such that they are ready to send and receive media immediately, they both go through these steps.
const signaling = new SignalingChannel(); // handles JSON.stringify/parse
const constraints = {audio: true, video: true};
const configuration = {iceServers: [{urls: 'stun:stun.example.org'}]};
let pc;
let audio;
let video;
let started = false;
// Call warmup() before media is ready, to warm-up ICE, DTLS, and media.
async function warmup(isAnswerer) {
  pc = new RTCPeerConnection(configuration);
  if (!isAnswerer) {
    audio = pc.addTransceiver('audio');
    video = pc.addTransceiver('video');
  }
  // send any ice candidates to the other peer
  pc.onicecandidate = ({candidate}) => signaling.send({candidate});
  // let the "negotiationneeded" event trigger offer generation
  pc.onnegotiationneeded = async () => {
    try {
      await pc.setLocalDescription();
      // send the offer to the other peer
      signaling.send({description: pc.localDescription});
    } catch (err) {
      console.error(err);
    }
  };
  pc.ontrack = async ({track, transceiver}) => {
    try {
      // once media for the remote track arrives, show it in the video element
      event.track.onunmute = () => {
        // don't set srcObject again if it is already set.
        if (!remoteView.srcObject) {
          remoteView.srcObject = new MediaStream();
        }
        remoteView.srcObject.addTrack(track);
      }
      if (isAnswerer) {
        if (track.kind == 'audio') {
          audio = transceiver;
        } else if (track.kind == 'video') {
          video = transceiver;
        }
        if (started) await addCameraMicWarmedUp();
      }
    } catch (err) {
      console.error(err);
    }
  };
  try {
    // get a local stream, show it in a self-view and add it to be sent
    selfView.srcObject = await navigator.mediaDevices.getUserMedia(constraints);
    if (started) await addCameraMicWarmedUp();
  } catch (err) {
    console.error(err);
  }
}
// call start() after warmup() to begin transmitting media from both ends
function start() {
  signaling.send({start: true});
  signaling.onmessage({data: {start: true}});
}
// add camera and microphone to already warmed-up connection
async function addCameraMicWarmedUp() {
  const stream = selfView.srcObject;
  if (audio && video && stream) {
    await Promise.all([
      audio.sender.replaceTrack(stream.getAudioTracks()[0]),
      video.sender.replaceTrack(stream.getVideoTracks()[0]),
    ]);
  }
}
signaling.onmessage = async ({data: {start, description, candidate}}) => {
  if (!pc) warmup(true);
  try {
    if (start) {
      started = true;
      await addCameraMicWarmedUp();
    } else if (description) {
      await pc.setRemoteDescription(description);
      // if we got an offer, we need to reply with an answer
      if (description.type == 'offer') {
        await pc.setLocalDescription();
        signaling.send({description: pc.localDescription});
      }
    } else {
      await pc.addIceCandidate(candidate);
    }
  } catch (err) {
    console.error(err);
  }
};A client wants to send multiple RTP encodings (simulcast) to a server.
const signaling = new SignalingChannel(); // handles JSON.stringify/parse
const constraints = {audio: true, video: true};
const configuration = {'iceServers': [{'urls': 'stun:stun.example.org'}]};
let pc;
// call start() to initiate
async function start() {
  pc = new RTCPeerConnection(configuration);
  // let the "negotiationneeded" event trigger offer generation
  pc.onnegotiationneeded = async () => {
    try {
      await pc.setLocalDescription();
      // send the offer to the other peer
      signaling.send({description: pc.localDescription});
    } catch (err) {
      console.error(err);
    }
  };
  try {
    // get a local stream, show it in a self-view and add it to be sent
    const stream = await navigator.mediaDevices.getUserMedia(constraints);
    selfView.srcObject = stream;
    pc.addTransceiver(stream.getAudioTracks()[0], {direction: 'sendonly'});
    pc.addTransceiver(stream.getVideoTracks()[0], {
      direction: 'sendonly',
      sendEncodings: [
        {rid: 'q', scaleResolutionDownBy: 4.0}
        {rid: 'h', scaleResolutionDownBy: 2.0},
        {rid: 'f'},
      ]
    });
  } catch (err) {
    console.error(err);
  }
}
signaling.onmessage = async ({data: {description, candidate}}) => {
  try {
    if (description) {
      await pc.setRemoteDescription(description);
      // if we got an offer, we need to reply with an answer
      if (description.type == 'offer') {
        await pc.setLocalDescription();
        signaling.send({description: pc.localDescription});
      }
    } else if (candidate) {
      await pc.addIceCandidate(candidate);
    }
  } catch (err) {
    console.error(err);
  }
};This example shows how to create an
        RTCDataChannelRTCDataChannelinput field for user input.
const signaling = new SignalingChannel(); // handles JSON.stringify/parse
const configuration = {iceServers: [{urls: 'stun:stun.example.org'}]};
let pc, channel;
// call start() to initiate
function start() {
  pc = new RTCPeerConnection(configuration);
  // send any ice candidates to the other peer
  pc.onicecandidate = ({candidate}) => signaling.send({candidate});
  // let the "negotiationneeded" event trigger offer generation
  pc.onnegotiationneeded = async () => {
    try {
      await pc.setLocalDescription();
      // send the offer to the other peer
      signaling.send({description: pc.localDescription});
    } catch (err) {
      console.error(err);
    }
  };
  // create data channel and setup chat using "negotiated" pattern
  channel = pc.createDataChannel('chat', {negotiated: true, id: 0});
  channel.onopen = () => input.disabled = false;
  channel.onmessage = ({data}) => showChatMessage(data);
  input.onkeypress = ({keyCode}) => {
    // only send when user presses enter
    if (keyCode != 13) return;
    channel.send(input.value);
  }
}
signaling.onmessage = async ({data: {description, candidate}}) => {
  if (!pc) start(false);
  try {
    if (description) {
      await pc.setRemoteDescription(description);
      // if we got an offer, we need to reply with an answer
      if (description.type == 'offer') {
        await pc.setLocalDescription();
        signaling.send({description: pc.localDescription});
      }
    } else if (candidate) {
      await pc.addIceCandidate(candidate);
    }
  } catch (err) {
    console.error(err);
  }
};This shows an example of one possible call flow between two browsers. This does not show the procedure to get access to local media or every callback that gets fired but instead tries to reduce it down to only show the key events and messages.
Examples assume that sender is an RTCRtpSender
Sending the DTMF signal "1234" with 500 ms duration per tone:
if (sender.dtmf.canInsertDTMF) {
  const duration = 500;
  sender.dtmf.insertDTMF('1234', duration);
} else {
  console.log('DTMF function not available');
}Send the DTMF signal "123" and abort after sending "2".
async function sendDTMF() {
  if (sender.dtmf.canInsertDTMF) {
    sender.dtmf.insertDTMF('123');
    await new Promise(r => sender.dtmf.ontonechange = e => e.tone == '2' && r());
    // empty the buffer to not play any tone after "2"
    sender.dtmf.insertDTMF('');
  } else {
    console.log('DTMF function not available');
  }
}Send the DTMF signal "1234", and light up the active key using
      lightKey(key) while the tone is playing (assuming that
      lightKey("") will darken all the keys):
const wait = ms => new Promise(resolve => setTimeout(resolve, ms));
if (sender.dtmf.canInsertDTMF) {
  const duration = 500; // ms
  sender.dtmf.insertDTMF(sender.dtmf.toneBuffer + '1234', duration);
  sender.dtmf.ontonechange = async ({tone}) => {
    if (!tone) return;
    lightKey(tone); // light up the key when playout starts
    await wait(duration);
    lightKey(''); // turn off the light after tone duration
  };
} else {
  console.log('DTMF function not available');
}It is always safe to append to the tone buffer. This example appends before any tone playout has started as well as during playout.
if (sender.dtmf.canInsertDTMF) {
  sender.dtmf.insertDTMF('123');
  // append more tones to the tone buffer before playout has begun
  sender.dtmf.insertDTMF(sender.dtmf.toneBuffer + '456');
  sender.dtmf.ontonechange = ({tone}) => {
    // append more tones when playout has begun
    if (tone != '1') return;
    sender.dtmf.insertDTMF(sender.dtmf.toneBuffer + '789');
  };
} else {
  console.log('DTMF function not available');
}Send a 1-second "1" tone followed by a 2-second "2" tone:
if (sender.dtmf.canInsertDTMF) {
  sender.dtmf.ontonechange = ({tone}) => {
    if (tone == '1') {
      sender.dtmf.insertDTMF(sender.dtmf.toneBuffer + '2', 2000);
    }
  };
  sender.dtmf.insertDTMF(sender.dtmf.toneBuffer + '1', 1000);
} else {
  console.log('DTMF function not available');
}Perfect negotiation is a recommended pattern to manage negotiation
      transparently, abstracting this asymmetric task away from the rest of an
      application. This pattern has advantages over one
      side always being the offerer, as it lets applications operate on both
      peer connection objects simultaneously without risk of glare (an offer
      coming in outside of "stable
It designates different roles to the two peers, with behavior to resolve signaling collisions between them:
The polite peer uses rollback to avoid collision with an incoming offer.
The impolite peer ignores an incoming offer when this would collide with its own.
Together, they manage signaling for the rest of the application in a
      manner that doesn't deadlock. The example assumes a
      polite boolean variable indicating the designated role:
const signaling = new SignalingChannel(); // handles JSON.stringify/parse
const constraints = {audio: true, video: true};
const configuration = {iceServers: [{urls: 'stun:stun.example.org'}]};
const pc = new RTCPeerConnection(configuration);
// call start() anytime on either end to add camera and microphone to connection
async function start() {
  try {
    const stream = await navigator.mediaDevices.getUserMedia(constraints);
    for (const track of stream.getTracks()) {
      pc.addTrack(track, stream);
    }
    selfView.srcObject = stream;
  } catch (err) {
    console.error(err);
  }
}
pc.ontrack = ({track, streams}) => {
  // once media for a remote track arrives, show it in the remote video element
  track.onunmute = () => {
    // don't set srcObject again if it is already set.
    if (remoteView.srcObject) return;
    remoteView.srcObject = streams[0];
  };
};
// - The perfect negotiation logic, separated from the rest of the application ---
// keep track of some negotiation state to prevent races and errors
let makingOffer = false;
let ignoreOffer = false;
let isSettingRemoteAnswerPending = false;
// send any ice candidates to the other peer
pc.onicecandidate = ({candidate}) => signaling.send({candidate});
// let the "negotiationneeded" event trigger offer generation
pc.onnegotiationneeded = async () => {
  try {
    makingOffer = true;
    await pc.setLocalDescription();
    signaling.send({description: pc.localDescription});
  } catch (err) {
     console.error(err);
  } finally {
    makingOffer = false;
  }
};
signaling.onmessage = async ({data: {description, candidate}}) => {
  try {
    if (description) {
      // An offer may come in while we are busy processing SRD(answer).
      // In this case, we will be in "stable" by the time the offer is processed
      // so it is safe to chain it on our Operations Chain now.
      const readyForOffer =
          !makingOffer &&
          (pc.signalingState == "stable" || isSettingRemoteAnswerPending);
      const offerCollision = description.type == "offer" && !readyForOffer;
      ignoreOffer = !polite && offerCollision;
      if (ignoreOffer) {
        return;
      }
      isSettingRemoteAnswerPending = description.type == "answer";
      await pc.setRemoteDescription(description); // SRD rolls back as needed
      isSettingRemoteAnswerPending = false;
      if (description.type == "offer") {
        await pc.setLocalDescription();
        signaling.send({description: pc.localDescription});
      }
    } else if (candidate) {
      try {
        await pc.addIceCandidate(candidate);
      } catch (err) {
        if (!ignoreOffer) throw err; // Suppress ignored offer's candidates
      }
    }
  } catch (err) {
    console.error(err);
  }
}Note that this is timing sensitive, and deliberately uses versions
      of setLocalDescriptionsetRemoteDescription
The ignoreOffer variable is needed, because
      the RTCPeerConnection
Some operations throw or fire RTCErrorDOMException
    that carries additional WebRTC-specific information.
RTCError InterfaceWebIDL[Exposed=Window] interfaceRTCError: DOMException {constructor(RTCErrorInitinit, optional DOMString message = ""); readonly attributeRTCErrorDetailTypeerrorDetail; readonly attribute long?sdpLineNumber; readonly attribute long?sctpCauseCode; readonly attribute unsigned long?receivedAlert; readonly attribute unsigned long?sentAlert; };
constructor()Run the following steps:
Let init be the constructor's first argument.
Let message be the constructor's second argument.
Let e be a new RTCError
Invoke the DOMException constructor of e with the
                messagename argument set to
                "OperationError".
This name does not have a mapping to a legacy
                code so e.code will return
                0.
Set all RTCErrornull.
Return e.
errorDetail of type RTCErrorDetailType, readonlyThe WebRTC-specific error code for the type of error that occurred.
sdpLineNumber of type long, readonly, nullableIf errorDetailsdp-syntax-error
sctpCauseCode of type long, readonly, nullableIf errorDetailsctp-failure
receivedAlert of type unsigned long, readonly,
          nullableIf errorDetaildtls-failure
sentAlert of type unsigned long, readonly,
          nullableIf errorDetaildtls-failure
All attributes defined in RTCErrorerrorDetailsdpLineNumbersctpCauseCodereceivedAlertsentAlertDOMException.
RTCErrorInit DictionaryWebIDLdictionaryRTCErrorInit{ requiredRTCErrorDetailTypeerrorDetail; longsdpLineNumber; longsctpCauseCode; unsigned longreceivedAlert; unsigned longsentAlert; };
The errorDetail, sdpLineNumber, sctpCauseCode, receivedAlert and sentAlert members of RTCErrorInitRTCError
RTCErrorDetailType EnumWebIDLenumRTCErrorDetailType{ "data-channel-failure", "dtls-failure", "fingerprint-failure", "sctp-failure", "sdp-syntax-error", "hardware-encoder-not-available", "hardware-encoder-error" };
| Enumeration description | |
|---|---|
| data-channel-failure | The data channel has failed. | 
| dtls-failure | The DTLS negotiation has failed or the connection
              has been terminated with a fatal error. The contains information relating to
              the nature of error.  If a fatal DTLS alert was received,
              theattribute is set to the
              value of the DTLS alert received. If a fatal DTLS alert was
              sent, theattribute is set to
              the value of the DTLS alert sent. | 
| fingerprint-failure | The 's
              remote certificate did not match any of the fingerprints
              provided in the SDP. If the remote peer cannot match
              the local certificate against the provided fingerprints,
              this error is not generated. Instead a "bad_certificate"
              (42) DTLS alert might be received from the remote peer,
              resulting in a "". | 
| sctp-failure | The SCTP negotiation has failed or the connection
              has been terminated with a fatal error. The attribute is set to the
              SCTP cause code. | 
| sdp-syntax-error | The SDP syntax is not valid. The attribute is set to the line number in the SDP where the syntax
              error was detected. | 
| hardware-encoder-not-available | The hardware encoder resources required for the requested operation are not available. | 
| hardware-encoder-error | The hardware encoder does not support the provided parameters. | 
RTCErrorEvent InterfaceThe RTCErrorEventRTCError
WebIDL[Exposed=Window] interfaceRTCErrorEvent: Event {constructor(DOMString type,RTCErrorEventIniteventInitDict); [SameObject] readonly attributeRTCErrorerror; };
constructor()Constructs a new
            RTCErrorEvent
error of type RTCErrorThe RTCError
RTCErrorEventInit DictionaryWebIDLdictionaryRTCErrorEventInit: EventInit { requiredRTCErrorerror; };
error of type RTCErrorThe RTCError
This section is non-normative.
The following events fire on RTCDataChannel
| Event name | Interface | Fired when... | 
|---|---|---|
| open | Event | The object's underlying data
            transport has been established (or re-established). | 
| message | MessageEvent[html] | A message was successfully received. | 
| bufferedamountlow | Event | The object'sdecreases from above itsto less than
          or equal to its. | 
| error |  | An error occurred on the data channel. | 
| closing | Event | The object transitions to the
            "" state | 
| close | Event | The object's underlying data
            transport has been closed. | 
The following events fire on RTCPeerConnection
| Event name | Interface | Fired when... | 
|---|---|---|
| track |  | New incoming media has been negotiated for a specific , and that receiver'shas been added to any associated remoteMediaStreams. | 
| negotiationneeded | Event | The browser wishes to inform the application that session negotiation needs to be done (i.e. a createOffer call followed by setLocalDescription). | 
| signalingstatechange | Event | The signaling state has changed. This state change is the
            result of either orbeing invoked. | 
| iceconnectionstatechange | Event | The 's ICE connection state
            has changed. | 
| icegatheringstatechange | Event | The 's ICE gathering state has
            changed. | 
| icecandidate |  | A new is made available to
          the script. | 
| connectionstatechange | Event | The .has changed. | 
| icecandidateerror |  | A failure occured when gathering ICE candidates. | 
| datachannel |  | A new is dispatched to the
          script in response to the other peer creating a channel. | 
The following events fire on RTCDTMFSender
| Event name | Interface | Fired when... | 
|---|---|---|
| tonechange |  | The object has either just
          begun playout of a tone (returned as theattribute) or just ended
          the playout of tones in the(returned as an empty value in theattribute). | 
The following events fire on RTCIceTransport
| Event name | Interface | Fired when... | 
|---|---|---|
| statechange | Event | The state changes. | 
| gatheringstatechange | Event | The gathering state
          changes. | 
| selectedcandidatepairchange | Event | The 's selected candidate pair
          changes. | 
The following events fire on RTCDtlsTransport
| Event name | Interface | Fired when... | 
|---|---|---|
| statechange | Event | The state changes. | 
| error |  | An error occurred on the (either "" or ""). | 
The following events fire on RTCSctpTransport
| Event name | Interface | Fired when... | 
|---|---|---|
| statechange | Event | The state changes. | 
This section is non-normative.
This section is non-normative; it specifies no new behaviour, but instead summarizes information already present in other parts of the specification. The overall security considerations of the general set of APIs and protocols used in WebRTC are described in [RTCWEB-SECURITY-ARCH].
This document extends the Web platform with the ability to set up real time, direct communication between browsers and other devices, including other browsers.
This means that data and media can be shared between applications running in different browsers, or between an application running in the same browser and something that is not a browser, something that is an extension to the usual barriers in the Web model against sending data between entities with different origins.
The WebRTC specification provides no user prompts or chrome indicators for communication; it assumes that once the Web page has been allowed to access media, it is free to share that media with other entities as it chooses. Peer-to-peer exchanges of data view WebRTC datachannels can thus occur without any user explicit consent or involvement, similarly as a server-mediated exchange (e.g. via Web Sockets) could occur without user involvement.
Even without WebRTC, the Web server providing a Web application will know the public IP address to which the application is delivered. Setting up communications exposes additional information about the browser’s network context to the web application, and may include the set of (possibly private) IP addresses available to the browser for WebRTC use. Some of this information has to be passed to the corresponding party to enable the establishment of a communication session.
Revealing IP addresses can leak location and means of connection; this can be sensitive. Depending on the network environment, it can also increase the fingerprinting surface and create persistent cross-origin state that cannot easily be cleared by the user.
A connection will always reveal the IP addresses proposed for
      communication to the corresponding party. The application can limit this
      exposure by choosing not to use certain addresses using the settings
      exposed by the RTCIceTransportPolicy
Mitigating the exposure of IP addresses to the application itself requires limiting the IP addresses that can be used, which will impact the ability to communicate on the most direct path between endpoints. Browsers are encouraged to provide appropriate controls for deciding which IP addresses are made available to applications, based on the security posture desired by the user. The choice of which addresses to expose is controlled by local policy (see [RTCWEB-IP-HANDLING] for details).
Since the browser is an active platform executing in a trusted network environment (inside the firewall), it is important to limit the damage that the browser can do to other elements on the local network, and it is important to protect data from interception, manipulation and modification by untrusted participants.
Mitigations include:
These measures are specified in the relevant IETF documents.
The fact that communication is taking place cannot be hidden from adversaries that can observe the network, so this has to be regarded as public information.
Communication certificates may be opaquely shared using
      postMessage() in anticipation of future needs. User agents are
      strongly encouraged to isolate the private keying material these objects
      hold a handle to, from the processes that have access to the
      RTCCertificate
As described above, the list of IP addresses exposed by the WebRTC API can be used as a persistent cross-origin state.
Beyond IP addresses, the WebRTC API exposes information about the
      underlying media system via the RTCRtpSendergetCapabilitiesRTCRtpReceivergetCapabilities
When establishing DTLS connections, the WebRTC API can generate certificates that can be persisted by the application (e.g. in IndexedDB). These certificates are not shared across origins, and get cleared when persistent storage is cleared for the origin.
setRemoteDescriptionontrack
This section is non-normative.
The WebRTC 1.0 specification exposes an API to control protocols (defined within the IETF) necessary to establish real-time audio, video and data exchange.
The Telecommunications Device for the Deaf (TDD/TTY) enables individuals who are hearing or speech impaired (among others) to communicate over telephone lines. Real-time Text, defined in [RFC4103], utilizes T.140 encapsulated in RTP to enable the transition from TDD/TTY devices to IP-based communications, including emergency communication with Public Safety Access Points (PSAP).
Since Real-time Text requires the ability to send and receive data in near real time, it can be best supported via the WebRTC 1.0 data channel API. As defined by the IETF, the data channel protocol utilizes the SCTP/DTLS/UDP protocol stack, which supports both reliable and unreliable data channels. The IETF chose to standardize SCTP/DTLS/UDP over proposals for an RTP data channel which relied on SRTP key management and were focused on unreliable communications.
Since the IETF chose a different approach than the RTP data channel as part of the WebRTC suite of protocols, as of the time of this publication there is no standardized way for the WebRTC APIs to directly support Real-time Text as defined at IETF and implemented in U.S. (FCC) regulations. The WebRTC working Group will evaluate whether the developing IETF protocols in this space warrant direct exposure in the browser APIs and is looking for input from the relevant user communities on this potential gap.
Within the IETF MMUSIC Working Group, work is ongoing to enable Real-time text to be sent over the WebRTC data channel, allowing gateways to be deployed to translate between the SCTP data channel protocol and RFC 4103 Real-time text. This work, once completed, is expected to enable a unified and interoperable approach for integrating real-time text in WebRTC user-agents (including browsers) - through a gateway or otherwise.
At the time of this publication, gateways that enable effective RTT support in WebRTC clients can be developed e.g. through a custom WebRTC data channel. This is deemed sufficient until such time as future standardized gateways are enabled via IETF protocols such as the SCTP data channel protocol and RFC 4103 Real-time text. This will need to be defined at IETF in conjunction with related work at W3C groups to effectively and consistently standardise RTT support internationally.
The editors wish to thank the Working Group chairs and Team Contact, Harald Alvestrand, Stefan Håkansson, Erik Lagerway and Dominique Hazaël-Massieux, for their support. Substantial text in this specification was provided by many people including Martin Thomson, Harald Alvestrand, Justin Uberti, Eric Rescorla, Peter Thatcher, Jan-Ivar Bruaroey and Peter Saint-Andre. Dan Burnett would like to acknowledge the significant support received from Voxeo and Aspect during the development of this specification.
The RTCRtpSenderRTCRtpReceiver