Abstract

This document defines a set of JavaScript APIs that allow local media, including audio and video, to be requested from a platform.

Status of This Document

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 not complete. It is subject to major changes and, while early experimentations are encouraged, it is therefore not intended for implementation. The API is based on preliminary work done in the WHATWG.

This document was published by the Web Real-Time Communication Working Group and Device APIs Working Group as an Editor's Draft. If you wish to make comments regarding this document, please send them to public-media-capture@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 (Web Real-Time Communication Working Group, Device APIs Working Group) 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.

Table of Contents

1. Introduction

This section is non-normative.

Access to multimedia streams (video, audio, or both) from local devices (video cameras, microphones, Web cams) can have a number of uses, such as real-time communication, recording, and surveillance.

This document defines the APIs used to get access to local devices that can generate multimedia stream data. This document also defines the MediaStream API by which JavaScript is able to manipulate the stream data or otherwise process it.

2. Conformance

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.

3. Terminology

HTML Terms:

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].

source

A source is the "thing" providing the source of a media stream track. The source is the broadcaster of the media itself. A source can be a physical webcam, microphone, local video or audio file from the user's hard drive, network resource, or static image.

Some sources have an identifier which must be unique to the application (un-guessable by another application) and persistent between application sessions (e.g., the identifier for a given source device/application must stay the same, but not be guessable by another application). Sources that must have an identifier are camera and microphone sources; local file sources are not required to have an identifier. Source identifiers let the application save, identify the availability of, and directly request specific sources.

Other than the identifier, other bits of source identity are never directly available to the application until the user agent connects a source to a track. Once a source has been "released" to the application (either via a permissions UI, pre-configured allow-list, or some other release mechanism) the application will be able discover additional source-specific capabilities.

Sources do not have constraints -- tracks have constraints. When a source is connected to a track, it must conform to the constraints present on that track (or set of tracks).

Sources will be released (un-attached) from a track when the track is ended for any reason.

On the MediaStreamTrack object, sources are represented by a sourceType attribute. The behavior of APIs associated with the source's capabilities and settings change depending on the source type.

Sources have capabilities and settings. The capabilities and settings are "owned" by the source and are common to any (multiple) tracks that happen to be using the same source (e.g., if two different track objects bound to the same source ask for the same capability or setting information, they will get back the same answer).

Setting (Source Setting)

A setting refers to the immediate, current value of the source's (optionally constrained) capabilities. Settings are always read-only.

A source's settings can change dynamically over time due to environmental conditions, sink configurations, or constraint changes. A source's settings must always conform to the current set of mandatory constraints that all of the tracks it is bound to have defined, and should do its best to conform to the set of optional constraints specified.

A source's settings are directly exposed to audio and video track objects through individual read-only attributes. These attributes share the same name as their corresponding capabilities and constraints.

Events are available that signal to the application that a source's settings have changed.

A conforming user-agent must support all the setting names defined in this spec.

Capabilities

Source capabilities are the intrinsic "features" of a source object. For each source setting, there is a corresponding capability that describes whether it is supported by the source and if so, what the range of supported values are. Capabilities are expressed as either a series of settings (for enumerated-type capabilities) or as a min/max range.

The values of the supported capabilities must be normalized to the ranges and enumerated types defined in this specification.

Capabilities return the same underlying per-source capabilities, regardless of any user-supplied constraints present on the source (capabilities are independent of constraints).

Source capabilities are effectively constant. Applications should be able to depend on a specific source having the same capabilities for any session.

Constraints

Constraints are an optional feature for restricting the range of allowed variability on a source. Without provided constraints, implementations are free to select a source's settings from the full ranges of its supported capabilities, and to adjust those settings at any time for any reason.

Constraints may be optional or mandatory. Optional constraints are represented by an ordered list, mandatory constraints are an unordered set. The order of the optional constraints is from most important (at the head of the list) to least important (at the tail of the list).

Constraints are stored on the track object, not the source. Each track can be optionally initialized with constraints, or constraints can be added afterward through the constraint APIs defined in this spec.

Applying track level constraints to a source is conditional based on the type of source. For example, read-only sources will ignore any specified constraints on the track.

It is possible for two tracks that share a unique source to apply contradictory constraints. Under such contradictions, the implementation will mute both tracks and notify them that they are over-constrained.

Events are available that allow the application to know when constraints cannot be met by the user agent. These typically occur when the application applies constraints beyond the capability of a source, contradictory constraints, or in some cases when a source cannot sustain itself in over-constrained scenarios (overheating, etc.).

A correspondingly-named constraint exists for each corresponding source setting name and capability name. In general, user agents will have more flexibility to optimize the media streaming experience the fewer constraints are applied.

4. MediaStream API

4.1 Introduction

The MediaStream interface is used to represent streams of media data, typically (but not necessarily) of audio and/or video content, e.g. from a local camera. The data from a MediaStream object does not necessarily have a canonical binary form; for example, it could just be "the video currently coming from the user's video camera". This allows user agents to manipulate media streams in whatever fashion is most suitable on the user's platform.

Each MediaStream object can contain zero or more tracks, in particular audio and video tracks. All tracks in a MediaStream are intended to be synchronized when rendered. Different MediaStreams do not need to be synchronized.

Each track in a MediaStream object has a corresponding MediaStreamTrack object.

A MediaStreamTrack represents content comprising one or more channels, where the channels have a defined well known relationship to each other (such as a stereo or 5.1 audio signal).

A channel is the smallest unit considered in this API specification.

A MediaStream object has an input and an output. The input depends on how the object was created: a MediaStream object generated by a getUserMedia() call (which is described later in this document), for instance, might take its input from the user's local camera. The output of the object controls how the object is used, e.g., what is saved if the object is written to a file or what is displayed if the object is used in a video element.

Each track in a MediaStream object can be disabled, meaning that it is muted in the object's output. All tracks are initially enabled.

A MediaStream can be finished, indicating that its inputs have forever stopped providing data.

The output of a MediaStream object MUST correspond to the tracks in its input. Muted audio tracks MUST be replaced with silence. Muted video tracks MUST be replaced with blackness.

A new MediaStream object can be created from accessible media sources (that does not require any additional permissions) using the MediaStream() constructor. The constructor argument can either be an existing MediaStream object, in which case all the tracks of the given stream are added to the new MediaStream object, or an array of MediaStreamTrack objects. The latter form makes it possible to compose a stream from different source streams.

A MediaStream

Both MediaStream and MediaStreamTrack objects can be cloned. This allows for greater control since the separate instances can be manipulated and consumed individually. A cloned MediaStream contains clones of all member tracks from the original stream.

When a MediaStream object is being generated from a local file (as opposed to a live audio/video source), the user agent SHOULD stream the data from the file in real time, not all at once. The MediaStream object is also used in contexts outside getUserMedia, such as [WEBRTC10]. In both cases, ensuring a realtime stream reduces the ease with which pages can distinguish live video from pre-recorded video, which can help protect the user's privacy.

4.2 MediaStream

The MediaStream() constructor composes a new stream out of existing tracks. It takes an optional argument of type MediaStream or an array of MediaStreamTrack objects. When the constructor is invoked, the UA must run the following steps:

  1. Let stream be a newly constructed MediaStream object.

  2. Initialize stream's id attribute to a newly generated value.

  3. If the constructor's argument is present, run the sub steps that corresponds to the argument type.

  4. If stream's track set is empty, set stream's active attribute to false, otherwise set it to true.

  5. Return stream.

A MediaStream can have multiple audio and video sources (e.g. because the user has multiple microphones, or because the real source of the stream is a media resource with many media tracks). The stream represented by a MediaStream thus has zero or more tracks.

The tracks of a MediaStream are stored in a track set. The track set MUST contain the MediaStreamTrack objects that correspond to the tracks of the stream. The relative order of the tracks in the set is user agent defined and the API will never put any requirements on the order. The proper way to find a specific MediaStreamTrack object in the set is to look it up by its id.

An object that reads data from the output of a MediaStream is referred to as a MediaStream consumer. The list of MediaStream consumers currently include the media elements [HTML5], RTCPeerConnection [WEBRTC10], MediaRecorder [mediastream-rec] and ImageCapture [mediastream-imagecap].

Note

MediaStream consumers must be able to handle tracks being added and removed. This behavior is specified per consumer.

A MediaStream object is said to be inactive when it does not have any tracks or all tracks belonging to the stream have ended. Otherwise the stream is active. A MediaStream can start its life as inactive if it is constructed without any tracks.

When a MediaStream goes from being active to inactive, the user agent MUST queue a task that sets the object's active attribute to false and fire a simple event named inactive at the object. When a MediaStream goes from being inactive to active, the user agent MUST queue a task that sets the object's active attribute to true and fire a simple event named active at the object.

