Proyectos de Subversion Moodle

Rev

| Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1 efrain 1
/**
2
 * Description of import/upgrade into Moodle:
3
 *
4
 * 1. Visit https://github.com/webrtc/adapter/releases.
5
 * 2. Check if the version has been updated from what is listed in lib/thirdpartylibs.xml in the Moodle wwwroot.
6
 * 3. If it has -
7
 *    1. Download the source code.
8
 *    2. Copy the content of the file release/adapter.js from the archive (ignore the first line).
9
 *    3. Replace the content below "return (function e(t,n,r) .." in this file with the content you copied.
10
 *    4. Ensure to update lib/thirdpartylibs.xml with any changes.
11
 */
12
 
13
// ESLint directives.
14
/* eslint-disable */
15
 
16
// JSHint directives.
17
/* jshint ignore:start */
18
 
19
define([], function() {
20
return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
21
/*
22
 *  Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
23
 *
24
 *  Use of this source code is governed by a BSD-style license
25
 *  that can be found in the LICENSE file in the root of the source
26
 *  tree.
27
 */
28
/* eslint-env node */
29
 
30
'use strict';
31
 
32
var _adapter_factory = require('./adapter_factory.js');
33
 
34
var adapter = (0, _adapter_factory.adapterFactory)({ window: typeof window === 'undefined' ? undefined : window });
35
module.exports = adapter; // this is the difference from adapter_core.
36
 
37
},{"./adapter_factory.js":2}],2:[function(require,module,exports){
38
'use strict';
39
 
40
Object.defineProperty(exports, "__esModule", {
41
  value: true
42
});
43
exports.adapterFactory = adapterFactory;
44
 
45
var _utils = require('./utils');
46
 
47
var utils = _interopRequireWildcard(_utils);
48
 
49
var _chrome_shim = require('./chrome/chrome_shim');
50
 
51
var chromeShim = _interopRequireWildcard(_chrome_shim);
52
 
53
var _firefox_shim = require('./firefox/firefox_shim');
54
 
55
var firefoxShim = _interopRequireWildcard(_firefox_shim);
56
 
57
var _safari_shim = require('./safari/safari_shim');
58
 
59
var safariShim = _interopRequireWildcard(_safari_shim);
60
 
61
var _common_shim = require('./common_shim');
62
 
63
var commonShim = _interopRequireWildcard(_common_shim);
64
 
65
var _sdp = require('sdp');
66
 
67
var sdp = _interopRequireWildcard(_sdp);
68
 
69
function _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; } }
70
 
71
// Shimming starts here.
72
/*
73
 *  Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
74
 *
75
 *  Use of this source code is governed by a BSD-style license
76
 *  that can be found in the LICENSE file in the root of the source
77
 *  tree.
78
 */
79
function adapterFactory() {
80
  var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
81
      window = _ref.window;
82
 
83
  var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {
84
    shimChrome: true,
85
    shimFirefox: true,
86
    shimSafari: true
87
  };
88
 
89
  // Utils.
90
  var logging = utils.log;
91
  var browserDetails = utils.detectBrowser(window);
92
 
93
  var adapter = {
94
    browserDetails: browserDetails,
95
    commonShim: commonShim,
96
    extractVersion: utils.extractVersion,
97
    disableLog: utils.disableLog,
98
    disableWarnings: utils.disableWarnings,
99
    // Expose sdp as a convenience. For production apps include directly.
100
    sdp: sdp
101
  };
102
 
103
  // Shim browser if found.
104
  switch (browserDetails.browser) {
105
    case 'chrome':
106
      if (!chromeShim || !chromeShim.shimPeerConnection || !options.shimChrome) {
107
        logging('Chrome shim is not included in this adapter release.');
108
        return adapter;
109
      }
110
      if (browserDetails.version === null) {
111
        logging('Chrome shim can not determine version, not shimming.');
112
        return adapter;
113
      }
114
      logging('adapter.js shimming chrome.');
115
      // Export to the adapter global object visible in the browser.
116
      adapter.browserShim = chromeShim;
117
 
118
      // Must be called before shimPeerConnection.
119
      commonShim.shimAddIceCandidateNullOrEmpty(window, browserDetails);
120
 
121
      chromeShim.shimGetUserMedia(window, browserDetails);
122
      chromeShim.shimMediaStream(window, browserDetails);
123
      chromeShim.shimPeerConnection(window, browserDetails);
124
      chromeShim.shimOnTrack(window, browserDetails);
125
      chromeShim.shimAddTrackRemoveTrack(window, browserDetails);
126
      chromeShim.shimGetSendersWithDtmf(window, browserDetails);
127
      chromeShim.shimGetStats(window, browserDetails);
128
      chromeShim.shimSenderReceiverGetStats(window, browserDetails);
129
      chromeShim.fixNegotiationNeeded(window, browserDetails);
130
 
131
      commonShim.shimRTCIceCandidate(window, browserDetails);
132
      commonShim.shimConnectionState(window, browserDetails);
133
      commonShim.shimMaxMessageSize(window, browserDetails);
134
      commonShim.shimSendThrowTypeError(window, browserDetails);
135
      commonShim.removeExtmapAllowMixed(window, browserDetails);
136
      break;
137
    case 'firefox':
138
      if (!firefoxShim || !firefoxShim.shimPeerConnection || !options.shimFirefox) {
139
        logging('Firefox shim is not included in this adapter release.');
140
        return adapter;
141
      }
142
      logging('adapter.js shimming firefox.');
143
      // Export to the adapter global object visible in the browser.
144
      adapter.browserShim = firefoxShim;
145
 
146
      // Must be called before shimPeerConnection.
147
      commonShim.shimAddIceCandidateNullOrEmpty(window, browserDetails);
148
 
149
      firefoxShim.shimGetUserMedia(window, browserDetails);
150
      firefoxShim.shimPeerConnection(window, browserDetails);
151
      firefoxShim.shimOnTrack(window, browserDetails);
152
      firefoxShim.shimRemoveStream(window, browserDetails);
153
      firefoxShim.shimSenderGetStats(window, browserDetails);
154
      firefoxShim.shimReceiverGetStats(window, browserDetails);
155
      firefoxShim.shimRTCDataChannel(window, browserDetails);
156
      firefoxShim.shimAddTransceiver(window, browserDetails);
157
      firefoxShim.shimGetParameters(window, browserDetails);
158
      firefoxShim.shimCreateOffer(window, browserDetails);
159
      firefoxShim.shimCreateAnswer(window, browserDetails);
160
 
161
      commonShim.shimRTCIceCandidate(window, browserDetails);
162
      commonShim.shimConnectionState(window, browserDetails);
163
      commonShim.shimMaxMessageSize(window, browserDetails);
164
      commonShim.shimSendThrowTypeError(window, browserDetails);
165
      break;
166
    case 'safari':
167
      if (!safariShim || !options.shimSafari) {
168
        logging('Safari shim is not included in this adapter release.');
169
        return adapter;
170
      }
171
      logging('adapter.js shimming safari.');
172
      // Export to the adapter global object visible in the browser.
173
      adapter.browserShim = safariShim;
174
 
175
      // Must be called before shimCallbackAPI.
176
      commonShim.shimAddIceCandidateNullOrEmpty(window, browserDetails);
177
 
178
      safariShim.shimRTCIceServerUrls(window, browserDetails);
179
      safariShim.shimCreateOfferLegacy(window, browserDetails);
180
      safariShim.shimCallbacksAPI(window, browserDetails);
181
      safariShim.shimLocalStreamsAPI(window, browserDetails);
182
      safariShim.shimRemoteStreamsAPI(window, browserDetails);
183
      safariShim.shimTrackEventTransceiver(window, browserDetails);
184
      safariShim.shimGetUserMedia(window, browserDetails);
185
      safariShim.shimAudioContext(window, browserDetails);
186
 
187
      commonShim.shimRTCIceCandidate(window, browserDetails);
188
      commonShim.shimMaxMessageSize(window, browserDetails);
189
      commonShim.shimSendThrowTypeError(window, browserDetails);
190
      commonShim.removeExtmapAllowMixed(window, browserDetails);
191
      break;
192
    default:
193
      logging('Unsupported browser!');
194
      break;
195
  }
196
 
197
  return adapter;
198
}
199
 
200
// Browser shims.
201
 
202
},{"./chrome/chrome_shim":3,"./common_shim":6,"./firefox/firefox_shim":7,"./safari/safari_shim":10,"./utils":11,"sdp":12}],3:[function(require,module,exports){
203
/*
204
 *  Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
205
 *
206
 *  Use of this source code is governed by a BSD-style license
207
 *  that can be found in the LICENSE file in the root of the source
208
 *  tree.
209
 */
210
/* eslint-env node */
211
'use strict';
212
 
213
Object.defineProperty(exports, "__esModule", {
214
  value: true
215
});
216
exports.shimGetDisplayMedia = exports.shimGetUserMedia = undefined;
217
 
218
var _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; };
219
 
220
var _getusermedia = require('./getusermedia');
221
 
222
Object.defineProperty(exports, 'shimGetUserMedia', {
223
  enumerable: true,
224
  get: function get() {
225
    return _getusermedia.shimGetUserMedia;
226
  }
227
});
228
 
229
var _getdisplaymedia = require('./getdisplaymedia');
230
 
231
Object.defineProperty(exports, 'shimGetDisplayMedia', {
232
  enumerable: true,
233
  get: function get() {
234
    return _getdisplaymedia.shimGetDisplayMedia;
235
  }
236
});
237
exports.shimMediaStream = shimMediaStream;
238
exports.shimOnTrack = shimOnTrack;
239
exports.shimGetSendersWithDtmf = shimGetSendersWithDtmf;
240
exports.shimGetStats = shimGetStats;
241
exports.shimSenderReceiverGetStats = shimSenderReceiverGetStats;
242
exports.shimAddTrackRemoveTrackWithNative = shimAddTrackRemoveTrackWithNative;
243
exports.shimAddTrackRemoveTrack = shimAddTrackRemoveTrack;
244
exports.shimPeerConnection = shimPeerConnection;
245
exports.fixNegotiationNeeded = fixNegotiationNeeded;
246
 
247
var _utils = require('../utils.js');
248
 
249
var utils = _interopRequireWildcard(_utils);
250
 
251
function _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; } }
252
 
253
function _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; }
254
 
255
function shimMediaStream(window) {
256
  window.MediaStream = window.MediaStream || window.webkitMediaStream;
257
}
258
 
259
function shimOnTrack(window) {
260
  if ((typeof window === 'undefined' ? 'undefined' : _typeof(window)) === 'object' && window.RTCPeerConnection && !('ontrack' in window.RTCPeerConnection.prototype)) {
261
    Object.defineProperty(window.RTCPeerConnection.prototype, 'ontrack', {
262
      get: function get() {
263
        return this._ontrack;
264
      },
265
      set: function set(f) {
266
        if (this._ontrack) {
267
          this.removeEventListener('track', this._ontrack);
268
        }
269
        this.addEventListener('track', this._ontrack = f);
270
      },
271
 
272
      enumerable: true,
273
      configurable: true
274
    });
275
    var origSetRemoteDescription = window.RTCPeerConnection.prototype.setRemoteDescription;
276
    window.RTCPeerConnection.prototype.setRemoteDescription = function setRemoteDescription() {
277
      var _this = this;
278
 
279
      if (!this._ontrackpoly) {
280
        this._ontrackpoly = function (e) {
281
          // onaddstream does not fire when a track is added to an existing
282
          // stream. But stream.onaddtrack is implemented so we use that.
283
          e.stream.addEventListener('addtrack', function (te) {
284
            var receiver = void 0;
285
            if (window.RTCPeerConnection.prototype.getReceivers) {
286
              receiver = _this.getReceivers().find(function (r) {
287
                return r.track && r.track.id === te.track.id;
288
              });
289
            } else {
290
              receiver = { track: te.track };
291
            }
292
 
293
            var event = new Event('track');
294
            event.track = te.track;
295
            event.receiver = receiver;
296
            event.transceiver = { receiver: receiver };
297
            event.streams = [e.stream];
298
            _this.dispatchEvent(event);
299
          });
300
          e.stream.getTracks().forEach(function (track) {
301
            var receiver = void 0;
302
            if (window.RTCPeerConnection.prototype.getReceivers) {
303
              receiver = _this.getReceivers().find(function (r) {
304
                return r.track && r.track.id === track.id;
305
              });
306
            } else {
307
              receiver = { track: track };
308
            }
309
            var event = new Event('track');
310
            event.track = track;
311
            event.receiver = receiver;
312
            event.transceiver = { receiver: receiver };
313
            event.streams = [e.stream];
314
            _this.dispatchEvent(event);
315
          });
316
        };
317
        this.addEventListener('addstream', this._ontrackpoly);
318
      }
319
      return origSetRemoteDescription.apply(this, arguments);
320
    };
321
  } else {
322
    // even if RTCRtpTransceiver is in window, it is only used and
323
    // emitted in unified-plan. Unfortunately this means we need
324
    // to unconditionally wrap the event.
325
    utils.wrapPeerConnectionEvent(window, 'track', function (e) {
326
      if (!e.transceiver) {
327
        Object.defineProperty(e, 'transceiver', { value: { receiver: e.receiver } });
328
      }
329
      return e;
330
    });
331
  }
332
}
333
 
334
function shimGetSendersWithDtmf(window) {
335
  // Overrides addTrack/removeTrack, depends on shimAddTrackRemoveTrack.
336
  if ((typeof window === 'undefined' ? 'undefined' : _typeof(window)) === 'object' && window.RTCPeerConnection && !('getSenders' in window.RTCPeerConnection.prototype) && 'createDTMFSender' in window.RTCPeerConnection.prototype) {
337
    var shimSenderWithDtmf = function shimSenderWithDtmf(pc, track) {
338
      return {
339
        track: track,
340
        get dtmf() {
341
          if (this._dtmf === undefined) {
342
            if (track.kind === 'audio') {
343
              this._dtmf = pc.createDTMFSender(track);
344
            } else {
345
              this._dtmf = null;
346
            }
347
          }
348
          return this._dtmf;
349
        },
350
        _pc: pc
351
      };
352
    };
353
 
354
    // augment addTrack when getSenders is not available.
355
    if (!window.RTCPeerConnection.prototype.getSenders) {
356
      window.RTCPeerConnection.prototype.getSenders = function getSenders() {
357
        this._senders = this._senders || [];
358
        return this._senders.slice(); // return a copy of the internal state.
359
      };
360
      var origAddTrack = window.RTCPeerConnection.prototype.addTrack;
361
      window.RTCPeerConnection.prototype.addTrack = function addTrack(track, stream) {
362
        var sender = origAddTrack.apply(this, arguments);
363
        if (!sender) {
364
          sender = shimSenderWithDtmf(this, track);
365
          this._senders.push(sender);
366
        }
367
        return sender;
368
      };
369
 
370
      var origRemoveTrack = window.RTCPeerConnection.prototype.removeTrack;
371
      window.RTCPeerConnection.prototype.removeTrack = function removeTrack(sender) {
372
        origRemoveTrack.apply(this, arguments);
373
        var idx = this._senders.indexOf(sender);
374
        if (idx !== -1) {
375
          this._senders.splice(idx, 1);
376
        }
377
      };
378
    }
379
    var origAddStream = window.RTCPeerConnection.prototype.addStream;
380
    window.RTCPeerConnection.prototype.addStream = function addStream(stream) {
381
      var _this2 = this;
382
 
383
      this._senders = this._senders || [];
384
      origAddStream.apply(this, [stream]);
385
      stream.getTracks().forEach(function (track) {
386
        _this2._senders.push(shimSenderWithDtmf(_this2, track));
387
      });
388
    };
389
 
390
    var origRemoveStream = window.RTCPeerConnection.prototype.removeStream;
391
    window.RTCPeerConnection.prototype.removeStream = function removeStream(stream) {
392
      var _this3 = this;
393
 
394
      this._senders = this._senders || [];
395
      origRemoveStream.apply(this, [stream]);
396
 
397
      stream.getTracks().forEach(function (track) {
398
        var sender = _this3._senders.find(function (s) {
399
          return s.track === track;
400
        });
401
        if (sender) {
402
          // remove sender
403
          _this3._senders.splice(_this3._senders.indexOf(sender), 1);
404
        }
405
      });
406
    };
407
  } 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)) {
408
    var origGetSenders = window.RTCPeerConnection.prototype.getSenders;
409
    window.RTCPeerConnection.prototype.getSenders = function getSenders() {
410
      var _this4 = this;
411
 
412
      var senders = origGetSenders.apply(this, []);
413
      senders.forEach(function (sender) {
414
        return sender._pc = _this4;
415
      });
416
      return senders;
417
    };
418
 
419
    Object.defineProperty(window.RTCRtpSender.prototype, 'dtmf', {
420
      get: function get() {
421
        if (this._dtmf === undefined) {
422
          if (this.track.kind === 'audio') {
423
            this._dtmf = this._pc.createDTMFSender(this.track);
424
          } else {
425
            this._dtmf = null;
426
          }
427
        }
428
        return this._dtmf;
429
      }
430
    });
431
  }
432
}
433
 
434
function shimGetStats(window) {
435
  if (!window.RTCPeerConnection) {
436
    return;
437
  }
438
 
439
  var origGetStats = window.RTCPeerConnection.prototype.getStats;
440
  window.RTCPeerConnection.prototype.getStats = function getStats() {
441
    var _this5 = this;
442
 
443
    var _arguments = Array.prototype.slice.call(arguments),
444
        selector = _arguments[0],
445
        onSucc = _arguments[1],
446
        onErr = _arguments[2];
447
 
448
    // If selector is a function then we are in the old style stats so just
449
    // pass back the original getStats format to avoid breaking old users.
450
 
451
 
452
    if (arguments.length > 0 && typeof selector === 'function') {
453
      return origGetStats.apply(this, arguments);
454
    }
455
 
456
    // When spec-style getStats is supported, return those when called with
457
    // either no arguments or the selector argument is null.
458
    if (origGetStats.length === 0 && (arguments.length === 0 || typeof selector !== 'function')) {
459
      return origGetStats.apply(this, []);
460
    }
461
 
462
    var fixChromeStats_ = function fixChromeStats_(response) {
463
      var standardReport = {};
464
      var reports = response.result();
465
      reports.forEach(function (report) {
466
        var standardStats = {
467
          id: report.id,
468
          timestamp: report.timestamp,
469
          type: {
470
            localcandidate: 'local-candidate',
471
            remotecandidate: 'remote-candidate'
472
          }[report.type] || report.type
473
        };
474
        report.names().forEach(function (name) {
475
          standardStats[name] = report.stat(name);
476
        });
477
        standardReport[standardStats.id] = standardStats;
478
      });
479
 
480
      return standardReport;
481
    };
482
 
483
    // shim getStats with maplike support
484
    var makeMapStats = function makeMapStats(stats) {
485
      return new Map(Object.keys(stats).map(function (key) {
486
        return [key, stats[key]];
487
      }));
488
    };
489
 
490
    if (arguments.length >= 2) {
491
      var successCallbackWrapper_ = function successCallbackWrapper_(response) {
492
        onSucc(makeMapStats(fixChromeStats_(response)));
493
      };
494
 
495
      return origGetStats.apply(this, [successCallbackWrapper_, selector]);
496
    }
497
 
498
    // promise-support
499
    return new Promise(function (resolve, reject) {
500
      origGetStats.apply(_this5, [function (response) {
501
        resolve(makeMapStats(fixChromeStats_(response)));
502
      }, reject]);
503
    }).then(onSucc, onErr);
504
  };
505
}
506
 
