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