If the stream's activity status changed due to a user request, the task source for this task is the user interaction task source. Otherwise the task source for this task is the networking task source.

[ Constructor,
 Constructor (MediaStream stream),
 Constructor (sequence<MediaStreamTrack> tracks)]
interface MediaStream : EventTarget {
    readonly    attribute DOMString    id;
    sequence<MediaStreamTrack> getAudioTracks ();
    sequence<MediaStreamTrack> getVideoTracks ();
    MediaStreamTrack?          getTrackById (DOMString trackId);
    void                       addTrack (MediaStreamTrack track);
    void                       removeTrack (MediaStreamTrack track);
    MediaStream                clone ();
    readonly    attribute boolean      active;
                attribute EventHandler onactive;
                attribute EventHandler oninactive;
                attribute EventHandler onaddtrack;
                attribute EventHandler onremovetrack;
};

4.2.1 Constructors

MediaStream
See the MediaStream constructor algorithm
No parameters.
MediaStream
See the MediaStream constructor algorithm
ParameterTypeNullableOptionalDescription
streamMediaStream
MediaStream
See the MediaStream constructor algorithm
ParameterTypeNullableOptionalDescription
trackssequence<MediaStreamTrack>

4.2.2 Attributes

active of type boolean, readonly

The MediaStream.active attribute returns true if the MediaStream is active (see inactive), and false otherwise.

When a MediaStream object is created, its active attribute MUST be set to true, unless stated otherwise (for example by the MediaStream() constructor algorithm).

id of type DOMString, readonly

When a MediaStream object is created, the user agent MUST generate a globally unique identifier string, and MUST initialize the object's id attribute to that string. Such strings MUST only use characters in the ranges U+0021, U+0023 to U+0027, U+002A to U+002B, U+002D to U+002E, U+0030 to U+0039, U+0041 to U+005A, U+005E to U+007E, and MUST be 36 characters long.

The id attribute MUST return the value to which it was initialized when the object was created.

onactive of type EventHandler,
This event handler, of type active, MUST be supported by all objects implementing the MediaStream interface.
onaddtrack of type EventHandler,
This event handler, of type addtrack, MUST be supported by all objects implementing the MediaStream interface.
oninactive of type EventHandler,
This event handler, of type inactive, MUST be supported by all objects implementing the MediaStream interface.
onremovetrack of type EventHandler,
This event handler, of type removetrack, MUST be supported by all objects implementing the MediaStream interface.

4.2.3 Methods

addTrack

Adds the given MediaStreamTrack to this MediaStream.

When the addTrack() method is invoked, the user agent MUST run the following steps:

  1. Let track be the MediaStreamTrack argument and stream this MediaStream object.

  2. If stream is finished, throw an INVALID_STATE_ERR exception.

  3. If track is already in stream's track set, then abort these steps.

  4. Add track to stream's track set.

ParameterTypeNullableOptionalDescription
trackMediaStreamTrack
Return type: void
clone

Clones the given MediaStream and all its tracks.

When the clone() method is invoked, the user agent MUST run the following steps:

  1. Let streamClone be a newly constructed MediaStream object.

  2. Initialize streamClone's id attribute to a newly generated value.

  3. Let trackSetClone be a list that contains the result of running MediaStreamTrack.clone() on all the tracks in this stream.

  4. Let trackSetClone be streamClone's track set.

No parameters.
Return type: MediaStream
getAudioTracks

Returns a sequence of MediaStreamTrack objects representing the audio tracks in this stream.

The getAudioTracks() method MUST return a sequence that represents a snapshot of all the MediaStreamTrack objects in this stream's track set whose kind is equal to "audio". The conversion from the track set to the sequence is user agent defined and the order does not have to stable between calls.

No parameters.
Return type: sequence<MediaStreamTrack>
getTrackById

The getTrackById() method MUST return the first MediaStreamTrack object in this stream's track set whose id is equal to trackId. The method MUST return null if no track matches the trackId argument.

ParameterTypeNullableOptionalDescription
trackIdDOMString
Return type: MediaStreamTrack, nullable
getVideoTracks

Returns a sequence of MediaStreamTrack objects representing the video tracks in this stream.

The getVideoTracks() method MUST return a sequence that represents a snapshot of all the MediaStreamTrack objects in this stream's track set whose kind is equal to "video". The conversion from the track set to the sequence is user agent defined and the order does not have to stable between calls.

No parameters.
Return type: sequence<MediaStreamTrack>
removeTrack

Removes the given MediaStreamTrack from this MediaStream.

When the removeTrack() method is invoked, the user agent MUST run the following steps:

  1. Let track be the MediaStreamTrack argument and stream this MediaStream object.

  2. If stream is finished, throw an INVALID_STATE_ERR exception.

  3. If track is in stream's track set, remove it.

ParameterTypeNullableOptionalDescription
trackMediaStreamTrack
Return type: void

4.3 MediaStreamTrack

A MediaStreamTrack object represents a media source in the user agent. Several MediaStreamTrack objects can represent the same media source, e.g., when the user chooses the same camera in the UI shown by two consecutive calls to getUserMedia() .

A script can indicate that a track no longer needs its source with the MediaStreamTrack.stop() method. When all tracks using a source have been stopped, the given permission for that source is revoked and the source is stopped. If the data is being generated from a live source (e.g., a microphone or camera), then the user agent SHOULD remove any active "on-air" indicator for that source. If the data is being generated from a prerecorded source (e.g. a video file), any remaining content in the file is ignored. An implementation may use a per source reference count to keep track of source usage, but the specifics are out of scope for this specification.

4.3.1 Life-cycle and Media Flow

A MediaStreamTrack has three stages in its lifecycle; new, live and ended. A track begins as new prior to being connected to an active source.

Once connected, the started event fires and the track becomes live. In the live state, the track is active and media is available for rendering at a MediaStream consumer.

A muted or disabled MediaStreamTrack renders either silence (audio), black frames (video), or a zero-information-content equivalent. For example, a video element sourced by a muted or disabled MediaStreamTrack (contained within a MediaStream), is playing but the rendered content is the muted output.

The muted/unmuted state of a track reflects if the source provides any media at this moment. The enabled/disabled state is under application control and determines if the track outputs media (to its consumers). Hence, media from the source only flows when a MediaStreamTrack object is both unmuted and enabled.

A MediaStreamTrack is muted when the source is temporarily unable to provide the track with data. A track can be muted by a user. Often this action is outside the control of the application. This could be as a result of the user hitting a hardware switch, or toggling a control in the operating system or browser chrome. A track can also be muted by the user agent. For example, a track that is a member of a MediaStream, received via a RTCPeerConnection [WEBRTC10], is muted if the application on the other side disables the corresponding track in the MediaStream being sent.

Applications are able to enable or disable a MediaStreamTrack to prevent it from rendering media from the source. A muted track will however, regardless of the enabled state, render silence and blackness. A disabled track is logically equivalent to a muted track, from a consumer point of view.

For a newly created MediaStreamTrack object, the following applies. The track is always enabled unless stated otherwise (for examlpe when cloned) and the muted state reflects the state of the source at the time the track is created.

A MediaStreamTrack object is said to end when the source of the track is disconnected or exhausted.