507
function shimSenderReceiverGetStats(window) {
508
  if (!((typeof window === 'undefined' ? 'undefined' : _typeof(window)) === 'object' && window.RTCPeerConnection && window.RTCRtpSender && window.RTCRtpReceiver)) {
509
    return;
510
  }
511
 
512
  // shim sender stats.
513
  if (!('getStats' in window.RTCRtpSender.prototype)) {
514
    var origGetSenders = window.RTCPeerConnection.prototype.getSenders;
515
    if (origGetSenders) {
516
      window.RTCPeerConnection.prototype.getSenders = function getSenders() {
517
        var _this6 = this;
518
 
519
        var senders = origGetSenders.apply(this, []);
520
        senders.forEach(function (sender) {
521
          return sender._pc = _this6;
522
        });
523
        return senders;
524
      };
525
    }
526
 
527
    var origAddTrack = window.RTCPeerConnection.prototype.addTrack;
528
    if (origAddTrack) {
529
      window.RTCPeerConnection.prototype.addTrack = function addTrack() {
530
        var sender = origAddTrack.apply(this, arguments);
531
        sender._pc = this;
532
        return sender;
533
      };
534
    }
535
    window.RTCRtpSender.prototype.getStats = function getStats() {
536
      var sender = this;
537
      return this._pc.getStats().then(function (result) {
538
        return (
539
          /* Note: this will include stats of all senders that
540
           *   send a track with the same id as sender.track as
541
           *   it is not possible to identify the RTCRtpSender.
542
           */
543
          utils.filterStats(result, sender.track, true)
544
        );
545
      });
546
    };
547
  }
548
 
549
  // shim receiver stats.
550
  if (!('getStats' in window.RTCRtpReceiver.prototype)) {
551
    var origGetReceivers = window.RTCPeerConnection.prototype.getReceivers;
552
    if (origGetReceivers) {
553
      window.RTCPeerConnection.prototype.getReceivers = function getReceivers() {
554
        var _this7 = this;
555
 
556
        var receivers = origGetReceivers.apply(this, []);
557
        receivers.forEach(function (receiver) {
558
          return receiver._pc = _this7;
559
        });
560
        return receivers;
561
      };
562
    }
563
    utils.wrapPeerConnectionEvent(window, 'track', function (e) {
564
      e.receiver._pc = e.srcElement;
565
      return e;
566
    });
567
    window.RTCRtpReceiver.prototype.getStats = function getStats() {
568
      var receiver = this;
569
      return this._pc.getStats().then(function (result) {
570
        return utils.filterStats(result, receiver.track, false);
571
      });
572
    };
573
  }
574
 
575
  if (!('getStats' in window.RTCRtpSender.prototype && 'getStats' in window.RTCRtpReceiver.prototype)) {
576
    return;
577
  }
578
 
579
  // shim RTCPeerConnection.getStats(track).
580
  var origGetStats = window.RTCPeerConnection.prototype.getStats;
581
  window.RTCPeerConnection.prototype.getStats = function getStats() {
582
    if (arguments.length > 0 && arguments[0] instanceof window.MediaStreamTrack) {
583
      var track = arguments[0];
584
      var sender = void 0;
585
      var receiver = void 0;
586
      var err = void 0;
587
      this.getSenders().forEach(function (s) {
588
        if (s.track === track) {
589
          if (sender) {
590
            err = true;
591
          } else {
592
            sender = s;
593
          }
594
        }
595
      });
596
      this.getReceivers().forEach(function (r) {
597
        if (r.track === track) {
598
          if (receiver) {
599
            err = true;
600
          } else {
601
            receiver = r;
602
          }
603
        }
604
        return r.track === track;
605
      });
606
      if (err || sender && receiver) {
607
        return Promise.reject(new DOMException('There are more than one sender or receiver for the track.', 'InvalidAccessError'));
608
      } else if (sender) {
609
        return sender.getStats();
610
      } else if (receiver) {
611
        return receiver.getStats();
612
      }
613
      return Promise.reject(new DOMException('There is no sender or receiver for the track.', 'InvalidAccessError'));
614
    }
615
    return origGetStats.apply(this, arguments);
616
  };
617
}
618
 
619
function shimAddTrackRemoveTrackWithNative(window) {
620
  // shim addTrack/removeTrack with native variants in order to make
621
  // the interactions with legacy getLocalStreams behave as in other browsers.
622
  // Keeps a mapping stream.id => [stream, rtpsenders...]
623
  window.RTCPeerConnection.prototype.getLocalStreams = function getLocalStreams() {
624
    var _this8 = this;
625
 
626
    this._shimmedLocalStreams = this._shimmedLocalStreams || {};
627
    return Object.keys(this._shimmedLocalStreams).map(function (streamId) {
628
      return _this8._shimmedLocalStreams[streamId][0];
629
    });
630
  };
631
 
632
  var origAddTrack = window.RTCPeerConnection.prototype.addTrack;
633
  window.RTCPeerConnection.prototype.addTrack = function addTrack(track, stream) {
634
    if (!stream) {
635
      return origAddTrack.apply(this, arguments);
636
    }
637
    this._shimmedLocalStreams = this._shimmedLocalStreams || {};
638
 
639
    var sender = origAddTrack.apply(this, arguments);
640
    if (!this._shimmedLocalStreams[stream.id]) {
641
      this._shimmedLocalStreams[stream.id] = [stream, sender];
642
    } else if (this._shimmedLocalStreams[stream.id].indexOf(sender) === -1) {
643
      this._shimmedLocalStreams[stream.id].push(sender);
644
    }
645
    return sender;
646
  };
647
 
648
  var origAddStream = window.RTCPeerConnection.prototype.addStream;
649
  window.RTCPeerConnection.prototype.addStream = function addStream(stream) {
650
    var _this9 = this;
651
 
652
    this._shimmedLocalStreams = this._shimmedLocalStreams || {};
653
 
654
    stream.getTracks().forEach(function (track) {
655
      var alreadyExists = _this9.getSenders().find(function (s) {
656
        return s.track === track;
657
      });
658
      if (alreadyExists) {
659
        throw new DOMException('Track already exists.', 'InvalidAccessError');
660
      }
661
    });
662
    var existingSenders = this.getSenders();
663
    origAddStream.apply(this, arguments);
664
    var newSenders = this.getSenders().filter(function (newSender) {
665
      return existingSenders.indexOf(newSender) === -1;
666
    });
667
    this._shimmedLocalStreams[stream.id] = [stream].concat(newSenders);
668
  };
669
 
670
  var origRemoveStream = window.RTCPeerConnection.prototype.removeStream;
671
  window.RTCPeerConnection.prototype.removeStream = function removeStream(stream) {
672
    this._shimmedLocalStreams = this._shimmedLocalStreams || {};
673
    delete this._shimmedLocalStreams[stream.id];
674
    return origRemoveStream.apply(this, arguments);
675
  };
676
 
677
  var origRemoveTrack = window.RTCPeerConnection.prototype.removeTrack;
678
  window.RTCPeerConnection.prototype.removeTrack = function removeTrack(sender) {
679
    var _this10 = this;
680
 
681
    this._shimmedLocalStreams = this._shimmedLocalStreams || {};
682
    if (sender) {
683
      Object.keys(this._shimmedLocalStreams).forEach(function (streamId) {
684
        var idx = _this10._shimmedLocalStreams[streamId].indexOf(sender);
685
        if (idx !== -1) {
686
          _this10._shimmedLocalStreams[streamId].splice(idx, 1);
687
        }
688
        if (_this10._shimmedLocalStreams[streamId].length === 1) {
689
          delete _this10._shimmedLocalStreams[streamId];
690
        }
691
      });
692
    }
693
    return origRemoveTrack.apply(this, arguments);
694
  };
695
}
696
 
697
function shimAddTrackRemoveTrack(window, browserDetails) {
698
  if (!window.RTCPeerConnection) {
699
    return;
700
  }
701
  // shim addTrack and removeTrack.
702
  if (window.RTCPeerConnection.prototype.addTrack && browserDetails.version >= 65) {
703
    return shimAddTrackRemoveTrackWithNative(window);
704
  }
705
 
706
  // also shim pc.getLocalStreams when addTrack is shimmed
707
  // to return the original streams.
708
  var origGetLocalStreams = window.RTCPeerConnection.prototype.getLocalStreams;
709
  window.RTCPeerConnection.prototype.getLocalStreams = function getLocalStreams() {
710
    var _this11 = this;
711
 
712
    var nativeStreams = origGetLocalStreams.apply(this);
713
    this._reverseStreams = this._reverseStreams || {};
714
    return nativeStreams.map(function (stream) {
715
      return _this11._reverseStreams[stream.id];
716
    });
717
  };
718
 
719
  var origAddStream = window.RTCPeerConnection.prototype.addStream;
720
  window.RTCPeerConnection.prototype.addStream = function addStream(stream) {
721
    var _this12 = this;
722
 
723
    this._streams = this._streams || {};
724
    this._reverseStreams = this._reverseStreams || {};
725
 
726
    stream.getTracks().forEach(function (track) {
727
      var alreadyExists = _this12.getSenders().find(function (s) {
728
        return s.track === track;
729
      });
730
      if (alreadyExists) {
731
        throw new DOMException('Track already exists.', 'InvalidAccessError');
732
      }
733
    });
734
    // Add identity mapping for consistency with addTrack.
735
    // Unless this is being used with a stream from addTrack.
736
    if (!this._reverseStreams[stream.id]) {
737
      var newStream = new window.MediaStream(stream.getTracks());
738
      this._streams[stream.id] = newStream;
739
      this._reverseStreams[newStream.id] = stream;
740
      stream = newStream;
741
    }
742
    origAddStream.apply(this, [stream]);
743
  };
744
 
745
  var origRemoveStream = window.RTCPeerConnection.prototype.removeStream;
746
  window.RTCPeerConnection.prototype.removeStream = function removeStream(stream) {
747
    this._streams = this._streams || {};
748
    this._reverseStreams = this._reverseStreams || {};
749
 
750
    origRemoveStream.apply(this, [this._streams[stream.id] || stream]);
751
    delete this._reverseStreams[this._streams[stream.id] ? this._streams[stream.id].id : stream.id];
752
    delete this._streams[stream.id];
753
  };
754
 
755
  window.RTCPeerConnection.prototype.addTrack = function addTrack(track, stream) {
756
    var _this13 = this;
757
 
758
    if (this.signalingState === 'closed') {
759
      throw new DOMException('The RTCPeerConnection\'s signalingState is \'closed\'.', 'InvalidStateError');
760
    }
761
    var streams = [].slice.call(arguments, 1);
762
    if (streams.length !== 1 || !streams[0].getTracks().find(function (t) {
763
      return t === track;
764
    })) {
765
      // this is not fully correct but all we can manage without
766
      // [[associated MediaStreams]] internal slot.
767
      throw new DOMException('The adapter.js addTrack polyfill only supports a single ' + ' stream which is associated with the specified track.', 'NotSupportedError');
768
    }
769
 
770
    var alreadyExists = this.getSenders().find(function (s) {
771
      return s.track === track;
772
    });
773
    if (alreadyExists) {
774
      throw new DOMException('Track already exists.', 'InvalidAccessError');
775
    }
776
 
777
    this._streams = this._streams || {};
778
    this._reverseStreams = this._reverseStreams || {};
779
    var oldStream = this._streams[stream.id];
780
    if (oldStream) {
781
      // this is using odd Chrome behaviour, use with caution:
782
      // https://bugs.chromium.org/p/webrtc/issues/detail?id=7815
783
      // Note: we rely on the high-level addTrack/dtmf shim to
784
      // create the sender with a dtmf sender.
785
      oldStream.addTrack(track);
786
 
787
      // Trigger ONN async.
788
      Promise.resolve().then(function () {
789
        _this13.dispatchEvent(new Event('negotiationneeded'));
790
      });
791
    } else {
792
      var newStream = new window.MediaStream([track]);
793
      this._streams[stream.id] = newStream;
794
      this._reverseStreams[newStream.id] = stream;
795
      this.addStream(newStream);
796
    }
797
    return this.getSenders().find(function (s) {
798
      return s.track === track;
799
    });
800
  };
801
 
802
  // replace the internal stream id with the external one and
803
  // vice versa.
804
  function replaceInternalStreamId(pc, description) {
805
    var sdp = description.sdp;
806
    Object.keys(pc._reverseStreams || []).forEach(function (internalId) {
807
      var externalStream = pc._reverseStreams[internalId];
808
      var internalStream = pc._streams[externalStream.id];
809
      sdp = sdp.replace(new RegExp(internalStream.id, 'g'), externalStream.id);
810
    });
811
    return new RTCSessionDescription({
812
      type: description.type,
813
      sdp: sdp
814
    });
815
  }
816
  function replaceExternalStreamId(pc, description) {
817
    var sdp = description.sdp;
818
    Object.keys(pc._reverseStreams || []).forEach(function (internalId) {
819
      var externalStream = pc._reverseStreams[internalId];
820
      var internalStream = pc._streams[externalStream.id];
821
      sdp = sdp.replace(new RegExp(externalStream.id, 'g'), internalStream.id);
822
    });
823
    return new RTCSessionDescription({
824
      type: description.type,
825
      sdp: sdp
826
    });
827
  }
828
  ['createOffer', 'createAnswer'].forEach(function (method) {
829
    var nativeMethod = window.RTCPeerConnection.prototype[method];
830
    var methodObj = _defineProperty({}, method, function () {
831
      var _this14 = this;
832
 
833
      var args = arguments;
834
      var isLegacyCall = arguments.length && typeof arguments[0] === 'function';
835
      if (isLegacyCall) {
836
        return nativeMethod.apply(this, [function (description) {
837
          var desc = replaceInternalStreamId(_this14, description);
838
          args[0].apply(null, [desc]);
839
        }, function (err) {
840
          if (args[1]) {
841
            args[1].apply(null, err);
842
          }
843
        }, arguments[2]]);
844
      }
845
      return nativeMethod.apply(this, arguments).then(function (description) {
846
        return replaceInternalStreamId(_this14, description);
847
      });
848
    });
849
    window.RTCPeerConnection.prototype[method] = methodObj[method];
850
  });
851
 
852
  var origSetLocalDescription = window.RTCPeerConnection.prototype.setLocalDescription;
853
  window.RTCPeerConnection.prototype.setLocalDescription = function setLocalDescription() {
854
    if (!arguments.length || !arguments[0].type) {
855
      return origSetLocalDescription.apply(this, arguments);
856
    }
857
    arguments[0] = replaceExternalStreamId(this, arguments[0]);
858
    return origSetLocalDescription.apply(this, arguments);
859
  };
860
 
861
  // TODO: mangle getStats: https://w3c.github.io/webrtc-stats/#dom-rtcmediastreamstats-streamidentifier
862
 
863
  var origLocalDescription = Object.getOwnPropertyDescriptor(window.RTCPeerConnection.prototype, 'localDescription');
864
  Object.defineProperty(window.RTCPeerConnection.prototype, 'localDescription', {
865
    get: function get() {
866
      var description = origLocalDescription.get.apply(this);
867
      if (description.type === '') {
868
        return description;
869
      }
870
      return replaceInternalStreamId(this, description);
871
    }
872
  });
873
 
874
  window.RTCPeerConnection.prototype.removeTrack = function removeTrack(sender) {
875
    var _this15 = this;
876
 
877
    if (this.signalingState === 'closed') {
878
      throw new DOMException('The RTCPeerConnection\'s signalingState is \'closed\'.', 'InvalidStateError');
879
    }
880
    // We can not yet check for sender instanceof RTCRtpSender
881
    // since we shim RTPSender. So we check if sender._pc is set.
882
    if (!sender._pc) {
883
      throw new DOMException('Argument 1 of RTCPeerConnection.removeTrack ' + 'does not implement interface RTCRtpSender.', 'TypeError');
884
    }
885
    var isLocal = sender._pc === this;
886
    if (!isLocal) {
887
      throw new DOMException('Sender was not created by this connection.', 'InvalidAccessError');
888
    }
889
 
890
    // Search for the native stream the senders track belongs to.
891
    this._streams = this._streams || {};
892
    var stream = void 0;
893
    Object.keys(this._streams).forEach(function (streamid) {
894
      var hasTrack = _this15._streams[streamid].getTracks().find(function (track) {
895
        return sender.track === track;
896
      });
897
      if (hasTrack) {
898
        stream = _this15._streams[streamid];
899
      }
900
    });
901
 
902
    if (stream) {
903
      if (stream.getTracks().length === 1) {
904
        // if this is the last track of the stream, remove the stream. This
905
        // takes care of any shimmed _senders.
906
        this.removeStream(this._reverseStreams[stream.id]);
907
      } else {
908
        // relying on the same odd chrome behaviour as above.
909
        stream.removeTrack(sender.track);
910
      }
911
      this.dispatchEvent(new Event('negotiationneeded'));
912
    }
913
  };
914
}
915
 
