aboutsummaryrefslogtreecommitdiff
path: root/files/de/web/api/rtcpeerconnection/index.html
blob: df67ef624c00e1083e340b09e1a429eb1f323707 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
---
title: RTCPeerConnection
slug: Web/API/RTCPeerConnection
translation_of: Web/API/RTCPeerConnection
---
<p>{{APIRef}}{{SeeCompatTable}}</p>

<p>The <strong><code>RTCPeerConnection</code></strong> interface represents a WebRTC connection between the local computer and a remote peer. It is used to handle efficient streaming of data between the two peers.</p>

<div class="note">
<p><strong>Note:</strong> <code>RTCPeerConnection</code> and {{domxref("RTCSessionDescription")}} are currently prefixed in most browsers, and the {{domxref("navigator.getUserMedia()")}} method is prefixed in many versions of some browsers; you should use code like the following to access these:</p>

<pre class="brush: js">var peerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection ||
                       window.webkitRTCPeerConnection || window.msRTCPeerConnection;
var sessionDescription = window.RTCSessionDescription || window.mozRTCSessionDescription ||
                       window.webkitRTCSessionDescription || window.msRTCSessionDescription;

navigator.getUserMedia = navigator.getUserMedia || navigator.mozGetUserMedia ||
                       navigator.webkitGetUserMedia || navigator.msGetUserMedia;
</pre>

<p>Simple code such as this is all it takes to ensure that your project will work on as many versions of as many browsers as possible.</p>
</div>

<h2 id="Basic_usage">Basic usage</h2>

<p>Basic <code>RTCPeerConnection</code> usage involves negotiating a connection between your local machine and a remote one by generating <a href="http://en.wikipedia.org/wiki/Session_Description_Protocol">Session Description Protocol</a> to exchange between the two. The caller starts the process by sending an offer to the remote machine, which responds by either accepting or rejecting the call.</p>

<p>Both parties (the caller and the called party) need to set up their own <code>RTCPeerConnection</code> instances to represent their end of the peer-to-peer connection:</p>

<pre class="brush: js">var pc = new RTCPeerConnection();
pc.onaddstream = function(obj) {
  var vid = document.createElement("video");
  document.appendChild(vid);
  vid.srcObject = obj.stream;
}

// Helper functions
function endCall() {
  var videos = document.getElementsByTagName("video");
  for (var i = 0; i &lt; videos.length; i++) {
    videos[i].pause();
  }

  pc.<a href="#close()">close</a>();
}

function error(err) {
  endCall();
}
</pre>

<h3 id="Initializing_the_call">Initializing the call</h3>

<p>If you are the one initiating the call, you would use {{domxref("navigator.getUserMedia()")}} to get a video stream, then add the stream to the <code>RTCPeerConnection</code>. Once that's been done, call {{domxref("RTCPeerConnection.createOffer()")}} to create an offer, configure the offer, then send it to the server through which the connection is being mediated.</p>

<pre class="brush: js">// Get a list of friends from a server
// User selects a friend to start a peer connection with
navigator.getUserMedia({video: true}, function(stream) {
  // Adding a local stream won't trigger the onaddstream callback,
  // so call it manually.
  pc.onaddstream({stream: stream});
  pc.<a href="#addStream()">addStream</a>(stream);

  pc.<a href="#createOffer()">createOffer</a>(function(offer) {
    pc.<a href="#setLocalDescription()">setLocalDescription</a>(new <span class="nx">RTCSessionDescription</span>(offer), function() {
      // send the offer to a server to be forwarded to the friend you're calling.
    }, error);
  }, error);
});
</pre>

<h3 id="Answering_a_call">Answering a call</h3>

<p>On the opposite end, the friend will receive the offer from the server using whatever protocol is being used to do so. Once the offer arrives, {{domxref("navigator.getUserMedia()")}} is once again used to create the stream, which is added to the <code>RTCPeerConnection</code>. An {{domxref("RTCSessionDescription")}} object is created and set up as the remote description by calling {{domxref("RTCPeerConnection.setRemoteDescription()")}}.</p>

<p>Then an answer is created using {{domxref("RTCPeerConnection.createAnswer()")}} and sent back to the server, which forwards it to the caller.</p>

<pre class="brush: js">var offer = getOfferFromFriend();
navigator.getUserMedia({video: true}, function(stream) {
  pc.onaddstream({stream: stream});
  pc.<a href="#addStream()">addStream</a>(stream);

  pc.setRemoteDescription(new <span class="nx">RTCSessionDescription</span>(offer), function() {
    pc.<a href="#createAnswer()">createAnswer</a>(function(answer) {
      pc.<a href="#setLocalDescription()">setLocalDescription</a>(new <span class="nx">RTCSessionDescription</span>(answer), function() {
        // <span style="font-size: 1rem;">send the answer to a server to be forwarded back to the caller (you)</span>
      }, error);
    }, error);
  }, error);
});
</pre>