When a MediaStreamTrack object ends for any reason (e.g., because the user rescinds the permission for the page to use the local camera, or because the data comes from a finite file and the file's end has been reached and the user has not requested that it be looped, or because the UA has instructed the track to end for any reason, it is said to be ended. When track instance track ends for any reason other than the stop() method being invoked on the MediaStreamTrack object that represents track, the user agent MUST queue a task that runs the following steps:

  1. If the track's readyState attribute has the value ended already, then abort these steps. (The stop() method was probably called just before the track stopped for other reasons.)

  2. Set track's readyState attribute to ended.

  3. Fire a simple event named ended at the object.

If the end of the stream was reached due to a user request, the event source for this event is the user interaction event source.

4.3.2 Tracks and Constraints

Constraints are independent of sources. However, if the sourceType is "none", the readonly attribute is true, or the remote attribute is true, the track's constraints will not be applied to the source.

Whether Constraints were provided at track initialization time or need to be established later at runtime, the APIs defined in the Constrainable Interface allow the retrieval and manipulation of the constraints currently established on a track.

Each track maintains an internal version of the Constraints structure, namely a mandatory set of constraints (no duplicates), and an optional ordered list of individual constraint objects (may contain duplicates). The internal stored constraint structure is exposed to the application by the constraints attribute, and may be modified by the applyConstraints() method.

When applyConstraints() is called, a user agent must queue a task to evaluate those changes when the task queue is next serviced. Similarly, if the sourceType changes, then the user agent should perform the same actions to re-evaluate the constraints of each track affected by that source change.

4.3.3 Interface Definition

MediaStreamTrack implements Constrainable;

All instances of the MediaStreamTrack type are defined to also implement the Constrainable interface.

interface MediaStreamTrack : EventTarget {
    readonly    attribute DOMString             kind;
    readonly    attribute DOMString             id;
    readonly    attribute DOMString             label;
                attribute boolean               enabled;
    readonly    attribute boolean               muted;
                attribute EventHandler          onmute;
                attribute EventHandler          onunmute;
    readonly    attribute boolean               _readonly;
    readonly    attribute boolean               remote;
    readonly    attribute MediaStreamTrackState readyState;
                attribute EventHandler          onstarted;
                attribute EventHandler          onended;
    MediaStreamTrack clone ();
    void             stop ();
};
4.3.3.1 Attributes
enabled of type boolean,

The MediaStreamTrack.enabled attribute, on getting, MUST return the last value to which it was set. On setting, it MUST be set to the new value, and then, if the MediaStreamTrack object is still associated with a track, MUST enable the track if the new value is true, and disable it otherwise.

Note

Thus, after a MediaStreamTrack is disassociated from its track, its enabled attribute still changes value when set; it just doesn't do anything with that new value.

id of type DOMString, readonly

Unless a MediaStreamTrack object is created as a part a of special purpose algorithm that specifies how the track id must be initialized, the user agent MUST generate a globally unique identifier string and initialize the object's id attribute to that string.

An example of an algorithm that specifies how the track id must be initialized is the algorithm to represent an incoming network component with a MediaStreamTrack object. [WEBRTC10]

MediaStreamTrack.id attribute MUST return the value to which it was initialized when the object was created.

kind of type DOMString, readonly

The MediaStreamTrack.kind attribute MUST return the string "audio" if the object represents an audio track or "video" if object represents a video track.

label of type DOMString, readonly

User agents MAY label audio and video sources (e.g., "Internal microphone" or "External USB Webcam"). The MediaStreamTrack.label attribute MUST return the label of the object's corresponding track, if any. If the corresponding track has or had no label, the attribute MUST instead return the empty string.

Note

Thus the kind and label attributes do not change value, even if the MediaStreamTrack object is disassociated from its corresponding track.

muted of type boolean, readonly

The MediaStreamTrack.muted attribute MUST return true if the track is muted, and false otherwise.

onended of type EventHandler,
This event handler, of type ended, MUST be supported by all objects implementing the MediaStreamTrack interface.
onmute of type EventHandler,
This event handler, of type mute, MUST be supported by all objects implementing the MediaStreamTrack interface.
onstarted of type EventHandler,
This event handler, of type started, MUST be supported by all objects implementing the MediaStreamTrack interface.
onunmute of type EventHandler,
This event handler, of type unmute, MUST be supported by all objects implementing the MediaStreamTrack interface.
readonly of type boolean, readonly
If the track (audio or video) is backed by a read-only source such as a file, or the track source is a local microphone or camera, but is shared so that constraints applied to the track cannot modify the source's state, the readonly attribute MUST return the value true. Otherwise, it must return the value false.
readyState of type MediaStreamTrackState, readonly

The readyState attribute represents the state of the track. It MUST return the value to which the user agent last set it.

remote of type boolean, readonly
If the track is sourced by an RTCPeerConnection, the remote attribute MUST return the value true. Otherwise, it must return the value false.
4.3.3.2 Methods
clone

Clones the given MediaStreamTrack.

When the clone() method is invoked, the user agent MUST run the following steps:

  1. Let trackClone be a newly constructed MediaStreamTrack object.

  2. Initialize trackClone's id attribute to a newly generated value.

  3. Let trackClone inherit this track's underlying source, kind, label and enabled attributes.

  4. Return trackClone.

No parameters.
Return type: MediaStreamTrack
stop

When a MediaStreamTrack object's stop() method is invoked, the user agent MUST run following steps:

  1. Let track be the current MediaStreamTrack object.

  2. If track has no source attached (sourceType is "none") or if the source is provided by an RTCPeerConnection, then abort these steps.

  3. Set track's readyState attribute to ended.

  4. Detach track's source.

    If no other MediaStreamTrack is using the same source, the source will be stopped.

The task source for the tasks queued for the stop() method is the DOM manipulation task source.

No parameters.
Return type: void
enum MediaStreamTrackState {
    "new",
    "live",
    "ended"
};
Enumeration description
newThe track type is new and has not been initialized (connected to a source of any kind). This state implies that the track's label will be the empty string.
live

The track is active (the track's underlying media source is making a best-effort attempt to provide data in real time).

The output of a track in the live state can be switched on and off with the enabled attribute.

ended

The track has ended (the track's underlying media source is no longer providing data, and will never provide more data for this track). Once a track enters this state, it never exits it.

For example, a video track in a MediaStream ends if the user unplugs the USB web camera that acts as the track's media source.

4.3.4 Track Source Types

enum SourceTypeEnum {
    "none",
    "camera",
    "microphone"
};
Enumeration description
noneThis track has no source. This is the case when the track is in the "new" or "ended" readyState.
cameraA valid source type only for VideoStreamTracks. The source is a local video-producing camera source.
microphoneA valid source type only for AudioStreamTracks. The source is a local audio-producing microphone source.

4.3.5 Isolated Media Streams

When either of the "noaccess" or "peerIdentity" constraints is applied to a MediaStreamTrack, the track shall be isolated so that its content is not accessible to the content JS. An isolated media stream may be used for two purposes:

  • Displayed in an appropriate tag (e.g., a video or audio element). The video element MUST have a unique origin so that it is inaccessible to the content JS. This is the same security mechanism as is used with an ordinary audio or video element which has a src= property from a separate origin.

  • Used as the argument to addStream() for a PeerConnection, subject to the restrictions detailed in the WebRTC document.

When the noaccess=true constraint applies to a track, that track may be added to any PeerConnection.

Note

Open Issue: The editors worry that the above paragraph is just wrong. If the track can be added to a PeerConnection that is connect to another PeerConenction in the same application, the application could get access to the data. We sugest this should be changed from "may be added" to "may not be added". This will allow noaccess=true to be used for things like hair check dialogs.

When the peerIdentity=foo constraint applies to a track, then that track may be added only to PeerConnections with compatible peer identities as described in the WebRTC document.

Both the noaccess and peerIdentity constraints must be mandatory. Any use of them in the optional block must trigger an error.

4.4 MediaStreamTrackEvent

The addtrack and removetrack events use the MediaStreamTrackEvent interface.

Firing a track event named e with a MediaStreamTrack track 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 MediaStreamTrackEvent interface with the track attribute set to track, MUST be created and dispatched at the given target.

dictionary MediaStreamTrackEventInit : EventInit {
    MediaStreamTrack? track;
};

[ Constructor (DOMString type, MediaStreamTrackEventInit eventInitDict)] interface MediaStreamTrackEvent : Event { readonly attribute MediaStreamTrack track; };

4.4.1 Constructors

MediaStreamTrackEvent
ParameterTypeNullableOptionalDescription
typeDOMString
eventInitDictMediaStreamTrackEventInit

4.4.2 Attributes

track of type MediaStreamTrack, readonly

The track attribute represents the MediaStreamTrack object associated with the event.

4.4.3 Dictionary MediaStreamTrackEventInit Members

track of type MediaStreamTrack, nullable

 

4.5 Video and Audio Tracks

The MediaStreamTrack object cannot be instantiated directly. To create an instance of a MediaStreamTrack, one of its derived track types may be instantiated. These derived types are defined in this section.

Note that the camera's green light doesn't come on when a new track is created; nor does the user get prompted to enable the camera/microphone. Those actions only happen after the developer has requested that a media stream containing "new" tracks be bound to a source via getUserMedia(). Until that point tracks are inert.

4.5.1 VideoStreamTrack interface

Video tracks may be instantiated with optional media track constraints. These constraints can be later modified on the track as needed by the application, or created after-the-fact if the initial constraints are unknown to the application.

Note

Example: VideoStreamTrack objects are instantiated in JavaScript using the new operator:

new VideoStreamTrack();
or
new VideoStreamTrack( { optional: [ { sourceId: "20983-20o198-109283-098-09812" }, { width: { min: 800, max: 1200 }}, { height: { min: 600 }}] });
[ Constructor (optional Constraints videoConstraints)]
interface VideoStreamTrack : MediaStreamTrack {
};
4.5.1.1 Constructors
VideoStreamTrack
ParameterTypeNullableOptionalDescription
videoConstraintsConstraints

4.5.2 AudioStreamTrack

Note

Example: AudioStreamTrack objects are instantiated in JavaScript using the new operator:

new AudioStreamTrack();
or
new AudioStreamTrack( { optional: [ { sourceId: "64815-wi3c89-1839dk-x82-392aa" }, { gain: 0.5 }] });
[ Constructor (optional Constraints audioConstraints)]
interface AudioStreamTrack : MediaStreamTrack {
};
4.5.2.1 Constructors
AudioStreamTrack
ParameterTypeNullableOptionalDescription
audioConstraintsConstraints

5. The model: sources, sinks, constraints, and states

Browsers provide a media pipeline from sources to sinks. In a browser, sinks are the <img>, <video> and <audio> tags. Traditional sources include camera, microphones, streamed content, files and web resources. The media produced by these sources typically does not change over time - these sources can be considered to be static.

The sinks that display these sources to the user (the actual tags themselves) have a variety of controls for manipulating the source content. For example, an <img> tag scales down a huge source image of 1600x1200 pixels to fit in a rectangle defined with width="400" and height="300".

The getUserMedia API adds dynamic sources such as microphones and cameras - the characteristics of these sources can change in response to application needs. These sources can be considered to be dynamic in nature. A <video> element that displays media from a dynamic source can either perform scaling or it can feed back information along the media pipeline and have the source produce content more suitable for display.

Note

Note: This sort of feedback loop is obviously just enabling an "optimization", but it's a non-trivial gain. This optimization can save battery, allow for less network congestion, etc...

Note that MediaStream sinks (such as <video>, <audio>, and even RTCPeerConnection) will continue to have mechanisms to further transform the source stream beyond that which the Settings, Capabilities, and Constraints described in this specification offer. (The sink transformation options, including those of RTCPeerConnection, are outside the scope of this specification.)

The act of changing or applying a track constraint may affect the settings of all tracks sharing that source and consequently all down-level sinks that are using that source. Many sinks may be able to take these changes in stride, such as the <video> element or RTCPeerConnection. Others like the Recorder API may fail as a result of a source state change.

The RTCPeerConnection is an interesting object because it acts simultaneously as both a sink and a source for over-the-network streams. As a sink, it has source transformational capabilities (e.g., lowering bit-rates, scaling-up or down resolutions, adjusting frame-rates), and as a source it could have its own states changed by a track source (though in this specification sources with the remote attribute set to true do not consider the current constraints applied to a track).

To illustrate how changes to a given source impact various sinks, consider the following example. This example only uses width and height, but the same principles apply to any of the Settings exposed in this proposal. In the first figure a home client has obtained a video source from its local video camera. The source's width and height state are 800 pixels by 600 pixels, respectively. Three MediaStream objects on the home client contain tracks that use this same sourceId. The three media streams are connected to three different sinks: a <video> element (A), another <video> element (B), and a peer connection (C). The peer connection is streaming the source video to an away client. On the away client there are two media streams with tracks that use the peer connection as a source. These two media streams are connected to two <video> element sinks (Y and Z).

Changing media stream source effects: before the
      requested change

Note that at this moment, all of the sinks on the home client must apply a transformation to the original source's provided dimension settings. A is scaling the video up (resulting in loss of quality), B is scaling the video down, and C is also scaling the video up slightly for sending over the network. On the away client, sink Y is scaling the video way down, while sink Z is not applying any scaling.

Using the Constrainable interface, the home client's video source is changed to a higher resolution (1920 by 1200 pixels).

Changing media stream source effects: after the
      requested change

Note that the source change immediately affects all of the sinks on the home client, but does not impact any of the sinks (or sources) on the away client. With the increase in the home client source video's dimensions, sink A no longer has to perform any scaling, while sink B must scale down even further than before. Sink C (the peer connection) must now scale down the video in order to keep the transmission constant to the away client.

While not shown, an equally valid settings change request could be made of the away client video source (the peer connection on the away client's side). This would not only impact sink Y and Z in the same manner as before, but would also cause re-negotiation with the peer connection on the home client in order to alter the transformation that it is applying to the home client's video source. Such a change would not change anything related to sink A or B or the home client's video source.

Note that this specification does not define a mechanism by which a change to the away client's video source could automatically trigger a change to the home client's video source. Implementations may choose to make such source-to-sink optimizations as long as they only do so within the constraints established by the application, as the next example demonstrates.

It is fairly obvious that changes to a given source will impact sink consumers. However, in some situations changes to a given sink may also be cause for implementations to adjust the characteristics of a source's stream. This is illustrated in the following figures. In the first figure below, the home client's video source is sending a video stream sized at 1920 by 1200 pixels. The video source is also unconstrained, such that the exact source dimensions are flexible as far as the application is concerned. Two MediaStream objects contain tracks with the same sourceId, and those MediaStreams are connected to two different <video> element sinks A and B. Sink A has been sized to width="1920" and height="1200" and is displaying the source's video content without any transformations. Sink B has been sized smaller and, as a result, is scaling the video down to fit its rectangle of 320 pixels across by 200 pixels down.

Changing media stream sinks may affect sources:
      before the requested change

When the application changes sink A to a smaller dimension (from 1920 to 1024 pixels wide and from 1200 to 768 pixels tall), the browser's media pipeline may recognize that none of its sinks require the higher source resolution, and needless work is being done both on the part of the source and on sink A. In such a case and without any other constraints forcing the source to continue producing the higher resolution video, the media pipeline MAY change the source resolution:

Changing media stream sinks may affect sources:
      after the requested change

In the above figure, the home client's video source resolution was changed to the greater of that from sinkA and from sinkB in order to optimize playback. While not shown above, the same behavior could apply to peer connections and other sinks.

It is possible that constraints can be applied to a track which a source is unable to satisfy. When this happens, the user agent is required to fire an overconstrained MediaErrorEvent to the track informing it of this condition, and the track becomes muted. There is no mandatory side-effect on the source itself as a result of this condition.

When multiple tracks share the same source (as illustrated in the previous figures), it is also possible that two (or more) tracks can apply contradictory constraints on the source. Since there is only a single thread of control, it is always possible for the browser to determine which track created the overconstrained condition. In this situation, the user agent MUST send the overconstrained MediaErrorEvent only to the track that created the condition and MUST not apply any of the constraints newly requested for that track. Here is an example of this behavior.

In this example, two media streams each have a video track that share the same source. The first track has a mandatory constraint forcing on the source's fill light. That track is connected to sink N. Sink N has a width and height of 800 by 600 pixels and is scaling down the source's resolution of 1024 by 768 to fit. The other track initially has no constraints applied; it is connected to sink P. Sink P has a width and height equal to that of the source.

Overconstrained

Now, the second track adds a mandatory constraint that the fill light should be forced off. At this point, both mandatory constraints cannot be satisfied by the source (the fill light cannot be simultaneously on and off at the same time). The second track is transitioned into the muted state and receives an overconstrained event. At the same time, the source notes that its remaining active sink only requires a resolution of 800 by 600 and so it adjusts its resolution down to match (this is an optional optimization that the user agent is allowed to make given the situation).

At this point, it is the responsibility of the application to fix the problem that led to the overconstrained situation (by either removing the fill light mandatory constraint on the second track, or by changing/removing the fill light mandatory constraint on the first track).

Overconstrained result

6. MediaStreams as Media Elements

A MediaStream may be assigned to media elements as defined in HTML5 [HTML5] A MediaStream is not preloadable or seekable and represents a simple, potentially infinite, linear media timeline. The timeline starts at 0 and increments linearly in real time as long as the MediaStream is playing. The timeline does not increment when the MediaStream is paused.

6.1 Direct Assignment to Media Elements

UAs that support this specification MUST support the following partial interface, which allows a MediaStream to be assigned directly to a media element.

partial interface HTMLMediaElement {
                attribute MediaStream? srcObject;
};

6.1.1 Attributes

srcObject of type MediaStream, , nullable

Holds the MediaStream that provides media for this element. This attribute overrides both the src attribute and any <source> elements. Specifically, if srcObject is specified, the UA MUST use it as the source of media, even if the src attribute is also set or <source> children are present. If the value of srcObject is replaced or set to null the UA MUST re-run the media element load algorithm

Issue 1

We may want to allow direct assignment of other types as well

6.2 Loading and Playing a MediaStream in a Media Element

The UA runs the media element load algorithm to obtain media for the media element to display. As defined in the [HTML5] specification, this algorithm has two basic phases: resource selection algorithm chooses the resource to play and resolves its URI. Then the resource fetch phase loads the resource. Both these phases are potentially simplified when using a MediaStream. First of all, srcObject takes priority over other means of specifying the resource, and it provides the object itself rather than a URI. Therefore, there is no need to run the resource selection algorithm. Secondly, when the UA reaches the resource fetch algorithm with a MediaStream, the MediaStream is a local object so there's nothing to fetch. Therefore, the following modifications/restrictions to the media element load algorithm apply:

6.3 Media Element Attributes when Playing a MediaStream

The nature of the MediaStream places certain restrictions on the behavior and attribute values of the associated media element and on the operations that can be performed on it, as shown below:

Legal values for the properties of a media element bound to a MediaStream
Attribute Name Attribute Type Valid Values When Using a MediaStream Additional considerations
currentSrc DOMString the empty string When srcObject is specified the UA MUST set this to the empty string.
preload DOMString none A MediaStream cannot be preloaded.
buffered TimeRanges buffered.length MUST return 0. A MediaStream cannot be preloaded. Therefore, the amount buffered is always an empty TimeRange.
networkState unsigned short NETWORK_IDLE The media element does not fetch the MediaStream so there is no network traffic.
readyState unsigned short HAVE_NOTHING, HAVE_ENOUGH_DATA A MediaStream may be created before there is any data available, for example when a stream is received from a remote peer. The value of the readyState of the media element MUST be HAVE_NOTHING before the first media arrives and HAVE_ENOUGH_DATA once the first media has arrived.
currentTime double Any positive integer. The initial value is 0 and the values increments linearly in real time whenever the stream is playing. The value is the current stream position, in seconds. On any attempt to set this attribute, the user agent must throw an InvalidStateError exception.
duration unrestricted double Infinity A MediaStream does not have a pre-defined duration.
seeking boolean false A MediaStream is not seekable. Therefore, this attribute MUST always have the value false.
defaultPlaybackRate double 1.0 A MediaStream is not seekable. Therefore, this attribute MUST always have the value 1.0 and any attempt to alter it MUST fail.
playbackRate double 1.0 A MediaStream is not seekable. Therefore, this attribute MUST always have the value 1.0 and any attempt to alter it MUST fail.
played TimeRanges played.length MUST return 1.
played.start(0) MUST return 0.
played.end(0) MUST return the last known currentTime.
A MediaStream's timeline always consists of a single range, starting at 0 and extending up to the currentTime.
seekable TimeRanges seekable.length MUST return 0.
seekable.start() MUST return currentTime.
seekable.end() MUST return currentTime.
A MediaStream is not seekable.
startDate Date Not-a-Number (NaN) A MediaStream does not specify a timeline offset.
loop boolean true, false Setting the loop attribute has no effect since a MediaStream has no defined end and therefore cannot be looped.

7. Error Handling

All errors defined in this specification implement the following interface:

[NoInterfaceObject]
interface MediaError {
    readonly    attribute DOMString  name;
    readonly    attribute DOMString? message;
    readonly    attribute DOMString? constraintName;
};

7.1 Attributes

constraintName of type DOMString, readonly , nullable

This attribute is only used for some types of errors. For MediaError with a name of ConstraintNotSatisfiedError, this attribute MUST be set to the name of the constraint that caused the error.

message of type DOMString, readonly , nullable
A UA-dependent string offering extra human-readable information about the error.
name of type DOMString, readonly

The name of the error

Note
Open Issue: We may make MediaError inherit from DOMError once the definition of DOMError is stable.
Note
Open Issue: Do we want to allow the constraintName attribute to contain multiple constraint names? In many cases the error is raised as soon as a single unsatisfied mandatory constraint is found, but in others it may be possible to determine that multiple constraints are not satisfied.

The following interface is defined for cases when a MediaError is raised as an event:

dictionary MediaErrorEventInit : EventInit {
    MediaError error;
};

[ Constructor (DOMString type, MediaErrorEventInit eventInitDict)] interface MediaErrorEvent : Event { readonly attribute MediaError error; };

7.2 Constructors

MediaErrorEvent
ParameterTypeNullableOptionalDescription
typeDOMString
eventInitDictMediaErrorEventInit

7.3 Attributes

error of type MediaError, readonly

7.4 Dictionary MediaErrorEventInit Members

error of type MediaError

 

8. Event summary

This section is non-normative.

The following event fires on MediaStream objects:

Event name Interface Fired when...
active Event The MediaStream became active (see inactive).
inactive Event The MediaStream became inactive.
addtrack MediaStreamTrackEvent A new MediaStreamTrack has been added to this stream. Note that this event is not fired when the script directly modifies the tracks of a MediaStream.
removetrack MediaStreamTrackEvent A MediaStreamTrack has been removed from this stream. Note that this event is not fired when the script directly modifies the tracks of a MediaStream.

The following event fires on MediaStreamTrack objects:

Event name Interface Fired when...
started Event The MediaStreamTrack object has just transitioned from the "new" readyState to another state. This event fires before any other corresponding events such as "ended" or "statechanged".
mute Event The MediaStreamTrack object's source is temporarily unable to provide data.
unmute Event The MediaStreamTrack object's source is live again after having been temporarily unable to provide data.
overconstrained MediaErrorEvent

This error event fires asynchronously for each affected track (when multiple tracks share the same source) after the user agent has evaluated the current constraints against a given sourceId and is not able to configure the source within the limitations established by the union of imposed constraints.

Due to being over-constrained, the user agent must mute each affected track.

The affected track(s) will remain un-usable (in the "muted" readyState) until the application adjusts the constraints to accommodate the source's capabilities.

ended Event The MediaStreamTrack object's source will no longer provide any data, either because the user revoked the permissions, or because the source device has been ejected, or because the remote peer stopped sending data, or because the stop() method was invoked.

9. Enumerating Local Media Devices

This section describes an API that the script can use to query the user agent about connected media input and output devices.

9.2 Device Info

callback MediaDeviceInfoCallback = void (sequence<MediaDeviceInfo> deviceInfoList);

9.2.1 Callback MediaDeviceInfoCallback Parameters

deviceInfoList of type sequence<MediaDeviceInfo>
A sequence of MediaDeviceInfo objects representing the result of a call to Navigator.getMediaDevices() .
Note
The old SourceInfo dictionary used to refer to the MediaSourceStates dictionary. That dictionary is no longer available when Constrainable is introduced. When Constrainable lands, we should see if we can align deviceId, kind and label, below, with the new definitions of source capabilities.
dictionary MediaDeviceInfo {
    DOMString       deviceId;
    MediaDeviceKind kind;
    DOMString       label;
    DOMString       groupId;
};

9.2.2 Dictionary MediaDeviceInfo Members

deviceId of type DOMString

The unique id for the represented device.

groupId of type DOMString

Returns the group identifier of the represented device. Two devices has the same group identifier if they belong to the same physical device; for example a headset.

kind of type MediaDeviceKind

Describes the kind of the represented device.

label of type DOMString

A label describing this device (for example "External USB Webcam"). If the device has no associated label, then this dictionary member MUST return the empty string.

enum MediaDeviceKind {
    "audioinput",
    "audiooutput",
    "videoinput"
};
Enumeration description
audioinput

Represents an audio input device; for example a microphone.

audiooutput

Represents an audio output device; for example a pair of headphones.

videoinput

Represents a video input device; for example a webcam.

10. Obtaining local multimedia content

10.2 MediaStreamConstraints

The MediaStreamConstraints dictionary is used to instruct the UA what sort of MediaStreamTracks to include in the MediaStream returned by getUserMedia().

dictionary MediaStreamConstraints {
    (boolean or Constraints) video = false;
    (boolean or Constraints) audio = false;
};

10.2.1 Dictionary MediaStreamConstraints Members

audio of type (boolean or Constraints), defaulting to false

If true, it requests that the returned MediaStream contain an audio track. If a Constraints structure is provided, it further specifies the nature and settings of the audio Track. If false, the MediaStream MUST not contain an audio Track.

video of type (boolean or Constraints), defaulting to false

If true, it requests that the returned MediaStream contain a video track. If a Constraints structure is provided, it further specifies the nature and settings of the video Track. If false, the MediaStream MUST not contain a video Track.

10.5 Implementation Suggestions

This section is non-normative.

Best Practice 1: Resource reservation

The user agent is encouraged to reserve resources when it has determined that a given call to getUserMedia() will succeed. It is preferable to reserve the resource prior to invoking the success callback provided by the web page. Subsequent calls to getUserMedia() (in this page or any other) should treat the resource that was previously allocated, as well as resources held by other applications, as busy. Resources marked as busy should not be provided as sources to the current web page, unless specified by the user. Optionally, the user agent may choose to provide a stream sourced from a busy source but only to a page whose origin matches the owner of the original stream that is keeping the source busy.

This document recommends that in the permission grant dialog or device selection interace (if one is present), the user be allowed to select any available hardware as a source for the stream requested by the page (provided the resource is able to fulfill mandatory constraints, if any were specified), in addition to the ability to substitute a video or audio source with local files and other media. A file picker may be used to provide this functionality to the user.

This document also recommends that the user be shown all resources that are currently busy as a result of prior calls to getUserMedia() (in this page or any other page that is still alive) and be allowed to terminate that stream and utilize the resource for the current page instead. If possible in the current operating environment, it is also suggested that resources currently held by other applications be presented and treated in the same manner. If the user chooses this option, the track corresponding to the resource that was provided to the page whose stream was affected must be removed.

Best Practice 2: Handling multiple devices

A MediaStream may contain more than one video and audio track. This makes it possible to include video from two or more webcams in a single stream object, for example. However, the current API does not allow a page to express a need for multiple video streams from independent sources.

It is recommended for multiple calls to getUserMedia() from the same page be allowed as a way for pages to request multiple, discrete, video or audio streams.

A single call to getUserMedia() will always return a stream with either zero or one audio tracks, and either zero or one video tracks. If a script calls getUserMedia() multiple times before reaching a stable state, this document advises the UI designer that the permission dialogs should be merged, so that the user can give permission for the use of multiple cameras and/or media sources in one dialog interaction. The constraints on each getUserMedia call can be used to decide which stream gets which media sources.

11. Constrainable Interface

The Constrainable interface allows its consumers to inspect and adjust the properties of the object that implements it. It is broken out as a separate partial interface so that it can be used in other specifications. The core concept is that of a Capability, which consists of a property or feature of an object and the set of its possible values, which may be specified either as a range or as an enumeration. For example, a camera might be capable of framerates (a property) between 20 and 50 frames per second (a range) and may be able to be positioned (a property) facing towards the user, away from the user, or to the left or right of the user (an enumerated set.) The application can examine a Constrainable object's set of Capabilities via the capabilities attribute.

The application can select the (range of) values it wants for a Capability by means of a Constraint and the applyConstraints() method. A Constraint consists of the name of the property, plus the desired value (or a range of desired values.) For example, the application may set a Constraint stating that the framerate of a camera be between 30 and 40 frames per second (a range) or that it wants the camera to be facing the user (a specific value). Constraints can be mandatory or optional. In the case of optional Constraints, the UA MUST consider the Constraints in the order in which they are specified, and MUST try to satisfy each one, but MAY ignore a Constraint if it cannot satisfy it. In the case of mandatory Constraints, the MUST try to satisfy all of them, and MUST call the errorCallback if it cannot do so. For example, suppose that an application applies three Constraints, stating that the video aspect ratio should be 3 to 2 (height to width), that the height should be 600 and that the width should be 500. Since these constraints interact with each other (the aspect ratio affects the possible values for height and width, and vice-versa) it is impossible to satisfy all three constraints, so if all the Constraints are mandatory, the UA will call the errorCallback. However if any one of the Constraints is optional, the other two can be satisified, so the UA will satisfy the two mandatory ones, silently ignore the optional one, and call the successCallback.

The ordering of optional constraints is significant. In the example in the previous paragraph, suppose that aspect ratio constraint is mandatory and that the height and width constraints are optional. If the height constraint is specified first, then it will be satisfied and the width constraint will be ignored. Thus the height will be set to 600 and the the width will be set to 400. On the other hand, if width is specified before height, the width constraint will be satisfied and the height constraint will be ignored, resulting in width of 500 and height of 750. (Note that the mandatory aspect ratio constraint is enforced in both cases.) The UA will attempt to satisfy as many optional constraints as it can, even if some of them cannot be satisfied and must therefore be ignored. Application authors can therefore implement a backoff strategy by specifying multiple optional constraints for the same property. For example, an application might specify three optional constraints, the first asking for a framerate greater than 500, the second asking for a framerate greater than 400, and the third asking for one greater than 300. If the UA is capable of setting a framerate greater than 500, it will (and the subsequent two constraints will be trivially satisifed.) However, if the UA cannot set the framerate above 500, it will ignore that constraint and attempt to set the framerate above 400. If that fails, it will then try to set it above 300. If the UA cannot satisfy any of the three constraints, it will set the framerate to any value it can get. If the developer wanted to insist on 300 as a lower bound, he could make that a mandatory constraint. In that case, the UA would fail altogether if it couldn't get a value over 300, but would choose a value over 500 if possible, then try for a value over 400. An application may inspect the set of Constraints currently in effect via the constraints attribute.

The specific value that the UA chooses for a Capability is referred to as a Setting. For example, if the application applies a Constraint that the framerate must be at least 30 frames per second, and no greater than 40, the Setting can be any intermediate value, e.g., 32, 35, or 37 frames per second. The application can query the current settings of the object's Capabilities via the settings attribute.

11.1 Interface Definition

[NoInterfaceObject]
interface Constrainable {
    readonly    attribute Capabilities capabilities();
    readonly    attribute Constraints  constraints;
    readonly    attribute Settings     settings;
                attribute EventHandler onoverconstrained;
    void applyConstraints (Constraints constraints, VoidFunction successCallback, ConstraintErrorCallback errorCallback);
};

11.1.1 Attributes

capabilities() of type Capabilities, readonly

Contains the dictionary of the capabilities that the object supports. Note that it is possible that the underlying hardware may not exactly map to the range defined in the specification. In this case, an implementation should make a reasonable attempt to translate and scale the hardware's setting onto the mapping provided by the relevant specification.

Note

An example of the user agent providing an alternative mapping: if a source supports a hypothetical fluxCapacitance capability that is defined to be the range from -10 (min) to 10 (max), but the source's (hardware setting) for fluxCapacitance only supports values of "off" "medium" and "full", then the user agent should map the range value of -10 to "off", 10 should map to "full", and 0 should map to "medium". Constraints imposing a strict value of 3 will cause the user agent to attempt to set the value of "medium" on the hardware, and return a fluxCapacitance of 0, the closest supported setting. No error event is raised in this scenario.

Issue 6
What about the case where the object uses the same units as the specification, but supports only a sub-range of the specified values? What about an object whose fluxCapacitance range is only -5 to 5? Should it map those to -10 to 10, or leave them as they are?
constraints of type Constraints, readonly

Contains all the Constraints that were applied to the object in the last succesfull call of applyConstraints(). The list MUST contain only the constraints that were successfully applied, and MUST maintain the order that they were specified in.

If no mandatory constraints have been defined, the mandatory field will not be present (it will be undefined). If no optional constraints have been defined, the optional field will not be present (it will be undefined). If neither optional nor mandatory constraints have been created, the value will be null.

The UA MUST raise a MediaErrorEvent named "overconstrained" if changing circumstances at runtime result in the currently valid mandatory constraints no longer being satisfied. This MediaErrorEvent MUST contain a MediaError whose name is "overconstrainedError", and whose constraintName attribute is set to one of the mandatory constraints that can no longer be satisifed. The message attribute of the MediaError SHOULD contain a string that is useful for debugging. The conditions under which this error might occur are platform- and application-specific. For example, the user might physically manipulate a camera in a way that makes it impossible to provide a resolution that satisifies the constraints. The UA MAY take other actions as a result of the overconstrained situation.

onoverconstrained of type EventHandler,
This event handler, of type overconstrained, MUST be supported by all objects implementing the Constrainable interface.
settings of type Settings, readonly
Contains the current settings of all the properties of the object, whether they are platform defaults or have been set by applyConstraints(). Note that the actual setting of a property MUST be a single value.

11.1.2 Methods

applyConstraints

The algorithm for applying constraints is stated below. Here are some preliminary definitions that are used in the statement of the algorithm:

  • A sequence of values for the properties of an object O satisfy constraint set C if each value a) is in the set of supported values specified by the corresponding Capability of O, and b) is in the set specified by any constraints in C that apply to that property, and c) there is no constraint in C that does not correspond to a Capability in O. (Note that although this definition ignores the difference between mandatory and optional constraints, the algorithm below distinguishes between them.)
  • A set of constraints C can be satisifed by an object O if it is possible to choose a sequence of values for the properties of O that satisfy C.
  • To apply a set of constraints C to object O is to choose such a sequence of values that satisfy C and assign them as the settings for the properties of O.

When applyConstraints is called, the UA MUST queue a task to run the following steps:

  1. let desiredContraints be the argument to this function. Each constraint MUST specify one or more values (or a range of values) for its property. A property MAY appear more than once in the list of optional constraints.
  2. Let newConstraints be an initially empty set of constraints
  3. Let object be the Constrainable object on which this method was called. Let copy be an unconstrained copy of object (i.e., copy should behave as if it were object with all constraints removed.)
  4. If the mandatory constraints in desiredConstraints is cannot be satisifed by copy, call the errorCallback, passing it a new MediaError with name ConstraintNotSatisfied and constraintName set to the mandatory constraints that could not be satisfied, and return. (Note that there may be more than one way of selecting the set of constraints that were not satisfied.) existingConstraints remain in effect on object in this case.
  5. Otherwise add the mandatory constraints to newConstraints
  6. Iterate over the optional constraints in desiredConstraints in the order in which they were specified. For each constraint,if it and newConstraints together can be satisfied by copy, add it to newConstraints. Otherwise, ignore it.
  7. In a single operation, remove all existing constraints from object, apply newConstraints, set the value of the constraints attribute to newConstraints, and fire the successCallback passing it newConstraints as its argument. Note: the UA MAY modify the values of one or more properties of object at any time, as long as the resulting set of values satisfy the current set of constraints.
ParameterTypeNullableOptionalDescription
constraintsConstraintsA new constraint structure to apply to this object.
successCallbackVoidFunctionCalled if all mandatory constraints can be satisfied.
errorCallbackConstraintErrorCallbackCalled if one or more mandatory constraints cannot be satisified.
Return type: void

11.1.3 applyConstraints Failure Callback

ConstraintErrorCallback
callback ConstraintErrorCallback = void (MediaError error);
Callback ConstraintErrorCallback Parameters
error of type MediaError
An MediaError holding the mandatory constraint that could not be satisfied.
Note

Here is an example of Constraints that could be passed into applyConstraints() or returned as a value of constraints. It uses the properties defined in the Track property registry, below:

{
  mandatory: {
    width: { min: 640 },
    height: { min: 480 }
  },
  optional: [
    { width: 650 },
    { width: { min: 650 }},
    { frameRate: 60 },
    { width: { max: 800 }},
    { facingMode: "user" }
  ]
}                                

11.1.4 Capabilities, Constraints, and Settings

11.1.4.1 The Property Registry

For each class/interface that implements Constrainable, there MUST be a corresponding registry that defines the constrainable properties of that class of object. The registry entries MUST contain the name of each property along with its set of legal values. The registry for MediaStreamTrack is defined below. The syntax for the specification of the set of legal values depends on the type of the values. In addition to the standard atomic types (boolean, int, float, DOMString), legal values include lists of any of the atomic types, plus min-max ranges, as defined below:

11.1.4.1.1 PropertyValueRange
dictionary PropertyValueRange {
    any max;
    any min;
};
11.1.4.1.1.1 Dictionary PropertyValueRange Members
max of type any
The maximum legal value of this property.

The type of this value is specific to the object and property in question.

min of type any
The minimum value of this Property.

The type of this value is specific to the object and property in question.

Issue 7

Should we allow registries to define new or different syntaxes for capabilities? For example could a registry introduce a new Capability that had a min, a max, and a step value?

Issue 8

Should we allow the use of multiple registries? For example, a spec might define a registry of Capabilities, and an implementation might define extensions. In that case, we could think of the implementation as having its own registry, and the final set of Capabilities as being the union of the two.

11.1.4.2 Capabilities

Capabilities a dictionary containing one or more key-value pairs, where each key MUST be a constrainable property defined in the associated registry, and each value SHOULD be a subset of the set of values defined for that property in the registry. The exact syntax of the value expression depends on the type of the property. The Capabilities dictionary specifies the subset of the constrainable properties and values from the registry that the UA supports. Note that a UA MAY support only a subset of the properties that are defined in the registry, and MAY support a subset of the set values for those properties that it does support.

11.1.4.3 Settings

Settings is a dictionary containing one or more key-value pairs. It MUST contain each key returned in capabilities(). There MUST be a single value for each key and the value MUST a member of the set defined for that property by capabilities(). Thus the Settings dictionary contains the actual values that the UA has chosen for the object's Capabilities.

11.1.4.4 Constraints
dictionary Constraints {
    ConstraintSet? mandatory;
    Constraint[]   optional;
};
11.1.4.4.1 Dictionary Constraints Members
mandatory of type ConstraintSet, nullable

The set of Constraints that the UA MUST satisfy or else call the errorCallback. Note that a given property name may occur only once in this set.

optional of type array of Constraint

The set of Constraints that the UA SHOULD try to satisfy but MAY ignore if they cannot be satisified. The order of these constraints is significant. In particular, when they are passed as an argument to applyConstraints, the UA MUST try to satisfy them in the order that is specified. Thus if optional constraints C1 and C2 can be satisfied individually, but not together, then whichever of C1 and C2 is first in this list will be satisfied, and the other will not. The UA MUST attempt to satisfy all optional constraints in the list, even if some cannot be satisfied. Thus, in the preceeding example, if optional constraint C3 is specified after C1 and C2, the UA will attempt to satisfy C3 even though C2 cannot be satisified. Note that a given property name may occur multiple times in this set.

Each entry in the ConstraintSet and Constraint dictionaries corresponds to a property and specifies a subset of its legal values. Applying a constraint instructs that UA to restrict the setting of the corresponding Capability to that value or range of values. A given property MAY occur both in the mandatory and the optional constraints list, and MAY occur more than once in the optional constraints list.

11.1.4.4.2 ConstraintSet

A ConstraintSet is a dictionary containing one or more key-value pairs, where each key is expected to be a constrainable property defined in the associated registry, and each value SHOULD be a subset of the set of values defined for that property in the registry. The exact syntax of the value expression depends on the type of the property.

11.1.4.4.3 Constraint

A Constraint is a dictionary containing exactly one key-value pair, where the key is expected to be a constrainable property defined in the associated registry, and the value SHOULD be a subset of the set of values defined for that property in the registry. The exact syntax of the value expression depends on the type of the property.

12. Examples

This sample code exposes a button. When clicked, the button is disabled and the user is prompted to offer a stream. The user can cause the button to be re-enabled by providing a stream (e.g., giving the page access to the local camera) and then disabling the stream (e.g., revoking that access).

Example 1
<input type="button" value="Start" onclick="start()" id="startBtn">
<script>
 var startBtn = document.getElementById('startBtn');
 function start() {
   navigator.getUserMedia({audio:true, video:true}, gotStream, logError);
   startBtn.disabled = true;
 }
 function gotStream(stream) {
   stream.oninactive = function () {
     startBtn.disabled = false;
   };
 }
 function logError(error) {
   log(error.name + ": " + error.message);
 }
</script> 

This example allows people to take photos of themselves from the local video camera. Note that the forthcoming Image Capture specification may provide a simpler way to accomplish this.

Example 2
<article>
 <style scoped>
  video { transform: scaleX(-1); }
  p { text-align: center; }
 </style>
 <h1>Snapshot Kiosk</h1>
 <section id="splash">
  <p id="errorMessage">Loading...</p>
 </section>
 <section id="app" hidden>
  <p><video id="monitor" autoplay></video> <canvas id="photo"></canvas>
  <p><input type=button value="&#x1F4F7;" onclick="snapshot()">
 </section>
 <script>
  navigator.getUserMedia({video:true}, gotStream, noStream);
  var video = document.getElementById('monitor');
  var canvas = document.getElementById('photo');
  function gotStream(stream) {
    video.srcObject = stream;
    stream.oninactive = noStream;
    video.onloadedmetadata = function () {
      canvas.width = video.videoWidth;
      canvas.height = video.videoHeight;
      document.getElementById('splash').hidden = true;
      document.getElementById('app').hidden = false;
    };
  }
  function noStream() {
    document.getElementById('errorMessage').textContent = 'No camera available.';
  }
  function snapshot() {
    canvas.getContext('2d').drawImage(video, 0, 0);
  }
 </script>
</article>

13. Error Names

This specification defines the following new error names

14. IANA Registrations

14.1 Track Property Registrations

IANA is requested to register the following properties as specified in [RTCWEB-CONSTRAINTS]:

Note

Note: The definitions for "noaccess" and "peerIdentity" are proposals under discussion, which may result in considerable modification. The other constraints listed are thought to be stable.

The following constraint names are defined to apply to both VideoStreamTrack and AudioStreamTrack objects:

Property Name Values Notes
sourceType SourceTypeEnum the type of the source of the MediaStreamTrack.
sourceId DOMString The application-unique identifier for this source. The same identifier MUST be valid between sessions of this application, but MUST also be different for other applications. Some sort of GUID is recommended for the identifier.
noaccess boolean Whether the MediaStreamTrack can be applied to an element which is readable by the JS.
peerIdentity DOMString Whether the stream can applied to an element which is readable by the JS. Require that any PeerConnections to which the stream is added match the provided identity.

The following properties are defined to apply only to VideoStreamTrack objects:

Property Name Values Notes
width PropertyValueRange of unsigned longs. The width or width range, in pixels, of the video source. As a capability, the range should span the video source's pre-set width values with min being the smallest width and max being the largest width.
height PropertyValueRange of unsigned longs The height or height range, in pixels, of the video source. As a capability, the range should span the video source's pre-set height values with min being the smallest height and max being the largest height.
frameRate PropertyValueRange of doubles The exact desired frame rate (frames per second) or frameRate range of the video source. If the source does not natively provide a frameRate, or the frameRate cannot be determined from the source stream, then this value MUST refer to the user agent's vsync display rate.
aspectRatio PropertyValueRange of flotas The exact aspect ratio (width in pixels divided by height in pixels), represented as a double rounded to the tenth decimal place.
facingMode list of VideoFacingModeEnum The members of the enum describe the directions that the camera can face, as seen from the user's perspective.
enum VideoFacingModeEnum {
    "user",
    "environment",
    "left",
    "right"
};
Enumeration description
userThe source is facing toward the user (a self-view camera).
environmentThe source is facing away from the user (viewing the environment).
leftThe source is facing to the left of the user.
rightThe source is facing to the right of the user.

Below is an illustration of the video facing modes in relation to the user.
Illustration of video facing modes in relation to user

The following properties are defined to apply only to AudioStreamTrack objects:

Property Name Values Notes
volume PropertyValueRange of unsigned longs The volume or volume range of the audio source, as a percentage. A volume of 0 is silence, while a volume of 100 is the maximum supported volume.

15. Change Log

This section will be removed before publication.

Changes since November 5, 2013

  1. ACTION-25: Switch mediastream.inactive to mediastream.active.
  2. ACTION-26: Rewrite stop to only detach the track's source.
  3. Bug 22338: Arbitrary changing of tracks.
  4. Bug 23125: Use double rather than float.
  5. Bug 22712: VideoFacingMode enum needs an illustration.
  6. Moved constraints into a separate Constrainable interface.
  7. Created a separate section on error handling.

Changes since October 17, 2013

  1. Bug 23263: Add output device enumeration to GetSources
  2. Introduced the Constrainable interface.
  3. Change consensus note on constraints in IANA section.
  4. Removed createObjectURL.
  5. Bug 22209: Should not use MUST requirements on values provided by the developer.

Changes since August 24, 2013

  1. Bug 22269: Renamed getSourceInfos() to getSources() and made the result async.
  2. Bug 22229: Editorial input
  3. Bug 22243: Clarify readonly track
  4. Bug 22259: Disabled mediastreamtrack and state of media element
  5. Bug 22226: Remove check of same source from MediaStream constructor algorithm
  6. Replaced ended with inactive for MediaStream (resolves bug 21618).
  7. Bug 22264: MediaStream.ended set to true on creation
  8. Bug 22272: Permission revokation via MediaStreamTrack.stop()
  9. Bug 22248: Relationship between MediaStreamTrack and HTML5 VideoTrack/AudioTrack after MediaStream assignment
  10. Bug 22247: Setting loop attribute on a media element reading from a MediaStream

Changes since July 4, 2013

  1. Bug 21967: Added paragraph on MediaStreamTrack enabled state and updated cloning algorithm.
  2. Bug 22210: Make getUserMedia() algorithm use all numbered items.
  3. Bug 22250: Fixed accidentally overridden error.
  4. Bug 22211: Added async error when no valid media type is requested.
  5. Bug 22216: Made NavigatorUserMediaError extend DOMError.
  6. Bug 22249: Throw on attempts to set currentTime on media elements playing MediaStream objects.
  7. Bug 22246: Made media.buffered have length 0.
  8. Bug 22692: Updated media element to use HAVE_NOTHING state before media arrives on the played MediaStream and HAVE_ENOUGH_DATA as soon as media arrives.

May 29, 2013

  1. Bug 22252: fixed usage of MUST in MediaStream() constructor description.
  2. Bug 22215: made MediaStream.ended readonly.
  3. Bug 21967: clarified MediaStreamTrack.enabled state initial value.
  4. Added aspectRatio constraint, capability, and state.
  5. Updated usage of MediaStreams in media elements.

May 15, 2013

  1. Added explanatory section for constraints, capabilities, and states.
  2. Added VideoFacingModeEnum (including left and right options).
  3. Added getSourceInfos() and SourceInfo dictionary.
  4. Added isolated streams.

April 29, 2013

  1. Removed remaining photo APIs and references (since we have a separate Image Capture Spec).

March 20, 2013

  1. Added readonly and remote attributes to MediaStreamTrack
  2. Removed getConstraint(), setConstraint(), appendConstraint(), and prependConstraint().
  3. Added source states. Added states() method on tracks. Moved sourceType and sourceId to be states.
  4. Added source capabilities. Added capabilities() method on tracks.
  5. Added clarifying text about MediaStreamTrack lifecycle and mediaflow.
  6. Made MediaStreamTrack cloning explicit.
  7. Removed takePhoto() and friends from VideoStreamTrack (we have a separate Image Capture Spec).
  8. Made getUserMedia() error callback mandatory.

December 12, 2012

  1. Changed error code to be string instead of number.
  2. Added core of settings proposal allowing for constraint changes after stream/track creation.

November 15 2012

  1. Introduced new representation of tracks in a stream (removed MediaStreamTrackList).
  2. Updated MediaStreamTrack.readyState to use an enum type (instad of unsigned short constants).
  3. Renamed MediaStream.label to MediaStream.id (the definition needs some more work).

October 1 2012

  1. Limited the track kind values to "audio" and "video" only (could previously be user defined as well).
  2. Made MediaStream extend EventTarget.
  3. Simplified the MediaStream constructor.

June 23 2012

  1. Rename title to "Media Capture and Streams".
  2. Update document to comply with HTML5.
  3. Update image describing a MediaStream.
  4. Add known issues and various other editorial changes.

June 22 2012

  1. Update wording for constraints algorithm.

June 19 2012

  1. Added "Media Streams as Media Elements section".

June 12 2012

  1. Switch to respec v3.

June 5 2012

  1. Added non-normative section "Implementation Suggestions".
  2. Removed stray whitespace.

June 1 2012

  1. Added media constraint algorithm.

Apr 23 2012

  1. Remove MediaStreamRecorder.

Apr 20 2012

  1. Add definitions of MediaStreams and related objects.

Dec 21 2011

  1. Changed to make wanted media opt in (rather than opt out). Minor edits.

Nov 29 2011

  1. Changed examples to use MediaStreamOptions objects rather than strings. Minor edits.

Nov 15 2011

  1. Removed MediaStream stuff. Refers to webrtc 1.0 spec for that part instead.

Nov 9 2011

  1. Created first version by copying the webrtc spec and ripping out stuff. Put it on github.

A. Acknowledgements

x

B. References

B.1 Normative references

[HTML5]
Robin Berjon; Steve Faulkner; Travis Leithead; Erika Doyle Navara; Edward O'Connor; Silvia Pfeiffer. HTML5. 6 August 2013. W3C Candidate Recommendation. URL: http://www.w3.org/TR/html5/
[RFC2119]
S. Bradner. Key words for use in RFCs to Indicate Requirement Levels. March 1997. Internet RFC 2119. URL: http://www.ietf.org/rfc/rfc2119.txt
[RTCWEB-CONSTRAINTS]
D. Burnett. IANA Registry for RTCWeb Media Constraints. URL: http://datatracker.ietf.org/doc/draft-burnett-rtcweb-constraints-registry/
[WEBIDL]
Cameron McCormack. Web IDL. 19 April 2012. W3C Candidate Recommendation. URL: http://www.w3.org/TR/WebIDL/
[WEBRTC10]
Adam Bergkvist; Daniel Burnett; Cullen Jennings; Anant Narayanan. WebRTC 1.0: Real-time Communication Between Browsers. 10 September 2013. W3C Working Draft. URL: http://www.w3.org/TR/webrtc/
[mediastream-imagecap]
Giridhar Mandyam. MediaStream Image Capture. W3C Working Draft. URL: http://www.w3.org/TR/image-capture/
[mediastream-rec]
Jim Barnett; Travis Leithead. MediaStream Recording. W3C Working Draft. URL: https://dvcs.w3.org/hg/dap/raw-file/tip/media-stream-capture/MediaRecorder.html