916
function shimPeerConnection(window, browserDetails) {
917
  if (!window.RTCPeerConnection && window.webkitRTCPeerConnection) {
918
    // very basic support for old versions.
919
    window.RTCPeerConnection = window.webkitRTCPeerConnection;
920
  }
921
  if (!window.RTCPeerConnection) {
922
    return;
923
  }
924
 
925
  // shim implicit creation of RTCSessionDescription/RTCIceCandidate
926
  if (browserDetails.version < 53) {
927
    ['setLocalDescription', 'setRemoteDescription', 'addIceCandidate'].forEach(function (method) {
928
      var nativeMethod = window.RTCPeerConnection.prototype[method];
929
      var methodObj = _defineProperty({}, method, function () {
930
        arguments[0] = new (method === 'addIceCandidate' ? window.RTCIceCandidate : window.RTCSessionDescription)(arguments[0]);
931
        return nativeMethod.apply(this, arguments);
932
      });
933
      window.RTCPeerConnection.prototype[method] = methodObj[method];
934
    });
935
  }
936
}
937
 
938
// Attempt to fix ONN in plan-b mode.
939
function fixNegotiationNeeded(window, browserDetails) {
940
  utils.wrapPeerConnectionEvent(window, 'negotiationneeded', function (e) {
941
    var pc = e.target;
942
    if (browserDetails.version < 72 || pc.getConfiguration && pc.getConfiguration().sdpSemantics === 'plan-b') {
943
      if (pc.signalingState !== 'stable') {
944
        return;
945
      }
946
    }
947
    return e;
948
  });
949
}
950
 
951
},{"../utils.js":11,"./getdisplaymedia":4,"./getusermedia":5}],4:[function(require,module,exports){
952
/*
953
 *  Copyright (c) 2018 The adapter.js project authors. All Rights Reserved.
954
 *
955
 *  Use of this source code is governed by a BSD-style license
956
 *  that can be found in the LICENSE file in the root of the source
957
 *  tree.
958
 */
959
/* eslint-env node */
960
'use strict';
961
 
962
Object.defineProperty(exports, "__esModule", {
963
  value: true
964
});
965
exports.shimGetDisplayMedia = shimGetDisplayMedia;
966
function shimGetDisplayMedia(window, getSourceId) {
967
  if (window.navigator.mediaDevices && 'getDisplayMedia' in window.navigator.mediaDevices) {
968
    return;
969
  }
970
  if (!window.navigator.mediaDevices) {
971
    return;
972
  }
973
  // getSourceId is a function that returns a promise resolving with
974
  // the sourceId of the screen/window/tab to be shared.
975
  if (typeof getSourceId !== 'function') {
976
    console.error('shimGetDisplayMedia: getSourceId argument is not ' + 'a function');
977
    return;
978
  }
979
  window.navigator.mediaDevices.getDisplayMedia = function getDisplayMedia(constraints) {
980
    return getSourceId(constraints).then(function (sourceId) {
981
      var widthSpecified = constraints.video && constraints.video.width;
982
      var heightSpecified = constraints.video && constraints.video.height;
983
      var frameRateSpecified = constraints.video && constraints.video.frameRate;
984
      constraints.video = {
985
        mandatory: {
986
          chromeMediaSource: 'desktop',
987
          chromeMediaSourceId: sourceId,
988
          maxFrameRate: frameRateSpecified || 3
989
        }
990
      };
991
      if (widthSpecified) {
992
        constraints.video.mandatory.maxWidth = widthSpecified;
993
      }
994
      if (heightSpecified) {
995
        constraints.video.mandatory.maxHeight = heightSpecified;
996
      }
997
      return window.navigator.mediaDevices.getUserMedia(constraints);
998
    });
999
  };
1000
}
1001
 
1002
},{}],5:[function(require,module,exports){
1003
/*
1004
 *  Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
1005
 *
1006
 *  Use of this source code is governed by a BSD-style license
1007
 *  that can be found in the LICENSE file in the root of the source
1008
 *  tree.
1009
 */
1010
/* eslint-env node */
1011
'use strict';
1012
 
1013
Object.defineProperty(exports, "__esModule", {
1014
  value: true
1015
});
1016
 
1017
var _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; };
1018
 
1019
exports.shimGetUserMedia = shimGetUserMedia;
1020
 
1021
var _utils = require('../utils.js');
1022
 
1023
var utils = _interopRequireWildcard(_utils);
1024
 
1025
function _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; } }
1026
 
1027
var logging = utils.log;
1028
 
1029
function shimGetUserMedia(window, browserDetails) {
1030
  var navigator = window && window.navigator;
1031
 
1032
  if (!navigator.mediaDevices) {
1033
    return;
1034
  }
1035
 
1036
  var constraintsToChrome_ = function constraintsToChrome_(c) {
1037
    if ((typeof c === 'undefined' ? 'undefined' : _typeof(c)) !== 'object' || c.mandatory || c.optional) {
1038
      return c;
1039
    }
1040
    var cc = {};
1041
    Object.keys(c).forEach(function (key) {
1042
      if (key === 'require' || key === 'advanced' || key === 'mediaSource') {
1043
        return;
1044
      }
1045
      var r = _typeof(c[key]) === 'object' ? c[key] : { ideal: c[key] };
1046
      if (r.exact !== undefined && typeof r.exact === 'number') {
1047
        r.min = r.max = r.exact;
1048
      }
1049
      var oldname_ = function oldname_(prefix, name) {
1050
        if (prefix) {
1051
          return prefix + name.charAt(0).toUpperCase() + name.slice(1);
1052
        }
1053
        return name === 'deviceId' ? 'sourceId' : name;
1054
      };
1055
      if (r.ideal !== undefined) {
1056
        cc.optional = cc.optional || [];
1057
        var oc = {};
1058
        if (typeof r.ideal === 'number') {
1059
          oc[oldname_('min', key)] = r.ideal;
1060
          cc.optional.push(oc);
1061
          oc = {};
1062
          oc[oldname_('max', key)] = r.ideal;
1063
          cc.optional.push(oc);
1064
        } else {
1065
          oc[oldname_('', key)] = r.ideal;
1066
          cc.optional.push(oc);
1067
        }
1068
      }
1069
      if (r.exact !== undefined && typeof r.exact !== 'number') {
1070
        cc.mandatory = cc.mandatory || {};
1071
        cc.mandatory[oldname_('', key)] = r.exact;
1072
      } else {
1073
        ['min', 'max'].forEach(function (mix) {
1074
          if (r[mix] !== undefined) {
1075
            cc.mandatory = cc.mandatory || {};
1076
            cc.mandatory[oldname_(mix, key)] = r[mix];
1077
          }
1078
        });
1079
      }
1080
    });
1081
    if (c.advanced) {
1082
      cc.optional = (cc.optional || []).concat(c.advanced);
1083
    }
1084
    return cc;
1085
  };
1086
 
1087
  var shimConstraints_ = function shimConstraints_(constraints, func) {
1088
    if (browserDetails.version >= 61) {
1089
      return func(constraints);
1090
    }
1091
    constraints = JSON.parse(JSON.stringify(constraints));
1092
    if (constraints && _typeof(constraints.audio) === 'object') {
1093
      var remap = function remap(obj, a, b) {
1094
        if (a in obj && !(b in obj)) {
1095
          obj[b] = obj[a];
1096
          delete obj[a];
1097
        }
1098
      };
1099
      constraints = JSON.parse(JSON.stringify(constraints));
1100
      remap(constraints.audio, 'autoGainControl', 'googAutoGainControl');
1101
      remap(constraints.audio, 'noiseSuppression', 'googNoiseSuppression');
1102
      constraints.audio = constraintsToChrome_(constraints.audio);
1103
    }
1104
    if (constraints && _typeof(constraints.video) === 'object') {
1105
      // Shim facingMode for mobile & surface pro.
1106
      var face = constraints.video.facingMode;
1107
      face = face && ((typeof face === 'undefined' ? 'undefined' : _typeof(face)) === 'object' ? face : { ideal: face });
1108
      var getSupportedFacingModeLies = browserDetails.version < 66;
1109
 
1110
      if (face && (face.exact === 'user' || face.exact === 'environment' || face.ideal === 'user' || face.ideal === 'environment') && !(navigator.mediaDevices.getSupportedConstraints && navigator.mediaDevices.getSupportedConstraints().facingMode && !getSupportedFacingModeLies)) {
1111
        delete constraints.video.facingMode;
1112
        var matches = void 0;
1113
        if (face.exact === 'environment' || face.ideal === 'environment') {
1114
          matches = ['back', 'rear'];
1115
        } else if (face.exact === 'user' || face.ideal === 'user') {
1116
          matches = ['front'];
1117
        }
1118
        if (matches) {
1119
          // Look for matches in label, or use last cam for back (typical).
1120
          return navigator.mediaDevices.enumerateDevices().then(function (devices) {
1121
            devices = devices.filter(function (d) {
1122
              return d.kind === 'videoinput';
1123
            });
1124
            var dev = devices.find(function (d) {
1125
              return matches.some(function (match) {
1126
                return d.label.toLowerCase().includes(match);
1127
              });
1128
            });
1129
            if (!dev && devices.length && matches.includes('back')) {
1130
              dev = devices[devices.length - 1]; // more likely the back cam
1131
            }
1132
            if (dev) {
1133
              constraints.video.deviceId = face.exact ? { exact: dev.deviceId } : { ideal: dev.deviceId };
1134
            }
1135
            constraints.video = constraintsToChrome_(constraints.video);
1136
            logging('chrome: ' + JSON.stringify(constraints));
1137
            return func(constraints);
1138
          });
1139
        }
1140
      }
1141
      constraints.video = constraintsToChrome_(constraints.video);
1142
    }
1143
    logging('chrome: ' + JSON.stringify(constraints));
1144
    return func(constraints);
1145
  };
1146
 
1147
  var shimError_ = function shimError_(e) {
1148
    if (browserDetails.version >= 64) {
1149
      return e;
1150
    }
1151
    return {
1152
      name: {
1153
        PermissionDeniedError: 'NotAllowedError',
1154
        PermissionDismissedError: 'NotAllowedError',
1155
        InvalidStateError: 'NotAllowedError',
1156
        DevicesNotFoundError: 'NotFoundError',
1157
        ConstraintNotSatisfiedError: 'OverconstrainedError',
1158
        TrackStartError: 'NotReadableError',
1159
        MediaDeviceFailedDueToShutdown: 'NotAllowedError',
1160
        MediaDeviceKillSwitchOn: 'NotAllowedError',
1161
        TabCaptureError: 'AbortError',
1162
        ScreenCaptureError: 'AbortError',
1163
        DeviceCaptureError: 'AbortError'
1164
      }[e.name] || e.name,
1165
      message: e.message,
1166
      constraint: e.constraint || e.constraintName,
1167
      toString: function toString() {
1168
        return this.name + (this.message && ': ') + this.message;
1169
      }
1170
    };
1171
  };
1172
 
1173
  var getUserMedia_ = function getUserMedia_(constraints, onSuccess, onError) {
1174
    shimConstraints_(constraints, function (c) {
1175
      navigator.webkitGetUserMedia(c, onSuccess, function (e) {
1176
        if (onError) {
1177
          onError(shimError_(e));
1178
        }
1179
      });
1180
    });
1181
  };
1182
  navigator.getUserMedia = getUserMedia_.bind(navigator);
1183
 
1184
  // Even though Chrome 45 has navigator.mediaDevices and a getUserMedia
1185
  // function which returns a Promise, it does not accept spec-style
1186
  // constraints.
1187
  if (navigator.mediaDevices.getUserMedia) {
1188
    var origGetUserMedia = navigator.mediaDevices.getUserMedia.bind(navigator.mediaDevices);
1189
    navigator.mediaDevices.getUserMedia = function (cs) {
1190
      return shimConstraints_(cs, function (c) {
1191
        return origGetUserMedia(c).then(function (stream) {
1192
          if (c.audio && !stream.getAudioTracks().length || c.video && !stream.getVideoTracks().length) {
1193
            stream.getTracks().forEach(function (track) {
1194
              track.stop();
1195
            });
1196
            throw new DOMException('', 'NotFoundError');
1197
          }
1198
          return stream;
1199
        }, function (e) {
1200
          return Promise.reject(shimError_(e));
1201
        });
1202
      });
1203
    };
1204
  }
1205
}
1206
 
1207
},{"../utils.js":11}],6:[function(require,module,exports){
1208
/*
1209
 *  Copyright (c) 2017 The WebRTC project authors. All Rights Reserved.
1210
 *
1211
 *  Use of this source code is governed by a BSD-style license
1212
 *  that can be found in the LICENSE file in the root of the source
1213
 *  tree.
1214
 */
1215
/* eslint-env node */
1216
'use strict';
1217
 
1218
Object.defineProperty(exports, "__esModule", {
1219
  value: true
1220
});
1221
 
1222
var _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; };
1223
 
1224
exports.shimRTCIceCandidate = shimRTCIceCandidate;
1225
exports.shimMaxMessageSize = shimMaxMessageSize;
1226
exports.shimSendThrowTypeError = shimSendThrowTypeError;
1227
exports.shimConnectionState = shimConnectionState;
1228
exports.removeExtmapAllowMixed = removeExtmapAllowMixed;
1229
exports.shimAddIceCandidateNullOrEmpty = shimAddIceCandidateNullOrEmpty;
1230
 
1231
var _sdp = require('sdp');
1232
 
1233
var _sdp2 = _interopRequireDefault(_sdp);
1234
 
1235
var _utils = require('./utils');
1236
 
1237
var utils = _interopRequireWildcard(_utils);
1238
 
1239
function _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; } }
1240
 
1241
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
1242
 
1243
function shimRTCIceCandidate(window) {
1244
  // foundation is arbitrarily chosen as an indicator for full support for
1245
  // https://w3c.github.io/webrtc-pc/#rtcicecandidate-interface
1246
  if (!window.RTCIceCandidate || window.RTCIceCandidate && 'foundation' in window.RTCIceCandidate.prototype) {
1247
    return;
1248
  }
1249
 
1250
  var NativeRTCIceCandidate = window.RTCIceCandidate;
1251
  window.RTCIceCandidate = function RTCIceCandidate(args) {
1252
    // Remove the a= which shouldn't be part of the candidate string.
1253
    if ((typeof args === 'undefined' ? 'undefined' : _typeof(args)) === 'object' && args.candidate && args.candidate.indexOf('a=') === 0) {
1254
      args = JSON.parse(JSON.stringify(args));
1255
      args.candidate = args.candidate.substr(2);
1256
    }
1257
 
1258
    if (args.candidate && args.candidate.length) {
1259
      // Augment the native candidate with the parsed fields.
1260
      var nativeCandidate = new NativeRTCIceCandidate(args);
1261
      var parsedCandidate = _sdp2.default.parseCandidate(args.candidate);
1262
      var augmentedCandidate = Object.assign(nativeCandidate, parsedCandidate);
1263
 
1264
      // Add a serializer that does not serialize the extra attributes.
1265
      augmentedCandidate.toJSON = function toJSON() {
1266
        return {
1267
          candidate: augmentedCandidate.candidate,
1268
          sdpMid: augmentedCandidate.sdpMid,
1269
          sdpMLineIndex: augmentedCandidate.sdpMLineIndex,
1270
          usernameFragment: augmentedCandidate.usernameFragment
1271
        };
1272
      };
1273
      return augmentedCandidate;
1274
    }
1275
    return new NativeRTCIceCandidate(args);
1276
  };
1277
  window.RTCIceCandidate.prototype = NativeRTCIceCandidate.prototype;
1278
 
1279
  // Hook up the augmented candidate in onicecandidate and
1280
  // addEventListener('icecandidate', ...)
1281
  utils.wrapPeerConnectionEvent(window, 'icecandidate', function (e) {
1282
    if (e.candidate) {
1283
      Object.defineProperty(e, 'candidate', {
1284
        value: new window.RTCIceCandidate(e.candidate),
1285
        writable: 'false'
1286
      });
1287
    }
1288
    return e;
1289
  });
1290
}
1291
 
1292
function shimMaxMessageSize(window, browserDetails) {
1293
  if (!window.RTCPeerConnection) {
1294
    return;
1295
  }
1296
 
1297
  if (!('sctp' in window.RTCPeerConnection.prototype)) {
1298
    Object.defineProperty(window.RTCPeerConnection.prototype, 'sctp', {
1299
      get: function get() {
1300
        return typeof this._sctp === 'undefined' ? null : this._sctp;
1301
      }
1302
    });
1303
  }
1304
 
1305
  var sctpInDescription = function sctpInDescription(description) {
1306
    if (!description || !description.sdp) {
1307
      return false;
1308
    }
1309
    var sections = _sdp2.default.splitSections(description.sdp);
1310
    sections.shift();
1311
    return sections.some(function (mediaSection) {
1312
      var mLine = _sdp2.default.parseMLine(mediaSection);
1313
      return mLine && mLine.kind === 'application' && mLine.protocol.indexOf('SCTP') !== -1;
1314
    });
1315
  };
1316
 
1317
  var getRemoteFirefoxVersion = function getRemoteFirefoxVersion(description) {
1318
    // TODO: Is there a better solution for detecting Firefox?
1319
    var match = description.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);
1320
    if (match === null || match.length < 2) {
1321
      return -1;
1322
    }
1323
    var version = parseInt(match[1], 10);
1324
    // Test for NaN (yes, this is ugly)
1325
    return version !== version ? -1 : version;
1326
  };
1327
 
1328
  var getCanSendMaxMessageSize = function getCanSendMaxMessageSize(remoteIsFirefox) {
1329
    // Every implementation we know can send at least 64 KiB.
1330
    // Note: Although Chrome is technically able to send up to 256 KiB, the
1331
    //       data does not reach the other peer reliably.
1332
    //       See: https://bugs.chromium.org/p/webrtc/issues/detail?id=8419
1333
    var canSendMaxMessageSize = 65536;
1334
    if (browserDetails.browser === 'firefox') {
1335
      if (browserDetails.version < 57) {
1336
        if (remoteIsFirefox === -1) {
1337
          // FF < 57 will send in 16 KiB chunks using the deprecated PPID
1338
          // fragmentation.
1339
          canSendMaxMessageSize = 16384;
1340
        } else {
1341
          // However, other FF (and RAWRTC) can reassemble PPID-fragmented
1342
          // messages. Thus, supporting ~2 GiB when sending.
1343
          canSendMaxMessageSize = 2147483637;
1344
        }
1345
      } else if (browserDetails.version < 60) {
1346
        // Currently, all FF >= 57 will reset the remote maximum message size
1347
        // to the default value when a data channel is created at a later
1348
        // stage. :(
1349
        // See: https://bugzilla.mozilla.org/show_bug.cgi?id=1426831
1350
        canSendMaxMessageSize = browserDetails.version === 57 ? 65535 : 65536;
1351
      } else {
1352
        // FF >= 60 supports sending ~2 GiB
1353
        canSendMaxMessageSize = 2147483637;
1354
      }
1355
    }
1356
    return canSendMaxMessageSize;
1357
  };
