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