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 developed by the Media Capture Task Force.
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.
While the specification is feature complete and is expected to be stable, there are also a number of known substantive issues on the specification that will be addressed during the Candidate Recommendation period based on implementation experience feedback.
It might also evolve based on feedback gathered as its associated test suite evolves. This test suite will be used to build an implementation report of the API.
Since the previous publication as Candidate Recommendation, the specification was updated with a number of bug fixes and clarifications in its algorithms. The following new APIs were added as part of these improvements: RTCRtpSender.setStreams()
, RTCRtpTransceiver.currentDirection
, RTCSctpTransport.maxChannels
, RTCPeerConnection.onstatsended
, and the RTCStatsEvent
interface.
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.
The following features are marked as at risk:
negotiate
of RTCRtcpMuxPolicyencodings
attribute of RTCRtpReceiveParameters
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. Comments regarding this document are welcome. Please send them to public-webrtc@w3.org (subscribe, 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 31 December 2018.
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 February 2018 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 Media Capture Task Force. 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, SHALL, and SHOULD are to be interpreted as described in [RFC2119].
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-1], as this specification uses that specification and terminology.
The EventHandler
interface, representing a callback used for event handlers, and the
ErrorEvent
interface are defined in [HTML51].
The concepts queue a task, fire a simple event and networking task source are defined in [HTML51].
The terms event, event handlers and event handler event types are defined in [HTML51].
performance.timeOrigin
and performance.now()
are defined in [HIGHRES-TIME].
The terms MediaStream, MediaStreamTrack
, and
MediaStreamConstraints
are defined in [GETUSERMEDIA].
Note that MediaStream
is extended in
the MediaStream section
in this document while
is extended in MediaStreamTrack
the MediaStreamTrack section
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 RTCStatsType, stats object and monitored object are defined in [WEBRTC-STATS].
When referring to exceptions, the terms throw and create are defined in [WEBIDL-1].
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 OAuth Client and Authorization Server roles are defined in [RFC6749] Section 1.1.
An
instance allows an
application to establish peer-to-peer communications with another
RTCPeerConnection
instance in another browser, or to
another endpoint implementing the required protocols. Communications are coordinated by the
exchange of control messages (called a signaling protocol) over a
signaling channel which is provided by unspecified means, but generally
by a script in the page via the server, e.g. using
RTCPeerConnection
XMLHttpRequest
[XMLHttpRequest] or Web Sockets
[WEBSOCKETS-API].
RTCConfiguration
DictionaryThe RTCConfiguration
defines a set of parameters to
configure how the peer-to-peer communication established via
is established or
re-established.RTCPeerConnection
dictionary RTCConfiguration
{
sequence<RTCIceServer
> iceServers
;
RTCIceTransportPolicy
iceTransportPolicy
= "all";
RTCBundlePolicy
bundlePolicy
= "balanced";
RTCRtcpMuxPolicy
rtcpMuxPolicy
= "require";
DOMString peerIdentity
;
sequence<RTCCertificate
> certificates
;
[EnforceRange]
octet iceCandidatePoolSize
= 0;
};
RTCConfiguration
MembersiceServers
of type sequence<RTCIceServer
>An array of objects describing servers available to be used by ICE, such as STUN and TURN servers.
iceTransportPolicy
of type
RTCIceTransportPolicy
,
defaulting to "all"
Indicates which candidates the ICE Agent is allowed to use.
bundlePolicy
of type RTCBundlePolicy
, defaulting to
"balanced"
Indicates which media-bundling policy to use when gathering ICE candidates.
rtcpMuxPolicy
of type RTCRtcpMuxPolicy
, defaulting to
"require"
Indicates which rtcp-mux policy to use when gathering ICE candidates.
peerIdentity
of type DOMStringSets the target peer identity for the
RTCPeerConnection
. The RTCPeerConnection
will not
establish a connection to a remote peer unless it can be
successfully authenticated with the provided name.
certificates
of type sequence<RTCCertificate
>A set of certificates that the
uses to authenticate.RTCPeerConnection
Valid values for this parameter are created through calls to
the
function.generateCertificate
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
implementation selects which of
the certificates is used for a given connection; how
certificates are selected is outside the scope of this
specification.
If this value is absent, then a default set of certificates
is generated for each
instance.RTCPeerConnection
This option allows applications to establish key continuity.
An RTCCertificate
can be persisted in
[INDEXEDDB] and reused. Persistence and reuse also avoids the
cost of key generation.
The value for this configuration option cannot change after its value is initially selected.
iceCandidatePoolSize
of type
octet, defaulting to
0
Size of the prefetched ICE pool as defined in [JSEP] (section 3.5.4. and section 4.1.1.).
RTCIceCredentialType
Enumenum RTCIceCredentialType
{
"password",
"oauth"
};
Enumeration description | |
---|---|
password |
The credential is a long-term authentication username and password, as described in [RFC5389], Section 10.2. |
oauth |
An OAuth 2.0 based authentication method, as described in [RFC7635]. For OAuth Authentication, the ICE Agent requires three
pieces of credential information. The credential is composed of
a Note
This specification does not define how an application (acting
as the OAuth Client) obtains the
The application, acting as the OAuth
Client, is responsible for refreshing the credential
information and updating the ICE Agent with fresh new
credentials before the The length of the HMAC key
( Note According to [RFC7635] Section 4.1, the HMAC key MUST be a symmetric key, as asymmetric keys would result in large access tokens which may not fit in a single STUN message. |
RTCOAuthCredential
DictionaryThe RTCOAuthCredential
dictionary is used to describe
the OAuth auth credential information which is used by the STUN/TURN
client (inside the ICE Agent) to authenticate against a STUN/TURN
server, as described in [RFC7635]. Note that the kid
parameter is not located in this dictionary, but in
RTCIceServer
's username
member.
dictionary RTCOAuthCredential
{
required DOMString macKey
;
required DOMString accessToken
;
};
RTCOAuthCredential
Members
macKey
of type DOMString, requiredThe "mac_key", as described in [RFC7635], Section 6.2, in a base64-url encoded format. It is used in STUN message integrity hash calculation (as the password is used in password based authentication). Note that the OAuth response "key" parameter is a JSON Web Key (JWK) or a JWK encrypted with a JWE format. Also note that this is the only OAuth parameter whose value is not used directly, but must be extracted from the "k" parameter value from the JWK, which contains the needed base64-encoded "mac_key".
accessToken
of type DOMString, requiredThe "access_token", as described in [RFC7635], Section 6.2, in a base64-encoded format. This is an encrypted self-contained token that is opaque to the application. Authenticated encryption is used for message encryption and integrity protection. The access token contains a non-encrypted nonce value, which is used by the Authorization Server for unique mac_key generation. The second part of the token is protected by Authenticated Encryption. It contains the mac_key, a timestamp and a lifetime. The timestamp combined with lifetime provides expiry information; this information describes the time window during which the token credential is valid and accepted by the TURN server.
An example of an RTCOAuthCredential dictionary is:
{
macKey: 'WmtzanB3ZW9peFhtdm42NzUzNG0=',
accessToken: 'AAwg3kPHWPfvk9bDFL936wYvkoctMADzQ5VhNDgeMR3+ZlZ35byg972fW8QjpEl7bx91YLBPFsIhsxloWcXPhA=='
}
RTCIceServer
DictionaryThe RTCIceServer
dictionary is used to describe the
STUN and TURN servers that can be used by the ICE Agent to
establish a connection with a peer.
dictionary RTCIceServer
{
required (DOMString or sequence<DOMString>) urls
;
DOMString username
;
(DOMString or RTCOAuthCredential
) credential
;
RTCIceCredentialType
credentialType
= "password";
};
RTCIceServer
Membersurls
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
object represents a
TURN server, and RTCIceServer
credentialType
is
"password"
, then this attribute specifies the
username to use with that TURN server.
If this
object represents a
TURN server, and RTCIceServer
credentialType
is
"oauth"
, then this attribute specifies the Key ID
(kid
) of the shared symmetric key, which is shared
between the TURN server and the Authorization Server, as described
in [RFC7635]. It is an ephemeral and unique key identifier.
The kid
allows the TURN server to select the
appropriate keying material for decryption of the Access-Token,
so the key identified by this kid
is used in the
Authenticated Encryption of the "access_token". The
kid
value is equal with the OAuth response "kid"
parameter, as defined in [RFC7515] Section 4.1.4.
credential
of type (DOMString or RTCOAuthCredential
)
If this
object represents a
TURN server, then this attribute specifies the credential to
use with that TURN server.RTCIceServer
If credentialType
is "password"
,
credential
is a DOMString, and represents a
long-term authentication password, as described in
[RFC5389], Section 10.2.
If credentialType
is "oauth"
,
credential
is an RTCOAuthCredential
, which
contains the OAuth access token and MAC key.
credentialType
of type RTCIceCredentialType
, defaulting to
"password"
If this
object represents a
TURN server, then this attribute specifies how
credential should be used when that TURN server
requests authorization.RTCIceServer
An example array of RTCIceServer objects is:
[
{urls: 'stun:stun1.example.net'},
{urls: ['turns:turn.example.org', 'turn:turn.example.net'],
username: 'user',
credential: 'myPassword',
credentialType: 'password'},
{urls: 'turns:turn2.example.net',
username: '22BIjxU93h/IgwEb',
credential: {
macKey: 'WmtzanB3ZW9peFhtdm42NzUzNG0=',
accessToken: 'AAwg3kPHWPfvk9bDFL936wYvkoctMADzQ5VhNDgeMR3+ZlZ35byg972fW8QjpEl7bx91YLBPFsIhsxloWcXPhA=='
},
credentialType: 'oauth'}
];
RTCIceTransportPolicy
EnumAs described in [JSEP] (section 4.1.1.), if the
iceTransportPolicy
member of
the RTCConfiguration
is specified, it defines the
ICE candidate policy
[JSEP] (section 3.5.3.) the browser uses to surface the permitted candidates
to the application; only these candidates will be used for connectivity
checks.
enum RTCIceTransportPolicy
{
"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
RTCIceCandidate. .
|
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.
enum RTCBundlePolicy
{
"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 RtcpMuxPolicy affects what ICE candidates are gathered to support non-multiplexed RTCP.
enum RTCRtcpMuxPolicy
{
// At risk due to lack of implementers' interest.
"negotiate",
"require"
};
Enumeration description (non-normative) | |
---|---|
negotiate |
Gather ICE candidates for both RTP and RTCP candidates. If
the remote-endpoint is capable of multiplexing RTCP, multiplex
RTCP on the RTP candidates. If it is not, use both the RTP and
RTCP candidates separately. Note that, as stated in [JSEP] (section 4.1.1.), the user agent
MAY not implement non-multiplexed RTCP, in which case it will
reject attempts to construct an RTCPeerConnection with the
negotiate policy. |
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. |
Aspects of this specification supporting non-multiplexed RTP/RTCP are marked as features at risk, since there is no clear commitment from implementers. This includes:
negotiate
, since there is no clear commitment
from implementers for the behavior associated with this.rtcpTransport
attribute within the
RTCRtpSender
and RTCRtpReceiver
.These dictionaries describe the options that can be used to control the offer/answer creation process.
dictionary RTCOfferAnswerOptions
{
boolean voiceActivityDetection
= true;
};
RTCOfferAnswerOptions
MembersvoiceActivityDetection
of type
boolean, defaulting to
true
Many codecs and systems are capable of detecting "silence" and changing their behavior in this case by doing things such as not transmitting any media. In many cases, such as when dealing with emergency calling or sounds other than spoken voice, it is desirable to be able to turn off this behavior. This option allows the application to provide information about whether it wishes this type of processing enabled or disabled.
dictionary RTCOfferOptions
: RTCOfferAnswerOptions
{
boolean iceRestart
= false;
};
RTCOfferOptions
MembersiceRestart
of type boolean, defaulting to
false
When the value of this dictionary member is true, the
generated description will have ICE credentials that are
different from the current credentials (as visible in the
attribute's
SDP). Applying the generated description will restart ICE, as
described in section 9.1.1.1 of [ICE].localDescription
When the value of this dictionary member is false, and the
attribute has
valid ICE credentials, the generated description will have the
same ICE credentials as the current value from the
localDescription
attribute.localDescription
The RTCAnswerOptions
dictionary describe options specific to session description of type answer
(none in this version of the specification).
dictionary RTCAnswerOptions
: RTCOfferAnswerOptions
{
};
RTCSignalingState
Enumenum RTCSignalingState
{
"stable",
"have-local-offer",
"have-remote-offer",
"have-local-pranswer",
"have-remote-pranswer",
"closed"
};
Enumeration description | |
---|---|
stable |
There is no offeranswer 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 "offer" , has been successfully
applied. |
have-remote-offer |
A remote description, of type "offer" , has been
successfully applied. |
have-local-pranswer |
A remote description of type "offer" has been successfully
applied and a local description of type "pranswer" has been
successfully applied. |
have-remote-pranswer |
A local description of type "offer" has been successfully
applied and a remote description of type "pranswer" has been
successfully applied. |
closed |
The has been closed;
its [[IsClosed]] slot is true . |
An example set of transitions might be:
stable
have-local-offer
have-remote-pranswer
stable
stable
have-remote-offer
have-local-pranswer
stable
RTCIceGatheringState
Enumenum RTCIceGatheringState
{
"new",
"gathering",
"complete"
};
Enumeration description | |
---|---|
new |
Any of the s are in the
"new" gathering state and none of the transports are
in the "gathering" state, or there are no
transports. |
gathering |
Any of the s are in the
"gathering" state. |
complete |
At least one exists,
and all s are in the
"completed" gathering state. |
RTCPeerConnectionState
Enumenum RTCPeerConnectionState
{
"new",
"connecting",
"connected",
"disconnected",
"failed",
"closed"
};
Enumeration description | |
---|---|
new |
Any of the s or
s are in the
"new" state and none of the transports are in the
"connecting" , "checking" ,
"failed" or "disconnected" state, or all
transports are in the "closed" state, or there are
no transports. |
connecting |
Any of the s or
s are in the
"connecting" or "checking" state and none
of them is in the "failed" state. |
connected |
All s and
s are in the
"connected" , "completed" or
"closed" state and at least one of them is in the
"connected" or "completed" state. |
disconnected |
Any of the s or
s are in the
"disconnected" state and none of them are in the
"failed" or "connecting" or
"checking" state. |
failed |
Any of the s or
s are in a
"failed" state. |
closed |
The object's
[[IsClosed]] slot is true .
|
RTCIceConnectionState
Enumenum RTCIceConnectionState
{
"new",
"checking",
"connected",
"completed",
"disconnected",
"failed",
"closed"
};
Enumeration description | |
---|---|
new |
Any of the s are in the
"new" state and none of them are in the
"checking" , "disconnected" or
"failed" state, or all
s are in the
"closed" state, or there are no transports. |
checking |
Any of the s are in the
"checking" state and none of them are in the
"disconnected" or "failed" state. |
connected |
All s are in the
"connected" , "completed" or
"closed" state and at least one of them is in the
"connected" state. |
completed |
All s are in the
"completed" or "closed" state and at
least one of them is in the "completed" state. |
disconnected |
Any of the s are in the
"disconnected" state and none of them are in the
"failed" state. |
failed |
Any of the s are in the
"failed" state. |
closed |
The object's
[[IsClosed]] slot is true .
|
Note that if an
is discarded as
a result of signaling (e.g. RTCP mux or bundling), or created as a
result of signaling (e.g. adding a new media description), the
state may advance directly from one state to another.RTCIceTransport
The [JSEP] specification, as a whole, describes the details of how
the
operates. References to
specific subsections of [JSEP] are provided as appropriate.RTCPeerConnection
Calling new
creates an RTCPeerConnection
(configuration)
object.RTCPeerConnection
configuration.servers
contains information
used to find and access the servers used by ICE. The application can
supply multiple servers of each type, and any TURN server MAY also be
used as a STUN server for the purposes of gathering server reflexive
candidates.
An
object has a signaling
state, a connection state, an ICE gathering
state, and an ICE connection state. These are
initialized when the object is created.RTCPeerConnection
The ICE protocol implementation of
an
is represented by an ICE
agent [ICE]. Certain RTCPeerConnection
methods involve interactions with the ICE Agent, namely
RTCPeerConnection
, addIceCandidate
,
setConfiguration
,
setLocalDescription
and setRemoteDescription
.
These interactions are described in the relevant sections in this
document and in [JSEP]. The ICE Agent also provides
indications to the user agent when the state of its internal
representation of an close
changes, as
described in 5.6 RTCIceTransport Interface.RTCIceTransport
The task source for the tasks listed in this section is the networking task source.
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" field set to an appropriate description.
Let connection be a newly created
object.RTCPeerConnection
If the certificates
value in
configuration is non-empty, check that
the expires
on each value is in the future. If a
certificate has expired or a the [[Origin]] internal slot of
the certificate does not match the current origin, throw an
InvalidAccessError
; otherwise, store the certificates.
If no certificates
value was specified, one or more
new RTCCertificate
instances are generated for use
with this RTCPeerConnection
instance. This MAY happen
asynchronously and the value of certificates
remains
undefined for the subsequent steps.
If configuration.
is
rtcpMuxPolicy
"negotiate"
, and the user agent does not implement
non-muxed RTCP, throw a NotSupportedError
.
Initialize connection's ICE Agent.
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 queue, initialized to an empty list.
Let connection have an [[LastOffer]] internal slot, initialized to "".
Let connection have an [[LastAnswer]] internal slot, initialized to "".
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
.
Return connection.
An
object has an
operations queue, [[Operations]], which ensures that
only one asynchronous operation in the queue is executed concurrently.
If subsequent calls are made while the returned promise of a previous
call is still not settled, they are added to the queue and executed
when all the previous calls have finished executing and their promises
have settled.RTCPeerConnection
To enqueue an operation to an
object's operation queue, run
the following steps:RTCPeerConnection
Let connection be the
object.RTCPeerConnection
If connection's [[IsClosed]] slot is
true
, return a promise rejected with a newly
created
InvalidStateError
.
Let operation be the operation to be enqueued.
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's [[IsClosed]] slot 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's [[IsClosed]] slot 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]].
Return p.
An
object has an aggregated
connection state. Whenever the state of an
RTCPeerConnection
or
RTCDtlsTransport
changes or when the
[[IsClosed]] slot turns RTCIceTransport
true
, the user agent MUST
update the connection state by queueing a task that runs the
following steps:
Let connection be this
object.RTCPeerConnection
Let newState be the value of deriving a new state
value as described by the
enum.RTCPeerConnectionState
If connection's connection state is equal to newState, abort these steps.
Let connection's connection state be newState.
Fire a simple event named
at
connection.connectionstatechange
To update the ICE gathering
state of an
instance
connection, the user agent MUST queue a task that runs the
following steps:RTCPeerConnection
If connection's [[IsClosed]] slot is
true
, abort these steps.
Let newState be the value of deriving a new state
value as described by the
enum.RTCIceGatheringState
If connection's ICE gathering state is equal to newState, abort these steps.
Set connection's ice gathering state to newState.
Fire a simple event named
at
connection.icegatheringstatechange
If newState is "completed"
, fire an ice candidate event
named
with icecandidate
null
at
connection.
RTCIceTransport
and/or
RTCPeerConnection
.To update the ICE
connection state of an
instance connection, the user agent MUST queue a task that
runs the following steps:RTCPeerConnection
If connection's [[IsClosed]] slot is
true
, abort these steps.
Let newState be the value of deriving a new state
value as described by the
enum.RTCIceConnectionState
If connection's ICE connection state is equal to newState, abort these steps.
Set connection's ice connection state to newState.
Fire a simple event named
at
connection.iceconnectionstatechange
To set an RTCSessionDescription
description on an
object connection, enqueue the following steps to
connection's operation queue:RTCPeerConnection
Let p be a new promise.
In parallel, start the process to apply description as described in [JSEP] (section 5.5. and section 5.6.).
If the process to apply description fails for any reason, then user agent MUST queue a task that runs the following steps:
If connection's [[IsClosed]] slot is
true
, then abort these steps.
If the description's
is invalid for the
current signaling state of connection
as described in [JSEP] (section 5.5. and section 5.6.),
then reject p with a newly
created
type
InvalidStateError
and abort these steps.
description.type
is
offer
and description.sdp
is not equal to connection's [[LastOffer]] slot,
then reject p with a newly created
InvalidModificationError
and abort these steps.
If description is set as a local description,
if description.type
is "rollback"
and signaling state is "stable"
then reject p with a newly created
InvalidStateError
and abort these steps.
description.type
is
"answer"
or "pranswer"
and
description.sdp
is not equal
to connection's [[LastAnswer]] slot,
then reject p with a newly created
InvalidModificationError
and abort these steps.
If the content of description is not
valid SDP syntax, then reject p with an
RTCError
(with errorDetail
set to "sdp-syntax-error" and the sdpLineNumber
attribute set to the line number in the SDP where
the syntax error was detected) 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's [[IsClosed]] slot is
true
, then abort these steps.
If description is set as a local description, then run one of the following steps:
If description is of type "offer"
, set
connection.[[PendingLocalDescription]]
to a new
object
constructed from description, and set
signaling state to RTCSessionDescription
"have-local-offer"
.
If description is of type "answer"
, then
this completes an offer answer negotiation. Set
connection.[[CurrentLocalDescription]]
to a new
object
constructed from description, and set
connection.[[CurrentRemoteDescription]]
to connection.[[PendingRemoteDescription]].
Set both connection.[[PendingRemoteDescription]]
and connection.[[PendingLocalDescription]]
to RTCSessionDescription
null
. Finally set connection's
signaling state to "stable"
.
If description is of type "rollback"
,
then this is a rollback. Set
connection.[[PendingLocalDescription]]
to null
, and set signaling state to
"stable"
.
If description is of type "pranswer"
,
then set connection.[[PendingLocalDescription]]
to a new
object
constructed from description, and set signaling state
to RTCSessionDescription
"have-local-pranswer"
.
Otherwise, if description is set as a remote description, then run one of the following steps:
If description is set as a remote description,
if description.type
is "rollback"
and signaling state is "stable"
then reject p with a newly created
InvalidStateError
and abort these steps.
If description is of type "offer"
, set
connection.[[PendingRemoteDescription]]
attribute to a new
object constructed from description, and set
signaling state to RTCSessionDescription
"have-remote-offer"
.
If description is of type "answer"
, then
this completes an offer answer negotiation. Set
connection.[[CurrentRemoteDescription]]
to a new
object
constructed from description, and set
connection.[[CurrentLocalDescription]]
to connection.[[PendingLocalDescription]].
Set both connection.[[PendingRemoteDescription]]
and connection.[[PendingLocalDescription]]
to RTCSessionDescription
null
. Finally set connection's
signaling state to "stable"
.
If description is of type "rollback"
,
then this is a rollback. Set
connection.[[PendingRemoteDescription]]
to null
, and set signaling state to
"stable"
.
If description is of type "pranswer"
,
then set connection.[[PendingRemoteDescription]]
to a new
object
constructed from description and
signaling state to RTCSessionDescription
"have-remote-pranswer"
.
If description is of type "answer"
, and it
initiates the closure of an existing SCTP association, as
defined in [SCTP-SDP], Sections 10.3 and 10.4, set the
value of connection's
[[SctpTransport]] internal slot to
null
.
If description is of type "answer"
or
"pranswer"
, then run the following steps:
If description initiates the
establishment of a new SCTP association, as defined in
[SCTP-SDP], Sections 10.3 and 10.4, create an
RTCSctpTransport with an initial state of
"connecting"
and assign the result to the
[[SctpTransport]] slot.
Otherwise, if an SCTP association is established, but the "max-message-size" SDP attribute is updated, update the data max message size of connection's [[SctpTransport]].
If description negotiates the DTLS role
of the SCTP transport, and there is an
with a RTCDataChannel
null
,
then generate an ID according to
[RTCWEB-DATA-PROTOCOL]. If no available ID could be
generated, then run the following steps:id
Let channel be the
object for which
an ID could not be generated.RTCDataChannel
Set channel's [[ReadyState]] slot
to "closed"
.
Fire an event named
with an
error
OperationError
exception at
channel.
Fire a simple event named
at
channel.close
Let trackEvents, muteTracks, addList, and removeList be empty lists.
If description is set as a local description, then run the following steps:
Run the following steps for each media description in description:
If the media description is not yet associated
with an
object then run
the following steps:RTCRtpTransceiver
Let transceiver be the
used to create the
media description.RTCRtpTransceiver
Set transceiver's
value to the mid of
the media description.mid
If transceiver's [[Stopped]] slot
is true
, abort these sub steps.
If the media description is indicated as using
an existing media transport according to
[BUNDLE], let transport and
rtcpTransport be the
objects
representing the RTP and RTCP components of that
transport, respectively.
RTCDtlsTransport
Otherwise, let transport and
rtcpTransport be newly created
objects, each
with a new underlying
RTCDtlsTransport
. Though if RTCP
multiplexing is negotiated according to [RFC5761],
or if connection's
RTCIceTransport
is RTCRtcpMuxPolicy
,
do not create any RTCP-specific transport objects,
and instead let rtcpTransport equal
transport.
require
Set transceiver.[[Sender]].[[SenderTransport]] to transport.
Set transceiver.[[Sender]].[[SenderRtcpTransport]] to rtcpTransport.
Set transceiver.[[Receiver]].[[ReceiverTransport]] to transport.
Set transceiver.[[Receiver]].[[ReceiverRtcpTransport]] to rtcpTransport.
Let transceiver be the
associated with the
media description.RTCRtpTransceiver
If transceiver's [[Stopped]] slot
is true
, abort these sub steps.
Let direction be an
value
representing the direction from the media
description.RTCRtpTransceiverDirection
If direction is "sendrecv"
or
"recvonly"
,
set transceiver's [[Receptive]] slot
to true
, otherwise set it to false
.
If description is of type
"answer"
or "pranswer"
,
then run the following steps:
If direction is
"sendonly"
or "inactive"
,
and transceiver's
[[FiredDirection]] slot is either
"sendrecv"
or "recvonly"
,
process the removal of a remote track for
the media description, given transceiver,
removeList, and muteTracks.
Set transceiver's [[CurrentDirection]] and [[FiredDirection]] slots to direction.
If description is set as a remote description, then run the following steps:
Run the following steps for each media description in description:
Let direction be an
value
representing the direction from the media
description, but with the send and receive
directions reversed to represent this peer's point
of view.RTCRtpTransceiverDirection
As described by [JSEP] (section 5.10.), attempt to
find an existing
object, transceiver, to represent the media
description.RTCRtpTransceiver
If no suitable transceiver is found (transceiver is unset), run the following steps:
Create an RTCRtpSender, sender, from the media description.
Create an RTCRtpReceiver, receiver, from the media description.
Create an RTCRtpTransceiver with
sender, receiver and
an
value of RTCRtpTransceiverDirection
"recvonly"
, and let
transceiver be the result.
Set transceiver's
value to the mid of
the corresponding media description. If the media
description has no MID, and transceiver's
mid
is unset, generate a random value as
described in [JSEP] (section 5.10.).mid
If direction is "sendrecv"
or
"recvonly"
, and
transceiver's
[[FiredDirection]] slot
is neither "sendrecv"
nor "recvonly"
,
process the addition of a remote track for
the media description, given transceiver,
addList, and trackEvents.
If direction is "sendonly"
or
"inactive"
,
set transceiver's [[Receptive]] slot
to false
.
If direction is
"sendonly"
or "inactive"
, and
transceiver's
[[FiredDirection]] slot
is either "sendrecv"
or "recvonly"
,
process the removal of a remote track for
the media description, given transceiver,
removeList, and muteTracks.
Set transceiver's [[FiredDirection]] slot to direction.
If description is of type
"answer"
or "pranswer"
, then run
the following steps:
Set transceiver's [[CurrentDirection]] slot to direction.
Let transport and rtcpTransport be the
objects representing the RTP
and RTCP components of the media transport used by
transceiver's associated media description,
according to [BUNDLE].
RTCDtlsTransport
Set transceiver.[[Sender]].[[SenderTransport]] to transport.
Set transceiver.[[Sender]].[[SenderRtcpTransport]] to rtcpTransport.
Set transceiver.[[Receiver]].[[ReceiverTransport]] to transport.
Set transceiver.[[Receiver]].[[ReceiverRtcpTransport]] to rtcpTransport.
If the media description is rejected, and transceiver is not already stopped, stop the RTCRtpTransceiver transceiver.
If description is of type "rollback"
, then run
the following steps:
If the
value of an
mid
was set to a
non-null value by the
RTCRtpTransceiver
that is being
rolled back, set the RTCSessionDescription
value of that
transceiver to null, as described by [JSEP] (section 4.1.8.2.).mid
If an
was
created by applying the
RTCRtpTransceiver
that is
being rolled back, and a track has not been attached to
it via RTCSessionDescription
addTrack
, remove that
transceiver from connection's set of transceivers, as
described by [JSEP] (section 4.1.8.2.).
RTCRtpTransceiver
s
remaining on connection, revert
any changes to the [[CurrentDirection]] and
[[Receptive]] internal slots made by the application
of the RTCSessionDescription
that is being rolled back.
Restore the value of connection's
[[SctpTransport]] internal slot to
its value at the last stable
signaling state.
If connection's signaling state
changed above, fire a simple event named
at
connection.signalingstatechange
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
trackEvent in trackEvents,
fire a track event named RTCTrackEvent
with trackEvent
at the connection object.track
If connection's signaling state is now
"stable"
, update the negotiation-needed
flag. If connection's
[[NegotiationNeeded]] slot was true
both
before and after this update, queue a task that runs the
following steps:
If connection's [[IsClosed]] slot
is true
, abort these steps.
If connection's [[NegotiationNeeded]]
slot is false
, abort these steps.
Fire a simple event named negotiationneeded
at connection.
Resolve p with undefined.
Return p.
To set a configuration, run the following steps:
RTCConfiguration
dictionary to be
processed.RTCPeerConnection
object.configuration.peerIdentity
is
set and its value differs from the target peer
identity, throw an InvalidModificationError
.
configuration.certificates
is
set and the set of certificates differs from the ones used
when connection was constructed, throw an
InvalidModificationError
.configuration.bundlePolicy
differs from the
connection's bundle policy, throw
an InvalidModificationError
.configuration.rtcpMuxPolicy
differs from the
connection's rtcpMux policy, throw an
InvalidModificationError
.configuration.iceCandidatePoolSize
differs from
the connection's previously set
iceCandidatePoolSize
, and setLocalDescription
has
already been called, throw an
InvalidModificationError
.Set the ICE Agent's ICE transports setting to
the value of configuration.
. As defined
in [JSEP] (section 4.1.16.), if
the new ICE transports setting changes the existing
setting, no action will be taken until the next gathering
phase. If a script wants this to happen immediately, it
should do an ICE restart.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.
. If the
new ICE candidate pool size changes the existing
setting, this may result in immediate gathering of new
pooled candidates, or discarding of existing pooled
candidates, as defined in [JSEP] (section 4.1.16.).iceCandidatePoolSize
Let validatedServers be an empty list.
If configuration.
is defined, then
run the following steps for each element:iceServers
Let server be the current list element.
If server.urls
is a string,
let server.urls
be a list
consisting of just that string.
For each url in
server.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
[RFC7064] fails, throw a
SyntaxError
. If scheme
name is stun
or
stuns
, and parsing the
url using the syntax defined in
[RFC7065] fails, throw a
SyntaxError
.
If scheme name is turn
or
turns
, and either of
server.username
or
server.credential
are omitted,
then throw an InvalidAccessError
.
If scheme name is turn
or
turns
, and
server.credentialType
is
"password"
, and
server.credential
is not a
DOMString, then
throw an InvalidAccessError
.
If scheme name is turn
or
turns
, and
server.credentialType
is
"oauth"
, and
server.credential
is not an
RTCOAuthCredential
, then throw an
InvalidAccessError
.
Append server to validatedServers.
Let validatedServers be the ICE Agent's ICE servers list.
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 the configuration in the [[Configuration]] internal slot.
The
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 RTCPeerConnection
objects.MediaStreamTrack
[Constructor(optional RTCConfiguration
configuration),
Exposed=Window]
interface RTCPeerConnection
: EventTarget {
Promise<RTCSessionDescriptionInit
> createOffer
(optional RTCOfferOptions
options);
Promise<RTCSessionDescriptionInit
> createAnswer
(optional RTCAnswerOptions
options);
Promise<void> setLocalDescription
(RTCSessionDescriptionInit
description);
readonly attribute RTCSessionDescription
? localDescription
;
readonly attribute RTCSessionDescription
? currentLocalDescription
;
readonly attribute RTCSessionDescription
? pendingLocalDescription
;
Promise<void> setRemoteDescription
(RTCSessionDescriptionInit
description);
readonly attribute RTCSessionDescription
? remoteDescription
;
readonly attribute RTCSessionDescription
? currentRemoteDescription
;
readonly attribute RTCSessionDescription
? pendingRemoteDescription
;
Promise<void> addIceCandidate
((RTCIceCandidateInit
or RTCIceCandidate
) candidate);
readonly attribute RTCSignalingState
signalingState
;
readonly attribute RTCIceGatheringState
iceGatheringState
;
readonly attribute RTCIceConnectionState
iceConnectionState
;
readonly attribute RTCPeerConnectionState
connectionState
;
readonly attribute boolean? canTrickleIceCandidates
;
static sequence<RTCIceServer
> getDefaultIceServers
();
RTCConfiguration
getConfiguration
();
void setConfiguration
(RTCConfiguration
configuration);
void close
();
attribute EventHandler onnegotiationneeded
;
attribute EventHandler onicecandidate
;
attribute EventHandler onicecandidateerror
;
attribute EventHandler onsignalingstatechange
;
attribute EventHandler oniceconnectionstatechange
;
attribute EventHandler onicegatheringstatechange
;
attribute EventHandler onconnectionstatechange
;
};
RTCPeerConnection
RTCPeerConnection
constructor algorithm
.
localDescription
of type RTCSessionDescription
, readonly,
nullableThe localDescription
attribute MUST return [[PendingLocalDescription]] if it is
not null and otherwise it MUST return
[[CurrentLocalDescription]].
Note that [[CurrentLocalDescription]].sdp and
[[PendingLocalDescription]].sdp need not be
string-wise identical to the SDP value passed to the corresponding
call (i.e. SDP
may be parsed and reformatted, and ICE candidates may be
added).setLocalDescription
currentLocalDescription
of type RTCSessionDescription
, readonly,
nullableThe currentLocalDescription
attribute MUST return [[CurrentLocalDescription]].
It represents the local description that was successfully
negotiated the last time the RTCPeerConnection
transitioned into the stable state plus any local candidates
that have been generated by the ICE Agent since the offer
or answer was created.
pendingLocalDescription
of type RTCSessionDescription
, readonly,
nullableThe pendingLocalDescription
attribute MUST return [[PendingLocalDescription]].
It represents a local description that is in the
process of being negotiated plus any local candidates that have
been generated by the ICE Agent since the offer or
answer was created. If the RTCPeerConnection
is in
the stable state, the value is null
.
remoteDescription
of type RTCSessionDescription
, readonly,
nullableThe remoteDescription
attribute MUST return [[PendingRemoteDescription]] if it
is not null
and otherwise it MUST return
[[CurrentRemoteDescription]].
Note that [[CurrentRemoteDescription]].sdp and
[[PendingRemoteDescription]].sdp need not be
string-wise identical to the SDP value passed to the corresponding
call (i.e. SDP
may be parsed and reformatted, and ICE candidates may be
added).setRemoteDescription
currentRemoteDescription
of type RTCSessionDescription
, readonly,
nullableThe currentRemoteDescription
attribute MUST return [[CurrentRemoteDescription]].
It represents the last remote description that was successfully
negotiated the last time the RTCPeerConnection
transitioned into the stable state plus any remote candidates
that have been supplied via addIceCandidate()
since the
offer or answer was created.
pendingRemoteDescription
of type RTCSessionDescription
, readonly,
nullableThe pendingRemoteDescription
attribute MUST return [[PendingRemoteDescription]].
It represents a remote description that is in the
process of being negotiated, complete with any remote
candidates that have been supplied via addIceCandidate()
since the
offer or answer was created. If the
RTCPeerConnection
is in the stable state, the
value is null
.
signalingState
of type RTCSignalingState
, readonlyThe signalingState
attribute MUST return the
object's
signaling state.RTCPeerConnection
iceGatheringState
of type RTCIceGatheringState
, readonlyThe iceGatheringState
attribute MUST return the ICE gathering state of the
RTCPeerConnection
instance.
iceConnectionState
of type RTCIceConnectionState
, readonlyThe iceConnectionState
attribute MUST return the ICE connection state of the
RTCPeerConnection
instance.
connectionState
of type RTCPeerConnectionState
, readonlyThe connectionState
attribute MUST return the connection state of the
instance.RTCPeerConnection
canTrickleIceCandidates
of type boolean, readonly, nullableThe canTrickleIceCandidates
attribute indicates whether the remote peer is able to accept
trickled ICE candidates [TRICKLE-ICE]. The value is
determined based on whether a remote description indicates
support for trickle ICE, as defined in [JSEP] (section 4.1.15.). Prior to the completion of
, this
value is setRemoteDescription
null
.
onnegotiationneeded
of type
EventHandlernegotiationneeded
.onicecandidate
of type EventHandlericecandidate
.onicecandidateerror
of type
EventHandlericecandidateerror
.onsignalingstatechange
of type
EventHandlersignalingstatechange
.oniceconnectionstatechange
of type
EventHandlericeconnectionstatechange
onicegatheringstatechange
of type
EventHandlericegatheringstatechange
.onconnectionstatechange
of type
EventHandlerconnectionstatechange
.createOffer
The createOffer
method generates a blob of SDP that contains
an RFC 3264 offer with the supported configurations for the
session, including descriptions of the local
MediaStreamTrack
s attached to this
RTCPeerConnection
, the codec/RTP/RTCP capabilities
supported by this implementation, and parameters of the ICE
agent and the DTLS connection. The options
parameter may be supplied to provide additional control over
the offer generated.
If a system has limited resources (e.g. a finite number of
decoders), createOffer
needs to return an offer
that reflects the current state of the system, so that
setLocalDescription
will succeed when it attempts
to acquire those resources. The session descriptions MUST
remain usable by setLocalDescription
without
causing an error until at least the end of the fulfillment
callback of the returned promise.
Creating the SDP MUST follow the appropriate process for
generating an offer described in [JSEP].
As an offer, the generated SDP will contain the full set of
codec/RTP/RTCP capabilities supported by the session (as
opposed to an answer, which will include only a specific
negotiated subset to use). In the event
createOffer
is called after the session is
established, createOffer
will generate an offer
that is compatible with the current session, incorporating any
changes that have been made to the session since the last
complete offer-answer exchange, such as addition or removal of
tracks. If no changes have been made, the offer will include
the capabilities of the current local description as well as
any additional capabilities that could be negotiated in an
updated offer.
The generated SDP will also contain the ICE agent's
usernameFragment
,
password
and
ICE options (as defined in [ICE], Section 14) and may also contain
any local candidates that have been gathered by the agent.
The certificates
value in configuration
for the RTCPeerConnection
provides the
certificates configured by the application for the
RTCPeerConnection
. These certificates,
along with any default certificates are used to produce a set of
certificate fingerprints. These certificate fingerprints are
used in the construction of SDP and as input to requests for
identity assertions.
If the RTCPeerConnection
is configured to
generate Identity assertions by calling
, then the session description
SHALL contain an appropriate assertion.setIdentityProvider
The process of generating an SDP exposes a
subset of the media capabilities of the underlying system,
which provides generally persistent cross-origin information on
the device. It thus increases the fingerprinting surface of the
application. In privacy-sensitive contexts, browsers can
consider mitigations such as generating SDP matching only a
common subset of the capabilities.
When the method is called, the user agent MUST run the following steps:
Let connection be the
object on which the
method was invoked.RTCPeerConnection
If connection's [[IsClosed]] slot is
true
, return a promise rejected with a newly
created
InvalidStateError
.
If connection is configured with an identity provider, then begin the identity assertion request process if it has not already begun.
Return the result of enqueuing the following steps to connection's operation queue:
Let p be a new promise.
In parallel, begin the steps to create an offer, given p.
Return p.
The steps to create an offer given 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.
Let provider be connection's
currently configured identity provider if one has been
configured, or null
otherwise.
If provider is non-null, wait for the identity assertion request process to complete.
If provider was unable to produce an
identity assertion, reject p with a newly
created
NotReadableError
and abort these steps.
Inspect the 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 p.
The final steps to create an offer given a promise p are as follows:
If connection's [[IsClosed]] slot is
true
, then abort these steps.
If connection was modified in such a way that additional inspection of the system state is necessary, or if its configured indentity provider is no longer provider, then in parallel begin the steps to create an offer again, given p, and abort these steps.
createOffer
was called when only an audio
RTCRtpTransceiver
was added to
connection, but while performing the steps
to create an offer in parallel, a video
RTCRtpTransceiver
was added,
requiring additional inspection of video system
resources.
Given the information that was obtained from previous
inspection, the current state of connection
and its
s, and the
identity assertion from provider (if non-null),
generate an SDP offer, sdpString, as described
in [JSEP] (section 5.2.).RTCRtpTransceiver
Let offer be a newly created
dictionary
with its RTCSessionDescriptionInit
type
member initialized to the string
"offer"
and its sdp
member
initialized to sdpString.
Set the [[LastOffer]] internal slot to sdpString.
Resolve p with offer.
createAnswer
The createAnswer
method generates an [SDP]
answer with the supported configuration for the session that is
compatible with the parameters in the remote configuration.
Like createOffer
, the returned blob of SDP contains
descriptions of the local MediaStreamTrack
s
attached to this RTCPeerConnection
, the
codec/RTP/RTCP options negotiated for this session, and any
candidates that have been gathered by the ICE Agent. The
options
parameter may be supplied to provide
additional control over the generated answer.
Like createOffer
, the
returned description SHOULD reflect the current state of the
system. The session descriptions MUST remain usable by
setLocalDescription
without causing an error until
at least the end of the fulfillment callback of the returned
promise.
As an answer, the generated SDP will contain a specific codec/RTP/RTCP configuration that, along with the corresponding offer, specifies how the media plane should be established. The generation of the SDP MUST follow the appropriate process for generating an answer described in [JSEP].
The generated SDP will also contain the ICE agent's
usernameFragment
,
password
and
ICE options (as defined in [ICE], Section 14) and may also contain
any local candidates that have been gathered by the agent.
The certificates
value in configuration
for the RTCPeerConnection
provides the
certificates configured by the application for the
RTCPeerConnection
. These certificates,
along with any default certificates are used to produce a set of
certificate fingerprints. These certificate fingerprints are
used in the construction of SDP and as input to requests for
identity assertions.
An answer can be marked as provisional, as described in
[JSEP] (section 4.1.8.1.),
by setting the
to
type
"pranswer"
.
If the RTCPeerConnection
is configured to
generate Identity assertions by calling
, then the session description SHALL
contain an appropriate assertion.setIdentityProvider
When the method is called, the user agent MUST run the following steps:
Let connection be the
object on which the
method was invoked.RTCPeerConnection
If connection's [[IsClosed]] slot is
true
, return a promise rejected with a newly
created
InvalidStateError
.
If connection is configured with an identity provider, then begin the identity assertion request process if it has not already begun.
Return the result of enqueuing the following steps to connection's operation queue:
If connection's signaling state
is neither "have-remote-offer"
nor
"have-local-pranswer"
, return a promise
rejected with a newly created
InvalidStateError
.
Let p be a new promise.
In parallel, begin the steps to create an answer, given p.
Return p.
The steps to create an answer given 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.
Let provider be connection's
currently configured identity provider if one has been
configured, or null
otherwise.
If provider is non-null, wait for the identity assertion request process to complete.
If provider was unable to produce an
identity assertion, reject p with a newly
created
NotReadableError
and abort these steps.
Inspect the 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's [[IsClosed]] slot is
true
, then abort these steps.
If connection was modified in such a way that additional inspection of the system state is necessary, or if its configured indentity provider is no longer provider, then in parallel begin the steps to create an answer again, given p, and abort these steps.
createAnswer
was called when an
RTCRtpTransceiver
's direction was
"recvonly"
, but while performing the steps to create
an answer in parallel, the direction was changed to
"sendrecv"
, requiring additional inspection of video
encoding resources.
Given the information that was obtained from previous
inspection and the current state of connection
and its
s, and the
identity assertion from provider (if non-null),
generate an SDP answer, sdpString, as described
in [JSEP] (section 5.3.).
RTCRtpTransceiver
Let answer be a newly created
dictionary
with its RTCSessionDescriptionInit
type
member initialized to the string
"answer"
and its sdp
member
initialized to sdpString.
Set the [[LastAnswer]] internal slot to sdpString.
Resolve p with answer.
setLocalDescription
The setLocalDescription
method instructs the
to
apply the supplied
RTCPeerConnection
as the local
description.RTCSessionDescriptionInit
This API changes the local media state. In order to
successfully handle scenarios where the application wants to
offer to change from one media format to a different,
incompatible format, the
MUST be able to simultaneously support use of both the current
and pending local descriptions (e.g. support codecs that exist
in both descriptions) until a final answer is received, at
which point the RTCPeerConnection
can fully
adopt the pending local description, or rollback to the current
description if the remote side rejected the change.RTCPeerConnection
As noted in [JSEP] (section 5.4.)
the SDP returned from createOffer
or
createAnswer
MUST NOT be changed
before passing it to setLocalDescription
. As
a result, when the method is invoked, the user agent MUST
run the following steps:
setLocalDescription
.description.sdp
is the
empty string and description.type
is "answer"
or "pranswer"
,
set description.sdp
to the value of
connection's [[LastAnswer]] slot.description.sdp
is the
empty string and description.type
is "offer"
, set description.sdp
to the value of connection's
[[LastOffer]] slot.description
.As noted in [JSEP] (section 5.9.), calling this method may trigger the ICE candidate gathering process by the ICE Agent.
setRemoteDescription
The setRemoteDescription
method instructs the
to
apply the supplied
RTCPeerConnection
as the remote
offer or answer. This API changes the local media state.RTCSessionDescriptionInit
When the method is invoked, the user agent MUST return the result of setting the RTCSessionDescription indicated by the method's first argument.
In addition, a remote description is processed to determine and verify the identity of the peer.
If an a=identity
attribute is present in the
session description, the browser validates the identity
assertion..
If the "peerIdentity" configuration is applied to the
, this establishes a
target peer identity of
the provided value. Alternatively, if the
RTCPeerConnection
has previously
authenticated the identity of the peer (that is, there is a
current value for RTCPeerConnection
), then this also
establishes a target peer identity.peerIdentity
The target peer identity cannot be changed once set.
Once set, if a different value is provided, the user agent MUST
reject the returned promise with a newly
created
InvalidModificationError
and abort this operation.
The
MUST be closed if the
validated peer identity does not match the target peer
identity.RTCPeerConnection
If there is no target peer identity, then
setRemoteDescription
does not await the completion
of identity validation.
addIceCandidate
The addIceCandidate
method provides a remote candidate to the ICE Agent.
This method can also be used to indicate the end of remote
candidates when called with an empty string for the
member. The only
members of the argument used by this method are candidate
, candidate
, sdpMid
, and
sdpMLineIndex
; the rest
are ignored. When the method is invoked, the user agent MUST
run the following steps:usernameFragment
Let candidate be the method's argument.
Let connection be the
object on which the
method was invoked.RTCPeerConnection
If both sdpMid and sdpMLineIndex are
null
, return a promise rejected with a newly
created
TypeError
.
Return the result of enqueuing the following steps to connection's operation queue:
If
is
remoteDescription
null
return a promise rejected with a newly
created
InvalidStateError
.
Let p be a new promise.
If candidate.sdpMid is not null, run the following steps:
If candidate.sdpMid is not equal to
the mid of any media description in
,
reject p with a newly
created remoteDescription
OperationError
and abort
these steps.
Else, if candidate.sdpMLineIndex is not null, run the following steps:
If candidate.sdpMLineIndex is equal
to or larger than the number of media descriptions
in
,
reject p with a newly
created remoteDescription
OperationError
and abort
these steps.
If candidate.usernameFragment
is neither
undefined
nor null
, and is not
equal to any username fragment present in the corresponding
media description of an applied remote
description, reject p with a newly
created
OperationError
and abort these steps.
In parallel, add the ICE candidate
candidate as described in [JSEP] (section 4.1.17.). Use
candidate.usernameFragment
to identify the
ICE generation; if usernameFragment
is null, process the
candidate for the most recent ICE
generation. If
candidate.candidate
is an empty
string, process candidate as an
end-of-candidates indication for the corresponding
media description and ICE candidate
generation.
If candidate could not be successfully added the user agent MUST queue a task that runs the following steps:
If connection's
[[IsClosed]] slot is true
,
then abort these steps.
Reject p with a
DOMException
object whose
name
attribute has the value
OperationError
and abort these
steps.
If candidate is applied successfully, the user agent MUST queue a task that runs the following steps:
If connection's
[[IsClosed]] slot 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 the connection.[[PendingRemoteDescription]].sdp.
If connection.[[CurrentRemoteDescription]]
is not null
, and represents the ICE generation
for which candidate was processed, add candidate
to the connection.[[CurrentRemoteDescription]].sdp.
Resolve p with
undefined
.
Return p.
getDefaultIceServers
Returns a list of ICE servers that are configured into the browser. A browser might be configured to use local or private STUN or TURN servers. This method allows an application to learn about these servers and optionally use them.
This list is likely to be persistent and
is the same across origins. It thus increases the
fingerprinting surface of the browser. In privacy-sensitive
contexts, browsers can consider mitigations such as only
providing this data to whitelisted origins (or not providing it
at all.)
Since the use of this information is left to the discretion of application developers, configuring a user agent with these defaults does not per se increase a user's ability to limit the exposure of their IP addresses.
getConfiguration
Returns an
object
representing the current configuration of this
RTCConfiguration
object.RTCPeerConnection
When this method is called, the user agent MUST return the
object stored in the
[[Configuration]] internal slot.RTCConfiguration
setConfiguration
The setConfiguration
method updates the
configuration of this
object. This includes changing the configuration of the ICE
Agent. As noted in [JSEP] (section 3.5.1.), when the ICE
configuration changes in a way that requires a new gathering
phase, an ICE restart is required.RTCPeerConnection
When the setConfiguration
method is
invoked, the user agent MUST run the following steps:
Let connection be the
on which the method
was invoked.RTCPeerConnection
If connection's [[IsClosed]] slot is
true
, throw an
InvalidStateError
.
Set the configuration specified by configuration.
close
When the close
method is invoked,
the user agent MUST run the following steps:
Let connection be the
object on which the
method was invoked.RTCPeerConnection
If connection's [[IsClosed]] slot is
true
, abort these steps.
Set connection's [[IsClosed]] slot to
true
.
Set connection's signaling state to
"closed"
.
Let transceivers be the result of executing the
CollectTransceivers
algorithm. For every
transceiver in
transceivers, run the following steps:RTCRtpTransceiver
If transceiver's [[Stopped]] slot
is true
, abort these steps.
Let sender be transceiver's [[Sender]].
Let receiver be transceiver's [[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.
Set the readyState
of
receiver's [[ReceiverTrack]] to
"ended"
.
Set transceiver's [[Stopped]] slot
to true
.
Set the [[ReadyState]] slot of each of
connection's
s
to RTCDataChannel
"closed"
RTCDataChannel
s
will be closed abruptly and the closing procedure
will not be invoked.If the connection's [[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
s
to RTCDtlsTransport
"closed"
.
Destroy connection's ICE Agent, abruptly ending any active ICE processing and releasing any relevant resources (e.g. TURN permissions).
Set the [[IceTransportState]] slot of each of
connection's
s
to RTCIceTransport
"closed"
.
Set connection's ICE connection state to
"closed"
.
Set connection's connection state to
"closed"
.
Supporting the methods in this section is optional. However, if these methods are supported it is mandatory to implement according to what is specified here.
RTCPeerConnection
is easy to polyfill as:
RTCPeerConnection.prototype.addStream = function(stream) {
stream.getTracks().forEach((track) => this.addTrack(track, stream));
};
partial interface RTCPeerConnection
{
Promise<void> createOffer
(RTCSessionDescriptionCallback
successCallback,
RTCPeerConnectionErrorCallback
failureCallback,
optional RTCOfferOptions
options);
Promise<void> setLocalDescription
(RTCSessionDescriptionInit
description,
VoidFunction successCallback,
RTCPeerConnectionErrorCallback
failureCallback);
Promise<void> createAnswer
(RTCSessionDescriptionCallback
successCallback,
RTCPeerConnectionErrorCallback
failureCallback);
Promise<void> setRemoteDescription
(RTCSessionDescriptionInit
description,
VoidFunction successCallback,
RTCPeerConnectionErrorCallback
failureCallback);
Promise<void> addIceCandidate
((RTCIceCandidateInit
or RTCIceCandidate
) candidate,
VoidFunction successCallback,
RTCPeerConnectionErrorCallback
failureCallback);
};
createOffer
When the createOffer
method is called, the user
agent MUST run the following steps:
Let successCallback be the method's first argument.
Let failureCallback be the callback indicated by the method's second argument.
Let options be the callback indicated by the method's third argument.
Run the steps specified by
's createOffer() method with
options as the sole argument, and let
p be the resulting promise.RTCPeerConnection
Upon fulfillment of p with value offer, invoke successCallback with offer as the argument.
Upon rejection of p with reason r, invoke failureCallback with r as the argument.
Return a promise resolved with
undefined
.
setLocalDescription
When the setLocalDescription
method is called,
the user agent MUST run the following steps:
Let description be the method's first argument.
Let successCallback be the callback indicated by the method's second argument.
Let failureCallback be the callback indicated by the method's third argument.
Run the steps specified by
's RTCPeerConnection
setLocalDescription
method with
description as the sole argument, and let
p be the resulting promise.
Upon fulfillment of p, invoke
successCallback with undefined
as
the argument.
Upon rejection of p with reason r, invoke failureCallback with r as the argument.
Return a promise resolved with
undefined
.
createAnswer
createAnswer
method
does not take an RTCAnswerOptions
parameter, since no known legacy createAnswer
implementation ever supported it.When the createAnswer
method is called, the
user agent MUST run the following steps:
Let successCallback be the method's first argument.
Let failureCallback be the callback indicated by the method's second argument.
Run the steps specified by
's createAnswer() method with no
arguments, and let p be the resulting
promise.RTCPeerConnection
Upon fulfillment of p with value answer, invoke successCallback with answer as the argument.
Upon rejection of p with reason r, invoke failureCallback with r as the argument.
Return a promise resolved with
undefined
.
setRemoteDescription
When the setRemoteDescription
method is called,
the user agent MUST run the following steps:
Let description be the method's first argument.
Let successCallback be the callback indicated by the method's second argument.
Let failureCallback be the callback indicated by the method's third argument.
Run the steps specified by
's RTCPeerConnection
setRemoteDescription
method with
description as the sole argument, and let
p be the resulting promise.
Upon fulfillment of p, invoke
successCallback with undefined
as
the argument.
Upon rejection of p with reason r, invoke failureCallback with r as the argument.
Return a promise resolved with
undefined
.
addIceCandidate
When the addIceCandidate
method is called, the
user agent MUST run the following steps:
Let candidate be the method's first argument.
Let successCallback be the callback indicated by the method's second argument.
Let failureCallback be the callback indicated by the method's third argument.
Run the steps specified by
's addIceCandidate() method with
candidate as the sole argument, and let
p be the resulting promise.RTCPeerConnection
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.
RTCPeerConnectionErrorCallback
callback RTCPeerConnectionErrorCallback
= void (DOMException error);
RTCPeerConnectionErrorCallback
Parameterserror
of type DOMExceptionRTCSessionDescriptionCallback
callback RTCSessionDescriptionCallback
= void (RTCSessionDescriptionInit
description);
RTCSessionDescriptionCallback
Parametersdescription
of type RTCSessionDescriptionInit
This section describes a set of legacy extensions that may be used to
influence how an offer is created, in addition to the media added to
the
. Developers are encouraged to
use the RTCPeerConnection
API instead.RTCRtpTransceiver
When createOffer is called with any of the legacy options specified in this section, run the followings steps instead of the regular createOffer steps:
Let options be the methods first argument.
Let connection be the current
object.RTCPeerConnection
For each "offerToReceive<Kind>" member in options with kind, kind, run the following steps:
If the value of the dictionary member is false,
For each non-stopped "sendrecv" transceiver of transceiver kind kind, set transceiver's [[Direction]] slot to "sendonly".
For each non-stopped "recvonly" transceiver of transceiver kind kind, set transceiver's [[Direction]] slot to "inactive".
Continue with the next option, if any.
If connection has any non-stopped "sendrecv" or "recvonly" transceivers of transceiver kind kind, continue with the next option, if any.
Let transceiver be the result of invoking the
equivalent of
connection.addTransceiver(kind)
, except
that this operation MUST NOT update the
negotiation-needed flag.
If transceiver is unset because the previous operation threw an error, abort these steps.
Set transceiver's [[Direction]] slot to "recvonly".
Run the steps specified by createOffer to create the offer.
partial dictionary RTCOfferOptions
{
boolean offerToReceiveAudio
;
boolean offerToReceiveVideo
;
};
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
object MUST not be garbage
collected as long as any event can cause an event handler to be
triggered on the object. When the object's [[IsClosed]] internal
slot is RTCPeerConnection
true
, no such event handler can be triggered and
it is therefore safe to garbage collect the object.
All
and
RTCDataChannel
objects that are connected to an
MediaStreamTrack
have a strong reference to the
RTCPeerConnection
object.RTCPeerConnection
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.
RTCSdpType
The RTCSdpType enum describes the type of an
or
RTCSessionDescriptionInit
instance.RTCSessionDescription
enum RTCSdpType
{
"offer",
"pranswer",
"answer",
"rollback"
};
Enumeration description | |
---|---|
offer |
An |
pranswer |
An |
answer |
An |
rollback |
An |
RTCSessionDescription
ClassThe RTCSessionDescription
class is used by
to expose local and remote
session descriptions.RTCPeerConnection
[Constructor(RTCSessionDescriptionInit
descriptionInitDict),
Exposed=Window]
interface RTCSessionDescription
{
readonly attribute RTCSdpType
type
;
readonly attribute DOMString sdp
;
[Default] object toJSON();
};
RTCSessionDescription
RTCSessionDescription()
constructor takes a dictionary argument,
descriptionInitDict, whose content is used to
initialize the new RTCSessionDescription
object. This constructor is deprecated; it exists for legacy
compatibility reasons only.
type
of type RTCSdpType
, readonlysdp
of type DOMString, readonlytoJSON()
dictionary RTCSessionDescriptionInit
{
required RTCSdpType
type
;
DOMString sdp
= "";
};
RTCSessionDescriptionInit
Memberstype
of type RTCSdpType
, requiredsdp
of type DOMStringtype
is "rollback"
, this member is unused.
Many changes to state of an
will
require communication with the remote side via the signaling channel, in
order to have the desired effect. The app can be kept informed as to when
it needs to do signaling, by listening to the
RTCPeerConnection
negotiationneeded
event. This event is fired according to
the state of the connection's negotiation-needed flag,
represented by a [[NegotiationNeeded]] internal slot.
This section is non-normative.
If an operation is performed on an
that requires signaling, the
connection will be marked as needing negotiation. Examples of such
operations include adding or stopping an
RTCPeerConnection
, or adding the first RTCRtpTransceiver
.
RTCDataChannel
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
of type "answer" is applied, and the supplied description matches
the state of the
RTCSessionDescription
s and
RTCRtpTransceiver
s that currently exist on the
RTCDataChannel
. Specifically, this means that all
non-RTCPeerConnection
stopped
transceivers have an
associated section in the local description with matching properties,
and, if any data channels have been created, a data section exists in
the local description.
Note that the exact procedures for 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 queue a task to update the negotiation-needed flag.
To update the negotiation-needed flag for connection, run the following steps:
If connection's [[IsClosed]] slot is
true
, abort these steps.
If connection's signaling state is not
"stable"
, abort these steps.
The negotiation-needed flag will be updated once the state transitions to "stable", as part of the steps for setting an RTCSessionDescription.
If the result of
checking if negotiation is needed is false
,
clear the negotiation-needed flag by setting
connection's [[NegotiationNeeded]] slot to
false
, and abort these steps.
If connection's [[NegotiationNeeded]] slot is
already true
, abort these steps.
Set connection's [[NegotiationNeeded]] slot to
true
.
Queue a task that runs the following steps:
If connection's [[IsClosed]] slot
is true
, abort these steps.
If connection's [[NegotiationNeeded]]
slot is false
, abort these steps.
Fire a simple event named negotiationneeded
at connection.
This queueing prevents negotiationneeded
from
firing prematurely, in the common situation where multiple
modifications to connection are being made at once.
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
.
Let description be connection.[[CurrentLocalDescription]].
If connection has created any
s, and no m= section in
description has been negotiated yet for data, return
RTCDataChannel
true
.
For each transceiver in connection's set of transceivers, perform the following checks:
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
"sendrecv"
or "sendonly"
,
and the associated m= section in description
either doesn't contain a single "a=msid" line, or the number
of MSIDs from the "a=msid" lines in this m= section,
or the MSID values themselves, differ from what is in
transceiver.sender.[[AssociatedMediaStreamIds]],
return true
.
If description is of type "offer"
,
and the direction of the associated m=
section in neither
connection.[[CurrentLocalDescription]] nor
connection.[[CurrentRemoteDescription]]
matches transceiver.[[Direction]],
return true
.
If description is of type "answer"
,
and the direction of the associated m=
section in the description does not match
transceiver.[[Direction]]
intersected with the offered direction (as described in
[JSEP] (section 5.3.1.)), return
true
.
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
candidate
, sdpMid
,
sdpMLineIndex
, and usernameFragment
,
the remaining attributes are derived from parsing the
candidate
member in candidateInitDict,
if it is well formed.
[Constructor(optional RTCIceCandidateInit
candidateInitDict),
Exposed=Window]
interface RTCIceCandidate
{
readonly attribute DOMString candidate
;
readonly attribute DOMString? sdpMid
;
readonly attribute unsigned short? sdpMLineIndex
;
readonly attribute DOMString? foundation
;
readonly attribute RTCIceComponent
? component
;
readonly attribute unsigned long? priority
;
readonly attribute DOMString? ip
;
readonly attribute RTCIceProtocol
? protocol
;
readonly attribute unsigned short? port
;
readonly attribute RTCIceCandidateType
? type
;
readonly attribute RTCIceTcpCandidateType
? tcpType
;
readonly attribute DOMString? usernameFragment
;
RTCIceCandidateInit
toJSON();
};
RTCIceCandidate
The RTCIceCandidate()
constructor takes
a dictionary argument, candidateInitDict, whose
content is used to initialize the new
object.RTCIceCandidate
When invoked, run the following steps:
sdpMid
and
sdpMLineIndex
dictionary members in candidateInitDict are
null
, throw a TypeError
.RTCIceCandidate
object.null
: foundation
,
component
, priority
,
ip
, protocol
,
port
, type
,
tcpType
, relatedAddress
,
and relatedPort
.candidate
, sdpMid
,
sdpMLineIndex
, usernameFragment
attributes
of iceCandidate with the corresponding dictionary member values
of candidateInitDict.
candidate
dictionary member of candidateInitDict. If
candidate is not an empty string, run the following steps:
candidate-attribute
grammar.candidate-attribute
has failed, abort
these steps.The constructor for RTCIceCandidate
only does basic
parsing and type checking for the dictionary members in
candidateInitDict. Detailed validation on the well-formedness
of candidate
, sdpMid
, sdpMLineIndex
,
usernameFragment
with the corresponding session description is done
when passing the RTCIceCandidate
object to
addIceCandidate()
.
To maintain backward compatibility, any error on parsing the
candidate attribute is ignored. In such case, the
attribute holds the raw
candidate
string given in candidateInitDict,
but derivative attributes such as candidate
,
foundation
, etc are set to priority
null
.
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 RTCIceCandidate
represents an end-of-candidates indication,
candidate
is an empty string.sdpMid
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, nullableRTCIceTransport
s.component
of type RTCIceComponent
, readonly, nullablertp
or rtcp
). This corresponds to the
component-id
field in candidate-attribute
,
decoded to the string representation as defined in
RTCIceComponent
.priority
of type unsigned long, readonly, nullableip
of type DOMString, readonly, nullableThe IP address of the candidate. This corresponds to the
connection-address
field in
candidate-attribute
.
The IP addresses exposed in candidates gathered via ICE
and made visibile to the application in
RTCIceCandidate
instances can reveal more
information about the device and the user (e.g. location,
local network topology) than the user might have expected in
a non-WebRTC enabled browser.
These IP 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 IP 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 IP addresses to the
communicating party, either temporarily or permanently, by
forcing the ICE Agent to report only relay candidates
via the iceTransportPolicy
member of
.RTCConfiguration
To limit the IP addresses exposed to the application itself, browsers can offer their users different policies regarding sharing local IP addresses, as defined in [RTCWEB-IP-HANDLING].
protocol
of type RTCIceProtocol
, readonly, nullableudp
/tcp
). This corresponds to the
transport
field in candidate-attribute
.port
of type unsigned short, readonly, nullabletype
of type RTCIceCandidateType
, readonly, nullablecandidate-types
field in candidate-attribute
.tcpType
of type RTCIceTcpCandidateType
, readonly,
nullableprotocol
is tcp
,
tcpType
represents the type of TCP candidate.
Otherwise, tcpType
is null
. This corresponds
to the tcp-type
field in candidate-attribute
.relatedAddress
of type DOMString, readonly, nullablerelatedAddress
is the IP
address of the candidate that it is derived from. For host
candidates, the relatedAddress
is
null
. This corresponds to the rel-address
field in candidate-attribute
.relatedPort
of type unsigned short, readonly,
nullablerelatedPort
is the port of
the candidate that it is derived from. For host candidates, the
relatedPort
is null
. 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 RTCIceCandidate
interface, run the following steps:
RTCIceCandidateInit
dictionary.RTCIceCandidate
object.json[attr]
to value.dictionary RTCIceCandidateInit
{
DOMString candidate
= "";
DOMString? sdpMid
= null;
unsigned short? sdpMLineIndex
= null;
DOMString usernameFragment
;
};
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, candidate
is an empty string.sdpMid
of type DOMString, nullable, defaulting to
null
null
, 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 null
null
, this indicates the index (starting at
zero) of the media description in the SDP this candidate
is associated with.usernameFragment
of type DOMStringufrag
as defined in section
15.4 of [ICE].candidate-attribute
GrammarThe candidate-attribute
grammar is used to parse
the
candidate
member of candidateInitDict
in the
constructor.RTCIceCandidate()
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
represents the protocol of the ICE
candidate.
enum RTCIceProtocol
{
"udp",
"tcp"
};
Enumeration description | |
---|---|
udp |
A UDP candidate, as described in [ICE]. |
tcp |
A TCP candidate, as described in [RFC6544]. |
RTCIceTcpCandidateType
EnumThe RTCIceTcpCandidateType
represents the type of the
ICE TCP candidate, as defined in [RFC6544].
enum RTCIceTcpCandidateType
{
"active",
"passive",
"so"
};
Enumeration description | |
---|---|
active |
An active TCP candidate is one for which the
transport will attempt to open an outbound connection but
will not receive incoming connection requests. |
passive |
A passive TCP candidate is one for which the
transport will receive incoming connection attempts but not
attempt a connection. |
so |
An so candidate is one for which the
transport will attempt to open a connection simultaneously
with its peer. |
The user agent will typically only gather active
ICE TCP candidates.
RTCIceCandidateType
EnumThe RTCIceCandidateType
represents the type of the ICE
candidate, as defined in [ICE] section 15.1.
enum RTCIceCandidateType
{
"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]. |
RTCPeerConnectionIceEvent
The icecandidate
event of the RTCPeerConnection uses
the
interface.RTCPeerConnectionIceEvent
Firing an
ice candidate event named
e with an
candidate means that an event with the name e,
which does not bubble (except where otherwise stated) and is not
cancelable (except where otherwise stated), and which uses the
RTCIceCandidate
RTCPeerConnectionIceEvent
interface with the
candidate
attribute set to the new ICE candidate, MUST be
created and dispatched at the given target.
When firing an
event
that contains an RTCPeerConnectionIceEvent
object, it MUST
include values for both RTCIceCandidate
and sdpMid
. If the
sdpMLineIndex
is of type RTCIceCandidate
srflx
or
type relay
, the url
property of the event
MUST be set to the URL of the ICE server from which the candidate was
obtained.
icecandidate
event is used for three
different types of indications:
A candidate has been gathered. The
member of the event will be populated normally. It should be
signaled to the remote peer and passed into
candidate
.addIceCandidate
An
has finished gathering a
generation of candidates, and is providing an end-of-candidates
indication as defined by Section 8.2 of [TRICKLE-ICE]. This is
indicated by RTCIceTransport
being set to an
empty string. The candidate
.candidate
object
should be signaled to the remote peer and passed into
candidate
like a typical ICE candidate, in order to provide the
end-of-candidates indication to the remote peer.addIceCandidate
All
s have finished
gathering candidates, and the RTCIceTransport
's
RTCPeerConnection
has transitioned to
RTCIceGatheringState
"
.
This is indicated by the
complete
"
member of the event being set to candidate
null
. This only
exists for backwards compatibility, and this event does not need
to be signaled to the remote peer. It's equivalent to an
"
event with the
icegatheringstatechange
""
state.complete
"
[Constructor(DOMString type, optional RTCPeerConnectionIceEventInit
eventInitDict),
Exposed=Window]
interface RTCPeerConnectionIceEvent
: Event {
readonly attribute RTCIceCandidate
? candidate
;
readonly attribute DOMString? url
;
};
RTCPeerConnectionIceEvent
candidate
of type RTCIceCandidate
, readonly,
nullableThe candidate
attribute is the
object with the new ICE
candidate that caused the event.RTCIceCandidate
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 url
attribute is the STUN or TURN URL that
identifies the STUN or TURN server used to gather this
candidate. If the candidate was not gathered from a STUN or
TURN server, this parameter will be set to
null
.
dictionary RTCPeerConnectionIceEventInit
: EventInit {
RTCIceCandidate
? candidate
;
DOMString? url
;
};
RTCPeerConnectionIceEventInit
Memberscandidate
of type RTCIceCandidate
, nullableSee the
candidate
attribute of the
RTCPeerConnectionIceEvent
interface.
url
of type DOMString, nullableurl
attribute is the STUN or TURN URL that
identifies the STUN or TURN server used to gather this
candidate.RTCPeerConnectionIceErrorEvent
The icecandidateerror
event of the RTCPeerConnection
uses the
interface.RTCPeerConnectionIceErrorEvent
[Constructor(DOMString type, RTCPeerConnectionIceErrorEventInit
eventInitDict),
Exposed=Window]
interface RTCPeerConnectionIceErrorEvent
: Event {
readonly attribute DOMString hostCandidate
;
readonly attribute DOMString url
;
readonly attribute unsigned short errorCode
;
readonly attribute USVString errorText
;
};
RTCPeerConnectionIceErrorEvent
hostCandidate
of type DOMString, readonlyThe hostCandidate
attribute is the local IP
address and port used to communicate with the STUN or TURN
server.
On a multihomed system, multiple interfaces may be used to contact the server, and this attribute allows the application to figure out on which one the failure occurred.
If use of multiple interfaces has been prohibited for privacy reasons, this attribute will be set to 0.0.0.0:0 or [::]:0, as appropriate.
url
of type DOMString, readonlyThe url
attribute is the STUN or TURN URL that
identifies the STUN or TURN server for which the failure
occurred.
errorCode
of type unsigned short, readonlyThe errorCode
attribute is the numeric STUN
error code returned by the STUN or TURN server
[STUN-PARAMETERS].
If no host candidate can reach the server,
errorCode
will be set to the value 701 which is
outside the STUN error code range. This error is only fired
once per server URL while in the
RTCIceGatheringState
of "gathering".
errorText
of type USVString, readonlyThe errorText
attribute is the STUN reason text
returned by the STUN or TURN server [STUN-PARAMETERS].
If the server could not be reached, errorText
will be set to an implementation-specific value providing
details about the error.
dictionary RTCPeerConnectionIceErrorEventInit
: EventInit {
DOMString hostCandidate
;
DOMString url
;
required unsigned short errorCode
;
USVString statusText
;
};
RTCPeerConnectionIceErrorEventInit
MembershostCandidate
of type DOMStringThe local IP address and port used to communicate with the STUN or TURN server.
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.
Many applications have multiple media flows of the same data type and
often some of the flows are more important than others. WebRTC uses the
priority and Quality of Service (QoS) framework described in
[RTCWEB-TRANSPORT] and [TSVWG-RTCWEB-QOS] to provide priority and
DSCP marking for packets that will help provide QoS in some networking
environments. The priority setting can be used to indicate the relative
priority of various flows. The priority API allows the JavaScript
applications to tell the browser whether a particular media flow is high,
medium, low or of very low importance to the application by setting the
priority
property of
objects to one of the
following values.RTCRtpEncodingParameters
RTCPriorityType
Enumenum RTCPriorityType
{
"very-low",
"low",
"medium",
"high"
};
Enumeration description | |
---|---|
very-low |
See [RTCWEB-TRANSPORT], Section 4. Corresponds to "below normal" as defined in [RTCWEB-DATA]. |
low |
See [RTCWEB-TRANSPORT], Section 4. Corresponds to "normal" as defined in [RTCWEB-DATA]. |
medium |
See [RTCWEB-TRANSPORT], Section 4. Corresponds to "high" as defined in [RTCWEB-DATA]. |
high |
See [RTCWEB-TRANSPORT], Section 4. Corresponds to "extra high" as defined in [RTCWEB-DATA]. |
Applications that use this API should be aware that often better overall user experience is obtained by lowering the priority of things that are not as important rather than raising the priority of the things that are.
The certificates that RTCPeerConnection
instances use to
authenticate with peers use the
interface. These objects can be explicitly generated by applications
using the RTCCertificate
method and
can be provided in the generateCertificate
when
constructing a new RTCConfiguration
RTCPeerConnection
instance.
The explicit certificate management functions provided here are
optional. If an application does not provide the
certificates
configuration option when constructing an
RTCPeerConnection
a new set of certificates MUST be
generated by the user agent. That set MUST include an ECDSA
certificate with a private key on the P-256 curve and a signature with a
SHA-256 hash.
partial interface RTCPeerConnection
{
static Promise<RTCCertificate
> generateCertificate
(AlgorithmIdentifier keygenAlgorithm);
};
generateCertificate
, staticThe generateCertificate
function causes the
user agent to create and store an X.509 certificate
[X509V3] and corresponding private key. A handle to
information is provided in the form of the
RTCCertificate
interface. The returned
RTCCertificate
can be used to control the
certificate that is offered in the DTLS sessions established by
RTCPeerConnection
.
The keygenAlgorithm argument is used to control how
the private key associated with the certificate is generated. The
keygenAlgorithm argument uses the WebCrypto
[WebCryptoAPI]
AlgorithmIdentifier
type. The
keygenAlgorithm value MUST be a valid argument to
window.crypto.subtle.generateKey
; that is, the
value MUST produce a non-error result when normalized according
to the WebCrypto
algorithm normalization process [WebCryptoAPI] with an
operation name of generateKey
and a [[supportedAlgorithms]]
value specific to production of certificates for
RTCPeerConnection
. If the algorithm normalization
process produces an error, the call to
generateCertificate
MUST be rejected with that
error.
Signatures produced by the generated key are used to
authenticate the DTLS connection. The identified algorithm (as
identified by the name
of the normalized
AlgorithmIdentifier
) MUST be an asymmetric algorithm
that can be used to produce a signature.
The certificate produced by this process also contains a
signature. The validity of this signature is only relevant for
compatibility reasons. Only the public key and the resulting
certificate fingerprint are used by
RTCPeerConnection
, but it is more likely that a
certificate will be accepted if the certificate is well formed.
The browser selects the algorithm used to sign the certificate; a
browser SHOULD select SHA-256 [FIPS-180-4] if a hash algorithm
is needed.
The resulting certificate MUST NOT include information that can be linked to a user or user agent. Randomized values for distinguished name and serial number SHOULD be used.
A user agent MUST reject a call to
generateCertificate()
with a
DOMException
of type NotSupportedError
if the keygenAlgorithm parameter identifies an
algorithm that the user agent cannot or will not use to
generate a certificate for RTCPeerConnection
.
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.
RTCCertificateExpiration
Dictionary
is used to set an
expiration date on certificates generated by RTCCertificateExpiration
.generateCertificate
dictionary RTCCertificateExpiration
{
[EnforceRange]
DOMTimeStamp expires
;
};
expires
An optional expires
attribute MAY be added to the
definition of the algorithm that is passed to
. If this
parameter is present it indicates the maximum time that the
generateCertificate
is valid for relative to the
current time.RTCCertificate
When
is called
with an generateCertificate
object
argument, the user agent
attempts to convert the object into an
. If this is
unsuccessful, immediately return a promise that is rejected with a
newly created
RTCCertificateExpiration
TypeError
and abort processing.
A user agent generates a certificate that has an
expiration date set to the current time plus the value of the
expires
attribute. The
attribute of the returned
expires
is set to the expiration time of
the certificate. A user agent MAY choose to limit the value
of the RTCCertificate
attribute.expires
RTCCertificate
InterfaceThe RTCCertificate
interface represents a
certificate used to authenticate WebRTC communications. In addition to
the visible properties, internal slots contain a handle to the
generated private keying materal ([[KeyingMaterial]]), a certificate
([[Certificate]]]]) that RTCPeerConnection
uses to authenticate with a peer, and the origin ([[Origin]])
that created the object.
[Exposed=Window]
interface RTCCertificate
{
readonly attribute DOMTimeStamp expires
;
static sequence<AlgorithmIdentifier> getSupportedAlgorithms
();
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
using this certificate fail.
Note that this value might not be reflected in a
notAfter
parameter in the certificate itself.
getSupportedAlgorithms
Returns a sequence providing a representative set of supported certificate algorithms. At least one algorithm MUST be returned.
For example, the "RSASSA-PKCS1-v1_5" algorithm dictionary,
RsaHashedKeyGenParams
, contains fields for the modulus
length, public exponent, and hash algorithm. Implementations
are likely to support a wide range of modulus lengths and exponents,
but a finite number of hash algorithms. So in this case, it would be
reasonable for the implementation to return one
AlgorithmIdentifier
for each supported hash algorithm
that can be used with RSA, using default/recommended values for
modulusLength
and publicExponent
(such as 1024 and 65537, respectively).
getFingerprints
Returns the list of certificate fingerprints, one of which is computed with the digest algorithm used in the certificate signature.
For the purposes of this API, the [[Certificate]] slot
contains unstructured binary data. No mechanism is provided for
applications to access the [[KeyingMaterial]] internal slot.
Implementations MUST support applications storing and retrieving
RTCCertificate
objects from persistent storage.
In implementations where an RTCCertificate
might not
directly hold private keying material (it might be stored in a
secure module), a reference to the private key can be held in
the [[KeyingMaterial]] internal slot, allowing the
private key to be stored and used.
When a user agent is required to obtain a structured
clone [HTML51] of an RTCCertificate
object,
it performs the following steps:
RTCCertificate
object to
be cloned.RTCCertificate
object.expires
attribute from
input to output.Supporting structured cloning in this manner
allows RTCCertificate
instances to be persisted to stores. It
also allows instances to be passed to other origins using APIs
like postMessage
[webmessaging]. However, the object cannot
be used by any other origin than the one that originally created it.
The RTP media API lets a web application send and receive
MediaStreamTrack
s over a peer-to-peer connection. Tracks, when
added to an RTCPeerConnection
, result in signaling; when this
signaling is forwarded to a remote peer, it causes corresponding tracks to
be created on the remote side.
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
values, situations when the resulting width
or height is not an integer may occur. In such situations the
user agent MUST use the
integer part of the result. What to transmit if the integer
part of the scaled width or height is zero is implementation-specific.
scaleResolutionDownBy
The actual encoding and transmission of MediaStreamTrack
s
is managed through objects called
s.
Similarly, the reception and decoding of RTCRtpSender
MediaStreamTrack
s is
managed through objects called
s. Each
RTCRtpReceiver
is associated with at most one track,
and each track to be received is associated with exactly
one RTCRtpSender
.RTCRtpReceiver
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
settings applied that
instruct the implementation to act differently.RTCRtpSender
An
object contains a set of
RTCPeerConnection
s, representing the paired
senders and receivers with some shared state. This set is initialized to
the empty set when the RTCRtpTransceiver
object is
created. RTCPeerConnection
s and
RTCRtpSender
s are always created at the same time
as an RTCRtpReceiver
, which they will remain
attached to for their lifetime.
RTCRtpTransceiver
s are created implicitly when the
application attaches a RTCRtpTransceiver
MediaStreamTrack
to an
via the RTCPeerConnection
addTrack
method, or explicitly when the application uses the
addTransceiver
method. They are also created when a remote
description is applied that includes a new media description.
Additionally, when a remote description is applied that indicates the
remote endpoint has media to send, the relevant
MediaStreamTrack
and
are
surfaced to the application via the RTCRtpReceiver
event.
track
The RTP media API extends the
interface as described below.RTCPeerConnection
partial interface RTCPeerConnection
{
sequence<RTCRtpSender
> getSenders
();
sequence<RTCRtpReceiver
> getReceivers
();
sequence<RTCRtpTransceiver
> getTransceivers
();
RTCRtpSender
addTrack
(MediaStreamTrack
track,
MediaStream... streams);
void removeTrack
(RTCRtpSender
sender);
RTCRtpTransceiver
addTransceiver
((MediaStreamTrack
or DOMString) trackOrKind,
optional RTCRtpTransceiverInit
init);
attribute EventHandler ontrack
;
};
ontrack
of type EventHandlerThe event type of this event handler is
.track
getSenders
Returns a sequence of
objects
representing the RTP senders that are currently attached to this
RTCRtpSender
object.RTCPeerConnection
The getSenders
method MUST return the result of executing the
CollectSenders
algorithm.
We define the CollectSenders algorithm as follows:
CollectTransceivers
algorithm.getReceivers
Returns a sequence of
objects representing the RTP receivers that are currently
attached to this RTCRtpReceiver
object.RTCPeerConnection
The getReceivers
method MUST return the result of executing the
CollectReceivers
algorithm.
We define the CollectReceivers algorithm as follows:
CollectTransceivers
algorithm.getTransceivers
Returns a sequence of
objects representing the RTP transceivers that are currently
attached to this RTCRtpTransceiver
object.RTCPeerConnection
The getTransceivers
method MUST return the result of executing the
CollectTransceivers
algorithm.
We define the CollectTransceivers algorithm as follows:
RTCRtpTransceiver
objects in this
RTCPeerConnection
object's
set of transceivers, in insertion order.
addTrack
Adds a new track to the
,
and indicates that it is contained in the specified
RTCPeerConnection
MediaStream
s.
When the addTrack
method is invoked,
the user agent MUST run the following steps:
Let connection be the
object on which this
method was invoked.RTCPeerConnection
Let track be the
object indicated by the
method's first argument.MediaStreamTrack
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's [[IsClosed]] slot is
true
, throw an
InvalidStateError
.
Let senders be the result of executing the
CollectSenders
algorithm. If an
for track already
exists in senders, throw an
RTCRtpSender
InvalidAccessError
.
The steps below describe how to determine if an existing
sender can be reused. Doing so will cause future calls to
createOffer
and createAnswer
to
mark the corresponding media description as
sendrecv
or sendonly
and add the
MSID of the track added, as defined in [JSEP] (section 5.2.2. and section 5.3.2.).
If any
object in
senders matches all the following criteria, let
sender be that object, or RTCRtpSender
null
otherwise:
The sender's track is null.
The transceiver kind of the
, associated with
the sender, matches kind.RTCRtpTransceiver
The transceiver is not stopped
. More
precisely, the [[Stopped]] slot of the
associated with the
sender is RTCRtpTransceiver
false
.
The sender has never been used to send. More
precisely, the [[CurrentDirection]] slot of the
associated with the
sender has never had a value of RTCRtpTransceiver
sendrecv
or
sendonly
.
If sender is not null
, run the
following steps to use that sender:
Set sender's [[SenderTrack]] to track.
Set sender's [[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
associated with
sender.RTCRtpTransceiver
If transceiver's [[Direction]] slot is
recvonly
, set transceiver's
[[Direction]] slot to sendrecv
.
If transceiver's [[Direction]] slot
is inactive
, set transceiver's
[[Direction]] slot to sendonly
.
If sender is null
, run the
following steps:
Create an RTCRtpSender with track, kind and streams, and let sender be the result.
Create an RTCRtpReceiver with kind, and let receiver be the result.
Create an RTCRtpTransceiver with
sender, receiver and
an
value
of RTCRtpTransceiverDirection
sendrecv
, and let transceiver
be the result.
Add transceiver to connection's set of transceivers
A track could have contents that are inaccessible to the
application. This can be due to being marked with a
peerIdentity
option or anything that would make
a track
CORS cross-origin. These tracks can be supplied to the
addTrack
method, and have an
created for them, but
content MUST NOT be transmitted, unless they are also marked
with RTCRtpSender
peerIdentity
and they meet the requirements
for sending (see isolated streams and
RTCPeerConnection
).
All other tracks that are not accessible to the application MUST NOT be sent to the peer, with silence (audio), black frames (video) or equivalently absent content being sent in place of track content.
Note that this property can change over time.
Update the negotiation-needed flag for connection.
Return sender.
removeTrack
Stops sending media from sender. The
will still appear
in RTCRtpSender
getSenders
. Doing so will cause future
calls to createOffer
to mark the
media description for the corresponding transceiver
as recvonly
or inactive
,
as defined in
[JSEP] (section 5.2.2.).
When the other peer stops sending a track in this manner, the
track is removed from any remote MediaStream
s
that were initially revealed in the track
event, and
if the
is not already muted,
a MediaStreamTrack
muted
event is
fired at the track.
When the removeTrack
method is
invoked, the user agent MUST run the following steps:
Let sender be the argument to
removeTrack
.
Let connection be the
object on which
the method was invoked.RTCPeerConnection
If connection's [[IsClosed]] slot 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 that it was removed due to setting an RTCSessionDescription of type "rollback"), then abort these steps.
If sender's [[SenderTrack]] is null, abort these steps.
Set sender's [[SenderTrack]] to null.
Let transceiver be the
object corresponding
to sender.RTCRtpTransceiver
If transceiver's [[Direction]] slot is
sendrecv
, set transceiver's
[[Direction]] slot to recvonly
.
If transceiver's [[Direction]] slot
is sendonly
, set transceiver's
[[Direction]] slot to inactive
.
Update the negotiation-needed flag for connection.
addTransceiver
Create a new
and add it
to the set of transceivers.RTCRtpTransceiver
Adding a transceiver will cause future calls to
createOffer
to add a media description for
the corresponding transceiver, as defined in [JSEP] (section 5.2.2.).
The initial value of
is null. Setting a new
mid
may change it to a
non-null value, as defined in [JSEP] (section 5.5. and section 5.6.).RTCSessionDescription
The sendEncodings
argument can be used to
specify the number of offered simulcast encodings, and
optionally their RIDs and encoding parameters.
When this method is invoked, the user agent MUST run the following steps:
Let init be the second argument.
Let streams be init's
streams
member.
Let sendEncodings be init's
sendEncodings
member.
Let direction be init's
direction
member.
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
, let it be
track and let kind be
track.kind.MediaStreamTrack
Verify that each
value in sendEncodings is composed only of
alphanumeric characters (a-z, A-Z, 0-9) up to
a maximum of 16 characters. If one of the RIDs does not meet
these requirements, throw a rid
TypeError
.
If any
dictionary in sendEncodings contains a
read-only parameter other than
RTCRtpEncodingParameters
,
throw an rid
InvalidAccessError
.
Verify that each
value in sendEncodings is greater than or equal to 1.0. If
one of the scaleResolutionDownBy
scaleResolutionDownBy
values does not meet
this requirement, throw a RangeError
.
Create an RTCRtpSender with track, kind, streams and sendEncodings and let sender be the result.
If sendEncodings is set, then subsequent calls
to createOffer
will be configured to send
multiple RTP encodings as defined in [JSEP] (section 5.2.2. and section 5.2.1.). When
setRemoteDescription
is called with a
corresponding remote description that is able to receive
multiple RTP encodings as defined in [JSEP] (section 3.7.), the
may send multiple RTP
encodings and the parameters retrieved via the transceiver's
RTCRtpSender
sender.getParameters()
will reflect the
encodings negotiated.
Create an RTCRtpReceiver with kind and
let receiver be the result. This specification
does not define how to configure createOffer
to
receive multiple RTP encodings. However when
setRemoteDescription
is called with a
corresponding remote description that is able to send
multiple RTP encodings as defined in [JSEP], the
may receive multiple RTP
encodings and the parameters retrieved via the transceiver's
RTCRtpReceiver
receiver.getParameters()
will reflect the
encodings negotiated.
Support for the encodings
attribute of
is marked
as a feature at risk, since there is no clear
commitment from implementers.RTCRtpReceiveParameters
Create an RTCRtpTransceiver with sender, receiver and direction, and let transceiver be the result.
Add transceiver to connection's set of transceivers
Update the negotiation-needed flag for connection.
Return transceiver.
dictionary RTCRtpTransceiverInit
{
RTCRtpTransceiverDirection
direction
= "sendrecv";
sequence<MediaStream> streams
= [];
sequence<RTCRtpEncodingParameters
> sendEncodings
= [];
};
RTCRtpTransceiverInit
Membersdirection
of type RTCRtpTransceiverDirection
,
defaulting to "sendrecv"
RTCRtpTransceiver
.streams
of type sequence<MediaStream>When the remote PeerConnection's track event fires
corresponding to the
being
added, these are the streams that will be put in the event.RTCRtpReceiver
sendEncodings
of type sequence<RTCRtpEncodingParameters
>A sequence containing parameters for sending RTP encodings of media.
enum RTCRtpTransceiverDirection
{
"sendrecv",
"sendonly",
"recvonly",
"inactive"
};
RTCRtpTransceiverDirection Enumeration description |
|
---|---|
sendrecv |
The 's
sender will offer to
send RTP, and will send RTP if the remote peer accepts and
sender.getParameters().encodings[i].active
is true for any value of i. The
's
will offer to receive RTP, and
will receive RTP if the remote peer accepts. |
sendonly |
The 's
sender will offer to
send RTP, and will send RTP if the remote peer accepts and
sender.getParameters().encodings[i].active
is true for any value of i. The
's
will not offer to receive RTP,
and will not receive RTP. |
recvonly |
The 's
will not offer to send RTP, and
will not send RTP. The 's
will offer to receive RTP, and
will receive RTP if the remote peer accepts. |
inactive |
The 's
will not offer to send RTP, and
will not send RTP. The 's
will not offer to receive RTP,
and will not receive RTP. |
An application can reject incoming media descriptions by calling
to stop both directions,
or set the transceiver's direction to "sendonly" to reject only the
incoming side.RTCRtpTransceiver
.stop()
To
process the addition of a remote track for
an incoming media description [JSEP] (section 5.10.) given
RTCRtpTransceiver
transceiver,
addList, and trackEvents, the user agent MUST run
the following steps:
Let receiver be transceiver's [[Receiver]].
Let msids be a list of the MSIDs that the media description indicates track is to be associated with.
Let removeList be an empty list.
Set the associated remote streams given receiver, msids, addList, and removeList.
Let track be receiver's [[ReceiverTrack]].
Let streams be receiver's [[AssociatedRemoteMediaStreams]] slot.
Add a new
with
receiver, track,
streams and transceiver to
trackEvents.RTCTrackEvent
To
process the removal of a remote track for
an incoming media description [JSEP] (section 5.10.) given
RTCRtpTransceiver
transceiver,
removeList, and muteTracks, the user agent MUST
run the following steps:
Let receiver be transceiver's [[Receiver]].
Let msids and addList be empty lists.
Set the associated remote streams, given receiver, msids, addList, and removeList.
Let track be receiver's [[ReceiverTrack]].
If track.muted is false
,
add track to muteTracks.
To set the associated remote streams given
RTCRtpReceiver
receiver, msids,
addList, and removeList, the user agent MUST run
the following steps:
Let connection be the
object associated with
receiver.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 id
s corresponding to
msids.
Let track be receiver's [[ReceiverTrack]].
For each stream in receiver's [[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's [[AssociatedRemoteMediaStreams]], add stream and track as a pair to addList.
Set receiver's [[AssociatedRemoteMediaStreams]] slot to streams.
RTCRtpSender
InterfaceThe RTCRtpSender
interface allows an
application to control how a given MediaStreamTrack
is
encoded and transmitted to a remote peer. When setParameters
is called on an
object, the encoding is
changed appropriately.RTCRtpSender
To create an RTCRtpSender with a
, track, a string,
kind, a list of
MediaStreamTrack
MediaStream
objects, streams, and
optionally a list of
objects, sendEncodings, run the following steps:RTCRtpEncodingParameters
Let sender be a new
object.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 [[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 a [[SenderRtcpTransport]] internal
slot initialized to null
.
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's [[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
dictionaries.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
with
RTCRtpEncodingParameters
active
set to true
.
RTCRtpEncodingParameters
allows the application
to set encoding parameters using
setParameters
, even
when simulcast isn't used.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 the number of
stored in [[SendEncodings]] exceeds maxN, then trim
[[SendEncodings]] from the tail until its length is
maxN.RTCRtpEncodingParameters
If the number of
now
stored in [[SendEncodings]] is RTCRtpEncodingParameters
1
, then remove any
member from the lone entry.rid
Let sender have a [[LastReturnedParameters]]
internal slot, which will be used to match
and
getParameters
transactions.setParameters
Return sender.
[Exposed=Window]
interface RTCRtpSender
{
readonly attribute MediaStreamTrack
? track
;
readonly attribute RTCDtlsTransport
? transport
;
readonly attribute RTCDtlsTransport
? rtcpTransport
;
static RTCRtpCapabilities
getCapabilities(DOMString kind);
Promise<void> setParameters
(RTCRtpSendParameters
parameters);
RTCRtpSendParameters
getParameters();
Promise<void> replaceTrack
(MediaStreamTrack
? withTrack);
void setStreams
(MediaStream... streams);
Promise<RTCStatsReport
> getStats();
};
track
of type MediaStreamTrack
, readonly,
nullableThe track
attribute is the track that is
associated with this
object. If
RTCRtpSender
track
is ended, or if the track's output is disabled,
i.e. the track is disabled and/or muted, the
MUST send silence (audio), black
frames (video) or a zero-information-content equivalent. In the
case of video, the RTCRtpSender
SHOULD send one
black frame per second. If RTCRtpSender
track
is null then
the RTCRtpSender
does not send. On getting, the
attribute MUST return the value of the [[SenderTrack]]
slot.
transport
of type RTCDtlsTransport
, readonly,
nullableThe transport
attribute is the transport over
which media from track
is sent in the form of RTP
packets. Prior to construction of the
object, the
RTCDtlsTransport
transport
attribute will be null. When bundling is
used, multiple
objects will
share one RTCRtpSender
transport
and will all send RTP and RTCP
over the same transport.
On getting, the attribute MUST return the value of the [[SenderTransport]] slot.
rtcpTransport
of type RTCDtlsTransport
, readonly,
nullableThe rtcpTransport
attribute is the transport over
which RTCP is sent and received. Prior to construction of the
object, the
RTCDtlsTransport
rtcpTransport
attribute will be null. When RTCP mux
is used (or bundling, which mandates RTCP mux),
rtcpTransport
will be null, and both RTP and RTCP
traffic will flow over the transport described by
transport
.
On getting, the attribute MUST return the value of the [[SenderRtcpTransport]] 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, getCapabilities
returns null
.
These capabilities provide generally
persistent cross-origin information on the device and thus
increases the fingerprinting surface of the application. In
privacy-sensitive contexts, browsers can consider mitigations
such as reporting only a common subset of the capabilities.
setParameters
The setParameters
method updates how
track
is encoded and transmitted to a remote
peer.
When the setParameters
method is called, the user
agent MUST run the following steps:
RTCRtpSender
object on which
setParameters
is invoked.RTCRtpTransceiver
object associated
with sender (i.e. sender is
transceiver's [[Sender]]).RTCRtpEncodingParameters
stored in
sender's internal [[SendEncodings]]
slot.true
, return a promise rejected with a newly
created
InvalidStateError
.null
, return a promise
rejected with a newly
created
InvalidStateError
.InvalidModificationError
:
parameters.encodings.length
is different from N.parameters.encodings
has been
re-ordered.For each value of i from 0 to the number of encodings,
check whether
parameters.encodings[i].codecPayloadType
(if set) corresponds to a value of
parameters.codecs[j].payloadType
where
j goes from 0 to the number of codecs. If there is no
correspondence, or if the MIME subtype portion of
parameters.codecs[j].mimeType
is equal to
"red", "cn", "telephone-event", "rtx" or a forward error correction
codec ("ulpfec" [RFC5109] or "flexfec" [FLEXFEC]), reject p with
a newly created
InvalidAccessError
.
scaleResolutionDownBy
parameter in the
parameters argument has a value less than 1.0,
return a promise rejected with a newly
created
RangeError
.null
.
parameters.encodings
.undefined
.
RTCError
whose
errorDetail
is set to
"hardware-encoder-not-available" and abort these steps.
RTCError
whose errorDetail
is set to "hardware-encoder-error" and abort these
steps.OperationError
.If the application selects a codec via
,
and this codec is removed from a subsequent offer/answer
negotiation, codecPayloadType
will be unset in the next call to codecPayloadType
,
and the implementation will fall back to its default codec
selection policy until a new codec is selected.getParameters
setParameters
does not cause SDP renegotiation
and can only be used to change what the media stack is sending or
receiving within the envelope negotiated by Offer/Answer. The
attributes in the
dictionary
are designed to not enable this, so attributes like
RTCRtpSendParameters
cname
that cannot be changed are read-only. Other
things, like bitrate, are controlled using limits such as
maxBitrate
, where the user agent needs to ensure it
does not exceed the maximum bitrate specified by
maxBitrate
, while at the same time making sure it
satisfies constraints on bitrate specified in other places such
as the SDP.
getParameters
The getParameters()
method
returns the
object's current
parameters for how RTCRtpSender
track
is encoded and transmitted
to a remote
.RTCRtpReceiver
When getParameters
is called, the
dictionary is
constructed as follows:RTCRtpSendParameters
transactionId
is set to a new unique identifier, used to match this
getParameters
call to a
setParameters
call that may occur later.
encodings
is set to the value of the [[SendEncodings]] internal
slot.
headerExtensions
sequence is populated based on the header extensions that
have been negotiated for sending.
codecs
sequence is populated based on the codecs that have been
negotiated for sending, and which the user agent is currently
capable of sending.
rtcp
.cname
is set to the CNAME of the associated
RTCPeerConnection
.
rtcp
.reducedSize
is set to true
if reduced-size RTCP has been negotiated
for sending, and false
otherwise.
degradationPreference
is set to the last value passed into setParameters
, or
the default value of "balanced" if setParameters
hasn't
been called.
The returned
dictionary
MUST be stored in the RTCRtpSendParameters
object's
[[LastReturnedParameters]] internal slot.RTCRtpSender
getParameters
may be used with
setParameters
to change the parameters in the
following way:
async function updateParameters() {
try {
const params = sender.getParameters();
// ... make changes to parameters
params.encodings[0].active = false;
await sender.setParameters(params);
} catch (err) {
console.error(err);
}
}
After a completed call to setParameters
,
subsequent calls to getParameters
will return the
modified set of parameters.
replaceTrack
Attempts to replace the
's
current RTCRtpSender
track
with another track provided (or
with a null track), without renegotiation.
To avoid track identifiers changing on the remote receiving end when a track is replaced, the sender MUST retain the original track identifier and stream associations and use these in subsequent negotiations.
When the replaceTrack
method is
invoked, the user agent MUST run the following steps:
Let sender be the
object on which
RTCRtpSender
replaceTrack
is invoked.
Let transceiver be the
object associated with
sender.RTCRtpTransceiver
Let connection be the
object associated with
sender.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 enqueuing the following steps to connection's operation queue:
If transceiver's [[Stopped]] slot is
true
, return a promise rejected
with a newly
created InvalidStateError
.
Let p be a new promise.
Let sending be true
if the
transceiver's [[CurrentDirection]]
is "sendrecv"
or "sendonly"
,
and false
otherwise.
Run the following steps in parallel:
If sending is true
, and
withTrack is null
, have the
sender stop sending.
If sending is true
, and
withTrack is not null
,
determine if withTrack can be sent
immediately by the sender without violating the
sender's already-negotiated envelope, and if it
cannot, then reject p with a newly
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 transceiver's [[Stopped]] slot is
true
, abort these steps.
Set sender's
attribute to
withTrack.track
Resolve p with
undefined
.
Return p.
Changing dimensions and/or frame rates might not require negotiation. Cases that may require negotiation include:
setStreams
Sets the MediaStream
s to be associated with this
sender's track.
When the setStreams
method is invoked,
the user agent MUST run the following steps:
Let sender be the
object on which this method
was invoked.RTCRtpSender
Let connection be the
object on which this
method was invoked.RTCPeerConnection
If connection's [[IsClosed]] slot 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's [[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.
getStats
Gathers stats for this sender only and reports the result asynchronously.
When the
getStats()
method is invoked, the user
agent MUST run the following steps:
Let selector be the
object on which the method
was invoked.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
object, containing
the gathered stats.RTCStatsReport
Return p.
RTCRtpParameters
Dictionarydictionary RTCRtpParameters
{
required sequence<RTCRtpHeaderExtensionParameters
> headerExtensions
;
required RTCRtcpParameters
rtcp
;
required sequence<RTCRtpCodecParameters
> codecs
;
};
RTCRtpParameters
MembersheaderExtensions
of type sequence<RTCRtpHeaderExtensionParameters
>,
requiredA sequence containing parameters for RTP header extensions. Read-only parameter.
rtcp
of type RTCRtcpParameters
, requiredParameters used for RTCP. Read-only parameter.
codecs
of type sequence<RTCRtpCodecParameters
>,
requiredA sequence containing the media codecs that an
will choose from, as well as
entries for RTX, RED and FEC mechanisms. Corresponding to each
media codec where retransmission via RTX is enabled, there will
be an entry in RTCRtpSender
codecs[]
with a mimeType
attribute indicating retransmission via "audio/rtx" or
"video/rtx", and an sdpFmtpLine
attribute (providing
the "apt" and "rtx-time" parameters). Read-only parameter.
RTCRtpSendParameters
Dictionarydictionary RTCRtpSendParameters
: RTCRtpParameters
{
required DOMString transactionId
;
required sequence<RTCRtpEncodingParameters
> encodings
;
RTCDegradationPreference
degradationPreference
= "balanced";
};
RTCRtpSendParameters
MemberstransactionId
of type DOMString, requiredAn unique identifier for the last set of parameters applied. Ensures that setParameters can only be called based on a previous getParameters, and that there are no intervening changes. Read-only parameter.
encodings
of type sequence<RTCRtpEncodingParameters
>,
requiredA sequence containing parameters for RTP encodings of media.
degradationPreference
of type
RTCDegradationPreference
,
defaulting to "balanced"
When bandwidth is constrained and the
RtpSender
needs to choose between degrading
resolution or degrading framerate,
degradationPreference
indicates which is
preferred.
RTCRtpReceiveParameters
Dictionarydictionary RTCRtpReceiveParameters
: RTCRtpParameters
{
required sequence<RTCRtpDecodingParameters
> encodings
;
};
RTCRtpReceiveParameters
Membersencodings
of type sequence<RTCRtpDecodingParameters
>,
requiredA sequence containing information about incoming RTP encodings of media.
RTCRtpCodingParameters
Dictionarydictionary RTCRtpCodingParameters
{
DOMString rid
;
};
RTCRtpCodingParameters
Membersrid
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
setParameters
. It can only be set or modified in
addTransceiver
on the sending side.
Read-only parameter.
RTCRtpDecodingParameters
Dictionarydictionary RTCRtpDecodingParameters
: RTCRtpCodingParameters
{
};
RTCRtpEncodingParameters
Dictionarydictionary RTCRtpEncodingParameters
: RTCRtpCodingParameters
{
octet codecPayloadType
;
RTCDtxStatus
dtx
;
boolean active
= true;
RTCPriorityType
priority
= "low";
unsigned long ptime
;
unsigned long maxBitrate
;
double maxFramerate
;
double scaleResolutionDownBy
;
};
RTCRtpEncodingParameters
MemberscodecPayloadType
of type octetUsed to select a
codec to be sent. Must reference a payload type from the
member of
codecs
. If left unset, the
implementation will select a codec according to its default policy.
RTCRtpParameters
dtx
of type RTCDtxStatus
This member is only used if the sender's kind
is "audio"
. It indicates whether
discontinuous transmission will be used. Setting it to
disabled
causes discontinuous transmission to be
turned off. Setting it to enabled
causes
discontinuous transmission to be turned on if it was negotiated
(either via a codec-specific parameter or via negotiation of the
CN codec); if it was not negotiated (such as when setting
voiceActivityDetection
to false
),
then discontinuous operation will be turned off regardless of the
value of dtx
, and media will be sent even when silence
is detected.
active
of type boolean, defaulting to
true
Indicates that this
encoding is actively being sent. Setting it to false
causes this encoding to no longer be sent. Setting it to true
causes this encoding to be sent.
priority
of type RTCPriorityType
, defaulting to
"low"
Indicates the priority of this encoding. It is specified in [RTCWEB-TRANSPORT], Section 4.
ptime
of type unsigned longWhen present, indicates the preferred duration of media represented by a packet in milliseconds for this encoding. Typically, this is only relevant for audio encoding. The user agent MUST use this duration if possible, and otherwise use the closest available duration. This value MUST take precedence over any "ptime" attribute in the remote description, whose processing is described in [JSEP] (section 5.10.). Note that the user agent MUST still respect the limit imposed by any "maxptime" attribute, as defined in [RFC4566], Section 6.
maxBitrate
of type unsigned longWhen present, indicates the maximum bitrate that can be used to send this encoding. The encoding may also be further constrained by other limits (such as maxFramerate or per-transport or per-session bandwidth limits) below the maximum specified here. maxBitrate is computed the same way as the Transport Independent Application Specific Maximum (TIAS) bandwidth defined in [RFC3890] Section 6.2.2, which is the maximum bandwidth needed without counting IP or other transport layers like TCP or UDP.
maxFramerate
of type doubleWhen present, indicates the maximum framerate that can be used to send this encoding, in frames per second.
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, the sender will not apply any scaling,
(i.e., scaleResolutionDownBy
will be 1.0).
RTCDtxStatus
Enumenum RTCDtxStatus
{
"disabled",
"enabled"
};
Enumeration description |
|
---|---|
disabled |
Discontinuous transmission is disabled. |
enabled |
Discontinuous transmission is enabled if negotiated. |
RTCDegradationPreference
Enum Enumeration description |
|
---|---|
maintain-framerate |
Degrade resolution in order to maintain framerate. |
maintain-resolution |
Degrade framerate in order to maintain resolution. |
balanced |
Degrade a balance of framerate and resolution. |
RTCRtcpParameters
Dictionarydictionary RTCRtcpParameters
{
DOMString cname
;
boolean reducedSize
;
};
RTCRtcpParameters
Memberscname
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
Dictionarydictionary RTCRtpHeaderExtensionParameters
{
required DOMString uri
;
required unsigned short id
;
boolean encrypted
= false;
};
RTCRtpHeaderExtensionParameters
Membersuri
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.
RTCRtpCodecParameters
Dictionarydictionary RTCRtpCodecParameters
{
required octet payloadType
;
required DOMString mimeType
;
required unsigned long clockRate
;
unsigned short channels
;
DOMString sdpFmtpLine
;
};
RTCRtpCodecParameters
MemberspayloadType
of type octetThe RTP payload type used to identify this codec. Read-only parameter.
mimeType
of type DOMStringThe codec MIME media type/subtype. Valid media types and subtypes are listed in [IANA-RTP-2]. Read-only parameter.
clockRate
of type unsigned longThe 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
, these parameters come from the
remote description, and for an
RTCRtpSender
, they come from the local
description. Read-only parameter.RTCRtpReceiver
RTCRtpCapabilities
Dictionarydictionary RTCRtpCapabilities
{
required sequence<RTCRtpCodecCapability
> codecs
;
required sequence<RTCRtpHeaderExtensionCapability
> headerExtensions
;
};
RTCRtpCapabilities
Memberscodecs
of type sequence<RTCRtpCodecCapability
>, requiredSupported media codecs as well as entries for RTX, RED and FEC
mechanisms. There will only be a single entry in
codecs[]
for retransmission via RTX, with
sdpFmtpLine
not present.
headerExtensions
of type sequence<RTCRtpHeaderExtensionCapability
>, requiredSupported RTP header extensions.
RTCRtpCodecCapability
Dictionarydictionary RTCRtpCodecCapability
{
required DOMString mimeType
;
required unsigned long clockRate
;
unsigned short channels
;
DOMString sdpFmtpLine
;
};
RTCRtpCodecCapability
Members The RTCRtpCodecCapability
dictionary provides
information about codec capabilities. Only capability
combinations that would utilize distinct payload types in a
generated SDP offer are provided. For example:
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
Dictionarydictionary RTCRtpHeaderExtensionCapability
{
DOMString uri
;
};
RTCRtpHeaderExtensionCapability
Membersuri
of type DOMStringThe URI of the RTP header extension, as defined in [RFC5285].
RTCRtpReceiver
InterfaceThe RTCRtpReceiver
interface allows an application to
inspect the receipt of a MediaStreamTrack
.
To create an RTCRtpReceiver with a string, kind, and optionally an id string, id, run the following steps:
Let receiver be a new
object.RTCRtpReceiver
Let track be a new
object [GETUSERMEDIA]. The source of track is a
remote source provided by receiver.MediaStreamTrack
Initialize track.kind to kind.
If an id string, id, was given as input to this algorithm, initialize track.id to id. (Otherwise the value generated when track was created will be used.)
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
section about how the
MediaStreamTrack
muted
attribute reflects if a
is receiving media data or
not.MediaStreamTrack
Let receiver have a [[ReceiverTrack]] internal slot initialized to track.
Let receiver have a [[ReceiverTransport]] internal
slot initialized to null
.
Let receiver have a [[ReceiverRtcpTransport]] internal
slot initialized to null
.
Let receiver have an
[[AssociatedRemoteMediaStreams]] internal slot, representing a
list of MediaStream
objects that the
object of this receiver is
associated with, and initialized to an empty list.MediaStreamTrack
Return receiver.
[Exposed=Window]
interface RTCRtpReceiver
{
readonly attribute MediaStreamTrack
track
;
readonly attribute RTCDtlsTransport
? transport
;
readonly attribute RTCDtlsTransport
? rtcpTransport
;
static RTCRtpCapabilities
getCapabilities(DOMString kind);
RTCRtpReceiveParameters
getParameters();
sequence<RTCRtpContributingSource
> getContributingSources
();
sequence<RTCRtpSynchronizationSource
> getSynchronizationSources
();
Promise<RTCStatsReport
> getStats();
};
track
of type MediaStreamTrack
, readonlyThe track
attribute is the track that is associated with this
object receiver.
RTCRtpReceiver
Note that track.stop()
is final, although
clones are not affected. Since
receiver.track.stop()
does not implicitly stop receiver, Receiver
Reports continue to be sent. On getting, the attribute MUST
return the value of the [[ReceiverTrack]] slot.
transport
of type RTCDtlsTransport
, readonly,
nullableThe transport
attribute is the
transport over which media for the receiver's track
is received in the form of RTP packets. Prior to construction of
the
object, the
RTCDtlsTransport
transport
attribute will be null. When bundling is
used, multiple
objects will
share one RTCRtpReceiver
transport
and will all receive RTP and
RTCP over the same transport.
On getting, the attribute MUST return the value of the [[ReceiverTransport]] slot.
rtcpTransport
of type RTCDtlsTransport
, readonly,
nullableThe rtcpTransport
attribute is the
transport over which RTCP is sent and received. Prior to
construction of the
object,
the RTCDtlsTransport
rtcpTransport
attribute will be null. When RTCP
mux is used (or bundling, which mandates RTCP mux),
rtcpTransport
will be null, and both RTP and RTCP
traffic will flow over transport
.
On getting, the attribute MUST return the value of the [[ReceiverRtcpTransport]] 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,
getCapabilities
returns null
.
These capabilities provide generally
persistent cross-origin information on the device and thus
increases the fingerprinting surface of the application. In
privacy-sensitive contexts, browsers can consider mitigations
such as reporting only a common subset of the capabilities.
getParameters
The getParameters()
method returns the
RTCRtpReceiver
object's current parameters for how
track
is decoded.
When getParameters
is called, the
dictionary is
constructed as follows:RTCRtpReceiveParameters
is populated based on the RIDs present in the current remote
description.encodings
headerExtensions
sequence is populated based on the header extensions that the
receiver is currently prepared to receive.
The
sequence is populated based on the codecs that the receiver
is currently prepared to receive.codecs
getParameters
. But if the remote endpoint only
answers with two, the absent codec will no longer be returned
by getParameters
as the receiver no longer needs
to be prepared to receive it.rtcp
.reducedSize
is set to true
if the receiver is currently prepared to
receive reduced-size RTCP packets, and false
otherwise.
rtcp
.cname
is
left out.
getContributingSources
Returns an
for
each unique CSRC identifier received by this RTCRtpReceiver in
the last 10 seconds.RTCRtpContributingSource
getSynchronizationSources
Returns an
for
each unique SSRC identifier received by this RTCRtpReceiver in
the last 10 seconds.RTCRtpSynchronizationSource
getStats
Gathers stats for this receiver only and reports the result asynchronously.
When the
getStats()
method is invoked, the user
agent MUST run the following steps:
Let selector be the
object on which the method
was invoked.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
object, containing
the gathered stats.RTCStatsReport
Return p.
The RTCRtpContributingSource
and
RTCRtpSynchronizationSource
dictionaries contain information
about a given contributing source (CSRC) or synchronization source (SSRC)
respectively, including the most recent time a
packet that the source contributed to was played out. The browser MUST
keep information from RTP packets received in the previous 10 seconds.
When the first audio frame contained in an RTP packet is delivered to the
's RTCRtpReceiver
for playout, the user agent MUST queue a task to update the relevant
information for the MediaStreamTrack
and
RTCRtpContributingSource
dictionaries based on the
contents of the packet. The information relevant to the
RTCRtpSynchronizationSource
dictionary corresponding
to the SSRC identifier, is updated each time, and if the RTP packet
contains CSRC identifiers, then the information relevant to the
RTCRtpSynchronizationSource
dictionaries corresponding to
those CSRC identifiers is also updated.RTCRtpContributingSource
RTCRtpSynchronizationSource
and RTCRtpContributingSource
dictionaries for a
particular RTCRtpReceiver
contain information from a
single point in the RTP stream.dictionary RTCRtpContributingSource
{
required DOMHighResTimeStamp timestamp
;
required unsigned long source
;
double audioLevel
;
};
timestamp
of type DOMHighResTimeStamp, requiredThe timestamp of type DOMHighResTimeStamp [HIGHRES-TIME],
indicating the most recent time of playout of media that arrived
in an RTP packet originating from this source. The timestamp is
defined as performance.timeOrigin
+
performance.now()
at the time of playout.
source
of type unsigned long, requiredThe CSRC or SSRC identifier of the contributing or synchronization source.
audioLevel
of type doubleThis 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 present, otherwise the user agent must compute the value from the audio data (the member must never 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)
.
dictionary RTCRtpSynchronizationSource
: RTCRtpContributingSource
{
boolean voiceActivityFlag
;
};
voiceActivityFlag
of type booleanWhether the last RTP packet played 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
will be absent.
RTCRtpTransceiver
InterfaceThe
interface represents a
combination of an RTCRtpTransceiver
and an
RTCRtpSender
that share a common
RTCRtpReceiver
mid
. As defined in [JSEP] (section 3.4.1.),
an
is said to be associated with
a media description if its RTCRtpTransceiver
property is non-null; otherwise it is said to be disassociated. Conceptually, an
associated transceiver is one that's represented in the last applied session
description.mid
The transceiver kind of an
is defined by the kind of the
associated RTCRtpTransceiver
's
RTCRtpReceiver
object.MediaStreamTrack
To create an RTCRtpTransceiver with an
object, receiver,
RTCRtpReceiver
object, sender, and an
RTCRtpSender
value,
direction, run the following steps:RTCRtpTransceiverDirection
Let transceiver be a new
object.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 [[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
.
Return transceiver.
RTCDtlsTransport
and
RTCIceTransport
objects. This will only occur as part
of the process of setting an
RTCSessionDescription
.[Exposed=Window]
interface RTCRtpTransceiver
{
readonly attribute DOMString? mid
;
[SameObject]
readonly attribute RTCRtpSender
sender
;
[SameObject]
readonly attribute RTCRtpReceiver
receiver
;
readonly attribute boolean stopped
;
attribute RTCRtpTransceiverDirection
direction
;
readonly attribute RTCRtpTransceiverDirection
? currentDirection
;
void stop
();
void setCodecPreferences
(sequence<RTCRtpCodecCapability
> codecs);
};
mid
of type DOMString, readonly, nullableThe mid
attribute is the mid
negotatiated and present in the
local and remote descriptions as defined in [JSEP] (section 5.2.1. and section 5.3.1.). Before
negotiation is complete, the mid
value may be null.
After rollbacks, the value may change from a non-null value
to null.
sender
of type RTCRtpSender
, readonlyThe sender
attribute exposes the
corresponding to the RTP media
that may be sent with mid = RTCRtpSender
. On getting,
the attribute MUST return the value of the [[Sender]]
slot.mid
receiver
of type RTCRtpReceiver
, readonlyThe receiver
attribute is the
corresponding to the RTP media
that may be received with mid = RTCRtpReceiver
. On
getting the attribute MUST return the value of the
[[Receiver]] slot.mid
stopped
of type boolean, readonlyThe stopped
attribute indicates that the sender
of this transceiver will no longer send, and that the receiver
will no longer receive. It is true if either stop
has been called or if setting the local or remote description has
caused the
to be stopped. On
getting, this attribute MUST return the value of the
[[Stopped]] slot.RTCRtpTransceiver
direction
of type RTCRtpTransceiverDirection
As defined in [JSEP] (section 4.2.4.), the
direction attribute indicates the preferred direction
of this transceiver, which will be used in calls to
and createOffer
. An update
of directionality does not take effect immediately. Instead,
future calls to createAnswer
createOffer
and createAnswer
mark the corresponding media
description as sendrecv
, sendonly
,
recvonly
or inactive
as defined in
[JSEP] (section 5.2.2. and section 5.3.2.)
On getting, this attribute MUST return the value of the [[Direction]] slot.
On setting, the user agent MUST run the following steps:
Let transceiver be the
object on which the setter is
invoked.RTCRtpTransceiver
Let connection be the
object
associated with transceiver.RTCPeerConnection
If connection's [[IsClosed]] slot is
true
, throw an
InvalidStateError
.
If transceiver's [[Stopped]] slot is
true
, throw an
InvalidStateError
.
Let newDirection be the argument to the setter.
If newDirection is equal to transceiver's [[Direction]] slot, abort these steps.
Set transceiver's [[Direction]] slot to newDirection.
Update the negotiation-needed flag for connection.
currentDirection
of type RTCRtpTransceiverDirection
,
readonly, nullableAs 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
RTCRtpEncodingParameters.
since one cannot be
deduced from the other. If this transceiver has never been
represented in an offer/answer exchange, or if the transceiver is
active
, the value is null. On getting, this
attribute MUST return the value of the [[CurrentDirection]] slot.stopped
stop
The stop
method irreversibly
stops the
. The
sender of this transceiver will no longer send, the
receiver will no longer receive. Calling
RTCRtpTransceiver
stop()
updates the
negotiation-needed flag for the
RTCRtpTransceiver
's associated
.RTCPeerConnection
Stopping a transceiver will cause future calls
to createOffer
to generate a zero port
in the media description for the corresponding
transceiver, as defined in
[JSEP] (section 4.2.1.).
When this method is invoked, to stop the RTCRtpTransceiver transceiver, the user agent MUST run the following steps:
If transceiver's [[Stopped]] slot is
true
, abort these steps.
Let connection be the
object on which
the transceiver is to be stopped.RTCPeerConnection
If connection's [[IsClosed]] slot is
true
, throw an
InvalidStateError
.
Let sender be transceiver's [[Sender]].
Let receiver be transceiver's [[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.
receiver's [[ReceiverTrack]] is now said to be ended.
Set transceiver's [[Stopped]]
slot to true
.
Set transceiver's [[Receptive]]
slot to false
.
Set transceiver's [[CurrentDirection]]
slot to null
.
Update the negotiation-needed flag for connection.
When a remote description is applied with a zero
port in the media description for the corresponding
transceiver, as defined in
[JSEP] (section 4.2.2.), the user agent MUST run the
above steps as if stop
had been called.
In addition, since the
receiver's [[ReceiverTrack]]
has ended, the steps described in track ended
MUST be followed.
setCodecPreferences
The setCodecPreferences
method overrides the
default codec preferences used by the user agent. When
generating a session description using either
createOffer
or createAnswer
, the
user agent MUST use the indicated codecs, in the order
specified in the codecs argument, for the media
section corresponding to this RTCRtpTransceiver
.
This method allows applications to disable the negotiation of specific codecs. 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
createOffer
and createAnswer
that
include this RTCRtpTransceiver
until this method is
called again. Setting codecs to an empty sequence
resets codec preferences to any default value.
The codecs
sequence passed into
setCodecPreferences
can only contain codecs that are
returned by RTCRtpSender.getCapabilities(kind)
or
RTCRtpReceiver.getCapabilities(kind)
, where
kind
is the kind of the
RTCRtpTransceiver
on which the method is called.
Additionally, the RTCRtpCodecCapability
dictionary
members cannot be modified. If codecs
does not
fulfill these requirements, the user agent MUST throw an
InvalidAccessError.
Due to a recommendation in [SDP], calls to
createAnswer
SHOULD use only the common subset of
the codec preferences and the codecs that appear in the offer.
For example, if codec preferences are "C, B, A", but only codecs
"A, B" were offered, the answer should only contain codecs "B,
A". However, [JSEP] (section 5.3.1.)
allows adding codecs that were not in the offer, so
implementations can behave differently.
Together, the
attribute and
the direction
method enable
developers to implement "hold" scenarios.replaceTrack
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
interface allows an
application access to information about the Datagram Transport Layer
Security (DTLS) transport over which RTP and RTCP packets are sent and
received by RTCDtlsTransport
and
RTCRtpSender
objects, as well other data such as
SCTP packets sent and received by data channels. In particular, DTLS adds
security to an underlying transport, and the
RTCRtpReceiver
RTCDtlsTransport
interface allows access to information
about the underlying transport and the security added.
objects are constructed as a result
of calls to RTCDtlsTransport
setLocalDescription()
and
setRemoteDescription()
. Each
object represents the DTLS transport
layer for the RTP or RTCP RTCDtlsTransport
of a specific component
, or a group of
RTCRtpTransceiver
s if such a group has been
negotiated via [BUNDLE].RTCRtpTransceiver
RTCRtpTransceiver
will be represented by an existing
RTCDtlsTransport
object, whose state
will be updated accordingly,
as opposed to being represented by a new object.An
has a
[[DtlsTransportState]] internal slot initialized to RTCDtlsTransport
.new
When the underlying DTLS transport needs to update the state of the
corresponding
object, the user agent
MUST queue a task that runs the following steps:RTCDtlsTransport
Let transport be the
object to receive the state update.RTCDtlsTransport
Let newState be the new state.
Set transport's [[DtlsTransportState]] slot to newState.
Fire a simple event named
at transport.statechange
[Exposed=Window]
interface RTCDtlsTransport
: EventTarget {
readonly attribute RTCIceTransport
transport
;
readonly attribute RTCDtlsTransportState
state
;
sequence<ArrayBuffer> getRemoteCertificates
();
attribute EventHandler onstatechange
;
attribute EventHandler onerror
;
};
transport
of type RTCIceTransport
, readonlyThe transport
attribute is the underlying
transport that is used to send and receive packets. The
underlying transport may not be shared between multiple active
objects.RTCDtlsTransport
state
of type RTCDtlsTransportState
, readonlyThe state
attribute MUST, on getting, return the
value of the [[DtlsTransportState]] slot.
onstatechange
of type EventHandler
statechange
.
onerror
of type
EventHandlererror
.getRemoteCertificates
Returns the certificate chain in use by the remote side, with
each certificate encoded in binary Distinguished Encoding Rules
(DER) [X690]. getRemoteCertificates()
will return
an empty list prior to selection of the remote certificate, which
will be completed by the time
transitions to
"connected".RTCDtlsTransportState
RTCDtlsTransportState
Enumenum RTCDtlsTransportState
{
"new",
"connecting",
"connected",
"closed",
"failed"
};
Enumeration description | |
---|---|
new |
DTLS has not started negotiating yet. |
connecting |
DTLS is in the process of negotiating a secure connection and verifying the remote fingerprint. |
connected |
DTLS has completed negotiation of a secure connection and verified the remote fingerprint. |
closed |
The transport has been closed intentionally as the result of
receipt of a close_notify alert, or calling close() . |
failed |
The transport has failed as the result of an error (such as receipt of an error alert or failure to validate the remote fingerprint). |
RTCDtlsFingerprint
DictionaryThe RTCDtlsFingerprint
dictionary includes
the hash function algorithm and certificate fingerprint as described in
[RFC4572].
dictionary RTCDtlsFingerprint
{
DOMString algorithm
;
DOMString value
;
};
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
interface allows an
application access to information about the ICE transport over which
packets are sent and received. In particular, ICE manages peer-to-peer
connections which involve state which the application may want to access.
RTCIceTransport
objects are constructed as a result
of calls to RTCIceTransport
setLocalDescription()
and
setRemoteDescription()
. The underlying ICE state is managed
by the ICE agent; as such, the state of an
changes when the ICE Agent
provides indications to the user agent as described below. Each
RTCIceTransport
object represents the ICE transport
layer for the RTP or RTCP RTCIceTransport
of a specific component
, or a group of
RTCRtpTransceiver
s if such a group has been
negotiated via [BUNDLE].RTCRtpTransceiver
RTCRtpTransceiver
will be represented by an existing
RTCIceTransport
object, whose state
will be updated
accordingly, as opposed to being represented by a new object.When the ICE Agent indicates that it began gathering a
generation of candidates for an
, the
user agent MUST queue a task that runs the following steps:RTCIceTransport
Let connection be the
object associated with this
ICE Agent.RTCPeerConnection
If connection's [[IsClosed]] slot is
true
, abort these steps.
Let transport be the
for which candidate gathering began.RTCIceTransport
Set transport's [[IceGathererState]]
slot to
.gathering
Fire a simple event named
at transport.gatheringstatechange
Update the ICE gathering state of connection.
When the ICE Agent indicates that it finished gathering a
generation of candidates for an
, the
user agent MUST queue a task that runs the following steps:RTCIceTransport
Let connection be the
object associated with this
ICE Agent.RTCPeerConnection
If connection's [[IsClosed]] slot is
true
, abort these steps.
Let transport be the
for which candidate gathering finished.RTCIceTransport
Create an
instance
newCandidate, with RTCIceCandidate
and
sdpMid
set to the values associated with this
sdpMLineIndex
, with
RTCIceTransport
set to the username fragment
of the generation of candidates for which gathering finished, with
usernameFragment
set to an
empty string, and with all other nullable members set to null.candidate
Fire an ice candidate event named
with
newCandidate at connection.icecandidate
If another generation of candidates is still being gathered, abort these steps.
Set transport's [[IceGathererState]]
slot to
.complete
Fire a simple event named
at transport.gatheringstatechange
Update the ICE gathering state of connection.
When the ICE Agent indicates that a new ICE candidate is
available for an
, either by taking one
from the ICE candidate pool or
gathering it from scratch, the user agent MUST queue a task that runs the
following steps:RTCIceTransport
Let connection be the
object associated with this
ICE Agent.RTCPeerConnection
If connection's [[IsClosed]] slot is
true
, abort these steps.
Let transport be the
for which this candidate is being made available.RTCIceTransport
If connection.[[PendingLocalDescription]] is
not null
, and represents the ICE generation for
which candidate was gathered, add candidate to
the connection.[[PendingLocalDescription]].sdp.
If connection.[[CurrentLocalDescription]]
is not null
, and represents the ICE generation for
which candidate was gathered, add candidate to
the connection.[[CurrentLocalDescription]].sdp.
Create an
instance to represent
the candidate. Let newCandidate be that object.RTCIceCandidate
Add newCandidate to transport's set of local candidates.
Fire an ice candidate event named
with
newCandidate at connection.icecandidate
When the ICE Agent indicates that the
for an
RTCIceTransportState
has changed, the user agent MUST queue
a task that runs the following steps:RTCIceTransport
Let connection be the
object associated with this
ICE Agent.RTCPeerConnection
If connection's [[IsClosed]] slot is
true
, abort these steps.
Let transport be the
whose state is changing.RTCIceTransport
Let newState be the new indicated
.
RTCIceTransportState
Set transport's [[IceTransportState]] slot to newState.
Fire a simple event named
at
transport.statechange
Update the ICE connection state of connection.
Update the connection state of connection.
When the ICE Agent indicates that the selected candidate pair
for an
has changed, the user agent
MUST queue a task that runs the following steps:RTCIceTransport
Let connection be the
object associated with this
ICE Agent.RTCPeerConnection
If connection's [[IsClosed]] slot is
true
, abort these steps.
Let transport be the
whose selected candidate pair is changing.RTCIceTransport
Let newCandidatePair be a newly created
representing the indicated
pair if one is selected, and RTCIceCandidatePair
null
otherwise.
Set transport's [[SelectedCandidatePair]] slot to newCandidatePair.
Fire a simple event named
at
transport.selectedcandidatepairchange
An RTCIceTransport
object has the following internal slots:
new
new
null
[Exposed=Window]
interface RTCIceTransport
: EventTarget {
readonly attribute RTCIceRole
role
;
readonly attribute RTCIceComponent
component
;
readonly attribute RTCIceTransportState
state
;
readonly attribute RTCIceGathererState
gatheringState
;
sequence<RTCIceCandidate
> getLocalCandidates
();
sequence<RTCIceCandidate
> getRemoteCandidates
();
RTCIceCandidatePair
? getSelectedCandidatePair
();
RTCIceParameters
? getLocalParameters
();
RTCIceParameters
? getRemoteParameters
();
attribute EventHandler onstatechange
;
attribute EventHandler ongatheringstatechange
;
attribute EventHandler onselectedcandidatepairchange
;
};
role
of type RTCIceRole
, readonlyThe role
attribute MUST return the ICE role of the transport.
component
of type RTCIceComponent
, readonlyThe component
attribute MUST return the ICE component of the transport. When
RTCP mux is used, a single
transports both RTP and RTCP
and RTCIceTransport
component
is set to "RTP".
state
of type RTCIceTransportState
, readonlyThe state
attribute MUST, on getting, return the value of the
[[IceTransportState]] slot.
gatheringState
of type RTCIceGathererState
, readonlyThe gathering
state
attribute MUST, on getting, return the value
of the [[IceGathererState]] slot.
onstatechange
of type EventHandlerstatechange
, MUST be fired any time the
RTCIceTransport
state changes.
ongatheringstatechange
of type
EventHandlergatheringstatechange
, MUST be fired any time
the RTCIceTransport
gathering state
changes.
onselectedcandidatepairchange
of type
EventHandlerselectedcandidatepairchange
, MUST be fired any
time the RTCIceTransport
's selected candidate
pair changes.getLocalCandidates
Returns a sequence describing the local ICE candidates
gathered for this
and sent in
RTCIceTransport
onicecandidate
getRemoteCandidates
Returns a sequence describing the remote ICE candidates
received by this
via
RTCIceTransport
addIceCandidate()
getSelectedCandidatePair
Returns the selected candidate pair on which packets are sent. This method MUST return the value of the [[SelectedCandidatePair]] slot.
getLocalParameters
Returns the local ICE parameters received by this
via RTCIceTransport
, or
setLocalDescription
null
if the parameters have not yet been
received.
getRemoteParameters
Returns the remote ICE parameters received by this
via RTCIceTransport
or
setRemoteDescription
null
if the parameters have not yet been
received.
RTCIceParameters
Dictionarydictionary RTCIceParameters
{
DOMString usernameFragment
;
DOMString password
;
};
RTCIceParameters
MembersRTCIceCandidatePair
Dictionarydictionary RTCIceCandidatePair
{
RTCIceCandidate
local
;
RTCIceCandidate
remote
;
};
RTCIceCandidatePair
Memberslocal
of type RTCIceCandidate
The local ICE candidate.
remote
of type RTCIceCandidate
The remote ICE candidate.
RTCIceGathererState
Enumenum RTCIceGathererState
{
"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
Enumenum RTCIceTransportState
{
"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 "checking" (if there are candidate pairs remaining
to be checked) or "disconnected" (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
"failed". |
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. |
closed |
The has shut down and is
no longer responding to STUN requests. |
An ICE restart causes candidate gathering and connectity checks to
begin anew, causing a transition to connected
if begun in the
completed
state. If begun in the transient
disconnected
state, it causes a transition to
checking
, effectively forgetting that connectivity was
previously lost.
The failed
and completed
states require an
indication that there are no additional remote candidates. This can be
indicated by calling addIceCandidate
with
a candidate value whose candidate
property is set
to an empty string or by canTrickleIceCandidates
being set to
false
.
Some example state transitions are:
RTCIceTransport
first created, as a result of
setLocalDescription
or setRemoteDescription
):
new
new
, remote candidates received):
checking
checking
, found usable connection):
connected
checking
, checks fail but gathering still in
progress): disconnected
checking
, gave up): failed
disconnected
, new local candidates):
checking
connected
, finished all checks):
completed
completed
, lost connectivity):
disconnected
disconnected
or failed
, ICE restart occurs):
checking
completed
, ICE restart occurs):
connected
RTCPeerConnection.close()
: closed
RTCIceRole
Enumenum RTCIceRole
{
"controlling",
"controlled"
};
Enumeration description |
|
---|---|
controlling |
A controlling agent as defined by [ICE], Section 3. |
controlled |
A controlled agent as defined by [ICE], Section 3. |
RTCIceComponent
Enumenum RTCIceComponent
{
"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-id value 1 when encoded
in candidate-attribute . |
rtcp |
The ICE Transport is used for RTCP as defined by [ICE],
Section 4.1.1.1. This represents the component-id
value 2 when encoded in
candidate-attribute . |
RTCTrackEvent
The
event uses the
track
interface.RTCTrackEvent
Firing a
track event named e with an
receiver, a
RTCRtpReceiver
track and a
MediaStreamTrack
MediaStream
[] streams, means that an event with
the name e, which does not bubble (except where otherwise
stated) and is not cancelable (except where otherwise stated), and which
uses the
interface with the
RTCTrackEvent
attribute set to
receiver, receiver
attribute set to track, track
attribute set to streams,
MUST be created and dispatched at the given target.streams
[Constructor(DOMString type, RTCTrackEventInit
eventInitDict),
Exposed=Window]
interface RTCTrackEvent
: Event {
readonly attribute RTCRtpReceiver
receiver
;
readonly attribute MediaStreamTrack
track
;
[SameObject]
readonly attribute FrozenArray<MediaStream> streams
;
readonly attribute RTCRtpTransceiver
transceiver
;
};
RTCTrackEvent
receiver
of type RTCRtpReceiver
, readonlyThe receiver
attribute
represents the
object
associated with the event.RTCRtpReceiver
track
of type MediaStreamTrack
, readonlyThe track
attribute represents the
object that is associated
with the MediaStreamTrack
identified by
RTCRtpReceiver
receiver
.
streams
of type FrozenArray<MediaStream>,
readonlyThe streams
attribute returns an array
of MediaStream
objects representing the
MediaStream
s that this event's
track
is a part of.
transceiver
of type RTCRtpTransceiver
, readonlyThe transceiver
attribute represents the
object associated with the event.RTCRtpTransceiver
dictionary RTCTrackEventInit
: EventInit {
required RTCRtpReceiver
receiver
;
required MediaStreamTrack
track
;
sequence<MediaStream> streams
= [];
required RTCRtpTransceiver
transceiver
;
};
RTCTrackEventInit
Membersreceiver
of type RTCRtpReceiver
, requiredThe receiver
attribute represents the
object associated with the
event.RTCRtpReceiver
track
of type MediaStreamTrack
, requiredThe track
attribute represents the
object that is associated
with the MediaStreamTrack
identified by
RTCRtpReceiver
receiver
.
streams
of type sequence<MediaStream>,
defaulting to []
The streams
attribute returns an array of
MediaStream
objects representing the
MediaStream
s that this event's
track
is a part of.
transceiver
of type RTCRtpTransceiver
, requiredThe transceiver
attribute represents the
object associated with the
event.RTCRtpTransceiver
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 WebSockets [WEBSOCKETS-API].
The Peer-to-peer data API extends the
interface as described below.RTCPeerConnection
partial interface RTCPeerConnection
{
readonly attribute RTCSctpTransport
? sctp
;
RTCDataChannel
createDataChannel
(USVString label,
optional RTCDataChannelInit
dataChannelDict);
attribute EventHandler ondatachannel
;
};
sctp
of type RTCSctpTransport
, readonly,
nullableThe 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
object stored in the [[SctpTransport]]
internal slot.RTCSctpTransport
ondatachannel
of type EventHandlerdatachannel
.createDataChannel
Creates a new
object with
the given label. The RTCDataChannel
dictionary can be used to configure properties of the underlying
channel such as data reliability.RTCDataChannelInit
When the createDataChannel
method is invoked, the user agent MUST run the following
steps.
Let connection be the
object on which the
method is invoked.RTCPeerConnection
If connection's [[IsClosed]] slot is
true
, throw an
InvalidStateError
.
Create an RTCDataChannel
,
channel.
Initialize channel's [[DataChannelLabel]] slot to the value of the first argument.
TypeError
.
Let options be the second argument.
Initialize channel's [[MaxPacketLifeTime]]
slot to option's
maxPacketLifeTime
member, if present, otherwise
null
.
Initialize channel's [[MaxRetransmits]]
slot to option's maxRetransmits
member, if present, otherwise null
.
Initialize channel's [[Ordered]] slot
to option's ordered
member.
Initialize channel's
[[DataChannelProtocol]] slot to option's
protocol
member.
TypeError
.
Initialize channel's [[Negotiated]]
slot to option's negotiated
member.
Initialize channel's [[DataChannelId]]
slot to the value of option's
id
member, if it is present and
[[Negotiated]] is true, otherwise
null
.
id
member will be ignored if
the data channel is negotiated in-band; this is
intentional. Data channels negotiated in-band should have
IDs selected based on the DTLS role, as specified in
[RTCWEB-DATA-PROTOCOL].
If [[Negotiated]] is true
and
[[DataChannelId]] is null
, throw
a TypeError
.
Initialize channel's
[[DataChannelPriority]] slot to option's
priority
member.
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
createDataChannel
, or [[Negotiated]] being false),
and the DTLS role of the SCTP transport has already been
negotiated, then initialize [[DataChannelId]]
to a value generated by the
user agent, according to [RTCWEB-DATA-PROTOCOL], and skip to
the next step. If no available ID could be generated, or if
the value of the [[DataChannelId]] slot
is being used by an existing
,
throw an RTCDataChannel
OperationError
exception.
null
after this step, it will be
populated once the DTLS role is determined during the
process of
setting an RTCSessionDescription
.
Let transport be the connection's [[SctpTransport]] slot.
If the [[DataChannelId]] slot is not
null
, transport is in the
connected
state and [[DataChannelId]] is
greater or equal to the transport's
[[MaxChannels]] slot, throw an
OperationError
.
If channel is the first
created on
connection, update the
negotiation-needed flag for connection.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
interface allows an
application access to information about the SCTP data channels tied to
a particular SCTP association.RTCSctpTransport
To create an
with an
optional initial state, initialState, run the following
steps:RTCSctpTransport
Let transport be a new
object.RTCSctpTransport
Let transport have a
[[SctpTransportState]] internal slot initialized to
initialState, if provided, otherwise
"new"
.
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
run the following
steps:RTCSctpTransport
Let transport be the
object to be updated.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
has been established, run the following
steps:
RTCSctpTransport
Let transport be the
object.RTCSctpTransport
Let connection be the
object associated with
transport.RTCPeerConnection
Set [[MaxChannels]] to the minimum of the negotiated amount of incoming and outgoing SCTP streams.
Fire a simple event named
at
transport.statechange
For each of connection's
:RTCDataChannel
Let channel be the
object.RTCDataChannel
If the channel's [[DataChannelId]] slot is greater or equal to transport's [[MaxChannels]] slot, close the channel due to a failure . Otherwise, announce the channel as open.
[Exposed=Window]
interface RTCSctpTransport
{
readonly attribute RTCDtlsTransport
transport
;
readonly attribute RTCSctpTransportState
state
;
readonly attribute unrestricted double maxMessageSize
;
readonly attribute unsigned short? maxChannels
;
attribute EventHandler onstatechange
;
};
transport
of type RTCDtlsTransport
, readonlyThe transport over which all SCTP packets for data channels will be sent and received.
state
of type RTCSctpTransportState
, readonlyThe 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
's RTCDataChannel
send()
method. The attribute MUST,
on getting, return the value of the [[MaxMessageSize]]
slot.
maxChannels
of type
unsigned short
, readonly, nullableThe maximum amount of
's
that can be used simultaneously. The attribute MUST, on
getting, return the value of the [[MaxChannels]] slot.
RTCDataChannel
null
until the SCTP transport went into the
connected
state.
onstatechange
of type EventHandlerThe event type of this event handler is
.statechange
RTCSctpTransportState
EnumRTCSctpTransportState
indicates the state of the SCTP
transport.
enum RTCSctpTransportState
{
"new",
"connecting",
"connected",
"closed"
};
Enumeration description | |
---|---|
new |
The |
connecting |
The |
connected |
The |
closed |
The SCTP association has been closed intentionally (such as by closing the peer connection or applying a remote description that rejects data or changes the SCTP port) or via receipt of a SHUTDOWN or ABORT chunk. |
RTCDataChannel
The
interface represents a
bi-directional data channel between two peers. An
RTCDataChannel
is created via a factory method on an
RTCDataChannel
object. The messages sent between
the browsers are described in [RTCWEB-DATA] and
[RTCWEB-DATA-PROTOCOL].RTCPeerConnection
There are two ways to establish a connection with
. The first way is to simply create an
RTCDataChannel
at one of the peers with the
RTCDataChannel
negotiated
dictionary member unset or set to
its default value false. This will announce the new channel in-band and
trigger an RTCDataChannelInit
with the corresponding
RTCDataChannelEvent
object at the other peer. The second
way is to let the application negotiate the
RTCDataChannel
. To do this, create an
RTCDataChannel
object with the RTCDataChannel
negotiated
dictionary member set to true, and
signal out-of-band (e.g. via a web server) to the other side that it
SHOULD create a corresponding RTCDataChannelInit
with the
RTCDataChannel
negotiated
dictionary member set to true and
the same RTCDataChannelInit
. This will
connect the two separately created id
objects. The second way makes it possible to create channels with
asymmetric properties and to create channels in a declarative way by
specifying matching RTCDataChannel
s.id
Each
has an associated
underlying data transport that is
used to transport actual data to the other peer. In the case of SCTP
data channels utilizing an RTCDataChannel
(which
represents the state of the SCTP association), the underlying data
transport is the SCTP stream pair. The transport properties of
the underlying data transport, such as in order delivery
settings and reliability mode, are configured by the peer as the channel
is created. The properties of a channel cannot change after the channel
has been created. The actual wire protocol between the peers is specified
by the WebRTC DataChannel Protocol specification [RTCWEB-DATA].RTCSctpTransport
An
can be configured to operate in
different reliability modes. A reliable channel ensures that the data is
delivered at the other peer through retransmissions. An unreliable
channel is configured to either limit the number of retransmissions (
RTCDataChannel
) or set
a time during which transmissions (including retransmissions) are allowed
( maxRetransmits
).
These properties can not be used simultaneously and an attempt to do so
will result in an error. Not setting any of these properties results in a
reliable channel.maxPacketLifeTime
An
, created with RTCDataChannel
or dispatched via an
createDataChannel
, MUST initially be in the
RTCDataChannelEvent
connecting
state. When the
object's underlying data
transport is ready, the user agent MUST announce the
RTCDataChannel
RTCDataChannel
as open.
To create an
, run the
following steps:RTCDataChannel
Let channel be a newly created
object.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]], [[DataChannelId]], and [[DataChannelPriority]].
Return channel.
When the user agent is to announce an RTCDataChannel
as
open, the user agent MUST queue a task to run the following
steps:
If the associated
object's
[[IsClosed]] slot is RTCPeerConnection
true
, abort these steps.
Let channel be the
object to be announced.RTCDataChannel
If channel's [[ReadyState]] is closing
or
closed
, abort these steps.
Set channel's [[ReadyState]] slot to
open
.
Fire a simple event named
at
channel.open
When an underlying data transport is to be announced (the other
peer created a channel with
unset or set to false), the
user agent of the peer that did not initiate the creation process MUST
queue a task to run the following steps:negotiated
If the associated
object's
[[IsClosed]] slot is RTCPeerConnection
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's [[DataChannelLabel]], [[Ordered]], [[MaxPacketLifeTime]], [[MaxRetransmits]], [[DataChannelProtocol]], and [[DataChannelId]] internal slots to the corresponding values in configuration.
Initialize channel's [[Negotiated]] internal
slot to false
.
Initialize channel's [[DataChannelPriority]] internal slot based on the integer priority value in configuration, according to the following mapping:
configuration priority value | value |
---|---|
0 to 128 |
|
129 to 256 |
|
257 to 512 |
|
513 and greater |
|
Set channel's [[ReadyState]] to
open
(but do not fire the
event, yet).open
datachannel
event handler prior to the
open
event being fired.Fire a datachannel event named
with channel at the
datachannel
object.RTCPeerConnection
An
object's underlying data
transport may be torn down in a non-abrupt manner by running the
closing procedure. When
that happens the user agent MUST queue a task to run the following
steps:RTCDataChannel
Let channel be the
object whose transport was
closed.RTCDataChannel
Unless the procedure was initiated by the channel's
method, set
channel's [[ReadyState]] slot to
close
closing
.
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 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
object's underlying data
transport has been closed, the
user agent MUST queue a task to run the following steps:RTCDataChannel
Let channel be the
object whose transport was
closed.RTCDataChannel
Set channel's [[ReadyState]] slot to
closed
.
If the transport was closed
with an error, fire
an RTCError
event at channel with
errorDetail
set to "sctp-failure".
Fire a simple event named
at
channel.close
In some cases, the user agent may be unable to create an
's underlying data transport.
For example, the data channel's RTCDataChannel
may be outside the range negotiated by the
[RTCWEB-DATA] implementations in the SCTP handshake. When the user
agent determines that an id
's
underlying data transport cannot be created, the user agent MUST
queue a task to run the following steps:RTCDataChannel
Let channel be the
object for which the user agent could not create an underlying
data transport.RTCDataChannel
Set channel's [[ReadyState]] slot to
closed
.
Fire an RTCError
event at channel with
errorDetail
set to "data-channel-failure".
Fire a simple event named
at
channel.close
When an
message has been received via
the underlying data transport with type type and data
rawData, the user agent MUST queue a task to run the following
steps:RTCDataChannel
Let channel be the
object for which the user agent has received a message.RTCDataChannel
If channel's [[ReadyState]] slot is not
open
, abort these steps and discard rawData.
Execute the sub step by switching on type and the
channel's 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
is "blob"
:
Let data be a new Blob
object
containing rawData as its raw data source.
If type indicates that rawData is binary
and binaryType
is "arraybuffer"
:
Let data be a new ArrayBuffer
object
containing rawData as its raw data source.
Fire an event named
at
channel with the message
origin
attribute initialized
to the origin of the document that created the channel's
associated RTCPeerConnection
, and the data
attribute initialized to data.
[Exposed=Window]
interface RTCDataChannel
: EventTarget {
readonly attribute USVString label
;
readonly attribute boolean ordered
;
readonly attribute unsigned short? maxPacketLifeTime
;
readonly attribute unsigned short? maxRetransmits
;
readonly attribute USVString protocol
;
readonly attribute boolean negotiated
;
readonly attribute unsigned short? id
;
readonly attribute RTCPriorityType
priority
;
readonly attribute RTCDataChannelState
readyState
;
readonly attribute unsigned long bufferedAmount
;
attribute unsigned long bufferedAmountLowThreshold
;
attribute EventHandler onopen
;
attribute EventHandler onbufferedamountlow
;
attribute EventHandler onerror
;
attribute EventHandler onclose
;
void close
();
attribute EventHandler onmessage
;
attribute DOMString binaryType
;
void send
(USVString data);
void send
(Blob data);
void send
(ArrayBuffer data);
void send
(ArrayBufferView data);
};
label
of type USVString, readonlyThe label
attribute represents a label that can be used to distinguish this
object from other
RTCDataChannel
objects. Scripts are allowed
to create multiple RTCDataChannel
objects
with the same label. On getting, the attribute MUST return the
value of the [[DataChannelLabel]] slot.RTCDataChannel
ordered
of type boolean, readonlyThe ordered
attribute
returns true if the
is
ordered, and false if other of order delivery is allowed. On
getting, the attribute MUST return the value of the [[Ordered]] slot.RTCDataChannel
maxPacketLifeTime
of type unsigned short, readonly,
nullableThe maxPacketLifeTime
attribute returns the length of the time window (in milliseconds)
during which transmissions and retransmissions may occur in
unreliable mode. On getting, the attribute MUST return the value
of the [[MaxPacketLifeTime]]
slot.
maxRetransmits
of type unsigned short, readonly,
nullableThe maxRetransmits
attribute returns the maximum number of retransmissions that are
attempted in unreliable mode. On getting, the attribute MUST
return the value of the [[MaxRetransmits]] slot.
protocol
of type USVString, readonlyThe protocol
attribute
returns the name of the sub-protocol used with this
. On getting, the attribute MUST
return the value of the [[DataChannelProtocol]]
slot.RTCDataChannel
negotiated
of type boolean, readonlyThe negotiated
attribute returns true if this
was negotiated by the application, or false otherwise. On getting,
the attribute MUST return the value of the [[Negotiated]] slot.RTCDataChannel
id
of type unsigned short, readonly, nullableThe id
attribute returns the ID for this
. The value is initally null,
which is what will be returned
if the ID was not provided at channel creation time, and the DTLS
role of the SCTP transport has not yet been negotiated.
Otherwise, it will return the ID that was either selected by the
script or generated by the user agent according to
[RTCWEB-DATA-PROTOCOL]. After the ID is set to a non-null
value, it will not change. On getting, the attribute MUST return
the value of the [[DataChannelId]] slot.RTCDataChannel
priority
of type RTCPriorityType
, readonlyThe priority
attribute returns the priority for
this
. The priority is assigned
by the user agent at channel creation time. On getting, the
attribute MUST return the value of the
[[DataChannelPriority]] slot.RTCDataChannel
readyState
of type RTCDataChannelState
, readonlyThe readyState
attribute represents the state of the RTCDataChannel
object. On getting, the attribute MUST return the value
of the [[ReadyState]] slot.
bufferedAmount
of type unsigned long, readonlyThe bufferedAmount
attribute MUST, on getting, return the value of the
[[BufferedAmount]] slot. The attribute exposes the number
of bytes of application data
(UTF-8 text and binary data) that have been queued using
send()
. Even
though the data transmission can occur in parallel, the returned
value MUST NOT be decreased before the current task yielded back
to the event loop to prevent race conditions.
The value does not include framing overhead incurred by the
protocol, or buffering done by the operating system or network
hardware. The value of the [[BufferedAmount]] slot will
only increase with each call to the send()
method as long as the
[[ReadyState]] slot is open
; however, the
slot does not reset to zero once the channel closes. When the
underlying data transport sends data from its queue, the
user agent MUST queue a task that reduces
[[BufferedAmount]] with the number of bytes that was
sent.
bufferedAmountLowThreshold
of type unsigned longThe bufferedAmountLowThreshold
attribute sets the threshold at which the
is considered to be
low. When the bufferedAmount
decreases from above
this threshold to equal or below it, the bufferedAmount
event fires. The bufferedamountlow
is
initially zero on each new bufferedAmountLowThreshold
,
but the application may change its value at any time.RTCDataChannel
onopen
of type EventHandleropen
.onbufferedamountlow
of type
EventHandlerbufferedamountlow
.onerror
of type EventHandlerThe event type of this event handler is
.
RTCErrorEvent
errorDetail
contains "sctp-failure",
sctpCauseCode
contains the SCTP
Cause Code value, and message
contains the SCTP Cause-Specific-Information,
possibly with additional text.
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
attribute MUST, on getting, return the value to which it was
last set. On setting, if the new value is either the string
"blob"
or the string "arraybuffer"
,
then set the IDL attribute to this new value. Otherwise,
throw a SyntaxError
. When an
object is
created, the RTCDataChannel
attribute MUST be
initialized to the string "binaryType
blob
".
This attribute controls how binary data is exposed to scripts. See the [WEBSOCKETS-API] for more information.
close
Closes the
. It may be
called regardless of whether the
RTCDataChannel
object was created by this
peer or the remote peer.RTCDataChannel
When the close
method is called, the user agent
MUST run the following steps:
Let channel be the
object which is about to
be closed.RTCDataChannel
If channel's [[ReadyState]] slot is
closing
or closed
, then abort these
steps.
Set channel's [[ReadyState]] slot to
closing
.
If the closing procedure
has not
started yet, start it.
send
Run the steps described by the send()
algorithm with argument type
string
object.
send
Run the steps described by the send()
algorithm with argument type
Blob
object.
send
Run the steps described by the send()
algorithm with argument type
ArrayBuffer
object.
send
Run the steps described by the send()
algorithm with argument type
ArrayBufferView
object.
dictionary RTCDataChannelInit
{
boolean ordered
= true;
unsigned short maxPacketLifeTime
;
unsigned short maxRetransmits
;
USVString protocol
= "";
boolean negotiated
= false;
[EnforceRange]
unsigned short id
;
RTCPriorityType
priority
= "low";
};
RTCDataChannelInit
Membersordered
of type boolean, defaulting to
true
If set to false, data is allowed to be delivered out of order. The default value of true, guarantees that data will be delivered in order.
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
false
The default value of false tells the user agent to announce
the channel in-band and instruct the other peer to dispatch a
corresponding
object. If set
to true, it is up to the application to negotiate the channel and
create an RTCDataChannel
object with the same
RTCDataChannel
at the other
peer.id
id
of type unsigned shortOverrides the default selection of ID for this channel.
priority
of type RTCPriorityType
, defaulting to
low
Priority of this channel.
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
object on which data is to be sent.RTCDataChannel
If channel's [[ReadyState]] slot is not
open
, throw an
InvalidStateError
.
Execute the sub step that corresponds to the type of the methods argument:
string
object:
Let data be a byte buffer that represents the result of encoding the method's argument as UTF-8.
Blob
object:
Let data be the raw data represented by the
Blob
object.
ArrayBuffer
object:
Let data be the data stored in the buffer described
by the ArrayBuffer
object.
ArrayBufferView
object:
Let data be the data stored in the section of the
buffer described by the ArrayBuffer
object that the
ArrayBufferView
object references.
TypeError
. This includes
null
and undefined
.If the byte size of data exceeds the value of
on
channel's associated maxMessageSize
RTCSctpTransport
,
throw a TypeError
.
Queue data for transmission on channel's
underlying data transport. If queuing data is not
possible because not enough buffer space is available, throw
an OperationError
.
onerror
.Increase the value of the [[BufferedAmount]] slot by the byte size of data.
enum RTCDataChannelState
{
"connecting",
"open",
"closing",
"closed"
};
RTCDataChannelState Enumeration description |
|
---|---|
connecting |
The user agent is attempting to establish the underlying
data transport. This is the initial state of an
|
open |
The underlying data transport is established and communication is possible. |
closing |
The |
closed |
The underlying data transport has been
|
RTCDataChannelEvent
The
event uses the
datachannel
interface.RTCDataChannelEvent
Firing a datachannel event named
e with an
channel means that an event with the name e, which
does not bubble (except where otherwise stated) and is not cancelable
(except where otherwise stated), and which uses the
RTCDataChannel
interface with the
RTCDataChannelEvent
attribute set
to channel, MUST be created and dispatched at the given
target.channel
[Constructor(DOMString type, RTCDataChannelEventInit
eventInitDict),
Exposed=Window]
interface RTCDataChannelEvent
: Event {
readonly attribute RTCDataChannel
channel
;
};
RTCDataChannelEvent
channel
of type RTCDataChannel
, readonlyThe channel
attribute represents the
object associated with the event.RTCDataChannel
dictionary RTCDataChannelEventInit
: EventInit {
required RTCDataChannel
channel
;
};
RTCDataChannelEventInit
Memberschannel
of type RTCDataChannel
, requiredThe
object to be announced
by the event.RTCDataChannel
An
object MUST not be garbage
collected if itsRTCDataChannel
[[ReadyState]] slot is
connecting
and at least one event listener is registered
for open
events, message
events,
error
events, or close
events.
[[ReadyState]] slot is
open
and at least one event listener is registered for
message
events, error
events, or
close
events.
[[ReadyState]] slot is
closing
and at least one event listener is registered
for error
events, or close
events.
underlying data transport is established and data is queued to be transmitted.
This section describes an interface on
to send DTMF (phone keypad) values across an
RTCRtpSender
. Details of how DTMF is sent to the
other peer are described in [RTCWEB-AUDIO].RTCPeerConnection
The Peer-to-peer DTMF API extends the
interface as described below.RTCRtpSender
partial interface RTCRtpSender
{
readonly attribute RTCDTMFSender
? dtmf
;
};
dtmf
of type RTCDTMFSender
, readonly, nullableOn getting, the dtmf
attribute returns the value
of the [[Dtmf]]internal slot, which represents a
which can be used to send DTMF, or
null if unset. The [[Dtmf]]internal slot is set
when the kind of an RTCDTMFSender
's
[[SenderTrack]] is RTCRtpSender
"audio"
.
RTCDTMFSender
To create an RTCDTMFSender
, the user agent MUST
run the following steps:
Let dtmf be a newly created
object.RTCDTMFSender
Let dtmf have a [[CanInsertDtmf]]
internal slot, initialized to false
.
Let dtmf have a [[Duration]] internal slot.
Let dtmf have a [[InterToneGap]] internal slot.
Let dtmf have a [[ToneBuffer]] internal slot.
[Exposed=Window]
interface RTCDTMFSender
: EventTarget {
void insertDTMF
(DOMString tones,
optional unsigned long duration = 100,
optional unsigned long interToneGap = 70);
attribute EventHandler ontonechange
;
readonly attribute boolean canInsertDTMF
;
readonly attribute DOMString toneBuffer
;
};
ontonechange
of type EventHandlerThe event type of this event handler is
.tonechange
canInsertDTMF
of type boolean, readonlyWhether the RTCDTMFSender
is capable of sending DTMF.
toneBuffer
of type DOMString, readonlyThe toneBuffer
attribute MUST return a list of the tones remaining to be played
out. For the syntax, content, and interpretation of this list,
see
.insertDTMF
insertDTMF
An
object's RTCDTMFSender
insertDTMF
method is used to send DTMF tones.
The tones parameter is treated as a series of characters. The characters 0 through 9, A through D, #, and * generate the associated DTMF tones. The characters a to d MUST be normalized to uppercase on entry and are equivalent to A to D. As noted in [RTCWEB-AUDIO] Section 3, support for the characters 0 through 9, A through D, #, and * are required. The character ',' MUST be supported, and indicates a delay of 2 seconds before processing the next character in the tones parameter. All other characters (and only those other characters) MUST be considered unrecognized.
The duration parameter indicates the duration in ms to use for each character passed in the tones parameters. The duration cannot be more than 6000 ms or less than 40 ms. The default duration is 100 ms for each tone.
The interToneGap parameter indicates the gap between tones in ms. The user agent clamps it to at least 30 ms and at most 6000 ms. The default value is 70 ms.
The browser MAY increase the duration and interToneGap times to cause the times that DTMF start and stop to align with the boundaries of RTP packets but it MUST not increase either of them by more than the duration of a single RTP audio packet.
When the insertDTMF()
method is invoked,
the user agent MUST run the following steps:
RTCRtpSender
used to send DTMF.Let transceiver be the
object associated with
sender.RTCRtpTransceiver
true
, throw an
InvalidStateError
.recvonly
or inactive
,
throw an InvalidStateError
.RTCDTMFSender
associated with sender.false
, throw an InvalidStateError
.InvalidCharacterError
.
duration
parameter.interToneGap
parameter.duration
parameter is less than 40 ms,
set dtmf's [[Duration]] slot to 40 ms.duration
parameter is greater than 6000 ms,
set dtmf's [[Duration]] slot to 6000 ms.interToneGap
parameter is less than 30 ms,
set dtmf's [[InterToneGap]] slot to 30 ms.interToneGap
parameter is greater than 6000 ms,
set dtmf's [[InterToneGap]] slot to 6000 ms.true
, abort these steps.recvonly
or inactive
,
abort these steps.tonechange
with an empty string at the RTCDTMFSender
object and abort these steps.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.tonechange
with a string
consisting of tone at the
RTCDTMFSender
object.Since insertDTMF
replaces the tone
buffer, in order to add to the DTMF tones being played,
it is necessary to call insertDTMF
with a
string containing both the remaining tones (stored in the
[[ToneBuffer]] slot) and the new tones appended
together. Calling
with an empty tones
parameter can be used to cancel all tones queued to play after
the currently playing tone.insertDTMF
RTCDTMFToneChangeEvent
The
event uses the
tonechange
interface.RTCDTMFToneChangeEvent
Firing a tonechange event named
e with a DOMString
tone means
that an event with the name e, which does not bubble (except
where otherwise stated) and is not cancelable (except where otherwise
stated), and which uses the
interface with the RTCDTMFToneChangeEvent
attribute set to
tone, MUST be created and dispatched at the given target.tone
[Constructor(DOMString type, RTCDTMFToneChangeEventInit
eventInitDict),
Exposed=Window]
interface RTCDTMFToneChangeEvent
: Event {
readonly attribute DOMString tone
;
};
RTCDTMFToneChangeEvent
tone
of type DOMString, readonlyThe tone
attribute contains the
character for the tone (including ",") that has just
begun playout (see insertDTMF
). If
the value is the empty string, it indicates that the
[[ToneBuffer]] slot is an empty string and that
the previous tones have completed playback.
dictionary RTCDTMFToneChangeEventInit
: EventInit {
required DOMString tone
;
};
RTCDTMFToneChangeEventInit
Memberstone
of type DOMStringThe tone
attribute contains the
character for the tone (including ",") that has just
begun playout (see insertDTMF
). If
the value is the empty string, it indicates that the
[[ToneBuffer]] slot is an empty string and that
the previous tones have completed playback.
The basic statistics model is that the browser maintains a set of statistics for monitored 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
object on which the stats request was issued. The calling Web application
provides the selector to the RTCPeerConnection
getStats()
method and the browser emits
(in the JavaScript) a set of statistics that are relevant to the selector,
according to the stats selection algorithm. Note that that
algorithm takes the sender or receiver of a selector.
The statistics returned are designed in such a way that repeated
queries can be linked by the RTCStats
id
dictionary member. Thus, a Web application can make
measurements over a given time period by requesting measurements at the
beginning and end of that period.
Stats objects may have a limited lifetime. Until the end of their lifetime, they are always present in the result from getStats(). When their lifetime ends, a record of the statistics for that object is emitted through a "statsended" event, containing an RTCStats dictionary. The object descriptions in [WEBRTC-STATS] describe the lifetime of each stats object type.
The Statistics API extends the
interface as described below.RTCPeerConnection
partial interface RTCPeerConnection
{
Promise<RTCStatsReport
> getStats(optional MediaStreamTrack
? selector = null);
attribute EventHandler onstatsended
;
};
onstatsended
of type
EventHandlerThe event type of this event handler
is
.
statsended
To delete stats for a set of monitored objects, the UA MUST queue a task to run the following steps:
RTCStatsEvent
called e, with its name set to
"statsended" and its "report" being set to report
getStats
Gathers stats for the given selector and reports the result asynchronously.
When the
getStats()
method is invoked, the user agent
MUST run the following steps:
Let selectorArg be the method's first argument.
Let connection be the
object on which
the method was invoked.RTCPeerConnection
If selectorArg is null
, let
selector be null
.
If selectorArg is a MediaStreamTrack
let selector be an RTCRtpSender
or
RTCRtpReceiver
on connection which
track
member matches selectorArg.
If no such sender or receiver exists, or if more than one
sender or receiver fit this criteria, return a promise
rejected with a newly
created
InvalidAccessError
.
Let p be a new promise.
Run the following steps in parallel:
Gather the stats indicated by selector according to the stats selection algorithm.
Resolve p with the resulting
object, containing
the gathered stats.RTCStatsReport
Return p.
RTCStatsReport
ObjectThe getStats()
method
delivers a successful result in the form of an
object. An
RTCStatsReport
object is a map between strings that
identify the inspected objects (RTCStatsReport
attribute in id
RTCStats
instances), and their corresponding
-derived
dictionaries.RTCStats
An
may be composed of several
RTCStatsReport
-derived dictionaries, each reporting stats
for one underlying object that the implementation thinks is relevant for
the selector. One achieves the total for the selector by
summing over all the stats of a certain type; for instance, if an
RTCStats
RTCRtpSender
uses multiple SSRCs to carry its track over the
network, the
may contain one
RTCStatsReport
RTCStats
-derived dictionary per SSRC (which can be
distinguished by the value of the "ssrc" stats attribute).
[Exposed=Window]
interface RTCStatsReport
{
readonly maplike<DOMString, object>;
};
This interface has "entries", "forEach", "get", "has", "keys",
"values", @@iterator methods and a "size" getter brought by
readonly maplike
.
Use these to retrieve the various dictionaries descended from
that this stats report is composed of. The
set of supported property names [WEBIDL-1] is defined as the ids of
all the RTCStats
-derived dictionaries that have
been generated for this stats report.RTCStats
RTCStats
DictionaryAn RTCStats
dictionary represents the stats object
constructed by inspecting a specific monitored object.
The RTCStats
dictionary is a base type that specifies
as set of default attributes, such as timestamp
and type
. Specific
stats are added by extending the RTCStats
dictionary.
Note that while stats names are standardized, any given implementation may be using experimental values or values not yet known to the Web application. Thus, applications MUST be prepared to deal with unknown stats.
Statistics need to be synchronized with each other in order to yield
reasonable values in computation; for instance, if "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
-derived dictionary.RTCStats
dictionary RTCStats
{
required DOMHighResTimeStamp timestamp
;
required RTCStatsType type
;
required DOMString id
;
};
RTCStats
Memberstimestamp
of type DOMHighResTimeStampThe timestamp
, of type
DOMHighResTimeStamp
[HIGHRES-TIME], associated
with this object. The time is relative to the UNIX epoch (Jan 1,
1970, UTC). For statistics that came from a remote source (e.g.,
from received RTCP packets), timestamp
represents
the time at which the information arrived at the local endpoint.
The remote timestamp can be found in an additional field in an
-derived dictionary, if
applicable.RTCStats
type
of type RTCStatsTypeThe type of this object.
The type
attribute MUST be initialized
to the name of the most specific type this
dictionary represents.RTCStats
id
of type DOMStringA unique id
that is associated with
the object that was inspected to produce this
object. Two
RTCStats
objects, extracted from two
different RTCStats
objects, MUST have
the same id if they were produced by inspecting the same
underlying object. User agents are free to pick any format for
the id as long as it meets the requirements above.RTCStatsReport
The set of valid values for RTCStatsType
, and the dictionaries derived
from RTCStats that they indicate, are documented in
[WEBRTC-STATS].
RTCStatsEvent
The
event uses
the statsended
.RTCStatsEvent
[Constructor(DOMString type, RTCStatsEventInit
eventInitDict),
Exposed=Window]
interface RTCStatsEvent
: Event {
readonly attribute RTCStatsReport
report
;
};
RTCStatsEvent
report
of
type RTCStatsReport
The report
attribute contains the stats objects of the appropriate
subclass of
object giving the value of the statistics for the monitored objects
whose lifetime have ended, at the time that it ended.RTCStats
dictionary RTCStatsEventInit
: EventInit {
required RTCStatsReport
report
;
};
RTCStatsEventInit
membersreport
of
type RTCStatsReport
,
requiredContains the
objects giving the
stats for the objects whose lifetime have ended.RTCStats
The stats selection algorithm is as follows:
null
, gather stats for the
whole connection, add them to result, return
result, and abort these steps.
RTCRtpSender
, gather stats for
and add the following objects to result:
RTCOutboundRTPStreamStats
objects representing RTP
streams being sent by selector.
RTCOutboundRTPStreamStats
objects added.
RTCRtpReceiver
, gather stats
for and add the following objects to result:
RTCInboundRTPStreamStats
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 types when the corresponding objects exist on a PeerConnection, with the attributes that are listed when they are valid for that object:
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() {
try {
const sender = pc.getSenders()[0];
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 (let 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) {
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);
}
}
WebRTC offers and answers (and hence the channels established by
objects) can be authenticated by
using a web-based Identity Provider (IdP). The idea is that the entity
sending an offer or answer acts as the Authenticating Party (AP) and
obtains an identity assertion from the IdP which it attaches to the
session description. The consumer of the session description (i.e., the
RTCPeerConnection
on which
RTCPeerConnection
setRemoteDescription
is called) acts as the Relying Party
(RP) and verifies the assertion.
The interaction with the IdP is designed to decouple the browser from any particular identity provider; the browser need only know how to load the IdP's JavaScript, the location of which is determined by the IdP's identity, and the generic interface to generating and validating assertions. The IdP provides whatever logic is necessary to bridge the generic protocol to the IdP's specific requirements. Thus, a single browser can support any number of identity protocols, including being forward compatible with IdPs which did not exist at the time the browser was written.
An IdP is used to generate an identity assertion as follows:
setIdentityProvider()
method has been called,
the IdP provided shall be used.setIdentityProvider()
method has not been
called, then the user agent MAY use an IdP configured into the
browser.In order to verify assertions, the IdP domain name and protocol are
taken from the domain
and protocol
fields of
the identity assertion.
In order to communicate with the IdP, the user agent loads the IdP
JavaScript from the IdP. The URI for the IdP script is a well-known URI
formed from the domain
and protocol
fields, as specified
in [RTCWEB-SECURITY-ARCH].
The IdP MAY generate an HTTP redirect to another "https" origin, the browser MUST treat a redirect to any other scheme as a fatal error.
The user agent instantiates an isolated interpreted context, a JavaScript realm that operates in the origin of the loaded JavaScript. Note that a redirect will change the origin of the loaded script.
The realm is populated with a global that implements both the
RTCIdentityProviderGlobalScope
and
WorkerGlobalScope
[WEBWORKERS] interfaces.
The user agent provides an instance of
named
rtcIdentityProvider in the global scope of the realm.
This object is used by the IdP to interact with the user agent.RTCIdentityProviderRegistrar
[Global,
Exposed=RTCIdentityProviderGlobalScope]
interface RTCIdentityProviderGlobalScope
: WorkerGlobalScope {
readonly attribute RTCIdentityProviderRegistrar
rtcIdentityProvider
;
};
rtcIdentityProvider
of type
RTCIdentityProviderRegistrar
,
readonlyRTCIdentityProvider
instance with the
browser.An environment that mimics the identity provider realm can be provided by any script. However, only scripts running in the origin of the IdP are able to generate an identical environment. Other origins can load and run the IdP proxy code, but they will be unable to replicate data that is unique to the origin of the IdP.
This means that it is critical that an IdP use data that is restricted to its own origin when generating identity assertions. Otherwise, another origin could load the IdP script and use it to impersonate users.
The data that the IdP script uses could be stored on the client (for example, in [INDEXEDDB]) or loaded from servers. Data that is acquired from a server SHOULD require credentials and be protected from cross-origin access.
There is no risk to the integrity of identity assertions if an IdP validates an identity assertion without using origin-private data.
An IdP proxy implements the
methods, which are the means by which the user agent is able to request
that an identity assertion be generated or validated.RTCIdentityProvider
Once instantiated, the IdP script is executed. The IdP MUST call the
register()
function on the
RTCIdentityProviderRegistrar
instance during script
execution. If an IdP is not registered during this script execution, the
user agent cannot use the IdP proxy and MUST fail any future attempt to
interact with the IdP.
[Exposed=RTCIdentityProviderGlobalScope]
interface RTCIdentityProviderRegistrar
{
void register
(RTCIdentityProvider
idp);
};
register
This method is invoked by the IdP when its script is first
executed. This registers
methods with the user agent.RTCIdentityProvider
The callback functions in RTCIdentityProvider
are
exposed by identity providers and is called by
RTCPeerConnection
to acquire or validate identity
assertions.
dictionary RTCIdentityProvider
{
required GenerateAssertionCallback
generateAssertion
;
required ValidateAssertionCallback
validateAssertion
;
};
RTCIdentityProvider
MembersgenerateAssertion
of type
GenerateAssertionCallback
,
requiredA user agent invokes this method on the IdP to request the generation of an identity assertion.
The IdP provides a promise that resolves to an
to successfully
generate an identity assertion. Any other value, or a rejected
promise, is treated as an error.RTCIdentityAssertionResult
validateAssertion
of type
ValidateAssertionCallback
,
requiredA user agent invokes this method on the IdP to request the validation of an identity assertion.
The IdP returns a Promise that resolves to an
to successfully
validate an identity assertion and to provide the actual
identity. Any other value, or a rejected promise, is treated as
an error.RTCIdentityValidationResult
callback GenerateAssertionCallback
= Promise<RTCIdentityAssertionResult
> (DOMString contents,
DOMString origin,
RTCIdentityProviderOptions
options);
GenerateAssertionCallback
Parameterscontents
of type DOMStringcontents
as opaque string. A
successful validation of the provided assertion MUST produce the
same string.origin
of type DOMStringRTCPeerConnection
that triggered this
request. An IdP can use this information as input to policy
decisions about use. This value is generated by the user
agent based on the origin of the document that created the
RTCPeerConnection
and therefore can be trusted to
be correct.
options
of type RTCIdentityProviderOptions
setIdentityProvider
. Though the
dictionary is an optional argument to
setIdentityProvider
, default values are used
as necessary when passing the value to the identity provider; see
the definition of RTCIdentityProviderOptions
for details.callback ValidateAssertionCallback
= Promise<RTCIdentityValidationResult
> (DOMString assertion,
DOMString origin);
ValidateAssertionCallback
Parametersassertion
of type DOMStringa=identity
in the session
description; that is, the value that was part of the
RTCIdentityAssertionResult
provided by the
IdP that generated the assertion.origin
of type DOMStringRTCPeerConnection
that triggered this
request. An IdP can use this information as input to policy
decisions about use.dictionary RTCIdentityAssertionResult
{
required RTCIdentityProviderDetails
idp
;
required DOMString assertion
;
};
RTCIdentityAssertionResult
Membersidp
of type RTCIdentityProviderDetails
,
requiredAn IdP provides these details to identify the IdP that
validates the identity assertion. This struct contains the same
information that is provided to
setIdentityProvider
.
assertion
of type DOMString, requiredAn identity assertion. This is an opaque string that MUST contain all information necessary to assert identity. This value is consumed by the validating IdP.
dictionary RTCIdentityProviderDetails
{
required DOMString domain
;
DOMString protocol
= "default";
};
RTCIdentityProviderDetails
Membersdomain
of type DOMString, requiredThe domain name of the IdP that validated the associated identity assertion.
protocol
of type DOMString, defaulting to
"default"
The protocol parameter used for the IdP. The string
MUST NOT include the character '/'
or
'\'
.
dictionary RTCIdentityValidationResult
{
required DOMString identity
;
required DOMString contents
;
};
RTCIdentityValidationResult
Membersidentity
of type DOMString, requiredThe validated identity of the peer.
contents
of type DOMString, requiredThe payload of the identity assertion. An IdP that validates an identity assertion MUST return the same string that was provided to the original IdP that generated the assertion.
The user agent uses the contents string to determine if the identity assertion matches the session description.
The identity assertion request process is triggered by a call to
createOffer
, createAnswer
, or
getIdentityAssertion
. When these calls are invoked and an
identity provider has been set, the following steps are executed:
The RTCPeerConnection
instantiates an IdP as
described in Identity
Provider Selection and Registering an
IdP Proxy. If the IdP cannot be loaded, instantiated, or the IdP
proxy is not registered, this process fails.
If the RTCPeerConnection
was not constructed with a set
of certificates, and one has not yet been generated, wait
for it to be generated.
The RTCPeerConnection
invokes the
method on the
generateAssertion
methods registered by the
IdP.RTCIdentityProvider
The RTCPeerConnection
generates the
contents parameter to this method as described in
[RTCWEB-SECURITY-ARCH]. The value of contents includes
the fingerprint of the certificate that was selected or generated
during the construction of the RTCPeerConnection
. The
origin parameter contains the origin of the script that
calls the RTCPeerConnection
method that triggers this
behavior. The usernameHint value is the same value that is
provided to setIdentityProvider
, if any such value
was provided.
The IdP proxy returns a Promise to the
RTCPeerConnection
. The IdP proxy is expected to generate
the identity assertion asynchronously.
If the user has been authenticated by the IdP, and the IdP is able
to generate an identity assertion, the IdP resolves the promise with
an identity assertion in the form of an
.RTCIdentityAssertionResult
This step depends entirely on the IdP. The methods by which an IdP authenticates users or generates assertions is not specified, though they could involve interacting with the IdP server or other servers.
If the IdP proxy produces an error or returns a promise that does
not resolve to a valid
(see 9.5 IdP Error Handling), then assertion generation fails.RTCIdentityAssertionResult
The RTCPeerConnection
MAY store the identity
assertion for use with future offers or answers. If a fresh identity
assertion is needed for any reason, applications can create a new
RTCPeerConnection
.
If the identity request was triggered by a
createOffer()
or createAnswer()
, then the
assertion is converted to a JSON string, base64-encoded and inserted
into an a=identity
attribute in the session
description.
If assertion generation fails, then the promise for the corresponding
function call is rejected with a newly created OperationError
.
An IdP MAY reject an attempt to generate an identity assertion if it is unable to verify that a user is authenticated. This might be due to the IdP not having the necessary authentication information available to it (such as cookies).
Rejecting the promise returned by
will cause the error
to propagate to the application. Login errors are indicated by rejecting
the promise with an generateAssertion
RTCError
with errorDetail
set to "idp-need-login".
The URL to login at will be passed to the application in the
idpLoginUrl
attribute of the
RTCPeerConnection
.
An application can load the login URL in an IFRAME or popup window; the resulting page then SHOULD provide the user with an opportunity to enter any information necessary to complete the authorization process.
Once the authorization process is complete, the page loaded in the IFRAME or popup sends a message using postMessage [webmessaging] to the page that loaded it (through the window.opener attribute for popups, or through window.parent for pages loaded in an IFRAME). The message MUST consist of the DOMString "WEBRTC-LOGINDONE". This message informs the application that another attempt at generating an identity assertion is likely to be successful.
Identity assertion validation happens when
is invoked on
setRemoteDescription
. The process runs asynchronously,
meaning that validation of an identity assertion might not block the
completion of RTCPeerConnection
setRemoteDescription
.
The identity assertion request process involves the following asynchronous steps:
The RTCPeerConnection
awaits any prior identity
validation. Only one identity validation can run at a time for an
RTCPeerConnection
. This can happen because the
resolution of setRemoteDescription
is not blocked by
identity validation unless there is a target peer
identity.
The RTCPeerConnection
loads the identity assertion
from the session description and decodes the base64 value, then
parses the resulting JSON. The idp parameter of the
resulting dictionary contains a domain and an optional
protocol value that identifies the IdP, as described in
[RTCWEB-SECURITY-ARCH].
If the identity assertion is malformed, or if protocol
includes the character '/'
or '\'
,
this process fails.
The RTCPeerConnection
instantiates the identified IdP
as described in 9.1.1 Identity Provider
Selection and
9.2 Registering an IdP Proxy. If the IdP cannot be loaded,
instantiated or the IdP proxy is not registered, this process
fails.
The RTCPeerConnection
invokes the
method registered
by the IdP.validateAssertion
The assertion parameter is taken from the decoded
identity assertion. The origin parameter contains the
origin of the script that calls the RTCPeerConnection
method that triggers this behavior.
The IdP proxy returns a promise and performs the validation process asynchronously.
The IdP proxy verifies the identity assertion using whatever means necessary. Depending on the authentication protocol this could involve interacting with the IdP server.
If the IdP proxy produces an error or returns a promise that does
not resolve to a valid
(see 9.5 IdP Error Handling), then identity validation fails.RTCIdentityValidationResult
Once the assertion is successfully verified, the IdP proxy
resolves the promise with an
containing the
validated identity and the original contents that are the payload of
the assertion.RTCIdentityValidationResult
The RTCPeerConnection
decodes the
and validates that
it contains a fingerprint value for every contents
a=fingerprint
attribute in the session description. This ensures that the
certificate used by the remote peer for communications is covered by
the identity assertion.
A user agent is required to fail to
communicate with peers that offer a certificate that doesn't match an
a=fingerprint
line in the negotiated session
description.
The user agent decodes
using
the format described in [RTCWEB-SECURITY-ARCH]. However the IdP
MUST treat contents
contents
as opaque and return the same string
to allow for future extensions.
The RTCPeerConnection
validates that the domain
portion of the identity matches the domain of the IdP as described in
[RTCWEB-SECURITY-ARCH]. If this check fails then the identity
validation fails.
The RTCPeerConnection
resolves the
attribute with a new
instance of peerIdentity
RTCIdentityAssertion
that includes the IdP
domain and peer identity.
The user agent MAY display identity information to a user in its UI. Any user identity information that is displayed in this fashion MUST use a mechanism that cannot be spoofed by content.
If identity validation fails, the
promise is rejected with a
newly created
peerIdentity
OperationError
.
If identity validation fails and there is a target peer
identity for the RTCPeerConnection
, the promise returned
by setRemoteDescription
MUST be rejected with the same
DOMException
.
If identity validation fails and there is no a target peer
identity, the value of the
MUST be set to a new,
unresolved promise instance. This permits the use of renegotiation (or a
subsequent answer, if the session description was a provisional answer)
to resolve or reject the identity.peerIdentity
Errors in IdP processing will - in most cases - result in the failure
of the procedure that invoked the IdP proxy. This will result in the
rejection of the promise returned by
, getIdentityAssertion
, or createOffer
. An IdP proxy error causes a
createAnswer
promise to be rejected if there is a target peer identity; IdP
errors in calls to setRemoteDescription
where there is no
target peer identity cause the setRemoteDescription
promise to be rejected
instead.peerIdentity
If an error occurs these promises are rejected with an
RTCError
if an error occurs in interacting with the IdP
proxy. The following scenarios result in errors:
An RTCPeerConnection
might be configured with an
identity provider, but loading of the IdP URI fails. Any procedure that
attempts to invoke such an identity provider and cannot load the
URI fails with an RTCError
with errorDetail
set to "idp-load-failure" and the httpRequestStatusCode attribute of
the error set to the HTTP status code of the response.
If the IdP loads fails due to the TLS certificate used for the
HTTPS connection not being trusted, it fails with an
RTCError
with errorDetail
set to
"idp-tls-failure". This typically happens when the IdP uses
certificate pinning and an intermediary such as an enterprise
firewall has intercepted the TLS connection.
If the script loaded from the identity provider is
not valid JavaScript or does not implement the correct interfaces,
it causes an IdP failure with an RTCError
with
errorDetail
set to "idp-bad-script-failure".
An apparently valid identity provider might fail in several
ways.
If the IdP token has expired, then the IdP MUST fail with an
RTCError
with errorDetail
set to
"idp-token-expired".
If the IdP token is not valid, then the IdP MUST fail with an
RTCError
with errorDetail
set to
"idp-token-invalid".
If an identity provider throws an exception or returns a promise
that is ultimately rejected, then the procedure that depends on the IdP
MUST also fail. These types of errors will cause an IdP failure with an
RTCError
with errorDetail
set to
"idp-execution-failure".
The user agent SHOULD limit the time that it allows for
an IdP to 15 seconds. This includes both the loading of the IdP proxy and the identity
assertion generation or validation. Failure to do so potentially causes
the corresponding operation to take an indefinite amount of time. This
timer can be cancelled when the IdP proxy produces a
response. Expiration of this timer cases an IdP failure with an
RTCError
with errorDetail
set to
"idp-timeout".
If the identity provider requires the user to login, the
operation will fail RTCError
with errorDetail
set to "idp-need-login" and the idpLoginUrl
attribute of
the error set to the URL that can be used to login.
Even when the IdP proxy produces a positive result, the
procedure that uses this information might still fail. Additional
validation of an RTCIdentityValidationResult
value is still
necessary. The procedure for validation of identity
assertions describes additional steps that are required to
successfully validate the output of the IdP proxy.
Any error generated by the IdP MAY provide additional
information in the idpErrorInfo
attribute. The
information in this string is defined by the IdP in use.
The Identity API extends the
interface as described below.RTCPeerConnection
partial interface RTCPeerConnection
{
void setIdentityProvider
(DOMString provider,
optional RTCIdentityProviderOptions
options);
Promise<DOMString> getIdentityAssertion
();
readonly attribute Promise<RTCIdentityAssertion
> peerIdentity
;
readonly attribute DOMString? idpLoginUrl
;
readonly attribute DOMString? idpErrorInfo
;
};
peerIdentity
of type Promise<RTCIdentityAssertion
>,
readonlyA promise that resolves with the identity of the peer if the identity is successfully validated.
This promise is rejected if an identity assertion is present in a remote session description and validation of that assertion fails for any reason. If the promise is rejected, a new unresolved value is created, unless a target peer identity has been established. If this promise successfully resolves, the value will not change.
idpLoginUrl
of type DOMString, readonly, nullableThe URL that an application can navigate to so that the user can login to the IdP, as described in 9.3.1 User Login Procedure.
idpErrorInfo
of type DOMString, readonly, nullableAn attribute that the IdP can use to pass additional information back to the applications about the error. The format of this string is defined by the IdP and may be JSON.
setIdentityProvider
Sets the identity provider to be used for a given
RTCPeerConnection
object. Applications need not make
this call; if the browser is already configured for an IdP, then
that configured IdP might be used to get an assertion.
When the setIdentityProvider
method is
invoked, the user agent MUST run the following steps:
If the
object's
[[IsClosed]] slot is RTCPeerConnection
true
, throw an
InvalidStateError
.
If options.protocol includes the the character
'/'
or '\'
, throw a
SyntaxError
.
Set the current identity provider values to the tuple
(provider
, options
).
If any identity provider value has changed, discard any stored identity assertion.
Identity provider information is not used until an identity
assertion is required, either in response to a call to
getIdentityAssertion
, or a session description is
requested with a call to either createOffer
or
createAnswer
.
getIdentityAssertion
Initiates the process of obtaining an identity assertion.
Applications need not make this call. It is merely intended to
allow them to start the process of obtaining identity assertions
before a call is initiated. If an identity is needed, either
because the browser has been configured with a default identity
provider or because the
method
was called, then an identity will be automatically requested when
an offer or answer is created.setIdentityProvider
When getIdentityAssertion
is invoked, queue a
task to run the following steps:
If the
object's
[[IsClosed]] slot is RTCPeerConnection
true
, throw an
InvalidStateError
.
Request an identity assertion from the IdP.
Resolve the promise with the base64 and JSON encoded assertion.
dictionary RTCIdentityProviderOptions
{
DOMString protocol
= "default";
DOMString usernameHint
;
DOMString peerIdentity
;
};
RTCIdentityProviderOptions
Membersprotocol
of type DOMStringThe name of the protocol that is used by the identity provider. This MUST NOT include '/' (U+002F) or '\' (U+005C) characters. This value defaults to "default" if not provided.
usernameHint
of type DOMStringA hint to the identity provider about the identity of the
principal for which it should generate an identity assertion. If
absent, the value undefined
is used.
peerIdentity
of type DOMStringThe identity of the peer. For identity providers that bind
their assertions to a particular pair of communication peers,
this allows them to generate an assertion that includes both
local and remote identities. If this value is omitted, but a
value is provided for the peerIdentity
member of
, the value from
RTCConfiguration
is used.RTCConfiguration
[Constructor(DOMString idp, DOMString name),
Exposed=Window]
interface RTCIdentityAssertion
{
attribute DOMString idp
;
attribute DOMString name
;
};
RTCIdentityAssertion
Attributesidp
of type DOMStringThe domain name of the identity provider that validated this identity.
name
of type DOMStringAn RFC5322-conformant [RFC5322] representation of the verified peer identity. This identity will have been verified via the procedures described in [RTCWEB-SECURITY-ARCH].
The identity system is designed so that applications need not take any special action in order for users to generate and verify identity assertions; if a user has configured an IdP into their browser, then the browser will automatically request/generate assertions and the other side will automatically verify them and display the results. However, applications may wish to exercise tighter control over the identity system as shown by the following examples.
This example shows how to configure the identity provider.
pc.setIdentityProvider('example.com');
This example shows how to configure the identity provider with all the options.
pc.setIdentityProvider('example.com', {
usernameHint: 'alice@example.com',
peerIdentity: 'bob@example.net'
});
This example shows how to consume identity assertions inside a Web application.
async function consumeIdentityAssertion() {
const identity = await pc.peerIdentity;
console.log('IdP = ', identity.idp, 'identity =', identity.name);
}
The MediaStreamTrack
interface, as defined in the
[GETUSERMEDIA] specification, typically represents a stream of data of
audio or video. One or more MediaStreamTrack
s 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
RTCRtpSender
and RTCRtpReceiver
can be used by
the application to get more fine grained control over the transmission
and reception of MediaStreamTrack
s.
Channels are the smallest unit considered in the
MediaStream
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
created by an
MediaStreamTrack
object (as described previously in
this document) will take as input the data received from a remote peer.
Similarly, a RTCPeerConnection
MediaStreamTrack
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
object.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
. Please refer to the original
definitions of the objects in the [GETUSERMEDIA] document for general
information on using RTCPeerConnection
MediaStream
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
API.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