1358
 
1359
  var getMaxMessageSize = function getMaxMessageSize(description, remoteIsFirefox) {
1360
    // Note: 65536 bytes is the default value from the SDP spec. Also,
1361
    //       every implementation we know supports receiving 65536 bytes.
1362
    var maxMessageSize = 65536;
1363
 
1364
    // FF 57 has a slightly incorrect default remote max message size, so
1365
    // we need to adjust it here to avoid a failure when sending.
1366
    // See: https://bugzilla.mozilla.org/show_bug.cgi?id=1425697
1367
    if (browserDetails.browser === 'firefox' && browserDetails.version === 57) {
1368
      maxMessageSize = 65535;
1369
    }
1370
 
1371
    var match = _sdp2.default.matchPrefix(description.sdp, 'a=max-message-size:');
1372
    if (match.length > 0) {
1373
      maxMessageSize = parseInt(match[0].substr(19), 10);
1374
    } else if (browserDetails.browser === 'firefox' && remoteIsFirefox !== -1) {
1375
      // If the maximum message size is not present in the remote SDP and
1376
      // both local and remote are Firefox, the remote peer can receive
1377
      // ~2 GiB.
1378
      maxMessageSize = 2147483637;
1379
    }
1380
    return maxMessageSize;
1381
  };
1382
 
1383
  var origSetRemoteDescription = window.RTCPeerConnection.prototype.setRemoteDescription;
1384
  window.RTCPeerConnection.prototype.setRemoteDescription = function setRemoteDescription() {
1385
    this._sctp = null;
1386
    // Chrome decided to not expose .sctp in plan-b mode.
1387
    // As usual, adapter.js has to do an 'ugly worakaround'
1388
    // to cover up the mess.
1389
    if (browserDetails.browser === 'chrome' && browserDetails.version >= 76) {
1390
      var _getConfiguration = this.getConfiguration(),
1391
          sdpSemantics = _getConfiguration.sdpSemantics;
1392
 
1393
      if (sdpSemantics === 'plan-b') {
1394
        Object.defineProperty(this, 'sctp', {
1395
          get: function get() {
1396
            return typeof this._sctp === 'undefined' ? null : this._sctp;
1397
          },
1398
 
1399
          enumerable: true,
1400
          configurable: true
1401
        });
1402
      }
1403
    }
1404
 
1405
    if (sctpInDescription(arguments[0])) {
1406
      // Check if the remote is FF.
1407
      var isFirefox = getRemoteFirefoxVersion(arguments[0]);
1408
 
1409
      // Get the maximum message size the local peer is capable of sending
1410
      var canSendMMS = getCanSendMaxMessageSize(isFirefox);
1411
 
1412
      // Get the maximum message size of the remote peer.
1413
      var remoteMMS = getMaxMessageSize(arguments[0], isFirefox);
1414
 
1415
      // Determine final maximum message size
1416
      var maxMessageSize = void 0;
1417
      if (canSendMMS === 0 && remoteMMS === 0) {
1418
        maxMessageSize = Number.POSITIVE_INFINITY;
1419
      } else if (canSendMMS === 0 || remoteMMS === 0) {
1420
        maxMessageSize = Math.max(canSendMMS, remoteMMS);
1421
      } else {
1422
        maxMessageSize = Math.min(canSendMMS, remoteMMS);
1423
      }
1424
 
1425
      // Create a dummy RTCSctpTransport object and the 'maxMessageSize'
1426
      // attribute.
1427
      var sctp = {};
1428
      Object.defineProperty(sctp, 'maxMessageSize', {
1429
        get: function get() {
1430
          return maxMessageSize;
1431
        }
1432
      });
1433
      this._sctp = sctp;
1434
    }
1435
 
1436
    return origSetRemoteDescription.apply(this, arguments);
1437
  };
1438
}
1439
 
1440
function shimSendThrowTypeError(window) {
1441
  if (!(window.RTCPeerConnection && 'createDataChannel' in window.RTCPeerConnection.prototype)) {
1442
    return;
1443
  }
1444
 
1445
  // Note: Although Firefox >= 57 has a native implementation, the maximum
1446
  //       message size can be reset for all data channels at a later stage.
1447
  //       See: https://bugzilla.mozilla.org/show_bug.cgi?id=1426831
1448
 
1449
  function wrapDcSend(dc, pc) {
1450
    var origDataChannelSend = dc.send;
1451
    dc.send = function send() {
1452
      var data = arguments[0];
1453
      var length = data.length || data.size || data.byteLength;
1454
      if (dc.readyState === 'open' && pc.sctp && length > pc.sctp.maxMessageSize) {
1455
        throw new TypeError('Message too large (can send a maximum of ' + pc.sctp.maxMessageSize + ' bytes)');
1456
      }
1457
      return origDataChannelSend.apply(dc, arguments);
1458
    };
1459
  }
1460
  var origCreateDataChannel = window.RTCPeerConnection.prototype.createDataChannel;
1461
  window.RTCPeerConnection.prototype.createDataChannel = function createDataChannel() {
1462
    var dataChannel = origCreateDataChannel.apply(this, arguments);
1463
    wrapDcSend(dataChannel, this);
1464
    return dataChannel;
1465
  };
1466
  utils.wrapPeerConnectionEvent(window, 'datachannel', function (e) {
1467
    wrapDcSend(e.channel, e.target);
1468
    return e;
1469
  });
1470
}
1471
 
1472
/* shims RTCConnectionState by pretending it is the same as iceConnectionState.
1473
 * See https://bugs.chromium.org/p/webrtc/issues/detail?id=6145#c12
1474
 * for why this is a valid hack in Chrome. In Firefox it is slightly incorrect
1475
 * since DTLS failures would be hidden. See
1476
 * https://bugzilla.mozilla.org/show_bug.cgi?id=1265827
1477
 * for the Firefox tracking bug.
1478
 */
1479
function shimConnectionState(window) {
1480
  if (!window.RTCPeerConnection || 'connectionState' in window.RTCPeerConnection.prototype) {
1481
    return;
1482
  }
1483
  var proto = window.RTCPeerConnection.prototype;
1484
  Object.defineProperty(proto, 'connectionState', {
1485
    get: function get() {
1486
      return {
1487
        completed: 'connected',
1488
        checking: 'connecting'
1489
      }[this.iceConnectionState] || this.iceConnectionState;
1490
    },
1491
 
1492
    enumerable: true,
1493
    configurable: true
1494
  });
1495
  Object.defineProperty(proto, 'onconnectionstatechange', {
1496
    get: function get() {
1497
      return this._onconnectionstatechange || null;
1498
    },
1499
    set: function set(cb) {
1500
      if (this._onconnectionstatechange) {
1501
        this.removeEventListener('connectionstatechange', this._onconnectionstatechange);
1502
        delete this._onconnectionstatechange;
1503
      }
1504
      if (cb) {
1505
        this.addEventListener('connectionstatechange', this._onconnectionstatechange = cb);
1506
      }
1507
    },
1508
 
1509
    enumerable: true,
1510
    configurable: true
1511
  });
1512
 
1513
  ['setLocalDescription', 'setRemoteDescription'].forEach(function (method) {
1514
    var origMethod = proto[method];
1515
    proto[method] = function () {
1516
      if (!this._connectionstatechangepoly) {
1517
        this._connectionstatechangepoly = function (e) {
1518
          var pc = e.target;
1519
          if (pc._lastConnectionState !== pc.connectionState) {
1520
            pc._lastConnectionState = pc.connectionState;
1521
            var newEvent = new Event('connectionstatechange', e);
1522
            pc.dispatchEvent(newEvent);
1523
          }
1524
          return e;
1525
        };
1526
        this.addEventListener('iceconnectionstatechange', this._connectionstatechangepoly);
1527
      }
1528
      return origMethod.apply(this, arguments);
1529
    };
1530
  });
1531
}
1532
 
1533
function removeExtmapAllowMixed(window, browserDetails) {
1534
  /* remove a=extmap-allow-mixed for webrtc.org < M71 */
1535
  if (!window.RTCPeerConnection) {
1536
    return;
1537
  }
1538
  if (browserDetails.browser === 'chrome' && browserDetails.version >= 71) {
1539
    return;
1540
  }
1541
  if (browserDetails.browser === 'safari' && browserDetails.version >= 605) {
1542
    return;
1543
  }
1544
  var nativeSRD = window.RTCPeerConnection.prototype.setRemoteDescription;
1545
  window.RTCPeerConnection.prototype.setRemoteDescription = function setRemoteDescription(desc) {
1546
    if (desc && desc.sdp && desc.sdp.indexOf('\na=extmap-allow-mixed') !== -1) {
1547
      var sdp = desc.sdp.split('\n').filter(function (line) {
1548
        return line.trim() !== 'a=extmap-allow-mixed';
1549
      }).join('\n');
1550
      // Safari enforces read-only-ness of RTCSessionDescription fields.
1551
      if (window.RTCSessionDescription && desc instanceof window.RTCSessionDescription) {
1552
        arguments[0] = new window.RTCSessionDescription({
1553
          type: desc.type,
1554
          sdp: sdp
1555
        });
1556
      } else {
1557
        desc.sdp = sdp;
1558
      }
1559
    }
1560
    return nativeSRD.apply(this, arguments);
1561
  };
1562
}
1563
 
1564
function shimAddIceCandidateNullOrEmpty(window, browserDetails) {
1565
  // Support for addIceCandidate(null or undefined)
1566
  // as well as addIceCandidate({candidate: "", ...})
1567
  // https://bugs.chromium.org/p/chromium/issues/detail?id=978582
1568
  // Note: must be called before other polyfills which change the signature.
1569
  if (!(window.RTCPeerConnection && window.RTCPeerConnection.prototype)) {
1570
    return;
1571
  }
1572
  var nativeAddIceCandidate = window.RTCPeerConnection.prototype.addIceCandidate;
1573
  if (!nativeAddIceCandidate || nativeAddIceCandidate.length === 0) {
1574
    return;
1575
  }
1576
  window.RTCPeerConnection.prototype.addIceCandidate = function addIceCandidate() {
1577
    if (!arguments[0]) {
1578
      if (arguments[1]) {
1579
        arguments[1].apply(null);
1580
      }
1581
      return Promise.resolve();
1582
    }
1583
    // Firefox 68+ emits and processes {candidate: "", ...}, ignore
1584
    // in older versions.
1585
    // Native support for ignoring exists for Chrome M77+.
1586
    // Safari ignores as well, exact version unknown but works in the same
1587
    // version that also ignores addIceCandidate(null).
1588
    if ((browserDetails.browser === 'chrome' && browserDetails.version < 78 || browserDetails.browser === 'firefox' && browserDetails.version < 68 || browserDetails.browser === 'safari') && arguments[0] && arguments[0].candidate === '') {
1589
      return Promise.resolve();
1590
    }
1591
    return nativeAddIceCandidate.apply(this, arguments);
1592
  };
1593
}
1594
 
1595
},{"./utils":11,"sdp":12}],7:[function(require,module,exports){
1596
/*
1597
 *  Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
1598
 *
1599
 *  Use of this source code is governed by a BSD-style license
1600
 *  that can be found in the LICENSE file in the root of the source
1601
 *  tree.
1602
 */
1603
/* eslint-env node */
1604
'use strict';
1605
 
1606
Object.defineProperty(exports, "__esModule", {
1607
  value: true
1608
});
1609
exports.shimGetDisplayMedia = exports.shimGetUserMedia = undefined;
1610
 
1611
var _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; };
1612
 
1613
var _getusermedia = require('./getusermedia');
1614
 
1615
Object.defineProperty(exports, 'shimGetUserMedia', {
1616
  enumerable: true,
1617
  get: function get() {
1618
    return _getusermedia.shimGetUserMedia;
1619
  }
1620
});
1621
 
1622
var _getdisplaymedia = require('./getdisplaymedia');
1623
 
1624
Object.defineProperty(exports, 'shimGetDisplayMedia', {
1625
  enumerable: true,
1626
  get: function get() {
1627
    return _getdisplaymedia.shimGetDisplayMedia;
1628
  }
1629
});
1630
exports.shimOnTrack = shimOnTrack;
1631
exports.shimPeerConnection = shimPeerConnection;
1632
exports.shimSenderGetStats = shimSenderGetStats;
1633
exports.shimReceiverGetStats = shimReceiverGetStats;
1634
exports.shimRemoveStream = shimRemoveStream;
1635
exports.shimRTCDataChannel = shimRTCDataChannel;
1636
exports.shimAddTransceiver = shimAddTransceiver;
1637
exports.shimGetParameters = shimGetParameters;
1638
exports.shimCreateOffer = shimCreateOffer;
1639
exports.shimCreateAnswer = shimCreateAnswer;
1640
 
1641
var _utils = require('../utils');
1642
 
1643
var utils = _interopRequireWildcard(_utils);
1644
 
1645
function _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; } }
1646
 
1647
function _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; }
1648
 
1649
function shimOnTrack(window) {
1650
  if ((typeof window === 'undefined' ? 'undefined' : _typeof(window)) === 'object' && window.RTCTrackEvent && 'receiver' in window.RTCTrackEvent.prototype && !('transceiver' in window.RTCTrackEvent.prototype)) {
1651
    Object.defineProperty(window.RTCTrackEvent.prototype, 'transceiver', {
1652
      get: function get() {
1653
        return { receiver: this.receiver };
1654
      }
1655
    });
1656
  }
1657
}
1658
 
1659
function shimPeerConnection(window, browserDetails) {
1660
  if ((typeof window === 'undefined' ? 'undefined' : _typeof(window)) !== 'object' || !(window.RTCPeerConnection || window.mozRTCPeerConnection)) {
1661
    return; // probably media.peerconnection.enabled=false in about:config
1662
  }
1663
  if (!window.RTCPeerConnection && window.mozRTCPeerConnection) {
1664
    // very basic support for old versions.
1665
    window.RTCPeerConnection = window.mozRTCPeerConnection;
1666
  }
1667
 
1668
  if (browserDetails.version < 53) {
1669
    // shim away need for obsolete RTCIceCandidate/RTCSessionDescription.
1670
    ['setLocalDescription', 'setRemoteDescription', 'addIceCandidate'].forEach(function (method) {
1671
      var nativeMethod = window.RTCPeerConnection.prototype[method];
1672
      var methodObj = _defineProperty({}, method, function () {
1673
        arguments[0] = new (method === 'addIceCandidate' ? window.RTCIceCandidate : window.RTCSessionDescription)(arguments[0]);
1674
        return nativeMethod.apply(this, arguments);
1675
      });
1676
      window.RTCPeerConnection.prototype[method] = methodObj[method];
1677
    });
1678
  }
1679
 
1680
  var modernStatsTypes = {
1681
    inboundrtp: 'inbound-rtp',
1682
    outboundrtp: 'outbound-rtp',
1683
    candidatepair: 'candidate-pair',
1684
    localcandidate: 'local-candidate',
1685
    remotecandidate: 'remote-candidate'
1686
  };
1687
 
1688
  var nativeGetStats = window.RTCPeerConnection.prototype.getStats;
1689
  window.RTCPeerConnection.prototype.getStats = function getStats() {
1690
    var _arguments = Array.prototype.slice.call(arguments),
1691
        selector = _arguments[0],
1692
        onSucc = _arguments[1],
1693
        onErr = _arguments[2];
1694
 
1695
    return nativeGetStats.apply(this, [selector || null]).then(function (stats) {
1696
      if (browserDetails.version < 53 && !onSucc) {
1697
        // Shim only promise getStats with spec-hyphens in type names
1698
        // Leave callback version alone; misc old uses of forEach before Map
1699
        try {
1700
          stats.forEach(function (stat) {
1701
            stat.type = modernStatsTypes[stat.type] || stat.type;
1702
          });
1703
        } catch (e) {
1704
          if (e.name !== 'TypeError') {
1705
            throw e;
1706
          }
1707
          // Avoid TypeError: "type" is read-only, in old versions. 34-43ish
1708
          stats.forEach(function (stat, i) {
1709
            stats.set(i, Object.assign({}, stat, {
1710
              type: modernStatsTypes[stat.type] || stat.type
1711
            }));
1712
          });
1713
        }
1714
      }
1715
      return stats;
1716
    }).then(onSucc, onErr);
1717
  };
1718
}
1719
 
1720
function shimSenderGetStats(window) {
1721
  if (!((typeof window === 'undefined' ? 'undefined' : _typeof(window)) === 'object' && window.RTCPeerConnection && window.RTCRtpSender)) {
1722
    return;
1723
  }
1724
  if (window.RTCRtpSender && 'getStats' in window.RTCRtpSender.prototype) {
1725
    return;
1726
  }
1727
  var origGetSenders = window.RTCPeerConnection.prototype.getSenders;
1728
  if (origGetSenders) {
1729
    window.RTCPeerConnection.prototype.getSenders = function getSenders() {
1730
      var _this = this;
1731
 
1732
      var senders = origGetSenders.apply(this, []);
1733
      senders.forEach(function (sender) {
1734
        return sender._pc = _this;
1735
      });
1736
      return senders;
1737
    };
1738
  }
1739
 
1740
  var origAddTrack = window.RTCPeerConnection.prototype.addTrack;
1741
  if (origAddTrack) {
1742
    window.RTCPeerConnection.prototype.addTrack = function addTrack() {
1743
      var sender = origAddTrack.apply(this, arguments);
1744
      sender._pc = this;
1745
      return sender;
1746
    };
1747
  }
1748
  window.RTCRtpSender.prototype.getStats = function getStats() {
1749
    return this.track ? this._pc.getStats(this.track) : Promise.resolve(new Map());
1750
  };
1751
}
1752
 
1753
function shimReceiverGetStats(window) {
1754
  if (!((typeof window === 'undefined' ? 'undefined' : _typeof(window)) === 'object' && window.RTCPeerConnection && window.RTCRtpSender)) {
1755
    return;
1756
  }
1757
  if (window.RTCRtpSender && 'getStats' in window.RTCRtpReceiver.prototype) {
1758
    return;
1759
  }
1760
  var origGetReceivers = window.RTCPeerConnection.prototype.getReceivers;
1761
  if (origGetReceivers) {
1762
    window.RTCPeerConnection.prototype.getReceivers = function getReceivers() {
1763
      var _this2 = this;
1764
 
1765
      var receivers = origGetReceivers.apply(this, []);
1766
      receivers.forEach(function (receiver) {
1767
        return receiver._pc = _this2;
1768
      });
1769
      return receivers;
1770
    };
1771
  }
1772
  utils.wrapPeerConnectionEvent(window, 'track', function (e) {
1773
    e.receiver._pc = e.srcElement;
1774
    return e;
1775
  });
1776
  window.RTCRtpReceiver.prototype.getStats = function getStats() {
1777
    return this._pc.getStats(this.track);
1778
  };
1779
}
1780
 