<h3 id="Handling_the_answer">Handling the answer</h3>

<p>Back on the original machine, the response is received. Once that happens, call {{domxref("RTCPeerConnection.setRemoteDescription()")}} to set the response as the remote end of the connection.</p>

<pre class="brush: js">// pc was set up earlier when we made the original offer
var offer = getResponseFromFriend();
pc.<a href="#createAnswer()">setRemoteDescription</a>(new <span class="nx">RTCSessionDescription</span>(offer), function() { }, error);
</pre>

<h2 id="Constructor">Constructor</h2>

<dl>
 <dt>{{domxref("RTCPeerConnection.RTCPeerConnection", "RTCPeerConnection()")}}</dt>
 <dd>Constructor; returns a new <code>RTCPeerConnection</code> object.</dd>
</dl>

<h2 id="Properties">Properties</h2>

<p><em>This interface inherits properties from its parent interface, {{domxref("EventTarget")}}.</em></p>

<dl>
 <dt>{{domxref("RTCPeerConnection.iceConnectionState")}} {{ReadOnlyInline}}</dt>
 <dd>Returns an enum of type <code>RTCIceConnectionState</code> that describes the ICE connection state for the connection. When this value changes, a {{event("iceconnectionstatechange")}} event is fired on the object.</dd>
 <dt>{{domxref("RTCPeerConnection.iceGatheringState")}} {{ReadOnlyInline}}</dt>
 <dd>Returns an enum of type <code>RTCIceGatheringState</code> that describes the ICE gathering state for the connection.</dd>
 <dt>{{domxref("RTCPeerConnection.localDescription")}} {{ReadOnlyInline}}</dt>
 <dd>Returns a {{domxref("RTCSessionDescription")}} describing the session for the local end of the connection. If it has not yet been set, it can be <code>null</code>.</dd>
 <dt>{{domxref("RTCPeerConnection.peerIdentity")}} {{ReadOnlyInline}}</dt>
 <dd>Returns a <code>RTCIdentityAssertion</code>, that is a couple of a domain name (<code>idp</code>) and a name (<code>name</code>) representing the identity of the remote peer of this connection, once set and verified. If no peer has yet been set and verified, this property will return <code>null</code>. Once set, via the appropriate method, it can't be changed.</dd>
 <dt>{{domxref("RTCPeerConnection.remoteDescription")}} {{ReadOnlyInline}}</dt>
 <dd>Returns a {{domxref("RTCSessionDescription")}} describing the session for the remote end of the connection. If it has not yet been set, it can be <code>null</code>.</dd>
 <dt>{{domxref("RTCPeerConnection.signalingState")}} {{ReadOnlyInline}}</dt>
 <dd>Returns an enum of type <code>RTCSignalingState</code> that describes the signaling state of the local connection. This state describes the SDP offer, that defines the configuration of the connections like the description of the locally associated objects of type {{domxref("MediaStream")}}, the codec/RTP/RTCP options, the candidates gathered by the ICE Agent. When this value changes, a {{event("signalingstatechange")}} event is fired on the object.</dd>
</dl>

<h3 id="Event_handlers">Event handlers</h3>

