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-2012 W3C® (MIT, ERCIM, Keio, Beihang), All Rights Reserved. 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 http://www.w3.org/TR/.
This document is neither complete nor stable, and as such is not yet suitable for commercial implementation. However, early experimentation is encouraged. The API is based on preliminary work done in the WHATWG. The Web Real-Time Communications Working Group expects this specification to evolve significantly based on:
This document was published by the Web Real-Time Communications Working Group as an Editor's Draft. If you wish to make comments regarding this document, please send them to public-webrtc@w3.org (subscribe, archives). All comments are welcome.
Publication as an Editor's Draft 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 5 February 2004 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 section is non-normative.
There are a number of facets to 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 developed by the Media Capture Task Force.
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 MUST, MUST NOT, REQUIRED, SHOULD, SHOULD NOT, RECOMMENDED, MAY, and OPTIONAL in this specification 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.
Implementations that use ECMAScript to implement the APIs defined in this specification must implement them in a manner consistent with the ECMAScript Bindings defined in the Web IDL specification [WEBIDL], as this specification uses that specification and terminology.
The EventHandler
interface represents a callback used for event handlers as defined in
[HTML5].
The concepts queue a task and fires a simple event are defined in [HTML5].
The terms event handlers and event handler event types are defined in [HTML5].
An
allows two users to
communicate directly, browser to browser. Communications are coordinated
via 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
.
dictionary RTCConfiguration {
RTCIceServer
[] iceServers;
};
RTCConfiguration
MembersiceServers
of type array of RTCIceServer
An array containing STUN and TURN servers available to be used by ICE.
dictionary RTCIceServer {
DOMString url;
DOMString? credential;
};
RTCIceServer
MembersIn network topologies with multiple layers of NATs, it is desirable to have a STUN server between every layer of NATs in addition to the TURN servers to minimize the peer to peer network latency.
An example array of RTCIceServer objects is:
[ { url:"stun:stun.example.net" } , {
url:"turn:user@turn.example.org", credential:"myPassword"} ]
The general operation of the RTCPeerConnection is described in [RTCWEB-JSEP].
Calling new
creates an RTCPeerConnection
(configuration
)
object.RTCPeerConnection
The configuration has the information to find and access the [STUN] and [TURN] servers. There may be multiple servers of each type and any TURN server also acts as a STUN server.
An
object has an associated
ICE agent[ICE],
RTCPeerConnection signaling
state, ICE gathering state, and ICE connection state.
These are initialized when the object is
created.RTCPeerConnection
An
object has two associated
stream sets. A local streams set,
representing streams that are currently sent, and a remote streams set, representing streams that
are currently received with this
RTCPeerConnection
object. The stream sets are
initialized to empty sets when the RTCPeerConnection
object is created.RTCPeerConnection
When the RTCPeerConnection()
constructor
is invoked, the user agent MUST run the following steps. This algorithm
has a synchronous section (which is triggered as part of the event loop
algorithm).
Create an ICE Agent as defined in [ICE] and let
connection's
RTCPeerConnection
ICE
Agent be that ICE Agent and provide it the STUN and TURN
servers from the configuration array. The ICE Agent will proceed
with gathering as soon as the IceTransports constraint is not set
to "none". At this point the ICE Agent does not know how many ICE
components it needs (and hence the number of candidates to gather),
but it can make a reasonable assumption such as 2. As the
RTCPeerConnection
object gets more information, the
ICE Agent can adjust the number of components.
Set connection's RTCPeerConnection
signalingState to stable
.
Set connection's RTCPeerConnection
ice connection state to new
.
Set connection's RTCPeerConnection
ice gathering state to new
.
Initialize an internal variable to represent a queue of
operations
with an empty set.
Return connection, but continue these steps asynchronously.
Await a stable state. The synchronous section consists of the remaining steps of this algorithm.
Once the RTCPeerConnection object has been initialized, for every
call to createOffer
, setLocalDescription
,
createAnswer
and setRemoteDescription
;
execute the following steps:
Append an object representing the current call being handled
(i.e. function name and corresponding arguments) to the
operations
array.
If the length of the operations
array is exactly 1,
execute the function from the front of the queue asynchronously.
When the asynchronous operation completes (either successfully
or with an error), remove the corresponding object from the
operations
array. After removal, if the array is
non-empty, execute the first object queued asynchronously and
repeat this step on completion.
The general idea is to have only one among createOffer
,
setLocalDescription
, createAnswer
and
setRemoteDescription
executing at any given time. If
subsequent calls are made while one of them is still executing, they
are added to a queue and processed when the previous operation is fully
completed. It is valid, and expected, for normal error handling
procedures to be applied.
Additionally, during the lifetime of the RTCPeerConnection object, the following procedures are followed when an ICE event occurs:
If iceConnectionState is new
and the IceTransports constraint
is not set to none
, it MUST queue a task to start gathering ICE
addresses and set the iceConnectionState to "gathering".
If the ICE Agent has found one or more candidate pairs for each MediaStreamTrack that forms a valid connection, the ICE connection state is changed to "connected".
When the ICE Agent finishes checking all candidate pairs, if at least one connection has been found for each MediaStreamTrack, the iceConnectionState is changed to "completed"; else the iceConnectionState is changed to "failed".
If the iceConnectionState is "connected" or "completed" and both the local and remote session descriptions have received a valid SDP offer / answer pair, the RTCPeerConnection state is set to "stable".
If the iceConnectionState is "failed", a task is queued to call the close method.
Open Issue: CJ - this seems wrong to me - just because a network connection failed does not mean the PC should be put into a dead state it can not recover from.
When the ICE Agent needs to notify the script about the candidate gathering progress, the user agent must queue a task to run the following steps:
Let connection be the
object associated with this
ICE Agent.RTCPeerConnection
If connection's RTCPeerConnection
signalingState is closed
, abort these
steps.
If the intent of the ICE Agent is to notify the script that:
A new candidate is available.
Add the candidate to connection's
localDescription
and create a
object to represent the
candidate. Let newCandidate be that object.RTCIceCandidate
The gathering process is done.
Set connection's
ice gathering
state to completed
and let
newCandidate be null.
Fire a icecandidate event named icecandidate
with
newCandidate at connection.
User agents negotiate the codec resolution, bitrate, and other media
parameters. It is RECOMMENDED that user agents initially negotiate for
the maximum resolution of a video stream. For streams that are then
rendered (using a video
element), it is RECOMMENDED that
user agents renegotiate for a resolution that matches the rendered
display size.
The word "components" in this context refers to an RTP media flow and does not have anything to do with how [ICE] uses the term "component".
When a user agent has reached the point where a
MediaStream
can be created to represent incoming
components, the user agent MUST run the following steps:
Let connection be the
expecting this media.RTCPeerConnection
Create a MediaStream
object
stream, to represent the incoming media stream.
Run the algorithm to represent an incoming component with a track for each incoming component.
The creation of new incoming
MediaStream
s may be triggered either by SDP
negotiation or by the receipt of media on a given flow.
Queue a task to run the following substeps:
If the connection's RTCPeerConnection
signalingState is closed
, abort these
steps.
Add stream to connection's remote streams set.
Fire a stream event named
addstream
with
stream at the connection object.
When a user agent has negotiated media for a component that belongs
to a media stream that is already represented by an existing
MediaStream
object, the user agent MUST associate
the component with that MediaStream
object.
When an
finds that a stream
from the remote peer has been removed, the user agent MUST follow these steps:RTCPeerConnection
Let connection be the
associated with the stream
being removed.RTCPeerConnection
Let stream be the MediaStream
object that represents the media stream being removed, if any. If
there isn't one, then abort these steps.
By definition, stream is now finished.
A task is thus queued to update stream and fire an event.
Queue a task to run the following substeps:
If the connection's RTCPeerConnection
signalingState is closed
, abort these
steps.
Remove stream from connection's remote streams set.
Fire a stream event named
removestream
with
stream at the connection
object.
The task source for the tasks listed in this section is the networking task source.
If something in the browser changes that causes the
object to need to initiate a new
session description negotiation, a RTCPeerConnection
negotiationneeded
event is fired at the
object.RTCPeerConnection
In particular, if an
object is
consuming a RTCPeerConnection
MediaStream
on
which a track is added, by, e.g., the addTrack()
method being invoked, the
object
MUST fire the "negotiationneeded" event. Removal of media components
must also trigger "negotiationneeded".RTCPeerConnection
To prevent network sniffing from allowing a fourth party to establish a connection to a peer using the information sent out-of-band to the other peer and thus spoofing the client, the configuration information SHOULD always be transmitted using an encrypted connection.
[Constructor (RTCConfiguration configuration, optional MediaConstraints constraints)]
interface RTCPeerConnection : EventTarget {
void createOffer (RTCSessionDescriptionCallback
successCallback, RTCPeerConnectionErrorCallback
failureCallback, optional MediaConstraints constraints);
void createAnswer (RTCSessionDescriptionCallback
successCallback, RTCPeerConnectionErrorCallback
failureCallback, optional MediaConstraints constraints);
void setLocalDescription (RTCSessionDescription
description, VoidFunction successCallback, RTCPeerConnectionErrorCallback
failureCallback);
readonly attribute RTCSessionDescription
localDescription;
void setRemoteDescription (RTCSessionDescription
description, VoidFunction successCallback, RTCPeerConnectionErrorCallback
failureCallback);
readonly attribute RTCSessionDescription
remoteDescription;
readonly attribute RTCSignalingState
signalingState;
void updateIce (optional RTCConfiguration
configuration, optional MediaConstraints constraints);
void addIceCandidate (RTCIceCandidate
candidate);
readonly attribute RTCIceGatheringState
iceGatheringState;
readonly attribute RTCIceConnectionState
iceConnectionState;
sequence<MediaStream> getLocalStreams ();
sequence<MediaStream> getRemoteStreams ();
MediaStream? getStreamById (DOMString streamId);
void addStream (MediaStream stream, optional MediaConstraints constraints);
void removeStream (MediaStream stream);
void close ();
attribute EventHandler onnegotiationneeded;
attribute EventHandler onicecandidate;
attribute EventHandler onsignalingstatechange;
attribute EventHandler onaddstream;
attribute EventHandler onremovestream;
attribute EventHandler oniceconnectionstatechange;
};
iceConnectionState
of type RTCIceConnectionState
, readonly The iceConnectionState
attribute
MUST return the state of the RTCPeerConnection
ICE
Agent ICE state.
iceGatheringState
of type RTCIceGatheringState
, readonly The iceGatheringState
attribute MUST return the gathering state of the RTCPeerConnection
ICE
Agent connection state.
localDescription
of type RTCSessionDescription
, readonly The localDescription
attribute MUST return the
that was most recently passed to RTCSessionDescription
setLocalDescription()
,
plus any local candidates that have been generated by the ICE Agent
since then.
A null object will be returned if the local description has not yet been set.
onaddstream
of type EventHandler, addstream
, MUST be fired by
all objects implementing the RTCPeerConnection
interface. It is called any time a MediaStream
is added
by the remote peer. This will be fired only as a result of
setRemoteDescription
. Onnaddstream happens as early as
possible after the setRemoteDescription
. This callback
does not wait for a given media stream to be accepted or rejected via
SDP negotiation.onicecandidate
of type EventHandler, icecandidate
, MUST be supported by
all objects implementing the RTCPeerConnection
interface.oniceconnectionstatechange
of type EventHandler, iceconnectionstatechange
, MUST be fired by all objects
implementing the RTCPeerConnection
interface. It
is called any time the iceConnectionState changes.onnegotiationneeded
of type EventHandler, negotiationneeded
, MUST be
supported by all objects implementing the
RTCPeerConnection
interface.onremovestream
of type EventHandler, removestream
, MUST be
fired by all objects implementing the
RTCPeerConnection
interface. It is called any
time a MediaStream
is removed by the remote peer. This
will be fired only as a result of
setRemoteDescription
.onsignalingstatechange
of type EventHandler, signalingstatechange
, MUST be supported
by all objects implementing the RTCPeerConnection
interface. It is called any time the readyState
changes,
i.e., from a call to setLocalDescription
, a call to
setRemoteDescription
, or code. It does not fire for the
initial state change into new
.remoteDescription
of type RTCSessionDescription
, readonly The remoteDescription
attribute MUST return the
that was most recently passed to RTCSessionDescription
setRemoteDescription()
,
plus any remote candidates that have been supplied via
addIceCandidate()
since then.
A null object will be returned if the remote description has not yet been set.
signalingState
of type RTCSignalingState
, readonly The signalingState
attribute MUST return the
RTCPeerConnection
object's RTCPeerConnection
signaling state.
addIceCandidate
The addIceCandidate()
method provides a remote candidate to the ICE Agent. In addition to
being added to the remote description, connectivity checks will be
sent to the new candidates as long as the "IceTransports"
constraint is not set to "none". This call will result in a change
to the connection state of the ICE Agent, and may result in a change to media
state if it results in different connectivity being
established.
An exception with an RTCError
object of type
INVALID_CANDIDATE_TYPE
is thrown if candidate
parameter is malformed.
Parameter | Type | Nullable | Optional | Description |
---|---|---|---|---|
candidate |
| ✘ | ✘ |
void
addStream
Adds a new stream to the RTCPeerConnection.
When the addStream()
method is invoked, the user agent MUST
run the following steps:
Let connection be the
object on which the RTCPeerConnection
MediaStream
, stream,
is to be added.
If connection's
RTCPeerConnection
signalingState is closed
, abort these steps,
and throw an exception with an RTCError
object of
type INVALID_STATE
.
If stream is already in connection's local streams set, then abort these steps.
Add stream to connection's local streams set.
Parse the constraints provided by the application
and apply them to the MediaStream, if possible. If the
constraints could not be successfully applied, provide an
RTCError
object of type
INCOMPATIBLE_CONSTRAINTS
to the failure
callback.
If connection's
RTCPeerConnection
signalingState is
stable
, then fire a negotiationneeded event at
connection.
ISSUE: Should this fire if the RTCPeerConnection is in "new"?
Parameter | Type | Nullable | Optional | Description |
---|---|---|---|---|
stream | MediaStream | ✘ | ✘ | |
constraints | MediaConstraints | ✘ | ✔ |
void
close
When the close()
method is invoked, the user agent MUST run
the following steps:
If the
object's
RTCPeerConnection
RTCPeerConnection
signalingState is closed
, throw an
INVALID_STATE
exception.
Destroy the RTCPeerConnection
ICE Agent, abruptly ending any active ICE processing and
any active streaming, and releasing any relevant resources
(e.g. TURN permissions).
Set the object's RTCPeerConnection
signalingState to closed
.
void
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 contains descriptions of the local MediaStreams 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 constraints parameter may be supplied to provide additional control over the generated answer.
As an answer, the generated SDP will contain a specific 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.
Session descriptions generated by createAnswer must be immediately usable by setLocalDescription without generating an error if setLocalDescription is called from the successCallback function. 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 successCallback function. Calling this method is needed to get the ICE user name fragment and password.
An answer can be marked as provisional, as described in
[RTCWEB-JSEP], by setting the type
to
"pranswer"
.
If the RTCPeerConnection
is configured to generate
Identity assertions, then the session description SHALL contain an
appropriate assertion.
If this RTCPeerConnection
object is closed before
the SDP generation process completes, the USER agent MUST suppress
the result and not call any of the result callbacks.
If the SDP generation process completed successfully, the user
agent MUST queue a task to invoke successCallback with a
newly created
object,
representing the generated answer, as its argument.RTCSessionDescription
If the SDP generation process failed for any reason, the user
agent MUST queue a task to invoke errorCallback with an
RTCError
object of type TBD as its argument.
An exception with an RTCError
object of type
INVALID_CONSTRAINTS_TYPE
is thrown if the constraints
parameter is malformed, and an RTCError
object of type
INCOMPATIBLE_CONSTRAINTS
is provided to the failure
callback if the constraints could not be successfully applied.
Parameter | Type | Nullable | Optional | Description |
---|---|---|---|---|
successCallback |
| ✘ | ✘ | |
failureCallback |
| ✘ | ✘ | |
constraints | MediaConstraints | ✘ | ✔ |
void
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 MediaStream
s
attached to this RTCPeerConnection
, the codec/RTP/RTCP
options supported by this implementation, and any candidates that
have been gathered by the ICE Agent. The constraints parameter may
be supplied to provide additional control over the offer generated.
More information about constraints can be found in
[RTCWEB-CONSTRAINTS].
As an offer, the generated SDP will contain the full set of capabilities supported by the session (as opposed to an answer, which will include only a specific negotiated subset to use); for each SDP line, the generation of the SDP must follow the appropriate process for generating an offer. 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 streams. 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.
Session descriptions generated by createOffer MUST be immediately usable by setLocalDescription without causing an error as long as setLocalDescription is called within the successCallback function. 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 end of the successCallback function. Calling this method is needed to get the ICE user name fragment and password.
If the RTCPeerConnection
is configured to generate
Identity assertions, then the session description SHALL contain an
appropriate assertion.
If this RTCPeerConnection
object is closed before
the SDP generation process completes, the USER agent MUST suppress
the result and not call any of the result callbacks.
If the SDP generation process completed successfully, the user
agent MUST queue a task to invoke successCallback with a
newly created
object,
representing the generated offer, as its argument.RTCSessionDescription
If the SDP generation process failed for any reason, the user
agent MUST queue a task to invoke errorCallback with an
RTCError
object of type TBD as its argument.
An exception with an RTCError
object of type
INVALID_CONSTRAINTS_TYPE
is thrown if the constraints
parameter is malformed, and an RTCError
object of type
INCOMPATIBLE_CONSTRAINTS
is provided to the failure
callback if the constraints could not be successfully applied.
To Do: Discuss privacy aspects of this from a fingerprinting point of view - it's probably around as bad as access to a canvas :-)
Parameter | Type | Nullable | Optional | Description |
---|---|---|---|---|
successCallback |
| ✘ | ✘ | |
failureCallback |
| ✘ | ✘ | |
constraints | MediaConstraints | ✘ | ✔ |
void
getLocalStreams
Returns a sequence of MediaStream
objects
representing the streams that are currently sent with this
object.RTCPeerConnection
The
getLocalStreams()
method MUST return a new
sequence that represents a snapshot of all the
MediaStream
objects in this
object’s local streams set. The conversion from the
streams set to the sequence, to be returned, is user agent defined
and the order does not have to stable between calls.RTCPeerConnection
sequence<MediaStream>
getRemoteStreams
Returns a sequence of MediaStream
objects
representing the streams that are currently received with this
object.RTCPeerConnection
The
getRemoteStreams()
method MUST return a new
sequence that represents a snapshot of all the
MediaStream
objects in this
object’s remote streams set. The conversion from the
streams set to the sequence, to be returned, is user agent defined
and the order does not have to stable between calls.RTCPeerConnection
sequence<MediaStream>
getStreamById
If a MediaStream
object, with an
id
equal
to trackId, exists in this
object’s stream sets (local streams set or remote streams set), then the
RTCPeerConnection
getStreamById()
method MUST return that
MediaStream
object. The method MUST return null
if no stream matches the streamId argument.
For this method to make sense, we need to make sure that ids are unique within the two stream sets of a PeerConnection. This is not the case today when a peer re-adds a stream that is received. Two different stream instances will now have the same id at both peers; one in the remote stream set and one in the local stream set.
One way to resolve this is to not allow re-adding a stream instance that is received (guard on id). If an application really needs this functionality it's really easy to make a clone of the stream, which will give it a new id, and send the clone.
Parameter | Type | Nullable | Optional | Description |
---|---|---|---|---|
streamId | DOMString | ✘ | ✘ |
MediaStream
, nullableremoveStream
Removes the given stream from the
.RTCPeerConnection
When the other peer stops sending a stream in this manner, a
removestream
event is
fired at the
object.RTCPeerConnection
When the removeStream()
method is invoked, the user agent
MUST run the following steps:
Let connection be the
object on which the RTCPeerConnection
MediaStream
, stream,
is to be removed.
If connection's
RTCPeerConnection
signalingState is closed
, throw an
INVALID_STATE
exception.
If stream is not in connection's local streams set, then abort these steps.
Remove stream from connection's local streams set.
If connection's
RTCPeerConnection
signalingState is
stable
, then fire a negotiationneeded event at
connection.
Parameter | Type | Nullable | Optional | Description |
---|---|---|---|---|
stream | MediaStream | ✘ | ✘ |
void
setLocalDescription
The setLocalDescription()
method instructs the
to apply
the supplied RTCPeerConnection
as the local
description.RTCSessionDescription
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 old and new 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 new local
description, or roll back to the old description if the remote side
denied the change.RTCPeerConnection
ISSUE: how to indicate to roll back?
To Do: specify what parts of the SDP can be changed between the createOffer and setLocalDescription
When the method is invoked, the user agent must follow the processing model described by the following list:
If this
object's
signaling state is
RTCPeerConnection
closed
, the user agent MUST throw an exception with
an RTCError
object of type INVALID_STATE
and abort this operation.
If a local description contains a different set of ICE credentials, then the ICE Agent MUST trigger an ICE restart.
If the process to apply the
argument fails for any
reason, then user agent must queue a task runs the following
steps:RTCSessionDescription
Let connection be the
object on with this
method was invoked.RTCPeerConnection
If connection's signaling state
is closed
, then abort these steps.
If the reason for the failure is:
The content of the
argument is invalid
or the RTCSessionDescription
type
is
wrong for the current signaling state
of connection.
Let errorType be
INVALID_SESSION_DESCRIPTION
.
The
is
a valid description but cannot be applied at the media
layer.RTCSessionDescription
This can happen, e.g., if there are insufficient resources to apply the SDP. The user agent MUST then roll back as necessary if the new description was partially applied when the failure occurred.
If rollback was not necessary or was completed
successfully, let errorType be
INCOMPATIBLE_SESSION_DESCRIPTION
. If
rollback was not possible, let errorType be
INTERNAL_ERROR
and set
connection's signaling
state to closed
.
Invoke the failureCallback with an
RTCError
object, of type
errorType, as its argument.
If the
argument is
applied successfully, then user agent must queue a task runs the
following steps:RTCSessionDescription
Let connection be the
object on with this
metod was invoked.RTCPeerConnection
If connection's signaling state
is closed
, then abort these steps.
Set connection's description attribute
(localDescription
or
remoteDescription
depending on the setting
operation) to the
argument.RTCSessionDescription
If the local description was set,
connection's ice gathering
state is new
, and the local description
contains media, then set connection's ice gathering
state to gathering
.
If the local description was set with content that
caused an ICE restart, then set connection's
ice
gathering state to gathering
.
Set connection's signalingState accordingly.
Fire a simple event named signalingstatechange
at connection.
Queue a new task that, if connection's signalingState
is not closed
, invokes the
successCallback.
Parameter | Type | Nullable | Optional | Description |
---|---|---|---|---|
description |
| ✘ | ✘ | |
successCallback | VoidFunction | ✘ | ✘ | |
failureCallback |
| ✘ | ✘ |
void
setRemoteDescription
The setRemoteDescription()
method instructs the
to apply
the supplied RTCPeerConnection
as the
remote offer or answer. This API changes the local media state.RTCSessionDescription
If a=identity
attributes are present, the browser
verifies the identity following the procedures in [XREF
sec.identity-proxy-assertion-request].
When the method is invoked, the user agent must follow the
processing model of
setLocalDescription()
.
Parameter | Type | Nullable | Optional | Description |
---|---|---|---|---|
description |
| ✘ | ✘ | |
successCallback | VoidFunction | ✘ | ✘ | |
failureCallback |
| ✘ | ✘ |
void
updateIce
The updateIce method updates the ICE Agent process of gathering local candidates and pinging remote candidates. If there is a mandatory constraint called "IceTransports" it will control how the ICE engine can act. This can be used to limit the use to TURN candidates by a callee to avoid leaking location information prior to the call being accepted.
This call may result in a change to the state of the ICE Agent, and may result in a change to media state if it results in connectivity being established.
An exception with an RTCError
object of type
INVALID_CONSTRAINTS_TYPE
is thrown if the constraints
parameter is malformed, and an RTCError
object of type
INCOMPATIBLE_CONSTRAINTS
is provided to the failure
callback if the constraints could not be successfully applied.
Parameter | Type | Nullable | Optional | Description |
---|---|---|---|---|
configuration |
| ✘ | ✔ | |
constraints | MediaConstraints | ✘ | ✔ |
void
A Window
object has a strong reference to any
objects created from the
constructor whose global object is that RTCPeerConnection
Window
object.
enum 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 supplied. |
have-remote-offer | A remote description, of type "offer", has been supplied. |
have-local-pranswer | A remote description of type "offer" has been supplied and a local description of type "pranswer" has been supplied. |
have-remote-pranswer | A local description of type "offer" has been supplied and a remote description of type "pranswer" has been supplied. |
closed | The connection is closed. |
The non-normative peer state transitions are:
An example set of transitions might be:
Caller transition:
stable
have-local-offer
have-remote-pranswer
stable
closed
Callee transition:
stable
have-remote-offer
have-local-pranswer
stable
closed
enum RTCIceGatheringState {
"new",
"gathering",
"complete"
};
Enumeration description | |
---|---|
new | The object was just created, and no networking has occurred yet. |
gathering | The ICE engine is in the process of gathering candidates for this RTCPeerConnection. |
complete | The ICE engine has completed gathering. Events such as adding a new interface or a new TURN server will cause the state to go back to gathering. |
enum RTCIceConnectionState {
"new",
"checking",
"connected",
"completed",
"failed",
"disconnected",
"closed"
};
Enumeration description | |
---|---|
new | The ICE Agent is gathering addresses and/or waiting for remote candidates to be supplied. |
checking | The ICE Agent has received remote candidates on at least one component, and is checking candidate pairs but has not yet found a connection. In addition to checking, it may also still be gathering. |
connected | The ICE Agent has found a usable connection for all components but is still checking other candidate pairs to see if there is a better connection. It may also still be gathering. |
completed | The ICE Agent has finished gathering and checking and found a connection for all components. Open issue: it is not clear how the non controlling ICE side knows it is in the state. |
failed | The ICE Agent is finished checking all candidate pairs and failed to find a connection for at least one component. Connections may have been found for some components. |
disconnected | Liveness checks have failed for one or more components. This is
more aggressive than failed , and may trigger
intermittently (and resolve itself without action) on a flaky
network. |
closed | The ICE Agent has shut down and is no longer responding to STUN requests. |
States take either the value of any component or all components, as outlined below:
checking
occurs if ANY component has received a
candidate and can start checkingconnected
occurs if ALL components have established
a working connectioncompleted
occurs if ALL components have finalized
the running of their ICE processesfailed
occurs if ANY component has given up trying
to connectdisconnected
occurs if ANY component has failed
liveness checksclosed
occurs only if
PeerConnection.close()
has been called.If a component is discarded as a result of signaling (e.g. RTCP mux
or BUNDLE), the state may advance directly from checking
to completed
.
An example transition might look like:
new
new
, remote candidates received): checking
checking
, found usable connection): connected
checking
, gave up): failed
connected
, finished all checks): completed
completed
, lost connectivity): disconnected
new
closed
The non-normative ICE state transitions are:
callback RTCPeerConnectionErrorCallback = void (RTCError
error);
RTCPeerConnectionErrorCallback
Parameterserror
of type RTCError
Errors are indicated in two ways: exceptions and objects passed to
error callbacks. Both forms of error reporting MUST provide an object
of type RTCError
. An exception MUST be thrown in the
following cases:
RTCExceptionName
enum MUST be used as the error
name.INVALID_STATE
MUST be used as the error name.In all other cases, an error object MUST be provided to the failure
callback. The error name in the object provided MUST be picked from
either the RTCExceptionName
or RTCErrorName
enums.
interface RTCError {
readonly attribute DOMString name;
readonly attribute DOMString? message;
};
message
of type DOMString, readonly , nullablename
of type DOMString, readonly RTCExceptionName
or
RTCErrorName
enums for the error object to be
valid.interface RTCSdpError : RTCError
{
readonly attribute long sdpLineNumber;
};
sdpLineNumber
of type long, readonly RTCSessionDescription
at which the
error was encountered.
enum RTCExceptionName {
"INVALID_CONSTRAINTS_TYPE",
"INVALID_CANDIDATE_TYPE",
"INVALID_MEDIASTREAM_TRACK",
"INVALID_STATE"
};
Enumeration description | |
---|---|
INVALID_CONSTRAINTS_TYPE | The provided constraints object is not a dictionary with either
the mandatory or optional keys. |
INVALID_CANDIDATE_TYPE | The provided candidate is not an object of type
RTCIceCandidate . |
INVALID_MEDIASTREAM_TRACK | The provided track is not an object of type
MediaStreamTrack . |
INVALID_STATE | The function was called on a RTCPeerConnection that
is an invalid state, or a state in which the function is not allowed
to be executed. |
enum RTCErrorName {
"INVALID_SESSION_DESCRIPTION",
"INCOMPATIBLE_SESSION_DESCRIPTION",
"INCOMPATIBLE_CONSTRAINTS",
"INCOMPATIBLE_MEDIASTREAMTRACK",
"INTERNAL_ERROR"
};
Enumeration description | |
---|---|
INVALID_SESSION_DESCRIPTION | The provided contained
invalid SDP, or the type was wrong for the
current state of the . User
agents SHOULD provide as much additional information in the error
message as possible, including the sdpLineNumber , if
appropriate. |
INCOMPATIBLE_SESSION_DESCRIPTION | The provided contained
SDP that could not be correctly applied to the
due to its current state. User agents
SHOULD provide as much additional information in the error message as
possible, including the sdpLineNumber , if appropriate.
|
INCOMPATIBLE_CONSTRAINTS | The provided MediaConstraints could not be correctly
applied to the RTCPeerConnection due to its current
state. User agents SHOULD provide as much additional information in
the error message as possible. |
INCOMPATIBLE_MEDIASTREAMTRACK | The provided MediaStreamTrack is not an
element of a MediaStream that is currently in
the RTCPeerConnection 's localStreams
attribute. |
INTERNAL_ERROR | The encountered an error
that it could not recover from. |
The RTCSdpType enum describes the type of an
instance.RTCSessionDescription
enum RTCSdpType {
"offer",
"pranswer",
"answer"
};
Enumeration description | |
---|---|
offer |
An RTCSdpType of "offer" indicates that a description should be treated as an [SDP] offer. |
pranswer |
An RTCSdpType of "pranswer" indicates that a description should be treated as an [SDP] answer, but not a final answer. A description used as an SDP "pranswer" may be applied as a response to a SDP offer, or an update to a previously sent SDP "pranswer". |
answer |
An RTCSdpType of "answer" indicates that a description should be treated as an [SDP] final answer, and the offer-answer exchange should be considered complete. A description used as an SDP answer may be applied as a response to an SDP offer or as an update to a previously sent SDP "pranswer". |
The RTCSessionDescription()
constructor takes an optional dictionary argument,
descriptionInitDict, whose content is used to initialize the
new
object. If a dictionary
key is not present in descriptionInitDict, the corresponding
attribute will be initialized to null. If the constructor is run
without the dictionary argument, all attributes will be initialized to
null. This class is a future extensible carrier for the data contained
in it and does not perform any substantive processing.RTCSessionDescription
Objects implementing the
interface MUST serialize with the serialization pattern "RTCSessionDescription
{
attribute }
".
dictionary RTCSessionDescriptionInit {
RTCSdpType
type;
DOMString sdp;
};
[Constructor (optional RTCSessionDescriptionInit descriptionInitDict)]
interface RTCSessionDescription {
attribute RTCSdpType
? type;
attribute DOMString? sdp;
serializer = {attribute};
};
sdp
of type DOMString, , nullabletype
of type RTCSdpType
, , nullableInstances of this interface are serialized as a map with entries for each of the serializable attributes.
RTCSessionDescriptionInit
Memberssdp
of type DOMStringtype
of type RTCSdpType
callback RTCSessionDescriptionCallback = void (RTCSessionDescription
sdp);
RTCSessionDescriptionCallback
Parameterssdp
of type RTCSessionDescription
The RTCIceCandidate()
constructor takes an optional dictionary argument,
candidateInitDict, whose content is used to initialize the
new
object. If a dictionary key is
not present in candidateInitDict, the corresponding
attribute will be initialized to null. If the constructor is run
without the dictionary argument, all attributes will be initialized to
null. This class is a future extensible carrier for the data contained
in it and does not perform any substantive processing.RTCIceCandidate
Objects implementing the
interface MUST serialize with the serialization pattern "RTCIceCandidate
{
attribute }
".
dictionary RTCIceCandidateInit {
DOMString candidate;
DOMString sdpMid;
unsigned short sdpMLineIndex;
};
[Constructor (optional RTCIceCandidateInit candidateInitDict)]
interface RTCIceCandidate {
attribute DOMString? candidate;
attribute DOMString? sdpMid;
attribute unsigned short? sdpMLineIndex;
serializer = {attribute};
};
candidate
of type DOMString, , nullablesdpMLineIndex
of type unsigned short, , nullablesdpMid
of type DOMString, , nullableInstances of this interface are serialized as a map with entries for each of the serializable attributes.
RTCIceCandidateInit
Memberscandidate
of type DOMStringsdpMLineIndex
of type unsigned shortsdpMid
of type DOMStringThe icecandidate
event of the RTCPeerConnection uses
the
interface.RTCPeerConnectionIceEvent
Firing an
event named
e with an RTCPeerConnectionIceEvent
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.
dictionary RTCPeerConnectionIceEventInit : EventInit {
RTCIceCandidate
candidate;
};
[Constructor(DOMString type, RTCPeerConnectionIceEventInit eventInitDict)]
interface RTCPeerConnectionIceEvent : Event {
readonly attribute RTCIceCandidate
candidate;
};
candidate
of type RTCIceCandidate
, readonly The candidate
attribute is the
object with the new ICE
candidate that caused the event.RTCIceCandidate
RTCPeerConnectionIceEventInit
Memberscandidate
of type RTCIceCandidate
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 {
RTCDataChannel
createDataChannel ([TreatNullAs=EmptyString] DOMString label, optional RTCDataChannelInit
dataChannelDict);
attribute EventHandler ondatachannel;
};
ondatachannel
of type EventHandler, datachannel
, MUST be
supported by all objects implementing the
RTCPeerConnection
interface.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. A corresponding
RTCDataChannelInit
object is dispatched at the
other peer if the channel setup was successful.RTCDataChannel
When the
createDataChannel()
method is invoked, the user
agent MUST run the following steps.
If the
object’s
RTCPeerConnection
RTCPeerConnection
signalingState is closed
, throw an
INVALID_STATE
exception.
Let channel be a newly created
object.RTCDataChannel
Initialize channel's label
attribute to the
value of the first argument.
Initialize channel's reliable
attribute to
true.
If the second argument is present and it contains a
reliable
dictionary member, then set channel's reliable
attribute to
the dictionary member value.
Return channel and continue these steps in the background.
Create channel's associated underlying data transport.
Parameter | Type | Nullable | Optional | Description |
---|---|---|---|---|
label | DOMString | ✘ | ✘ | |
dataChannelDict |
| ✘ | ✔ |
RTCDataChannel
The
interface represents a
bi-directional data channel between two peers. A
RTCDataChannel
is created via a factory method on an
RTCDataChannel
object. The corresponding
RTCPeerConnection
object is then dispatched at the other
peer if the channel setup was successful.RTCDataChannel
Each
has an associated
underlying data transport that is used to transport actual
data to the other peer. The transport properties of the underlying
data transport, such as reliability mode, are configured by the peer
taking the initiative to create the channel. The other peer cannot change
any transport properties of an offered data channel. The actual wire
protocol between the peers is out of the scope for this
specification.RTCDataChannel
A
created with RTCDataChannel
createDataChannel()
MUST initially be in the connecting
state. If the
object’s underlying data
transport is successfully set up, the user agent MUST announce the RTCDataChannel
RTCDataChannel
as
open.
When the user agent is to announce
a RTCDataChannel
as open, the user agent MUST queue a
task to run the following steps:
If the associated
object's
RTCPeerConnection
RTCPeerConnection
signalingState is closed
, abort these steps.
Let channel be the
object to be announced.RTCDataChannel
Set channel's readyState
attribute to
open
.
Fire a simple event named open
at channel.
When an underlying data transport has been established, the user agent of the peer that did not initiate the creation process MUST queue a task to run the following steps:
If the associated
object's
RTCPeerConnection
RTCPeerConnection
signalingState is closed
, abort these steps.
Let configuration be an information bundle with key-value pairs, received from the other peer as a part of the process to establish the underlying data channel.
Let channel be a newly created
object.RTCDataChannel
Initialize channel's label
attribute to value that
corresponds to the "label
" key in
configuration.
Initialize channel's reliable
attribute to
true.
If configuration contains a key named
"reliable
", set channel's reliable
attribute to the
corresponding value.
Set channel's readyState
attribute to
open
.
Fire a datachannel event named datachannel
with
channel at the
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, unless the procedure was initiated by
the RTCDataChannel
close()
method, queue a task that sets the object's readyState
attribute to
closing
. This will eventually render the data transport closed.
When a
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
attribute to
closed
.
If the transport was closed with an error, fire an error event at channel.
Fire a simple event named close
at
channel.
dictionary RTCDataChannelInit {
boolean reliable;
};
interface RTCDataChannel : EventTarget {
readonly attribute DOMString label;
readonly attribute boolean reliable;
readonly attribute RTCDataChannelState
readyState;
readonly attribute unsigned long bufferedAmount;
attribute EventHandler onopen;
attribute EventHandler onerror;
attribute EventHandler onclose;
void close ();
attribute EventHandler onmessage;
attribute DOMString binaryType;
void send (DOMString data);
void send (Blob data);
void send (ArrayBuffer data);
void send (ArrayBufferView data);
};
binaryType
of type DOMString, The binaryType
attribute MUST, on getting, return the value to which it was last set.
On setting, the user agent must set the IDL attribute to the new
value. When a
object is created,
the RTCDataChannel
binaryType
attribute MUST be initialized to the string "blob
".
This attribute controls how binary data is exposed to scripts. See the [WEBSOCKETS-API] for more information.
bufferedAmount
of type unsigned long, readonly The bufferedAmount
attribute MUST return the number of bytes of application data (UTF-8
text and binary data) that have been queued using send()
but that, as of the last
time the event loop started executing a task, had not yet been
transmitted to the network. (This thus includes any text sent during
the execution of the current task, regardless of whether the user
agent is able to transmit text asynchronously with script execution.)
This does not include framing overhead incurred by the protocol, or
buffering done by the operating system or network hardware. If the
channel is closed, this attribute's value will only increase with each
call to the send()
method (the attribute does not reset to zero once the channel closes).
label
of type DOMString, readonly The RTCDataChannel.label
attribute represents a label that can be used to distinguish this
object from other
RTCDataChannel
objects. The attribute MUST return
the value to which it was set when the
RTCDataChannel
object was created.RTCDataChannel
onclose
of type EventHandler, close
, MUST be supported by all
objects implementing the RTCDataChannel
interface.onerror
of type EventHandler, error
, MUST be supported by all
objects implementing the RTCDataChannel
interface.onmessage
of type EventHandler, message
,MUST be supported by
all objects implementing the RTCDataChannel
interface.onopen
of type EventHandler, open
, MUST be supported by all
objects implementing the RTCDataChannel
interface.readyState
of type RTCDataChannelState
, readonly The RTCDataChannel.readyState
attribute represents the state of the RTCDataChannel
object. It MUST return the value to which the user agent last set it
(as defined by the processing model algorithms).
reliable
of type boolean, readonly The RTCDataChannel.reliable
attribute returns true if the
is
reliable, and false otherwise. The attribute MUST return the value to
which it was set when the RTCDataChannel
was
created.RTCDataChannel
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
is
closing
or closed
, then abort these
steps.
Set channel's readyState
attribute to
closing
.
If the closing procedure
has not started yet, start it.
void
send
Run the steps described by the send()
algorithm with argument type
string
object.
Parameter | Type | Nullable | Optional | Description |
---|---|---|---|---|
data | DOMString | ✘ | ✘ |
void
send
Run the steps described by the send()
algorithm with argument type
Blob
object.
Parameter | Type | Nullable | Optional | Description |
---|---|---|---|---|
data | Blob | ✘ | ✘ |
void
send
Run the steps described by the send()
algorithm with argument type
ArrayBuffer
object.
Parameter | Type | Nullable | Optional | Description |
---|---|---|---|---|
data | ArrayBuffer | ✘ | ✘ |
void
send
Run the steps described by the send()
algorithm with argument type
ArrayBufferView
object.
Parameter | Type | Nullable | Optional | Description |
---|---|---|---|---|
data | ArrayBufferView | ✘ | ✘ |
void
RTCDataChannelInit
Membersreliable
of type booleanThe 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
attribute
is connecting
, throw an INVALID_STATE
exception and abort these steps.
Execute the sub step that corresponds to the type of the methods argument:
string
object:
Let data be the result of converting the
argument object to a sequence of Unicode characters and
increase the bufferedAmount
attribute by the number of bytes needed to express
data as UTF-8.
Blob
object:
Let data be the raw data represented by the
Blob
object and increase the bufferedAmount
attribute by the size of data, in bytes.
ArrayBuffer
object:
Let data be the data stored in the buffer described
by the ArrayBuffer
object and increase the
bufferedAmount
attribute by the length of the ArrayBuffer
in bytes.
ArrayBufferView
object:
Let data be the data stored in the section of the
buffer described by the ArrayBuffer
object that the
ArrayBufferView
object references and increase the
bufferedAmount
attribute by the length of the
ArrayBufferView
in bytes.
If channel’s underlying data transport is not
established yet, or if the closing procedure
has
started, then abort these steps.
Attempt to send data on channel’s underlying data transport; if the data cannot be sent, e.g. because it would need to be buffered but the buffer is full, the user agent MUST abruptly close channel’s underlying data transport with an error.
enum RTCDataChannelState {
"connecting",
"open",
"closing",
"closed"
};
Enumeration description | |
---|---|
connecting |
The user agent is attempting to establish the underlying data
transport. This is the initial state of a
|
open |
The underlying data transport is established and
communication is possible. This is the initial state of a
|
closing |
The |
closed |
The underlying data transport has been |
The datachannel
event uses the
interface.RTCDataChannelEvent
Firing a datachannel event named
e with a
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
channel
attribute set to
channel, MUST be created and dispatched at the given
target.
dictionary RTCDataChannelEventInit : EventInit {
RTCDataChannel
channel;
};
[Constructor(DOMString type, RTCDataChannelEventInit eventInitDict)]
interface RTCDataChannelEvent : Event {
readonly attribute RTCDataChannel
channel;
};
channel
of type RTCDataChannel
, readonly The channel
attribute
represents the
object associated
with the event.RTCDataChannel
RTCDataChannelEventInit
Memberschannel
of type RTCDataChannel
TODO
A
object MUST not be garbage
collected if itsRTCDataChannel
readyState
is connecting
and at least one event listener is
registered for open
events, message
events,
error
events, or close
events.
readyState
is open
and at least one event listener is registered
for message
events, error
events, or
close
events.
readyState
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.
In order to send DTMF (phone keypad) values across an
, the user agent needs to know which RTCPeerConnection
MediaStreamTrack
on which
will carry the DTMF. This section describes an interface on RTCPeerConnection
to associate DTMF capability with a RTCPeerConnection
MediaStreamTrack
for that
.RTCPeerConnection
The Peer-to-peer DTMF API extends the
interface as described below.RTCPeerConnection
partial interface RTCPeerConnection {
RTCDTMFSender
createDTMFSender (MediaStreamTrack track);
};
createDTMFSender
The createDTMFSender() method creates an RTCDTMFSender that
references the given MediaStreamTrack. The
MediaStreamTrack MUST be an element of a MediaStream
that's currently in the
object's local streams set; if
not, throw an exception with an RTCPeerConnection
RTCError
object of type
INVALID_MEDIASTREAMTRACK
.
Parameter | Type | Nullable | Optional | Description |
---|---|---|---|---|
track | MediaStreamTrack | ✘ | ✘ |
RTCDTMFSender
An
is created by calling the RTCDTMFSender
createDTMFSender()
method on an
. This constructs an object that exposes the functions required to send DTMF on the given RTCPeerConnection
MediaStreamTrack
.
[NoInterfaceObject]
interface RTCDTMFSender {
readonly attribute boolean canInsertDTMF;
void insertDTMF (DOMString tones, optional long duration, optional long interToneGap);
readonly attribute MediaStreamTrack track;
attribute EventHandler ontonechange;
readonly attribute DOMString toneBuffer;
readonly attribute long duration;
readonly attribute long interToneGap;
};
canInsertDTMF
of type boolean, readonly The canInsertDTMF
attribute MUST indicate if the
is capable of sending
DTMF.RTCDTMFSender
duration
of type long, readonly The duration
attribute MUST return the current tone duration value. This
value will be the value last set via
the insertDTMF()
method, or the default
value of 100 ms if insertDTMF()
was
called without specifying the duration.
interToneGap
of type long, readonly The interToneGap
attribute MUST return the current value of the between-tone
gap. This value will be the value last set via
the insertDTMF()
method, or the default
value of 50 ms if insertDTMF()
was
called without specifying the interToneGap.
ontonechange
of type EventHandler, This event handler uses
the
interface to
return the character for each tone as it is played out.
See RTCDTMFToneChangeEvent
for
details.RTCDTMFToneChangeEvent
toneBuffer
of type DOMString, readonly The toneBuffer
attribute MUST return a list of the tones remaining to be
played out. For the syntax, content, and interpretation of
this list, see insertDTMF
.
track
of type MediaStreamTrack, readonly The track
attribute MUST return
the MediaStreamTrack
given as argument
to the createDTMFSender()
method.
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 are equivalent to A to D. The character ',' indicates a delay of 2 seconds before processing the next character in the tones parameter. Unrecognized characters are ignored.
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 70 ms. The default duration is 100 ms for each tone.
The interToneGap parameter indicates the gap between tones. It MUST be at least 50 ms. The default value is 50 ms.
ISSUE: How are invalid values handled?
When the insertDTMF()
method is invoked, the user agent MUST run the following steps:
MediaStreamTrack
is not connected to the associated RTCPeerConnection
, return.canInsertDTMF
attribute is false, return.toneBuffer
attribute to the value of the tones argument, the value of the duration
attribute to the duration argument if specified, and the value of the interToneGap
to the interToneGap argument, if specified.toneBuffer
is an empty string, return.toneBuffer
is an empty string, fire an event named tonechange
with an empty string at the RTCDTMFSender
object and abort these steps.toneBuffer
and let that character be tone.duration
ms on the
associated RTP media stream, using the appropriate codec.duration
+ interToneGap
ms from now that runs the steps labelled Playout task.tonechange
with a string consisting of tone at the RTCDTMFSender
object.Calling insertDTMF()
with an empty
tones parameter can be used to cancel all tones queued to play after
the currently playing tone.
Parameter | Type | Nullable | Optional | Description |
---|---|---|---|---|
tones | DOMString | ✘ | ✘ | |
duration | long | ✘ | ✔ | |
interToneGap | long | ✘ | ✔ |
void
The tonechange
event uses the
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
tone
attribute set to
tone, MUST be created and dispatched at the given
target.
[Constructor(DOMString type, RTCDTMFToneChangeEventInit eventInitDict)]
interface RTCDTMFToneChangeEvent : Event {
readonly attribute DOMString tone;
};
tone
of type DOMString, readonly The tone
attribute contains the character for the tone that has
just begun playout (see insertDTMF()
).
If the value is the empty string, it indicates that the
previous tone has completed playback.
The basic statistics model is that the browser maintains a set of
statistics referenced by a selector. The
selector may, for example, be a MediaStreamTrack
. For a
track to be a valid selector, it must be a member of a
MediaStream
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 it believes is relevant to the selector.
The statistics returned are designed in such a way that repeated
queries can be linked by the
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.RTCStats
The Statistics API extends the
interface as described below.RTCPeerConnection
partial interface RTCPeerConnection {
void getStats (MediaStreamTrack? selector, RTCStatsCallback
successCallback, RTCPeerConnectionErrorCallback
failureCallback);
};
getStats
Gathers stats for the given selector and reports the result asynchronously.
When the
getStats()
method is invoked, the user agent MUST
queue a task to run the following steps:
If the
object's
RTCPeerConnection
RTCPeerConnection
signalingState is closed
, throw an
INVALID_STATE
exception.
Return, but continue the following steps in the background.
Let selectorArg be the methods first argument.
If selectorArg is an invalid selector, the user agent MUST queue a task to invoke the failure callback (the method's third argument).
Start gathering the stats indicated by
selectorArg. In case selectorArg is null,
stats MUST be gathered for the whole
object.RTCPeerConnection
When the relevant stats have been gathered, queue a task to
invoke the success callback (the method's second argument) with
a new
object, representing
the gathered stats, as its argument.RTCStatsReport
Parameter | Type | Nullable | Optional | Description |
---|---|---|---|---|
selector | MediaStreamTrack | ✔ | ✘ | |
successCallback |
| ✘ | ✘ | |
failureCallback |
| ✘ | ✘ |
void
callback RTCStatsCallback = void (RTCStatsReport
report);
RTCStatsCallback
Parametersreport
of type RTCStatsReport
A
representing the gathered
stats.RTCStatsReport
The getStats()
method delivers a successful result in the form of a
object. A RTCStatsReport
object represents a map between strings,
identifying the inspected objects
(RTCStats.id), and their
corresponding RTCStatsReport
objects.RTCStats
An
may be composed of
several RTCStatsReport
objects, 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 a RTCStats
MediaStreamTrack
is
carried by multiple SSRCs over the network, the
may contain one RTCStatsReport
RTCStats
object
per SSRC (which can be distinguished by the value of the "ssrc" stats
attribute).
interface RTCStatsReport {
getter RTCStats (DOMString id);
};
RTCStats
Getter to retrieve the
objects that
this stats report is composed of.RTCStats
The set of supported property names [WEBIDL] is defined as the
ids of all the
objects that has been
generated for this stats report. The order of the property names is
left to the user agent.RTCStats
Parameter | Type | Nullable | Optional | Description |
---|---|---|---|---|
id | DOMString | ✘ | ✘ |
getter
An
dictionary represents the stats gathered
by inspecting a specific object relevant to a selector. 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.RTCStats
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 a
object.RTCStats
dictionary RTCStats {
DOMHiResTimeStamp timestamp;
RTCStatsType
type;
DOMString id;
};
RTCStats
Membersid
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
timestamp
of type DOMHiResTimeStampThe timestamp
,
of type DOMHiResTimeStamp
[HIGHRES-TIME], associated
with this object. The time is relative to the UNIX epoch (Jan 1,
1970, UTC).
type
of type RTCStatsType
The type of this object.
The type
attribute MUST be initialized to the name of the most specific type
this
dictionary represents.RTCStats
enum RTCStatsType {
"inbound-rtp",
"outbound-rtp"
};
Enumeration description | |
---|---|
inbound-rtp | Inbound RTP. |
outbound-rtp | Outbund RTP. |
dictionary RTCRTPStreamStats : RTCStats
{
DOMString ssrc;
DOMString remoteId;
};
RTCRTPStreamStats
MembersremoteId
of type DOMStringThe remoteId
can be used to look up the corresponding
object that represents stats reported
by the other peer.RTCStats
ssrc
of type DOMString...
dictionary RTCInboundRTPStreamStats : RTCRTPStreamStats
{
unsigned long packetsReceived;
unsigned long bytesReceived;
};
RTCInboundRTPStreamStats
MembersbytesReceived
of type unsigned long...
packetsReceived
of type unsigned long...
dictionary RTCOutboundRTPStreamStats : RTCRTPStreamStats
{
unsigned long packetsSent;
unsigned long bytesSent;
};
RTCOutboundRTPStreamStats
MembersbytesSent
of type unsigned long...
packetsSent
of type unsigned long...
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:
var baselineReport, currentReport; var selector = pc.getRemoteStreams()[0].getAudioTracks()[0]; pc.getStats(selector, function (report) { baselineReport = report; }); // ... wait a bit setTimeout(function () { pc.getStats(selector, function (report) { currentReport = report; processStats(); }); }, aBit); function processStats() { // compare the elements from the current report with the baseline for each (var now in currentReport) { if (now.type != "outbund-rtp") continue; // get the corresponding stats from the baseline report base = baselineReport[now.id]; if (base) { remoteNow = currentReport[now.remoteId]; remoteBase = baselineReport[base.remoteId]; var packetsSent = now.packetsSent - base.packetsSent; var packetsReceived = remoteNow.packetsReceived - remoteBase.packetsReceived; // if fractionLost is > 0.3, we have probably found the culprit var fractionLost = (packetsSent - packetsReceived) / packetsSent; } } }
WebRTC offers and answers (and hence the channels established by
RTCPeerConnection
objects) can be authenticated by using
web-based Identity Providers. The idea is that the entity sending the
offer/answer acts as the Authenticating Party (AP) and obtains an
identity assertion from the IdP which it attaches to the offer/answer.
The consumer of the offer/answer (i.e., the
RTCPeerConnection
on which
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 -- which is deterministic from the IdP's identity -- and the generic protocol for requesting and verifying 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. The generic protocol details are described in [RTCWEB-SECURITY-ARCH]. This document specifies the procedures required to instantiate the IdP proxy, request identity assertions, and consume the results.
In order to communicate with the IdP, the browser must instantiate an isolated interpreted context [TODO: What's the technical term?], such as an invisible IFRAME. The initial contents of the context are loaded from a URI derived from the IdP's domain name. [RTCWEB-SECURITY-ARCH; Section XXX].
For purposes of generating assertions, the IdP shall be chosen as follows:
setIdentityProvider()
method has been called,
the IdP provided shall be used.setIdentityProvider()
method has not been
called, then the browser shall use an IdP configured into the
browser. If more than one such IdP is configured, the browser should
provide the user with a chooser interface.In order to verify assertions, the IdP domain name and protocol shall be equal to the "domain" and "protocol" fields of the identity assertion.
The context MUST have a MessageChannel
named
window.TBD
which is "entangled" to the
RTCPeerConnection
and is unique to that subcontext. This
channel is used for messaging between the
RTCPeerConnection
and the IdP. All messages sent via this
channel are strings, specifically the JSONified versions of JavaScript
structs.
All messages sent from the RTCPeerConnection
to the IdP
context MUST have an origin
of
rtcweb://peerconnection/
. The fact that ordinary Web pages
cannot set their origin values arbitrarily is an essential security
feature, as it stops attackers from requesting WebRTC-compatible
identity assertions from IdPs. For this reason, the origin must be
included in the identity assertion and verified by the consuming
RTCPeerConnection
.
The identity assertion request process involves the following steps.
RTCPeerConnection
instantiates an IdP context as
described in the previous section.RTCPeerConnection
desires to be bound to the user's
identity.RTCPeerConnection
over the message channel.RTCPeerConnection
stores the assertion for use
with future offers or answers. If the identity request was triggered
by a createOffer()
or createAnswer()
, then
the assertion is inserted in the offer/answer.The identity assertion request process involves the following steps.
RTCPeerConnection
instantiates an IdP context as
described in the previous section.PostMessage
calls.RTCPeerConnection
over the message channel.RTCPeerConnection
displays the assertion
information in the browser UI and stores the assertion in the
peerIdentity
attribute for availability to the JavaScript application. The
assertion information to be displayed shall contain the domain name
of the IdP and the identity returned by the IdP and must be displayed
via some mechanism which cannot be spoofed by content. [[OPEN ISSUE:
The identity information should also be available in the inspector
interface defined in [RTCWEB-SECURITY-ARCH; Section 5.5].The Identity API extends the
interface as described below.RTCPeerConnection
partial interface RTCPeerConnection {
void setIdentityProvider (DOMString provider, optional DOMString protocol, optional DOMString username);
void getIdentityAssertion ();
readonly attribute RTCIdentityAssertion
? peerIdentity;
attribute EventHandler onidentityresult;
};
onidentityresult
of type EventHandler, identityresult
, MUST be fired by
all objects implementing the RTCPeerConnection
interface. It is called any time an identity verification succeeds or
fails.peerIdentity
of type RTCIdentityAssertion
, readonly , nullableContains the peer identity assertion information if an identity assertion was provided and verified.
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 setIdentityProvider()
method
was called, then an identity will be automatically requested when
an offer or answer is created.
Queue a task to run the following substeps.
If the connection's RTCPeerConnection
signalingState is closed
, abort these
steps.
Instantiate a new IdP proxy and request an identity assertion.
void
setIdentityProvider
Sets the identity provider to be used for a given
PeerConnection
object. Applications need not make this
call; if the browser is already configured for an IdP, then that
configured IdP will be used to get an assertion.
When the setIdentityProvider()
method is invoked, the user
agent MUST run the following steps:
Set the current identity values to the triplet
(provider
, protocol
,
username
).
If the
object's
RTCPeerConnection
RTCPeerConnection
signalingState is stable
, and any of
the identity settings have changed, queue a task to run the
following substeps:
If the connection's RTCPeerConnection
signalingState is closed
, abort these
steps, and throw an exception with an RTCError
object of type INVALID_STATE
.
Instantiate a new IdP proxy and request an identity assertion.
If/when the assertion is obtained, fire a negotiationneeded event.
Parameter | Type | Nullable | Optional | Description |
---|---|---|---|---|
provider | DOMString | ✘ | ✘ | |
protocol | DOMString | ✘ | ✔ | |
username | DOMString | ✘ | ✔ |
void
dictionary RTCIdentityAssertion {
DOMString idp;
DOMString name;
};
RTCIdentityAssertion
Membersidp
of type DOMStringA domain name representing the identity provider.
name
of type DOMStringAn RFC822-conformant [TODO: REF] 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 and protocol.
pc.setIdentityProvider("example.com", "default", "alice@example.com");
This example shows how to consume identity assertions inside a Web application.
pc.onidentityresult = function(result) { console.log("IdP= " + pc.peerIdentity.idp + " identity=" + pc.peerIdentity.name); };
The MediaStream
interface, as defined in the
[GETUSERMEDIA] specification, typically represents a stream of data of
audio and/or video. A MediaStream
may be extended to
represent a stream that either comes from or is sent to a remote node
(and not just the local camera, for instance). The extensions required to
enable this capability on the MediaStream
object will be
described in this document.
A MediaStream
as defined in [GETUSERMEDIA] may contain
zero or more MediaStreamTrack
objects. 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.
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
MediaStream
apply in the case of MediaStream
objects transmitted over the network as well. A
MediaStream
created by an
object (described later in this
document) will take as input the data received from a remote peer.
Similarly, a RTCPeerConnection
MediaStream
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
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 tracks from different
MediaStream
objects into a new
MediaStream
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 after they are sent through the
RTCPeerConnection
API.
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, a locally generated
stream could be sent from one user agent to a remote peer using
and then sent back to the
original user agent in the same manner, in which case the original user
agent will have multiple streams with the same id (the
locally-generated one and the one received from the remote peer).RTCPeerConnection
A new media track may be associated with an existing
MediaStream
. For example, if a remote peer adds a
new MediaStreamTrack
object to a
MediaStream
that is being sent over an
, this is observed on the local
user agent. If this happens for the reason exemplified, or for any
other reason than the RTCPeerConnection
addTrack()
method being invoked locally on a MediaStream
or
tracks being added as the stream is created (i.e. the stream is
initialized with tracks), the user agent MUST run the following steps:
Let stream be the target
MediaStream
object.
Represent component with track: Run the following steps to create a track representing the incoming component:
Create a MediaStreamTrack
object
track to represent the component.
Initialize track’s kind
attribute to "audio
" or "video
"
depending on the media type of the incoming component.
Initialize track’s id
attribute to the component track id.
Initialize track’s label
attribute to "remote audio
" or "remote
video
" depending on the media type of the incoming
component.
Initialize track’s readyState
attribute to muted
.
Add track to stream’s track set.
Fire a track event named
addtrack
with the newly created
MediaStreamTrack
object at stream.
An existing media track may also be disassociated from a
MediaStream
. If this happens for any other reason
than the removeTrack()
method being invoked locally on a MediaStream
or the
stream being destroyed, the user agent MUST run the following steps:
Let stream be the target
MediaStream
object.
Let track be the MediaStreamTrack
object representing the media component about to be removed.
Remove track from stream’s track set.
Fire a track event named
removetrack
with track at stream.
The event source for the onended
event in the networked
case is the
object.RTCPeerConnection
A MediaStreamTrack
object’s reference to its
MediaStream
in the non-local media source case (an RTP
source, as is the case for a MediaStream
received over an
) is always strong.RTCPeerConnection
When a track belongs to a MediaStream
that comes
from a remote peer and the remote peer has permanently stopped sending
data the ended
event MUST be fired on the track, as
specified in [GETUSERMEDIA].
ISSUE: How do you know when it has stopped? This seems like an SDP question, not a media-level question.
A track in a MediaStream
, received with an
, MUST have its
RTCPeerConnection
readyState
attribute [GETUSERMEDIA] set to
muted
until media data arrives.
In addition, a MediaStreamTrack
has its
readyState
set to muted
on the remote peer if
the local user agent disables the corresponding
MediaStreamTrack
in the
MediaStream
that is being sent. When the addstream
event triggers on an
, all
RTCPeerConnection
MediaStreamTrack
objects in the resulting
MediaStream
are muted until media data can be read
from the RTP source.
ISSUE: How do you know when it has been disabled? This seems like an SDP question, not a media-level question.
The addstream
and removestream
events use the
interface.MediaStreamEvent
Firing a
stream event named e with a
MediaStream
stream 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
MediaStreamEvent
stream
attribute
set to stream, MUST be created and dispatched at the
given target.
dictionary MediaStreamEventInit : EventInit {
MediaStream stream;
};
[Constructor(DOMString type, MediaStreamEventInit eventInitDict)]
interface MediaStreamEvent : Event {
readonly attribute MediaStream? stream;
};
stream
of type MediaStream, readonly , nullableThe stream
attribute
represents the MediaStream
object associated with
the event.
MediaStreamEventInit
Membersstream
of type MediaStream
This section is non-normative.
This section is non-normative.
When two peers decide they are going to set up a connection to each other, they both go through these steps. The STUN/TURN server configuration describes a server they can use to get things like their public IP address or to set up NAT traversal. They also have to send data for the signaling channel to each other using the same out-of-band mechanism they used to establish that they were going to communicate in the first place.
var signalingChannel = new SignalingChannel(); var configuration = { "iceServers": [{ "url": "stun:stun.example.org" }] }; var pc; // call start() to initiate function start() { pc = new RTCPeerConnection(configuration); // send any ice candidates to the other peer pc.onicecandidate = function (evt) { if (evt.candidate) signalingChannel.send(JSON.stringify({ "candidate": evt.candidate })); }; // let the "negotiationneeded" event trigger offer generation pc.onnegotiationneeded = function () { pc.createOffer(localDescCreated, logError); } // once remote stream arrives, show it in the remote video element pc.onaddstream = function (evt) { remoteView.src = URL.createObjectURL(evt.stream); }; // get a local stream, show it in a self-view and add it to be sent navigator.getUserMedia({ "audio": true, "video": true }, function (stream) { selfView.src = URL.createObjectURL(stream); pc.addStream(stream); }); } function localDescCreated(desc) { pc.setLocalDescription(desc, function () { signalingChannel.send(JSON.stringify({ "sdp": pc.localDescription })); }, logError); } signalingChannel.onmessage = function (evt) { if (!pc) start(); var message = JSON.parse(evt.data); if (message.sdp) pc.setRemoteDescription(new RTCSessionDescription(message.sdp), function () { // if we received an offer, we need to answer if (pc.remoteDescription.type == "offer") pc.createAnswer(localDescCreated, logError); }, logError); else pc.addIceCandidate(new RTCIceCandidate(message.candidate)); }; function logError(error) { log(error.name + ": " + error.message); }
This example shows the more complete functionality.
TODO
This example shows how to create a
object and perform the offer/answer
exchange required to connect the channel to the other peer. The
RTCDataChannel
is used in the context of a simple
chat application and listeners are attached to monitor when the channel
is ready, messages are received and when the channel is closed.RTCDataChannel
This example uses the negotiationneeded
event to initiate the offer/answer dialog. The exact behavior
surrounding the negotiationneeded
event is not specified
in detail at the moment. This example can hopefully help to drive that
discussion. An assumption made in this example is that the event only
triggers when a new negotiation should be started. This means that an
action (such as addStream()) that normally would have fired the
negotiationneeded
event will not do so during an ongoing
offer/answer dialog.
var signalingChannel = new SignalingChannel(); var configuration = { "iceServers": [{ "url": "stun:stun.example.org" }] }; var pc; var channel; // call start(true) to initiate function start(isInitiator) { pc = new RTCPeerConnection(configuration); // send any ice candidates to the other peer pc.onicecandidate = function (evt) { if (evt.candidate) signalingChannel.send(JSON.stringify({ "candidate": evt.candidate })); }; // let the "negotiationneeded" event trigger offer generation pc.onnegotiationneeded = function () { pc.createOffer(localDescCreated, logError); } if (isInitiator) { // create data channel and setup chat channel = pc.createDataChannel("chat"); setupChat(); } else { // setup chat on incoming data channel pc.ondatachannel = function (evt) { channel = evt.channel; setupChat(); }; } } function localDescCreated(desc) { pc.setLocalDescription(desc, function () { signalingChannel.send(JSON.stringify({ "sdp": pc.localDescription })); }, logError); } signalingChannel.onmessage = function (evt) { if (!pc) start(false); var message = JSON.parse(evt.data); if (message.sdp) pc.setRemoteDescription(new RTCSessionDescription(message.sdp), function () { // if we received an offer, we need to answer if (pc.remoteDescription.type == "offer") pc.createAnswer(localDescCreated, logError); }, logError); else pc.addIceCandidate(new RTCIceCandidate(message.candidate)); }; function setupChat() { channel.onopen = function () { // e.g. enable send button enableChat(channel); }; channel.onmessage = function (evt) { showChatMessage(evt.data); }; } function sendChatMessage(msg) { channel.send(msg); } function logError(error) { log(error.name + ": " + error.message); }
Editors' Note: This example flow needs to be discussed on the list and is likely wrong in many ways.
This shows an example of one possible call flow between two browsers. This does not show the procedure to get access to local media or every callback that gets fired but instead tries to reduce it down to only show the key events and messages.
Examples assume that pc is a connected RTCPeerConnection, and track is an audio track on that connection.
Sending the DTMF signal "1234" with 500 ms duration per tone:
var sender = pc.createDTMFSender(track); if (sender.canInsertDTMF) { var duration = 500; sender.insertDTMF("1234", duration); } else log("DTMF function not available");
Send the DTMF signal "1234", and light up the active key using
lightKey(key)
while the tone is playing (assuming that
lightKey("")
will darken all the keys):
var sender = pc.createDTMFSender(track); sender.ontonechange = function (e) { if (!e.tone) return; // light up the key when playout starts lightKey(e.tone); // turn off the light after tone duration setTimeout(lightKey, sender.duration, ""); }; sender.insertDTMF("1234");
Send a 1-second "1" tone followed by a 2-second "2" tone:
var sender = pc.createDTMFSender(track); sender.ontonechange = function (e) { if (e.tone == "1") sender.insertDTMF("2", 2000); }; sender.insertDTMF("1", 1000);
It is always safe to append to the tone buffer. This example appends before any tone playout has started as well as during playout.
var sender = pc.createDTMFSender(track); sender.insertDTMF("123"); // append more tones to the tone buffer before playout has begun sender.insertDTMF(sender.toneBuffer + "456"); sender.ontonechange = function (e) { if (e.tone == "1") // append more tones when playout has begun sender.insertDTMF(sender.toneBuffer + "789"); };
Send the DTMF signal "123" and abort after sending "2".
var sender = pc.createDTMFSender(track); sender.ontonechange = function (e) { if (e.tone == "2") // empty the buffer to not play any tone after "2" sender.insertDTMF(""); }; sender.insertDTMF("123");
This section is non-normative.
The following events fire on
objects:RTCDataChannel
Event name | Interface | Fired when... |
---|---|---|
open |
Event |
The object's underlying data
transport has been established (or re-established).
|
MessageEvent |
Event |
A message was successfully received. TODO: Ref where MessageEvent is defined? |
error |
Event |
TODO. |
close |
Event |
The object's underlying data
transport has bee closed.
|
The following events fire on
objects:RTCPeerConnection
Event name | Interface | Fired when... |
---|---|---|
connecting |
Event |
TODO |
addstream |
|
A new stream has been added to the remote streams set. |
removestream |
|
A stream has been removed from the remote streams set. |
negotiationneeded |
Event |
The browser wishes to inform the application that session negotiation needs to be done at some point in the near future. |
signalingstatechange |
Event |
The RTCPeerConnection
signalingState has changed. This state change is the result of
either setLocalDescription()
or setRemoteDescription()
being invoked. |
iceconnectionstatechange |
Event |
The RTCPeerConnection
ice connection state has changed. |
icecandidate |
|
A new is made available to
the script. |
identityresult |
RTCIdentityEvent |
TODO |
The following events fire on
objects:RTCDTMFSender
Event name | Interface | Fired when... |
---|---|---|
tonechange |
Event |
The object has either just begun playout of a tone (returned as the tone attribute) or just ended playout of a tone (returned as an empty value in the tone attribute).
|
TBD.
IANA is requested to register the constraints defined in Constraints Section as specified in [RTCWEB-CONSTRAINTS].
TOOD: Need to change the naming and declaration of these constraints to match the constraints draft once that is a bit further along. The names here now are likely not quite right but they serve as a place holder.
ISSUE: there are multiple ways to add constraints. How are multiple values reconciled?
The following new constraints are defined that can be used with an
RTCPeerConnection
object:
This is an enum type constraint that can take the values "true"
and "false". The default is a non mandatory "true" for an
RTCPeerConnection
object that has a video stream at the
point in time when the constraints are being evaluated and is non
mandatory "false" otherwise.
In some cases, an RTCPeerConnection
may wish to
receive video but not send any video. The
RTCPeerConnection
needs to know if it should signal to
the remote side whether it wishes to receive video or not. This
constraint allows an application to indicate its preferences for
receiving video when creating an offer.
This is an enum type constraint that can take the values "true" and "false". The default is a non mandatory "true".
In some cases, an RTCPeerConnection
may wish to
receive audio but not send any audio. The
RTCPeerConnection
needs to know if it should signal to
the remote side whether it wishes to receive audio. This constraints
allows an application to indicate its preferences for receiving audio
when creating an offer.
This is an enum type constraint that can take the values "true" and "false". The default is a non mandatory "true".
Many codecs and system 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 sounds other than spoken voice or emergency calling, it is desirable to be able to turn off this behavior. This constraint allows the application to provide information about whether it wishes this type of processing enabled or disabled.
This is an enum type constraint that can take the values "none", "relay", and "all". The default is a non mandatory "all".
This constraint indicates which candidates the ICE engine is allowed to use. The value "none" means the ICE engine MUST not send or receive any packets at this point. The value "relay" indicates the ICE engine MUST only use media relay candidates such as candidates passing through a TURN server. This can be used to reduce leakage of IP addresses in certain use cases. The value of "all" indicates all values can be used.
This is an enum type constraint that can take the values "yes", "no", and "ifconfigured". The default is a non mandatory "ifconfigured".
This constraint indicates whether an identity should be requested.
The constraint may be used with either of the
createOffer()
or createAnswer()
calls or
with the constructor. The value "yes" means that an identity must be
requested. The value "no" means that no identity is to be requested.
The value "ifconfigured" means that an identity will be requested if
either the user has configured an identity in the browser or if the
setIdentityProvider()
call has been made in JavaScript.
As this is the default value, an identity will be requested if and
only if the user has configured an IdP in some way. Note that as long
as DTLS-SRTP is in used, fingerprints will be sent regardless of the
value of this constraint.
TODO items - need to register with IANA.
This section will be removed before publication.
The editors wish to thank the Working Group chairs and Team Contact, Harald Alvestrand, Stefan Håkansson and Dominique Hazaël-Massieux, for their support. Substantial text in this specification was provided by many people including Harald Alvestrand, Justin Uberti, and Eric Rescorla.