1781
function shimRemoveStream(window) {
1782
  if (!window.RTCPeerConnection || 'removeStream' in window.RTCPeerConnection.prototype) {
1783
    return;
1784
  }
1785
  window.RTCPeerConnection.prototype.removeStream = function removeStream(stream) {
1786
    var _this3 = this;
1787
 
1788
    utils.deprecated('removeStream', 'removeTrack');
1789
    this.getSenders().forEach(function (sender) {
1790
      if (sender.track && stream.getTracks().includes(sender.track)) {
1791
        _this3.removeTrack(sender);
1792
      }
1793
    });
1794
  };
1795
}
1796
 
1797
function shimRTCDataChannel(window) {
1798
  // rename DataChannel to RTCDataChannel (native fix in FF60):
1799
  // https://bugzilla.mozilla.org/show_bug.cgi?id=1173851
1800
  if (window.DataChannel && !window.RTCDataChannel) {
1801
    window.RTCDataChannel = window.DataChannel;
1802
  }
1803
}
1804
 
1805
function shimAddTransceiver(window) {
1806
  // https://github.com/webrtcHacks/adapter/issues/998#issuecomment-516921647
1807
  // Firefox ignores the init sendEncodings options passed to addTransceiver
1808
  // https://bugzilla.mozilla.org/show_bug.cgi?id=1396918
1809
  if (!((typeof window === 'undefined' ? 'undefined' : _typeof(window)) === 'object' && window.RTCPeerConnection)) {
1810
    return;
1811
  }
1812
  var origAddTransceiver = window.RTCPeerConnection.prototype.addTransceiver;
1813
  if (origAddTransceiver) {
1814
    window.RTCPeerConnection.prototype.addTransceiver = function addTransceiver() {
1815
      this.setParametersPromises = [];
1816
      var initParameters = arguments[1];
1817
      var shouldPerformCheck = initParameters && 'sendEncodings' in initParameters;
1818
      if (shouldPerformCheck) {
1819
        // If sendEncodings params are provided, validate grammar
1820
        initParameters.sendEncodings.forEach(function (encodingParam) {
1821
          if ('rid' in encodingParam) {
1822
            var ridRegex = /^[a-z0-9]{0,16}$/i;
1823
            if (!ridRegex.test(encodingParam.rid)) {
1824
              throw new TypeError('Invalid RID value provided.');
1825
            }
1826
          }
1827
          if ('scaleResolutionDownBy' in encodingParam) {
1828
            if (!(parseFloat(encodingParam.scaleResolutionDownBy) >= 1.0)) {
1829
              throw new RangeError('scale_resolution_down_by must be >= 1.0');
1830
            }
1831
          }
1832
          if ('maxFramerate' in encodingParam) {
1833
            if (!(parseFloat(encodingParam.maxFramerate) >= 0)) {
1834
              throw new RangeError('max_framerate must be >= 0.0');
1835
            }
1836
          }
1837
        });
1838
      }
1839
      var transceiver = origAddTransceiver.apply(this, arguments);
1840
      if (shouldPerformCheck) {
1841
        // Check if the init options were applied. If not we do this in an
1842
        // asynchronous way and save the promise reference in a global object.
1843
        // This is an ugly hack, but at the same time is way more robust than
1844
        // checking the sender parameters before and after the createOffer
1845
        // Also note that after the createoffer we are not 100% sure that
1846
        // the params were asynchronously applied so we might miss the
1847
        // opportunity to recreate offer.
1848
        var sender = transceiver.sender;
1849
 
1850
        var params = sender.getParameters();
1851
        if (!('encodings' in params) ||
1852
        // Avoid being fooled by patched getParameters() below.
1853
        params.encodings.length === 1 && Object.keys(params.encodings[0]).length === 0) {
1854
          params.encodings = initParameters.sendEncodings;
1855
          sender.sendEncodings = initParameters.sendEncodings;
1856
          this.setParametersPromises.push(sender.setParameters(params).then(function () {
1857
            delete sender.sendEncodings;
1858
          }).catch(function () {
1859
            delete sender.sendEncodings;
1860
          }));
1861
        }
1862
      }
1863
      return transceiver;
1864
    };
1865
  }
1866
}
1867
 
1868
function shimGetParameters(window) {
1869
  if (!((typeof window === 'undefined' ? 'undefined' : _typeof(window)) === 'object' && window.RTCRtpSender)) {
1870
    return;
1871
  }
1872
  var origGetParameters = window.RTCRtpSender.prototype.getParameters;
1873
  if (origGetParameters) {
1874
    window.RTCRtpSender.prototype.getParameters = function getParameters() {
1875
      var params = origGetParameters.apply(this, arguments);
1876
      if (!('encodings' in params)) {
1877
        params.encodings = [].concat(this.sendEncodings || [{}]);
1878
      }
1879
      return params;
1880
    };
1881
  }
1882
}
1883
 
1884
function shimCreateOffer(window) {
1885
  // https://github.com/webrtcHacks/adapter/issues/998#issuecomment-516921647
1886
  // Firefox ignores the init sendEncodings options passed to addTransceiver
1887
  // https://bugzilla.mozilla.org/show_bug.cgi?id=1396918
1888
  if (!((typeof window === 'undefined' ? 'undefined' : _typeof(window)) === 'object' && window.RTCPeerConnection)) {
1889
    return;
1890
  }
1891
  var origCreateOffer = window.RTCPeerConnection.prototype.createOffer;
1892
  window.RTCPeerConnection.prototype.createOffer = function createOffer() {
1893
    var _this4 = this,
1894
        _arguments2 = arguments;
1895
 
1896
    if (this.setParametersPromises && this.setParametersPromises.length) {
1897
      return Promise.all(this.setParametersPromises).then(function () {
1898
        return origCreateOffer.apply(_this4, _arguments2);
1899
      }).finally(function () {
1900
        _this4.setParametersPromises = [];
1901
      });
1902
    }
1903
    return origCreateOffer.apply(this, arguments);
1904
  };
1905
}
1906
 
1907
function shimCreateAnswer(window) {
1908
  // https://github.com/webrtcHacks/adapter/issues/998#issuecomment-516921647
1909
  // Firefox ignores the init sendEncodings options passed to addTransceiver
1910
  // https://bugzilla.mozilla.org/show_bug.cgi?id=1396918
1911
  if (!((typeof window === 'undefined' ? 'undefined' : _typeof(window)) === 'object' && window.RTCPeerConnection)) {
1912
    return;
1913
  }
1914
  var origCreateAnswer = window.RTCPeerConnection.prototype.createAnswer;
1915
  window.RTCPeerConnection.prototype.createAnswer = function createAnswer() {
1916
    var _this5 = this,
1917
        _arguments3 = arguments;
1918
 
1919
    if (this.setParametersPromises && this.setParametersPromises.length) {
1920
      return Promise.all(this.setParametersPromises).then(function () {
1921
        return origCreateAnswer.apply(_this5, _arguments3);
1922
      }).finally(function () {
1923
        _this5.setParametersPromises = [];
1924
      });
1925
    }
1926
    return origCreateAnswer.apply(this, arguments);
1927
  };
1928
}
1929
 
1930
},{"../utils":11,"./getdisplaymedia":8,"./getusermedia":9}],8:[function(require,module,exports){
1931
/*
1932
 *  Copyright (c) 2018 The adapter.js project authors. All Rights Reserved.
1933
 *
1934
 *  Use of this source code is governed by a BSD-style license
1935
 *  that can be found in the LICENSE file in the root of the source
1936
 *  tree.
1937
 */
1938
/* eslint-env node */
1939
'use strict';
1940
 
1941
Object.defineProperty(exports, "__esModule", {
1942
  value: true
1943
});
1944
exports.shimGetDisplayMedia = shimGetDisplayMedia;
1945
function shimGetDisplayMedia(window, preferredMediaSource) {
1946
  if (window.navigator.mediaDevices && 'getDisplayMedia' in window.navigator.mediaDevices) {
1947
    return;
1948
  }
1949
  if (!window.navigator.mediaDevices) {
1950
    return;
1951
  }
1952
  window.navigator.mediaDevices.getDisplayMedia = function getDisplayMedia(constraints) {
1953
    if (!(constraints && constraints.video)) {
1954
      var err = new DOMException('getDisplayMedia without video ' + 'constraints is undefined');
1955
      err.name = 'NotFoundError';
1956
      // from https://heycam.github.io/webidl/#idl-DOMException-error-names
1957
      err.code = 8;
1958
      return Promise.reject(err);
1959
    }
1960
    if (constraints.video === true) {
1961
      constraints.video = { mediaSource: preferredMediaSource };
1962
    } else {
1963
      constraints.video.mediaSource = preferredMediaSource;
1964
    }
1965
    return window.navigator.mediaDevices.getUserMedia(constraints);
1966
  };
1967
}
1968
 
1969
},{}],9:[function(require,module,exports){
1970
/*
1971
 *  Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
1972
 *
1973
 *  Use of this source code is governed by a BSD-style license
1974
 *  that can be found in the LICENSE file in the root of the source
1975
 *  tree.
1976
 */
1977
/* eslint-env node */
1978
'use strict';
1979
 
1980
Object.defineProperty(exports, "__esModule", {
1981
  value: true
1982
});
1983
 
1984
var _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; };
1985
 
1986
exports.shimGetUserMedia = shimGetUserMedia;
1987
 
1988
var _utils = require('../utils');
1989
 
1990
var utils = _interopRequireWildcard(_utils);
1991
 
1992
function _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; } }
1993
 
1994
function shimGetUserMedia(window, browserDetails) {
1995
  var navigator = window && window.navigator;
1996
  var MediaStreamTrack = window && window.MediaStreamTrack;
1997
 
1998
  navigator.getUserMedia = function (constraints, onSuccess, onError) {
1999
    // Replace Firefox 44+'s deprecation warning with unprefixed version.
2000
    utils.deprecated('navigator.getUserMedia', 'navigator.mediaDevices.getUserMedia');
2001
    navigator.mediaDevices.getUserMedia(constraints).then(onSuccess, onError);
2002
  };
2003
 
2004
  if (!(browserDetails.version > 55 && 'autoGainControl' in navigator.mediaDevices.getSupportedConstraints())) {
2005
    var remap = function remap(obj, a, b) {
2006
      if (a in obj && !(b in obj)) {
2007
        obj[b] = obj[a];
2008
        delete obj[a];
2009
      }
2010
    };
2011
 
2012
    var nativeGetUserMedia = navigator.mediaDevices.getUserMedia.bind(navigator.mediaDevices);
2013
    navigator.mediaDevices.getUserMedia = function (c) {
2014
      if ((typeof c === 'undefined' ? 'undefined' : _typeof(c)) === 'object' && _typeof(c.audio) === 'object') {
2015
        c = JSON.parse(JSON.stringify(c));
2016
        remap(c.audio, 'autoGainControl', 'mozAutoGainControl');
2017
        remap(c.audio, 'noiseSuppression', 'mozNoiseSuppression');
2018
      }
2019
      return nativeGetUserMedia(c);
2020
    };
2021
 
2022
    if (MediaStreamTrack && MediaStreamTrack.prototype.getSettings) {
2023
      var nativeGetSettings = MediaStreamTrack.prototype.getSettings;
2024
      MediaStreamTrack.prototype.getSettings = function () {
2025
        var obj = nativeGetSettings.apply(this, arguments);
2026
        remap(obj, 'mozAutoGainControl', 'autoGainControl');
2027
        remap(obj, 'mozNoiseSuppression', 'noiseSuppression');
2028
        return obj;
2029
      };
2030
    }
2031
 
2032
    if (MediaStreamTrack && MediaStreamTrack.prototype.applyConstraints) {
2033
      var nativeApplyConstraints = MediaStreamTrack.prototype.applyConstraints;
2034
      MediaStreamTrack.prototype.applyConstraints = function (c) {
2035
        if (this.kind === 'audio' && (typeof c === 'undefined' ? 'undefined' : _typeof(c)) === 'object') {
2036
          c = JSON.parse(JSON.stringify(c));
2037
          remap(c, 'autoGainControl', 'mozAutoGainControl');
2038
          remap(c, 'noiseSuppression', 'mozNoiseSuppression');
2039
        }
2040
        return nativeApplyConstraints.apply(this, [c]);
2041
      };
2042
    }
2043
  }
2044
}
2045
 
2046
},{"../utils":11}],10:[function(require,module,exports){
2047
/*
2048
 *  Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
2049
 *
2050
 *  Use of this source code is governed by a BSD-style license
2051
 *  that can be found in the LICENSE file in the root of the source
2052
 *  tree.
2053
 */
2054
'use strict';
2055
 
2056
Object.defineProperty(exports, "__esModule", {
2057
  value: true
2058
});
2059
 
2060
var _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; };
2061
 
2062
exports.shimLocalStreamsAPI = shimLocalStreamsAPI;
2063
exports.shimRemoteStreamsAPI = shimRemoteStreamsAPI;
2064
exports.shimCallbacksAPI = shimCallbacksAPI;
2065
exports.shimGetUserMedia = shimGetUserMedia;
2066
exports.shimConstraints = shimConstraints;
2067
exports.shimRTCIceServerUrls = shimRTCIceServerUrls;
2068
exports.shimTrackEventTransceiver = shimTrackEventTransceiver;
2069
exports.shimCreateOfferLegacy = shimCreateOfferLegacy;
2070
exports.shimAudioContext = shimAudioContext;
2071
 
2072
var _utils = require('../utils');
2073
 
2074
var utils = _interopRequireWildcard(_utils);
2075
 
2076
function _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; } }
2077
 
2078
function shimLocalStreamsAPI(window) {
2079
  if ((typeof window === 'undefined' ? 'undefined' : _typeof(window)) !== 'object' || !window.RTCPeerConnection) {
2080
    return;
2081
  }
2082
  if (!('getLocalStreams' in window.RTCPeerConnection.prototype)) {
2083
    window.RTCPeerConnection.prototype.getLocalStreams = function getLocalStreams() {
2084
      if (!this._localStreams) {
2085
        this._localStreams = [];
2086
      }
2087
      return this._localStreams;
2088
    };
2089
  }
2090
  if (!('addStream' in window.RTCPeerConnection.prototype)) {
2091
    var _addTrack = window.RTCPeerConnection.prototype.addTrack;
2092
    window.RTCPeerConnection.prototype.addStream = function addStream(stream) {
2093
      var _this = this;
2094
 
2095
      if (!this._localStreams) {
2096
        this._localStreams = [];
2097
      }
2098
      if (!this._localStreams.includes(stream)) {
2099
        this._localStreams.push(stream);
2100
      }
2101
      // Try to emulate Chrome's behaviour of adding in audio-video order.
2102
      // Safari orders by track id.
2103
      stream.getAudioTracks().forEach(function (track) {
2104
        return _addTrack.call(_this, track, stream);
2105
      });
2106
      stream.getVideoTracks().forEach(function (track) {
2107
        return _addTrack.call(_this, track, stream);
2108
      });
2109
    };
2110
 
2111
    window.RTCPeerConnection.prototype.addTrack = function addTrack(track) {
2112
      var _this2 = this;
2113
 
2114
      for (var _len = arguments.length, streams = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
2115
        streams[_key - 1] = arguments[_key];
2116
      }
2117
 
2118
      if (streams) {
2119
        streams.forEach(function (stream) {
2120
          if (!_this2._localStreams) {
2121
            _this2._localStreams = [stream];
2122
          } else if (!_this2._localStreams.includes(stream)) {
2123
            _this2._localStreams.push(stream);
2124
          }
2125
        });
2126
      }
2127
      return _addTrack.apply(this, arguments);
2128
    };
2129
  }
2130
  if (!('removeStream' in window.RTCPeerConnection.prototype)) {
2131
    window.RTCPeerConnection.prototype.removeStream = function removeStream(stream) {
2132
      var _this3 = this;
2133
 
2134
      if (!this._localStreams) {
2135
        this._localStreams = [];
2136
      }
2137
      var index = this._localStreams.indexOf(stream);
2138
      if (index === -1) {
2139
        return;
2140
      }
2141
      this._localStreams.splice(index, 1);
2142
      var tracks = stream.getTracks();
2143
      this.getSenders().forEach(function (sender) {
2144
        if (tracks.includes(sender.track)) {
2145
          _this3.removeTrack(sender);
2146
        }
2147
      });
2148
    };
2149
  }
2150
}
2151
 
2152
function shimRemoteStreamsAPI(window) {
2153
  if ((typeof window === 'undefined' ? 'undefined' : _typeof(window)) !== 'object' || !window.RTCPeerConnection) {
2154
    return;
2155
  }
2156
  if (!('getRemoteStreams' in window.RTCPeerConnection.prototype)) {
2157
    window.RTCPeerConnection.prototype.getRemoteStreams = function getRemoteStreams() {
2158
      return this._remoteStreams ? this._remoteStreams : [];
2159
    };
2160
  }
2161
  if (!('onaddstream' in window.RTCPeerConnection.prototype)) {
2162
    Object.defineProperty(window.RTCPeerConnection.prototype, 'onaddstream', {
2163
      get: function get() {
2164
        return this._onaddstream;
2165
      },
2166
      set: function set(f) {
2167
        var _this4 = this;
2168
 
2169
        if (this._onaddstream) {
2170
          this.removeEventListener('addstream', this._onaddstream);
2171
          this.removeEventListener('track', this._onaddstreampoly);
2172
        }
2173
        this.addEventListener('addstream', this._onaddstream = f);
2174
        this.addEventListener('track', this._onaddstreampoly = function (e) {
2175
          e.streams.forEach(function (stream) {
2176
            if (!_this4._remoteStreams) {
2177
              _this4._remoteStreams = [];
2178
            }
2179
            if (_this4._remoteStreams.includes(stream)) {
2180
              return;
2181
            }
2182
            _this4._remoteStreams.push(stream);
2183
            var event = new Event('addstream');
2184
            event.stream = stream;
2185
            _this4.dispatchEvent(event);
2186
          });
2187
        });
2188
      }
2189
    });
2190
    var origSetRemoteDescription = window.RTCPeerConnection.prototype.setRemoteDescription;
2191
    window.RTCPeerConnection.prototype.setRemoteDescription = function setRemoteDescription() {
2192
      var pc = this;
2193
      if (!this._onaddstreampoly) {
2194
        this.addEventListener('track', this._onaddstreampoly = function (e) {
2195
          e.streams.forEach(function (stream) {
2196
            if (!pc._remoteStreams) {
2197
              pc._remoteStreams = [];
2198
            }
2199
            if (pc._remoteStreams.indexOf(stream) >= 0) {
2200
              return;
2201
            }
2202
            pc._remoteStreams.push(stream);
2203
            var event = new Event('addstream');
2204
            event.stream = stream;
2205
            pc.dispatchEvent(event);
2206
          });
2207
        });
2208
      }
2209
      return origSetRemoteDescription.apply(pc, arguments);
2210
    };
2211
  }
2212
}
2213
 