<dl>
 <dt>{{domxref("RTCPeerConnection.onaddstream")}}</dt>
 <dd>Is the event handler called when the {{event("addstream")}} event is received. Such an event is sent when a {{domxref("MediaStream")}} is added to this connection by the remote peer. The event is sent immediately after the call {{domxref("RTCPeerConnection.setRemoteDescription()")}} and doesn't wait for the result of the SDP negotiation.</dd>
 <dt>{{domxref("RTCPeerConnection.ondatachannel")}}</dt>
 <dd>Is the event handler called when the {{event("datachannel")}} event is received. Such an event is sent when a {{domxref("RTCDataChannel")}} is added to this connection.</dd>
 <dt>{{domxref("RTCPeerConnection.onicecandidate")}}</dt>
 <dd>Is the event handler called when the {{event("icecandidate")}} event is received. Such an event is sent when a {{domxref("RTCICECandidate")}} object is added to the script.</dd>
 <dt>{{domxref("RTCPeerConnection.oniceconnectionstatechange")}}</dt>
 <dd>Is the event handler called when the {{event("iceconnectionstatechange")}} event is received. Such an event is sent when the value of {{domxref("RTCPeerConnection.iceConnectionState", "iceConnectionState")}} changes.</dd>
 <dt>{{domxref("RTCPeerConnection.onidentityresult")}}</dt>
 <dd>Is the event handler called when the {{event("identityresult")}} event is received. Such an event is sent when an identity assertion is generated, via {{domxref("RTCPeerConnection.getIdentityAssertion()", "getIdentityAssertion()")}}, or during the creation of an offer or an answer.</dd>
 <dt>{{domxref("RTCPeerConnection.onidpassertionerror")}}</dt>
 <dd>Is the event handler called when the {{event("idpassertionerror")}} event is received. Such an event is sent when the associated identity provider (IdP) encounters an error while generating an identity assertion.</dd>
 <dt>{{domxref("RTCPeerConnection.onidpvalidationerror")}}</dt>
 <dd>Is the event handler alled when the {{event("idpvalidationerror")}} event is received. Such an event is sent when the associated identity provider (IdP) encounters an error while validating an identity assertion.</dd>
 <dt>{{domxref("RTCPeerConnection.onnegotiationneeded")}}</dt>
 <dd>Is the event handler called when the {{event("negotiationneeded")}} event, sent by the browser to inform that negotiation will be required at some point in the future, is received.</dd>
 <dt>{{domxref("RTCPeerConnection.onpeeridentity")}}</dt>
 <dd>Is the event handler called when the {{event("peeridentity")}} event, sent when a peer identity has been set and verified on this connection, is received.</dd>
 <dt>{{domxref("RTCPeerConnection.onremovestream")}}</dt>
 <dd>Is the event handler called when the {{event("removestream")}} event, sent when a {{domxref("MediaStream")}} is removed from this connection, is received.</dd>
 <dt>{{domxref("RTCPeerConnection.onsignalingstatechange")}}</dt>
 <dd>Is the event handler called when the {{event("signalingstatechange")}} event, sent when the value of {{domxref("RTCPeerConnection.signalingState", "signalingState")}} changes, is received.</dd>
</dl>

<h2 id="Methods">Methods</h2>

<dl>
 <dt>{{domxref("RTCPeerConnection.addIceCandidate()")}}</dt>
 <dd> </dd>
 <dt>{{domxref("RTCPeerConnection.addStream()")}}</dt>
 <dd>Adds a {{domxref("MediaStream")}} as a local source of audio or video. If the negotiation already happened, a new one will be needed for the remote peer to be able to use it.</dd>
 <dt>{{domxref("RTCPeerConnection.close()")}}</dt>
 <dd>Abruptly closes a connection.</dd>
 <dt>{{domxref("RTCPeerConnection.createAnswer()")}}</dt>
 <dd>Creates an answer to the offer received by the remote peer, in a two-part offer/answer negotiation of a connection. The two first parameters are respectively success and error callbacks, the optional third one represent options for the answer to be created.</dd>
 <dt>{{domxref("RTCPeerConnection.createDataChannel()")}}</dt>
 <dd>Creates a new {{domxref("RTCDataChannel")}} associated with this connection. The method takes a dictionary as parameter, with the configuration required for the underlying data channel, like its reliability.</dd>
 <dt>{{domxref("RTCPeerConnection.createDTMFSender()")}}</dt>
 <dd>Creates a new {{domxref("RTCDTMFSender")}}, associated to a specific {{domxref("MediaStreamTrack")}}, that will be able to send {{Glossary("DTMF")}} phone signaling over the connection.</dd>
 <dt>{{domxref("RTCPeerConnection.createOffer()")}}</dt>
 <dd>Creates a request to find a remote peer with a specific configuration. </dd>
 <dt>{{domxref("RTCPeerConnection.generateCertificate()")}}</dt>
 <dd>Creates and stores an X.509 certificate and corresponding private key then returns an {{domxref("RTCCertificate")}}, providing access to it.</dd>
 <dt>{{domxref("RTCPeerConnection.getConfiguration()")}}</dt>
 <dd> </dd>
 <dt>{{domxref("RTCPeerConnection.getIdentityAssertion()")}}</dt>
 <dd>Initiates the gathering of an identity assertion. This has an effect only if the {{domxref("RTCPeerConnection.signalingState", "signalingState")}} is not <code>"closed"</code>. It is not expected for the application dealing with the <code>RTCPeerConnection</code>: this is automatically done; an explicit call only allows to anticipate the need.</dd>
 <dt>{{domxref("RTCPeerConnection.getLocalStreams()")}}</dt>
 <dd>Returns an array of {{domxref("MediaStream")}} associated with the local end of the connection. The array may be empty.</dd>
 <dt>{{domxref("RTCPeerConnection.getRemoteStreams()")}}</dt>
 <dd>Returns an array of {{domxref("MediaStream")}} associated with the remote end of the connection. The array may be empty.</dd>
 <dt>{{domxref("RTCPeerConnection.getStats()")}}</dt>
 <dd>Creates a new {{domxref("RTCStatsReport")}} that contains and allows access to statistics regarding the connection.</dd>
 <dt>{{domxref("RTCPeerConnection.getStreamById()")}}</dt>
 <dd>Returns the {{domxref("MediaStream")}} with the given id that is associated with local or remote end of the connection. If no stream matches, it returns <code>null</code>.</dd>
 <dt>{{domxref("RTCPeerConnection.removeStream()")}}</dt>
 <dd>Removes a {{domxref("MediaStream")}} as a local source of audio or video. If the negotiation already happened, a new one will be needed for the remote peer to stop using it.</dd>
 <dt>{{domxref("RTCPeerConnection.setIdentityProvider()")}}</dt>
 <dd>Sets the Identity Provider (IdP) to the triplet given in parameter: its name, the protocol used to communicate with it (optional) and an optional username. The IdP will be used only when an assertion will be needed.</dd>
 <dt>{{domxref("RTCPeerConnection.setLocalDescription()")}}</dt>
 <dd>Changes the local description associated with the connection. The description defines the properties of the connection like its codec. The connection is affected by this change and must be able to support both old and new descriptions. The method takes three parameters, a {{domxref("RTCSessionDescription")}} object to set, and two callbacks, one called if the change of description succeeds, another called if it failed.</dd>
 <dt>{{domxref("RTCPeerConnection.setRemoteDescription()")}}</dt>
 <dd>Changes the remote description associated with the connection. The description defines the properties of the connection like its codec. The connection is affected by this change and must be able to support both old and new descriptions. The method takes three parameters, a {{domxref("RTCSessionDescription")}} object to set, and two callbacks, one called if the change of description succeeds, another called if it failed.</dd>
 <dt>{{domxref("RTCPeerConnection.updateIce()")}}</dt>
 <dd> </dd>
