Debian Codegraph @

eyes17/blockly/cv/webrtc-adapter.js

raw
1 (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.adapter = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
2 /*
3 * Copyright (c) 2017 The WebRTC project authors. All Rights Reserved.
4 *
5 * Use of this source code is governed by a BSD-style license
6 * that can be found in the LICENSE file in the root of the source
7 * tree.
8 */
9 /* eslint-env node */
10 'use strict';
11
12 var SDPUtils = require('sdp');
13
14 function writeMediaSection(transceiver, caps, type, stream) {
15 var sdp = SDPUtils.writeRtpDescription(transceiver.kind, caps);
16
17 // Map ICE parameters (ufrag, pwd) to SDP.
18 sdp += SDPUtils.writeIceParameters(
19 transceiver.iceGatherer.getLocalParameters());
20
21 // Map DTLS parameters to SDP.
22 sdp += SDPUtils.writeDtlsParameters(
23 transceiver.dtlsTransport.getLocalParameters(),
24 type === 'offer' ? 'actpass' : 'active');
25
26 sdp += 'a=mid:' + transceiver.mid + '\r\n';
27
28 if (transceiver.direction) {
29 sdp += 'a=' + transceiver.direction + '\r\n';
30 } else if (transceiver.rtpSender && transceiver.rtpReceiver) {
31 sdp += 'a=sendrecv\r\n';
32 } else if (transceiver.rtpSender) {
33 sdp += 'a=sendonly\r\n';
34 } else if (transceiver.rtpReceiver) {
35 sdp += 'a=recvonly\r\n';
36 } else {
37 sdp += 'a=inactive\r\n';
38 }
39
40 if (transceiver.rtpSender) {
41 // spec.
42 var msid = 'msid:' + stream.id + ' ' +
43 transceiver.rtpSender.track.id + '\r\n';
44 sdp += 'a=' + msid;
45
46 // for Chrome.
47 sdp += 'a=ssrc:' + transceiver.sendEncodingParameters[0].ssrc +
48 ' ' + msid;
49 if (transceiver.sendEncodingParameters[0].rtx) {
50 sdp += 'a=ssrc:' + transceiver.sendEncodingParameters[0].rtx.ssrc +
51 ' ' + msid;
52 sdp += 'a=ssrc-group:FID ' +
53 transceiver.sendEncodingParameters[0].ssrc + ' ' +
54 transceiver.sendEncodingParameters[0].rtx.ssrc +
55 '\r\n';
56 }
57 }
58 // FIXME: this should be written by writeRtpDescription.
59 sdp += 'a=ssrc:' + transceiver.sendEncodingParameters[0].ssrc +
60 ' cname:' + SDPUtils.localCName + '\r\n';
61 if (transceiver.rtpSender && transceiver.sendEncodingParameters[0].rtx) {
62 sdp += 'a=ssrc:' + transceiver.sendEncodingParameters[0].rtx.ssrc +
63 ' cname:' + SDPUtils.localCName + '\r\n';
64 }
65 return sdp;
66 }
67
68 // Edge does not like
69 // 1) stun: filtered after 14393 unless ?transport=udp is present
70 // 2) turn: that does not have all of turn:host:port?transport=udp
71 // 3) turn: with ipv6 addresses
72 // 4) turn: occurring muliple times
73 function filterIceServers(iceServers, edgeVersion) {
74 var hasTurn = false;
75 iceServers = JSON.parse(JSON.stringify(iceServers));
76 return iceServers.filter(function(server) {
77 if (server && (server.urls || server.url)) {
78 var urls = server.urls || server.url;
79 if (server.url && !server.urls) {
80 console.warn('RTCIceServer.url is deprecated! Use urls instead.');
81 }
82 var isString = typeof urls === 'string';
83 if (isString) {
84 urls = [urls];
85 }
86 urls = urls.filter(function(url) {
87 var validTurn = url.indexOf('turn:') === 0 &&
88 url.indexOf('transport=udp') !== -1 &&
89 url.indexOf('turn:[') === -1 &&
90 !hasTurn;
91
92 if (validTurn) {
93 hasTurn = true;
94 return true;
95 }
96 return url.indexOf('stun:') === 0 && edgeVersion >= 14393 &&
97 url.indexOf('?transport=udp') === -1;
98 });
99
100 delete server.url;
101 server.urls = isString ? urls[0] : urls;
102 return !!urls.length;
103 }
104 return false;
105 });
106 }
107
108 // Determines the intersection of local and remote capabilities.
109 function getCommonCapabilities(localCapabilities, remoteCapabilities) {
110 var commonCapabilities = {
111 codecs: [],
112 headerExtensions: [],
113 fecMechanisms: []
114 };
115
116 var findCodecByPayloadType = function(pt, codecs) {
117 pt = parseInt(pt, 10);
118 for (var i = 0; i < codecs.length; i++) {
119 if (codecs[i].payloadType === pt ||
120 codecs[i].preferredPayloadType === pt) {
121 return codecs[i];
122 }
123 }
124 };
125
126 var rtxCapabilityMatches = function(lRtx, rRtx, lCodecs, rCodecs) {
127 var lCodec = findCodecByPayloadType(lRtx.parameters.apt, lCodecs);
128 var rCodec = findCodecByPayloadType(rRtx.parameters.apt, rCodecs);
129 return lCodec && rCodec &&
130 lCodec.name.toLowerCase() === rCodec.name.toLowerCase();
131 };
132
133 localCapabilities.codecs.forEach(function(lCodec) {
134 for (var i = 0; i < remoteCapabilities.codecs.length; i++) {
135 var rCodec = remoteCapabilities.codecs[i];
136 if (lCodec.name.toLowerCase() === rCodec.name.toLowerCase() &&
137 lCodec.clockRate === rCodec.clockRate) {
138 if (lCodec.name.toLowerCase() === 'rtx' &&
139 lCodec.parameters && rCodec.parameters.apt) {
140 // for RTX we need to find the local rtx that has a apt
141 // which points to the same local codec as the remote one.
142 if (!rtxCapabilityMatches(lCodec, rCodec,
143 localCapabilities.codecs, remoteCapabilities.codecs)) {
144 continue;
145 }
146 }
147 rCodec = JSON.parse(JSON.stringify(rCodec)); // deepcopy
148 // number of channels is the highest common number of channels
149 rCodec.numChannels = Math.min(lCodec.numChannels,
150 rCodec.numChannels);
151 // push rCodec so we reply with offerer payload type
152 commonCapabilities.codecs.push(rCodec);
153
154 // determine common feedback mechanisms
155 rCodec.rtcpFeedback = rCodec.rtcpFeedback.filter(function(fb) {
156 for (var j = 0; j < lCodec.rtcpFeedback.length; j++) {
157 if (lCodec.rtcpFeedback[j].type === fb.type &&
158 lCodec.rtcpFeedback[j].parameter === fb.parameter) {
159 return true;
160 }
161 }
162 return false;
163 });
164 // FIXME: also need to determine .parameters
165 // see https://github.com/openpeer/ortc/issues/569
166 break;
167 }
168 }
169 });
170
171 localCapabilities.headerExtensions.forEach(function(lHeaderExtension) {
172 for (var i = 0; i < remoteCapabilities.headerExtensions.length;
173 i++) {
174 var rHeaderExtension = remoteCapabilities.headerExtensions[i];
175 if (lHeaderExtension.uri === rHeaderExtension.uri) {
176 commonCapabilities.headerExtensions.push(rHeaderExtension);
177 break;
178 }
179 }
180 });
181
182 // FIXME: fecMechanisms
183 return commonCapabilities;
184 }
185
186 // is action=setLocalDescription with type allowed in signalingState
187 function isActionAllowedInSignalingState(action, type, signalingState) {
188 return {
189 offer: {
190 setLocalDescription: ['stable', 'have-local-offer'],
191 setRemoteDescription: ['stable', 'have-remote-offer']
192 },
193 answer: {
194 setLocalDescription: ['have-remote-offer', 'have-local-pranswer'],
195 setRemoteDescription: ['have-local-offer', 'have-remote-pranswer']
196 }
197 }[type][action].indexOf(signalingState) !== -1;
198 }
199
200 function maybeAddCandidate(iceTransport, candidate) {
201 // Edge's internal representation adds some fields therefore
202 // not all fieldѕ are taken into account.
203 var alreadyAdded = iceTransport.getRemoteCandidates()
204 .find(function(remoteCandidate) {
205 return candidate.foundation === remoteCandidate.foundation &&
206 candidate.ip === remoteCandidate.ip &&
207 candidate.port === remoteCandidate.port &&
208 candidate.priority === remoteCandidate.priority &&
209 candidate.protocol === remoteCandidate.protocol &&
210 candidate.type === remoteCandidate.type;
211 });
212 if (!alreadyAdded) {
213 iceTransport.addRemoteCandidate(candidate);
214 }
215 return !alreadyAdded;
216 }
217
218 module.exports = function(window, edgeVersion) {
219 var RTCPeerConnection = function(config) {
220 var self = this;
221
222 var _eventTarget = document.createDocumentFragment();
223 ['addEventListener', 'removeEventListener', 'dispatchEvent']
224 .forEach(function(method) {
225 self[method] = _eventTarget[method].bind(_eventTarget);
226 });
227
228 this.onicecandidate = null;
229 this.onaddstream = null;
230 this.ontrack = null;
231 this.onremovestream = null;
232 this.onsignalingstatechange = null;
233 this.oniceconnectionstatechange = null;
234 this.onicegatheringstatechange = null;
235 this.onnegotiationneeded = null;
236 this.ondatachannel = null;
237 this.canTrickleIceCandidates = null;
238
239 this.needNegotiation = false;
240
241 this.localStreams = [];
242 this.remoteStreams = [];
243
244 this.localDescription = null;
245 this.remoteDescription = null;
246
247 this.signalingState = 'stable';
248 this.iceConnectionState = 'new';
249 this.iceGatheringState = 'new';
250
251 config = JSON.parse(JSON.stringify(config || {}));
252
253 this.usingBundle = config.bundlePolicy === 'max-bundle';
254 if (config.rtcpMuxPolicy === 'negotiate') {
255 var e = new Error('rtcpMuxPolicy \'negotiate\' is not supported');
256 e.name = 'NotSupportedError';
257 throw(e);
258 } else if (!config.rtcpMuxPolicy) {
259 config.rtcpMuxPolicy = 'require';
260 }
261
262 switch (config.iceTransportPolicy) {
263 case 'all':
264 case 'relay':
265 break;
266 default:
267 config.iceTransportPolicy = 'all';
268 break;
269 }
270
271 switch (config.bundlePolicy) {
272 case 'balanced':
273 case 'max-compat':
274 case 'max-bundle':
275 break;
276 default:
277 config.bundlePolicy = 'balanced';
278 break;
279 }
280
281 config.iceServers = filterIceServers(config.iceServers || [], edgeVersion);
282
283 this._iceGatherers = [];
284 if (config.iceCandidatePoolSize) {
285 for (var i = config.iceCandidatePoolSize; i > 0; i--) {
286 this._iceGatherers = new window.RTCIceGatherer({
287 iceServers: config.iceServers,
288 gatherPolicy: config.iceTransportPolicy
289 });
290 }
291 } else {
292 config.iceCandidatePoolSize = 0;
293 }
294
295 this._config = config;
296
297 // per-track iceGathers, iceTransports, dtlsTransports, rtpSenders, ...
298 // everything that is needed to describe a SDP m-line.
299 this.transceivers = [];
300
301 this._sdpSessionId = SDPUtils.generateSessionId();
302 this._sdpSessionVersion = 0;
303 };
304
305 RTCPeerConnection.prototype._emitGatheringStateChange = function() {
306 var event = new Event('icegatheringstatechange');
307 this.dispatchEvent(event);
308 if (typeof this.onicegatheringstatechange === 'function') {
309 this.onicegatheringstatechange(event);
310 }
311 };
312
313 RTCPeerConnection.prototype.getConfiguration = function() {
314 return this._config;
315 };
316
317 RTCPeerConnection.prototype.getLocalStreams = function() {
318 return this.localStreams;
319 };
320
321 RTCPeerConnection.prototype.getRemoteStreams = function() {
322 return this.remoteStreams;
323 };
324
325 // internal helper to create a transceiver object.
326 // (whih is not yet the same as the WebRTC 1.0 transceiver)
327 RTCPeerConnection.prototype._createTransceiver = function(kind) {
328 var hasBundleTransport = this.transceivers.length > 0;
329 var transceiver = {
330 track: null,
331 iceGatherer: null,
332 iceTransport: null,
333 dtlsTransport: null,
334 localCapabilities: null,
335 remoteCapabilities: null,
336 rtpSender: null,
337 rtpReceiver: null,
338 kind: kind,
339 mid: null,
340 sendEncodingParameters: null,
341 recvEncodingParameters: null,
342 stream: null,
343 wantReceive: true
344 };
345 if (this.usingBundle && hasBundleTransport) {
346 transceiver.iceTransport = this.transceivers[0].iceTransport;
347 transceiver.dtlsTransport = this.transceivers[0].dtlsTransport;
348 } else {
349 var transports = this._createIceAndDtlsTransports();
350 transceiver.iceTransport = transports.iceTransport;
351 transceiver.dtlsTransport = transports.dtlsTransport;
352 }
353 this.transceivers.push(transceiver);
354 return transceiver;
355 };
356
357 RTCPeerConnection.prototype.addTrack = function(track, stream) {
358 var transceiver;
359 for (var i = 0; i < this.transceivers.length; i++) {
360 if (!this.transceivers[i].track &&
361 this.transceivers[i].kind === track.kind) {
362 transceiver = this.transceivers[i];
363 }
364 }
365 if (!transceiver) {
366 transceiver = this._createTransceiver(track.kind);
367 }
368
369 this._maybeFireNegotiationNeeded();
370
371 if (this.localStreams.indexOf(stream) === -1) {
372 this.localStreams.push(stream);
373 }
374
375 transceiver.track = track;
376 transceiver.stream = stream;
377 transceiver.rtpSender = new window.RTCRtpSender(track,
378 transceiver.dtlsTransport);
379 return transceiver.rtpSender;
380 };
381
382 RTCPeerConnection.prototype.addStream = function(stream) {
383 var self = this;
384 if (edgeVersion >= 15025) {
385 stream.getTracks().forEach(function(track) {
386 self.addTrack(track, stream);
387 });
388 } else {
389 // Clone is necessary for local demos mostly, attaching directly
390 // to two different senders does not work (build 10547).
391 // Fixed in 15025 (or earlier)
392 var clonedStream = stream.clone();
393 stream.getTracks().forEach(function(track, idx) {
394 var clonedTrack = clonedStream.getTracks()[idx];
395 track.addEventListener('enabled', function(event) {
396 clonedTrack.enabled = event.enabled;
397 });
398 });
399 clonedStream.getTracks().forEach(function(track) {
400 self.addTrack(track, clonedStream);
401 });
402 }
403 };
404
405 RTCPeerConnection.prototype.removeStream = function(stream) {
406 var idx = this.localStreams.indexOf(stream);
407 if (idx > -1) {
408 this.localStreams.splice(idx, 1);
409 this._maybeFireNegotiationNeeded();
410 }
411 };
412
413 RTCPeerConnection.prototype.getSenders = function() {
414 return this.transceivers.filter(function(transceiver) {
415 return !!transceiver.rtpSender;
416 })
417 .map(function(transceiver) {
418 return transceiver.rtpSender;
419 });
420 };
421
422 RTCPeerConnection.prototype.getReceivers = function() {
423 return this.transceivers.filter(function(transceiver) {
424 return !!transceiver.rtpReceiver;
425 })
426 .map(function(transceiver) {
427 return transceiver.rtpReceiver;
428 });
429 };
430
431
432 RTCPeerConnection.prototype._createIceGatherer = function(sdpMLineIndex,
433 usingBundle) {
434 var self = this;
435 if (usingBundle && sdpMLineIndex > 0) {
436 return this.transceivers[0].iceGatherer;
437 } else if (this._iceGatherers.length) {
438 return this._iceGatherers.shift();
439 }
440 var iceGatherer = new window.RTCIceGatherer({
441 iceServers: this._config.iceServers,
442 gatherPolicy: this._config.iceTransportPolicy
443 });
444 Object.defineProperty(iceGatherer, 'state',
445 {value: 'new', writable: true}
446 );
447
448 this.transceivers[sdpMLineIndex].candidates = [];
449 this.transceivers[sdpMLineIndex].bufferCandidates = function(event) {
450 var end = !event.candidate || Object.keys(event.candidate).length === 0;
451 // polyfill since RTCIceGatherer.state is not implemented in
452 // Edge 10547 yet.
453 iceGatherer.state = end ? 'completed' : 'gathering';
454 if (self.transceivers[sdpMLineIndex].candidates !== null) {
455 self.transceivers[sdpMLineIndex].candidates.push(event.candidate);
456 }
457 };
458 iceGatherer.addEventListener('localcandidate',
459 this.transceivers[sdpMLineIndex].bufferCandidates);
460 return iceGatherer;
461 };
462
463 // start gathering from an RTCIceGatherer.
464 RTCPeerConnection.prototype._gather = function(mid, sdpMLineIndex) {
465 var self = this;
466 var iceGatherer = this.transceivers[sdpMLineIndex].iceGatherer;
467 if (iceGatherer.onlocalcandidate) {
468 return;
469 }
470 var candidates = this.transceivers[sdpMLineIndex].candidates;
471 this.transceivers[sdpMLineIndex].candidates = null;
472 iceGatherer.removeEventListener('localcandidate',
473 this.transceivers[sdpMLineIndex].bufferCandidates);
474 iceGatherer.onlocalcandidate = function(evt) {
475 if (self.usingBundle && sdpMLineIndex > 0) {
476 // if we know that we use bundle we can drop candidates with
477 // ѕdpMLineIndex > 0. If we don't do this then our state gets
478 // confused since we dispose the extra ice gatherer.
479 return;
480 }
481 var event = new Event('icecandidate');
482 event.candidate = {sdpMid: mid, sdpMLineIndex: sdpMLineIndex};
483
484 var cand = evt.candidate;
485 // Edge emits an empty object for RTCIceCandidateComplete‥
486 var end = !cand || Object.keys(cand).length === 0;
487 if (end) {
488 // polyfill since RTCIceGatherer.state is not implemented in
489 // Edge 10547 yet.
490 if (iceGatherer.state === 'new' || iceGatherer.state === 'gathering') {
491 iceGatherer.state = 'completed';
492 }
493 } else {
494 if (iceGatherer.state === 'new') {
495 iceGatherer.state = 'gathering';
496 }
497 // RTCIceCandidate doesn't have a component, needs to be added
498 cand.component = 1;
499 event.candidate.candidate = SDPUtils.writeCandidate(cand);
500 }
501
502 // update local description.
503 var sections = SDPUtils.splitSections(self.localDescription.sdp);
504 if (!end) {
505 sections[event.candidate.sdpMLineIndex + 1] +=
506 'a=' + event.candidate.candidate + '\r\n';
507 } else {
508 sections[event.candidate.sdpMLineIndex + 1] +=
509 'a=end-of-candidates\r\n';
510 }
511 self.localDescription.sdp = sections.join('');
512 var complete = self.transceivers.every(function(transceiver) {
513 return transceiver.iceGatherer &&
514 transceiver.iceGatherer.state === 'completed';
515 });
516
517 if (self.iceGatheringState !== 'gathering') {
518 self.iceGatheringState = 'gathering';
519 self._emitGatheringStateChange();
520 }
521
522 // Emit candidate. Also emit null candidate when all gatherers are
523 // complete.
524 if (!end) {
525 self.dispatchEvent(event);
526 if (typeof self.onicecandidate === 'function') {
527 self.onicecandidate(event);
528 }
529 }
530 if (complete) {
531 self.dispatchEvent(new Event('icecandidate'));
532 if (typeof self.onicecandidate === 'function') {
533 self.onicecandidate(new Event('icecandidate'));
534 }
535 self.iceGatheringState = 'complete';
536 self._emitGatheringStateChange();
537 }
538 };
539
540 // emit already gathered candidates.
541 window.setTimeout(function() {
542 candidates.forEach(function(candidate) {
543 var e = new Event('RTCIceGatherEvent');
544 e.candidate = candidate;
545 iceGatherer.onlocalcandidate(e);
546 });
547 }, 0);
548 };
549
550 // Create ICE transport and DTLS transport.
551 RTCPeerConnection.prototype._createIceAndDtlsTransports = function() {
552 var self = this;
553 var iceTransport = new window.RTCIceTransport(null);
554 iceTransport.onicestatechange = function() {
555 self._updateConnectionState();
556 };
557
558 var dtlsTransport = new window.RTCDtlsTransport(iceTransport);
559 dtlsTransport.ondtlsstatechange = function() {
560 self._updateConnectionState();
561 };
562 dtlsTransport.onerror = function() {
563 // onerror does not set state to failed by itself.
564 Object.defineProperty(dtlsTransport, 'state',
565 {value: 'failed', writable: true});
566 self._updateConnectionState();
567 };
568
569 return {
570 iceTransport: iceTransport,
571 dtlsTransport: dtlsTransport
572 };
573 };
574
575 // Destroy ICE gatherer, ICE transport and DTLS transport.
576 // Without triggering the callbacks.
577 RTCPeerConnection.prototype._disposeIceAndDtlsTransports = function(
578 sdpMLineIndex) {
579 var iceGatherer = this.transceivers[sdpMLineIndex].iceGatherer;
580 if (iceGatherer) {
581 delete iceGatherer.onlocalcandidate;
582 delete this.transceivers[sdpMLineIndex].iceGatherer;
583 }
584 var iceTransport = this.transceivers[sdpMLineIndex].iceTransport;
585 if (iceTransport) {
586 delete iceTransport.onicestatechange;
587 delete this.transceivers[sdpMLineIndex].iceTransport;
588 }
589 var dtlsTransport = this.transceivers[sdpMLineIndex].dtlsTransport;
590 if (dtlsTransport) {
591 delete dtlsTransport.ondtlsstatechange;
592 delete dtlsTransport.onerror;
593 delete this.transceivers[sdpMLineIndex].dtlsTransport;
594 }
595 };
596
597 // Start the RTP Sender and Receiver for a transceiver.
598 RTCPeerConnection.prototype._transceive = function(transceiver,
599 send, recv) {
600 var params = getCommonCapabilities(transceiver.localCapabilities,
601 transceiver.remoteCapabilities);
602 if (send && transceiver.rtpSender) {
603 params.encodings = transceiver.sendEncodingParameters;
604 params.rtcp = {
605 cname: SDPUtils.localCName,
606 compound: transceiver.rtcpParameters.compound
607 };
608 if (transceiver.recvEncodingParameters.length) {
609 params.rtcp.ssrc = transceiver.recvEncodingParameters[0].ssrc;
610 }
611 transceiver.rtpSender.send(params);
612 }
613 if (recv && transceiver.rtpReceiver && params.codecs.length > 0) {
614 // remove RTX field in Edge 14942
615 if (transceiver.kind === 'video'
616 && transceiver.recvEncodingParameters
617 && edgeVersion < 15019) {
618 transceiver.recvEncodingParameters.forEach(function(p) {
619 delete p.rtx;
620 });
621 }
622 params.encodings = transceiver.recvEncodingParameters;
623 params.rtcp = {
624 cname: transceiver.rtcpParameters.cname,
625 compound: transceiver.rtcpParameters.compound
626 };
627 if (transceiver.sendEncodingParameters.length) {
628 params.rtcp.ssrc = transceiver.sendEncodingParameters[0].ssrc;
629 }
630 transceiver.rtpReceiver.receive(params);
631 }
632 };
633
634 RTCPeerConnection.prototype.setLocalDescription = function(description) {
635 var self = this;
636 var args = arguments;
637
638 if (!isActionAllowedInSignalingState('setLocalDescription',
639 description.type, this.signalingState)) {
640 return new Promise(function(resolve, reject) {
641 var e = new Error('Can not set local ' + description.type +
642 ' in state ' + self.signalingState);
643 e.name = 'InvalidStateError';
644 if (args.length > 2 && typeof args[2] === 'function') {
645 args[2].apply(null, [e]);
646 }
647 reject(e);
648 });
649 }
650
651 var sections;
652 var sessionpart;
653 if (description.type === 'offer') {
654 // VERY limited support for SDP munging. Limited to:
655 // * changing the order of codecs
656 sections = SDPUtils.splitSections(description.sdp);
657 sessionpart = sections.shift();
658 sections.forEach(function(mediaSection, sdpMLineIndex) {
659 var caps = SDPUtils.parseRtpParameters(mediaSection);
660 self.transceivers[sdpMLineIndex].localCapabilities = caps;
661 });
662
663 this.transceivers.forEach(function(transceiver, sdpMLineIndex) {
664 self._gather(transceiver.mid, sdpMLineIndex);
665 });
666 } else if (description.type === 'answer') {
667 sections = SDPUtils.splitSections(self.remoteDescription.sdp);
668 sessionpart = sections.shift();
669 var isIceLite = SDPUtils.matchPrefix(sessionpart,
670 'a=ice-lite').length > 0;
671 sections.forEach(function(mediaSection, sdpMLineIndex) {
672 var transceiver = self.transceivers[sdpMLineIndex];
673 var iceGatherer = transceiver.iceGatherer;
674 var iceTransport = transceiver.iceTransport;
675 var dtlsTransport = transceiver.dtlsTransport;
676 var localCapabilities = transceiver.localCapabilities;
677 var remoteCapabilities = transceiver.remoteCapabilities;
678
679 // treat bundle-only as not-rejected.
680 var rejected = SDPUtils.isRejected(mediaSection) &&
681 !SDPUtils.matchPrefix(mediaSection, 'a=bundle-only').length === 1;
682
683 if (!rejected && !transceiver.isDatachannel) {
684 var remoteIceParameters = SDPUtils.getIceParameters(
685 mediaSection, sessionpart);
686 var remoteDtlsParameters = SDPUtils.getDtlsParameters(
687 mediaSection, sessionpart);
688 if (isIceLite) {
689 remoteDtlsParameters.role = 'server';
690 }
691
692 if (!self.usingBundle || sdpMLineIndex === 0) {
693 self._gather(transceiver.mid, sdpMLineIndex);
694 if (iceTransport.state === 'new') {
695 iceTransport.start(iceGatherer, remoteIceParameters,
696 isIceLite ? 'controlling' : 'controlled');
697 }
698 if (dtlsTransport.state === 'new') {
699 dtlsTransport.start(remoteDtlsParameters);
700 }
701 }
702
703 // Calculate intersection of capabilities.
704 var params = getCommonCapabilities(localCapabilities,
705 remoteCapabilities);
706
707 // Start the RTCRtpSender. The RTCRtpReceiver for this
708 // transceiver has already been started in setRemoteDescription.
709 self._transceive(transceiver,
710 params.codecs.length > 0,
711 false);
712 }
713 });
714 }
715
716 this.localDescription = {
717 type: description.type,
718 sdp: description.sdp
719 };
720 switch (description.type) {
721 case 'offer':
722 this._updateSignalingState('have-local-offer');
723 break;
724 case 'answer':
725 this._updateSignalingState('stable');
726 break;
727 default:
728 throw new TypeError('unsupported type "' + description.type +
729 '"');
730 }
731
732 // If a success callback was provided, emit ICE candidates after it
733 // has been executed. Otherwise, emit callback after the Promise is
734 // resolved.
735 var cb = arguments.length > 1 && typeof arguments[1] === 'function' &&
736 arguments[1];
737 return new Promise(function(resolve) {
738 if (cb) {
739 cb.apply(null);
740 }
741 resolve();
742 });
743 };
744
745 RTCPeerConnection.prototype.setRemoteDescription = function(description) {
746 var self = this;
747 var args = arguments;
748
749 if (!isActionAllowedInSignalingState('setRemoteDescription',
750 description.type, this.signalingState)) {
751 return new Promise(function(resolve, reject) {
752 var e = new Error('Can not set remote ' + description.type +
753 ' in state ' + self.signalingState);
754 e.name = 'InvalidStateError';
755 if (args.length > 2 && typeof args[2] === 'function') {
756 args[2].apply(null, [e]);
757 }
758 reject(e);
759 });
760 }
761
762 var streams = {};
763 this.remoteStreams.forEach(function(stream) {
764 streams[stream.id] = stream;
765 });
766 var receiverList = [];
767 var sections = SDPUtils.splitSections(description.sdp);
768 var sessionpart = sections.shift();
769 var isIceLite = SDPUtils.matchPrefix(sessionpart,
770 'a=ice-lite').length > 0;
771 var usingBundle = SDPUtils.matchPrefix(sessionpart,
772 'a=group:BUNDLE ').length > 0;
773 this.usingBundle = usingBundle;
774 var iceOptions = SDPUtils.matchPrefix(sessionpart,
775 'a=ice-options:')[0];
776 if (iceOptions) {
777 this.canTrickleIceCandidates = iceOptions.substr(14).split(' ')
778 .indexOf('trickle') >= 0;
779 } else {
780 this.canTrickleIceCandidates = false;
781 }
782
783 sections.forEach(function(mediaSection, sdpMLineIndex) {
784 var lines = SDPUtils.splitLines(mediaSection);
785 var kind = SDPUtils.getKind(mediaSection);
786 // treat bundle-only as not-rejected.
787 var rejected = SDPUtils.isRejected(mediaSection) &&
788 !SDPUtils.matchPrefix(mediaSection, 'a=bundle-only').length === 1;
789 var protocol = lines[0].substr(2).split(' ')[2];
790
791 var direction = SDPUtils.getDirection(mediaSection, sessionpart);
792 var remoteMsid = SDPUtils.parseMsid(mediaSection);
793
794 var mid = SDPUtils.getMid(mediaSection) || SDPUtils.generateIdentifier();
795
796 // Reject datachannels which are not implemented yet.
797 if (kind === 'application' && protocol === 'DTLS/SCTP') {
798 self.transceivers[sdpMLineIndex] = {
799 mid: mid,
800 isDatachannel: true
801 };
802 return;
803 }
804
805 var transceiver;
806 var iceGatherer;
807 var iceTransport;
808 var dtlsTransport;
809 var rtpReceiver;
810 var sendEncodingParameters;
811 var recvEncodingParameters;
812 var localCapabilities;
813
814 var track;
815 // FIXME: ensure the mediaSection has rtcp-mux set.
816 var remoteCapabilities = SDPUtils.parseRtpParameters(mediaSection);
817 var remoteIceParameters;
818 var remoteDtlsParameters;
819 if (!rejected) {
820 remoteIceParameters = SDPUtils.getIceParameters(mediaSection,
821 sessionpart);
822 remoteDtlsParameters = SDPUtils.getDtlsParameters(mediaSection,
823 sessionpart);
824 remoteDtlsParameters.role = 'client';
825 }
826 recvEncodingParameters =
827 SDPUtils.parseRtpEncodingParameters(mediaSection);
828
829 var rtcpParameters = SDPUtils.parseRtcpParameters(mediaSection);
830
831 var isComplete = SDPUtils.matchPrefix(mediaSection,
832 'a=end-of-candidates', sessionpart).length > 0;
833 var cands = SDPUtils.matchPrefix(mediaSection, 'a=candidate:')
834 .map(function(cand) {
835 return SDPUtils.parseCandidate(cand);
836 })
837 .filter(function(cand) {
838 return cand.component === 1;
839 });
840
841 // Check if we can use BUNDLE and dispose transports.
842 if ((description.type === 'offer' || description.type === 'answer') &&
843 !rejected && usingBundle && sdpMLineIndex > 0 &&
844 self.transceivers[sdpMLineIndex]) {
845 self._disposeIceAndDtlsTransports(sdpMLineIndex);
846 self.transceivers[sdpMLineIndex].iceGatherer =
847 self.transceivers[0].iceGatherer;
848 self.transceivers[sdpMLineIndex].iceTransport =
849 self.transceivers[0].iceTransport;
850 self.transceivers[sdpMLineIndex].dtlsTransport =
851 self.transceivers[0].dtlsTransport;
852 if (self.transceivers[sdpMLineIndex].rtpSender) {
853 self.transceivers[sdpMLineIndex].rtpSender.setTransport(
854 self.transceivers[0].dtlsTransport);
855 }
856 if (self.transceivers[sdpMLineIndex].rtpReceiver) {
857 self.transceivers[sdpMLineIndex].rtpReceiver.setTransport(
858 self.transceivers[0].dtlsTransport);
859 }
860 }
861 if (description.type === 'offer' && !rejected) {
862 transceiver = self.transceivers[sdpMLineIndex] ||
863 self._createTransceiver(kind);
864 transceiver.mid = mid;
865
866 if (!transceiver.iceGatherer) {
867 transceiver.iceGatherer = self._createIceGatherer(sdpMLineIndex,
868 usingBundle);
869 }
870
871 if (cands.length && transceiver.iceTransport.state === 'new') {
872 if (isComplete && (!usingBundle || sdpMLineIndex === 0)) {
873 transceiver.iceTransport.setRemoteCandidates(cands);
874 } else {
875 cands.forEach(function(candidate) {
876 maybeAddCandidate(transceiver.iceTransport, candidate);
877 });
878 }
879 }
880
881 localCapabilities = window.RTCRtpReceiver.getCapabilities(kind);
882
883 // filter RTX until additional stuff needed for RTX is implemented
884 // in adapter.js
885 if (edgeVersion < 15019) {
886 localCapabilities.codecs = localCapabilities.codecs.filter(
887 function(codec) {
888 return codec.name !== 'rtx';
889 });
890 }
891
892 sendEncodingParameters = [{
893 ssrc: (2 * sdpMLineIndex + 2) * 1001
894 }];
895
896 if (direction === 'sendrecv' || direction === 'sendonly') {
897 var isNewTrack = !transceiver.rtpReceiver;
898 rtpReceiver = transceiver.rtpReceiver ||
899 new window.RTCRtpReceiver(transceiver.dtlsTransport, kind);
900
901 if (isNewTrack) {
902 var stream;
903 track = rtpReceiver.track;
904 // FIXME: does not work with Plan B.
905 if (remoteMsid) {
906 if (!streams[remoteMsid.stream]) {
907 streams[remoteMsid.stream] = new window.MediaStream();
908 Object.defineProperty(streams[remoteMsid.stream], 'id', {
909 get: function() {
910 return remoteMsid.stream;
911 }
912 });
913 }
914 Object.defineProperty(track, 'id', {
915 get: function() {
916 return remoteMsid.track;
917 }
918 });
919 stream = streams[remoteMsid.stream];
920 } else {
921 if (!streams.default) {
922 streams.default = new window.MediaStream();
923 }
924 stream = streams.default;
925 }
926 stream.addTrack(track);
927 receiverList.push([track, rtpReceiver, stream]);
928 }
929 }
930
931 transceiver.localCapabilities = localCapabilities;
932 transceiver.remoteCapabilities = remoteCapabilities;
933 transceiver.rtpReceiver = rtpReceiver;
934 transceiver.rtcpParameters = rtcpParameters;
935 transceiver.sendEncodingParameters = sendEncodingParameters;
936 transceiver.recvEncodingParameters = recvEncodingParameters;
937
938 // Start the RTCRtpReceiver now. The RTPSender is started in
939 // setLocalDescription.
940 self._transceive(self.transceivers[sdpMLineIndex],
941 false,
942 direction === 'sendrecv' || direction === 'sendonly');
943 } else if (description.type === 'answer' && !rejected) {
944 transceiver = self.transceivers[sdpMLineIndex];
945 iceGatherer = transceiver.iceGatherer;
946 iceTransport = transceiver.iceTransport;
947 dtlsTransport = transceiver.dtlsTransport;
948 rtpReceiver = transceiver.rtpReceiver;
949 sendEncodingParameters = transceiver.sendEncodingParameters;
950 localCapabilities = transceiver.localCapabilities;
951
952 self.transceivers[sdpMLineIndex].recvEncodingParameters =
953 recvEncodingParameters;
954 self.transceivers[sdpMLineIndex].remoteCapabilities =
955 remoteCapabilities;
956 self.transceivers[sdpMLineIndex].rtcpParameters = rtcpParameters;
957
958 if (cands.length) {
959 if ((isIceLite || isComplete) &&
960 (!usingBundle || sdpMLineIndex === 0) &&
961 iceTransport.state === 'new') {
962 iceTransport.setRemoteCandidates(cands);
963 } else {
964 cands.forEach(function(candidate) {
965 maybeAddCandidate(transceiver.iceTransport, candidate);
966 });
967 }
968 }
969
970 if (!usingBundle || sdpMLineIndex === 0) {
971 if (iceTransport.state === 'new') {
972 iceTransport.start(iceGatherer, remoteIceParameters,
973 'controlling');
974 }
975 if (dtlsTransport.state === 'new') {
976 dtlsTransport.start(remoteDtlsParameters);
977 }
978 }
979
980 self._transceive(transceiver,
981 direction === 'sendrecv' || direction === 'recvonly',
982 direction === 'sendrecv' || direction === 'sendonly');
983
984 if (rtpReceiver &&
985 (direction === 'sendrecv' || direction === 'sendonly')) {
986 track = rtpReceiver.track;
987 if (remoteMsid) {
988 if (!streams[remoteMsid.stream]) {
989 streams[remoteMsid.stream] = new window.MediaStream();
990 }
991 streams[remoteMsid.stream].addTrack(track);
992 receiverList.push([track, rtpReceiver, streams[remoteMsid.stream]]);
993 } else {
994 if (!streams.default) {
995 streams.default = new window.MediaStream();
996 }
997 streams.default.addTrack(track);
998 receiverList.push([track, rtpReceiver, streams.default]);
999 }
1000 } else {
1001 // FIXME: actually the receiver should be created later.
1002 delete transceiver.rtpReceiver;
1003 }
1004 }
1005 });
1006
1007 this.remoteDescription = {
1008 type: description.type,
1009 sdp: description.sdp
1010 };
1011 switch (description.type) {
1012 case 'offer':
1013 this._updateSignalingState('have-remote-offer');
1014 break;
1015 case 'answer':
1016 this._updateSignalingState('stable');
1017 break;
1018 default:
1019 throw new TypeError('unsupported type "' + description.type +
1020 '"');
1021 }
1022 Object.keys(streams).forEach(function(sid) {
1023 var stream = streams[sid];
1024 if (stream.getTracks().length) {
1025 if (self.remoteStreams.indexOf(stream) === -1) {
1026 self.remoteStreams.push(stream);
1027 var event = new Event('addstream');
1028 event.stream = stream;
1029 window.setTimeout(function() {
1030 self.dispatchEvent(event);
1031 if (typeof self.onaddstream === 'function') {
1032 self.onaddstream(event);
1033 }
1034 });
1035 }
1036
1037 receiverList.forEach(function(item) {
1038 var track = item[0];
1039 var receiver = item[1];
1040 if (stream.id !== item[2].id) {
1041 return;
1042 }
1043 var trackEvent = new Event('track');
1044 trackEvent.track = track;
1045 trackEvent.receiver = receiver;
1046 trackEvent.transceiver = {receiver: receiver};
1047 trackEvent.streams = [stream];
1048 window.setTimeout(function() {
1049 self.dispatchEvent(trackEvent);
1050 if (typeof self.ontrack === 'function') {
1051 self.ontrack(trackEvent);
1052 }
1053 });
1054 });
1055 }
1056 });
1057
1058 // check whether addIceCandidate({}) was called within four seconds after
1059 // setRemoteDescription.
1060 window.setTimeout(function() {
1061 if (!(self && self.transceivers)) {
1062 return;
1063 }
1064 self.transceivers.forEach(function(transceiver) {
1065 if (transceiver.iceTransport &&
1066 transceiver.iceTransport.state === 'new' &&
1067 transceiver.iceTransport.getRemoteCandidates().length > 0) {
1068 console.warn('Timeout for addRemoteCandidate. Consider sending ' +
1069 'an end-of-candidates notification');
1070 transceiver.iceTransport.addRemoteCandidate({});
1071 }
1072 });
1073 }, 4000);
1074
1075 return new Promise(function(resolve) {
1076 if (args.length > 1 && typeof args[1] === 'function') {
1077 args[1].apply(null);
1078 }
1079 resolve();
1080 });
1081 };
1082
1083 RTCPeerConnection.prototype.close = function() {
1084 this.transceivers.forEach(function(transceiver) {
1085 /* not yet
1086 if (transceiver.iceGatherer) {
1087 transceiver.iceGatherer.close();
1088 }
1089 */
1090 if (transceiver.iceTransport) {
1091 transceiver.iceTransport.stop();
1092 }
1093 if (transceiver.dtlsTransport) {
1094 transceiver.dtlsTransport.stop();
1095 }
1096 if (transceiver.rtpSender) {
1097 transceiver.rtpSender.stop();
1098 }
1099 if (transceiver.rtpReceiver) {
1100 transceiver.rtpReceiver.stop();
1101 }
1102 });
1103 // FIXME: clean up tracks, local streams, remote streams, etc
1104 this._updateSignalingState('closed');
1105 };
1106
1107 // Update the signaling state.
1108 RTCPeerConnection.prototype._updateSignalingState = function(newState) {
1109 this.signalingState = newState;
1110 var event = new Event('signalingstatechange');
1111 this.dispatchEvent(event);
1112 if (typeof this.onsignalingstatechange === 'function') {
1113 this.onsignalingstatechange(event);
1114 }
1115 };
1116
1117 // Determine whether to fire the negotiationneeded event.
1118 RTCPeerConnection.prototype._maybeFireNegotiationNeeded = function() {
1119 var self = this;
1120 if (this.signalingState !== 'stable' || this.needNegotiation === true) {
1121 return;
1122 }
1123 this.needNegotiation = true;
1124 window.setTimeout(function() {
1125 if (self.needNegotiation === false) {
1126 return;
1127 }
1128 self.needNegotiation = false;
1129 var event = new Event('negotiationneeded');
1130 self.dispatchEvent(event);
1131 if (typeof self.onnegotiationneeded === 'function') {
1132 self.onnegotiationneeded(event);
1133 }
1134 }, 0);
1135 };
1136
1137 // Update the connection state.
1138 RTCPeerConnection.prototype._updateConnectionState = function() {
1139 var self = this;
1140 var newState;
1141 var states = {
1142 'new': 0,
1143 closed: 0,
1144 connecting: 0,
1145 checking: 0,
1146 connected: 0,
1147 completed: 0,
1148 disconnected: 0,
1149 failed: 0
1150 };
1151 this.transceivers.forEach(function(transceiver) {
1152 states[transceiver.iceTransport.state]++;
1153 states[transceiver.dtlsTransport.state]++;
1154 });
1155 // ICETransport.completed and connected are the same for this purpose.
1156 states.connected += states.completed;
1157
1158 newState = 'new';
1159 if (states.failed > 0) {
1160 newState = 'failed';
1161 } else if (states.connecting > 0 || states.checking > 0) {
1162 newState = 'connecting';
1163 } else if (states.disconnected > 0) {
1164 newState = 'disconnected';
1165 } else if (states.new > 0) {
1166 newState = 'new';
1167 } else if (states.connected > 0 || states.completed > 0) {
1168 newState = 'connected';
1169 }
1170
1171 if (newState !== self.iceConnectionState) {
1172 self.iceConnectionState = newState;
1173 var event = new Event('iceconnectionstatechange');
1174 this.dispatchEvent(event);
1175 if (typeof this.oniceconnectionstatechange === 'function') {
1176 this.oniceconnectionstatechange(event);
1177 }
1178 }
1179 };
1180
1181 RTCPeerConnection.prototype.createOffer = function() {
1182 var self = this;
1183 var args = arguments;
1184
1185 var offerOptions;
1186 if (arguments.length === 1 && typeof arguments[0] !== 'function') {
1187 offerOptions = arguments[0];
1188 } else if (arguments.length === 3) {
1189 offerOptions = arguments[2];
1190 }
1191
1192 var numAudioTracks = this.transceivers.filter(function(t) {
1193 return t.kind === 'audio';
1194 }).length;
1195 var numVideoTracks = this.transceivers.filter(function(t) {
1196 return t.kind === 'video';
1197 }).length;
1198
1199 // Determine number of audio and video tracks we need to send/recv.
1200 if (offerOptions) {
1201 // Reject Chrome legacy constraints.
1202 if (offerOptions.mandatory || offerOptions.optional) {
1203 throw new TypeError(
1204 'Legacy mandatory/optional constraints not supported.');
1205 }
1206 if (offerOptions.offerToReceiveAudio !== undefined) {
1207 if (offerOptions.offerToReceiveAudio === true) {
1208 numAudioTracks = 1;
1209 } else if (offerOptions.offerToReceiveAudio === false) {
1210 numAudioTracks = 0;
1211 } else {
1212 numAudioTracks = offerOptions.offerToReceiveAudio;
1213 }
1214 }
1215 if (offerOptions.offerToReceiveVideo !== undefined) {
1216 if (offerOptions.offerToReceiveVideo === true) {
1217 numVideoTracks = 1;
1218 } else if (offerOptions.offerToReceiveVideo === false) {
1219 numVideoTracks = 0;
1220 } else {
1221 numVideoTracks = offerOptions.offerToReceiveVideo;
1222 }
1223 }
1224 }
1225
1226 this.transceivers.forEach(function(transceiver) {
1227 if (transceiver.kind === 'audio') {
1228 numAudioTracks--;
1229 if (numAudioTracks < 0) {
1230 transceiver.wantReceive = false;
1231 }
1232 } else if (transceiver.kind === 'video') {
1233 numVideoTracks--;
1234 if (numVideoTracks < 0) {
1235 transceiver.wantReceive = false;
1236 }
1237 }
1238 });
1239
1240 // Create M-lines for recvonly streams.
1241 while (numAudioTracks > 0 || numVideoTracks > 0) {
1242 if (numAudioTracks > 0) {
1243 this._createTransceiver('audio');
1244 numAudioTracks--;
1245 }
1246 if (numVideoTracks > 0) {
1247 this._createTransceiver('video');
1248 numVideoTracks--;
1249 }
1250 }
1251
1252 var sdp = SDPUtils.writeSessionBoilerplate(this._sdpSessionId,
1253 this._sdpSessionVersion++);
1254 this.transceivers.forEach(function(transceiver, sdpMLineIndex) {
1255 // For each track, create an ice gatherer, ice transport,
1256 // dtls transport, potentially rtpsender and rtpreceiver.
1257 var track = transceiver.track;
1258 var kind = transceiver.kind;
1259 var mid = SDPUtils.generateIdentifier();
1260 transceiver.mid = mid;
1261
1262 if (!transceiver.iceGatherer) {
1263 transceiver.iceGatherer = self._createIceGatherer(sdpMLineIndex,
1264 self.usingBundle);
1265 }
1266
1267 var localCapabilities = window.RTCRtpSender.getCapabilities(kind);
1268 // filter RTX until additional stuff needed for RTX is implemented
1269 // in adapter.js
1270 if (edgeVersion < 15019) {
1271 localCapabilities.codecs = localCapabilities.codecs.filter(
1272 function(codec) {
1273 return codec.name !== 'rtx';
1274 });
1275 }
1276 localCapabilities.codecs.forEach(function(codec) {
1277 // work around https://bugs.chromium.org/p/webrtc/issues/detail?id=6552
1278 // by adding level-asymmetry-allowed=1
1279 if (codec.name === 'H264' &&
1280 codec.parameters['level-asymmetry-allowed'] === undefined) {
1281 codec.parameters['level-asymmetry-allowed'] = '1';
1282 }
1283 });
1284
1285 // generate an ssrc now, to be used later in rtpSender.send
1286 var sendEncodingParameters = [{
1287 ssrc: (2 * sdpMLineIndex + 1) * 1001
1288 }];
1289 if (track) {
1290 // add RTX
1291 if (edgeVersion >= 15019 && kind === 'video') {
1292 sendEncodingParameters[0].rtx = {
1293 ssrc: (2 * sdpMLineIndex + 1) * 1001 + 1
1294 };
1295 }
1296 }
1297
1298 if (transceiver.wantReceive) {
1299 transceiver.rtpReceiver = new window.RTCRtpReceiver(
1300 transceiver.dtlsTransport, kind);
1301 }
1302
1303 transceiver.localCapabilities = localCapabilities;
1304 transceiver.sendEncodingParameters = sendEncodingParameters;
1305 });
1306
1307 // always offer BUNDLE and dispose on return if not supported.
1308 if (this._config.bundlePolicy !== 'max-compat') {
1309 sdp += 'a=group:BUNDLE ' + this.transceivers.map(function(t) {
1310 return t.mid;
1311 }).join(' ') + '\r\n';
1312 }
1313 sdp += 'a=ice-options:trickle\r\n';
1314
1315 this.transceivers.forEach(function(transceiver, sdpMLineIndex) {
1316 sdp += writeMediaSection(transceiver,
1317 transceiver.localCapabilities, 'offer', transceiver.stream);
1318 sdp += 'a=rtcp-rsize\r\n';
1319
1320 if (transceiver.iceGatherer && self.iceGatheringState !== 'new' &&
1321 (sdpMLineIndex === 0 || !self.usingBundle)) {
1322 transceiver.iceGatherer.getLocalCandidates().forEach(function(cand) {
1323 cand.component = 1;
1324 sdp += 'a=' + SDPUtils.writeCandidate(cand) + '\r\n';
1325 });
1326
1327 if (transceiver.iceGatherer.state === 'completed') {
1328 sdp += 'a=end-of-candidates\r\n';
1329 }
1330 }
1331 });
1332
1333 var desc = new window.RTCSessionDescription({
1334 type: 'offer',
1335 sdp: sdp
1336 });
1337 return new Promise(function(resolve) {
1338 if (args.length > 0 && typeof args[0] === 'function') {
1339 args[0].apply(null, [desc]);
1340 resolve();
1341 return;
1342 }
1343 resolve(desc);
1344 });
1345 };
1346
1347 RTCPeerConnection.prototype.createAnswer = function() {
1348 var args = arguments;
1349
1350 var sdp = SDPUtils.writeSessionBoilerplate(this._sdpSessionId,
1351 this._sdpSessionVersion++);
1352 if (this.usingBundle) {
1353 sdp += 'a=group:BUNDLE ' + this.transceivers.map(function(t) {
1354 return t.mid;
1355 }).join(' ') + '\r\n';
1356 }
1357 var mediaSectionsInOffer = SDPUtils.splitSections(
1358 this.remoteDescription.sdp).length - 1;
1359 this.transceivers.forEach(function(transceiver, sdpMLineIndex) {
1360 if (sdpMLineIndex + 1 > mediaSectionsInOffer) {
1361 return;
1362 }
1363 if (transceiver.isDatachannel) {
1364 sdp += 'm=application 0 DTLS/SCTP 5000\r\n' +
1365 'c=IN IP4 0.0.0.0\r\n' +
1366 'a=mid:' + transceiver.mid + '\r\n';
1367 return;
1368 }
1369
1370 // FIXME: look at direction.
1371 if (transceiver.stream) {
1372 var localTrack;
1373 if (transceiver.kind === 'audio') {
1374 localTrack = transceiver.stream.getAudioTracks()[0];
1375 } else if (transceiver.kind === 'video') {
1376 localTrack = transceiver.stream.getVideoTracks()[0];
1377 }
1378 if (localTrack) {
1379 // add RTX
1380 if (edgeVersion >= 15019 && transceiver.kind === 'video') {
1381 transceiver.sendEncodingParameters[0].rtx = {
1382 ssrc: (2 * sdpMLineIndex + 2) * 1001 + 1
1383 };
1384 }
1385 }
1386 }
1387
1388 // Calculate intersection of capabilities.
1389 var commonCapabilities = getCommonCapabilities(
1390 transceiver.localCapabilities,
1391 transceiver.remoteCapabilities);
1392
1393 var hasRtx = commonCapabilities.codecs.filter(function(c) {
1394 return c.name.toLowerCase() === 'rtx';
1395 }).length;
1396 if (!hasRtx && transceiver.sendEncodingParameters[0].rtx) {
1397 delete transceiver.sendEncodingParameters[0].rtx;
1398 }
1399
1400 sdp += writeMediaSection(transceiver, commonCapabilities,
1401 'answer', transceiver.stream);
1402 if (transceiver.rtcpParameters &&
1403 transceiver.rtcpParameters.reducedSize) {
1404 sdp += 'a=rtcp-rsize\r\n';
1405 }
1406 });
1407
1408 var desc = new window.RTCSessionDescription({
1409 type: 'answer',
1410 sdp: sdp
1411 });
1412 return new Promise(function(resolve) {
1413 if (args.length > 0 && typeof args[0] === 'function') {
1414 args[0].apply(null, [desc]);
1415 resolve();
1416 return;
1417 }
1418 resolve(desc);
1419 });
1420 };
1421
1422 RTCPeerConnection.prototype.addIceCandidate = function(candidate) {
1423 var err;
1424 var sections;
1425 if (!candidate || candidate.candidate === '') {
1426 for (var j = 0; j < this.transceivers.length; j++) {
1427 if (this.transceivers[j].isDatachannel) {
1428 continue;
1429 }
1430 this.transceivers[j].iceTransport.addRemoteCandidate({});
1431 sections = SDPUtils.splitSections(this.remoteDescription.sdp);
1432 sections[j + 1] += 'a=end-of-candidates\r\n';
1433 this.remoteDescription.sdp = sections.join('');
1434 if (this.usingBundle) {
1435 break;
1436 }
1437 }
1438 } else if (!(candidate.sdpMLineIndex || candidate.sdpMid)) {
1439 throw new TypeError('sdpMLineIndex or sdpMid required');
1440 } else if (!this.remoteDescription) {
1441 err = new Error('Can not add ICE candidate without ' +
1442 'a remote description');
1443 err.name = 'InvalidStateError';
1444 } else {
1445 var sdpMLineIndex = candidate.sdpMLineIndex;
1446 if (candidate.sdpMid) {
1447 for (var i = 0; i < this.transceivers.length; i++) {
1448 if (this.transceivers[i].mid === candidate.sdpMid) {
1449 sdpMLineIndex = i;
1450 break;
1451 }
1452 }
1453 }
1454 var transceiver = this.transceivers[sdpMLineIndex];
1455 if (transceiver) {
1456 if (transceiver.isDatachannel) {
1457 return Promise.resolve();
1458 }
1459 var cand = Object.keys(candidate.candidate).length > 0 ?
1460 SDPUtils.parseCandidate(candidate.candidate) : {};
1461 // Ignore Chrome's invalid candidates since Edge does not like them.
1462 if (cand.protocol === 'tcp' && (cand.port === 0 || cand.port === 9)) {
1463 return Promise.resolve();
1464 }
1465 // Ignore RTCP candidates, we assume RTCP-MUX.
1466 if (cand.component && cand.component !== 1) {
1467 return Promise.resolve();
1468 }
1469 // when using bundle, avoid adding candidates to the wrong
1470 // ice transport. And avoid adding candidates added in the SDP.
1471 if (sdpMLineIndex === 0 || (sdpMLineIndex > 0 &&
1472 transceiver.iceTransport !== this.transceivers[0].iceTransport)) {
1473 if (!maybeAddCandidate(transceiver.iceTransport, cand)) {
1474 err = new Error('Can not add ICE candidate');
1475 err.name = 'OperationError';
1476 }
1477 }
1478
1479 if (!err) {
1480 // update the remoteDescription.
1481 var candidateString = candidate.candidate.trim();
1482 if (candidateString.indexOf('a=') === 0) {
1483 candidateString = candidateString.substr(2);
1484 }
1485 sections = SDPUtils.splitSections(this.remoteDescription.sdp);
1486 sections[sdpMLineIndex + 1] += 'a=' +
1487 (cand.type ? candidateString : 'end-of-candidates')
1488 + '\r\n';
1489 this.remoteDescription.sdp = sections.join('');
1490 }
1491 } else {
1492 err = new Error('Can not add ICE candidate');
1493 err.name = 'OperationError';
1494 }
1495 }
1496 var args = arguments;
1497 return new Promise(function(resolve, reject) {
1498 if (err) {
1499 if (args.length > 2 && typeof args[2] === 'function') {
1500 args[2].apply(null, [err]);
1501 }
1502 reject(err);
1503 } else {
1504 if (args.length > 1 && typeof args[1] === 'function') {
1505 args[1].apply(null);
1506 }
1507 resolve();
1508 }
1509 });
1510 };
1511
1512 RTCPeerConnection.prototype.getStats = function() {
1513 var promises = [];
1514 this.transceivers.forEach(function(transceiver) {
1515 ['rtpSender', 'rtpReceiver', 'iceGatherer', 'iceTransport',
1516 'dtlsTransport'].forEach(function(method) {
1517 if (transceiver[method]) {
1518 promises.push(transceiver[method].getStats());
1519 }
1520 });
1521 });
1522 var cb = arguments.length > 1 && typeof arguments[1] === 'function' &&
1523 arguments[1];
1524 var fixStatsType = function(stat) {
1525 return {
1526 inboundrtp: 'inbound-rtp',
1527 outboundrtp: 'outbound-rtp',
1528 candidatepair: 'candidate-pair',
1529 localcandidate: 'local-candidate',
1530 remotecandidate: 'remote-candidate'
1531 }[stat.type] || stat.type;
1532 };
1533 return new Promise(function(resolve) {
1534 // shim getStats with maplike support
1535 var results = new Map();
1536 Promise.all(promises).then(function(res) {
1537 res.forEach(function(result) {
1538 Object.keys(result).forEach(function(id) {
1539 result[id].type = fixStatsType(result[id]);
1540 results.set(id, result[id]);
1541 });
1542 });
1543 if (cb) {
1544 cb.apply(null, results);
1545 }
1546 resolve(results);
1547 });
1548 });
1549 };
1550 return RTCPeerConnection;
1551 };
1552
1553 },{"sdp":2}],2:[function(require,module,exports){
1554 /* eslint-env node */
1555 'use strict';
1556
1557 // SDP helpers.
1558 var SDPUtils = {};
1559
1560 // Generate an alphanumeric identifier for cname or mids.
1561 // TODO: use UUIDs instead? https://gist.github.com/jed/982883
1562 SDPUtils.generateIdentifier = function() {
1563 return Math.random().toString(36).substr(2, 10);
1564 };
1565
1566 // The RTCP CNAME used by all peerconnections from the same JS.
1567 SDPUtils.localCName = SDPUtils.generateIdentifier();
1568
1569 // Splits SDP into lines, dealing with both CRLF and LF.
1570 SDPUtils.splitLines = function(blob) {
1571 return blob.trim().split('\n').map(function(line) {
1572 return line.trim();
1573 });
1574 };
1575 // Splits SDP into sessionpart and mediasections. Ensures CRLF.
1576 SDPUtils.splitSections = function(blob) {
1577 var parts = blob.split('\nm=');
1578 return parts.map(function(part, index) {
1579 return (index > 0 ? 'm=' + part : part).trim() + '\r\n';
1580 });
1581 };
1582
1583 // Returns lines that start with a certain prefix.
1584 SDPUtils.matchPrefix = function(blob, prefix) {
1585 return SDPUtils.splitLines(blob).filter(function(line) {
1586 return line.indexOf(prefix) === 0;
1587 });
1588 };
1589
1590 // Parses an ICE candidate line. Sample input:
1591 // candidate:702786350 2 udp 41819902 8.8.8.8 60769 typ relay raddr 8.8.8.8
1592 // rport 55996"
1593 SDPUtils.parseCandidate = function(line) {
1594 var parts;
1595 // Parse both variants.
1596 if (line.indexOf('a=candidate:') === 0) {
1597 parts = line.substring(12).split(' ');
1598 } else {
1599 parts = line.substring(10).split(' ');
1600 }
1601
1602 var candidate = {
1603 foundation: parts[0],
1604 component: parseInt(parts[1], 10),
1605 protocol: parts[2].toLowerCase(),
1606 priority: parseInt(parts[3], 10),
1607 ip: parts[4],
1608 port: parseInt(parts[5], 10),
1609 // skip parts[6] == 'typ'
1610 type: parts[7]
1611 };
1612
1613 for (var i = 8; i < parts.length; i += 2) {
1614 switch (parts[i]) {
1615 case 'raddr':
1616 candidate.relatedAddress = parts[i + 1];
1617 break;
1618 case 'rport':
1619 candidate.relatedPort = parseInt(parts[i + 1], 10);
1620 break;
1621 case 'tcptype':
1622 candidate.tcpType = parts[i + 1];
1623 break;
1624 case 'ufrag':
1625 candidate.ufrag = parts[i + 1]; // for backward compability.
1626 candidate.usernameFragment = parts[i + 1];
1627 break;
1628 default: // extension handling, in particular ufrag
1629 candidate[parts[i]] = parts[i + 1];
1630 break;
1631 }
1632 }
1633 return candidate;
1634 };
1635
1636 // Translates a candidate object into SDP candidate attribute.
1637 SDPUtils.writeCandidate = function(candidate) {
1638 var sdp = [];
1639 sdp.push(candidate.foundation);
1640 sdp.push(candidate.component);
1641 sdp.push(candidate.protocol.toUpperCase());
1642 sdp.push(candidate.priority);
1643 sdp.push(candidate.ip);
1644 sdp.push(candidate.port);
1645
1646 var type = candidate.type;
1647 sdp.push('typ');
1648 sdp.push(type);
1649 if (type !== 'host' && candidate.relatedAddress &&
1650 candidate.relatedPort) {
1651 sdp.push('raddr');
1652 sdp.push(candidate.relatedAddress); // was: relAddr
1653 sdp.push('rport');
1654 sdp.push(candidate.relatedPort); // was: relPort
1655 }
1656 if (candidate.tcpType && candidate.protocol.toLowerCase() === 'tcp') {
1657 sdp.push('tcptype');
1658 sdp.push(candidate.tcpType);
1659 }
1660 if (candidate.ufrag) {
1661 sdp.push('ufrag');
1662 sdp.push(candidate.ufrag);
1663 }
1664 return 'candidate:' + sdp.join(' ');
1665 };
1666
1667 // Parses an ice-options line, returns an array of option tags.
1668 // a=ice-options:foo bar
1669 SDPUtils.parseIceOptions = function(line) {
1670 return line.substr(14).split(' ');
1671 }
1672
1673 // Parses an rtpmap line, returns RTCRtpCoddecParameters. Sample input:
1674 // a=rtpmap:111 opus/48000/2
1675 SDPUtils.parseRtpMap = function(line) {
1676 var parts = line.substr(9).split(' ');
1677 var parsed = {
1678 payloadType: parseInt(parts.shift(), 10) // was: id
1679 };
1680
1681 parts = parts[0].split('/');
1682
1683 parsed.name = parts[0];
1684 parsed.clockRate = parseInt(parts[1], 10); // was: clockrate
1685 // was: channels
1686 parsed.numChannels = parts.length === 3 ? parseInt(parts[2], 10) : 1;
1687 return parsed;
1688 };
1689
1690 // Generate an a=rtpmap line from RTCRtpCodecCapability or
1691 // RTCRtpCodecParameters.
1692 SDPUtils.writeRtpMap = function(codec) {
1693 var pt = codec.payloadType;
1694 if (codec.preferredPayloadType !== undefined) {
1695 pt = codec.preferredPayloadType;
1696 }
1697 return 'a=rtpmap:' + pt + ' ' + codec.name + '/' + codec.clockRate +
1698 (codec.numChannels !== 1 ? '/' + codec.numChannels : '') + '\r\n';
1699 };
1700
1701 // Parses an a=extmap line (headerextension from RFC 5285). Sample input:
1702 // a=extmap:2 urn:ietf:params:rtp-hdrext:toffset
1703 // a=extmap:2/sendonly urn:ietf:params:rtp-hdrext:toffset
1704 SDPUtils.parseExtmap = function(line) {
1705 var parts = line.substr(9).split(' ');
1706 return {
1707 id: parseInt(parts[0], 10),
1708 direction: parts[0].indexOf('/') > 0 ? parts[0].split('/')[1] : 'sendrecv',
1709 uri: parts[1]
1710 };
1711 };
1712
1713 // Generates a=extmap line from RTCRtpHeaderExtensionParameters or
1714 // RTCRtpHeaderExtension.
1715 SDPUtils.writeExtmap = function(headerExtension) {
1716 return 'a=extmap:' + (headerExtension.id || headerExtension.preferredId) +
1717 (headerExtension.direction && headerExtension.direction !== 'sendrecv'
1718 ? '/' + headerExtension.direction
1719 : '') +
1720 ' ' + headerExtension.uri + '\r\n';
1721 };
1722
1723 // Parses an ftmp line, returns dictionary. Sample input:
1724 // a=fmtp:96 vbr=on;cng=on
1725 // Also deals with vbr=on; cng=on
1726 SDPUtils.parseFmtp = function(line) {
1727 var parsed = {};
1728 var kv;
1729 var parts = line.substr(line.indexOf(' ') + 1).split(';');
1730 for (var j = 0; j < parts.length; j++) {
1731 kv = parts[j].trim().split('=');
1732 parsed[kv[0].trim()] = kv[1];
1733 }
1734 return parsed;
1735 };
1736
1737 // Generates an a=ftmp line from RTCRtpCodecCapability or RTCRtpCodecParameters.
1738 SDPUtils.writeFmtp = function(codec) {
1739 var line = '';
1740 var pt = codec.payloadType;
1741 if (codec.preferredPayloadType !== undefined) {
1742 pt = codec.preferredPayloadType;
1743 }
1744 if (codec.parameters && Object.keys(codec.parameters).length) {
1745 var params = [];
1746 Object.keys(codec.parameters).forEach(function(param) {
1747 params.push(param + '=' + codec.parameters[param]);
1748 });
1749 line += 'a=fmtp:' + pt + ' ' + params.join(';') + '\r\n';
1750 }
1751 return line;
1752 };
1753
1754 // Parses an rtcp-fb line, returns RTCPRtcpFeedback object. Sample input:
1755 // a=rtcp-fb:98 nack rpsi
1756 SDPUtils.parseRtcpFb = function(line) {
1757 var parts = line.substr(line.indexOf(' ') + 1).split(' ');
1758 return {
1759 type: parts.shift(),
1760 parameter: parts.join(' ')
1761 };
1762 };
1763 // Generate a=rtcp-fb lines from RTCRtpCodecCapability or RTCRtpCodecParameters.
1764 SDPUtils.writeRtcpFb = function(codec) {
1765 var lines = '';
1766 var pt = codec.payloadType;
1767 if (codec.preferredPayloadType !== undefined) {
1768 pt = codec.preferredPayloadType;
1769 }
1770 if (codec.rtcpFeedback && codec.rtcpFeedback.length) {
1771 // FIXME: special handling for trr-int?
1772 codec.rtcpFeedback.forEach(function(fb) {
1773 lines += 'a=rtcp-fb:' + pt + ' ' + fb.type +
1774 (fb.parameter && fb.parameter.length ? ' ' + fb.parameter : '') +
1775 '\r\n';
1776 });
1777 }
1778 return lines;
1779 };
1780
1781 // Parses an RFC 5576 ssrc media attribute. Sample input:
1782 // a=ssrc:3735928559 cname:something
1783 SDPUtils.parseSsrcMedia = function(line) {
1784 var sp = line.indexOf(' ');
1785 var parts = {
1786 ssrc: parseInt(line.substr(7, sp - 7), 10)
1787 };
1788 var colon = line.indexOf(':', sp);
1789 if (colon > -1) {
1790 parts.attribute = line.substr(sp + 1, colon - sp - 1);
1791 parts.value = line.substr(colon + 1);
1792 } else {
1793 parts.attribute = line.substr(sp + 1);
1794 }
1795 return parts;
1796 };
1797
1798 // Extracts the MID (RFC 5888) from a media section.
1799 // returns the MID or undefined if no mid line was found.
1800 SDPUtils.getMid = function(mediaSection) {
1801 var mid = SDPUtils.matchPrefix(mediaSection, 'a=mid:')[0];
1802 if (mid) {
1803 return mid.substr(6);
1804 }
1805 }
1806
1807 SDPUtils.parseFingerprint = function(line) {
1808 var parts = line.substr(14).split(' ');
1809 return {
1810 algorithm: parts[0].toLowerCase(), // algorithm is case-sensitive in Edge.
1811 value: parts[1]
1812 };
1813 };
1814
1815 // Extracts DTLS parameters from SDP media section or sessionpart.
1816 // FIXME: for consistency with other functions this should only
1817 // get the fingerprint line as input. See also getIceParameters.
1818 SDPUtils.getDtlsParameters = function(mediaSection, sessionpart) {
1819 var lines = SDPUtils.matchPrefix(mediaSection + sessionpart,
1820 'a=fingerprint:');
1821 // Note: a=setup line is ignored since we use the 'auto' role.
1822 // Note2: 'algorithm' is not case sensitive except in Edge.
1823 return {
1824 role: 'auto',
1825 fingerprints: lines.map(SDPUtils.parseFingerprint)
1826 };
1827 };
1828
1829 // Serializes DTLS parameters to SDP.
1830 SDPUtils.writeDtlsParameters = function(params, setupType) {
1831 var sdp = 'a=setup:' + setupType + '\r\n';
1832 params.fingerprints.forEach(function(fp) {
1833 sdp += 'a=fingerprint:' + fp.algorithm + ' ' + fp.value + '\r\n';
1834 });
1835 return sdp;
1836 };
1837 // Parses ICE information from SDP media section or sessionpart.
1838 // FIXME: for consistency with other functions this should only
1839 // get the ice-ufrag and ice-pwd lines as input.
1840 SDPUtils.getIceParameters = function(mediaSection, sessionpart) {
1841 var lines = SDPUtils.splitLines(mediaSection);
1842 // Search in session part, too.
1843 lines = lines.concat(SDPUtils.splitLines(sessionpart));
1844 var iceParameters = {
1845 usernameFragment: lines.filter(function(line) {
1846 return line.indexOf('a=ice-ufrag:') === 0;
1847 })[0].substr(12),
1848 password: lines.filter(function(line) {
1849 return line.indexOf('a=ice-pwd:') === 0;
1850 })[0].substr(10)
1851 };
1852 return iceParameters;
1853 };
1854
1855 // Serializes ICE parameters to SDP.
1856 SDPUtils.writeIceParameters = function(params) {
1857 return 'a=ice-ufrag:' + params.usernameFragment + '\r\n' +
1858 'a=ice-pwd:' + params.password + '\r\n';
1859 };
1860
1861 // Parses the SDP media section and returns RTCRtpParameters.
1862 SDPUtils.parseRtpParameters = function(mediaSection) {
1863 var description = {
1864 codecs: [],
1865 headerExtensions: [],
1866 fecMechanisms: [],
1867 rtcp: []
1868 };
1869 var lines = SDPUtils.splitLines(mediaSection);
1870 var mline = lines[0].split(' ');
1871 for (var i = 3; i < mline.length; i++) { // find all codecs from mline[3..]
1872 var pt = mline[i];
1873 var rtpmapline = SDPUtils.matchPrefix(
1874 mediaSection, 'a=rtpmap:' + pt + ' ')[0];
1875 if (rtpmapline) {
1876 var codec = SDPUtils.parseRtpMap(rtpmapline);
1877 var fmtps = SDPUtils.matchPrefix(
1878 mediaSection, 'a=fmtp:' + pt + ' ');
1879 // Only the first a=fmtp:<pt> is considered.
1880 codec.parameters = fmtps.length ? SDPUtils.parseFmtp(fmtps[0]) : {};
1881 codec.rtcpFeedback = SDPUtils.matchPrefix(
1882 mediaSection, 'a=rtcp-fb:' + pt + ' ')
1883 .map(SDPUtils.parseRtcpFb);
1884 description.codecs.push(codec);
1885 // parse FEC mechanisms from rtpmap lines.
1886 switch (codec.name.toUpperCase()) {
1887 case 'RED':
1888 case 'ULPFEC':
1889 description.fecMechanisms.push(codec.name.toUpperCase());
1890 break;
1891 default: // only RED and ULPFEC are recognized as FEC mechanisms.
1892 break;
1893 }
1894 }
1895 }
1896 SDPUtils.matchPrefix(mediaSection, 'a=extmap:').forEach(function(line) {
1897 description.headerExtensions.push(SDPUtils.parseExtmap(line));
1898 });
1899 // FIXME: parse rtcp.
1900 return description;
1901 };
1902
1903 // Generates parts of the SDP media section describing the capabilities /
1904 // parameters.
1905 SDPUtils.writeRtpDescription = function(kind, caps) {
1906 var sdp = '';
1907
1908 // Build the mline.
1909 sdp += 'm=' + kind + ' ';
1910 sdp += caps.codecs.length > 0 ? '9' : '0'; // reject if no codecs.
1911 sdp += ' UDP/TLS/RTP/SAVPF ';
1912 sdp += caps.codecs.map(function(codec) {
1913 if (codec.preferredPayloadType !== undefined) {
1914 return codec.preferredPayloadType;
1915 }
1916 return codec.payloadType;
1917 }).join(' ') + '\r\n';
1918
1919 sdp += 'c=IN IP4 0.0.0.0\r\n';
1920 sdp += 'a=rtcp:9 IN IP4 0.0.0.0\r\n';
1921
1922 // Add a=rtpmap lines for each codec. Also fmtp and rtcp-fb.
1923 caps.codecs.forEach(function(codec) {
1924 sdp += SDPUtils.writeRtpMap(codec);
1925 sdp += SDPUtils.writeFmtp(codec);
1926 sdp += SDPUtils.writeRtcpFb(codec);
1927 });
1928 var maxptime = 0;
1929 caps.codecs.forEach(function(codec) {
1930 if (codec.maxptime > maxptime) {
1931 maxptime = codec.maxptime;
1932 }
1933 });
1934 if (maxptime > 0) {
1935 sdp += 'a=maxptime:' + maxptime + '\r\n';
1936 }
1937 sdp += 'a=rtcp-mux\r\n';
1938
1939 caps.headerExtensions.forEach(function(extension) {
1940 sdp += SDPUtils.writeExtmap(extension);
1941 });
1942 // FIXME: write fecMechanisms.
1943 return sdp;
1944 };
1945
1946 // Parses the SDP media section and returns an array of
1947 // RTCRtpEncodingParameters.
1948 SDPUtils.parseRtpEncodingParameters = function(mediaSection) {
1949 var encodingParameters = [];
1950 var description = SDPUtils.parseRtpParameters(mediaSection);
1951 var hasRed = description.fecMechanisms.indexOf('RED') !== -1;
1952 var hasUlpfec = description.fecMechanisms.indexOf('ULPFEC') !== -1;
1953
1954 // filter a=ssrc:... cname:, ignore PlanB-msid
1955 var ssrcs = SDPUtils.matchPrefix(mediaSection, 'a=ssrc:')
1956 .map(function(line) {
1957 return SDPUtils.parseSsrcMedia(line);
1958 })
1959 .filter(function(parts) {
1960 return parts.attribute === 'cname';
1961 });
1962 var primarySsrc = ssrcs.length > 0 && ssrcs[0].ssrc;
1963 var secondarySsrc;
1964
1965 var flows = SDPUtils.matchPrefix(mediaSection, 'a=ssrc-group:FID')
1966 .map(function(line) {
1967 var parts = line.split(' ');
1968 parts.shift();
1969 return parts.map(function(part) {
1970 return parseInt(part, 10);
1971 });
1972 });
1973 if (flows.length > 0 && flows[0].length > 1 && flows[0][0] === primarySsrc) {
1974 secondarySsrc = flows[0][1];
1975 }
1976
1977 description.codecs.forEach(function(codec) {
1978 if (codec.name.toUpperCase() === 'RTX' && codec.parameters.apt) {
1979 var encParam = {
1980 ssrc: primarySsrc,
1981 codecPayloadType: parseInt(codec.parameters.apt, 10),
1982 rtx: {
1983 ssrc: secondarySsrc
1984 }
1985 };
1986 encodingParameters.push(encParam);
1987 if (hasRed) {
1988 encParam = JSON.parse(JSON.stringify(encParam));
1989 encParam.fec = {
1990 ssrc: secondarySsrc,
1991 mechanism: hasUlpfec ? 'red+ulpfec' : 'red'
1992 };
1993 encodingParameters.push(encParam);
1994 }
1995 }
1996 });
1997 if (encodingParameters.length === 0 && primarySsrc) {
1998 encodingParameters.push({
1999 ssrc: primarySsrc
2000 });
2001 }
2002
2003 // we support both b=AS and b=TIAS but interpret AS as TIAS.
2004 var bandwidth = SDPUtils.matchPrefix(mediaSection, 'b=');
2005 if (bandwidth.length) {
2006 if (bandwidth[0].indexOf('b=TIAS:') === 0) {
2007 bandwidth = parseInt(bandwidth[0].substr(7), 10);
2008 } else if (bandwidth[0].indexOf('b=AS:') === 0) {
2009 // use formula from JSEP to convert b=AS to TIAS value.
2010 bandwidth = parseInt(bandwidth[0].substr(5), 10) * 1000 * 0.95
2011 - (50 * 40 * 8);
2012 } else {
2013 bandwidth = undefined;
2014 }
2015 encodingParameters.forEach(function(params) {
2016 params.maxBitrate = bandwidth;
2017 });
2018 }
2019 return encodingParameters;
2020 };
2021
2022 // parses http://draft.ortc.org/#rtcrtcpparameters*
2023 SDPUtils.parseRtcpParameters = function(mediaSection) {
2024 var rtcpParameters = {};
2025
2026 var cname;
2027 // Gets the first SSRC. Note that with RTX there might be multiple
2028 // SSRCs.
2029 var remoteSsrc = SDPUtils.matchPrefix(mediaSection, 'a=ssrc:')
2030 .map(function(line) {
2031 return SDPUtils.parseSsrcMedia(line);
2032 })
2033 .filter(function(obj) {
2034 return obj.attribute === 'cname';
2035 })[0];
2036 if (remoteSsrc) {
2037 rtcpParameters.cname = remoteSsrc.value;
2038 rtcpParameters.ssrc = remoteSsrc.ssrc;
2039 }
2040
2041 // Edge uses the compound attribute instead of reducedSize
2042 // compound is !reducedSize
2043 var rsize = SDPUtils.matchPrefix(mediaSection, 'a=rtcp-rsize');
2044 rtcpParameters.reducedSize = rsize.length > 0;
2045 rtcpParameters.compound = rsize.length === 0;
2046
2047 // parses the rtcp-mux attrіbute.
2048 // Note that Edge does not support unmuxed RTCP.
2049 var mux = SDPUtils.matchPrefix(mediaSection, 'a=rtcp-mux');
2050 rtcpParameters.mux = mux.length > 0;
2051
2052 return rtcpParameters;
2053 };
2054
2055 // parses either a=msid: or a=ssrc:... msid lines and returns
2056 // the id of the MediaStream and MediaStreamTrack.
2057 SDPUtils.parseMsid = function(mediaSection) {
2058 var parts;
2059 var spec = SDPUtils.matchPrefix(mediaSection, 'a=msid:');
2060 if (spec.length === 1) {
2061 parts = spec[0].substr(7).split(' ');
2062 return {stream: parts[0], track: parts[1]};
2063 }
2064 var planB = SDPUtils.matchPrefix(mediaSection, 'a=ssrc:')
2065 .map(function(line) {
2066 return SDPUtils.parseSsrcMedia(line);
2067 })
2068 .filter(function(parts) {
2069 return parts.attribute === 'msid';
2070 });
2071 if (planB.length > 0) {
2072 parts = planB[0].value.split(' ');
2073 return {stream: parts[0], track: parts[1]};
2074 }
2075 };
2076
2077 // Generate a session ID for SDP.
2078 // https://tools.ietf.org/html/draft-ietf-rtcweb-jsep-20#section-5.2.1
2079 // recommends using a cryptographically random +ve 64-bit value
2080 // but right now this should be acceptable and within the right range
2081 SDPUtils.generateSessionId = function() {
2082 return Math.random().toString().substr(2, 21);
2083 };
2084
2085 // Write boilder plate for start of SDP
2086 // sessId argument is optional - if not supplied it will
2087 // be generated randomly
2088 // sessVersion is optional and defaults to 2
2089 SDPUtils.writeSessionBoilerplate = function(sessId, sessVer) {
2090 var sessionId;
2091 var version = sessVer !== undefined ? sessVer : 2;
2092 if (sessId) {
2093 sessionId = sessId;
2094 } else {
2095 sessionId = SDPUtils.generateSessionId();
2096 }
2097 // FIXME: sess-id should be an NTP timestamp.
2098 return 'v=0\r\n' +
2099 'o=thisisadapterortc ' + sessionId + ' ' + version + ' IN IP4 127.0.0.1\r\n' +
2100 's=-\r\n' +
2101 't=0 0\r\n';
2102 };
2103
2104 SDPUtils.writeMediaSection = function(transceiver, caps, type, stream) {
2105 var sdp = SDPUtils.writeRtpDescription(transceiver.kind, caps);
2106
2107 // Map ICE parameters (ufrag, pwd) to SDP.
2108 sdp += SDPUtils.writeIceParameters(
2109 transceiver.iceGatherer.getLocalParameters());
2110
2111 // Map DTLS parameters to SDP.
2112 sdp += SDPUtils.writeDtlsParameters(
2113 transceiver.dtlsTransport.getLocalParameters(),
2114 type === 'offer' ? 'actpass' : 'active');
2115
2116 sdp += 'a=mid:' + transceiver.mid + '\r\n';
2117
2118 if (transceiver.direction) {
2119 sdp += 'a=' + transceiver.direction + '\r\n';
2120 } else if (transceiver.rtpSender && transceiver.rtpReceiver) {
2121 sdp += 'a=sendrecv\r\n';
2122 } else if (transceiver.rtpSender) {
2123 sdp += 'a=sendonly\r\n';
2124 } else if (transceiver.rtpReceiver) {
2125 sdp += 'a=recvonly\r\n';
2126 } else {
2127 sdp += 'a=inactive\r\n';
2128 }
2129
2130 if (transceiver.rtpSender) {
2131 // spec.
2132 var msid = 'msid:' + stream.id + ' ' +
2133 transceiver.rtpSender.track.id + '\r\n';
2134 sdp += 'a=' + msid;
2135
2136 // for Chrome.
2137 sdp += 'a=ssrc:' + transceiver.sendEncodingParameters[0].ssrc +
2138 ' ' + msid;
2139 if (transceiver.sendEncodingParameters[0].rtx) {
2140 sdp += 'a=ssrc:' + transceiver.sendEncodingParameters[0].rtx.ssrc +
2141 ' ' + msid;
2142 sdp += 'a=ssrc-group:FID ' +
2143 transceiver.sendEncodingParameters[0].ssrc + ' ' +
2144 transceiver.sendEncodingParameters[0].rtx.ssrc +
2145 '\r\n';
2146 }
2147 }
2148 // FIXME: this should be written by writeRtpDescription.
2149 sdp += 'a=ssrc:' + transceiver.sendEncodingParameters[0].ssrc +
2150 ' cname:' + SDPUtils.localCName + '\r\n';
2151 if (transceiver.rtpSender && transceiver.sendEncodingParameters[0].rtx) {
2152 sdp += 'a=ssrc:' + transceiver.sendEncodingParameters[0].rtx.ssrc +
2153 ' cname:' + SDPUtils.localCName + '\r\n';
2154 }
2155 return sdp;
2156 };
2157
2158 // Gets the direction from the mediaSection or the sessionpart.
2159 SDPUtils.getDirection = function(mediaSection, sessionpart) {
2160 // Look for sendrecv, sendonly, recvonly, inactive, default to sendrecv.
2161 var lines = SDPUtils.splitLines(mediaSection);
2162 for (var i = 0; i < lines.length; i++) {
2163 switch (lines[i]) {
2164 case 'a=sendrecv':
2165 case 'a=sendonly':
2166 case 'a=recvonly':
2167 case 'a=inactive':
2168 return lines[i].substr(2);
2169 default:
2170 // FIXME: What should happen here?
2171 }
2172 }
2173 if (sessionpart) {
2174 return SDPUtils.getDirection(sessionpart);
2175 }
2176 return 'sendrecv';
2177 };
2178
2179 SDPUtils.getKind = function(mediaSection) {
2180 var lines = SDPUtils.splitLines(mediaSection);
2181 var mline = lines[0].split(' ');
2182 return mline[0].substr(2);
2183 };
2184
2185 SDPUtils.isRejected = function(mediaSection) {
2186 return mediaSection.split(' ', 2)[1] === '0';
2187 };
2188
2189 SDPUtils.parseMLine = function(mediaSection) {
2190 var lines = SDPUtils.splitLines(mediaSection);
2191 var mline = lines[0].split(' ');
2192 return {
2193 kind: mline[0].substr(2),
2194 port: parseInt(mline[1], 10),
2195 protocol: mline[2],
2196 fmt: mline.slice(3).join(' ')
2197 };
2198 };
2199
2200 // Expose public methods.
2201 if (typeof module === 'object') {
2202 module.exports = SDPUtils;
2203 }
2204
2205 },{}],3:[function(require,module,exports){
2206 (function (global){
2207 /*
2208 * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
2209 *
2210 * Use of this source code is governed by a BSD-style license
2211 * that can be found in the LICENSE file in the root of the source
2212 * tree.
2213 */
2214 /* eslint-env node */
2215
2216 'use strict';
2217
2218 var adapterFactory = require('./adapter_factory.js');
2219 module.exports = adapterFactory({window: global.window});
2220
2221 }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
2222 },{"./adapter_factory.js":4}],4:[function(require,module,exports){
2223 /*
2224 * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
2225 *
2226 * Use of this source code is governed by a BSD-style license
2227 * that can be found in the LICENSE file in the root of the source
2228 * tree.
2229 */
2230 /* eslint-env node */
2231
2232 'use strict';
2233
2234 var utils = require('./utils');
2235 // Shimming starts here.
2236 module.exports = function(dependencies, opts) {
2237 var window = dependencies && dependencies.window;
2238
2239 var options = {
2240 shimChrome: true,
2241 shimFirefox: true,
2242 shimEdge: true,
2243 shimSafari: true,
2244 };
2245
2246 for (var key in opts) {
2247 if (hasOwnProperty.call(opts, key)) {
2248 options[key] = opts[key];
2249 }
2250 }
2251
2252 // Utils.
2253 var logging = utils.log;
2254 var browserDetails = utils.detectBrowser(window);
2255
2256 // Export to the adapter global object visible in the browser.
2257 var adapter = {
2258 browserDetails: browserDetails,
2259 extractVersion: utils.extractVersion,
2260 disableLog: utils.disableLog,
2261 disableWarnings: utils.disableWarnings
2262 };
2263
2264 // Uncomment the line below if you want logging to occur, including logging
2265 // for the switch statement below. Can also be turned on in the browser via
2266 // adapter.disableLog(false), but then logging from the switch statement below
2267 // will not appear.
2268 // require('./utils').disableLog(false);
2269
2270 // Browser shims.
2271 var chromeShim = require('./chrome/chrome_shim') || null;
2272 var edgeShim = require('./edge/edge_shim') || null;
2273 var firefoxShim = require('./firefox/firefox_shim') || null;
2274 var safariShim = require('./safari/safari_shim') || null;
2275 var commonShim = require('./common_shim') || null;
2276
2277 // Shim browser if found.
2278 switch (browserDetails.browser) {
2279 case 'chrome':
2280 if (!chromeShim || !chromeShim.shimPeerConnection ||
2281 !options.shimChrome) {
2282 logging('Chrome shim is not included in this adapter release.');
2283 return adapter;
2284 }
2285 logging('adapter.js shimming chrome.');
2286 // Export to the adapter global object visible in the browser.
2287 adapter.browserShim = chromeShim;
2288 commonShim.shimCreateObjectURL(window);
2289
2290 chromeShim.shimGetUserMedia(window);
2291 chromeShim.shimMediaStream(window);
2292 chromeShim.shimSourceObject(window);
2293 chromeShim.shimPeerConnection(window);
2294 chromeShim.shimOnTrack(window);
2295 chromeShim.shimAddTrackRemoveTrack(window);
2296 chromeShim.shimGetSendersWithDtmf(window);
2297
2298 commonShim.shimRTCIceCandidate(window);
2299 break;
2300 case 'firefox':
2301 if (!firefoxShim || !firefoxShim.shimPeerConnection ||
2302 !options.shimFirefox) {
2303 logging('Firefox shim is not included in this adapter release.');
2304 return adapter;
2305 }
2306 logging('adapter.js shimming firefox.');
2307 // Export to the adapter global object visible in the browser.
2308 adapter.browserShim = firefoxShim;
2309 commonShim.shimCreateObjectURL(window);
2310
2311 firefoxShim.shimGetUserMedia(window);
2312 firefoxShim.shimSourceObject(window);
2313 firefoxShim.shimPeerConnection(window);
2314 firefoxShim.shimOnTrack(window);
2315
2316 commonShim.shimRTCIceCandidate(window);
2317 break;
2318 case 'edge':
2319 if (!edgeShim || !edgeShim.shimPeerConnection || !options.shimEdge) {
2320 logging('MS edge shim is not included in this adapter release.');
2321 return adapter;
2322 }
2323 logging('adapter.js shimming edge.');
2324 // Export to the adapter global object visible in the browser.
2325 adapter.browserShim = edgeShim;
2326 commonShim.shimCreateObjectURL(window);
2327
2328 edgeShim.shimGetUserMedia(window);
2329 edgeShim.shimPeerConnection(window);
2330 edgeShim.shimReplaceTrack(window);
2331
2332 // the edge shim implements the full RTCIceCandidate object.
2333 break;
2334 case 'safari':
2335 if (!safariShim || !options.shimSafari) {
2336 logging('Safari shim is not included in this adapter release.');
2337 return adapter;
2338 }
2339 logging('adapter.js shimming safari.');
2340 // Export to the adapter global object visible in the browser.
2341 adapter.browserShim = safariShim;
2342 commonShim.shimCreateObjectURL(window);
2343
2344 safariShim.shimRTCIceServerUrls(window);
2345 safariShim.shimCallbacksAPI(window);
2346 safariShim.shimLocalStreamsAPI(window);
2347 safariShim.shimRemoteStreamsAPI(window);
2348 safariShim.shimTrackEventTransceiver(window);
2349 safariShim.shimGetUserMedia(window);
2350
2351 commonShim.shimRTCIceCandidate(window);
2352 break;
2353 default:
2354 logging('Unsupported browser!');
2355 break;
2356 }
2357
2358 return adapter;
2359 };
2360
2361 },{"./chrome/chrome_shim":5,"./common_shim":7,"./edge/edge_shim":8,"./firefox/firefox_shim":10,"./safari/safari_shim":12,"./utils":13}],5:[function(require,module,exports){
2362
2363 /*
2364 * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
2365 *
2366 * Use of this source code is governed by a BSD-style license
2367 * that can be found in the LICENSE file in the root of the source
2368 * tree.
2369 */
2370 /* eslint-env node */
2371 'use strict';
2372 var utils = require('../utils.js');
2373 var logging = utils.log;
2374
2375 var chromeShim = {
2376 shimMediaStream: function(window) {
2377 window.MediaStream = window.MediaStream || window.webkitMediaStream;
2378 },
2379
2380 shimOnTrack: function(window) {
2381 if (typeof window === 'object' && window.RTCPeerConnection && !('ontrack' in
2382 window.RTCPeerConnection.prototype)) {
2383 Object.defineProperty(window.RTCPeerConnection.prototype, 'ontrack', {
2384 get: function() {
2385 return this._ontrack;
2386 },
2387 set: function(f) {
2388 if (this._ontrack) {
2389 this.removeEventListener('track', this._ontrack);
2390 }
2391 this.addEventListener('track', this._ontrack = f);
2392 }
2393 });
2394 var origSetRemoteDescription =
2395 window.RTCPeerConnection.prototype.setRemoteDescription;
2396 window.RTCPeerConnection.prototype.setRemoteDescription = function() {
2397 var pc = this;
2398 if (!pc._ontrackpoly) {
2399 pc._ontrackpoly = function(e) {
2400 // onaddstream does not fire when a track is added to an existing
2401 // stream. But stream.onaddtrack is implemented so we use that.
2402 e.stream.addEventListener('addtrack', function(te) {
2403 var receiver;
2404 if (window.RTCPeerConnection.prototype.getReceivers) {
2405 receiver = pc.getReceivers().find(function(r) {
2406 return r.track && r.track.id === te.track.id;
2407 });
2408 } else {
2409 receiver = {track: te.track};
2410 }
2411
2412 var event = new Event('track');
2413 event.track = te.track;
2414 event.receiver = receiver;
2415 event.transceiver = {receiver: receiver};
2416 event.streams = [e.stream];
2417 pc.dispatchEvent(event);
2418 });
2419 e.stream.getTracks().forEach(function(track) {
2420 var receiver;
2421 if (window.RTCPeerConnection.prototype.getReceivers) {
2422 receiver = pc.getReceivers().find(function(r) {
2423 return r.track && r.track.id === track.id;
2424 });
2425 } else {
2426 receiver = {track: track};
2427 }
2428 var event = new Event('track');
2429 event.track = track;
2430 event.receiver = receiver;
2431 event.transceiver = {receiver: receiver};
2432 event.streams = [e.stream];
2433 pc.dispatchEvent(event);
2434 });
2435 };
2436 pc.addEventListener('addstream', pc._ontrackpoly);
2437 }
2438 return origSetRemoteDescription.apply(pc, arguments);
2439 };
2440 }
2441 },
2442
2443 shimGetSendersWithDtmf: function(window) {
2444 // Overrides addTrack/removeTrack, depends on shimAddTrackRemoveTrack.
2445 if (typeof window === 'object' && window.RTCPeerConnection &&
2446 !('getSenders' in window.RTCPeerConnection.prototype) &&
2447 'createDTMFSender' in window.RTCPeerConnection.prototype) {
2448 var shimSenderWithDtmf = function(pc, track) {
2449 return {
2450 track: track,
2451 get dtmf() {
2452 if (this._dtmf === undefined) {
2453 if (track.kind === 'audio') {
2454 this._dtmf = pc.createDTMFSender(track);
2455 } else {
2456 this._dtmf = null;
2457 }
2458 }
2459 return this._dtmf;
2460 },
2461 _pc: pc
2462 };
2463 };
2464
2465 // augment addTrack when getSenders is not available.
2466 if (!window.RTCPeerConnection.prototype.getSenders) {
2467 window.RTCPeerConnection.prototype.getSenders = function() {
2468 this._senders = this._senders || [];
2469 return this._senders.slice(); // return a copy of the internal state.
2470 };
2471 var origAddTrack = window.RTCPeerConnection.prototype.addTrack;
2472 window.RTCPeerConnection.prototype.addTrack = function(track, stream) {
2473 var pc = this;
2474 var sender = origAddTrack.apply(pc, arguments);
2475 if (!sender) {
2476 sender = shimSenderWithDtmf(pc, track);
2477 pc._senders.push(sender);
2478 }
2479 return sender;
2480 };
2481
2482 var origRemoveTrack = window.RTCPeerConnection.prototype.removeTrack;
2483 window.RTCPeerConnection.prototype.removeTrack = function(sender) {
2484 var pc = this;
2485 origRemoveTrack.apply(pc, arguments);
2486 var idx = pc._senders.indexOf(sender);
2487 if (idx !== -1) {
2488 pc._senders.splice(idx, 1);
2489 }
2490 };
2491 }
2492 var origAddStream = window.RTCPeerConnection.prototype.addStream;
2493 window.RTCPeerConnection.prototype.addStream = function(stream) {
2494 var pc = this;
2495 pc._senders = pc._senders || [];
2496 origAddStream.apply(pc, [stream]);
2497 stream.getTracks().forEach(function(track) {
2498 pc._senders.push(shimSenderWithDtmf(pc, track));
2499 });
2500 };
2501
2502 var origRemoveStream = window.RTCPeerConnection.prototype.removeStream;
2503 window.RTCPeerConnection.prototype.removeStream = function(stream) {
2504 var pc = this;
2505 pc._senders = pc._senders || [];
2506 origRemoveStream.apply(pc, [(pc._streams[stream.id] || stream)]);
2507
2508 stream.getTracks().forEach(function(track) {
2509 var sender = pc._senders.find(function(s) {
2510 return s.track === track;
2511 });
2512 if (sender) {
2513 pc._senders.splice(pc._senders.indexOf(sender), 1); // remove sender
2514 }
2515 });
2516 };
2517 } else if (typeof window === 'object' && window.RTCPeerConnection &&
2518 'getSenders' in window.RTCPeerConnection.prototype &&
2519 'createDTMFSender' in window.RTCPeerConnection.prototype &&
2520 window.RTCRtpSender &&
2521 !('dtmf' in window.RTCRtpSender.prototype)) {
2522 var origGetSenders = window.RTCPeerConnection.prototype.getSenders;
2523 window.RTCPeerConnection.prototype.getSenders = function() {
2524 var pc = this;
2525 var senders = origGetSenders.apply(pc, []);
2526 senders.forEach(function(sender) {
2527 sender._pc = pc;
2528 });
2529 return senders;
2530 };
2531
2532 Object.defineProperty(window.RTCRtpSender.prototype, 'dtmf', {
2533 get: function() {
2534 if (this._dtmf === undefined) {
2535 if (this.track.kind === 'audio') {
2536 this._dtmf = this._pc.createDTMFSender(this.track);
2537 } else {
2538 this._dtmf = null;
2539 }
2540 }
2541 return this._dtmf;
2542 }
2543 });
2544 }
2545 },
2546
2547 shimSourceObject: function(window) {
2548 var URL = window && window.URL;
2549
2550 if (typeof window === 'object') {
2551 if (window.HTMLMediaElement &&
2552 !('srcObject' in window.HTMLMediaElement.prototype)) {
2553 // Shim the srcObject property, once, when HTMLMediaElement is found.
2554 Object.defineProperty(window.HTMLMediaElement.prototype, 'srcObject', {
2555 get: function() {
2556 return this._srcObject;
2557 },
2558 set: function(stream) {
2559 var self = this;
2560 // Use _srcObject as a private property for this shim
2561 this._srcObject = stream;
2562 if (this.src) {
2563 URL.revokeObjectURL(this.src);
2564 }
2565
2566 if (!stream) {
2567 this.src = '';
2568 return undefined;
2569 }
2570 this.src = URL.createObjectURL(stream);
2571 // We need to recreate the blob url when a track is added or
2572 // removed. Doing it manually since we want to avoid a recursion.
2573 stream.addEventListener('addtrack', function() {
2574 if (self.src) {
2575 URL.revokeObjectURL(self.src);
2576 }
2577 self.src = URL.createObjectURL(stream);
2578 });
2579 stream.addEventListener('removetrack', function() {
2580 if (self.src) {
2581 URL.revokeObjectURL(self.src);
2582 }
2583 self.src = URL.createObjectURL(stream);
2584 });
2585 }
2586 });
2587 }
2588 }
2589 },
2590
2591 shimAddTrackRemoveTrack: function(window) {
2592 var browserDetails = utils.detectBrowser(window);
2593 // shim addTrack and removeTrack.
2594 if (window.RTCPeerConnection.prototype.addTrack &&
2595 browserDetails.version >= 62) {
2596 return;
2597 }
2598
2599 // also shim pc.getLocalStreams when addTrack is shimmed
2600 // to return the original streams.
2601 var origGetLocalStreams = window.RTCPeerConnection.prototype
2602 .getLocalStreams;
2603 window.RTCPeerConnection.prototype.getLocalStreams = function() {
2604 var self = this;
2605 var nativeStreams = origGetLocalStreams.apply(this);
2606 self._reverseStreams = self._reverseStreams || {};
2607 return nativeStreams.map(function(stream) {
2608 return self._reverseStreams[stream.id];
2609 });
2610 };
2611
2612 var origAddStream = window.RTCPeerConnection.prototype.addStream;
2613 window.RTCPeerConnection.prototype.addStream = function(stream) {
2614 var pc = this;
2615 pc._streams = pc._streams || {};
2616 pc._reverseStreams = pc._reverseStreams || {};
2617
2618 stream.getTracks().forEach(function(track) {
2619 var alreadyExists = pc.getSenders().find(function(s) {
2620 return s.track === track;
2621 });
2622 if (alreadyExists) {
2623 throw new DOMException('Track already exists.',
2624 'InvalidAccessError');
2625 }
2626 });
2627 // Add identity mapping for consistency with addTrack.
2628 // Unless this is being used with a stream from addTrack.
2629 if (!pc._reverseStreams[stream.id]) {
2630 var newStream = new window.MediaStream(stream.getTracks());
2631 pc._streams[stream.id] = newStream;
2632 pc._reverseStreams[newStream.id] = stream;
2633 stream = newStream;
2634 }
2635 origAddStream.apply(pc, [stream]);
2636 };
2637
2638 var origRemoveStream = window.RTCPeerConnection.prototype.removeStream;
2639 window.RTCPeerConnection.prototype.removeStream = function(stream) {
2640 var pc = this;
2641 pc._streams = pc._streams || {};
2642 pc._reverseStreams = pc._reverseStreams || {};
2643
2644 origRemoveStream.apply(pc, [(pc._streams[stream.id] || stream)]);
2645 delete pc._reverseStreams[(pc._streams[stream.id] ?
2646 pc._streams[stream.id].id : stream.id)];
2647 delete pc._streams[stream.id];
2648 };
2649
2650 window.RTCPeerConnection.prototype.addTrack = function(track, stream) {
2651 var pc = this;
2652 if (pc.signalingState === 'closed') {
2653 throw new DOMException(
2654 'The RTCPeerConnection\'s signalingState is \'closed\'.',
2655 'InvalidStateError');
2656 }
2657 var streams = [].slice.call(arguments, 1);
2658 if (streams.length !== 1 ||
2659 !streams[0].getTracks().find(function(t) {
2660 return t === track;
2661 })) {
2662 // this is not fully correct but all we can manage without
2663 // [[associated MediaStreams]] internal slot.
2664 throw new DOMException(
2665 'The adapter.js addTrack polyfill only supports a single ' +
2666 ' stream which is associated with the specified track.',
2667 'NotSupportedError');
2668 }
2669
2670 var alreadyExists = pc.getSenders().find(function(s) {
2671 return s.track === track;
2672 });
2673 if (alreadyExists) {
2674 throw new DOMException('Track already exists.',
2675 'InvalidAccessError');
2676 }
2677
2678 pc._streams = pc._streams || {};
2679 pc._reverseStreams = pc._reverseStreams || {};
2680 var oldStream = pc._streams[stream.id];
2681 if (oldStream) {
2682 // this is using odd Chrome behaviour, use with caution:
2683 // https://bugs.chromium.org/p/webrtc/issues/detail?id=7815
2684 // Note: we rely on the high-level addTrack/dtmf shim to
2685 // create the sender with a dtmf sender.
2686 oldStream.addTrack(track);
2687
2688 // Trigger ONN async.
2689 Promise.resolve().then(function() {
2690 pc.dispatchEvent(new Event('negotiationneeded'));
2691 });
2692 } else {
2693 var newStream = new window.MediaStream([track]);
2694 pc._streams[stream.id] = newStream;
2695 pc._reverseStreams[newStream.id] = stream;
2696 pc.addStream(newStream);
2697 }
2698 return pc.getSenders().find(function(s) {
2699 return s.track === track;
2700 });
2701 };
2702
2703 // replace the internal stream id with the external one and
2704 // vice versa.
2705 function replaceInternalStreamId(pc, description) {
2706 var sdp = description.sdp;
2707 Object.keys(pc._reverseStreams || []).forEach(function(internalId) {
2708 var externalStream = pc._reverseStreams[internalId];
2709 var internalStream = pc._streams[externalStream.id];
2710 sdp = sdp.replace(new RegExp(internalStream.id, 'g'),
2711 externalStream.id);
2712 });
2713 return new RTCSessionDescription({
2714 type: description.type,
2715 sdp: sdp
2716 });
2717 }
2718 function replaceExternalStreamId(pc, description) {
2719 var sdp = description.sdp;
2720 Object.keys(pc._reverseStreams || []).forEach(function(internalId) {
2721 var externalStream = pc._reverseStreams[internalId];
2722 var internalStream = pc._streams[externalStream.id];
2723 sdp = sdp.replace(new RegExp(externalStream.id, 'g'),
2724 internalStream.id);
2725 });
2726 return new RTCSessionDescription({
2727 type: description.type,
2728 sdp: sdp
2729 });
2730 }
2731 ['createOffer', 'createAnswer'].forEach(function(method) {
2732 var nativeMethod = window.RTCPeerConnection.prototype[method];
2733 window.RTCPeerConnection.prototype[method] = function() {
2734 var pc = this;
2735 var args = arguments;
2736 var isLegacyCall = arguments.length &&
2737 typeof arguments[0] === 'function';
2738 if (isLegacyCall) {
2739 return nativeMethod.apply(pc, [
2740 function(description) {
2741 var desc = replaceInternalStreamId(pc, description);
2742 args[0].apply(null, [desc]);
2743 },
2744 function(err) {
2745 if (args[1]) {
2746 args[1].apply(null, err);
2747 }
2748 }, arguments[2]
2749 ]);
2750 }
2751 return nativeMethod.apply(pc, arguments)
2752 .then(function(description) {
2753 return replaceInternalStreamId(pc, description);
2754 });
2755 };
2756 });
2757
2758 var origSetLocalDescription =
2759 window.RTCPeerConnection.prototype.setLocalDescription;
2760 window.RTCPeerConnection.prototype.setLocalDescription = function() {
2761 var pc = this;
2762 if (!arguments.length || !arguments[0].type) {
2763 return origSetLocalDescription.apply(pc, arguments);
2764 }
2765 arguments[0] = replaceExternalStreamId(pc, arguments[0]);
2766 return origSetLocalDescription.apply(pc, arguments);
2767 };
2768
2769 // TODO: mangle getStats: https://w3c.github.io/webrtc-stats/#dom-rtcmediastreamstats-streamidentifier
2770
2771 var origLocalDescription = Object.getOwnPropertyDescriptor(
2772 window.RTCPeerConnection.prototype, 'localDescription');
2773 Object.defineProperty(window.RTCPeerConnection.prototype,
2774 'localDescription', {
2775 get: function() {
2776 var pc = this;
2777 var description = origLocalDescription.get.apply(this);
2778 if (description.type === '') {
2779 return description;
2780 }
2781 return replaceInternalStreamId(pc, description);
2782 }
2783 });
2784
2785 window.RTCPeerConnection.prototype.removeTrack = function(sender) {
2786 var pc = this;
2787 if (pc.signalingState === 'closed') {
2788 throw new DOMException(
2789 'The RTCPeerConnection\'s signalingState is \'closed\'.',
2790 'InvalidStateError');
2791 }
2792 // We can not yet check for sender instanceof RTCRtpSender
2793 // since we shim RTPSender. So we check if sender._pc is set.
2794 if (!sender._pc) {
2795 throw new DOMException('Argument 1 of RTCPeerConnection.removeTrack ' +
2796 'does not implement interface RTCRtpSender.', 'TypeError');
2797 }
2798 var isLocal = sender._pc === pc;
2799 if (!isLocal) {
2800 throw new DOMException('Sender was not created by this connection.',
2801 'InvalidAccessError');
2802 }
2803
2804 // Search for the native stream the senders track belongs to.
2805 pc._streams = pc._streams || {};
2806 var stream;
2807 Object.keys(pc._streams).forEach(function(streamid) {
2808 var hasTrack = pc._streams[streamid].getTracks().find(function(track) {
2809 return sender.track === track;
2810 });
2811 if (hasTrack) {
2812 stream = pc._streams[streamid];
2813 }
2814 });
2815
2816 if (stream) {
2817 if (stream.getTracks().length === 1) {
2818 // if this is the last track of the stream, remove the stream. This
2819 // takes care of any shimmed _senders.
2820 pc.removeStream(stream);
2821 } else {
2822 // relying on the same odd chrome behaviour as above.
2823 stream.removeTrack(sender.track);
2824 }
2825 pc.dispatchEvent(new Event('negotiationneeded'));
2826 }
2827 };
2828 },
2829
2830 shimPeerConnection: function(window) {
2831 var browserDetails = utils.detectBrowser(window);
2832
2833 // The RTCPeerConnection object.
2834 if (!window.RTCPeerConnection) {
2835 window.RTCPeerConnection = function(pcConfig, pcConstraints) {
2836 // Translate iceTransportPolicy to iceTransports,
2837 // see https://code.google.com/p/webrtc/issues/detail?id=4869
2838 // this was fixed in M56 along with unprefixing RTCPeerConnection.
2839 logging('PeerConnection');
2840 if (pcConfig && pcConfig.iceTransportPolicy) {
2841 pcConfig.iceTransports = pcConfig.iceTransportPolicy;
2842 }
2843
2844 return new window.webkitRTCPeerConnection(pcConfig, pcConstraints);
2845 };
2846 window.RTCPeerConnection.prototype =
2847 window.webkitRTCPeerConnection.prototype;
2848 // wrap static methods. Currently just generateCertificate.
2849 if (window.webkitRTCPeerConnection.generateCertificate) {
2850 Object.defineProperty(window.RTCPeerConnection, 'generateCertificate', {
2851 get: function() {
2852 return window.webkitRTCPeerConnection.generateCertificate;
2853 }
2854 });
2855 }
2856 } else {
2857 // migrate from non-spec RTCIceServer.url to RTCIceServer.urls
2858 var OrigPeerConnection = window.RTCPeerConnection;
2859 window.RTCPeerConnection = function(pcConfig, pcConstraints) {
2860 if (pcConfig && pcConfig.iceServers) {
2861 var newIceServers = [];
2862 for (var i = 0; i < pcConfig.iceServers.length; i++) {
2863 var server = pcConfig.iceServers[i];
2864 if (!server.hasOwnProperty('urls') &&
2865 server.hasOwnProperty('url')) {
2866 utils.deprecated('RTCIceServer.url', 'RTCIceServer.urls');
2867 server = JSON.parse(JSON.stringify(server));
2868 server.urls = server.url;
2869 newIceServers.push(server);
2870 } else {
2871 newIceServers.push(pcConfig.iceServers[i]);
2872 }
2873 }
2874 pcConfig.iceServers = newIceServers;
2875 }
2876 return new OrigPeerConnection(pcConfig, pcConstraints);
2877 };
2878 window.RTCPeerConnection.prototype = OrigPeerConnection.prototype;
2879 // wrap static methods. Currently just generateCertificate.
2880 Object.defineProperty(window.RTCPeerConnection, 'generateCertificate', {
2881 get: function() {
2882 return OrigPeerConnection.generateCertificate;
2883 }
2884 });
2885 }
2886
2887 var origGetStats = window.RTCPeerConnection.prototype.getStats;
2888 window.RTCPeerConnection.prototype.getStats = function(selector,
2889 successCallback, errorCallback) {
2890 var self = this;
2891 var args = arguments;
2892
2893 // If selector is a function then we are in the old style stats so just
2894 // pass back the original getStats format to avoid breaking old users.
2895 if (arguments.length > 0 && typeof selector === 'function') {
2896 return origGetStats.apply(this, arguments);
2897 }
2898
2899 // When spec-style getStats is supported, return those when called with
2900 // either no arguments or the selector argument is null.
2901 if (origGetStats.length === 0 && (arguments.length === 0 ||
2902 typeof arguments[0] !== 'function')) {
2903 return origGetStats.apply(this, []);
2904 }
2905
2906 var fixChromeStats_ = function(response) {
2907 var standardReport = {};
2908 var reports = response.result();
2909 reports.forEach(function(report) {
2910 var standardStats = {
2911 id: report.id,
2912 timestamp: report.timestamp,
2913 type: {
2914 localcandidate: 'local-candidate',
2915 remotecandidate: 'remote-candidate'
2916 }[report.type] || report.type
2917 };
2918 report.names().forEach(function(name) {
2919 standardStats[name] = report.stat(name);
2920 });
2921 standardReport[standardStats.id] = standardStats;
2922 });
2923
2924 return standardReport;
2925 };
2926
2927 // shim getStats with maplike support
2928 var makeMapStats = function(stats) {
2929 return new Map(Object.keys(stats).map(function(key) {
2930 return [key, stats[key]];
2931 }));
2932 };
2933
2934 if (arguments.length >= 2) {
2935 var successCallbackWrapper_ = function(response) {
2936 args[1](makeMapStats(fixChromeStats_(response)));
2937 };
2938
2939 return origGetStats.apply(this, [successCallbackWrapper_,
2940 arguments[0]]);
2941 }
2942
2943 // promise-support
2944 return new Promise(function(resolve, reject) {
2945 origGetStats.apply(self, [
2946 function(response) {
2947 resolve(makeMapStats(fixChromeStats_(response)));
2948 }, reject]);
2949 }).then(successCallback, errorCallback);
2950 };
2951
2952 // add promise support -- natively available in Chrome 51
2953 if (browserDetails.version < 51) {
2954 ['setLocalDescription', 'setRemoteDescription', 'addIceCandidate']
2955 .forEach(function(method) {
2956 var nativeMethod = window.RTCPeerConnection.prototype[method];
2957 window.RTCPeerConnection.prototype[method] = function() {
2958 var args = arguments;
2959 var self = this;
2960 var promise = new Promise(function(resolve, reject) {
2961 nativeMethod.apply(self, [args[0], resolve, reject]);
2962 });
2963 if (args.length < 2) {
2964 return promise;
2965 }
2966 return promise.then(function() {
2967 args[1].apply(null, []);
2968 },
2969 function(err) {
2970 if (args.length >= 3) {
2971 args[2].apply(null, [err]);
2972 }
2973 });
2974 };
2975 });
2976 }
2977
2978 // promise support for createOffer and createAnswer. Available (without
2979 // bugs) since M52: crbug/619289
2980 if (browserDetails.version < 52) {
2981 ['createOffer', 'createAnswer'].forEach(function(method) {
2982 var nativeMethod = window.RTCPeerConnection.prototype[method];
2983 window.RTCPeerConnection.prototype[method] = function() {
2984 var self = this;
2985 if (arguments.length < 1 || (arguments.length === 1 &&
2986 typeof arguments[0] === 'object')) {
2987 var opts = arguments.length === 1 ? arguments[0] : undefined;
2988 return new Promise(function(resolve, reject) {
2989 nativeMethod.apply(self, [resolve, reject, opts]);
2990 });
2991 }
2992 return nativeMethod.apply(this, arguments);
2993 };
2994 });
2995 }
2996
2997 // shim implicit creation of RTCSessionDescription/RTCIceCandidate
2998 ['setLocalDescription', 'setRemoteDescription', 'addIceCandidate']
2999 .forEach(function(method) {
3000 var nativeMethod = window.RTCPeerConnection.prototype[method];
3001 window.RTCPeerConnection.prototype[method] = function() {
3002 arguments[0] = new ((method === 'addIceCandidate') ?
3003 window.RTCIceCandidate :
3004 window.RTCSessionDescription)(arguments[0]);
3005 return nativeMethod.apply(this, arguments);
3006 };
3007 });
3008
3009 // support for addIceCandidate(null or undefined)
3010 var nativeAddIceCandidate =
3011 window.RTCPeerConnection.prototype.addIceCandidate;
3012 window.RTCPeerConnection.prototype.addIceCandidate = function() {
3013 if (!arguments[0]) {
3014 if (arguments[1]) {
3015 arguments[1].apply(null);
3016 }
3017 return Promise.resolve();
3018 }
3019 return nativeAddIceCandidate.apply(this, arguments);
3020 };
3021 }
3022 };
3023
3024
3025 // Expose public methods.
3026 module.exports = {
3027 shimMediaStream: chromeShim.shimMediaStream,
3028 shimOnTrack: chromeShim.shimOnTrack,
3029 shimAddTrackRemoveTrack: chromeShim.shimAddTrackRemoveTrack,
3030 shimGetSendersWithDtmf: chromeShim.shimGetSendersWithDtmf,
3031 shimSourceObject: chromeShim.shimSourceObject,
3032 shimPeerConnection: chromeShim.shimPeerConnection,
3033 shimGetUserMedia: require('./getusermedia')
3034 };
3035
3036 },{"../utils.js":13,"./getusermedia":6}],6:[function(require,module,exports){
3037 /*
3038 * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
3039 *
3040 * Use of this source code is governed by a BSD-style license
3041 * that can be found in the LICENSE file in the root of the source
3042 * tree.
3043 */
3044 /* eslint-env node */
3045 'use strict';
3046 var utils = require('../utils.js');
3047 var logging = utils.log;
3048
3049 // Expose public methods.
3050 module.exports = function(window) {
3051 var browserDetails = utils.detectBrowser(window);
3052 var navigator = window && window.navigator;
3053
3054 var constraintsToChrome_ = function(c) {
3055 if (typeof c !== 'object' || c.mandatory || c.optional) {
3056 return c;
3057 }
3058 var cc = {};
3059 Object.keys(c).forEach(function(key) {
3060 if (key === 'require' || key === 'advanced' || key === 'mediaSource') {
3061 return;
3062 }
3063 var r = (typeof c[key] === 'object') ? c[key] : {ideal: c[key]};
3064 if (r.exact !== undefined && typeof r.exact === 'number') {
3065 r.min = r.max = r.exact;
3066 }
3067 var oldname_ = function(prefix, name) {
3068 if (prefix) {
3069 return prefix + name.charAt(0).toUpperCase() + name.slice(1);
3070 }
3071 return (name === 'deviceId') ? 'sourceId' : name;
3072 };
3073 if (r.ideal !== undefined) {
3074 cc.optional = cc.optional || [];
3075 var oc = {};
3076 if (typeof r.ideal === 'number') {
3077 oc[oldname_('min', key)] = r.ideal;
3078 cc.optional.push(oc);
3079 oc = {};
3080 oc[oldname_('max', key)] = r.ideal;
3081 cc.optional.push(oc);
3082 } else {
3083 oc[oldname_('', key)] = r.ideal;
3084 cc.optional.push(oc);
3085 }
3086 }
3087 if (r.exact !== undefined && typeof r.exact !== 'number') {
3088 cc.mandatory = cc.mandatory || {};
3089 cc.mandatory[oldname_('', key)] = r.exact;
3090 } else {
3091 ['min', 'max'].forEach(function(mix) {
3092 if (r[mix] !== undefined) {
3093 cc.mandatory = cc.mandatory || {};
3094 cc.mandatory[oldname_(mix, key)] = r[mix];
3095 }
3096 });
3097 }
3098 });
3099 if (c.advanced) {
3100 cc.optional = (cc.optional || []).concat(c.advanced);
3101 }
3102 return cc;
3103 };
3104
3105 var shimConstraints_ = function(constraints, func) {
3106 constraints = JSON.parse(JSON.stringify(constraints));
3107 if (constraints && typeof constraints.audio === 'object') {
3108 var remap = function(obj, a, b) {
3109 if (a in obj && !(b in obj)) {
3110 obj[b] = obj[a];
3111 delete obj[a];
3112 }
3113 };
3114 constraints = JSON.parse(JSON.stringify(constraints));
3115 remap(constraints.audio, 'autoGainControl', 'googAutoGainControl');
3116 remap(constraints.audio, 'noiseSuppression', 'googNoiseSuppression');
3117 constraints.audio = constraintsToChrome_(constraints.audio);
3118 }
3119 if (constraints && typeof constraints.video === 'object') {
3120 // Shim facingMode for mobile & surface pro.
3121 var face = constraints.video.facingMode;
3122 face = face && ((typeof face === 'object') ? face : {ideal: face});
3123 var getSupportedFacingModeLies = browserDetails.version < 61;
3124
3125 if ((face && (face.exact === 'user' || face.exact === 'environment' ||
3126 face.ideal === 'user' || face.ideal === 'environment')) &&
3127 !(navigator.mediaDevices.getSupportedConstraints &&
3128 navigator.mediaDevices.getSupportedConstraints().facingMode &&
3129 !getSupportedFacingModeLies)) {
3130 delete constraints.video.facingMode;
3131 var matches;
3132 if (face.exact === 'environment' || face.ideal === 'environment') {
3133 matches = ['back', 'rear'];
3134 } else if (face.exact === 'user' || face.ideal === 'user') {
3135 matches = ['front'];
3136 }
3137 if (matches) {
3138 // Look for matches in label, or use last cam for back (typical).
3139 return navigator.mediaDevices.enumerateDevices()
3140 .then(function(devices) {
3141 devices = devices.filter(function(d) {
3142 return d.kind === 'videoinput';
3143 });
3144 var dev = devices.find(function(d) {
3145 return matches.some(function(match) {
3146 return d.label.toLowerCase().indexOf(match) !== -1;
3147 });
3148 });
3149 if (!dev && devices.length && matches.indexOf('back') !== -1) {
3150 dev = devices[devices.length - 1]; // more likely the back cam
3151 }
3152 if (dev) {
3153 constraints.video.deviceId = face.exact ? {exact: dev.deviceId} :
3154 {ideal: dev.deviceId};
3155 }
3156 constraints.video = constraintsToChrome_(constraints.video);
3157 logging('chrome: ' + JSON.stringify(constraints));
3158 return func(constraints);
3159 });
3160 }
3161 }
3162 constraints.video = constraintsToChrome_(constraints.video);
3163 }
3164 logging('chrome: ' + JSON.stringify(constraints));
3165 return func(constraints);
3166 };
3167
3168 var shimError_ = function(e) {
3169 return {
3170 name: {
3171 PermissionDeniedError: 'NotAllowedError',
3172 InvalidStateError: 'NotReadableError',
3173 DevicesNotFoundError: 'NotFoundError',
3174 ConstraintNotSatisfiedError: 'OverconstrainedError',
3175 TrackStartError: 'NotReadableError',
3176 MediaDeviceFailedDueToShutdown: 'NotReadableError',
3177 MediaDeviceKillSwitchOn: 'NotReadableError'
3178 }[e.name] || e.name,
3179 message: e.message,
3180 constraint: e.constraintName,
3181 toString: function() {
3182 return this.name + (this.message && ': ') + this.message;
3183 }
3184 };
3185 };
3186
3187 var getUserMedia_ = function(constraints, onSuccess, onError) {
3188 shimConstraints_(constraints, function(c) {
3189 navigator.webkitGetUserMedia(c, onSuccess, function(e) {
3190 if (onError) {
3191 onError(shimError_(e));
3192 }
3193 });
3194 });
3195 };
3196
3197 navigator.getUserMedia = getUserMedia_;
3198
3199 // Returns the result of getUserMedia as a Promise.
3200 var getUserMediaPromise_ = function(constraints) {
3201 return new Promise(function(resolve, reject) {
3202 navigator.getUserMedia(constraints, resolve, reject);
3203 });
3204 };
3205
3206 if (!navigator.mediaDevices) {
3207 navigator.mediaDevices = {
3208 getUserMedia: getUserMediaPromise_,
3209 enumerateDevices: function() {
3210 return new Promise(function(resolve) {
3211 var kinds = {audio: 'audioinput', video: 'videoinput'};
3212 return window.MediaStreamTrack.getSources(function(devices) {
3213 resolve(devices.map(function(device) {
3214 return {label: device.label,
3215 kind: kinds[device.kind],
3216 deviceId: device.id,
3217 groupId: ''};
3218 }));
3219 });
3220 });
3221 },
3222 getSupportedConstraints: function() {
3223 return {
3224 deviceId: true, echoCancellation: true, facingMode: true,
3225 frameRate: true, height: true, width: true
3226 };
3227 }
3228 };
3229 }
3230
3231 // A shim for getUserMedia method on the mediaDevices object.
3232 // TODO(KaptenJansson) remove once implemented in Chrome stable.
3233 if (!navigator.mediaDevices.getUserMedia) {
3234 navigator.mediaDevices.getUserMedia = function(constraints) {
3235 return getUserMediaPromise_(constraints);
3236 };
3237 } else {
3238 // Even though Chrome 45 has navigator.mediaDevices and a getUserMedia
3239 // function which returns a Promise, it does not accept spec-style
3240 // constraints.
3241 var origGetUserMedia = navigator.mediaDevices.getUserMedia.
3242 bind(navigator.mediaDevices);
3243 navigator.mediaDevices.getUserMedia = function(cs) {
3244 return shimConstraints_(cs, function(c) {
3245 return origGetUserMedia(c).then(function(stream) {
3246 if (c.audio && !stream.getAudioTracks().length ||
3247 c.video && !stream.getVideoTracks().length) {
3248 stream.getTracks().forEach(function(track) {
3249 track.stop();
3250 });
3251 throw new DOMException('', 'NotFoundError');
3252 }
3253 return stream;
3254 }, function(e) {
3255 return Promise.reject(shimError_(e));
3256 });
3257 });
3258 };
3259 }
3260
3261 // Dummy devicechange event methods.
3262 // TODO(KaptenJansson) remove once implemented in Chrome stable.
3263 if (typeof navigator.mediaDevices.addEventListener === 'undefined') {
3264 navigator.mediaDevices.addEventListener = function() {
3265 logging('Dummy mediaDevices.addEventListener called.');
3266 };
3267 }
3268 if (typeof navigator.mediaDevices.removeEventListener === 'undefined') {
3269 navigator.mediaDevices.removeEventListener = function() {
3270 logging('Dummy mediaDevices.removeEventListener called.');
3271 };
3272 }
3273 };
3274
3275 },{"../utils.js":13}],7:[function(require,module,exports){
3276 /*
3277 * Copyright (c) 2017 The WebRTC project authors. All Rights Reserved.
3278 *
3279 * Use of this source code is governed by a BSD-style license
3280 * that can be found in the LICENSE file in the root of the source
3281 * tree.
3282 */
3283 /* eslint-env node */
3284 'use strict';
3285
3286 var SDPUtils = require('sdp');
3287 var utils = require('./utils');
3288
3289 // Wraps the peerconnection event eventNameToWrap in a function
3290 // which returns the modified event object.
3291 function wrapPeerConnectionEvent(window, eventNameToWrap, wrapper) {
3292 if (!window.RTCPeerConnection) {
3293 return;
3294 }
3295 var proto = window.RTCPeerConnection.prototype;
3296 var nativeAddEventListener = proto.addEventListener;
3297 proto.addEventListener = function(nativeEventName, cb) {
3298 if (nativeEventName !== eventNameToWrap) {
3299 return nativeAddEventListener.apply(this, arguments);
3300 }
3301 var wrappedCallback = function(e) {
3302 cb(wrapper(e));
3303 };
3304 this._eventMap = this._eventMap || {};
3305 this._eventMap[cb] = wrappedCallback;
3306 return nativeAddEventListener.apply(this, [nativeEventName,
3307 wrappedCallback]);
3308 };
3309
3310 var nativeRemoveEventListener = proto.removeEventListener;
3311 proto.removeEventListener = function(nativeEventName, cb) {
3312 if (nativeEventName !== eventNameToWrap || !this._eventMap
3313 || !this._eventMap[cb]) {
3314 return nativeRemoveEventListener.apply(this, arguments);
3315 }
3316 var unwrappedCb = this._eventMap[cb];
3317 delete this._eventMap[cb];
3318 return nativeRemoveEventListener.apply(this, [nativeEventName,
3319 unwrappedCb]);
3320 };
3321
3322 Object.defineProperty(proto, 'on' + eventNameToWrap, {
3323 get: function() {
3324 return this['_on' + eventNameToWrap];
3325 },
3326 set: function(cb) {
3327 if (this['_on' + eventNameToWrap]) {
3328 this.removeEventListener(eventNameToWrap,
3329 this['_on' + eventNameToWrap]);
3330 delete this['_on' + eventNameToWrap];
3331 }
3332 if (cb) {
3333 this.addEventListener(eventNameToWrap,
3334 this['_on' + eventNameToWrap] = cb);
3335 }
3336 }
3337 });
3338 }
3339
3340 module.exports = {
3341 shimRTCIceCandidate: function(window) {
3342 // foundation is arbitrarily chosen as an indicator for full support for
3343 // https://w3c.github.io/webrtc-pc/#rtcicecandidate-interface
3344 if (window.RTCIceCandidate && 'foundation' in
3345 window.RTCIceCandidate.prototype) {
3346 return;
3347 }
3348
3349 var NativeRTCIceCandidate = window.RTCIceCandidate;
3350 window.RTCIceCandidate = function(args) {
3351 // Remove the a= which shouldn't be part of the candidate string.
3352 if (typeof args === 'object' && args.candidate &&
3353 args.candidate.indexOf('a=') === 0) {
3354 args = JSON.parse(JSON.stringify(args));
3355 args.candidate = args.candidate.substr(2);
3356 }
3357
3358 // Augment the native candidate with the parsed fields.
3359 var nativeCandidate = new NativeRTCIceCandidate(args);
3360 var parsedCandidate = SDPUtils.parseCandidate(args.candidate);
3361 var augmentedCandidate = Object.assign(nativeCandidate,
3362 parsedCandidate);
3363
3364 // Add a serializer that does not serialize the extra attributes.
3365 augmentedCandidate.toJSON = function() {
3366 return {
3367 candidate: augmentedCandidate.candidate,
3368 sdpMid: augmentedCandidate.sdpMid,
3369 sdpMLineIndex: augmentedCandidate.sdpMLineIndex,
3370 usernameFragment: augmentedCandidate.usernameFragment,
3371 };
3372 };
3373 return augmentedCandidate;
3374 };
3375
3376 // Hook up the augmented candidate in onicecandidate and
3377 // addEventListener('icecandidate', ...)
3378 wrapPeerConnectionEvent(window, 'icecandidate', function(e) {
3379 if (e.candidate) {
3380 Object.defineProperty(e, 'candidate', {
3381 value: new window.RTCIceCandidate(e.candidate),
3382 writable: 'false'
3383 });
3384 }
3385 return e;
3386 });
3387 },
3388
3389 // shimCreateObjectURL must be called before shimSourceObject to avoid loop.
3390
3391 shimCreateObjectURL: function(window) {
3392 var URL = window && window.URL;
3393
3394 if (!(typeof window === 'object' && window.HTMLMediaElement &&
3395 'srcObject' in window.HTMLMediaElement.prototype &&
3396 URL.createObjectURL && URL.revokeObjectURL)) {
3397 // Only shim CreateObjectURL using srcObject if srcObject exists.
3398 return undefined;
3399 }
3400
3401 var nativeCreateObjectURL = URL.createObjectURL.bind(URL);
3402 var nativeRevokeObjectURL = URL.revokeObjectURL.bind(URL);
3403 var streams = new Map(), newId = 0;
3404
3405 URL.createObjectURL = function(stream) {
3406 if ('getTracks' in stream) {
3407 var url = 'polyblob:' + (++newId);
3408 streams.set(url, stream);
3409 utils.deprecated('URL.createObjectURL(stream)',
3410 'elem.srcObject = stream');
3411 return url;
3412 }
3413 return nativeCreateObjectURL(stream);
3414 };
3415 URL.revokeObjectURL = function(url) {
3416 nativeRevokeObjectURL(url);
3417 streams.delete(url);
3418 };
3419
3420 var dsc = Object.getOwnPropertyDescriptor(window.HTMLMediaElement.prototype,
3421 'src');
3422 Object.defineProperty(window.HTMLMediaElement.prototype, 'src', {
3423 get: function() {
3424 return dsc.get.apply(this);
3425 },
3426 set: function(url) {
3427 this.srcObject = streams.get(url) || null;
3428 return dsc.set.apply(this, [url]);
3429 }
3430 });
3431
3432 var nativeSetAttribute = window.HTMLMediaElement.prototype.setAttribute;
3433 window.HTMLMediaElement.prototype.setAttribute = function() {
3434 if (arguments.length === 2 &&
3435 ('' + arguments[0]).toLowerCase() === 'src') {
3436 this.srcObject = streams.get(arguments[1]) || null;
3437 }
3438 return nativeSetAttribute.apply(this, arguments);
3439 };
3440 }
3441 };
3442
3443 },{"./utils":13,"sdp":2}],8:[function(require,module,exports){
3444 /*
3445 * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
3446 *
3447 * Use of this source code is governed by a BSD-style license
3448 * that can be found in the LICENSE file in the root of the source
3449 * tree.
3450 */
3451 /* eslint-env node */
3452 'use strict';
3453
3454 var utils = require('../utils');
3455 var shimRTCPeerConnection = require('rtcpeerconnection-shim');
3456
3457 module.exports = {
3458 shimGetUserMedia: require('./getusermedia'),
3459 shimPeerConnection: function(window) {
3460 var browserDetails = utils.detectBrowser(window);
3461
3462 if (window.RTCIceGatherer) {
3463 // ORTC defines an RTCIceCandidate object but no constructor.
3464 // Not implemented in Edge.
3465 if (!window.RTCIceCandidate) {
3466 window.RTCIceCandidate = function(args) {
3467 return args;
3468 };
3469 }
3470 // ORTC does not have a session description object but
3471 // other browsers (i.e. Chrome) that will support both PC and ORTC
3472 // in the future might have this defined already.
3473 if (!window.RTCSessionDescription) {
3474 window.RTCSessionDescription = function(args) {
3475 return args;
3476 };
3477 }
3478 // this adds an additional event listener to MediaStrackTrack that signals
3479 // when a tracks enabled property was changed. Workaround for a bug in
3480 // addStream, see below. No longer required in 15025+
3481 if (browserDetails.version < 15025) {
3482 var origMSTEnabled = Object.getOwnPropertyDescriptor(
3483 window.MediaStreamTrack.prototype, 'enabled');
3484 Object.defineProperty(window.MediaStreamTrack.prototype, 'enabled', {
3485 set: function(value) {
3486 origMSTEnabled.set.call(this, value);
3487 var ev = new Event('enabled');
3488 ev.enabled = value;
3489 this.dispatchEvent(ev);
3490 }
3491 });
3492 }
3493 }
3494
3495 // ORTC defines the DTMF sender a bit different.
3496 // https://github.com/w3c/ortc/issues/714
3497 if (window.RTCRtpSender && !('dtmf' in window.RTCRtpSender.prototype)) {
3498 Object.defineProperty(window.RTCRtpSender.prototype, 'dtmf', {
3499 get: function() {
3500 if (this._dtmf === undefined) {
3501 if (this.track.kind === 'audio') {
3502 this._dtmf = new window.RTCDtmfSender(this);
3503 } else if (this.track.kind === 'video') {
3504 this._dtmf = null;
3505 }
3506 }
3507 return this._dtmf;
3508 }
3509 });
3510 }
3511
3512 window.RTCPeerConnection =
3513 shimRTCPeerConnection(window, browserDetails.version);
3514 },
3515 shimReplaceTrack: function(window) {
3516 // ORTC has replaceTrack -- https://github.com/w3c/ortc/issues/614
3517 if (window.RTCRtpSender &&
3518 !('replaceTrack' in window.RTCRtpSender.prototype)) {
3519 window.RTCRtpSender.prototype.replaceTrack =
3520 window.RTCRtpSender.prototype.setTrack;
3521 }
3522 }
3523 };
3524
3525 },{"../utils":13,"./getusermedia":9,"rtcpeerconnection-shim":1}],9:[function(require,module,exports){
3526 /*
3527 * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
3528 *
3529 * Use of this source code is governed by a BSD-style license
3530 * that can be found in the LICENSE file in the root of the source
3531 * tree.
3532 */
3533 /* eslint-env node */
3534 'use strict';
3535
3536 // Expose public methods.
3537 module.exports = function(window) {
3538 var navigator = window && window.navigator;
3539
3540 var shimError_ = function(e) {
3541 return {
3542 name: {PermissionDeniedError: 'NotAllowedError'}[e.name] || e.name,
3543 message: e.message,
3544 constraint: e.constraint,
3545 toString: function() {
3546 return this.name;
3547 }
3548 };
3549 };
3550
3551 // getUserMedia error shim.
3552 var origGetUserMedia = navigator.mediaDevices.getUserMedia.
3553 bind(navigator.mediaDevices);
3554 navigator.mediaDevices.getUserMedia = function(c) {
3555 return origGetUserMedia(c).catch(function(e) {
3556 return Promise.reject(shimError_(e));
3557 });
3558 };
3559 };
3560
3561 },{}],10:[function(require,module,exports){
3562 /*
3563 * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
3564 *
3565 * Use of this source code is governed by a BSD-style license
3566 * that can be found in the LICENSE file in the root of the source
3567 * tree.
3568 */
3569 /* eslint-env node */
3570 'use strict';
3571
3572 var utils = require('../utils');
3573
3574 var firefoxShim = {
3575 shimOnTrack: function(window) {
3576 if (typeof window === 'object' && window.RTCPeerConnection && !('ontrack' in
3577 window.RTCPeerConnection.prototype)) {
3578 Object.defineProperty(window.RTCPeerConnection.prototype, 'ontrack', {
3579 get: function() {
3580 return this._ontrack;
3581 },
3582 set: function(f) {
3583 if (this._ontrack) {
3584 this.removeEventListener('track', this._ontrack);
3585 this.removeEventListener('addstream', this._ontrackpoly);
3586 }
3587 this.addEventListener('track', this._ontrack = f);
3588 this.addEventListener('addstream', this._ontrackpoly = function(e) {
3589 e.stream.getTracks().forEach(function(track) {
3590 var event = new Event('track');
3591 event.track = track;
3592 event.receiver = {track: track};
3593 event.transceiver = {receiver: event.receiver};
3594 event.streams = [e.stream];
3595 this.dispatchEvent(event);
3596 }.bind(this));
3597 }.bind(this));
3598 }
3599 });
3600 }
3601 if (typeof window === 'object' && window.RTCTrackEvent &&
3602 ('receiver' in window.RTCTrackEvent.prototype) &&
3603 !('transceiver' in window.RTCTrackEvent.prototype)) {
3604 Object.defineProperty(window.RTCTrackEvent.prototype, 'transceiver', {
3605 get: function() {
3606 return {receiver: this.receiver};
3607 }
3608 });
3609 }
3610 },
3611
3612 shimSourceObject: function(window) {
3613 // Firefox has supported mozSrcObject since FF22, unprefixed in 42.
3614 if (typeof window === 'object') {
3615 if (window.HTMLMediaElement &&
3616 !('srcObject' in window.HTMLMediaElement.prototype)) {
3617 // Shim the srcObject property, once, when HTMLMediaElement is found.
3618 Object.defineProperty(window.HTMLMediaElement.prototype, 'srcObject', {
3619 get: function() {
3620 return this.mozSrcObject;
3621 },
3622 set: function(stream) {
3623 this.mozSrcObject = stream;
3624 }
3625 });
3626 }
3627 }
3628 },
3629
3630 shimPeerConnection: function(window) {
3631 var browserDetails = utils.detectBrowser(window);
3632
3633 if (typeof window !== 'object' || !(window.RTCPeerConnection ||
3634 window.mozRTCPeerConnection)) {
3635 return; // probably media.peerconnection.enabled=false in about:config
3636 }
3637 // The RTCPeerConnection object.
3638 if (!window.RTCPeerConnection) {
3639 window.RTCPeerConnection = function(pcConfig, pcConstraints) {
3640 if (browserDetails.version < 38) {
3641 // .urls is not supported in FF < 38.
3642 // create RTCIceServers with a single url.
3643 if (pcConfig && pcConfig.iceServers) {
3644 var newIceServers = [];
3645 for (var i = 0; i < pcConfig.iceServers.length; i++) {
3646 var server = pcConfig.iceServers[i];
3647 if (server.hasOwnProperty('urls')) {
3648 for (var j = 0; j < server.urls.length; j++) {
3649 var newServer = {
3650 url: server.urls[j]
3651 };
3652 if (server.urls[j].indexOf('turn') === 0) {
3653 newServer.username = server.username;
3654 newServer.credential = server.credential;
3655 }
3656 newIceServers.push(newServer);
3657 }
3658 } else {
3659 newIceServers.push(pcConfig.iceServers[i]);
3660 }
3661 }
3662 pcConfig.iceServers = newIceServers;
3663 }
3664 }
3665 return new window.mozRTCPeerConnection(pcConfig, pcConstraints);
3666 };
3667 window.RTCPeerConnection.prototype =
3668 window.mozRTCPeerConnection.prototype;
3669
3670 // wrap static methods. Currently just generateCertificate.
3671 if (window.mozRTCPeerConnection.generateCertificate) {
3672 Object.defineProperty(window.RTCPeerConnection, 'generateCertificate', {
3673 get: function() {
3674 return window.mozRTCPeerConnection.generateCertificate;
3675 }
3676 });
3677 }
3678
3679 window.RTCSessionDescription = window.mozRTCSessionDescription;
3680 window.RTCIceCandidate = window.mozRTCIceCandidate;
3681 }
3682
3683 // shim away need for obsolete RTCIceCandidate/RTCSessionDescription.
3684 ['setLocalDescription', 'setRemoteDescription', 'addIceCandidate']
3685 .forEach(function(method) {
3686 var nativeMethod = window.RTCPeerConnection.prototype[method];
3687 window.RTCPeerConnection.prototype[method] = function() {
3688 arguments[0] = new ((method === 'addIceCandidate') ?
3689 window.RTCIceCandidate :
3690 window.RTCSessionDescription)(arguments[0]);
3691 return nativeMethod.apply(this, arguments);
3692 };
3693 });
3694
3695 // support for addIceCandidate(null or undefined)
3696 var nativeAddIceCandidate =
3697 window.RTCPeerConnection.prototype.addIceCandidate;
3698 window.RTCPeerConnection.prototype.addIceCandidate = function() {
3699 if (!arguments[0]) {
3700 if (arguments[1]) {
3701 arguments[1].apply(null);
3702 }
3703 return Promise.resolve();
3704 }
3705 return nativeAddIceCandidate.apply(this, arguments);
3706 };
3707
3708 // shim getStats with maplike support
3709 var makeMapStats = function(stats) {
3710 var map = new Map();
3711 Object.keys(stats).forEach(function(key) {
3712 map.set(key, stats[key]);
3713 map[key] = stats[key];
3714 });
3715 return map;
3716 };
3717
3718 var modernStatsTypes = {
3719 inboundrtp: 'inbound-rtp',
3720 outboundrtp: 'outbound-rtp',
3721 candidatepair: 'candidate-pair',
3722 localcandidate: 'local-candidate',
3723 remotecandidate: 'remote-candidate'
3724 };
3725
3726 var nativeGetStats = window.RTCPeerConnection.prototype.getStats;
3727 window.RTCPeerConnection.prototype.getStats = function(
3728 selector,
3729 onSucc,
3730 onErr
3731 ) {
3732 return nativeGetStats.apply(this, [selector || null])
3733 .then(function(stats) {
3734 if (browserDetails.version < 48) {
3735 stats = makeMapStats(stats);
3736 }
3737 if (browserDetails.version < 53 && !onSucc) {
3738 // Shim only promise getStats with spec-hyphens in type names
3739 // Leave callback version alone; misc old uses of forEach before Map
3740 try {
3741 stats.forEach(function(stat) {
3742 stat.type = modernStatsTypes[stat.type] || stat.type;
3743 });
3744 } catch (e) {
3745 if (e.name !== 'TypeError') {
3746 throw e;
3747 }
3748 // Avoid TypeError: "type" is read-only, in old versions. 34-43ish
3749 stats.forEach(function(stat, i) {
3750 stats.set(i, Object.assign({}, stat, {
3751 type: modernStatsTypes[stat.type] || stat.type
3752 }));
3753 });
3754 }
3755 }
3756 return stats;
3757 })
3758 .then(onSucc, onErr);
3759 };
3760 }
3761 };
3762
3763 // Expose public methods.
3764 module.exports = {
3765 shimOnTrack: firefoxShim.shimOnTrack,
3766 shimSourceObject: firefoxShim.shimSourceObject,
3767 shimPeerConnection: firefoxShim.shimPeerConnection,
3768 shimGetUserMedia: require('./getusermedia')
3769 };
3770
3771 },{"../utils":13,"./getusermedia":11}],11:[function(require,module,exports){
3772 /*
3773 * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
3774 *
3775 * Use of this source code is governed by a BSD-style license
3776 * that can be found in the LICENSE file in the root of the source
3777 * tree.
3778 */
3779 /* eslint-env node */
3780 'use strict';
3781
3782 var utils = require('../utils');
3783 var logging = utils.log;
3784
3785 // Expose public methods.
3786 module.exports = function(window) {
3787 var browserDetails = utils.detectBrowser(window);
3788 var navigator = window && window.navigator;
3789 var MediaStreamTrack = window && window.MediaStreamTrack;
3790
3791 var shimError_ = function(e) {
3792 return {
3793 name: {
3794 InternalError: 'NotReadableError',
3795 NotSupportedError: 'TypeError',
3796 PermissionDeniedError: 'NotAllowedError',
3797 SecurityError: 'NotAllowedError'
3798 }[e.name] || e.name,
3799 message: {
3800 'The operation is insecure.': 'The request is not allowed by the ' +
3801 'user agent or the platform in the current context.'
3802 }[e.message] || e.message,
3803 constraint: e.constraint,
3804 toString: function() {
3805 return this.name + (this.message && ': ') + this.message;
3806 }
3807 };
3808 };
3809
3810 // getUserMedia constraints shim.
3811 var getUserMedia_ = function(constraints, onSuccess, onError) {
3812 var constraintsToFF37_ = function(c) {
3813 if (typeof c !== 'object' || c.require) {
3814 return c;
3815 }
3816 var require = [];
3817 Object.keys(c).forEach(function(key) {
3818 if (key === 'require' || key === 'advanced' || key === 'mediaSource') {
3819 return;
3820 }
3821 var r = c[key] = (typeof c[key] === 'object') ?
3822 c[key] : {ideal: c[key]};
3823 if (r.min !== undefined ||
3824 r.max !== undefined || r.exact !== undefined) {
3825 require.push(key);
3826 }
3827 if (r.exact !== undefined) {
3828 if (typeof r.exact === 'number') {
3829 r. min = r.max = r.exact;
3830 } else {
3831 c[key] = r.exact;
3832 }
3833 delete r.exact;
3834 }
3835 if (r.ideal !== undefined) {
3836 c.advanced = c.advanced || [];
3837 var oc = {};
3838 if (typeof r.ideal === 'number') {
3839 oc[key] = {min: r.ideal, max: r.ideal};
3840 } else {
3841 oc[key] = r.ideal;
3842 }
3843 c.advanced.push(oc);
3844 delete r.ideal;
3845 if (!Object.keys(r).length) {
3846 delete c[key];
3847 }
3848 }
3849 });
3850 if (require.length) {
3851 c.require = require;
3852 }
3853 return c;
3854 };
3855 constraints = JSON.parse(JSON.stringify(constraints));
3856 if (browserDetails.version < 38) {
3857 logging('spec: ' + JSON.stringify(constraints));
3858 if (constraints.audio) {
3859 constraints.audio = constraintsToFF37_(constraints.audio);
3860 }
3861 if (constraints.video) {
3862 constraints.video = constraintsToFF37_(constraints.video);
3863 }
3864 logging('ff37: ' + JSON.stringify(constraints));
3865 }
3866 return navigator.mozGetUserMedia(constraints, onSuccess, function(e) {
3867 onError(shimError_(e));
3868 });
3869 };
3870
3871 // Returns the result of getUserMedia as a Promise.
3872 var getUserMediaPromise_ = function(constraints) {
3873 return new Promise(function(resolve, reject) {
3874 getUserMedia_(constraints, resolve, reject);
3875 });
3876 };
3877
3878 // Shim for mediaDevices on older versions.
3879 if (!navigator.mediaDevices) {
3880 navigator.mediaDevices = {getUserMedia: getUserMediaPromise_,
3881 addEventListener: function() { },
3882 removeEventListener: function() { }
3883 };
3884 }
3885 navigator.mediaDevices.enumerateDevices =
3886 navigator.mediaDevices.enumerateDevices || function() {
3887 return new Promise(function(resolve) {
3888 var infos = [
3889 {kind: 'audioinput', deviceId: 'default', label: '', groupId: ''},
3890 {kind: 'videoinput', deviceId: 'default', label: '', groupId: ''}
3891 ];
3892 resolve(infos);
3893 });
3894 };
3895
3896 if (browserDetails.version < 41) {
3897 // Work around http://bugzil.la/1169665
3898 var orgEnumerateDevices =
3899 navigator.mediaDevices.enumerateDevices.bind(navigator.mediaDevices);
3900 navigator.mediaDevices.enumerateDevices = function() {
3901 return orgEnumerateDevices().then(undefined, function(e) {
3902 if (e.name === 'NotFoundError') {
3903 return [];
3904 }
3905 throw e;
3906 });
3907 };
3908 }
3909 if (browserDetails.version < 49) {
3910 var origGetUserMedia = navigator.mediaDevices.getUserMedia.
3911 bind(navigator.mediaDevices);
3912 navigator.mediaDevices.getUserMedia = function(c) {
3913 return origGetUserMedia(c).then(function(stream) {
3914 // Work around https://bugzil.la/802326
3915 if (c.audio && !stream.getAudioTracks().length ||
3916 c.video && !stream.getVideoTracks().length) {
3917 stream.getTracks().forEach(function(track) {
3918 track.stop();
3919 });
3920 throw new DOMException('The object can not be found here.',
3921 'NotFoundError');
3922 }
3923 return stream;
3924 }, function(e) {
3925 return Promise.reject(shimError_(e));
3926 });
3927 };
3928 }
3929 if (!(browserDetails.version > 55 &&
3930 'autoGainControl' in navigator.mediaDevices.getSupportedConstraints())) {
3931 var remap = function(obj, a, b) {
3932 if (a in obj && !(b in obj)) {
3933 obj[b] = obj[a];
3934 delete obj[a];
3935 }
3936 };
3937
3938 var nativeGetUserMedia = navigator.mediaDevices.getUserMedia.
3939 bind(navigator.mediaDevices);
3940 navigator.mediaDevices.getUserMedia = function(c) {
3941 if (typeof c === 'object' && typeof c.audio === 'object') {
3942 c = JSON.parse(JSON.stringify(c));
3943 remap(c.audio, 'autoGainControl', 'mozAutoGainControl');
3944 remap(c.audio, 'noiseSuppression', 'mozNoiseSuppression');
3945 }
3946 return nativeGetUserMedia(c);
3947 };
3948
3949 if (MediaStreamTrack && MediaStreamTrack.prototype.getSettings) {
3950 var nativeGetSettings = MediaStreamTrack.prototype.getSettings;
3951 MediaStreamTrack.prototype.getSettings = function() {
3952 var obj = nativeGetSettings.apply(this, arguments);
3953 remap(obj, 'mozAutoGainControl', 'autoGainControl');
3954 remap(obj, 'mozNoiseSuppression', 'noiseSuppression');
3955 return obj;
3956 };
3957 }
3958
3959 if (MediaStreamTrack && MediaStreamTrack.prototype.applyConstraints) {
3960 var nativeApplyConstraints = MediaStreamTrack.prototype.applyConstraints;
3961 MediaStreamTrack.prototype.applyConstraints = function(c) {
3962 if (this.kind === 'audio' && typeof c === 'object') {
3963 c = JSON.parse(JSON.stringify(c));
3964 remap(c, 'autoGainControl', 'mozAutoGainControl');
3965 remap(c, 'noiseSuppression', 'mozNoiseSuppression');
3966 }
3967 return nativeApplyConstraints.apply(this, [c]);
3968 };
3969 }
3970 }
3971 navigator.getUserMedia = function(constraints, onSuccess, onError) {
3972 if (browserDetails.version < 44) {
3973 return getUserMedia_(constraints, onSuccess, onError);
3974 }
3975 // Replace Firefox 44+'s deprecation warning with unprefixed version.
3976 utils.deprecated('navigator.getUserMedia',
3977 'navigator.mediaDevices.getUserMedia');
3978 navigator.mediaDevices.getUserMedia(constraints).then(onSuccess, onError);
3979 };
3980 };
3981
3982 },{"../utils":13}],12:[function(require,module,exports){
3983 /*
3984 * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
3985 *
3986 * Use of this source code is governed by a BSD-style license
3987 * that can be found in the LICENSE file in the root of the source
3988 * tree.
3989 */
3990 'use strict';
3991 var utils = require('../utils');
3992
3993 var safariShim = {
3994 // TODO: DrAlex, should be here, double check against LayoutTests
3995
3996 // TODO: once the back-end for the mac port is done, add.
3997 // TODO: check for webkitGTK+
3998 // shimPeerConnection: function() { },
3999
4000 shimLocalStreamsAPI: function(window) {
4001 if (typeof window !== 'object' || !window.RTCPeerConnection) {
4002 return;
4003 }
4004 if (!('getLocalStreams' in window.RTCPeerConnection.prototype)) {
4005 window.RTCPeerConnection.prototype.getLocalStreams = function() {
4006 if (!this._localStreams) {
4007 this._localStreams = [];
4008 }
4009 return this._localStreams;
4010 };
4011 }
4012 if (!('getStreamById' in window.RTCPeerConnection.prototype)) {
4013 window.RTCPeerConnection.prototype.getStreamById = function(id) {
4014 var result = null;
4015 if (this._localStreams) {
4016 this._localStreams.forEach(function(stream) {
4017 if (stream.id === id) {
4018 result = stream;
4019 }
4020 });
4021 }
4022 if (this._remoteStreams) {
4023 this._remoteStreams.forEach(function(stream) {
4024 if (stream.id === id) {
4025 result = stream;
4026 }
4027 });
4028 }
4029 return result;
4030 };
4031 }
4032 if (!('addStream' in window.RTCPeerConnection.prototype)) {
4033 var _addTrack = window.RTCPeerConnection.prototype.addTrack;
4034 window.RTCPeerConnection.prototype.addStream = function(stream) {
4035 if (!this._localStreams) {
4036 this._localStreams = [];
4037 }
4038 if (this._localStreams.indexOf(stream) === -1) {
4039 this._localStreams.push(stream);
4040 }
4041 var self = this;
4042 stream.getTracks().forEach(function(track) {
4043 _addTrack.call(self, track, stream);
4044 });
4045 };
4046
4047 window.RTCPeerConnection.prototype.addTrack = function(track, stream) {
4048 if (stream) {
4049 if (!this._localStreams) {
4050 this._localStreams = [stream];
4051 } else if (this._localStreams.indexOf(stream) === -1) {
4052 this._localStreams.push(stream);
4053 }
4054 }
4055 _addTrack.call(this, track, stream);
4056 };
4057 }
4058 if (!('removeStream' in window.RTCPeerConnection.prototype)) {
4059 window.RTCPeerConnection.prototype.removeStream = function(stream) {
4060 if (!this._localStreams) {
4061 this._localStreams = [];
4062 }
4063 var index = this._localStreams.indexOf(stream);
4064 if (index === -1) {
4065 return;
4066 }
4067 this._localStreams.splice(index, 1);
4068 var self = this;
4069 var tracks = stream.getTracks();
4070 this.getSenders().forEach(function(sender) {
4071 if (tracks.indexOf(sender.track) !== -1) {
4072 self.removeTrack(sender);
4073 }
4074 });
4075 };
4076 }
4077 },
4078 shimRemoteStreamsAPI: function(window) {
4079 if (typeof window !== 'object' || !window.RTCPeerConnection) {
4080 return;
4081 }
4082 if (!('getRemoteStreams' in window.RTCPeerConnection.prototype)) {
4083 window.RTCPeerConnection.prototype.getRemoteStreams = function() {
4084 return this._remoteStreams ? this._remoteStreams : [];
4085 };
4086 }
4087 if (!('onaddstream' in window.RTCPeerConnection.prototype)) {
4088 Object.defineProperty(window.RTCPeerConnection.prototype, 'onaddstream', {
4089 get: function() {
4090 return this._onaddstream;
4091 },
4092 set: function(f) {
4093 if (this._onaddstream) {
4094 this.removeEventListener('addstream', this._onaddstream);
4095 this.removeEventListener('track', this._onaddstreampoly);
4096 }
4097 this.addEventListener('addstream', this._onaddstream = f);
4098 this.addEventListener('track', this._onaddstreampoly = function(e) {
4099 var stream = e.streams[0];
4100 if (!this._remoteStreams) {
4101 this._remoteStreams = [];
4102 }
4103 if (this._remoteStreams.indexOf(stream) >= 0) {
4104 return;
4105 }
4106 this._remoteStreams.push(stream);
4107 var event = new Event('addstream');
4108 event.stream = e.streams[0];
4109 this.dispatchEvent(event);
4110 }.bind(this));
4111 }
4112 });
4113 }
4114 },
4115 shimCallbacksAPI: function(window) {
4116 if (typeof window !== 'object' || !window.RTCPeerConnection) {
4117 return;
4118 }
4119 var prototype = window.RTCPeerConnection.prototype;
4120 var createOffer = prototype.createOffer;
4121 var createAnswer = prototype.createAnswer;
4122 var setLocalDescription = prototype.setLocalDescription;
4123 var setRemoteDescription = prototype.setRemoteDescription;
4124 var addIceCandidate = prototype.addIceCandidate;
4125
4126 prototype.createOffer = function(successCallback, failureCallback) {
4127 var options = (arguments.length >= 2) ? arguments[2] : arguments[0];
4128 var promise = createOffer.apply(this, [options]);
4129 if (!failureCallback) {
4130 return promise;
4131 }
4132 promise.then(successCallback, failureCallback);
4133 return Promise.resolve();
4134 };
4135
4136 prototype.createAnswer = function(successCallback, failureCallback) {
4137 var options = (arguments.length >= 2) ? arguments[2] : arguments[0];
4138 var promise = createAnswer.apply(this, [options]);
4139 if (!failureCallback) {
4140 return promise;
4141 }
4142 promise.then(successCallback, failureCallback);
4143 return Promise.resolve();
4144 };
4145
4146 var withCallback = function(description, successCallback, failureCallback) {
4147 var promise = setLocalDescription.apply(this, [description]);
4148 if (!failureCallback) {
4149 return promise;
4150 }
4151 promise.then(successCallback, failureCallback);
4152 return Promise.resolve();
4153 };
4154 prototype.setLocalDescription = withCallback;
4155
4156 withCallback = function(description, successCallback, failureCallback) {
4157 var promise = setRemoteDescription.apply(this, [description]);
4158 if (!failureCallback) {
4159 return promise;
4160 }
4161 promise.then(successCallback, failureCallback);
4162 return Promise.resolve();
4163 };
4164 prototype.setRemoteDescription = withCallback;
4165
4166 withCallback = function(candidate, successCallback, failureCallback) {
4167 var promise = addIceCandidate.apply(this, [candidate]);
4168 if (!failureCallback) {
4169 return promise;
4170 }
4171 promise.then(successCallback, failureCallback);
4172 return Promise.resolve();
4173 };
4174 prototype.addIceCandidate = withCallback;
4175 },
4176 shimGetUserMedia: function(window) {
4177 var navigator = window && window.navigator;
4178
4179 if (!navigator.getUserMedia) {
4180 if (navigator.webkitGetUserMedia) {
4181 navigator.getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
4182 } else if (navigator.mediaDevices &&
4183 navigator.mediaDevices.getUserMedia) {
4184 navigator.getUserMedia = function(constraints, cb, errcb) {
4185 navigator.mediaDevices.getUserMedia(constraints)
4186 .then(cb, errcb);
4187 }.bind(navigator);
4188 }
4189 }
4190 },
4191 shimRTCIceServerUrls: function(window) {
4192 // migrate from non-spec RTCIceServer.url to RTCIceServer.urls
4193 var OrigPeerConnection = window.RTCPeerConnection;
4194 window.RTCPeerConnection = function(pcConfig, pcConstraints) {
4195 if (pcConfig && pcConfig.iceServers) {
4196 var newIceServers = [];
4197 for (var i = 0; i < pcConfig.iceServers.length; i++) {
4198 var server = pcConfig.iceServers[i];
4199 if (!server.hasOwnProperty('urls') &&
4200 server.hasOwnProperty('url')) {
4201 utils.deprecated('RTCIceServer.url', 'RTCIceServer.urls');
4202 server = JSON.parse(JSON.stringify(server));
4203 server.urls = server.url;
4204 delete server.url;
4205 newIceServers.push(server);
4206 } else {
4207 newIceServers.push(pcConfig.iceServers[i]);
4208 }
4209 }
4210 pcConfig.iceServers = newIceServers;
4211 }
4212 return new OrigPeerConnection(pcConfig, pcConstraints);
4213 };
4214 window.RTCPeerConnection.prototype = OrigPeerConnection.prototype;
4215 // wrap static methods. Currently just generateCertificate.
4216 if ('generateCertificate' in window.RTCPeerConnection) {
4217 Object.defineProperty(window.RTCPeerConnection, 'generateCertificate', {
4218 get: function() {
4219 return OrigPeerConnection.generateCertificate;
4220 }
4221 });
4222 }
4223 },
4224 shimTrackEventTransceiver: function(window) {
4225 // Add event.transceiver member over deprecated event.receiver
4226 if (typeof window === 'object' && window.RTCPeerConnection &&
4227 ('receiver' in window.RTCTrackEvent.prototype) &&
4228 // can't check 'transceiver' in window.RTCTrackEvent.prototype, as it is
4229 // defined for some reason even when window.RTCTransceiver is not.
4230 !window.RTCTransceiver) {
4231 Object.defineProperty(window.RTCTrackEvent.prototype, 'transceiver', {
4232 get: function() {
4233 return {receiver: this.receiver};
4234 }
4235 });
4236 }
4237 }
4238 };
4239
4240 // Expose public methods.
4241 module.exports = {
4242 shimCallbacksAPI: safariShim.shimCallbacksAPI,
4243 shimLocalStreamsAPI: safariShim.shimLocalStreamsAPI,
4244 shimRemoteStreamsAPI: safariShim.shimRemoteStreamsAPI,
4245 shimGetUserMedia: safariShim.shimGetUserMedia,
4246 shimRTCIceServerUrls: safariShim.shimRTCIceServerUrls,
4247 shimTrackEventTransceiver: safariShim.shimTrackEventTransceiver
4248 // TODO
4249 // shimPeerConnection: safariShim.shimPeerConnection
4250 };
4251
4252 },{"../utils":13}],13:[function(require,module,exports){
4253 /*
4254 * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
4255 *
4256 * Use of this source code is governed by a BSD-style license
4257 * that can be found in the LICENSE file in the root of the source
4258 * tree.
4259 */
4260 /* eslint-env node */
4261 'use strict';
4262
4263 var logDisabled_ = true;
4264 var deprecationWarnings_ = true;
4265
4266 // Utility methods.
4267 var utils = {
4268 disableLog: function(bool) {
4269 if (typeof bool !== 'boolean') {
4270 return new Error('Argument type: ' + typeof bool +
4271 '. Please use a boolean.');
4272 }
4273 logDisabled_ = bool;
4274 return (bool) ? 'adapter.js logging disabled' :
4275 'adapter.js logging enabled';
4276 },
4277
4278 /**
4279 * Disable or enable deprecation warnings
4280 * @param {!boolean} bool set to true to disable warnings.
4281 */
4282 disableWarnings: function(bool) {
4283 if (typeof bool !== 'boolean') {
4284 return new Error('Argument type: ' + typeof bool +
4285 '. Please use a boolean.');
4286 }
4287 deprecationWarnings_ = !bool;
4288 return 'adapter.js deprecation warnings ' + (bool ? 'disabled' : 'enabled');
4289 },
4290
4291 log: function() {
4292 if (typeof window === 'object') {
4293 if (logDisabled_) {
4294 return;
4295 }
4296 if (typeof console !== 'undefined' && typeof console.log === 'function') {
4297 console.log.apply(console, arguments);
4298 }
4299 }
4300 },
4301
4302 /**
4303 * Shows a deprecation warning suggesting the modern and spec-compatible API.
4304 */
4305 deprecated: function(oldMethod, newMethod) {
4306 if (!deprecationWarnings_) {
4307 return;
4308 }
4309 console.warn(oldMethod + ' is deprecated, please use ' + newMethod +
4310 ' instead.');
4311 },
4312
4313 /**
4314 * Extract browser version out of the provided user agent string.
4315 *
4316 * @param {!string} uastring userAgent string.
4317 * @param {!string} expr Regular expression used as match criteria.
4318 * @param {!number} pos position in the version string to be returned.
4319 * @return {!number} browser version.
4320 */
4321 extractVersion: function(uastring, expr, pos) {
4322 var match = uastring.match(expr);
4323 return match && match.length >= pos && parseInt(match[pos], 10);
4324 },
4325
4326 /**
4327 * Browser detector.
4328 *
4329 * @return {object} result containing browser and version
4330 * properties.
4331 */
4332 detectBrowser: function(window) {
4333 var navigator = window && window.navigator;
4334
4335 // Returned result object.
4336 var result = {};
4337 result.browser = null;
4338 result.version = null;
4339
4340 // Fail early if it's not a browser
4341 if (typeof window === 'undefined' || !window.navigator) {
4342 result.browser = 'Not a browser.';
4343 return result;
4344 }
4345
4346 // Firefox.
4347 if (navigator.mozGetUserMedia) {
4348 result.browser = 'firefox';
4349 result.version = this.extractVersion(navigator.userAgent,
4350 /Firefox\/(\d+)\./, 1);
4351 } else if (navigator.webkitGetUserMedia) {
4352 // Chrome, Chromium, Webview, Opera, all use the chrome shim for now
4353 if (window.webkitRTCPeerConnection) {
4354 result.browser = 'chrome';
4355 result.version = this.extractVersion(navigator.userAgent,
4356 /Chrom(e|ium)\/(\d+)\./, 2);
4357 } else { // Safari (in an unpublished version) or unknown webkit-based.
4358 if (navigator.userAgent.match(/Version\/(\d+).(\d+)/)) {
4359 result.browser = 'safari';
4360 result.version = this.extractVersion(navigator.userAgent,
4361 /AppleWebKit\/(\d+)\./, 1);
4362 } else { // unknown webkit-based browser.
4363 result.browser = 'Unsupported webkit-based browser ' +
4364 'with GUM support but no WebRTC support.';
4365 return result;
4366 }
4367 }
4368 } else if (navigator.mediaDevices &&
4369 navigator.userAgent.match(/Edge\/(\d+).(\d+)$/)) { // Edge.
4370 result.browser = 'edge';
4371 result.version = this.extractVersion(navigator.userAgent,
4372 /Edge\/(\d+).(\d+)$/, 2);
4373 } else if (navigator.mediaDevices &&
4374 navigator.userAgent.match(/AppleWebKit\/(\d+)\./)) {
4375 // Safari, with webkitGetUserMedia removed.
4376 result.browser = 'safari';
4377 result.version = this.extractVersion(navigator.userAgent,
4378 /AppleWebKit\/(\d+)\./, 1);
4379 } else { // Default fallthrough: not supported.
4380 result.browser = 'Not a supported browser.';
4381 return result;
4382 }
4383
4384 return result;
4385 },
4386
4387 };
4388
4389 // Export.
4390 module.exports = {
4391 log: utils.log,
4392 deprecated: utils.deprecated,
4393 disableLog: utils.disableLog,
4394 disableWarnings: utils.disableWarnings,
4395 extractVersion: utils.extractVersion,
4396 shimCreateObjectURL: utils.shimCreateObjectURL,
4397 detectBrowser: utils.detectBrowser.bind(utils)
4398 };
4399
4400 },{}]},{},[3])(3)
4401 });