2214
function shimCallbacksAPI(window) {
2215
  if ((typeof window === 'undefined' ? 'undefined' : _typeof(window)) !== 'object' || !window.RTCPeerConnection) {
2216
    return;
2217
  }
2218
  var prototype = window.RTCPeerConnection.prototype;
2219
  var origCreateOffer = prototype.createOffer;
2220
  var origCreateAnswer = prototype.createAnswer;
2221
  var setLocalDescription = prototype.setLocalDescription;
2222
  var setRemoteDescription = prototype.setRemoteDescription;
2223
  var addIceCandidate = prototype.addIceCandidate;
2224
 
2225
  prototype.createOffer = function createOffer(successCallback, failureCallback) {
2226
    var options = arguments.length >= 2 ? arguments[2] : arguments[0];
2227
    var promise = origCreateOffer.apply(this, [options]);
2228
    if (!failureCallback) {
2229
      return promise;
2230
    }
2231
    promise.then(successCallback, failureCallback);
2232
    return Promise.resolve();
2233
  };
2234
 
2235
  prototype.createAnswer = function createAnswer(successCallback, failureCallback) {
2236
    var options = arguments.length >= 2 ? arguments[2] : arguments[0];
2237
    var promise = origCreateAnswer.apply(this, [options]);
2238
    if (!failureCallback) {
2239
      return promise;
2240
    }
2241
    promise.then(successCallback, failureCallback);
2242
    return Promise.resolve();
2243
  };
2244
 
2245
  var withCallback = function withCallback(description, successCallback, failureCallback) {
2246
    var promise = setLocalDescription.apply(this, [description]);
2247
    if (!failureCallback) {
2248
      return promise;
2249
    }
2250
    promise.then(successCallback, failureCallback);
2251
    return Promise.resolve();
2252
  };
2253
  prototype.setLocalDescription = withCallback;
2254
 
2255
  withCallback = function withCallback(description, successCallback, failureCallback) {
2256
    var promise = setRemoteDescription.apply(this, [description]);
2257
    if (!failureCallback) {
2258
      return promise;
2259
    }
2260
    promise.then(successCallback, failureCallback);
2261
    return Promise.resolve();
2262
  };
2263
  prototype.setRemoteDescription = withCallback;
2264
 
2265
  withCallback = function withCallback(candidate, successCallback, failureCallback) {
2266
    var promise = addIceCandidate.apply(this, [candidate]);
2267
    if (!failureCallback) {
2268
      return promise;
2269
    }
2270
    promise.then(successCallback, failureCallback);
2271
    return Promise.resolve();
2272
  };
2273
  prototype.addIceCandidate = withCallback;
2274
}
2275
 
2276
function shimGetUserMedia(window) {
2277
  var navigator = window && window.navigator;
2278
 
2279
  if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
2280
    // shim not needed in Safari 12.1
2281
    var mediaDevices = navigator.mediaDevices;
2282
    var _getUserMedia = mediaDevices.getUserMedia.bind(mediaDevices);
2283
    navigator.mediaDevices.getUserMedia = function (constraints) {
2284
      return _getUserMedia(shimConstraints(constraints));
2285
    };
2286
  }
2287
 
2288
  if (!navigator.getUserMedia && navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
2289
    navigator.getUserMedia = function getUserMedia(constraints, cb, errcb) {
2290
      navigator.mediaDevices.getUserMedia(constraints).then(cb, errcb);
2291
    }.bind(navigator);
2292
  }
2293
}
2294
 
2295
function shimConstraints(constraints) {
2296
  if (constraints && constraints.video !== undefined) {
2297
    return Object.assign({}, constraints, { video: utils.compactObject(constraints.video) });
2298
  }
2299
 
2300
  return constraints;
2301
}
2302
 
2303
function shimRTCIceServerUrls(window) {
2304
  if (!window.RTCPeerConnection) {
2305
    return;
2306
  }
2307
  // migrate from non-spec RTCIceServer.url to RTCIceServer.urls
2308
  var OrigPeerConnection = window.RTCPeerConnection;
2309
  window.RTCPeerConnection = function RTCPeerConnection(pcConfig, pcConstraints) {
2310
    if (pcConfig && pcConfig.iceServers) {
2311
      var newIceServers = [];
2312
      for (var i = 0; i < pcConfig.iceServers.length; i++) {
2313
        var server = pcConfig.iceServers[i];
2314
        if (!server.hasOwnProperty('urls') && server.hasOwnProperty('url')) {
2315
          utils.deprecated('RTCIceServer.url', 'RTCIceServer.urls');
2316
          server = JSON.parse(JSON.stringify(server));
2317
          server.urls = server.url;
2318
          delete server.url;
2319
          newIceServers.push(server);
2320
        } else {
2321
          newIceServers.push(pcConfig.iceServers[i]);
2322
        }
2323
      }
2324
      pcConfig.iceServers = newIceServers;
2325
    }
2326
    return new OrigPeerConnection(pcConfig, pcConstraints);
2327
  };
2328
  window.RTCPeerConnection.prototype = OrigPeerConnection.prototype;
2329
  // wrap static methods. Currently just generateCertificate.
2330
  if ('generateCertificate' in OrigPeerConnection) {
2331
    Object.defineProperty(window.RTCPeerConnection, 'generateCertificate', {
2332
      get: function get() {
2333
        return OrigPeerConnection.generateCertificate;
2334
      }
2335
    });
2336
  }
2337
}
2338
 
2339
function shimTrackEventTransceiver(window) {
2340
  // Add event.transceiver member over deprecated event.receiver
2341
  if ((typeof window === 'undefined' ? 'undefined' : _typeof(window)) === 'object' && window.RTCTrackEvent && 'receiver' in window.RTCTrackEvent.prototype && !('transceiver' in window.RTCTrackEvent.prototype)) {
2342
    Object.defineProperty(window.RTCTrackEvent.prototype, 'transceiver', {
2343
      get: function get() {
2344
        return { receiver: this.receiver };
2345
      }
2346
    });
2347
  }
2348
}
2349
 
2350
function shimCreateOfferLegacy(window) {
2351
  var origCreateOffer = window.RTCPeerConnection.prototype.createOffer;
2352
  window.RTCPeerConnection.prototype.createOffer = function createOffer(offerOptions) {
2353
    if (offerOptions) {
2354
      if (typeof offerOptions.offerToReceiveAudio !== 'undefined') {
2355
        // support bit values
2356
        offerOptions.offerToReceiveAudio = !!offerOptions.offerToReceiveAudio;
2357
      }
2358
      var audioTransceiver = this.getTransceivers().find(function (transceiver) {
2359
        return transceiver.receiver.track.kind === 'audio';
2360
      });
2361
      if (offerOptions.offerToReceiveAudio === false && audioTransceiver) {
2362
        if (audioTransceiver.direction === 'sendrecv') {
2363
          if (audioTransceiver.setDirection) {
2364
            audioTransceiver.setDirection('sendonly');
2365
          } else {
2366
            audioTransceiver.direction = 'sendonly';
2367
          }
2368
        } else if (audioTransceiver.direction === 'recvonly') {
2369
          if (audioTransceiver.setDirection) {
2370
            audioTransceiver.setDirection('inactive');
2371
          } else {
2372
            audioTransceiver.direction = 'inactive';
2373
          }
2374
        }
2375
      } else if (offerOptions.offerToReceiveAudio === true && !audioTransceiver) {
2376
        this.addTransceiver('audio');
2377
      }
2378
 
2379
      if (typeof offerOptions.offerToReceiveVideo !== 'undefined') {
2380
        // support bit values
2381
        offerOptions.offerToReceiveVideo = !!offerOptions.offerToReceiveVideo;
2382
      }
2383
      var videoTransceiver = this.getTransceivers().find(function (transceiver) {
2384
        return transceiver.receiver.track.kind === 'video';
2385
      });
2386
      if (offerOptions.offerToReceiveVideo === false && videoTransceiver) {
2387
        if (videoTransceiver.direction === 'sendrecv') {
2388
          if (videoTransceiver.setDirection) {
2389
            videoTransceiver.setDirection('sendonly');
2390
          } else {
2391
            videoTransceiver.direction = 'sendonly';
2392
          }
2393
        } else if (videoTransceiver.direction === 'recvonly') {
2394
          if (videoTransceiver.setDirection) {
2395
            videoTransceiver.setDirection('inactive');
2396
          } else {
2397
            videoTransceiver.direction = 'inactive';
2398
          }
2399
        }
2400
      } else if (offerOptions.offerToReceiveVideo === true && !videoTransceiver) {
2401
        this.addTransceiver('video');
2402
      }
2403
    }
2404
    return origCreateOffer.apply(this, arguments);
2405
  };
2406
}
2407
 
2408
function shimAudioContext(window) {
2409
  if ((typeof window === 'undefined' ? 'undefined' : _typeof(window)) !== 'object' || window.AudioContext) {
2410
    return;
2411
  }
2412
  window.AudioContext = window.webkitAudioContext;
2413
}
2414
 
2415
},{"../utils":11}],11:[function(require,module,exports){
2416
/*
2417
 *  Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
2418
 *
2419
 *  Use of this source code is governed by a BSD-style license
2420
 *  that can be found in the LICENSE file in the root of the source
2421
 *  tree.
2422
 */
2423
/* eslint-env node */
2424
'use strict';
2425
 
2426
Object.defineProperty(exports, "__esModule", {
2427
  value: true
2428
});
2429
 
2430
var _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; };
2431
 
2432
exports.extractVersion = extractVersion;
2433
exports.wrapPeerConnectionEvent = wrapPeerConnectionEvent;
2434
exports.disableLog = disableLog;
2435
exports.disableWarnings = disableWarnings;
2436
exports.log = log;
2437
exports.deprecated = deprecated;
2438
exports.detectBrowser = detectBrowser;
2439
exports.compactObject = compactObject;
2440
exports.walkStats = walkStats;
2441
exports.filterStats = filterStats;
2442
 
2443
function _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; }
2444
 
2445
var logDisabled_ = true;
2446
var deprecationWarnings_ = true;
2447
 
2448
/**
2449
 * Extract browser version out of the provided user agent string.
2450
 *
2451
 * @param {!string} uastring userAgent string.
2452
 * @param {!string} expr Regular expression used as match criteria.
2453
 * @param {!number} pos position in the version string to be returned.
2454
 * @return {!number} browser version.
2455
 */
2456
function extractVersion(uastring, expr, pos) {
2457
  var match = uastring.match(expr);
2458
  return match && match.length >= pos && parseInt(match[pos], 10);
2459
}
2460
 
2461
// Wraps the peerconnection event eventNameToWrap in a function
2462
// which returns the modified event object (or false to prevent
2463
// the event).
2464
function wrapPeerConnectionEvent(window, eventNameToWrap, wrapper) {
2465
  if (!window.RTCPeerConnection) {
2466
    return;
2467
  }
2468
  var proto = window.RTCPeerConnection.prototype;
2469
  var nativeAddEventListener = proto.addEventListener;
2470
  proto.addEventListener = function (nativeEventName, cb) {
2471
    if (nativeEventName !== eventNameToWrap) {
2472
      return nativeAddEventListener.apply(this, arguments);
2473
    }
2474
    var wrappedCallback = function wrappedCallback(e) {
2475
      var modifiedEvent = wrapper(e);
2476
      if (modifiedEvent) {
2477
        if (cb.handleEvent) {
2478
          cb.handleEvent(modifiedEvent);
2479
        } else {
2480
          cb(modifiedEvent);
2481
        }
2482
      }
2483
    };
2484
    this._eventMap = this._eventMap || {};
2485
    if (!this._eventMap[eventNameToWrap]) {
2486
      this._eventMap[eventNameToWrap] = new Map();
2487
    }
2488
    this._eventMap[eventNameToWrap].set(cb, wrappedCallback);
2489
    return nativeAddEventListener.apply(this, [nativeEventName, wrappedCallback]);
2490
  };
2491
 
2492
  var nativeRemoveEventListener = proto.removeEventListener;
2493
  proto.removeEventListener = function (nativeEventName, cb) {
2494
    if (nativeEventName !== eventNameToWrap || !this._eventMap || !this._eventMap[eventNameToWrap]) {
2495
      return nativeRemoveEventListener.apply(this, arguments);
2496
    }
2497
    if (!this._eventMap[eventNameToWrap].has(cb)) {
2498
      return nativeRemoveEventListener.apply(this, arguments);
2499
    }
2500
    var unwrappedCb = this._eventMap[eventNameToWrap].get(cb);
2501
    this._eventMap[eventNameToWrap].delete(cb);
2502
    if (this._eventMap[eventNameToWrap].size === 0) {
2503
      delete this._eventMap[eventNameToWrap];
2504
    }
2505
    if (Object.keys(this._eventMap).length === 0) {
2506
      delete this._eventMap;
2507
    }
2508
    return nativeRemoveEventListener.apply(this, [nativeEventName, unwrappedCb]);
2509
  };
2510
 
2511
  Object.defineProperty(proto, 'on' + eventNameToWrap, {
2512
    get: function get() {
2513
      return this['_on' + eventNameToWrap];
2514
    },
2515
    set: function set(cb) {
2516
      if (this['_on' + eventNameToWrap]) {
2517
        this.removeEventListener(eventNameToWrap, this['_on' + eventNameToWrap]);
2518
        delete this['_on' + eventNameToWrap];
2519
      }
2520
      if (cb) {
2521
        this.addEventListener(eventNameToWrap, this['_on' + eventNameToWrap] = cb);
2522
      }
2523
    },
2524
 
2525
    enumerable: true,
2526
    configurable: true
2527
  });
2528
}
2529
 
2530
function disableLog(bool) {
2531
  if (typeof bool !== 'boolean') {
2532
    return new Error('Argument type: ' + (typeof bool === 'undefined' ? 'undefined' : _typeof(bool)) + '. Please use a boolean.');
2533
  }
2534
  logDisabled_ = bool;
2535
  return bool ? 'adapter.js logging disabled' : 'adapter.js logging enabled';
2536
}
2537
 
2538
/**
2539
 * Disable or enable deprecation warnings
2540
 * @param {!boolean} bool set to true to disable warnings.
2541
 */
2542
function disableWarnings(bool) {
2543
  if (typeof bool !== 'boolean') {
2544
    return new Error('Argument type: ' + (typeof bool === 'undefined' ? 'undefined' : _typeof(bool)) + '. Please use a boolean.');
2545
  }
2546
  deprecationWarnings_ = !bool;
2547
  return 'adapter.js deprecation warnings ' + (bool ? 'disabled' : 'enabled');
2548
}
2549
 
2550
function log() {
2551
  if ((typeof window === 'undefined' ? 'undefined' : _typeof(window)) === 'object') {
2552
    if (logDisabled_) {
2553
      return;
2554
    }
2555
    if (typeof console !== 'undefined' && typeof console.log === 'function') {
2556
      console.log.apply(console, arguments);
2557
    }
2558
  }
2559
}
2560
 
2561
/**
2562
 * Shows a deprecation warning suggesting the modern and spec-compatible API.
2563
 */
2564
function deprecated(oldMethod, newMethod) {
2565
  if (!deprecationWarnings_) {
2566
    return;
2567
  }
2568
  console.warn(oldMethod + ' is deprecated, please use ' + newMethod + ' instead.');
2569
}
2570
 
2571
/**
2572
 * Browser detector.
2573
 *
2574
 * @return {object} result containing browser and version
2575
 *     properties.
2576
 */
2577
function detectBrowser(window) {
2578
  // Returned result object.
2579
  var result = { browser: null, version: null };
2580
 
2581
  // Fail early if it's not a browser
2582
  if (typeof window === 'undefined' || !window.navigator) {
2583
    result.browser = 'Not a browser.';
2584
    return result;
2585
  }
2586
 
2587
  var navigator = window.navigator;
2588
 
2589
 
2590
  if (navigator.mozGetUserMedia) {
2591
    // Firefox.
2592
    result.browser = 'firefox';
2593
    result.version = extractVersion(navigator.userAgent, /Firefox\/(\d+)\./, 1);
2594
  } else if (navigator.webkitGetUserMedia || window.isSecureContext === false && window.webkitRTCPeerConnection && !window.RTCIceGatherer) {
2595
    // Chrome, Chromium, Webview, Opera.
2596
    // Version matches Chrome/WebRTC version.
2597
    // Chrome 74 removed webkitGetUserMedia on http as well so we need the
2598
    // more complicated fallback to webkitRTCPeerConnection.
2599
    result.browser = 'chrome';
2600
    result.version = extractVersion(navigator.userAgent, /Chrom(e|ium)\/(\d+)\./, 2);
2601
  } else if (window.RTCPeerConnection && navigator.userAgent.match(/AppleWebKit\/(\d+)\./)) {
2602
    // Safari.
2603
    result.browser = 'safari';
2604
    result.version = extractVersion(navigator.userAgent, /AppleWebKit\/(\d+)\./, 1);
2605
    result.supportsUnifiedPlan = window.RTCRtpTransceiver && 'currentDirection' in window.RTCRtpTransceiver.prototype;
2606
  } else {
2607
    // Default fallthrough: not supported.
2608
    result.browser = 'Not a supported browser.';
2609
    return result;
2610
  }
2611
 
2612
  return result;
2613
}
2614
 
2615
/**
2616
 * Checks if something is an object.
2617
 *
2618
 * @param {*} val The something you want to check.
2619
 * @return true if val is an object, false otherwise.
2620
 */
2621
function isObject(val) {
2622
  return Object.prototype.toString.call(val) === '[object Object]';
2623
}
2624
 