</dl>

<h3 id="Constructor_2">Constructor</h3>

<pre>new RTCPeerConnection({{domxref("RTCConfiguration")}} configuration, optional {{domxref("MediaConstraints")}} constraints);</pre>

<div class="note">
<p><strong>Note:</strong> While the PeerConnection specification reads like passing an RTCConfiguration object is required, Firefox will supply a default if you don't.</p>
</div>

<h2 id="Methods_2">Methods</h2>

<h3 id="createOffer">createOffer</h3>

<p><code>void createOffer({{domxref("RTCSessionDescriptionCallback")}} successCallback, {{domxref("RTCPeerConnectionErrorCallback")}} failureCallback, optional {{domxref("MediaConstraints")}} constraints);</code></p>

<p>Create offer generates a blob of description data to facilitate a PeerConnection to the local machine. Use this when you've got a remote Peer connection and you want to set up the local one.</p>

<h4 id="Example">Example</h4>

<pre class="prettyprint">var pc = new PeerConnection();
pc.addStream(video);
pc.createOffer(function(desc){
  pc.setLocalDescription(desc, function() {
    // send the offer to a server that can negotiate with a remote client
  });
}</pre>

<h4 id="Arguments">Arguments</h4>

<dl>
 <dt>successCallback</dt>
 <dd>An {{domxref("RTCSessionDescriptionCallback")}} which will be passed a single {{domxref("RTCSessionDescription")}} object</dd>
 <dt>errorCallback</dt>
 <dd>An {{domxref("RTCPeerConnectionErrorCallback")}} which will be passed a single {{domxref("DOMError")}} object</dd>
 <dt>[optional] constraints</dt>
 <dd>An optional {{domxref("MediaConstraints")}} object.</dd>
</dl>

<h3 id="createAnswer">createAnswer</h3>

<p><code>void createAnswer({{domxref("RTCSessionDescriptionCallback")}} successCallback, {{domxref("RTCPeerConnectionErrorCallback")}} failureCallback, optional {{domxref("MediaConstraints")}} constraints)")</code></p>

<p>Respond to an offer sent from a remote connection.</p>

<h4 id="Example_2">Example</h4>

<pre class="line">var pc = new PeerConnection();
pc.setRemoteDescription(new RTCSessionDescription(offer), function() {
  pc.createAnswer(function(answer) {
    pc.setLocalDescription(answer, function() {
      // send the answer to the remote connection
    })
  })
});</pre>

<h4 id="Arguments_2">Arguments</h4>

<dl>
 <dt>successCallback</dt>
 <dd>An {{domxref("RTCSessionDescriptionCallback")}} which will be passed a single {{domxref("RTCSessionDescription")}} object</dd>
 <dt>errorCallback</dt>
 <dd>An {{domxref("RTCPeerConnectionErrorCallback")}} which will be passed a single {{domxref("DOMError")}} object</dd>
 <dt>[optional] constraints</dt>
 <dd>An optional {{domxref("MediaConstraints")}} object.</dd>
</dl>

<h3 id="updateIce()">updateIce()</h3>

<p>updateIce(optional {{domxref("RTCConfiguration")}} configuration, optional {{domxref("MediaConstraints")}} constraints)</p>

<p>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.</p>

<h4 id="Example_3">Example</h4>

<pre> </pre>

<h3 id="addIceCandidate()">addIceCandidate()</h3>

<p>addIceCandidate ({{domxref("RTCIceCandidate")}} candidate, {{domxref("Function")}} successCallback, {{domxref("RTCPeerConnectionErrorCallback")}} failureCallback);</p>

<p>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.</p>

<h4 id="Example_4">Example</h4>

<pre>  pc.addIceCandidate(new RTCIceCandidate(candidate));
</pre>

<h3 id="createDataChannel">createDataChannel</h3>

<p><code>{{domxref("RTCDataChannel")}} createDataChannel ({{domxref("DOMString")}} label, optional {{domxref("RTCDataChannelInit")}} dataChannelDict);</code></p>

<p>Creates a data channel for sending non video or audio data across the peer connection</p>

<h4 id="Example_5">Example</h4>

<pre class="brush: js">var pc = new PeerConnection();
var channel = pc.createDataChannel("Mydata");
channel.onopen = function(event) {
  <code>channel.send('sending a message');</code>
}
channel.onmessage = function(event) { console.log(event.data); }</pre>

<h2 id="Specifications">Specifications</h2>

<table class="standard-table">
 <tbody>
  <tr>
   <th scope="col">Specification</th>
   <th scope="col">Status</th>
   <th scope="col">Comment</th>
  </tr>
  <tr>
   <td>{{SpecName('WebRTC 1.0')}}</td>
   <td>{{Spec2('WebRTC 1.0')}}</td>
   <td>Initial definition.</td>
  </tr>
 </tbody>
</table>

<h2 id="Browser_compatibility">Browser compatibility</h2>

<div>{{CompatibilityTable}}</div>

<div id="compat-desktop">
<table class="compat-table">
 <tbody>
  <tr>
   <th>Feature</th>
   <th>Chrome</th>
   <th>Firefox (Gecko)</th>
   <th>Internet Explorer</th>
   <th>Opera</th>
   <th>Safari (WebKit)</th>
  </tr>
  <tr>
   <td>Basic support</td>
   <td>{{CompatVersionUnknown}}</td>
   <td> </td>
   <td> </td>
   <td> </td>
   <td> </td>
  </tr>
 </tbody>
</table>
</div>

<div id="compat-mobile">
<table class="compat-table">
 <tbody>
  <tr>
   <th>Feature</th>
   <th>Android</th>
   <th>Android Webview</th>
   <th>Firefox Mobile (Gecko)</th>
   <th>Firefox OS</th>
   <th>IE Mobile</th>
   <th>Opera Mobile</th>
   <th>Safari Mobile</th>
   <th>Chrome for Android</th>
  </tr>
  <tr>
   <td>Basic support</td>
   <td>{{CompatNo}}</td>
   <td>{{CompatVersionUnknown}}</td>
   <td> </td>
   <td> </td>
   <td> </td>
   <td> </td>
   <td> </td>
   <td>{{CompatVersionUnknown}}</td>
  </tr>
 </tbody>
</table>
</div>

<h2 id="See_also">See also</h2>

<ul>
 <li><a href="https://github.com/jesup/nightly-gupshup/blob/master/static/js/chat.js">https://github.com/jesup/nightly-gupshup/blob/master/static/js/chat.js</a></li>
 <li><a href="http://www.html5rocks.com/en/tutorials/webrtc/basics/#toc-simple">http://www.html5rocks.com/en/tutorials/webrtc/basics/#toc-simple</a></li>
 <li><a href="http://dev.w3.org/2011/webrtc/editor/webrtc.html">http://dev.w3.org/2011/webrtc/editor/webrtc.html</a></li>
</ul>