2625
/**
2626
 * Remove all empty objects and undefined values
2627
 * from a nested object -- an enhanced and vanilla version
2628
 * of Lodash's `compact`.
2629
 */
2630
function compactObject(data) {
2631
  if (!isObject(data)) {
2632
    return data;
2633
  }
2634
 
2635
  return Object.keys(data).reduce(function (accumulator, key) {
2636
    var isObj = isObject(data[key]);
2637
    var value = isObj ? compactObject(data[key]) : data[key];
2638
    var isEmptyObject = isObj && !Object.keys(value).length;
2639
    if (value === undefined || isEmptyObject) {
2640
      return accumulator;
2641
    }
2642
    return Object.assign(accumulator, _defineProperty({}, key, value));
2643
  }, {});
2644
}
2645
 
2646
/* iterates the stats graph recursively. */
2647
function walkStats(stats, base, resultSet) {
2648
  if (!base || resultSet.has(base.id)) {
2649
    return;
2650
  }
2651
  resultSet.set(base.id, base);
2652
  Object.keys(base).forEach(function (name) {
2653
    if (name.endsWith('Id')) {
2654
      walkStats(stats, stats.get(base[name]), resultSet);
2655
    } else if (name.endsWith('Ids')) {
2656
      base[name].forEach(function (id) {
2657
        walkStats(stats, stats.get(id), resultSet);
2658
      });
2659
    }
2660
  });
2661
}
2662
 
2663
/* filter getStats for a sender/receiver track. */
2664
function filterStats(result, track, outbound) {
2665
  var streamStatsType = outbound ? 'outbound-rtp' : 'inbound-rtp';
2666
  var filteredResult = new Map();
2667
  if (track === null) {
2668
    return filteredResult;
2669
  }
2670
  var trackStats = [];
2671
  result.forEach(function (value) {
2672
    if (value.type === 'track' && value.trackIdentifier === track.id) {
2673
      trackStats.push(value);
2674
    }
2675
  });
2676
  trackStats.forEach(function (trackStat) {
2677
    result.forEach(function (stats) {
2678
      if (stats.type === streamStatsType && stats.trackId === trackStat.id) {
2679
        walkStats(result, stats, filteredResult);
2680
      }
2681
    });
2682
  });
2683
  return filteredResult;
2684
}
2685
 
2686
},{}],12:[function(require,module,exports){
2687
/* eslint-env node */
2688
'use strict';
2689
 
2690
// SDP helpers.
2691
 
2692
var _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; };
2693
 
2694
var SDPUtils = {};
2695
 
2696
// Generate an alphanumeric identifier for cname or mids.
2697
// TODO: use UUIDs instead? https://gist.github.com/jed/982883
2698
SDPUtils.generateIdentifier = function () {
2699
  return Math.random().toString(36).substr(2, 10);
2700
};
2701
 
2702
// The RTCP CNAME used by all peerconnections from the same JS.
2703
SDPUtils.localCName = SDPUtils.generateIdentifier();
2704
 
2705
// Splits SDP into lines, dealing with both CRLF and LF.
2706
SDPUtils.splitLines = function (blob) {
2707
  return blob.trim().split('\n').map(function (line) {
2708
    return line.trim();
2709
  });
2710
};
2711
// Splits SDP into sessionpart and mediasections. Ensures CRLF.
2712
SDPUtils.splitSections = function (blob) {
2713
  var parts = blob.split('\nm=');
2714
  return parts.map(function (part, index) {
2715
    return (index > 0 ? 'm=' + part : part).trim() + '\r\n';
2716
  });
2717
};
2718
 
2719
// returns the session description.
2720
SDPUtils.getDescription = function (blob) {
2721
  var sections = SDPUtils.splitSections(blob);
2722
  return sections && sections[0];
2723
};
2724
 
2725
// returns the individual media sections.
2726
SDPUtils.getMediaSections = function (blob) {
2727
  var sections = SDPUtils.splitSections(blob);
2728
  sections.shift();
2729
  return sections;
2730
};
2731
 
2732
// Returns lines that start with a certain prefix.
2733
SDPUtils.matchPrefix = function (blob, prefix) {
2734
  return SDPUtils.splitLines(blob).filter(function (line) {
2735
    return line.indexOf(prefix) === 0;
2736
  });
2737
};
2738
 
2739
// Parses an ICE candidate line. Sample input:
2740
// candidate:702786350 2 udp 41819902 8.8.8.8 60769 typ relay raddr 8.8.8.8
2741
// rport 55996"
2742
SDPUtils.parseCandidate = function (line) {
2743
  var parts = void 0;
2744
  // Parse both variants.
2745
  if (line.indexOf('a=candidate:') === 0) {
2746
    parts = line.substring(12).split(' ');
2747
  } else {
2748
    parts = line.substring(10).split(' ');
2749
  }
2750
 
2751
  var candidate = {
2752
    foundation: parts[0],
2753
    component: { 1: 'rtp', 2: 'rtcp' }[parts[1]],
2754
    protocol: parts[2].toLowerCase(),
2755
    priority: parseInt(parts[3], 10),
2756
    ip: parts[4],
2757
    address: parts[4], // address is an alias for ip.
2758
    port: parseInt(parts[5], 10),
2759
    // skip parts[6] == 'typ'
2760
    type: parts[7]
2761
  };
2762
 
2763
  for (var i = 8; i < parts.length; i += 2) {
2764
    switch (parts[i]) {
2765
      case 'raddr':
2766
        candidate.relatedAddress = parts[i + 1];
2767
        break;
2768
      case 'rport':
2769
        candidate.relatedPort = parseInt(parts[i + 1], 10);
2770
        break;
2771
      case 'tcptype':
2772
        candidate.tcpType = parts[i + 1];
2773
        break;
2774
      case 'ufrag':
2775
        candidate.ufrag = parts[i + 1]; // for backward compatibility.
2776
        candidate.usernameFragment = parts[i + 1];
2777
        break;
2778
      default:
2779
        // extension handling, in particular ufrag. Don't overwrite.
2780
        if (candidate[parts[i]] === undefined) {
2781
          candidate[parts[i]] = parts[i + 1];
2782
        }
2783
        break;
2784
    }
2785
  }
2786
  return candidate;
2787
};
2788
 
2789
// Translates a candidate object into SDP candidate attribute.
2790
SDPUtils.writeCandidate = function (candidate) {
2791
  var sdp = [];
2792
  sdp.push(candidate.foundation);
2793
 
2794
  var component = candidate.component;
2795
  if (component === 'rtp') {
2796
    sdp.push(1);
2797
  } else if (component === 'rtcp') {
2798
    sdp.push(2);
2799
  } else {
2800
    sdp.push(component);
2801
  }
2802
  sdp.push(candidate.protocol.toUpperCase());
2803
  sdp.push(candidate.priority);
2804
  sdp.push(candidate.address || candidate.ip);
2805
  sdp.push(candidate.port);
2806
 
2807
  var type = candidate.type;
2808
  sdp.push('typ');
2809
  sdp.push(type);
2810
  if (type !== 'host' && candidate.relatedAddress && candidate.relatedPort) {
2811
    sdp.push('raddr');
2812
    sdp.push(candidate.relatedAddress);
2813
    sdp.push('rport');
2814
    sdp.push(candidate.relatedPort);
2815
  }
2816
  if (candidate.tcpType && candidate.protocol.toLowerCase() === 'tcp') {
2817
    sdp.push('tcptype');
2818
    sdp.push(candidate.tcpType);
2819
  }
2820
  if (candidate.usernameFragment || candidate.ufrag) {
2821
    sdp.push('ufrag');
2822
    sdp.push(candidate.usernameFragment || candidate.ufrag);
2823
  }
2824
  return 'candidate:' + sdp.join(' ');
2825
};
2826
 
2827
// Parses an ice-options line, returns an array of option tags.
2828
// a=ice-options:foo bar
2829
SDPUtils.parseIceOptions = function (line) {
2830
  return line.substr(14).split(' ');
2831
};
2832
 
2833
// Parses an rtpmap line, returns RTCRtpCoddecParameters. Sample input:
2834
// a=rtpmap:111 opus/48000/2
2835
SDPUtils.parseRtpMap = function (line) {
2836
  var parts = line.substr(9).split(' ');
2837
  var parsed = {
2838
    payloadType: parseInt(parts.shift(), 10) // was: id
2839
  };
2840
 
2841
  parts = parts[0].split('/');
2842
 
2843
  parsed.name = parts[0];
2844
  parsed.clockRate = parseInt(parts[1], 10); // was: clockrate
2845
  parsed.channels = parts.length === 3 ? parseInt(parts[2], 10) : 1;
2846
  // legacy alias, got renamed back to channels in ORTC.
2847
  parsed.numChannels = parsed.channels;
2848
  return parsed;
2849
};
2850
 
2851
// Generate an a=rtpmap line from RTCRtpCodecCapability or
2852
// RTCRtpCodecParameters.
2853
SDPUtils.writeRtpMap = function (codec) {
2854
  var pt = codec.payloadType;
2855
  if (codec.preferredPayloadType !== undefined) {
2856
    pt = codec.preferredPayloadType;
2857
  }
2858
  var channels = codec.channels || codec.numChannels || 1;
2859
  return 'a=rtpmap:' + pt + ' ' + codec.name + '/' + codec.clockRate + (channels !== 1 ? '/' + channels : '') + '\r\n';
2860
};
2861
 
2862
// Parses an a=extmap line (headerextension from RFC 5285). Sample input:
2863
// a=extmap:2 urn:ietf:params:rtp-hdrext:toffset
2864
// a=extmap:2/sendonly urn:ietf:params:rtp-hdrext:toffset
2865
SDPUtils.parseExtmap = function (line) {
2866
  var parts = line.substr(9).split(' ');
2867
  return {
2868
    id: parseInt(parts[0], 10),
2869
    direction: parts[0].indexOf('/') > 0 ? parts[0].split('/')[1] : 'sendrecv',
2870
    uri: parts[1]
2871
  };
2872
};
2873
 
2874
// Generates a=extmap line from RTCRtpHeaderExtensionParameters or
2875
// RTCRtpHeaderExtension.
2876
SDPUtils.writeExtmap = function (headerExtension) {
2877
  return 'a=extmap:' + (headerExtension.id || headerExtension.preferredId) + (headerExtension.direction && headerExtension.direction !== 'sendrecv' ? '/' + headerExtension.direction : '') + ' ' + headerExtension.uri + '\r\n';
2878
};
2879
 
2880
// Parses an ftmp line, returns dictionary. Sample input:
2881
// a=fmtp:96 vbr=on;cng=on
2882
// Also deals with vbr=on; cng=on
2883
SDPUtils.parseFmtp = function (line) {
2884
  var parsed = {};
2885
  var kv = void 0;
2886
  var parts = line.substr(line.indexOf(' ') + 1).split(';');
2887
  for (var j = 0; j < parts.length; j++) {
2888
    kv = parts[j].trim().split('=');
2889
    parsed[kv[0].trim()] = kv[1];
2890
  }
2891
  return parsed;
2892
};
2893
 
2894
// Generates an a=ftmp line from RTCRtpCodecCapability or RTCRtpCodecParameters.
2895
SDPUtils.writeFmtp = function (codec) {
2896
  var line = '';
2897
  var pt = codec.payloadType;
2898
  if (codec.preferredPayloadType !== undefined) {
2899
    pt = codec.preferredPayloadType;
2900
  }
2901
  if (codec.parameters && Object.keys(codec.parameters).length) {
2902
    var params = [];
2903
    Object.keys(codec.parameters).forEach(function (param) {
2904
      if (codec.parameters[param]) {
2905
        params.push(param + '=' + codec.parameters[param]);
2906
      } else {
2907
        params.push(param);
2908
      }
2909
    });
2910
    line += 'a=fmtp:' + pt + ' ' + params.join(';') + '\r\n';
2911
  }
2912
  return line;
2913
};
2914
 
2915
// Parses an rtcp-fb line, returns RTCPRtcpFeedback object. Sample input:
2916
// a=rtcp-fb:98 nack rpsi
2917
SDPUtils.parseRtcpFb = function (line) {
2918
  var parts = line.substr(line.indexOf(' ') + 1).split(' ');
2919
  return {
2920
    type: parts.shift(),
2921
    parameter: parts.join(' ')
2922
  };
2923
};
2924
// Generate a=rtcp-fb lines from RTCRtpCodecCapability or RTCRtpCodecParameters.
2925
SDPUtils.writeRtcpFb = function (codec) {
2926
  var lines = '';
2927
  var pt = codec.payloadType;
2928
  if (codec.preferredPayloadType !== undefined) {
2929
    pt = codec.preferredPayloadType;
2930
  }
2931
  if (codec.rtcpFeedback && codec.rtcpFeedback.length) {
2932
    // FIXME: special handling for trr-int?
2933
    codec.rtcpFeedback.forEach(function (fb) {
2934
      lines += 'a=rtcp-fb:' + pt + ' ' + fb.type + (fb.parameter && fb.parameter.length ? ' ' + fb.parameter : '') + '\r\n';
2935
    });
2936
  }
2937
  return lines;
2938
};
2939
 
2940
// Parses an RFC 5576 ssrc media attribute. Sample input:
2941
// a=ssrc:3735928559 cname:something
2942
SDPUtils.parseSsrcMedia = function (line) {
2943
  var sp = line.indexOf(' ');
2944
  var parts = {
2945
    ssrc: parseInt(line.substr(7, sp - 7), 10)
2946
  };
2947
  var colon = line.indexOf(':', sp);
2948
  if (colon > -1) {
2949
    parts.attribute = line.substr(sp + 1, colon - sp - 1);
2950
    parts.value = line.substr(colon + 1);
2951
  } else {
2952
    parts.attribute = line.substr(sp + 1);
2953
  }
2954
  return parts;
2955
};
2956
 
2957
SDPUtils.parseSsrcGroup = function (line) {
2958
  var parts = line.substr(13).split(' ');
2959
  return {
2960
    semantics: parts.shift(),
2961
    ssrcs: parts.map(function (ssrc) {
2962
      return parseInt(ssrc, 10);
2963
    })
2964
  };
2965
};
2966
 
2967
// Extracts the MID (RFC 5888) from a media section.
2968
// returns the MID or undefined if no mid line was found.
2969
SDPUtils.getMid = function (mediaSection) {
2970
  var mid = SDPUtils.matchPrefix(mediaSection, 'a=mid:')[0];
2971
  if (mid) {
2972
    return mid.substr(6);
2973
  }
2974
};
2975
 
2976
SDPUtils.parseFingerprint = function (line) {
2977
  var parts = line.substr(14).split(' ');
2978
  return {
2979
    algorithm: parts[0].toLowerCase(), // algorithm is case-sensitive in Edge.
2980
    value: parts[1]
2981
  };
2982
};
2983
 
2984
// Extracts DTLS parameters from SDP media section or sessionpart.
2985
// FIXME: for consistency with other functions this should only
2986
//   get the fingerprint line as input. See also getIceParameters.
2987
SDPUtils.getDtlsParameters = function (mediaSection, sessionpart) {
2988
  var lines = SDPUtils.matchPrefix(mediaSection + sessionpart, 'a=fingerprint:');
2989
  // Note: a=setup line is ignored since we use the 'auto' role.
2990
  // Note2: 'algorithm' is not case sensitive except in Edge.
2991
  return {
2992
    role: 'auto',
2993
    fingerprints: lines.map(SDPUtils.parseFingerprint)
2994
  };
2995
};
2996
 
2997
// Serializes DTLS parameters to SDP.
2998
SDPUtils.writeDtlsParameters = function (params, setupType) {
2999
  var sdp = 'a=setup:' + setupType + '\r\n';
3000
  params.fingerprints.forEach(function (fp) {
3001
    sdp += 'a=fingerprint:' + fp.algorithm + ' ' + fp.value + '\r\n';
3002
  });
3003
  return sdp;
3004
};
3005
 
3006
// Parses a=crypto lines into
3007
//   https://rawgit.com/aboba/edgertc/master/msortc-rs4.html#dictionary-rtcsrtpsdesparameters-members
3008
SDPUtils.parseCryptoLine = function (line) {
3009
  var parts = line.substr(9).split(' ');
3010
  return {
3011
    tag: parseInt(parts[0], 10),
3012
    cryptoSuite: parts[1],
3013
    keyParams: parts[2],
3014
    sessionParams: parts.slice(3)
3015
  };
3016
};
3017
 
3018
SDPUtils.writeCryptoLine = function (parameters) {
3019
  return 'a=crypto:' + parameters.tag + ' ' + parameters.cryptoSuite + ' ' + (_typeof(parameters.keyParams) === 'object' ? SDPUtils.writeCryptoKeyParams(parameters.keyParams) : parameters.keyParams) + (parameters.sessionParams ? ' ' + parameters.sessionParams.join(' ') : '') + '\r\n';
3020
};
3021
 
3022
// Parses the crypto key parameters into
3023
//   https://rawgit.com/aboba/edgertc/master/msortc-rs4.html#rtcsrtpkeyparam*
3024
SDPUtils.parseCryptoKeyParams = function (keyParams) {
3025
  if (keyParams.indexOf('inline:') !== 0) {
3026
    return null;
3027
  }
3028
  var parts = keyParams.substr(7).split('|');
3029
  return {
3030
    keyMethod: 'inline',
3031
    keySalt: parts[0],
3032
    lifeTime: parts[1],
3033
    mkiValue: parts[2] ? parts[2].split(':')[0] : undefined,
3034
    mkiLength: parts[2] ? parts[2].split(':')[1] : undefined
3035
  };
3036
};
3037
 
3038
SDPUtils.writeCryptoKeyParams = function (keyParams) {
3039
  return keyParams.keyMethod + ':' + keyParams.keySalt + (keyParams.lifeTime ? '|' + keyParams.lifeTime : '') + (keyParams.mkiValue && keyParams.mkiLength ? '|' + keyParams.mkiValue + ':' + keyParams.mkiLength : '');
3040
};
3041
 
3042
// Extracts all SDES parameters.
3043
SDPUtils.getCryptoParameters = function (mediaSection, sessionpart) {
3044
  var lines = SDPUtils.matchPrefix(mediaSection + sessionpart, 'a=crypto:');
3045
  return lines.map(SDPUtils.parseCryptoLine);
3046
};
3047
 
3048
// Parses ICE information from SDP media section or sessionpart.
3049
// FIXME: for consistency with other functions this should only
3050
//   get the ice-ufrag and ice-pwd lines as input.
3051
SDPUtils.getIceParameters = function (mediaSection, sessionpart) {
3052
  var ufrag = SDPUtils.matchPrefix(mediaSection + sessionpart, 'a=ice-ufrag:')[0];
3053
  var pwd = SDPUtils.matchPrefix(mediaSection + sessionpart, 'a=ice-pwd:')[0];
3054
  if (!(ufrag && pwd)) {
3055
    return null;
3056
  }
3057
  return {
3058
    usernameFragment: ufrag.substr(12),
3059
    password: pwd.substr(10)
3060
  };
3061
};
3062
 
3063
// Serializes ICE parameters to SDP.
3064
SDPUtils.writeIceParameters = function (params) {
3065
  var sdp = 'a=ice-ufrag:' + params.usernameFragment + '\r\n' + 'a=ice-pwd:' + params.password + '\r\n';
3066
  if (params.iceLite) {
3067
    sdp += 'a=ice-lite\r\n';
3068
  }
3069
  return sdp;
3070
};
3071
 
3072
// Parses the SDP media section and returns RTCRtpParameters.
3073
SDPUtils.parseRtpParameters = function (mediaSection) {
3074
  var description = {
3075
    codecs: [],
3076
    headerExtensions: [],
3077
    fecMechanisms: [],
3078
    rtcp: []
3079
  };
3080
  var lines = SDPUtils.splitLines(mediaSection);
3081
  var mline = lines[0].split(' ');
3082
  for (var i = 3; i < mline.length; i++) {
3083
    // find all codecs from mline[3..]
3084
    var pt = mline[i];
3085
    var rtpmapline = SDPUtils.matchPrefix(mediaSection, 'a=rtpmap:' + pt + ' ')[0];
3086
    if (rtpmapline) {
3087
      var codec = SDPUtils.parseRtpMap(rtpmapline);
3088
      var fmtps = SDPUtils.matchPrefix(mediaSection, 'a=fmtp:' + pt + ' ');
3089
      // Only the first a=fmtp:<pt> is considered.
3090
      codec.parameters = fmtps.length ? SDPUtils.parseFmtp(fmtps[0]) : {};
3091
      codec.rtcpFeedback = SDPUtils.matchPrefix(mediaSection, 'a=rtcp-fb:' + pt + ' ').map(SDPUtils.parseRtcpFb);
3092
      description.codecs.push(codec);
3093
      // parse FEC mechanisms from rtpmap lines.
3094
      switch (codec.name.toUpperCase()) {
3095
        case 'RED':
3096
        case 'ULPFEC':
3097
          description.fecMechanisms.push(codec.name.toUpperCase());
3098
          break;
3099
        default:
3100
          // only RED and ULPFEC are recognized as FEC mechanisms.
3101
          break;
3102
      }
3103
    }
3104
  }
3105
  SDPUtils.matchPrefix(mediaSection, 'a=extmap:').forEach(function (line) {
3106
    description.headerExtensions.push(SDPUtils.parseExtmap(line));
3107
  });
3108
  // FIXME: parse rtcp.
3109
  return description;
3110
};
3111
 
3112
// Generates parts of the SDP media section describing the capabilities /
3113
// parameters.
3114
SDPUtils.writeRtpDescription = function (kind, caps) {
3115
  var sdp = '';
3116
 
3117
  // Build the mline.
3118
  sdp += 'm=' + kind + ' ';
3119
  sdp += caps.codecs.length > 0 ? '9' : '0'; // reject if no codecs.
3120
  sdp += ' UDP/TLS/RTP/SAVPF ';
3121
  sdp += caps.codecs.map(function (codec) {
3122
    if (codec.preferredPayloadType !== undefined) {
3123
      return codec.preferredPayloadType;
3124
    }
3125
    return codec.payloadType;
3126
  }).join(' ') + '\r\n';
3127
 
3128
  sdp += 'c=IN IP4 0.0.0.0\r\n';
3129
  sdp += 'a=rtcp:9 IN IP4 0.0.0.0\r\n';
3130
 
3131
  // Add a=rtpmap lines for each codec. Also fmtp and rtcp-fb.
3132
  caps.codecs.forEach(function (codec) {
3133
    sdp += SDPUtils.writeRtpMap(codec);
3134
    sdp += SDPUtils.writeFmtp(codec);
3135
    sdp += SDPUtils.writeRtcpFb(codec);
3136
  });
3137
  var maxptime = 0;
3138
  caps.codecs.forEach(function (codec) {
3139
    if (codec.maxptime > maxptime) {
3140
      maxptime = codec.maxptime;
3141
    }
3142
  });
3143
  if (maxptime > 0) {
3144
    sdp += 'a=maxptime:' + maxptime + '\r\n';
3145
  }
3146
 
3147
  if (caps.headerExtensions) {
3148
    caps.headerExtensions.forEach(function (extension) {
3149
      sdp += SDPUtils.writeExtmap(extension);
3150
    });
3151
  }
3152
  // FIXME: write fecMechanisms.
3153
  return sdp;
3154
};
3155
 
3156
// Parses the SDP media section and returns an array of
3157
// RTCRtpEncodingParameters.
3158
SDPUtils.parseRtpEncodingParameters = function (mediaSection) {
3159
  var encodingParameters = [];
3160
  var description = SDPUtils.parseRtpParameters(mediaSection);
3161
  var hasRed = description.fecMechanisms.indexOf('RED') !== -1;
3162
  var hasUlpfec = description.fecMechanisms.indexOf('ULPFEC') !== -1;
3163
 
3164
  // filter a=ssrc:... cname:, ignore PlanB-msid
3165
  var ssrcs = SDPUtils.matchPrefix(mediaSection, 'a=ssrc:').map(function (line) {
3166
    return SDPUtils.parseSsrcMedia(line);
3167
  }).filter(function (parts) {
3168
    return parts.attribute === 'cname';
3169
  });
3170
  var primarySsrc = ssrcs.length > 0 && ssrcs[0].ssrc;
3171
  var secondarySsrc = void 0;
3172
 
3173
  var flows = SDPUtils.matchPrefix(mediaSection, 'a=ssrc-group:FID').map(function (line) {
3174
    var parts = line.substr(17).split(' ');
3175
    return parts.map(function (part) {
3176
      return parseInt(part, 10);
3177
    });
3178
  });
3179
  if (flows.length > 0 && flows[0].length > 1 && flows[0][0] === primarySsrc) {
3180
    secondarySsrc = flows[0][1];
3181
  }
3182
 
3183
  description.codecs.forEach(function (codec) {
3184
    if (codec.name.toUpperCase() === 'RTX' && codec.parameters.apt) {
3185
      var encParam = {
3186
        ssrc: primarySsrc,
3187
        codecPayloadType: parseInt(codec.parameters.apt, 10)
3188
      };
3189
      if (primarySsrc && secondarySsrc) {
3190
        encParam.rtx = { ssrc: secondarySsrc };
3191
      }
3192
      encodingParameters.push(encParam);
3193
      if (hasRed) {
3194
        encParam = JSON.parse(JSON.stringify(encParam));
3195
        encParam.fec = {
3196
          ssrc: primarySsrc,
3197
          mechanism: hasUlpfec ? 'red+ulpfec' : 'red'
3198
        };
3199
        encodingParameters.push(encParam);
3200
      }
3201
    }
3202
  });
3203
  if (encodingParameters.length === 0 && primarySsrc) {
3204
    encodingParameters.push({
3205
      ssrc: primarySsrc
3206
    });
3207
  }
3208
 
3209
  // we support both b=AS and b=TIAS but interpret AS as TIAS.
3210
  var bandwidth = SDPUtils.matchPrefix(mediaSection, 'b=');
3211
  if (bandwidth.length) {
3212
    if (bandwidth[0].indexOf('b=TIAS:') === 0) {
3213
      bandwidth = parseInt(bandwidth[0].substr(7), 10);
3214
    } else if (bandwidth[0].indexOf('b=AS:') === 0) {
3215
      // use formula from JSEP to convert b=AS to TIAS value.
3216
      bandwidth = parseInt(bandwidth[0].substr(5), 10) * 1000 * 0.95 - 50 * 40 * 8;
3217
    } else {
3218
      bandwidth = undefined;
3219
    }
3220
    encodingParameters.forEach(function (params) {
3221
      params.maxBitrate = bandwidth;
3222
    });
3223
  }
3224
  return encodingParameters;
3225
};
3226
 
3227
// parses http://draft.ortc.org/#rtcrtcpparameters*
3228
SDPUtils.parseRtcpParameters = function (mediaSection) {
3229
  var rtcpParameters = {};
3230
 
3231
  // Gets the first SSRC. Note that with RTX there might be multiple
3232
  // SSRCs.
3233
  var remoteSsrc = SDPUtils.matchPrefix(mediaSection, 'a=ssrc:').map(function (line) {
3234
    return SDPUtils.parseSsrcMedia(line);
3235
  }).filter(function (obj) {
3236
    return obj.attribute === 'cname';
3237
  })[0];
3238
  if (remoteSsrc) {
3239
    rtcpParameters.cname = remoteSsrc.value;
3240
    rtcpParameters.ssrc = remoteSsrc.ssrc;
3241
  }
3242
 
3243
  // Edge uses the compound attribute instead of reducedSize
3244
  // compound is !reducedSize
3245
  var rsize = SDPUtils.matchPrefix(mediaSection, 'a=rtcp-rsize');
3246
  rtcpParameters.reducedSize = rsize.length > 0;
3247
  rtcpParameters.compound = rsize.length === 0;
3248
 
3249
  // parses the rtcp-mux attrіbute.
3250
  // Note that Edge does not support unmuxed RTCP.
3251
  var mux = SDPUtils.matchPrefix(mediaSection, 'a=rtcp-mux');
3252
  rtcpParameters.mux = mux.length > 0;
3253
 
3254
  return rtcpParameters;
3255
};
3256
 
3257
SDPUtils.writeRtcpParameters = function (rtcpParameters) {
3258
  var sdp = '';
3259
  if (rtcpParameters.reducedSize) {
3260
    sdp += 'a=rtcp-rsize\r\n';
3261
  }
3262
  if (rtcpParameters.mux) {
3263
    sdp += 'a=rtcp-mux\r\n';
3264
  }
3265
  if (rtcpParameters.ssrc !== undefined && rtcpParameters.cname) {
3266
    sdp += 'a=ssrc:' + rtcpParameters.ssrc + ' cname:' + rtcpParameters.cname + '\r\n';
3267
  }
3268
  return sdp;
3269
};
3270
 
3271
// parses either a=msid: or a=ssrc:... msid lines and returns
3272
// the id of the MediaStream and MediaStreamTrack.
3273
SDPUtils.parseMsid = function (mediaSection) {
3274
  var parts = void 0;
3275
  var spec = SDPUtils.matchPrefix(mediaSection, 'a=msid:');
3276
  if (spec.length === 1) {
3277
    parts = spec[0].substr(7).split(' ');
3278
    return { stream: parts[0], track: parts[1] };
3279
  }
3280
  var planB = SDPUtils.matchPrefix(mediaSection, 'a=ssrc:').map(function (line) {
3281
    return SDPUtils.parseSsrcMedia(line);
3282
  }).filter(function (msidParts) {
3283
    return msidParts.attribute === 'msid';
3284
  });
3285
  if (planB.length > 0) {
3286
    parts = planB[0].value.split(' ');
3287
    return { stream: parts[0], track: parts[1] };
3288
  }
3289
};
3290
 
3291
// SCTP
3292
// parses draft-ietf-mmusic-sctp-sdp-26 first and falls back
3293
// to draft-ietf-mmusic-sctp-sdp-05
3294
SDPUtils.parseSctpDescription = function (mediaSection) {
3295
  var mline = SDPUtils.parseMLine(mediaSection);
3296
  var maxSizeLine = SDPUtils.matchPrefix(mediaSection, 'a=max-message-size:');
3297
  var maxMessageSize = void 0;
3298
  if (maxSizeLine.length > 0) {
3299
    maxMessageSize = parseInt(maxSizeLine[0].substr(19), 10);
3300
  }
3301
  if (isNaN(maxMessageSize)) {
3302
    maxMessageSize = 65536;
3303
  }
3304
  var sctpPort = SDPUtils.matchPrefix(mediaSection, 'a=sctp-port:');
3305
  if (sctpPort.length > 0) {
3306
    return {
3307
      port: parseInt(sctpPort[0].substr(12), 10),
3308
      protocol: mline.fmt,
3309
      maxMessageSize: maxMessageSize
3310
    };
3311
  }
3312
  var sctpMapLines = SDPUtils.matchPrefix(mediaSection, 'a=sctpmap:');
3313
  if (sctpMapLines.length > 0) {
3314
    var parts = sctpMapLines[0].substr(10).split(' ');
3315
    return {
3316
      port: parseInt(parts[0], 10),
3317
      protocol: parts[1],
3318
      maxMessageSize: maxMessageSize
3319
    };
3320
  }
3321
};
3322
 
3323
// SCTP
3324
// outputs the draft-ietf-mmusic-sctp-sdp-26 version that all browsers
3325
// support by now receiving in this format, unless we originally parsed
3326
// as the draft-ietf-mmusic-sctp-sdp-05 format (indicated by the m-line
3327
// protocol of DTLS/SCTP -- without UDP/ or TCP/)
3328
SDPUtils.writeSctpDescription = function (media, sctp) {
3329
  var output = [];
3330
  if (media.protocol !== 'DTLS/SCTP') {
3331
    output = ['m=' + media.kind + ' 9 ' + media.protocol + ' ' + sctp.protocol + '\r\n', 'c=IN IP4 0.0.0.0\r\n', 'a=sctp-port:' + sctp.port + '\r\n'];
3332
  } else {
3333
    output = ['m=' + media.kind + ' 9 ' + media.protocol + ' ' + sctp.port + '\r\n', 'c=IN IP4 0.0.0.0\r\n', 'a=sctpmap:' + sctp.port + ' ' + sctp.protocol + ' 65535\r\n'];
3334
  }
3335
  if (sctp.maxMessageSize !== undefined) {
3336
    output.push('a=max-message-size:' + sctp.maxMessageSize + '\r\n');
3337
  }
3338
  return output.join('');
3339
};
3340
 
3341
// Generate a session ID for SDP.
3342
// https://tools.ietf.org/html/draft-ietf-rtcweb-jsep-20#section-5.2.1
3343
// recommends using a cryptographically random +ve 64-bit value
3344
// but right now this should be acceptable and within the right range
3345
SDPUtils.generateSessionId = function () {
3346
  return Math.random().toString().substr(2, 21);
3347
};
3348
 
3349
// Write boiler plate for start of SDP
3350
// sessId argument is optional - if not supplied it will
3351
// be generated randomly
3352
// sessVersion is optional and defaults to 2
3353
// sessUser is optional and defaults to 'thisisadapterortc'
3354
SDPUtils.writeSessionBoilerplate = function (sessId, sessVer, sessUser) {
3355
  var sessionId = void 0;
3356
  var version = sessVer !== undefined ? sessVer : 2;
3357
  if (sessId) {
3358
    sessionId = sessId;
3359
  } else {
3360
    sessionId = SDPUtils.generateSessionId();
3361
  }
3362
  var user = sessUser || 'thisisadapterortc';
3363
  // FIXME: sess-id should be an NTP timestamp.
3364
  return 'v=0\r\n' + 'o=' + user + ' ' + sessionId + ' ' + version + ' IN IP4 127.0.0.1\r\n' + 's=-\r\n' + 't=0 0\r\n';
3365
};
3366
 
3367
// Gets the direction from the mediaSection or the sessionpart.
3368
SDPUtils.getDirection = function (mediaSection, sessionpart) {
3369
  // Look for sendrecv, sendonly, recvonly, inactive, default to sendrecv.
3370
  var lines = SDPUtils.splitLines(mediaSection);
3371
  for (var i = 0; i < lines.length; i++) {
3372
    switch (lines[i]) {
3373
      case 'a=sendrecv':
3374
      case 'a=sendonly':
3375
      case 'a=recvonly':
3376
      case 'a=inactive':
3377
        return lines[i].substr(2);
3378
      default:
3379
      // FIXME: What should happen here?
3380
    }
3381
  }
3382
  if (sessionpart) {
3383
    return SDPUtils.getDirection(sessionpart);
3384
  }
3385
  return 'sendrecv';
3386
};
3387
 
3388
SDPUtils.getKind = function (mediaSection) {
3389
  var lines = SDPUtils.splitLines(mediaSection);
3390
  var mline = lines[0].split(' ');
3391
  return mline[0].substr(2);
3392
};
3393
 
3394
SDPUtils.isRejected = function (mediaSection) {
3395
  return mediaSection.split(' ', 2)[1] === '0';
3396
};
3397
 
3398
SDPUtils.parseMLine = function (mediaSection) {
3399
  var lines = SDPUtils.splitLines(mediaSection);
3400
  var parts = lines[0].substr(2).split(' ');
3401
  return {
3402
    kind: parts[0],
3403
    port: parseInt(parts[1], 10),
3404
    protocol: parts[2],
3405
    fmt: parts.slice(3).join(' ')
3406
  };
3407
};
3408
 
3409
SDPUtils.parseOLine = function (mediaSection) {
3410
  var line = SDPUtils.matchPrefix(mediaSection, 'o=')[0];
3411
  var parts = line.substr(2).split(' ');
3412
  return {
3413
    username: parts[0],
3414
    sessionId: parts[1],
3415
    sessionVersion: parseInt(parts[2], 10),
3416
    netType: parts[3],
3417
    addressType: parts[4],
3418
    address: parts[5]
3419
  };
3420
};
3421
 
3422
// a very naive interpretation of a valid SDP.
3423
SDPUtils.isValidSDP = function (blob) {
3424
  if (typeof blob !== 'string' || blob.length === 0) {
3425
    return false;
3426
  }
3427
  var lines = SDPUtils.splitLines(blob);
3428
  for (var i = 0; i < lines.length; i++) {
3429
    if (lines[i].length < 2 || lines[i].charAt(1) !== '=') {
3430
      return false;
3431
    }
3432
    // TODO: check the modifier a bit more.
3433
  }
3434
  return true;
3435
};
3436
 
3437
// Expose public methods.
3438
if ((typeof module === 'undefined' ? 'undefined' : _typeof(module)) === 'object') {
3439
  module.exports = SDPUtils;
3440
}
3441
},{}]},{},[1])(1)
3442
});