Debian Codegraph @

addons/mail/static/lib/odoo_sfu/odoo_sfu.js

raw symbols SCIP
1 /* @odoo-module */
2 var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
3
4 var lib$2 = {};
5
6 var browser = {exports: {}};
7
8 /**
9 * Helpers.
10 */
11
12 var ms;
13 var hasRequiredMs;
14
15 function requireMs () {
16 if (hasRequiredMs) return ms;
17 hasRequiredMs = 1;
18 var s = 1000;
19 var m = s * 60;
20 var h = m * 60;
21 var d = h * 24;
22 var w = d * 7;
23 var y = d * 365.25;
24
25 /**
26 * Parse or format the given `val`.
27 *
28 * Options:
29 *
30 * - `long` verbose formatting [false]
31 *
32 * @param {String|Number} val
33 * @param {Object} [options]
34 * @throws {Error} throw an error if val is not a non-empty string or a number
35 * @return {String|Number}
36 * @api public
37 */
38
39 ms = function(val, options) {
40 options = options || {};
41 var type = typeof val;
42 if (type === 'string' && val.length > 0) {
43 return parse(val);
44 } else if (type === 'number' && isFinite(val)) {
45 return options.long ? fmtLong(val) : fmtShort(val);
46 }
47 throw new Error(
48 'val is not a non-empty string or a valid number. val=' +
49 JSON.stringify(val)
50 );
51 };
52
53 /**
54 * Parse the given `str` and return milliseconds.
55 *
56 * @param {String} str
57 * @return {Number}
58 * @api private
59 */
60
61 function parse(str) {
62 str = String(str);
63 if (str.length > 100) {
64 return;
65 }
66 var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(
67 str
68 );
69 if (!match) {
70 return;
71 }
72 var n = parseFloat(match[1]);
73 var type = (match[2] || 'ms').toLowerCase();
74 switch (type) {
75 case 'years':
76 case 'year':
77 case 'yrs':
78 case 'yr':
79 case 'y':
80 return n * y;
81 case 'weeks':
82 case 'week':
83 case 'w':
84 return n * w;
85 case 'days':
86 case 'day':
87 case 'd':
88 return n * d;
89 case 'hours':
90 case 'hour':
91 case 'hrs':
92 case 'hr':
93 case 'h':
94 return n * h;
95 case 'minutes':
96 case 'minute':
97 case 'mins':
98 case 'min':
99 case 'm':
100 return n * m;
101 case 'seconds':
102 case 'second':
103 case 'secs':
104 case 'sec':
105 case 's':
106 return n * s;
107 case 'milliseconds':
108 case 'millisecond':
109 case 'msecs':
110 case 'msec':
111 case 'ms':
112 return n;
113 default:
114 return undefined;
115 }
116 }
117
118 /**
119 * Short format for `ms`.
120 *
121 * @param {Number} ms
122 * @return {String}
123 * @api private
124 */
125
126 function fmtShort(ms) {
127 var msAbs = Math.abs(ms);
128 if (msAbs >= d) {
129 return Math.round(ms / d) + 'd';
130 }
131 if (msAbs >= h) {
132 return Math.round(ms / h) + 'h';
133 }
134 if (msAbs >= m) {
135 return Math.round(ms / m) + 'm';
136 }
137 if (msAbs >= s) {
138 return Math.round(ms / s) + 's';
139 }
140 return ms + 'ms';
141 }
142
143 /**
144 * Long format for `ms`.
145 *
146 * @param {Number} ms
147 * @return {String}
148 * @api private
149 */
150
151 function fmtLong(ms) {
152 var msAbs = Math.abs(ms);
153 if (msAbs >= d) {
154 return plural(ms, msAbs, d, 'day');
155 }
156 if (msAbs >= h) {
157 return plural(ms, msAbs, h, 'hour');
158 }
159 if (msAbs >= m) {
160 return plural(ms, msAbs, m, 'minute');
161 }
162 if (msAbs >= s) {
163 return plural(ms, msAbs, s, 'second');
164 }
165 return ms + ' ms';
166 }
167
168 /**
169 * Pluralization helper.
170 */
171
172 function plural(ms, msAbs, n, name) {
173 var isPlural = msAbs >= n * 1.5;
174 return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');
175 }
176 return ms;
177 }
178
179 /**
180 * This is the common logic for both the Node.js and web browser
181 * implementations of `debug()`.
182 */
183
184 function setup(env) {
185 createDebug.debug = createDebug;
186 createDebug.default = createDebug;
187 createDebug.coerce = coerce;
188 createDebug.disable = disable;
189 createDebug.enable = enable;
190 createDebug.enabled = enabled;
191 createDebug.humanize = requireMs();
192 createDebug.destroy = destroy;
193
194 Object.keys(env).forEach(key => {
195 createDebug[key] = env[key];
196 });
197
198 /**
199 * The currently active debug mode names, and names to skip.
200 */
201
202 createDebug.names = [];
203 createDebug.skips = [];
204
205 /**
206 * Map of special "%n" handling functions, for the debug "format" argument.
207 *
208 * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N".
209 */
210 createDebug.formatters = {};
211
212 /**
213 * Selects a color for a debug namespace
214 * @param {String} namespace The namespace string for the debug instance to be colored
215 * @return {Number|String} An ANSI color code for the given namespace
216 * @api private
217 */
218 function selectColor(namespace) {
219 let hash = 0;
220
221 for (let i = 0; i < namespace.length; i++) {
222 hash = ((hash << 5) - hash) + namespace.charCodeAt(i);
223 hash |= 0; // Convert to 32bit integer
224 }
225
226 return createDebug.colors[Math.abs(hash) % createDebug.colors.length];
227 }
228 createDebug.selectColor = selectColor;
229
230 /**
231 * Create a debugger with the given `namespace`.
232 *
233 * @param {String} namespace
234 * @return {Function}
235 * @api public
236 */
237 function createDebug(namespace) {
238 let prevTime;
239 let enableOverride = null;
240 let namespacesCache;
241 let enabledCache;
242
243 function debug(...args) {
244 // Disabled?
245 if (!debug.enabled) {
246 return;
247 }
248
249 const self = debug;
250
251 // Set `diff` timestamp
252 const curr = Number(new Date());
253 const ms = curr - (prevTime || curr);
254 self.diff = ms;
255 self.prev = prevTime;
256 self.curr = curr;
257 prevTime = curr;
258
259 args[0] = createDebug.coerce(args[0]);
260
261 if (typeof args[0] !== 'string') {
262 // Anything else let's inspect with %O
263 args.unshift('%O');
264 }
265
266 // Apply any `formatters` transformations
267 let index = 0;
268 args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => {
269 // If we encounter an escaped % then don't increase the array index
270 if (match === '%%') {
271 return '%';
272 }
273 index++;
274 const formatter = createDebug.formatters[format];
275 if (typeof formatter === 'function') {
276 const val = args[index];
277 match = formatter.call(self, val);
278
279 // Now we need to remove `args[index]` since it's inlined in the `format`
280 args.splice(index, 1);
281 index--;
282 }
283 return match;
284 });
285
286 // Apply env-specific formatting (colors, etc.)
287 createDebug.formatArgs.call(self, args);
288
289 const logFn = self.log || createDebug.log;
290 logFn.apply(self, args);
291 }
292
293 debug.namespace = namespace;
294 debug.useColors = createDebug.useColors();
295 debug.color = createDebug.selectColor(namespace);
296 debug.extend = extend;
297 debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release.
298
299 Object.defineProperty(debug, 'enabled', {
300 enumerable: true,
301 configurable: false,
302 get: () => {
303 if (enableOverride !== null) {
304 return enableOverride;
305 }
306 if (namespacesCache !== createDebug.namespaces) {
307 namespacesCache = createDebug.namespaces;
308 enabledCache = createDebug.enabled(namespace);
309 }
310
311 return enabledCache;
312 },
313 set: v => {
314 enableOverride = v;
315 }
316 });
317
318 // Env-specific initialization logic for debug instances
319 if (typeof createDebug.init === 'function') {
320 createDebug.init(debug);
321 }
322
323 return debug;
324 }
325
326 function extend(namespace, delimiter) {
327 const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace);
328 newDebug.log = this.log;
329 return newDebug;
330 }
331
332 /**
333 * Enables a debug mode by namespaces. This can include modes
334 * separated by a colon and wildcards.
335 *
336 * @param {String} namespaces
337 * @api public
338 */
339 function enable(namespaces) {
340 createDebug.save(namespaces);
341 createDebug.namespaces = namespaces;
342
343 createDebug.names = [];
344 createDebug.skips = [];
345
346 let i;
347 const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/);
348 const len = split.length;
349
350 for (i = 0; i < len; i++) {
351 if (!split[i]) {
352 // ignore empty strings
353 continue;
354 }
355
356 namespaces = split[i].replace(/\*/g, '.*?');
357
358 if (namespaces[0] === '-') {
359 createDebug.skips.push(new RegExp('^' + namespaces.slice(1) + '$'));
360 } else {
361 createDebug.names.push(new RegExp('^' + namespaces + '$'));
362 }
363 }
364 }
365
366 /**
367 * Disable debug output.
368 *
369 * @return {String} namespaces
370 * @api public
371 */
372 function disable() {
373 const namespaces = [
374 ...createDebug.names.map(toNamespace),
375 ...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace)
376 ].join(',');
377 createDebug.enable('');
378 return namespaces;
379 }
380
381 /**
382 * Returns true if the given mode name is enabled, false otherwise.
383 *
384 * @param {String} name
385 * @return {Boolean}
386 * @api public
387 */
388 function enabled(name) {
389 if (name[name.length - 1] === '*') {
390 return true;
391 }
392
393 let i;
394 let len;
395
396 for (i = 0, len = createDebug.skips.length; i < len; i++) {
397 if (createDebug.skips[i].test(name)) {
398 return false;
399 }
400 }
401
402 for (i = 0, len = createDebug.names.length; i < len; i++) {
403 if (createDebug.names[i].test(name)) {
404 return true;
405 }
406 }
407
408 return false;
409 }
410
411 /**
412 * Convert regexp to namespace
413 *
414 * @param {RegExp} regxep
415 * @return {String} namespace
416 * @api private
417 */
418 function toNamespace(regexp) {
419 return regexp.toString()
420 .substring(2, regexp.toString().length - 2)
421 .replace(/\.\*\?$/, '*');
422 }
423
424 /**
425 * Coerce `val`.
426 *
427 * @param {Mixed} val
428 * @return {Mixed}
429 * @api private
430 */
431 function coerce(val) {
432 if (val instanceof Error) {
433 return val.stack || val.message;
434 }
435 return val;
436 }
437
438 /**
439 * XXX DO NOT USE. This is a temporary stub function.
440 * XXX It WILL be removed in the next major release.
441 */
442 function destroy() {
443 console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');
444 }
445
446 createDebug.enable(createDebug.load());
447
448 return createDebug;
449 }
450
451 var common = setup;
452
453 /* eslint-env browser */
454 browser.exports;
455
456 (function (module, exports) {
457 /**
458 * This is the web browser implementation of `debug()`.
459 */
460
461 exports.formatArgs = formatArgs;
462 exports.save = save;
463 exports.load = load;
464 exports.useColors = useColors;
465 exports.storage = localstorage();
466 exports.destroy = (() => {
467 let warned = false;
468
469 return () => {
470 if (!warned) {
471 warned = true;
472 console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');
473 }
474 };
475 })();
476
477 /**
478 * Colors.
479 */
480
481 exports.colors = [
482 '#0000CC',
483 '#0000FF',
484 '#0033CC',
485 '#0033FF',
486 '#0066CC',
487 '#0066FF',
488 '#0099CC',
489 '#0099FF',
490 '#00CC00',
491 '#00CC33',
492 '#00CC66',
493 '#00CC99',
494 '#00CCCC',
495 '#00CCFF',
496 '#3300CC',
497 '#3300FF',
498 '#3333CC',
499 '#3333FF',
500 '#3366CC',
501 '#3366FF',
502 '#3399CC',
503 '#3399FF',
504 '#33CC00',
505 '#33CC33',
506 '#33CC66',
507 '#33CC99',
508 '#33CCCC',
509 '#33CCFF',
510 '#6600CC',
511 '#6600FF',
512 '#6633CC',
513 '#6633FF',
514 '#66CC00',
515 '#66CC33',
516 '#9900CC',
517 '#9900FF',
518 '#9933CC',
519 '#9933FF',
520 '#99CC00',
521 '#99CC33',
522 '#CC0000',
523 '#CC0033',
524 '#CC0066',
525 '#CC0099',
526 '#CC00CC',
527 '#CC00FF',
528 '#CC3300',
529 '#CC3333',
530 '#CC3366',
531 '#CC3399',
532 '#CC33CC',
533 '#CC33FF',
534 '#CC6600',
535 '#CC6633',
536 '#CC9900',
537 '#CC9933',
538 '#CCCC00',
539 '#CCCC33',
540 '#FF0000',
541 '#FF0033',
542 '#FF0066',
543 '#FF0099',
544 '#FF00CC',
545 '#FF00FF',
546 '#FF3300',
547 '#FF3333',
548 '#FF3366',
549 '#FF3399',
550 '#FF33CC',
551 '#FF33FF',
552 '#FF6600',
553 '#FF6633',
554 '#FF9900',
555 '#FF9933',
556 '#FFCC00',
557 '#FFCC33'
558 ];
559
560 /**
561 * Currently only WebKit-based Web Inspectors, Firefox >= v31,
562 * and the Firebug extension (any Firefox version) are known
563 * to support "%c" CSS customizations.
564 *
565 * TODO: add a `localStorage` variable to explicitly enable/disable colors
566 */
567
568 // eslint-disable-next-line complexity
569 function useColors() {
570 // NB: In an Electron preload script, document will be defined but not fully
571 // initialized. Since we know we're in Chrome, we'll just detect this case
572 // explicitly
573 if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) {
574 return true;
575 }
576
577 // Internet Explorer and Edge do not support colors.
578 if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) {
579 return false;
580 }
581
582 // Is webkit? http://stackoverflow.com/a/16459606/376773
583 // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632
584 return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||
585 // Is firebug? http://stackoverflow.com/a/398120/376773
586 (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||
587 // Is firefox >= v31?
588 // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
589 (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) ||
590 // Double check webkit in userAgent just in case we are in a worker
591 (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/));
592 }
593
594 /**
595 * Colorize log arguments if enabled.
596 *
597 * @api public
598 */
599
600 function formatArgs(args) {
601 args[0] = (this.useColors ? '%c' : '') +
602 this.namespace +
603 (this.useColors ? ' %c' : ' ') +
604 args[0] +
605 (this.useColors ? '%c ' : ' ') +
606 '+' + module.exports.humanize(this.diff);
607
608 if (!this.useColors) {
609 return;
610 }
611
612 const c = 'color: ' + this.color;
613 args.splice(1, 0, c, 'color: inherit');
614
615 // The final "%c" is somewhat tricky, because there could be other
616 // arguments passed either before or after the %c, so we need to
617 // figure out the correct index to insert the CSS into
618 let index = 0;
619 let lastC = 0;
620 args[0].replace(/%[a-zA-Z%]/g, match => {
621 if (match === '%%') {
622 return;
623 }
624 index++;
625 if (match === '%c') {
626 // We only are interested in the *last* %c
627 // (the user may have provided their own)
628 lastC = index;
629 }
630 });
631
632 args.splice(lastC, 0, c);
633 }
634
635 /**
636 * Invokes `console.debug()` when available.
637 * No-op when `console.debug` is not a "function".
638 * If `console.debug` is not available, falls back
639 * to `console.log`.
640 *
641 * @api public
642 */
643 exports.log = console.debug || console.log || (() => {});
644
645 /**
646 * Save `namespaces`.
647 *
648 * @param {String} namespaces
649 * @api private
650 */
651 function save(namespaces) {
652 try {
653 if (namespaces) {
654 exports.storage.setItem('debug', namespaces);
655 } else {
656 exports.storage.removeItem('debug');
657 }
658 } catch (error) {
659 // Swallow
660 // XXX (@Qix-) should we be logging these?
661 }
662 }
663
664 /**
665 * Load `namespaces`.
666 *
667 * @return {String} returns the previously persisted debug modes
668 * @api private
669 */
670 function load() {
671 let r;
672 try {
673 r = exports.storage.getItem('debug');
674 } catch (error) {
675 // Swallow
676 // XXX (@Qix-) should we be logging these?
677 }
678
679 // If debug isn't set in LS, and we're in Electron, try to load $DEBUG
680 if (!r && typeof process !== 'undefined' && 'env' in process) {
681 r = process.env.DEBUG;
682 }
683
684 return r;
685 }
686
687 /**
688 * Localstorage attempts to return the localstorage.
689 *
690 * This is necessary because safari throws
691 * when a user disables cookies/localstorage
692 * and you attempt to access it.
693 *
694 * @return {LocalStorage}
695 * @api private
696 */
697
698 function localstorage() {
699 try {
700 // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context
701 // The Browser also has localStorage in the global context.
702 return localStorage;
703 } catch (error) {
704 // Swallow
705 // XXX (@Qix-) should we be logging these?
706 }
707 }
708
709 module.exports = common(exports);
710
711 const {formatters} = module.exports;
712
713 /**
714 * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
715 */
716
717 formatters.j = function (v) {
718 try {
719 return JSON.stringify(v);
720 } catch (error) {
721 return '[UnexpectedJSONParseError]: ' + error.message;
722 }
723 };
724 } (browser, browser.exports));
725
726 var browserExports = browser.exports;
727
728 var Device$1 = {};
729
730 var uaParser = {exports: {}};
731
732 uaParser.exports;
733
734 (function (module, exports) {
735 /////////////////////////////////////////////////////////////////////////////////
736 /* UAParser.js v1.0.37
737 Copyright © 2012-2021 Faisal Salman <[email protected]>
738 MIT License *//*
739 Detect Browser, Engine, OS, CPU, and Device type/model from User-Agent data.
740 Supports browser & node.js environment.
741 Demo : https://faisalman.github.io/ua-parser-js
742 Source : https://github.com/faisalman/ua-parser-js */
743 /////////////////////////////////////////////////////////////////////////////////
744
745 (function (window, undefined$1) {
746
747 //////////////
748 // Constants
749 /////////////
750
751
752 var LIBVERSION = '1.0.37',
753 EMPTY = '',
754 UNKNOWN = '?',
755 FUNC_TYPE = 'function',
756 UNDEF_TYPE = 'undefined',
757 OBJ_TYPE = 'object',
758 STR_TYPE = 'string',
759 MAJOR = 'major',
760 MODEL = 'model',
761 NAME = 'name',
762 TYPE = 'type',
763 VENDOR = 'vendor',
764 VERSION = 'version',
765 ARCHITECTURE= 'architecture',
766 CONSOLE = 'console',
767 MOBILE = 'mobile',
768 TABLET = 'tablet',
769 SMARTTV = 'smarttv',
770 WEARABLE = 'wearable',
771 EMBEDDED = 'embedded',
772 UA_MAX_LENGTH = 500;
773
774 var AMAZON = 'Amazon',
775 APPLE = 'Apple',
776 ASUS = 'ASUS',
777 BLACKBERRY = 'BlackBerry',
778 BROWSER = 'Browser',
779 CHROME = 'Chrome',
780 EDGE = 'Edge',
781 FIREFOX = 'Firefox',
782 GOOGLE = 'Google',
783 HUAWEI = 'Huawei',
784 LG = 'LG',
785 MICROSOFT = 'Microsoft',
786 MOTOROLA = 'Motorola',
787 OPERA = 'Opera',
788 SAMSUNG = 'Samsung',
789 SHARP = 'Sharp',
790 SONY = 'Sony',
791 XIAOMI = 'Xiaomi',
792 ZEBRA = 'Zebra',
793 FACEBOOK = 'Facebook',
794 CHROMIUM_OS = 'Chromium OS',
795 MAC_OS = 'Mac OS';
796
797 ///////////
798 // Helper
799 //////////
800
801 var extend = function (regexes, extensions) {
802 var mergedRegexes = {};
803 for (var i in regexes) {
804 if (extensions[i] && extensions[i].length % 2 === 0) {
805 mergedRegexes[i] = extensions[i].concat(regexes[i]);
806 } else {
807 mergedRegexes[i] = regexes[i];
808 }
809 }
810 return mergedRegexes;
811 },
812 enumerize = function (arr) {
813 var enums = {};
814 for (var i=0; i<arr.length; i++) {
815 enums[arr[i].toUpperCase()] = arr[i];
816 }
817 return enums;
818 },
819 has = function (str1, str2) {
820 return typeof str1 === STR_TYPE ? lowerize(str2).indexOf(lowerize(str1)) !== -1 : false;
821 },
822 lowerize = function (str) {
823 return str.toLowerCase();
824 },
825 majorize = function (version) {
826 return typeof(version) === STR_TYPE ? version.replace(/[^\d\.]/g, EMPTY).split('.')[0] : undefined$1;
827 },
828 trim = function (str, len) {
829 if (typeof(str) === STR_TYPE) {
830 str = str.replace(/^\s\s*/, EMPTY);
831 return typeof(len) === UNDEF_TYPE ? str : str.substring(0, UA_MAX_LENGTH);
832 }
833 };
834
835 ///////////////
836 // Map helper
837 //////////////
838
839 var rgxMapper = function (ua, arrays) {
840
841 var i = 0, j, k, p, q, matches, match;
842
843 // loop through all regexes maps
844 while (i < arrays.length && !matches) {
845
846 var regex = arrays[i], // even sequence (0,2,4,..)
847 props = arrays[i + 1]; // odd sequence (1,3,5,..)
848 j = k = 0;
849
850 // try matching uastring with regexes
851 while (j < regex.length && !matches) {
852
853 if (!regex[j]) { break; }
854 matches = regex[j++].exec(ua);
855
856 if (!!matches) {
857 for (p = 0; p < props.length; p++) {
858 match = matches[++k];
859 q = props[p];
860 // check if given property is actually array
861 if (typeof q === OBJ_TYPE && q.length > 0) {
862 if (q.length === 2) {
863 if (typeof q[1] == FUNC_TYPE) {
864 // assign modified match
865 this[q[0]] = q[1].call(this, match);
866 } else {
867 // assign given value, ignore regex match
868 this[q[0]] = q[1];
869 }
870 } else if (q.length === 3) {
871 // check whether function or regex
872 if (typeof q[1] === FUNC_TYPE && !(q[1].exec && q[1].test)) {
873 // call function (usually string mapper)
874 this[q[0]] = match ? q[1].call(this, match, q[2]) : undefined$1;
875 } else {
876 // sanitize match using given regex
877 this[q[0]] = match ? match.replace(q[1], q[2]) : undefined$1;
878 }
879 } else if (q.length === 4) {
880 this[q[0]] = match ? q[3].call(this, match.replace(q[1], q[2])) : undefined$1;
881 }
882 } else {
883 this[q] = match ? match : undefined$1;
884 }
885 }
886 }
887 }
888 i += 2;
889 }
890 },
891
892 strMapper = function (str, map) {
893
894 for (var i in map) {
895 // check if current value is array
896 if (typeof map[i] === OBJ_TYPE && map[i].length > 0) {
897 for (var j = 0; j < map[i].length; j++) {
898 if (has(map[i][j], str)) {
899 return (i === UNKNOWN) ? undefined$1 : i;
900 }
901 }
902 } else if (has(map[i], str)) {
903 return (i === UNKNOWN) ? undefined$1 : i;
904 }
905 }
906 return str;
907 };
908
909 ///////////////
910 // String map
911 //////////////
912
913 // Safari < 3.0
914 var oldSafariMap = {
915 '1.0' : '/8',
916 '1.2' : '/1',
917 '1.3' : '/3',
918 '2.0' : '/412',
919 '2.0.2' : '/416',
920 '2.0.3' : '/417',
921 '2.0.4' : '/419',
922 '?' : '/'
923 },
924 windowsVersionMap = {
925 'ME' : '4.90',
926 'NT 3.11' : 'NT3.51',
927 'NT 4.0' : 'NT4.0',
928 '2000' : 'NT 5.0',
929 'XP' : ['NT 5.1', 'NT 5.2'],
930 'Vista' : 'NT 6.0',
931 '7' : 'NT 6.1',
932 '8' : 'NT 6.2',
933 '8.1' : 'NT 6.3',
934 '10' : ['NT 6.4', 'NT 10.0'],
935 'RT' : 'ARM'
936 };
937
938 //////////////
939 // Regex map
940 /////////////
941
942 var regexes = {
943
944 browser : [[
945
946 /\b(?:crmo|crios)\/([\w\.]+)/i // Chrome for Android/iOS
947 ], [VERSION, [NAME, 'Chrome']], [
948 /edg(?:e|ios|a)?\/([\w\.]+)/i // Microsoft Edge
949 ], [VERSION, [NAME, 'Edge']], [
950
951 // Presto based
952 /(opera mini)\/([-\w\.]+)/i, // Opera Mini
953 /(opera [mobiletab]{3,6})\b.+version\/([-\w\.]+)/i, // Opera Mobi/Tablet
954 /(opera)(?:.+version\/|[\/ ]+)([\w\.]+)/i // Opera
955 ], [NAME, VERSION], [
956 /opios[\/ ]+([\w\.]+)/i // Opera mini on iphone >= 8.0
957 ], [VERSION, [NAME, OPERA+' Mini']], [
958 /\bopr\/([\w\.]+)/i // Opera Webkit
959 ], [VERSION, [NAME, OPERA]], [
960
961 // Mixed
962 /\bb[ai]*d(?:uhd|[ub]*[aekoprswx]{5,6})[\/ ]?([\w\.]+)/i // Baidu
963 ], [VERSION, [NAME, 'Baidu']], [
964 /(kindle)\/([\w\.]+)/i, // Kindle
965 /(lunascape|maxthon|netfront|jasmine|blazer)[\/ ]?([\w\.]*)/i, // Lunascape/Maxthon/Netfront/Jasmine/Blazer
966 // Trident based
967 /(avant|iemobile|slim)\s?(?:browser)?[\/ ]?([\w\.]*)/i, // Avant/IEMobile/SlimBrowser
968 /(?:ms|\()(ie) ([\w\.]+)/i, // Internet Explorer
969
970 // Webkit/KHTML based // Flock/RockMelt/Midori/Epiphany/Silk/Skyfire/Bolt/Iron/Iridium/PhantomJS/Bowser/QupZilla/Falkon
971 /(flock|rockmelt|midori|epiphany|silk|skyfire|bolt|iron|vivaldi|iridium|phantomjs|bowser|quark|qupzilla|falkon|rekonq|puffin|brave|whale(?!.+naver)|qqbrowserlite|qq|duckduckgo)\/([-\w\.]+)/i,
972 // Rekonq/Puffin/Brave/Whale/QQBrowserLite/QQ, aka ShouQ
973 /(heytap|ovi)browser\/([\d\.]+)/i, // Heytap/Ovi
974 /(weibo)__([\d\.]+)/i // Weibo
975 ], [NAME, VERSION], [
976 /(?:\buc? ?browser|(?:juc.+)ucweb)[\/ ]?([\w\.]+)/i // UCBrowser
977 ], [VERSION, [NAME, 'UC'+BROWSER]], [
978 /microm.+\bqbcore\/([\w\.]+)/i, // WeChat Desktop for Windows Built-in Browser
979 /\bqbcore\/([\w\.]+).+microm/i,
980 /micromessenger\/([\w\.]+)/i // WeChat
981 ], [VERSION, [NAME, 'WeChat']], [
982 /konqueror\/([\w\.]+)/i // Konqueror
983 ], [VERSION, [NAME, 'Konqueror']], [
984 /trident.+rv[: ]([\w\.]{1,9})\b.+like gecko/i // IE11
985 ], [VERSION, [NAME, 'IE']], [
986 /ya(?:search)?browser\/([\w\.]+)/i // Yandex
987 ], [VERSION, [NAME, 'Yandex']], [
988 /slbrowser\/([\w\.]+)/i // Smart Lenovo Browser
989 ], [VERSION, [NAME, 'Smart Lenovo '+BROWSER]], [
990 /(avast|avg)\/([\w\.]+)/i // Avast/AVG Secure Browser
991 ], [[NAME, /(.+)/, '$1 Secure '+BROWSER], VERSION], [
992 /\bfocus\/([\w\.]+)/i // Firefox Focus
993 ], [VERSION, [NAME, FIREFOX+' Focus']], [
994 /\bopt\/([\w\.]+)/i // Opera Touch
995 ], [VERSION, [NAME, OPERA+' Touch']], [
996 /coc_coc\w+\/([\w\.]+)/i // Coc Coc Browser
997 ], [VERSION, [NAME, 'Coc Coc']], [
998 /dolfin\/([\w\.]+)/i // Dolphin
999 ], [VERSION, [NAME, 'Dolphin']], [
1000 /coast\/([\w\.]+)/i // Opera Coast
1001 ], [VERSION, [NAME, OPERA+' Coast']], [
1002 /miuibrowser\/([\w\.]+)/i // MIUI Browser
1003 ], [VERSION, [NAME, 'MIUI '+BROWSER]], [
1004 /fxios\/([-\w\.]+)/i // Firefox for iOS
1005 ], [VERSION, [NAME, FIREFOX]], [
1006 /\bqihu|(qi?ho?o?|360)browser/i // 360
1007 ], [[NAME, '360 ' + BROWSER]], [
1008 /(oculus|sailfish|huawei|vivo)browser\/([\w\.]+)/i
1009 ], [[NAME, /(.+)/, '$1 ' + BROWSER], VERSION], [ // Oculus/Sailfish/HuaweiBrowser/VivoBrowser
1010 /samsungbrowser\/([\w\.]+)/i // Samsung Internet
1011 ], [VERSION, [NAME, SAMSUNG + ' Internet']], [
1012 /(comodo_dragon)\/([\w\.]+)/i // Comodo Dragon
1013 ], [[NAME, /_/g, ' '], VERSION], [
1014 /metasr[\/ ]?([\d\.]+)/i // Sogou Explorer
1015 ], [VERSION, [NAME, 'Sogou Explorer']], [
1016 /(sogou)mo\w+\/([\d\.]+)/i // Sogou Mobile
1017 ], [[NAME, 'Sogou Mobile'], VERSION], [
1018 /(electron)\/([\w\.]+) safari/i, // Electron-based App
1019 /(tesla)(?: qtcarbrowser|\/(20\d\d\.[-\w\.]+))/i, // Tesla
1020 /m?(qqbrowser|2345Explorer)[\/ ]?([\w\.]+)/i // QQBrowser/2345 Browser
1021 ], [NAME, VERSION], [
1022 /(lbbrowser)/i, // LieBao Browser
1023 /\[(linkedin)app\]/i // LinkedIn App for iOS & Android
1024 ], [NAME], [
1025
1026 // WebView
1027 /((?:fban\/fbios|fb_iab\/fb4a)(?!.+fbav)|;fbav\/([\w\.]+);)/i // Facebook App for iOS & Android
1028 ], [[NAME, FACEBOOK], VERSION], [
1029 /(Klarna)\/([\w\.]+)/i, // Klarna Shopping Browser for iOS & Android
1030 /(kakao(?:talk|story))[\/ ]([\w\.]+)/i, // Kakao App
1031 /(naver)\(.*?(\d+\.[\w\.]+).*\)/i, // Naver InApp
1032 /safari (line)\/([\w\.]+)/i, // Line App for iOS
1033 /\b(line)\/([\w\.]+)\/iab/i, // Line App for Android
1034 /(alipay)client\/([\w\.]+)/i, // Alipay
1035 /(chromium|instagram|snapchat)[\/ ]([-\w\.]+)/i // Chromium/Instagram/Snapchat
1036 ], [NAME, VERSION], [
1037 /\bgsa\/([\w\.]+) .*safari\//i // Google Search Appliance on iOS
1038 ], [VERSION, [NAME, 'GSA']], [
1039 /musical_ly(?:.+app_?version\/|_)([\w\.]+)/i // TikTok
1040 ], [VERSION, [NAME, 'TikTok']], [
1041
1042 /headlesschrome(?:\/([\w\.]+)| )/i // Chrome Headless
1043 ], [VERSION, [NAME, CHROME+' Headless']], [
1044
1045 / wv\).+(chrome)\/([\w\.]+)/i // Chrome WebView
1046 ], [[NAME, CHROME+' WebView'], VERSION], [
1047
1048 /droid.+ version\/([\w\.]+)\b.+(?:mobile safari|safari)/i // Android Browser
1049 ], [VERSION, [NAME, 'Android '+BROWSER]], [
1050
1051 /(chrome|omniweb|arora|[tizenoka]{5} ?browser)\/v?([\w\.]+)/i // Chrome/OmniWeb/Arora/Tizen/Nokia
1052 ], [NAME, VERSION], [
1053
1054 /version\/([\w\.\,]+) .*mobile\/\w+ (safari)/i // Mobile Safari
1055 ], [VERSION, [NAME, 'Mobile Safari']], [
1056 /version\/([\w(\.|\,)]+) .*(mobile ?safari|safari)/i // Safari & Safari Mobile
1057 ], [VERSION, NAME], [
1058 /webkit.+?(mobile ?safari|safari)(\/[\w\.]+)/i // Safari < 3.0
1059 ], [NAME, [VERSION, strMapper, oldSafariMap]], [
1060
1061 /(webkit|khtml)\/([\w\.]+)/i
1062 ], [NAME, VERSION], [
1063
1064 // Gecko based
1065 /(navigator|netscape\d?)\/([-\w\.]+)/i // Netscape
1066 ], [[NAME, 'Netscape'], VERSION], [
1067 /mobile vr; rv:([\w\.]+)\).+firefox/i // Firefox Reality
1068 ], [VERSION, [NAME, FIREFOX+' Reality']], [
1069 /ekiohf.+(flow)\/([\w\.]+)/i, // Flow
1070 /(swiftfox)/i, // Swiftfox
1071 /(icedragon|iceweasel|camino|chimera|fennec|maemo browser|minimo|conkeror|klar)[\/ ]?([\w\.\+]+)/i,
1072 // IceDragon/Iceweasel/Camino/Chimera/Fennec/Maemo/Minimo/Conkeror/Klar
1073 /(seamonkey|k-meleon|icecat|iceape|firebird|phoenix|palemoon|basilisk|waterfox)\/([-\w\.]+)$/i,
1074 // Firefox/SeaMonkey/K-Meleon/IceCat/IceApe/Firebird/Phoenix
1075 /(firefox)\/([\w\.]+)/i, // Other Firefox-based
1076 /(mozilla)\/([\w\.]+) .+rv\:.+gecko\/\d+/i, // Mozilla
1077
1078 // Other
1079 /(polaris|lynx|dillo|icab|doris|amaya|w3m|netsurf|sleipnir|obigo|mosaic|(?:go|ice|up)[\. ]?browser)[-\/ ]?v?([\w\.]+)/i,
1080 // Polaris/Lynx/Dillo/iCab/Doris/Amaya/w3m/NetSurf/Sleipnir/Obigo/Mosaic/Go/ICE/UP.Browser
1081 /(links) \(([\w\.]+)/i, // Links
1082 /panasonic;(viera)/i // Panasonic Viera
1083 ], [NAME, VERSION], [
1084
1085 /(cobalt)\/([\w\.]+)/i // Cobalt
1086 ], [NAME, [VERSION, /master.|lts./, ""]]
1087 ],
1088
1089 cpu : [[
1090
1091 /(?:(amd|x(?:(?:86|64)[-_])?|wow|win)64)[;\)]/i // AMD64 (x64)
1092 ], [[ARCHITECTURE, 'amd64']], [
1093
1094 /(ia32(?=;))/i // IA32 (quicktime)
1095 ], [[ARCHITECTURE, lowerize]], [
1096
1097 /((?:i[346]|x)86)[;\)]/i // IA32 (x86)
1098 ], [[ARCHITECTURE, 'ia32']], [
1099
1100 /\b(aarch64|arm(v?8e?l?|_?64))\b/i // ARM64
1101 ], [[ARCHITECTURE, 'arm64']], [
1102
1103 /\b(arm(?:v[67])?ht?n?[fl]p?)\b/i // ARMHF
1104 ], [[ARCHITECTURE, 'armhf']], [
1105
1106 // PocketPC mistakenly identified as PowerPC
1107 /windows (ce|mobile); ppc;/i
1108 ], [[ARCHITECTURE, 'arm']], [
1109
1110 /((?:ppc|powerpc)(?:64)?)(?: mac|;|\))/i // PowerPC
1111 ], [[ARCHITECTURE, /ower/, EMPTY, lowerize]], [
1112
1113 /(sun4\w)[;\)]/i // SPARC
1114 ], [[ARCHITECTURE, 'sparc']], [
1115
1116 /((?:avr32|ia64(?=;))|68k(?=\))|\barm(?=v(?:[1-7]|[5-7]1)l?|;|eabi)|(?=atmel )avr|(?:irix|mips|sparc)(?:64)?\b|pa-risc)/i
1117 // IA64, 68K, ARM/64, AVR/32, IRIX/64, MIPS/64, SPARC/64, PA-RISC
1118 ], [[ARCHITECTURE, lowerize]]
1119 ],
1120
1121 device : [[
1122
1123 //////////////////////////
1124 // MOBILES & TABLETS
1125 /////////////////////////
1126
1127 // Samsung
1128 /\b(sch-i[89]0\d|shw-m380s|sm-[ptx]\w{2,4}|gt-[pn]\d{2,4}|sgh-t8[56]9|nexus 10)/i
1129 ], [MODEL, [VENDOR, SAMSUNG], [TYPE, TABLET]], [
1130 /\b((?:s[cgp]h|gt|sm)-\w+|sc[g-]?[\d]+a?|galaxy nexus)/i,
1131 /samsung[- ]([-\w]+)/i,
1132 /sec-(sgh\w+)/i
1133 ], [MODEL, [VENDOR, SAMSUNG], [TYPE, MOBILE]], [
1134
1135 // Apple
1136 /(?:\/|\()(ip(?:hone|od)[\w, ]*)(?:\/|;)/i // iPod/iPhone
1137 ], [MODEL, [VENDOR, APPLE], [TYPE, MOBILE]], [
1138 /\((ipad);[-\w\),; ]+apple/i, // iPad
1139 /applecoremedia\/[\w\.]+ \((ipad)/i,
1140 /\b(ipad)\d\d?,\d\d?[;\]].+ios/i
1141 ], [MODEL, [VENDOR, APPLE], [TYPE, TABLET]], [
1142 /(macintosh);/i
1143 ], [MODEL, [VENDOR, APPLE]], [
1144
1145 // Sharp
1146 /\b(sh-?[altvz]?\d\d[a-ekm]?)/i
1147 ], [MODEL, [VENDOR, SHARP], [TYPE, MOBILE]], [
1148
1149 // Huawei
1150 /\b((?:ag[rs][23]?|bah2?|sht?|btv)-a?[lw]\d{2})\b(?!.+d\/s)/i
1151 ], [MODEL, [VENDOR, HUAWEI], [TYPE, TABLET]], [
1152 /(?:huawei|honor)([-\w ]+)[;\)]/i,
1153 /\b(nexus 6p|\w{2,4}e?-[atu]?[ln][\dx][012359c][adn]?)\b(?!.+d\/s)/i
1154 ], [MODEL, [VENDOR, HUAWEI], [TYPE, MOBILE]], [
1155
1156 // Xiaomi
1157 /\b(poco[\w ]+|m2\d{3}j\d\d[a-z]{2})(?: bui|\))/i, // Xiaomi POCO
1158 /\b; (\w+) build\/hm\1/i, // Xiaomi Hongmi 'numeric' models
1159 /\b(hm[-_ ]?note?[_ ]?(?:\d\w)?) bui/i, // Xiaomi Hongmi
1160 /\b(redmi[\-_ ]?(?:note|k)?[\w_ ]+)(?: bui|\))/i, // Xiaomi Redmi
1161 /oid[^\)]+; (m?[12][0-389][01]\w{3,6}[c-y])( bui|; wv|\))/i, // Xiaomi Redmi 'numeric' models
1162 /\b(mi[-_ ]?(?:a\d|one|one[_ ]plus|note lte|max|cc)?[_ ]?(?:\d?\w?)[_ ]?(?:plus|se|lite)?)(?: bui|\))/i // Xiaomi Mi
1163 ], [[MODEL, /_/g, ' '], [VENDOR, XIAOMI], [TYPE, MOBILE]], [
1164 /oid[^\)]+; (2\d{4}(283|rpbf)[cgl])( bui|\))/i, // Redmi Pad
1165 /\b(mi[-_ ]?(?:pad)(?:[\w_ ]+))(?: bui|\))/i // Mi Pad tablets
1166 ],[[MODEL, /_/g, ' '], [VENDOR, XIAOMI], [TYPE, TABLET]], [
1167
1168 // OPPO
1169 /; (\w+) bui.+ oppo/i,
1170 /\b(cph[12]\d{3}|p(?:af|c[al]|d\w|e[ar])[mt]\d0|x9007|a101op)\b/i
1171 ], [MODEL, [VENDOR, 'OPPO'], [TYPE, MOBILE]], [
1172
1173 // Vivo
1174 /vivo (\w+)(?: bui|\))/i,
1175 /\b(v[12]\d{3}\w?[at])(?: bui|;)/i
1176 ], [MODEL, [VENDOR, 'Vivo'], [TYPE, MOBILE]], [
1177
1178 // Realme
1179 /\b(rmx[1-3]\d{3})(?: bui|;|\))/i
1180 ], [MODEL, [VENDOR, 'Realme'], [TYPE, MOBILE]], [
1181
1182 // Motorola
1183 /\b(milestone|droid(?:[2-4x]| (?:bionic|x2|pro|razr))?:?( 4g)?)\b[\w ]+build\//i,
1184 /\bmot(?:orola)?[- ](\w*)/i,
1185 /((?:moto[\w\(\) ]+|xt\d{3,4}|nexus 6)(?= bui|\)))/i
1186 ], [MODEL, [VENDOR, MOTOROLA], [TYPE, MOBILE]], [
1187 /\b(mz60\d|xoom[2 ]{0,2}) build\//i
1188 ], [MODEL, [VENDOR, MOTOROLA], [TYPE, TABLET]], [
1189
1190 // LG
1191 /((?=lg)?[vl]k\-?\d{3}) bui| 3\.[-\w; ]{10}lg?-([06cv9]{3,4})/i
1192 ], [MODEL, [VENDOR, LG], [TYPE, TABLET]], [
1193 /(lm(?:-?f100[nv]?|-[\w\.]+)(?= bui|\))|nexus [45])/i,
1194 /\blg[-e;\/ ]+((?!browser|netcast|android tv)\w+)/i,
1195 /\blg-?([\d\w]+) bui/i
1196 ], [MODEL, [VENDOR, LG], [TYPE, MOBILE]], [
1197
1198 // Lenovo
1199 /(ideatab[-\w ]+)/i,
1200 /lenovo ?(s[56]000[-\w]+|tab(?:[\w ]+)|yt[-\d\w]{6}|tb[-\d\w]{6})/i
1201 ], [MODEL, [VENDOR, 'Lenovo'], [TYPE, TABLET]], [
1202
1203 // Nokia
1204 /(?:maemo|nokia).*(n900|lumia \d+)/i,
1205 /nokia[-_ ]?([-\w\.]*)/i
1206 ], [[MODEL, /_/g, ' '], [VENDOR, 'Nokia'], [TYPE, MOBILE]], [
1207
1208 // Google
1209 /(pixel c)\b/i // Google Pixel C
1210 ], [MODEL, [VENDOR, GOOGLE], [TYPE, TABLET]], [
1211 /droid.+; (pixel[\daxl ]{0,6})(?: bui|\))/i // Google Pixel
1212 ], [MODEL, [VENDOR, GOOGLE], [TYPE, MOBILE]], [
1213
1214 // Sony
1215 /droid.+ (a?\d[0-2]{2}so|[c-g]\d{4}|so[-gl]\w+|xq-a\w[4-7][12])(?= bui|\).+chrome\/(?![1-6]{0,1}\d\.))/i
1216 ], [MODEL, [VENDOR, SONY], [TYPE, MOBILE]], [
1217 /sony tablet [ps]/i,
1218 /\b(?:sony)?sgp\w+(?: bui|\))/i
1219 ], [[MODEL, 'Xperia Tablet'], [VENDOR, SONY], [TYPE, TABLET]], [
1220
1221 // OnePlus
1222 / (kb2005|in20[12]5|be20[12][59])\b/i,
1223 /(?:one)?(?:plus)? (a\d0\d\d)(?: b|\))/i
1224 ], [MODEL, [VENDOR, 'OnePlus'], [TYPE, MOBILE]], [
1225
1226 // Amazon
1227 /(alexa)webm/i,
1228 /(kf[a-z]{2}wi|aeo[c-r]{2})( bui|\))/i, // Kindle Fire without Silk / Echo Show
1229 /(kf[a-z]+)( bui|\)).+silk\//i // Kindle Fire HD
1230 ], [MODEL, [VENDOR, AMAZON], [TYPE, TABLET]], [
1231 /((?:sd|kf)[0349hijorstuw]+)( bui|\)).+silk\//i // Fire Phone
1232 ], [[MODEL, /(.+)/g, 'Fire Phone $1'], [VENDOR, AMAZON], [TYPE, MOBILE]], [
1233
1234 // BlackBerry
1235 /(playbook);[-\w\),; ]+(rim)/i // BlackBerry PlayBook
1236 ], [MODEL, VENDOR, [TYPE, TABLET]], [
1237 /\b((?:bb[a-f]|st[hv])100-\d)/i,
1238 /\(bb10; (\w+)/i // BlackBerry 10
1239 ], [MODEL, [VENDOR, BLACKBERRY], [TYPE, MOBILE]], [
1240
1241 // Asus
1242 /(?:\b|asus_)(transfo[prime ]{4,10} \w+|eeepc|slider \w+|nexus 7|padfone|p00[cj])/i
1243 ], [MODEL, [VENDOR, ASUS], [TYPE, TABLET]], [
1244 / (z[bes]6[027][012][km][ls]|zenfone \d\w?)\b/i
1245 ], [MODEL, [VENDOR, ASUS], [TYPE, MOBILE]], [
1246
1247 // HTC
1248 /(nexus 9)/i // HTC Nexus 9
1249 ], [MODEL, [VENDOR, 'HTC'], [TYPE, TABLET]], [
1250 /(htc)[-;_ ]{1,2}([\w ]+(?=\)| bui)|\w+)/i, // HTC
1251
1252 // ZTE
1253 /(zte)[- ]([\w ]+?)(?: bui|\/|\))/i,
1254 /(alcatel|geeksphone|nexian|panasonic(?!(?:;|\.))|sony(?!-bra))[-_ ]?([-\w]*)/i // Alcatel/GeeksPhone/Nexian/Panasonic/Sony
1255 ], [VENDOR, [MODEL, /_/g, ' '], [TYPE, MOBILE]], [
1256
1257 // Acer
1258 /droid.+; ([ab][1-7]-?[0178a]\d\d?)/i
1259 ], [MODEL, [VENDOR, 'Acer'], [TYPE, TABLET]], [
1260
1261 // Meizu
1262 /droid.+; (m[1-5] note) bui/i,
1263 /\bmz-([-\w]{2,})/i
1264 ], [MODEL, [VENDOR, 'Meizu'], [TYPE, MOBILE]], [
1265
1266 // Ulefone
1267 /; ((?:power )?armor(?:[\w ]{0,8}))(?: bui|\))/i
1268 ], [MODEL, [VENDOR, 'Ulefone'], [TYPE, MOBILE]], [
1269
1270 // MIXED
1271 /(blackberry|benq|palm(?=\-)|sonyericsson|acer|asus|dell|meizu|motorola|polytron|infinix|tecno)[-_ ]?([-\w]*)/i,
1272 // BlackBerry/BenQ/Palm/Sony-Ericsson/Acer/Asus/Dell/Meizu/Motorola/Polytron
1273 /(hp) ([\w ]+\w)/i, // HP iPAQ
1274 /(asus)-?(\w+)/i, // Asus
1275 /(microsoft); (lumia[\w ]+)/i, // Microsoft Lumia
1276 /(lenovo)[-_ ]?([-\w]+)/i, // Lenovo
1277 /(jolla)/i, // Jolla
1278 /(oppo) ?([\w ]+) bui/i // OPPO
1279 ], [VENDOR, MODEL, [TYPE, MOBILE]], [
1280
1281 /(kobo)\s(ereader|touch)/i, // Kobo
1282 /(archos) (gamepad2?)/i, // Archos
1283 /(hp).+(touchpad(?!.+tablet)|tablet)/i, // HP TouchPad
1284 /(kindle)\/([\w\.]+)/i, // Kindle
1285 /(nook)[\w ]+build\/(\w+)/i, // Nook
1286 /(dell) (strea[kpr\d ]*[\dko])/i, // Dell Streak
1287 /(le[- ]+pan)[- ]+(\w{1,9}) bui/i, // Le Pan Tablets
1288 /(trinity)[- ]*(t\d{3}) bui/i, // Trinity Tablets
1289 /(gigaset)[- ]+(q\w{1,9}) bui/i, // Gigaset Tablets
1290 /(vodafone) ([\w ]+)(?:\)| bui)/i // Vodafone
1291 ], [VENDOR, MODEL, [TYPE, TABLET]], [
1292
1293 /(surface duo)/i // Surface Duo
1294 ], [MODEL, [VENDOR, MICROSOFT], [TYPE, TABLET]], [
1295 /droid [\d\.]+; (fp\du?)(?: b|\))/i // Fairphone
1296 ], [MODEL, [VENDOR, 'Fairphone'], [TYPE, MOBILE]], [
1297 /(u304aa)/i // AT&T
1298 ], [MODEL, [VENDOR, 'AT&T'], [TYPE, MOBILE]], [
1299 /\bsie-(\w*)/i // Siemens
1300 ], [MODEL, [VENDOR, 'Siemens'], [TYPE, MOBILE]], [
1301 /\b(rct\w+) b/i // RCA Tablets
1302 ], [MODEL, [VENDOR, 'RCA'], [TYPE, TABLET]], [
1303 /\b(venue[\d ]{2,7}) b/i // Dell Venue Tablets
1304 ], [MODEL, [VENDOR, 'Dell'], [TYPE, TABLET]], [
1305 /\b(q(?:mv|ta)\w+) b/i // Verizon Tablet
1306 ], [MODEL, [VENDOR, 'Verizon'], [TYPE, TABLET]], [
1307 /\b(?:barnes[& ]+noble |bn[rt])([\w\+ ]*) b/i // Barnes & Noble Tablet
1308 ], [MODEL, [VENDOR, 'Barnes & Noble'], [TYPE, TABLET]], [
1309 /\b(tm\d{3}\w+) b/i
1310 ], [MODEL, [VENDOR, 'NuVision'], [TYPE, TABLET]], [
1311 /\b(k88) b/i // ZTE K Series Tablet
1312 ], [MODEL, [VENDOR, 'ZTE'], [TYPE, TABLET]], [
1313 /\b(nx\d{3}j) b/i // ZTE Nubia
1314 ], [MODEL, [VENDOR, 'ZTE'], [TYPE, MOBILE]], [
1315 /\b(gen\d{3}) b.+49h/i // Swiss GEN Mobile
1316 ], [MODEL, [VENDOR, 'Swiss'], [TYPE, MOBILE]], [
1317 /\b(zur\d{3}) b/i // Swiss ZUR Tablet
1318 ], [MODEL, [VENDOR, 'Swiss'], [TYPE, TABLET]], [
1319 /\b((zeki)?tb.*\b) b/i // Zeki Tablets
1320 ], [MODEL, [VENDOR, 'Zeki'], [TYPE, TABLET]], [
1321 /\b([yr]\d{2}) b/i,
1322 /\b(dragon[- ]+touch |dt)(\w{5}) b/i // Dragon Touch Tablet
1323 ], [[VENDOR, 'Dragon Touch'], MODEL, [TYPE, TABLET]], [
1324 /\b(ns-?\w{0,9}) b/i // Insignia Tablets
1325 ], [MODEL, [VENDOR, 'Insignia'], [TYPE, TABLET]], [
1326 /\b((nxa|next)-?\w{0,9}) b/i // NextBook Tablets
1327 ], [MODEL, [VENDOR, 'NextBook'], [TYPE, TABLET]], [
1328 /\b(xtreme\_)?(v(1[045]|2[015]|[3469]0|7[05])) b/i // Voice Xtreme Phones
1329 ], [[VENDOR, 'Voice'], MODEL, [TYPE, MOBILE]], [
1330 /\b(lvtel\-)?(v1[12]) b/i // LvTel Phones
1331 ], [[VENDOR, 'LvTel'], MODEL, [TYPE, MOBILE]], [
1332 /\b(ph-1) /i // Essential PH-1
1333 ], [MODEL, [VENDOR, 'Essential'], [TYPE, MOBILE]], [
1334 /\b(v(100md|700na|7011|917g).*\b) b/i // Envizen Tablets
1335 ], [MODEL, [VENDOR, 'Envizen'], [TYPE, TABLET]], [
1336 /\b(trio[-\w\. ]+) b/i // MachSpeed Tablets
1337 ], [MODEL, [VENDOR, 'MachSpeed'], [TYPE, TABLET]], [
1338 /\btu_(1491) b/i // Rotor Tablets
1339 ], [MODEL, [VENDOR, 'Rotor'], [TYPE, TABLET]], [
1340 /(shield[\w ]+) b/i // Nvidia Shield Tablets
1341 ], [MODEL, [VENDOR, 'Nvidia'], [TYPE, TABLET]], [
1342 /(sprint) (\w+)/i // Sprint Phones
1343 ], [VENDOR, MODEL, [TYPE, MOBILE]], [
1344 /(kin\.[onetw]{3})/i // Microsoft Kin
1345 ], [[MODEL, /\./g, ' '], [VENDOR, MICROSOFT], [TYPE, MOBILE]], [
1346 /droid.+; (cc6666?|et5[16]|mc[239][23]x?|vc8[03]x?)\)/i // Zebra
1347 ], [MODEL, [VENDOR, ZEBRA], [TYPE, TABLET]], [
1348 /droid.+; (ec30|ps20|tc[2-8]\d[kx])\)/i
1349 ], [MODEL, [VENDOR, ZEBRA], [TYPE, MOBILE]], [
1350
1351 ///////////////////
1352 // SMARTTVS
1353 ///////////////////
1354
1355 /smart-tv.+(samsung)/i // Samsung
1356 ], [VENDOR, [TYPE, SMARTTV]], [
1357 /hbbtv.+maple;(\d+)/i
1358 ], [[MODEL, /^/, 'SmartTV'], [VENDOR, SAMSUNG], [TYPE, SMARTTV]], [
1359 /(nux; netcast.+smarttv|lg (netcast\.tv-201\d|android tv))/i // LG SmartTV
1360 ], [[VENDOR, LG], [TYPE, SMARTTV]], [
1361 /(apple) ?tv/i // Apple TV
1362 ], [VENDOR, [MODEL, APPLE+' TV'], [TYPE, SMARTTV]], [
1363 /crkey/i // Google Chromecast
1364 ], [[MODEL, CHROME+'cast'], [VENDOR, GOOGLE], [TYPE, SMARTTV]], [
1365 /droid.+aft(\w+)( bui|\))/i // Fire TV
1366 ], [MODEL, [VENDOR, AMAZON], [TYPE, SMARTTV]], [
1367 /\(dtv[\);].+(aquos)/i,
1368 /(aquos-tv[\w ]+)\)/i // Sharp
1369 ], [MODEL, [VENDOR, SHARP], [TYPE, SMARTTV]],[
1370 /(bravia[\w ]+)( bui|\))/i // Sony
1371 ], [MODEL, [VENDOR, SONY], [TYPE, SMARTTV]], [
1372 /(mitv-\w{5}) bui/i // Xiaomi
1373 ], [MODEL, [VENDOR, XIAOMI], [TYPE, SMARTTV]], [
1374 /Hbbtv.*(technisat) (.*);/i // TechniSAT
1375 ], [VENDOR, MODEL, [TYPE, SMARTTV]], [
1376 /\b(roku)[\dx]*[\)\/]((?:dvp-)?[\d\.]*)/i, // Roku
1377 /hbbtv\/\d+\.\d+\.\d+ +\([\w\+ ]*; *([\w\d][^;]*);([^;]*)/i // HbbTV devices
1378 ], [[VENDOR, trim], [MODEL, trim], [TYPE, SMARTTV]], [
1379 /\b(android tv|smart[- ]?tv|opera tv|tv; rv:)\b/i // SmartTV from Unidentified Vendors
1380 ], [[TYPE, SMARTTV]], [
1381
1382 ///////////////////
1383 // CONSOLES
1384 ///////////////////
1385
1386 /(ouya)/i, // Ouya
1387 /(nintendo) ([wids3utch]+)/i // Nintendo
1388 ], [VENDOR, MODEL, [TYPE, CONSOLE]], [
1389 /droid.+; (shield) bui/i // Nvidia
1390 ], [MODEL, [VENDOR, 'Nvidia'], [TYPE, CONSOLE]], [
1391 /(playstation [345portablevi]+)/i // Playstation
1392 ], [MODEL, [VENDOR, SONY], [TYPE, CONSOLE]], [
1393 /\b(xbox(?: one)?(?!; xbox))[\); ]/i // Microsoft Xbox
1394 ], [MODEL, [VENDOR, MICROSOFT], [TYPE, CONSOLE]], [
1395
1396 ///////////////////
1397 // WEARABLES
1398 ///////////////////
1399
1400 /((pebble))app/i // Pebble
1401 ], [VENDOR, MODEL, [TYPE, WEARABLE]], [
1402 /(watch)(?: ?os[,\/]|\d,\d\/)[\d\.]+/i // Apple Watch
1403 ], [MODEL, [VENDOR, APPLE], [TYPE, WEARABLE]], [
1404 /droid.+; (glass) \d/i // Google Glass
1405 ], [MODEL, [VENDOR, GOOGLE], [TYPE, WEARABLE]], [
1406 /droid.+; (wt63?0{2,3})\)/i
1407 ], [MODEL, [VENDOR, ZEBRA], [TYPE, WEARABLE]], [
1408 /(quest( 2| pro)?)/i // Oculus Quest
1409 ], [MODEL, [VENDOR, FACEBOOK], [TYPE, WEARABLE]], [
1410
1411 ///////////////////
1412 // EMBEDDED
1413 ///////////////////
1414
1415 /(tesla)(?: qtcarbrowser|\/[-\w\.]+)/i // Tesla
1416 ], [VENDOR, [TYPE, EMBEDDED]], [
1417 /(aeobc)\b/i // Echo Dot
1418 ], [MODEL, [VENDOR, AMAZON], [TYPE, EMBEDDED]], [
1419
1420 ////////////////////
1421 // MIXED (GENERIC)
1422 ///////////////////
1423
1424 /droid .+?; ([^;]+?)(?: bui|; wv\)|\) applew).+? mobile safari/i // Android Phones from Unidentified Vendors
1425 ], [MODEL, [TYPE, MOBILE]], [
1426 /droid .+?; ([^;]+?)(?: bui|\) applew).+?(?! mobile) safari/i // Android Tablets from Unidentified Vendors
1427 ], [MODEL, [TYPE, TABLET]], [
1428 /\b((tablet|tab)[;\/]|focus\/\d(?!.+mobile))/i // Unidentifiable Tablet
1429 ], [[TYPE, TABLET]], [
1430 /(phone|mobile(?:[;\/]| [ \w\/\.]*safari)|pda(?=.+windows ce))/i // Unidentifiable Mobile
1431 ], [[TYPE, MOBILE]], [
1432 /(android[-\w\. ]{0,9});.+buil/i // Generic Android Device
1433 ], [MODEL, [VENDOR, 'Generic']]
1434 ],
1435
1436 engine : [[
1437
1438 /windows.+ edge\/([\w\.]+)/i // EdgeHTML
1439 ], [VERSION, [NAME, EDGE+'HTML']], [
1440
1441 /webkit\/537\.36.+chrome\/(?!27)([\w\.]+)/i // Blink
1442 ], [VERSION, [NAME, 'Blink']], [
1443
1444 /(presto)\/([\w\.]+)/i, // Presto
1445 /(webkit|trident|netfront|netsurf|amaya|lynx|w3m|goanna)\/([\w\.]+)/i, // WebKit/Trident/NetFront/NetSurf/Amaya/Lynx/w3m/Goanna
1446 /ekioh(flow)\/([\w\.]+)/i, // Flow
1447 /(khtml|tasman|links)[\/ ]\(?([\w\.]+)/i, // KHTML/Tasman/Links
1448 /(icab)[\/ ]([23]\.[\d\.]+)/i, // iCab
1449 /\b(libweb)/i
1450 ], [NAME, VERSION], [
1451
1452 /rv\:([\w\.]{1,9})\b.+(gecko)/i // Gecko
1453 ], [VERSION, NAME]
1454 ],
1455
1456 os : [[
1457
1458 // Windows
1459 /microsoft (windows) (vista|xp)/i // Windows (iTunes)
1460 ], [NAME, VERSION], [
1461 /(windows (?:phone(?: os)?|mobile))[\/ ]?([\d\.\w ]*)/i // Windows Phone
1462 ], [NAME, [VERSION, strMapper, windowsVersionMap]], [
1463 /windows nt 6\.2; (arm)/i, // Windows RT
1464 /windows[\/ ]?([ntce\d\. ]+\w)(?!.+xbox)/i,
1465 /(?:win(?=3|9|n)|win 9x )([nt\d\.]+)/i
1466 ], [[VERSION, strMapper, windowsVersionMap], [NAME, 'Windows']], [
1467
1468 // iOS/macOS
1469 /ip[honead]{2,4}\b(?:.*os ([\w]+) like mac|; opera)/i, // iOS
1470 /(?:ios;fbsv\/|iphone.+ios[\/ ])([\d\.]+)/i,
1471 /cfnetwork\/.+darwin/i
1472 ], [[VERSION, /_/g, '.'], [NAME, 'iOS']], [
1473 /(mac os x) ?([\w\. ]*)/i,
1474 /(macintosh|mac_powerpc\b)(?!.+haiku)/i // Mac OS
1475 ], [[NAME, MAC_OS], [VERSION, /_/g, '.']], [
1476
1477 // Mobile OSes
1478 /droid ([\w\.]+)\b.+(android[- ]x86|harmonyos)/i // Android-x86/HarmonyOS
1479 ], [VERSION, NAME], [ // Android/WebOS/QNX/Bada/RIM/Maemo/MeeGo/Sailfish OS
1480 /(android|webos|qnx|bada|rim tablet os|maemo|meego|sailfish)[-\/ ]?([\w\.]*)/i,
1481 /(blackberry)\w*\/([\w\.]*)/i, // Blackberry
1482 /(tizen|kaios)[\/ ]([\w\.]+)/i, // Tizen/KaiOS
1483 /\((series40);/i // Series 40
1484 ], [NAME, VERSION], [
1485 /\(bb(10);/i // BlackBerry 10
1486 ], [VERSION, [NAME, BLACKBERRY]], [
1487 /(?:symbian ?os|symbos|s60(?=;)|series60)[-\/ ]?([\w\.]*)/i // Symbian
1488 ], [VERSION, [NAME, 'Symbian']], [
1489 /mozilla\/[\d\.]+ \((?:mobile|tablet|tv|mobile; [\w ]+); rv:.+ gecko\/([\w\.]+)/i // Firefox OS
1490 ], [VERSION, [NAME, FIREFOX+' OS']], [
1491 /web0s;.+rt(tv)/i,
1492 /\b(?:hp)?wos(?:browser)?\/([\w\.]+)/i // WebOS
1493 ], [VERSION, [NAME, 'webOS']], [
1494 /watch(?: ?os[,\/]|\d,\d\/)([\d\.]+)/i // watchOS
1495 ], [VERSION, [NAME, 'watchOS']], [
1496
1497 // Google Chromecast
1498 /crkey\/([\d\.]+)/i // Google Chromecast
1499 ], [VERSION, [NAME, CHROME+'cast']], [
1500 /(cros) [\w]+(?:\)| ([\w\.]+)\b)/i // Chromium OS
1501 ], [[NAME, CHROMIUM_OS], VERSION],[
1502
1503 // Smart TVs
1504 /panasonic;(viera)/i, // Panasonic Viera
1505 /(netrange)mmh/i, // Netrange
1506 /(nettv)\/(\d+\.[\w\.]+)/i, // NetTV
1507
1508 // Console
1509 /(nintendo|playstation) ([wids345portablevuch]+)/i, // Nintendo/Playstation
1510 /(xbox); +xbox ([^\);]+)/i, // Microsoft Xbox (360, One, X, S, Series X, Series S)
1511
1512 // Other
1513 /\b(joli|palm)\b ?(?:os)?\/?([\w\.]*)/i, // Joli/Palm
1514 /(mint)[\/\(\) ]?(\w*)/i, // Mint
1515 /(mageia|vectorlinux)[; ]/i, // Mageia/VectorLinux
1516 /([kxln]?ubuntu|debian|suse|opensuse|gentoo|arch(?= linux)|slackware|fedora|mandriva|centos|pclinuxos|red ?hat|zenwalk|linpus|raspbian|plan 9|minix|risc os|contiki|deepin|manjaro|elementary os|sabayon|linspire)(?: gnu\/linux)?(?: enterprise)?(?:[- ]linux)?(?:-gnu)?[-\/ ]?(?!chrom|package)([-\w\.]*)/i,
1517 // Ubuntu/Debian/SUSE/Gentoo/Arch/Slackware/Fedora/Mandriva/CentOS/PCLinuxOS/RedHat/Zenwalk/Linpus/Raspbian/Plan9/Minix/RISCOS/Contiki/Deepin/Manjaro/elementary/Sabayon/Linspire
1518 /(hurd|linux) ?([\w\.]*)/i, // Hurd/Linux
1519 /(gnu) ?([\w\.]*)/i, // GNU
1520 /\b([-frentopcghs]{0,5}bsd|dragonfly)[\/ ]?(?!amd|[ix346]{1,2}86)([\w\.]*)/i, // FreeBSD/NetBSD/OpenBSD/PC-BSD/GhostBSD/DragonFly
1521 /(haiku) (\w+)/i // Haiku
1522 ], [NAME, VERSION], [
1523 /(sunos) ?([\w\.\d]*)/i // Solaris
1524 ], [[NAME, 'Solaris'], VERSION], [
1525 /((?:open)?solaris)[-\/ ]?([\w\.]*)/i, // Solaris
1526 /(aix) ((\d)(?=\.|\)| )[\w\.])*/i, // AIX
1527 /\b(beos|os\/2|amigaos|morphos|openvms|fuchsia|hp-ux|serenityos)/i, // BeOS/OS2/AmigaOS/MorphOS/OpenVMS/Fuchsia/HP-UX/SerenityOS
1528 /(unix) ?([\w\.]*)/i // UNIX
1529 ], [NAME, VERSION]
1530 ]
1531 };
1532
1533 /////////////////
1534 // Constructor
1535 ////////////////
1536
1537 var UAParser = function (ua, extensions) {
1538
1539 if (typeof ua === OBJ_TYPE) {
1540 extensions = ua;
1541 ua = undefined$1;
1542 }
1543
1544 if (!(this instanceof UAParser)) {
1545 return new UAParser(ua, extensions).getResult();
1546 }
1547
1548 var _navigator = (typeof window !== UNDEF_TYPE && window.navigator) ? window.navigator : undefined$1;
1549 var _ua = ua || ((_navigator && _navigator.userAgent) ? _navigator.userAgent : EMPTY);
1550 var _uach = (_navigator && _navigator.userAgentData) ? _navigator.userAgentData : undefined$1;
1551 var _rgxmap = extensions ? extend(regexes, extensions) : regexes;
1552 var _isSelfNav = _navigator && _navigator.userAgent == _ua;
1553
1554 this.getBrowser = function () {
1555 var _browser = {};
1556 _browser[NAME] = undefined$1;
1557 _browser[VERSION] = undefined$1;
1558 rgxMapper.call(_browser, _ua, _rgxmap.browser);
1559 _browser[MAJOR] = majorize(_browser[VERSION]);
1560 // Brave-specific detection
1561 if (_isSelfNav && _navigator && _navigator.brave && typeof _navigator.brave.isBrave == FUNC_TYPE) {
1562 _browser[NAME] = 'Brave';
1563 }
1564 return _browser;
1565 };
1566 this.getCPU = function () {
1567 var _cpu = {};
1568 _cpu[ARCHITECTURE] = undefined$1;
1569 rgxMapper.call(_cpu, _ua, _rgxmap.cpu);
1570 return _cpu;
1571 };
1572 this.getDevice = function () {
1573 var _device = {};
1574 _device[VENDOR] = undefined$1;
1575 _device[MODEL] = undefined$1;
1576 _device[TYPE] = undefined$1;
1577 rgxMapper.call(_device, _ua, _rgxmap.device);
1578 if (_isSelfNav && !_device[TYPE] && _uach && _uach.mobile) {
1579 _device[TYPE] = MOBILE;
1580 }
1581 // iPadOS-specific detection: identified as Mac, but has some iOS-only properties
1582 if (_isSelfNav && _device[MODEL] == 'Macintosh' && _navigator && typeof _navigator.standalone !== UNDEF_TYPE && _navigator.maxTouchPoints && _navigator.maxTouchPoints > 2) {
1583 _device[MODEL] = 'iPad';
1584 _device[TYPE] = TABLET;
1585 }
1586 return _device;
1587 };
1588 this.getEngine = function () {
1589 var _engine = {};
1590 _engine[NAME] = undefined$1;
1591 _engine[VERSION] = undefined$1;
1592 rgxMapper.call(_engine, _ua, _rgxmap.engine);
1593 return _engine;
1594 };
1595 this.getOS = function () {
1596 var _os = {};
1597 _os[NAME] = undefined$1;
1598 _os[VERSION] = undefined$1;
1599 rgxMapper.call(_os, _ua, _rgxmap.os);
1600 if (_isSelfNav && !_os[NAME] && _uach && _uach.platform != 'Unknown') {
1601 _os[NAME] = _uach.platform
1602 .replace(/chrome os/i, CHROMIUM_OS)
1603 .replace(/macos/i, MAC_OS); // backward compatibility
1604 }
1605 return _os;
1606 };
1607 this.getResult = function () {
1608 return {
1609 ua : this.getUA(),
1610 browser : this.getBrowser(),
1611 engine : this.getEngine(),
1612 os : this.getOS(),
1613 device : this.getDevice(),
1614 cpu : this.getCPU()
1615 };
1616 };
1617 this.getUA = function () {
1618 return _ua;
1619 };
1620 this.setUA = function (ua) {
1621 _ua = (typeof ua === STR_TYPE && ua.length > UA_MAX_LENGTH) ? trim(ua, UA_MAX_LENGTH) : ua;
1622 return this;
1623 };
1624 this.setUA(_ua);
1625 return this;
1626 };
1627
1628 UAParser.VERSION = LIBVERSION;
1629 UAParser.BROWSER = enumerize([NAME, VERSION, MAJOR]);
1630 UAParser.CPU = enumerize([ARCHITECTURE]);
1631 UAParser.DEVICE = enumerize([MODEL, VENDOR, TYPE, CONSOLE, MOBILE, SMARTTV, TABLET, WEARABLE, EMBEDDED]);
1632 UAParser.ENGINE = UAParser.OS = enumerize([NAME, VERSION]);
1633
1634 ///////////
1635 // Export
1636 //////////
1637
1638 // check js environment
1639 {
1640 // nodejs env
1641 if (module.exports) {
1642 exports = module.exports = UAParser;
1643 }
1644 exports.UAParser = UAParser;
1645 }
1646
1647 // jQuery/Zepto specific (optional)
1648 // Note:
1649 // In AMD env the global scope should be kept clean, but jQuery is an exception.
1650 // jQuery always exports to global scope, unless jQuery.noConflict(true) is used,
1651 // and we should catch that.
1652 var $ = typeof window !== UNDEF_TYPE && (window.jQuery || window.Zepto);
1653 if ($ && !$.ua) {
1654 var parser = new UAParser();
1655 $.ua = parser.getResult();
1656 $.ua.get = function () {
1657 return parser.getUA();
1658 };
1659 $.ua.set = function (ua) {
1660 parser.setUA(ua);
1661 var result = parser.getResult();
1662 for (var prop in result) {
1663 $.ua[prop] = result[prop];
1664 }
1665 };
1666 }
1667
1668 })(typeof window === 'object' ? window : commonjsGlobal);
1669 } (uaParser, uaParser.exports));
1670
1671 var uaParserExports = uaParser.exports;
1672
1673 var Logger$3 = {};
1674
1675 var __importDefault$1 = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) {
1676 return (mod && mod.__esModule) ? mod : { "default": mod };
1677 };
1678 Object.defineProperty(Logger$3, "__esModule", { value: true });
1679 Logger$3.Logger = void 0;
1680 const debug_1$1 = __importDefault$1(browserExports);
1681 const APP_NAME = 'mediasoup-client';
1682 class Logger$2 {
1683 constructor(prefix) {
1684 if (prefix) {
1685 this._debug = (0, debug_1$1.default)(`${APP_NAME}:${prefix}`);
1686 this._warn = (0, debug_1$1.default)(`${APP_NAME}:WARN:${prefix}`);
1687 this._error = (0, debug_1$1.default)(`${APP_NAME}:ERROR:${prefix}`);
1688 }
1689 else {
1690 this._debug = (0, debug_1$1.default)(APP_NAME);
1691 this._warn = (0, debug_1$1.default)(`${APP_NAME}:WARN`);
1692 this._error = (0, debug_1$1.default)(`${APP_NAME}:ERROR`);
1693 }
1694 /* eslint-disable no-console */
1695 this._debug.log = console.info.bind(console);
1696 this._warn.log = console.warn.bind(console);
1697 this._error.log = console.error.bind(console);
1698 /* eslint-enable no-console */
1699 }
1700 get debug() {
1701 return this._debug;
1702 }
1703 get warn() {
1704 return this._warn;
1705 }
1706 get error() {
1707 return this._error;
1708 }
1709 }
1710 Logger$3.Logger = Logger$2;
1711
1712 var EnhancedEventEmitter$1 = {};
1713
1714 var events = {exports: {}};
1715
1716 var R = typeof Reflect === 'object' ? Reflect : null;
1717 var ReflectApply = R && typeof R.apply === 'function'
1718 ? R.apply
1719 : function ReflectApply(target, receiver, args) {
1720 return Function.prototype.apply.call(target, receiver, args);
1721 };
1722
1723 var ReflectOwnKeys;
1724 if (R && typeof R.ownKeys === 'function') {
1725 ReflectOwnKeys = R.ownKeys;
1726 } else if (Object.getOwnPropertySymbols) {
1727 ReflectOwnKeys = function ReflectOwnKeys(target) {
1728 return Object.getOwnPropertyNames(target)
1729 .concat(Object.getOwnPropertySymbols(target));
1730 };
1731 } else {
1732 ReflectOwnKeys = function ReflectOwnKeys(target) {
1733 return Object.getOwnPropertyNames(target);
1734 };
1735 }
1736
1737 function ProcessEmitWarning(warning) {
1738 if (console && console.warn) console.warn(warning);
1739 }
1740
1741 var NumberIsNaN = Number.isNaN || function NumberIsNaN(value) {
1742 return value !== value;
1743 };
1744
1745 function EventEmitter() {
1746 EventEmitter.init.call(this);
1747 }
1748 events.exports = EventEmitter;
1749 events.exports.once = once;
1750
1751 // Backwards-compat with node 0.10.x
1752 EventEmitter.EventEmitter = EventEmitter;
1753
1754 EventEmitter.prototype._events = undefined;
1755 EventEmitter.prototype._eventsCount = 0;
1756 EventEmitter.prototype._maxListeners = undefined;
1757
1758 // By default EventEmitters will print a warning if more than 10 listeners are
1759 // added to it. This is a useful default which helps finding memory leaks.
1760 var defaultMaxListeners = 10;
1761
1762 function checkListener(listener) {
1763 if (typeof listener !== 'function') {
1764 throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener);
1765 }
1766 }
1767
1768 Object.defineProperty(EventEmitter, 'defaultMaxListeners', {
1769 enumerable: true,
1770 get: function() {
1771 return defaultMaxListeners;
1772 },
1773 set: function(arg) {
1774 if (typeof arg !== 'number' || arg < 0 || NumberIsNaN(arg)) {
1775 throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + arg + '.');
1776 }
1777 defaultMaxListeners = arg;
1778 }
1779 });
1780
1781 EventEmitter.init = function() {
1782
1783 if (this._events === undefined ||
1784 this._events === Object.getPrototypeOf(this)._events) {
1785 this._events = Object.create(null);
1786 this._eventsCount = 0;
1787 }
1788
1789 this._maxListeners = this._maxListeners || undefined;
1790 };
1791
1792 // Obviously not all Emitters should be limited to 10. This function allows
1793 // that to be increased. Set to zero for unlimited.
1794 EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) {
1795 if (typeof n !== 'number' || n < 0 || NumberIsNaN(n)) {
1796 throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + n + '.');
1797 }
1798 this._maxListeners = n;
1799 return this;
1800 };
1801
1802 function _getMaxListeners(that) {
1803 if (that._maxListeners === undefined)
1804 return EventEmitter.defaultMaxListeners;
1805 return that._maxListeners;
1806 }
1807
1808 EventEmitter.prototype.getMaxListeners = function getMaxListeners() {
1809 return _getMaxListeners(this);
1810 };
1811
1812 EventEmitter.prototype.emit = function emit(type) {
1813 var args = [];
1814 for (var i = 1; i < arguments.length; i++) args.push(arguments[i]);
1815 var doError = (type === 'error');
1816
1817 var events = this._events;
1818 if (events !== undefined)
1819 doError = (doError && events.error === undefined);
1820 else if (!doError)
1821 return false;
1822
1823 // If there is no 'error' event listener then throw.
1824 if (doError) {
1825 var er;
1826 if (args.length > 0)
1827 er = args[0];
1828 if (er instanceof Error) {
1829 // Note: The comments on the `throw` lines are intentional, they show
1830 // up in Node's output if this results in an unhandled exception.
1831 throw er; // Unhandled 'error' event
1832 }
1833 // At least give some kind of context to the user
1834 var err = new Error('Unhandled error.' + (er ? ' (' + er.message + ')' : ''));
1835 err.context = er;
1836 throw err; // Unhandled 'error' event
1837 }
1838
1839 var handler = events[type];
1840
1841 if (handler === undefined)
1842 return false;
1843
1844 if (typeof handler === 'function') {
1845 ReflectApply(handler, this, args);
1846 } else {
1847 var len = handler.length;
1848 var listeners = arrayClone(handler, len);
1849 for (var i = 0; i < len; ++i)
1850 ReflectApply(listeners[i], this, args);
1851 }
1852
1853 return true;
1854 };
1855
1856 function _addListener(target, type, listener, prepend) {
1857 var m;
1858 var events;
1859 var existing;
1860
1861 checkListener(listener);
1862
1863 events = target._events;
1864 if (events === undefined) {
1865 events = target._events = Object.create(null);
1866 target._eventsCount = 0;
1867 } else {
1868 // To avoid recursion in the case that type === "newListener"! Before
1869 // adding it to the listeners, first emit "newListener".
1870 if (events.newListener !== undefined) {
1871 target.emit('newListener', type,
1872 listener.listener ? listener.listener : listener);
1873
1874 // Re-assign `events` because a newListener handler could have caused the
1875 // this._events to be assigned to a new object
1876 events = target._events;
1877 }
1878 existing = events[type];
1879 }
1880
1881 if (existing === undefined) {
1882 // Optimize the case of one listener. Don't need the extra array object.
1883 existing = events[type] = listener;
1884 ++target._eventsCount;
1885 } else {
1886 if (typeof existing === 'function') {
1887 // Adding the second element, need to change to array.
1888 existing = events[type] =
1889 prepend ? [listener, existing] : [existing, listener];
1890 // If we've already got an array, just append.
1891 } else if (prepend) {
1892 existing.unshift(listener);
1893 } else {
1894 existing.push(listener);
1895 }
1896
1897 // Check for listener leak
1898 m = _getMaxListeners(target);
1899 if (m > 0 && existing.length > m && !existing.warned) {
1900 existing.warned = true;
1901 // No error code for this since it is a Warning
1902 // eslint-disable-next-line no-restricted-syntax
1903 var w = new Error('Possible EventEmitter memory leak detected. ' +
1904 existing.length + ' ' + String(type) + ' listeners ' +
1905 'added. Use emitter.setMaxListeners() to ' +
1906 'increase limit');
1907 w.name = 'MaxListenersExceededWarning';
1908 w.emitter = target;
1909 w.type = type;
1910 w.count = existing.length;
1911 ProcessEmitWarning(w);
1912 }
1913 }
1914
1915 return target;
1916 }
1917
1918 EventEmitter.prototype.addListener = function addListener(type, listener) {
1919 return _addListener(this, type, listener, false);
1920 };
1921
1922 EventEmitter.prototype.on = EventEmitter.prototype.addListener;
1923
1924 EventEmitter.prototype.prependListener =
1925 function prependListener(type, listener) {
1926 return _addListener(this, type, listener, true);
1927 };
1928
1929 function onceWrapper() {
1930 if (!this.fired) {
1931 this.target.removeListener(this.type, this.wrapFn);
1932 this.fired = true;
1933 if (arguments.length === 0)
1934 return this.listener.call(this.target);
1935 return this.listener.apply(this.target, arguments);
1936 }
1937 }
1938
1939 function _onceWrap(target, type, listener) {
1940 var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener };
1941 var wrapped = onceWrapper.bind(state);
1942 wrapped.listener = listener;
1943 state.wrapFn = wrapped;
1944 return wrapped;
1945 }
1946
1947 EventEmitter.prototype.once = function once(type, listener) {
1948 checkListener(listener);
1949 this.on(type, _onceWrap(this, type, listener));
1950 return this;
1951 };
1952
1953 EventEmitter.prototype.prependOnceListener =
1954 function prependOnceListener(type, listener) {
1955 checkListener(listener);
1956 this.prependListener(type, _onceWrap(this, type, listener));
1957 return this;
1958 };
1959
1960 // Emits a 'removeListener' event if and only if the listener was removed.
1961 EventEmitter.prototype.removeListener =
1962 function removeListener(type, listener) {
1963 var list, events, position, i, originalListener;
1964
1965 checkListener(listener);
1966
1967 events = this._events;
1968 if (events === undefined)
1969 return this;
1970
1971 list = events[type];
1972 if (list === undefined)
1973 return this;
1974
1975 if (list === listener || list.listener === listener) {
1976 if (--this._eventsCount === 0)
1977 this._events = Object.create(null);
1978 else {
1979 delete events[type];
1980 if (events.removeListener)
1981 this.emit('removeListener', type, list.listener || listener);
1982 }
1983 } else if (typeof list !== 'function') {
1984 position = -1;
1985
1986 for (i = list.length - 1; i >= 0; i--) {
1987 if (list[i] === listener || list[i].listener === listener) {
1988 originalListener = list[i].listener;
1989 position = i;
1990 break;
1991 }
1992 }
1993
1994 if (position < 0)
1995 return this;
1996
1997 if (position === 0)
1998 list.shift();
1999 else {
2000 spliceOne(list, position);
2001 }
2002
2003 if (list.length === 1)
2004 events[type] = list[0];
2005
2006 if (events.removeListener !== undefined)
2007 this.emit('removeListener', type, originalListener || listener);
2008 }
2009
2010 return this;
2011 };
2012
2013 EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
2014
2015 EventEmitter.prototype.removeAllListeners =
2016 function removeAllListeners(type) {
2017 var listeners, events, i;
2018
2019 events = this._events;
2020 if (events === undefined)
2021 return this;
2022
2023 // not listening for removeListener, no need to emit
2024 if (events.removeListener === undefined) {
2025 if (arguments.length === 0) {
2026 this._events = Object.create(null);
2027 this._eventsCount = 0;
2028 } else if (events[type] !== undefined) {
2029 if (--this._eventsCount === 0)
2030 this._events = Object.create(null);
2031 else
2032 delete events[type];
2033 }
2034 return this;
2035 }
2036
2037 // emit removeListener for all listeners on all events
2038 if (arguments.length === 0) {
2039 var keys = Object.keys(events);
2040 var key;
2041 for (i = 0; i < keys.length; ++i) {
2042 key = keys[i];
2043 if (key === 'removeListener') continue;
2044 this.removeAllListeners(key);
2045 }
2046 this.removeAllListeners('removeListener');
2047 this._events = Object.create(null);
2048 this._eventsCount = 0;
2049 return this;
2050 }
2051
2052 listeners = events[type];
2053
2054 if (typeof listeners === 'function') {
2055 this.removeListener(type, listeners);
2056 } else if (listeners !== undefined) {
2057 // LIFO order
2058 for (i = listeners.length - 1; i >= 0; i--) {
2059 this.removeListener(type, listeners[i]);
2060 }
2061 }
2062
2063 return this;
2064 };
2065
2066 function _listeners(target, type, unwrap) {
2067 var events = target._events;
2068
2069 if (events === undefined)
2070 return [];
2071
2072 var evlistener = events[type];
2073 if (evlistener === undefined)
2074 return [];
2075
2076 if (typeof evlistener === 'function')
2077 return unwrap ? [evlistener.listener || evlistener] : [evlistener];
2078
2079 return unwrap ?
2080 unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length);
2081 }
2082
2083 EventEmitter.prototype.listeners = function listeners(type) {
2084 return _listeners(this, type, true);
2085 };
2086
2087 EventEmitter.prototype.rawListeners = function rawListeners(type) {
2088 return _listeners(this, type, false);
2089 };
2090
2091 EventEmitter.listenerCount = function(emitter, type) {
2092 if (typeof emitter.listenerCount === 'function') {
2093 return emitter.listenerCount(type);
2094 } else {
2095 return listenerCount.call(emitter, type);
2096 }
2097 };
2098
2099 EventEmitter.prototype.listenerCount = listenerCount;
2100 function listenerCount(type) {
2101 var events = this._events;
2102
2103 if (events !== undefined) {
2104 var evlistener = events[type];
2105
2106 if (typeof evlistener === 'function') {
2107 return 1;
2108 } else if (evlistener !== undefined) {
2109 return evlistener.length;
2110 }
2111 }
2112
2113 return 0;
2114 }
2115
2116 EventEmitter.prototype.eventNames = function eventNames() {
2117 return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : [];
2118 };
2119
2120 function arrayClone(arr, n) {
2121 var copy = new Array(n);
2122 for (var i = 0; i < n; ++i)
2123 copy[i] = arr[i];
2124 return copy;
2125 }
2126
2127 function spliceOne(list, index) {
2128 for (; index + 1 < list.length; index++)
2129 list[index] = list[index + 1];
2130 list.pop();
2131 }
2132
2133 function unwrapListeners(arr) {
2134 var ret = new Array(arr.length);
2135 for (var i = 0; i < ret.length; ++i) {
2136 ret[i] = arr[i].listener || arr[i];
2137 }
2138 return ret;
2139 }
2140
2141 function once(emitter, name) {
2142 return new Promise(function (resolve, reject) {
2143 function errorListener(err) {
2144 emitter.removeListener(name, resolver);
2145 reject(err);
2146 }
2147
2148 function resolver() {
2149 if (typeof emitter.removeListener === 'function') {
2150 emitter.removeListener('error', errorListener);
2151 }
2152 resolve([].slice.call(arguments));
2153 }
2154 eventTargetAgnosticAddListener(emitter, name, resolver, { once: true });
2155 if (name !== 'error') {
2156 addErrorHandlerIfEventEmitter(emitter, errorListener, { once: true });
2157 }
2158 });
2159 }
2160
2161 function addErrorHandlerIfEventEmitter(emitter, handler, flags) {
2162 if (typeof emitter.on === 'function') {
2163 eventTargetAgnosticAddListener(emitter, 'error', handler, flags);
2164 }
2165 }
2166
2167 function eventTargetAgnosticAddListener(emitter, name, listener, flags) {
2168 if (typeof emitter.on === 'function') {
2169 if (flags.once) {
2170 emitter.once(name, listener);
2171 } else {
2172 emitter.on(name, listener);
2173 }
2174 } else if (typeof emitter.addEventListener === 'function') {
2175 // EventTarget does not have `error` event semantics like Node
2176 // EventEmitters, we do not listen for `error` events here.
2177 emitter.addEventListener(name, function wrapListener(arg) {
2178 // IE does not have builtin `{ once: true }` support so we
2179 // have to do it manually.
2180 if (flags.once) {
2181 emitter.removeEventListener(name, wrapListener);
2182 }
2183 listener(arg);
2184 });
2185 } else {
2186 throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type ' + typeof emitter);
2187 }
2188 }
2189
2190 var eventsExports = events.exports;
2191
2192 Object.defineProperty(EnhancedEventEmitter$1, "__esModule", { value: true });
2193 EnhancedEventEmitter$1.EnhancedEventEmitter = void 0;
2194 const events_1 = eventsExports;
2195 const Logger_1$j = Logger$3;
2196 const logger$j = new Logger_1$j.Logger('EnhancedEventEmitter');
2197 class EnhancedEventEmitter extends events_1.EventEmitter {
2198 constructor() {
2199 super();
2200 this.setMaxListeners(Infinity);
2201 }
2202 emit(eventName, ...args) {
2203 return super.emit(eventName, ...args);
2204 }
2205 /**
2206 * Special addition to the EventEmitter API.
2207 */
2208 safeEmit(eventName, ...args) {
2209 const numListeners = super.listenerCount(eventName);
2210 try {
2211 return super.emit(eventName, ...args);
2212 }
2213 catch (error) {
2214 logger$j.error('safeEmit() | event listener threw an error [eventName:%s]:%o', eventName, error);
2215 return Boolean(numListeners);
2216 }
2217 }
2218 on(eventName, listener) {
2219 super.on(eventName, listener);
2220 return this;
2221 }
2222 off(eventName, listener) {
2223 super.off(eventName, listener);
2224 return this;
2225 }
2226 addListener(eventName, listener) {
2227 super.on(eventName, listener);
2228 return this;
2229 }
2230 prependListener(eventName, listener) {
2231 super.prependListener(eventName, listener);
2232 return this;
2233 }
2234 once(eventName, listener) {
2235 super.once(eventName, listener);
2236 return this;
2237 }
2238 prependOnceListener(eventName, listener) {
2239 super.prependOnceListener(eventName, listener);
2240 return this;
2241 }
2242 removeListener(eventName, listener) {
2243 super.off(eventName, listener);
2244 return this;
2245 }
2246 removeAllListeners(eventName) {
2247 super.removeAllListeners(eventName);
2248 return this;
2249 }
2250 listenerCount(eventName) {
2251 return super.listenerCount(eventName);
2252 }
2253 listeners(eventName) {
2254 return super.listeners(eventName);
2255 }
2256 rawListeners(eventName) {
2257 return super.rawListeners(eventName);
2258 }
2259 }
2260 EnhancedEventEmitter$1.EnhancedEventEmitter = EnhancedEventEmitter;
2261
2262 var errors = {};
2263
2264 Object.defineProperty(errors, "__esModule", { value: true });
2265 errors.InvalidStateError = errors.UnsupportedError = void 0;
2266 /**
2267 * Error indicating not support for something.
2268 */
2269 class UnsupportedError extends Error {
2270 constructor(message) {
2271 super(message);
2272 this.name = 'UnsupportedError';
2273 if (Error.hasOwnProperty('captureStackTrace')) // Just in V8.
2274 {
2275 // @ts-ignore
2276 Error.captureStackTrace(this, UnsupportedError);
2277 }
2278 else {
2279 this.stack = (new Error(message)).stack;
2280 }
2281 }
2282 }
2283 errors.UnsupportedError = UnsupportedError;
2284 /**
2285 * Error produced when calling a method in an invalid state.
2286 */
2287 class InvalidStateError extends Error {
2288 constructor(message) {
2289 super(message);
2290 this.name = 'InvalidStateError';
2291 if (Error.hasOwnProperty('captureStackTrace')) // Just in V8.
2292 {
2293 // @ts-ignore
2294 Error.captureStackTrace(this, InvalidStateError);
2295 }
2296 else {
2297 this.stack = (new Error(message)).stack;
2298 }
2299 }
2300 }
2301 errors.InvalidStateError = InvalidStateError;
2302
2303 var utils$h = {};
2304
2305 Object.defineProperty(utils$h, "__esModule", { value: true });
2306 utils$h.generateRandomNumber = utils$h.clone = void 0;
2307 /**
2308 * Clones the given value.
2309 */
2310 function clone(value) {
2311 if (value === undefined) {
2312 return undefined;
2313 }
2314 else if (Number.isNaN(value)) {
2315 return NaN;
2316 }
2317 else if (typeof structuredClone === 'function') {
2318 // Available in Node >= 18.
2319 return structuredClone(value);
2320 }
2321 else {
2322 return JSON.parse(JSON.stringify(value));
2323 }
2324 }
2325 utils$h.clone = clone;
2326 /**
2327 * Generates a random positive integer.
2328 */
2329 function generateRandomNumber() {
2330 return Math.round(Math.random() * 10000000);
2331 }
2332 utils$h.generateRandomNumber = generateRandomNumber;
2333
2334 var ortc$d = {};
2335
2336 var h264ProfileLevelId = {};
2337
2338 (function (exports) {
2339 const debug = browserExports('h264-profile-level-id');
2340 const warn = browserExports('h264-profile-level-id:WARN');
2341
2342 /* eslint-disable no-console */
2343 debug.log = console.info.bind(console);
2344 warn.log = console.warn.bind(console);
2345 /* eslint-enable no-console */
2346
2347 const ProfileConstrainedBaseline = 1;
2348 const ProfileBaseline = 2;
2349 const ProfileMain = 3;
2350 const ProfileConstrainedHigh = 4;
2351 const ProfileHigh = 5;
2352
2353 exports.ProfileConstrainedBaseline = ProfileConstrainedBaseline;
2354 exports.ProfileBaseline = ProfileBaseline;
2355 exports.ProfileMain = ProfileMain;
2356 exports.ProfileConstrainedHigh = ProfileConstrainedHigh;
2357 exports.ProfileHigh = ProfileHigh;
2358
2359 // All values are equal to ten times the level number, except level 1b which is
2360 // special.
2361 const Level1_b = 0;
2362 const Level1 = 10;
2363 const Level1_1 = 11;
2364 const Level1_2 = 12;
2365 const Level1_3 = 13;
2366 const Level2 = 20;
2367 const Level2_1 = 21;
2368 const Level2_2 = 22;
2369 const Level3 = 30;
2370 const Level3_1 = 31;
2371 const Level3_2 = 32;
2372 const Level4 = 40;
2373 const Level4_1 = 41;
2374 const Level4_2 = 42;
2375 const Level5 = 50;
2376 const Level5_1 = 51;
2377 const Level5_2 = 52;
2378
2379 exports.Level1_b = Level1_b;
2380 exports.Level1 = Level1;
2381 exports.Level1_1 = Level1_1;
2382 exports.Level1_2 = Level1_2;
2383 exports.Level1_3 = Level1_3;
2384 exports.Level2 = Level2;
2385 exports.Level2_1 = Level2_1;
2386 exports.Level2_2 = Level2_2;
2387 exports.Level3 = Level3;
2388 exports.Level3_1 = Level3_1;
2389 exports.Level3_2 = Level3_2;
2390 exports.Level4 = Level4;
2391 exports.Level4_1 = Level4_1;
2392 exports.Level4_2 = Level4_2;
2393 exports.Level5 = Level5;
2394 exports.Level5_1 = Level5_1;
2395 exports.Level5_2 = Level5_2;
2396
2397 class ProfileLevelId
2398 {
2399 constructor(profile, level)
2400 {
2401 this.profile = profile;
2402 this.level = level;
2403 }
2404 }
2405
2406 exports.ProfileLevelId = ProfileLevelId;
2407
2408 // Default ProfileLevelId.
2409 //
2410 // TODO: The default should really be profile Baseline and level 1 according to
2411 // the spec: https://tools.ietf.org/html/rfc6184#section-8.1. In order to not
2412 // break backwards compatibility with older versions of WebRTC where external
2413 // codecs don't have any parameters, use profile ConstrainedBaseline level 3_1
2414 // instead. This workaround will only be done in an interim period to allow
2415 // external clients to update their code.
2416 //
2417 // http://crbug/webrtc/6337.
2418 const DefaultProfileLevelId =
2419 new ProfileLevelId(ProfileConstrainedBaseline, Level3_1);
2420
2421 // For level_idc=11 and profile_idc=0x42, 0x4D, or 0x58, the constraint set3
2422 // flag specifies if level 1b or level 1.1 is used.
2423 const ConstraintSet3Flag = 0x10;
2424
2425 // Class for matching bit patterns such as "x1xx0000" where 'x' is allowed to
2426 // be either 0 or 1.
2427 class BitPattern
2428 {
2429 constructor(str)
2430 {
2431 this._mask = ~byteMaskString('x', str);
2432 this._maskedValue = byteMaskString('1', str);
2433 }
2434
2435 isMatch(value)
2436 {
2437 return this._maskedValue === (value & this._mask);
2438 }
2439 }
2440
2441 // Class for converting between profile_idc/profile_iop to Profile.
2442 class ProfilePattern
2443 {
2444 constructor(profile_idc, profile_iop, profile)
2445 {
2446 this.profile_idc = profile_idc;
2447 this.profile_iop = profile_iop;
2448 this.profile = profile;
2449 }
2450 }
2451
2452 // This is from https://tools.ietf.org/html/rfc6184#section-8.1.
2453 const ProfilePatterns =
2454 [
2455 new ProfilePattern(0x42, new BitPattern('x1xx0000'), ProfileConstrainedBaseline),
2456 new ProfilePattern(0x4D, new BitPattern('1xxx0000'), ProfileConstrainedBaseline),
2457 new ProfilePattern(0x58, new BitPattern('11xx0000'), ProfileConstrainedBaseline),
2458 new ProfilePattern(0x42, new BitPattern('x0xx0000'), ProfileBaseline),
2459 new ProfilePattern(0x58, new BitPattern('10xx0000'), ProfileBaseline),
2460 new ProfilePattern(0x4D, new BitPattern('0x0x0000'), ProfileMain),
2461 new ProfilePattern(0x64, new BitPattern('00000000'), ProfileHigh),
2462 new ProfilePattern(0x64, new BitPattern('00001100'), ProfileConstrainedHigh)
2463 ];
2464
2465 /**
2466 * Parse profile level id that is represented as a string of 3 hex bytes.
2467 * Nothing will be returned if the string is not a recognized H264 profile
2468 * level id.
2469 *
2470 * @param {String} str - profile-level-id value as a string of 3 hex bytes.
2471 *
2472 * @returns {ProfileLevelId}
2473 */
2474 exports.parseProfileLevelId = function(str)
2475 {
2476 // The string should consist of 3 bytes in hexadecimal format.
2477 if (typeof str !== 'string' || str.length !== 6)
2478 {
2479 return null;
2480 }
2481
2482 const profile_level_id_numeric = parseInt(str, 16);
2483
2484 if (profile_level_id_numeric === 0)
2485 {
2486 return null;
2487 }
2488
2489 // Separate into three bytes.
2490 const level_idc = profile_level_id_numeric & 0xFF;
2491 const profile_iop = (profile_level_id_numeric >> 8) & 0xFF;
2492 const profile_idc = (profile_level_id_numeric >> 16) & 0xFF;
2493
2494 // Parse level based on level_idc and constraint set 3 flag.
2495 let level;
2496
2497 switch (level_idc)
2498 {
2499 case Level1_1:
2500 {
2501 level = (profile_iop & ConstraintSet3Flag) !== 0 ? Level1_b : Level1_1;
2502 break;
2503 }
2504 case Level1:
2505 case Level1_2:
2506 case Level1_3:
2507 case Level2:
2508 case Level2_1:
2509 case Level2_2:
2510 case Level3:
2511 case Level3_1:
2512 case Level3_2:
2513 case Level4:
2514 case Level4_1:
2515 case Level4_2:
2516 case Level5:
2517 case Level5_1:
2518 case Level5_2:
2519 {
2520 level = level_idc;
2521 break;
2522 }
2523 // Unrecognized level_idc.
2524 default:
2525 {
2526 warn(
2527 `parseProfileLevelId() | unrecognized level_idc [str:${str}, level_idc:${level_idc}]`
2528 );
2529
2530 return null;
2531 }
2532 }
2533
2534 // Parse profile_idc/profile_iop into a Profile enum.
2535 for (const pattern of ProfilePatterns)
2536 {
2537 if (
2538 profile_idc === pattern.profile_idc &&
2539 pattern.profile_iop.isMatch(profile_iop)
2540 )
2541 {
2542 return new ProfileLevelId(pattern.profile, level);
2543 }
2544 }
2545
2546 warn(
2547 `parseProfileLevelId() | unrecognized profile_idc/profile_iop combination [str:${str}, profile_idc:${profile_idc}, profile_iop:${profile_iop}]`
2548 );
2549
2550 return null;
2551 };
2552
2553 /**
2554 * Returns canonical string representation as three hex bytes of the profile
2555 * level id, or returns nothing for invalid profile level ids.
2556 *
2557 * @param {ProfileLevelId} profile_level_id
2558 *
2559 * @returns {String}
2560 */
2561 exports.profileLevelIdToString = function(profile_level_id)
2562 {
2563 // Handle special case level == 1b.
2564 if (profile_level_id.level == Level1_b)
2565 {
2566 switch (profile_level_id.profile)
2567 {
2568 case ProfileConstrainedBaseline:
2569 {
2570 return '42f00b';
2571 }
2572 case ProfileBaseline:
2573 {
2574 return '42100b';
2575 }
2576 case ProfileMain:
2577 {
2578 return '4d100b';
2579 }
2580 // Level 1_b is not allowed for other profiles.
2581 default:
2582 {
2583 warn(
2584 `profileLevelIdToString() | Level 1_b not is allowed for profile ${profile_level_id.profile}`
2585 );
2586
2587 return null;
2588 }
2589 }
2590 }
2591
2592 let profile_idc_iop_string;
2593
2594 switch (profile_level_id.profile)
2595 {
2596 case ProfileConstrainedBaseline:
2597 {
2598 profile_idc_iop_string = '42e0';
2599 break;
2600 }
2601 case ProfileBaseline:
2602 {
2603 profile_idc_iop_string = '4200';
2604 break;
2605 }
2606 case ProfileMain:
2607 {
2608 profile_idc_iop_string = '4d00';
2609 break;
2610 }
2611 case ProfileConstrainedHigh:
2612 {
2613 profile_idc_iop_string = '640c';
2614 break;
2615 }
2616 case ProfileHigh:
2617 {
2618 profile_idc_iop_string = '6400';
2619 break;
2620 }
2621 default:
2622 {
2623 warn(
2624 `profileLevelIdToString() | unrecognized profile ${profile_level_id.profile}`
2625 );
2626
2627 return null;
2628 }
2629 }
2630
2631 let levelStr = (profile_level_id.level).toString(16);
2632
2633 if (levelStr.length === 1)
2634 {
2635 levelStr = `0${levelStr}`;
2636 }
2637
2638 return `${profile_idc_iop_string}${levelStr}`;
2639 };
2640
2641 /**
2642 * Parse profile level id that is represented as a string of 3 hex bytes
2643 * contained in an SDP key-value map. A default profile level id will be
2644 * returned if the profile-level-id key is missing. Nothing will be returned
2645 * if the key is present but the string is invalid.
2646 *
2647 * @param {Object} [params={}] - Codec parameters object.
2648 *
2649 * @returns {ProfileLevelId}
2650 */
2651 exports.parseSdpProfileLevelId = function(params = {})
2652 {
2653 const profile_level_id = params['profile-level-id'];
2654
2655 return !profile_level_id
2656 ? DefaultProfileLevelId
2657 : exports.parseProfileLevelId(profile_level_id);
2658 };
2659
2660 /**
2661 * Returns true if the parameters have the same H264 profile, i.e. the same
2662 * H264 profile (Baseline, High, etc).
2663 *
2664 * @param {Object} [params1={}] - Codec parameters object.
2665 * @param {Object} [params2={}] - Codec parameters object.
2666 *
2667 * @returns {Boolean}
2668 */
2669 exports.isSameProfile = function(params1 = {}, params2 = {})
2670 {
2671 const profile_level_id_1 = exports.parseSdpProfileLevelId(params1);
2672 const profile_level_id_2 = exports.parseSdpProfileLevelId(params2);
2673
2674 // Compare H264 profiles, but not levels.
2675 return Boolean(
2676 profile_level_id_1 &&
2677 profile_level_id_2 &&
2678 profile_level_id_1.profile === profile_level_id_2.profile
2679 );
2680 };
2681
2682 /**
2683 * Generate codec parameters that will be used as answer in an SDP negotiation
2684 * based on local supported parameters and remote offered parameters. Both
2685 * local_supported_params and remote_offered_params represent sendrecv media
2686 * descriptions, i.e they are a mix of both encode and decode capabilities. In
2687 * theory, when the profile in local_supported_params represent a strict
2688 * superset of the profile in remote_offered_params, we could limit the profile
2689 * in the answer to the profile in remote_offered_params.
2690 *
2691 * However, to simplify the code, each supported H264 profile should be listed
2692 * explicitly in the list of local supported codecs, even if they are redundant.
2693 * Then each local codec in the list should be tested one at a time against the
2694 * remote codec, and only when the profiles are equal should this function be
2695 * called. Therefore, this function does not need to handle profile intersection,
2696 * and the profile of local_supported_params and remote_offered_params must be
2697 * equal before calling this function. The parameters that are used when
2698 * negotiating are the level part of profile-level-id and level-asymmetry-allowed.
2699 *
2700 * @param {Object} [local_supported_params={}]
2701 * @param {Object} [remote_offered_params={}]
2702 *
2703 * @returns {String} Canonical string representation as three hex bytes of the
2704 * profile level id, or null if no one of the params have profile-level-id.
2705 *
2706 * @throws {TypeError} If Profile mismatch or invalid params.
2707 */
2708 exports.generateProfileLevelIdForAnswer = function(
2709 local_supported_params = {},
2710 remote_offered_params = {}
2711 )
2712 {
2713 // If both local and remote params do not contain profile-level-id, they are
2714 // both using the default profile. In this case, don't return anything.
2715 if (
2716 !local_supported_params['profile-level-id'] &&
2717 !remote_offered_params['profile-level-id']
2718 )
2719 {
2720 warn(
2721 'generateProfileLevelIdForAnswer() | profile-level-id missing in local and remote params'
2722 );
2723
2724 return null;
2725 }
2726
2727 // Parse profile-level-ids.
2728 const local_profile_level_id =
2729 exports.parseSdpProfileLevelId(local_supported_params);
2730 const remote_profile_level_id =
2731 exports.parseSdpProfileLevelId(remote_offered_params);
2732
2733 // The local and remote codec must have valid and equal H264 Profiles.
2734 if (!local_profile_level_id)
2735 {
2736 throw new TypeError('invalid local_profile_level_id');
2737 }
2738
2739 if (!remote_profile_level_id)
2740 {
2741 throw new TypeError('invalid remote_profile_level_id');
2742 }
2743
2744 if (local_profile_level_id.profile !== remote_profile_level_id.profile)
2745 {
2746 throw new TypeError('H264 Profile mismatch');
2747 }
2748
2749 // Parse level information.
2750 const level_asymmetry_allowed = (
2751 isLevelAsymmetryAllowed(local_supported_params) &&
2752 isLevelAsymmetryAllowed(remote_offered_params)
2753 );
2754
2755 const local_level = local_profile_level_id.level;
2756 const remote_level = remote_profile_level_id.level;
2757 const min_level = minLevel(local_level, remote_level);
2758
2759 // Determine answer level. When level asymmetry is not allowed, level upgrade
2760 // is not allowed, i.e., the level in the answer must be equal to or lower
2761 // than the level in the offer.
2762 const answer_level = level_asymmetry_allowed ? local_level : min_level;
2763
2764 debug(
2765 `generateProfileLevelIdForAnswer() | result [profile:${local_profile_level_id.profile}, level:${answer_level}]`
2766 );
2767
2768 // Return the resulting profile-level-id for the answer parameters.
2769 return exports.profileLevelIdToString(
2770 new ProfileLevelId(local_profile_level_id.profile, answer_level));
2771 };
2772
2773 // Convert a string of 8 characters into a byte where the positions containing
2774 // character c will have their bit set. For example, c = 'x', str = "x1xx0000"
2775 // will return 0b10110000.
2776 function byteMaskString(c, str)
2777 {
2778 return (
2779 ((str[0] === c) << 7) | ((str[1] === c) << 6) | ((str[2] === c) << 5) |
2780 ((str[3] === c) << 4) | ((str[4] === c) << 3) | ((str[5] === c) << 2) |
2781 ((str[6] === c) << 1) | ((str[7] === c) << 0)
2782 );
2783 }
2784
2785 // Compare H264 levels and handle the level 1b case.
2786 function isLessLevel(a, b)
2787 {
2788 if (a === Level1_b)
2789 {
2790 return b !== Level1 && b !== Level1_b;
2791 }
2792
2793 if (b === Level1_b)
2794 {
2795 return a !== Level1;
2796 }
2797
2798 return a < b;
2799 }
2800
2801 function minLevel(a, b)
2802 {
2803 return isLessLevel(a, b) ? a : b;
2804 }
2805
2806 function isLevelAsymmetryAllowed(params = {})
2807 {
2808 const level_asymmetry_allowed = params['level-asymmetry-allowed'];
2809
2810 return (
2811 level_asymmetry_allowed === 1 ||
2812 level_asymmetry_allowed === '1'
2813 );
2814 }
2815 } (h264ProfileLevelId));
2816
2817 var __createBinding$h = (commonjsGlobal && commonjsGlobal.__createBinding) || (Object.create ? (function(o, m, k, k2) {
2818 if (k2 === undefined) k2 = k;
2819 var desc = Object.getOwnPropertyDescriptor(m, k);
2820 if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
2821 desc = { enumerable: true, get: function() { return m[k]; } };
2822 }
2823 Object.defineProperty(o, k2, desc);
2824 }) : (function(o, m, k, k2) {
2825 if (k2 === undefined) k2 = k;
2826 o[k2] = m[k];
2827 }));
2828 var __setModuleDefault$h = (commonjsGlobal && commonjsGlobal.__setModuleDefault) || (Object.create ? (function(o, v) {
2829 Object.defineProperty(o, "default", { enumerable: true, value: v });
2830 }) : function(o, v) {
2831 o["default"] = v;
2832 });
2833 var __importStar$h = (commonjsGlobal && commonjsGlobal.__importStar) || function (mod) {
2834 if (mod && mod.__esModule) return mod;
2835 var result = {};
2836 if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding$h(result, mod, k);
2837 __setModuleDefault$h(result, mod);
2838 return result;
2839 };
2840 Object.defineProperty(ortc$d, "__esModule", { value: true });
2841 ortc$d.canReceive = ortc$d.canSend = ortc$d.generateProbatorRtpParameters = ortc$d.reduceCodecs = ortc$d.getSendingRemoteRtpParameters = ortc$d.getSendingRtpParameters = ortc$d.getRecvRtpCapabilities = ortc$d.getExtendedRtpCapabilities = ortc$d.validateSctpStreamParameters = ortc$d.validateSctpParameters = ortc$d.validateNumSctpStreams = ortc$d.validateSctpCapabilities = ortc$d.validateRtcpParameters = ortc$d.validateRtpEncodingParameters = ortc$d.validateRtpHeaderExtensionParameters = ortc$d.validateRtpCodecParameters = ortc$d.validateRtpParameters = ortc$d.validateRtpHeaderExtension = ortc$d.validateRtcpFeedback = ortc$d.validateRtpCodecCapability = ortc$d.validateRtpCapabilities = void 0;
2842 const h264 = __importStar$h(h264ProfileLevelId);
2843 const utils$g = __importStar$h(utils$h);
2844 const RTP_PROBATOR_MID = 'probator';
2845 const RTP_PROBATOR_SSRC = 1234;
2846 const RTP_PROBATOR_CODEC_PAYLOAD_TYPE = 127;
2847 /**
2848 * Validates RtpCapabilities. It may modify given data by adding missing
2849 * fields with default values.
2850 * It throws if invalid.
2851 */
2852 function validateRtpCapabilities(caps) {
2853 if (typeof caps !== 'object') {
2854 throw new TypeError('caps is not an object');
2855 }
2856 // codecs is optional. If unset, fill with an empty array.
2857 if (caps.codecs && !Array.isArray(caps.codecs)) {
2858 throw new TypeError('caps.codecs is not an array');
2859 }
2860 else if (!caps.codecs) {
2861 caps.codecs = [];
2862 }
2863 for (const codec of caps.codecs) {
2864 validateRtpCodecCapability(codec);
2865 }
2866 // headerExtensions is optional. If unset, fill with an empty array.
2867 if (caps.headerExtensions && !Array.isArray(caps.headerExtensions)) {
2868 throw new TypeError('caps.headerExtensions is not an array');
2869 }
2870 else if (!caps.headerExtensions) {
2871 caps.headerExtensions = [];
2872 }
2873 for (const ext of caps.headerExtensions) {
2874 validateRtpHeaderExtension(ext);
2875 }
2876 }
2877 ortc$d.validateRtpCapabilities = validateRtpCapabilities;
2878 /**
2879 * Validates RtpCodecCapability. It may modify given data by adding missing
2880 * fields with default values.
2881 * It throws if invalid.
2882 */
2883 function validateRtpCodecCapability(codec) {
2884 const MimeTypeRegex = new RegExp('^(audio|video)/(.+)', 'i');
2885 if (typeof codec !== 'object') {
2886 throw new TypeError('codec is not an object');
2887 }
2888 // mimeType is mandatory.
2889 if (!codec.mimeType || typeof codec.mimeType !== 'string') {
2890 throw new TypeError('missing codec.mimeType');
2891 }
2892 const mimeTypeMatch = MimeTypeRegex.exec(codec.mimeType);
2893 if (!mimeTypeMatch) {
2894 throw new TypeError('invalid codec.mimeType');
2895 }
2896 // Just override kind with media component of mimeType.
2897 codec.kind = mimeTypeMatch[1].toLowerCase();
2898 // preferredPayloadType is optional.
2899 if (codec.preferredPayloadType && typeof codec.preferredPayloadType !== 'number') {
2900 throw new TypeError('invalid codec.preferredPayloadType');
2901 }
2902 // clockRate is mandatory.
2903 if (typeof codec.clockRate !== 'number') {
2904 throw new TypeError('missing codec.clockRate');
2905 }
2906 // channels is optional. If unset, set it to 1 (just if audio).
2907 if (codec.kind === 'audio') {
2908 if (typeof codec.channels !== 'number') {
2909 codec.channels = 1;
2910 }
2911 }
2912 else {
2913 delete codec.channels;
2914 }
2915 // parameters is optional. If unset, set it to an empty object.
2916 if (!codec.parameters || typeof codec.parameters !== 'object') {
2917 codec.parameters = {};
2918 }
2919 for (const key of Object.keys(codec.parameters)) {
2920 let value = codec.parameters[key];
2921 if (value === undefined) {
2922 codec.parameters[key] = '';
2923 value = '';
2924 }
2925 if (typeof value !== 'string' && typeof value !== 'number') {
2926 throw new TypeError(`invalid codec parameter [key:${key}s, value:${value}]`);
2927 }
2928 // Specific parameters validation.
2929 if (key === 'apt') {
2930 if (typeof value !== 'number') {
2931 throw new TypeError('invalid codec apt parameter');
2932 }
2933 }
2934 }
2935 // rtcpFeedback is optional. If unset, set it to an empty array.
2936 if (!codec.rtcpFeedback || !Array.isArray(codec.rtcpFeedback)) {
2937 codec.rtcpFeedback = [];
2938 }
2939 for (const fb of codec.rtcpFeedback) {
2940 validateRtcpFeedback(fb);
2941 }
2942 }
2943 ortc$d.validateRtpCodecCapability = validateRtpCodecCapability;
2944 /**
2945 * Validates RtcpFeedback. It may modify given data by adding missing
2946 * fields with default values.
2947 * It throws if invalid.
2948 */
2949 function validateRtcpFeedback(fb) {
2950 if (typeof fb !== 'object') {
2951 throw new TypeError('fb is not an object');
2952 }
2953 // type is mandatory.
2954 if (!fb.type || typeof fb.type !== 'string') {
2955 throw new TypeError('missing fb.type');
2956 }
2957 // parameter is optional. If unset set it to an empty string.
2958 if (!fb.parameter || typeof fb.parameter !== 'string') {
2959 fb.parameter = '';
2960 }
2961 }
2962 ortc$d.validateRtcpFeedback = validateRtcpFeedback;
2963 /**
2964 * Validates RtpHeaderExtension. It may modify given data by adding missing
2965 * fields with default values.
2966 * It throws if invalid.
2967 */
2968 function validateRtpHeaderExtension(ext) {
2969 if (typeof ext !== 'object') {
2970 throw new TypeError('ext is not an object');
2971 }
2972 // kind is mandatory.
2973 if (ext.kind !== 'audio' && ext.kind !== 'video') {
2974 throw new TypeError('invalid ext.kind');
2975 }
2976 // uri is mandatory.
2977 if (!ext.uri || typeof ext.uri !== 'string') {
2978 throw new TypeError('missing ext.uri');
2979 }
2980 // preferredId is mandatory.
2981 if (typeof ext.preferredId !== 'number') {
2982 throw new TypeError('missing ext.preferredId');
2983 }
2984 // preferredEncrypt is optional. If unset set it to false.
2985 if (ext.preferredEncrypt && typeof ext.preferredEncrypt !== 'boolean') {
2986 throw new TypeError('invalid ext.preferredEncrypt');
2987 }
2988 else if (!ext.preferredEncrypt) {
2989 ext.preferredEncrypt = false;
2990 }
2991 // direction is optional. If unset set it to sendrecv.
2992 if (ext.direction && typeof ext.direction !== 'string') {
2993 throw new TypeError('invalid ext.direction');
2994 }
2995 else if (!ext.direction) {
2996 ext.direction = 'sendrecv';
2997 }
2998 }
2999 ortc$d.validateRtpHeaderExtension = validateRtpHeaderExtension;
3000 /**
3001 * Validates RtpParameters. It may modify given data by adding missing
3002 * fields with default values.
3003 * It throws if invalid.
3004 */
3005 function validateRtpParameters(params) {
3006 if (typeof params !== 'object') {
3007 throw new TypeError('params is not an object');
3008 }
3009 // mid is optional.
3010 if (params.mid && typeof params.mid !== 'string') {
3011 throw new TypeError('params.mid is not a string');
3012 }
3013 // codecs is mandatory.
3014 if (!Array.isArray(params.codecs)) {
3015 throw new TypeError('missing params.codecs');
3016 }
3017 for (const codec of params.codecs) {
3018 validateRtpCodecParameters(codec);
3019 }
3020 // headerExtensions is optional. If unset, fill with an empty array.
3021 if (params.headerExtensions && !Array.isArray(params.headerExtensions)) {
3022 throw new TypeError('params.headerExtensions is not an array');
3023 }
3024 else if (!params.headerExtensions) {
3025 params.headerExtensions = [];
3026 }
3027 for (const ext of params.headerExtensions) {
3028 validateRtpHeaderExtensionParameters(ext);
3029 }
3030 // encodings is optional. If unset, fill with an empty array.
3031 if (params.encodings && !Array.isArray(params.encodings)) {
3032 throw new TypeError('params.encodings is not an array');
3033 }
3034 else if (!params.encodings) {
3035 params.encodings = [];
3036 }
3037 for (const encoding of params.encodings) {
3038 validateRtpEncodingParameters(encoding);
3039 }
3040 // rtcp is optional. If unset, fill with an empty object.
3041 if (params.rtcp && typeof params.rtcp !== 'object') {
3042 throw new TypeError('params.rtcp is not an object');
3043 }
3044 else if (!params.rtcp) {
3045 params.rtcp = {};
3046 }
3047 validateRtcpParameters(params.rtcp);
3048 }
3049 ortc$d.validateRtpParameters = validateRtpParameters;
3050 /**
3051 * Validates RtpCodecParameters. It may modify given data by adding missing
3052 * fields with default values.
3053 * It throws if invalid.
3054 */
3055 function validateRtpCodecParameters(codec) {
3056 const MimeTypeRegex = new RegExp('^(audio|video)/(.+)', 'i');
3057 if (typeof codec !== 'object') {
3058 throw new TypeError('codec is not an object');
3059 }
3060 // mimeType is mandatory.
3061 if (!codec.mimeType || typeof codec.mimeType !== 'string') {
3062 throw new TypeError('missing codec.mimeType');
3063 }
3064 const mimeTypeMatch = MimeTypeRegex.exec(codec.mimeType);
3065 if (!mimeTypeMatch) {
3066 throw new TypeError('invalid codec.mimeType');
3067 }
3068 // payloadType is mandatory.
3069 if (typeof codec.payloadType !== 'number') {
3070 throw new TypeError('missing codec.payloadType');
3071 }
3072 // clockRate is mandatory.
3073 if (typeof codec.clockRate !== 'number') {
3074 throw new TypeError('missing codec.clockRate');
3075 }
3076 const kind = mimeTypeMatch[1].toLowerCase();
3077 // channels is optional. If unset, set it to 1 (just if audio).
3078 if (kind === 'audio') {
3079 if (typeof codec.channels !== 'number') {
3080 codec.channels = 1;
3081 }
3082 }
3083 else {
3084 delete codec.channels;
3085 }
3086 // parameters is optional. If unset, set it to an empty object.
3087 if (!codec.parameters || typeof codec.parameters !== 'object') {
3088 codec.parameters = {};
3089 }
3090 for (const key of Object.keys(codec.parameters)) {
3091 let value = codec.parameters[key];
3092 if (value === undefined) {
3093 codec.parameters[key] = '';
3094 value = '';
3095 }
3096 if (typeof value !== 'string' && typeof value !== 'number') {
3097 throw new TypeError(`invalid codec parameter [key:${key}s, value:${value}]`);
3098 }
3099 // Specific parameters validation.
3100 if (key === 'apt') {
3101 if (typeof value !== 'number') {
3102 throw new TypeError('invalid codec apt parameter');
3103 }
3104 }
3105 }
3106 // rtcpFeedback is optional. If unset, set it to an empty array.
3107 if (!codec.rtcpFeedback || !Array.isArray(codec.rtcpFeedback)) {
3108 codec.rtcpFeedback = [];
3109 }
3110 for (const fb of codec.rtcpFeedback) {
3111 validateRtcpFeedback(fb);
3112 }
3113 }
3114 ortc$d.validateRtpCodecParameters = validateRtpCodecParameters;
3115 /**
3116 * Validates RtpHeaderExtensionParameteters. It may modify given data by adding missing
3117 * fields with default values.
3118 * It throws if invalid.
3119 */
3120 function validateRtpHeaderExtensionParameters(ext) {
3121 if (typeof ext !== 'object') {
3122 throw new TypeError('ext is not an object');
3123 }
3124 // uri is mandatory.
3125 if (!ext.uri || typeof ext.uri !== 'string') {
3126 throw new TypeError('missing ext.uri');
3127 }
3128 // id is mandatory.
3129 if (typeof ext.id !== 'number') {
3130 throw new TypeError('missing ext.id');
3131 }
3132 // encrypt is optional. If unset set it to false.
3133 if (ext.encrypt && typeof ext.encrypt !== 'boolean') {
3134 throw new TypeError('invalid ext.encrypt');
3135 }
3136 else if (!ext.encrypt) {
3137 ext.encrypt = false;
3138 }
3139 // parameters is optional. If unset, set it to an empty object.
3140 if (!ext.parameters || typeof ext.parameters !== 'object') {
3141 ext.parameters = {};
3142 }
3143 for (const key of Object.keys(ext.parameters)) {
3144 let value = ext.parameters[key];
3145 if (value === undefined) {
3146 ext.parameters[key] = '';
3147 value = '';
3148 }
3149 if (typeof value !== 'string' && typeof value !== 'number') {
3150 throw new TypeError('invalid header extension parameter');
3151 }
3152 }
3153 }
3154 ortc$d.validateRtpHeaderExtensionParameters = validateRtpHeaderExtensionParameters;
3155 /**
3156 * Validates RtpEncodingParameters. It may modify given data by adding missing
3157 * fields with default values.
3158 * It throws if invalid.
3159 */
3160 function validateRtpEncodingParameters(encoding) {
3161 if (typeof encoding !== 'object') {
3162 throw new TypeError('encoding is not an object');
3163 }
3164 // ssrc is optional.
3165 if (encoding.ssrc && typeof encoding.ssrc !== 'number') {
3166 throw new TypeError('invalid encoding.ssrc');
3167 }
3168 // rid is optional.
3169 if (encoding.rid && typeof encoding.rid !== 'string') {
3170 throw new TypeError('invalid encoding.rid');
3171 }
3172 // rtx is optional.
3173 if (encoding.rtx && typeof encoding.rtx !== 'object') {
3174 throw new TypeError('invalid encoding.rtx');
3175 }
3176 else if (encoding.rtx) {
3177 // RTX ssrc is mandatory if rtx is present.
3178 if (typeof encoding.rtx.ssrc !== 'number') {
3179 throw new TypeError('missing encoding.rtx.ssrc');
3180 }
3181 }
3182 // dtx is optional. If unset set it to false.
3183 if (!encoding.dtx || typeof encoding.dtx !== 'boolean') {
3184 encoding.dtx = false;
3185 }
3186 // scalabilityMode is optional.
3187 if (encoding.scalabilityMode && typeof encoding.scalabilityMode !== 'string') {
3188 throw new TypeError('invalid encoding.scalabilityMode');
3189 }
3190 }
3191 ortc$d.validateRtpEncodingParameters = validateRtpEncodingParameters;
3192 /**
3193 * Validates RtcpParameters. It may modify given data by adding missing
3194 * fields with default values.
3195 * It throws if invalid.
3196 */
3197 function validateRtcpParameters(rtcp) {
3198 if (typeof rtcp !== 'object') {
3199 throw new TypeError('rtcp is not an object');
3200 }
3201 // cname is optional.
3202 if (rtcp.cname && typeof rtcp.cname !== 'string') {
3203 throw new TypeError('invalid rtcp.cname');
3204 }
3205 // reducedSize is optional. If unset set it to true.
3206 if (!rtcp.reducedSize || typeof rtcp.reducedSize !== 'boolean') {
3207 rtcp.reducedSize = true;
3208 }
3209 }
3210 ortc$d.validateRtcpParameters = validateRtcpParameters;
3211 /**
3212 * Validates SctpCapabilities. It may modify given data by adding missing
3213 * fields with default values.
3214 * It throws if invalid.
3215 */
3216 function validateSctpCapabilities(caps) {
3217 if (typeof caps !== 'object') {
3218 throw new TypeError('caps is not an object');
3219 }
3220 // numStreams is mandatory.
3221 if (!caps.numStreams || typeof caps.numStreams !== 'object') {
3222 throw new TypeError('missing caps.numStreams');
3223 }
3224 validateNumSctpStreams(caps.numStreams);
3225 }
3226 ortc$d.validateSctpCapabilities = validateSctpCapabilities;
3227 /**
3228 * Validates NumSctpStreams. It may modify given data by adding missing
3229 * fields with default values.
3230 * It throws if invalid.
3231 */
3232 function validateNumSctpStreams(numStreams) {
3233 if (typeof numStreams !== 'object') {
3234 throw new TypeError('numStreams is not an object');
3235 }
3236 // OS is mandatory.
3237 if (typeof numStreams.OS !== 'number') {
3238 throw new TypeError('missing numStreams.OS');
3239 }
3240 // MIS is mandatory.
3241 if (typeof numStreams.MIS !== 'number') {
3242 throw new TypeError('missing numStreams.MIS');
3243 }
3244 }
3245 ortc$d.validateNumSctpStreams = validateNumSctpStreams;
3246 /**
3247 * Validates SctpParameters. It may modify given data by adding missing
3248 * fields with default values.
3249 * It throws if invalid.
3250 */
3251 function validateSctpParameters(params) {
3252 if (typeof params !== 'object') {
3253 throw new TypeError('params is not an object');
3254 }
3255 // port is mandatory.
3256 if (typeof params.port !== 'number') {
3257 throw new TypeError('missing params.port');
3258 }
3259 // OS is mandatory.
3260 if (typeof params.OS !== 'number') {
3261 throw new TypeError('missing params.OS');
3262 }
3263 // MIS is mandatory.
3264 if (typeof params.MIS !== 'number') {
3265 throw new TypeError('missing params.MIS');
3266 }
3267 // maxMessageSize is mandatory.
3268 if (typeof params.maxMessageSize !== 'number') {
3269 throw new TypeError('missing params.maxMessageSize');
3270 }
3271 }
3272 ortc$d.validateSctpParameters = validateSctpParameters;
3273 /**
3274 * Validates SctpStreamParameters. It may modify given data by adding missing
3275 * fields with default values.
3276 * It throws if invalid.
3277 */
3278 function validateSctpStreamParameters(params) {
3279 if (typeof params !== 'object') {
3280 throw new TypeError('params is not an object');
3281 }
3282 // streamId is mandatory.
3283 if (typeof params.streamId !== 'number') {
3284 throw new TypeError('missing params.streamId');
3285 }
3286 // ordered is optional.
3287 let orderedGiven = false;
3288 if (typeof params.ordered === 'boolean') {
3289 orderedGiven = true;
3290 }
3291 else {
3292 params.ordered = true;
3293 }
3294 // maxPacketLifeTime is optional.
3295 if (params.maxPacketLifeTime && typeof params.maxPacketLifeTime !== 'number') {
3296 throw new TypeError('invalid params.maxPacketLifeTime');
3297 }
3298 // maxRetransmits is optional.
3299 if (params.maxRetransmits && typeof params.maxRetransmits !== 'number') {
3300 throw new TypeError('invalid params.maxRetransmits');
3301 }
3302 if (params.maxPacketLifeTime && params.maxRetransmits) {
3303 throw new TypeError('cannot provide both maxPacketLifeTime and maxRetransmits');
3304 }
3305 if (orderedGiven &&
3306 params.ordered &&
3307 (params.maxPacketLifeTime || params.maxRetransmits)) {
3308 throw new TypeError('cannot be ordered with maxPacketLifeTime or maxRetransmits');
3309 }
3310 else if (!orderedGiven && (params.maxPacketLifeTime || params.maxRetransmits)) {
3311 params.ordered = false;
3312 }
3313 // label is optional.
3314 if (params.label && typeof params.label !== 'string') {
3315 throw new TypeError('invalid params.label');
3316 }
3317 // protocol is optional.
3318 if (params.protocol && typeof params.protocol !== 'string') {
3319 throw new TypeError('invalid params.protocol');
3320 }
3321 }
3322 ortc$d.validateSctpStreamParameters = validateSctpStreamParameters;
3323 /**
3324 * Generate extended RTP capabilities for sending and receiving.
3325 */
3326 function getExtendedRtpCapabilities(localCaps, remoteCaps) {
3327 const extendedRtpCapabilities = {
3328 codecs: [],
3329 headerExtensions: []
3330 };
3331 // Match media codecs and keep the order preferred by remoteCaps.
3332 for (const remoteCodec of remoteCaps.codecs || []) {
3333 if (isRtxCodec(remoteCodec)) {
3334 continue;
3335 }
3336 const matchingLocalCodec = (localCaps.codecs || [])
3337 .find((localCodec) => (matchCodecs(localCodec, remoteCodec, { strict: true, modify: true })));
3338 if (!matchingLocalCodec) {
3339 continue;
3340 }
3341 const extendedCodec = {
3342 mimeType: matchingLocalCodec.mimeType,
3343 kind: matchingLocalCodec.kind,
3344 clockRate: matchingLocalCodec.clockRate,
3345 channels: matchingLocalCodec.channels,
3346 localPayloadType: matchingLocalCodec.preferredPayloadType,
3347 localRtxPayloadType: undefined,
3348 remotePayloadType: remoteCodec.preferredPayloadType,
3349 remoteRtxPayloadType: undefined,
3350 localParameters: matchingLocalCodec.parameters,
3351 remoteParameters: remoteCodec.parameters,
3352 rtcpFeedback: reduceRtcpFeedback(matchingLocalCodec, remoteCodec)
3353 };
3354 extendedRtpCapabilities.codecs.push(extendedCodec);
3355 }
3356 // Match RTX codecs.
3357 for (const extendedCodec of extendedRtpCapabilities.codecs) {
3358 const matchingLocalRtxCodec = localCaps.codecs
3359 .find((localCodec) => (isRtxCodec(localCodec) &&
3360 localCodec.parameters.apt === extendedCodec.localPayloadType));
3361 const matchingRemoteRtxCodec = remoteCaps.codecs
3362 .find((remoteCodec) => (isRtxCodec(remoteCodec) &&
3363 remoteCodec.parameters.apt === extendedCodec.remotePayloadType));
3364 if (matchingLocalRtxCodec && matchingRemoteRtxCodec) {
3365 extendedCodec.localRtxPayloadType = matchingLocalRtxCodec.preferredPayloadType;
3366 extendedCodec.remoteRtxPayloadType = matchingRemoteRtxCodec.preferredPayloadType;
3367 }
3368 }
3369 // Match header extensions.
3370 for (const remoteExt of remoteCaps.headerExtensions) {
3371 const matchingLocalExt = localCaps.headerExtensions
3372 .find((localExt) => (matchHeaderExtensions(localExt, remoteExt)));
3373 if (!matchingLocalExt) {
3374 continue;
3375 }
3376 const extendedExt = {
3377 kind: remoteExt.kind,
3378 uri: remoteExt.uri,
3379 sendId: matchingLocalExt.preferredId,
3380 recvId: remoteExt.preferredId,
3381 encrypt: matchingLocalExt.preferredEncrypt,
3382 direction: 'sendrecv'
3383 };
3384 switch (remoteExt.direction) {
3385 case 'sendrecv':
3386 extendedExt.direction = 'sendrecv';
3387 break;
3388 case 'recvonly':
3389 extendedExt.direction = 'sendonly';
3390 break;
3391 case 'sendonly':
3392 extendedExt.direction = 'recvonly';
3393 break;
3394 case 'inactive':
3395 extendedExt.direction = 'inactive';
3396 break;
3397 }
3398 extendedRtpCapabilities.headerExtensions.push(extendedExt);
3399 }
3400 return extendedRtpCapabilities;
3401 }
3402 ortc$d.getExtendedRtpCapabilities = getExtendedRtpCapabilities;
3403 /**
3404 * Generate RTP capabilities for receiving media based on the given extended
3405 * RTP capabilities.
3406 */
3407 function getRecvRtpCapabilities(extendedRtpCapabilities) {
3408 const rtpCapabilities = {
3409 codecs: [],
3410 headerExtensions: []
3411 };
3412 for (const extendedCodec of extendedRtpCapabilities.codecs) {
3413 const codec = {
3414 mimeType: extendedCodec.mimeType,
3415 kind: extendedCodec.kind,
3416 preferredPayloadType: extendedCodec.remotePayloadType,
3417 clockRate: extendedCodec.clockRate,
3418 channels: extendedCodec.channels,
3419 parameters: extendedCodec.localParameters,
3420 rtcpFeedback: extendedCodec.rtcpFeedback
3421 };
3422 rtpCapabilities.codecs.push(codec);
3423 // Add RTX codec.
3424 if (!extendedCodec.remoteRtxPayloadType) {
3425 continue;
3426 }
3427 const rtxCodec = {
3428 mimeType: `${extendedCodec.kind}/rtx`,
3429 kind: extendedCodec.kind,
3430 preferredPayloadType: extendedCodec.remoteRtxPayloadType,
3431 clockRate: extendedCodec.clockRate,
3432 parameters: {
3433 apt: extendedCodec.remotePayloadType
3434 },
3435 rtcpFeedback: []
3436 };
3437 rtpCapabilities.codecs.push(rtxCodec);
3438 // TODO: In the future, we need to add FEC, CN, etc, codecs.
3439 }
3440 for (const extendedExtension of extendedRtpCapabilities.headerExtensions) {
3441 // Ignore RTP extensions not valid for receiving.
3442 if (extendedExtension.direction !== 'sendrecv' &&
3443 extendedExtension.direction !== 'recvonly') {
3444 continue;
3445 }
3446 const ext = {
3447 kind: extendedExtension.kind,
3448 uri: extendedExtension.uri,
3449 preferredId: extendedExtension.recvId,
3450 preferredEncrypt: extendedExtension.encrypt,
3451 direction: extendedExtension.direction
3452 };
3453 rtpCapabilities.headerExtensions.push(ext);
3454 }
3455 return rtpCapabilities;
3456 }
3457 ortc$d.getRecvRtpCapabilities = getRecvRtpCapabilities;
3458 /**
3459 * Generate RTP parameters of the given kind for sending media.
3460 * NOTE: mid, encodings and rtcp fields are left empty.
3461 */
3462 function getSendingRtpParameters(kind, extendedRtpCapabilities) {
3463 const rtpParameters = {
3464 mid: undefined,
3465 codecs: [],
3466 headerExtensions: [],
3467 encodings: [],
3468 rtcp: {}
3469 };
3470 for (const extendedCodec of extendedRtpCapabilities.codecs) {
3471 if (extendedCodec.kind !== kind) {
3472 continue;
3473 }
3474 const codec = {
3475 mimeType: extendedCodec.mimeType,
3476 payloadType: extendedCodec.localPayloadType,
3477 clockRate: extendedCodec.clockRate,
3478 channels: extendedCodec.channels,
3479 parameters: extendedCodec.localParameters,
3480 rtcpFeedback: extendedCodec.rtcpFeedback
3481 };
3482 rtpParameters.codecs.push(codec);
3483 // Add RTX codec.
3484 if (extendedCodec.localRtxPayloadType) {
3485 const rtxCodec = {
3486 mimeType: `${extendedCodec.kind}/rtx`,
3487 payloadType: extendedCodec.localRtxPayloadType,
3488 clockRate: extendedCodec.clockRate,
3489 parameters: {
3490 apt: extendedCodec.localPayloadType
3491 },
3492 rtcpFeedback: []
3493 };
3494 rtpParameters.codecs.push(rtxCodec);
3495 }
3496 }
3497 for (const extendedExtension of extendedRtpCapabilities.headerExtensions) {
3498 // Ignore RTP extensions of a different kind and those not valid for sending.
3499 if ((extendedExtension.kind && extendedExtension.kind !== kind) ||
3500 (extendedExtension.direction !== 'sendrecv' &&
3501 extendedExtension.direction !== 'sendonly')) {
3502 continue;
3503 }
3504 const ext = {
3505 uri: extendedExtension.uri,
3506 id: extendedExtension.sendId,
3507 encrypt: extendedExtension.encrypt,
3508 parameters: {}
3509 };
3510 rtpParameters.headerExtensions.push(ext);
3511 }
3512 return rtpParameters;
3513 }
3514 ortc$d.getSendingRtpParameters = getSendingRtpParameters;
3515 /**
3516 * Generate RTP parameters of the given kind suitable for the remote SDP answer.
3517 */
3518 function getSendingRemoteRtpParameters(kind, extendedRtpCapabilities) {
3519 const rtpParameters = {
3520 mid: undefined,
3521 codecs: [],
3522 headerExtensions: [],
3523 encodings: [],
3524 rtcp: {}
3525 };
3526 for (const extendedCodec of extendedRtpCapabilities.codecs) {
3527 if (extendedCodec.kind !== kind) {
3528 continue;
3529 }
3530 const codec = {
3531 mimeType: extendedCodec.mimeType,
3532 payloadType: extendedCodec.localPayloadType,
3533 clockRate: extendedCodec.clockRate,
3534 channels: extendedCodec.channels,
3535 parameters: extendedCodec.remoteParameters,
3536 rtcpFeedback: extendedCodec.rtcpFeedback
3537 };
3538 rtpParameters.codecs.push(codec);
3539 // Add RTX codec.
3540 if (extendedCodec.localRtxPayloadType) {
3541 const rtxCodec = {
3542 mimeType: `${extendedCodec.kind}/rtx`,
3543 payloadType: extendedCodec.localRtxPayloadType,
3544 clockRate: extendedCodec.clockRate,
3545 parameters: {
3546 apt: extendedCodec.localPayloadType
3547 },
3548 rtcpFeedback: []
3549 };
3550 rtpParameters.codecs.push(rtxCodec);
3551 }
3552 }
3553 for (const extendedExtension of extendedRtpCapabilities.headerExtensions) {
3554 // Ignore RTP extensions of a different kind and those not valid for sending.
3555 if ((extendedExtension.kind && extendedExtension.kind !== kind) ||
3556 (extendedExtension.direction !== 'sendrecv' &&
3557 extendedExtension.direction !== 'sendonly')) {
3558 continue;
3559 }
3560 const ext = {
3561 uri: extendedExtension.uri,
3562 id: extendedExtension.sendId,
3563 encrypt: extendedExtension.encrypt,
3564 parameters: {}
3565 };
3566 rtpParameters.headerExtensions.push(ext);
3567 }
3568 // Reduce codecs' RTCP feedback. Use Transport-CC if available, REMB otherwise.
3569 if (rtpParameters.headerExtensions.some((ext) => (ext.uri === 'http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01'))) {
3570 for (const codec of rtpParameters.codecs) {
3571 codec.rtcpFeedback = (codec.rtcpFeedback || [])
3572 .filter((fb) => fb.type !== 'goog-remb');
3573 }
3574 }
3575 else if (rtpParameters.headerExtensions.some((ext) => (ext.uri === 'http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time'))) {
3576 for (const codec of rtpParameters.codecs) {
3577 codec.rtcpFeedback = (codec.rtcpFeedback || [])
3578 .filter((fb) => fb.type !== 'transport-cc');
3579 }
3580 }
3581 else {
3582 for (const codec of rtpParameters.codecs) {
3583 codec.rtcpFeedback = (codec.rtcpFeedback || [])
3584 .filter((fb) => (fb.type !== 'transport-cc' &&
3585 fb.type !== 'goog-remb'));
3586 }
3587 }
3588 return rtpParameters;
3589 }
3590 ortc$d.getSendingRemoteRtpParameters = getSendingRemoteRtpParameters;
3591 /**
3592 * Reduce given codecs by returning an array of codecs "compatible" with the
3593 * given capability codec. If no capability codec is given, take the first
3594 * one(s).
3595 *
3596 * Given codecs must be generated by ortc.getSendingRtpParameters() or
3597 * ortc.getSendingRemoteRtpParameters().
3598 *
3599 * The returned array of codecs also include a RTX codec if available.
3600 */
3601 function reduceCodecs(codecs, capCodec) {
3602 const filteredCodecs = [];
3603 // If no capability codec is given, take the first one (and RTX).
3604 if (!capCodec) {
3605 filteredCodecs.push(codecs[0]);
3606 if (isRtxCodec(codecs[1])) {
3607 filteredCodecs.push(codecs[1]);
3608 }
3609 }
3610 // Otherwise look for a compatible set of codecs.
3611 else {
3612 for (let idx = 0; idx < codecs.length; ++idx) {
3613 if (matchCodecs(codecs[idx], capCodec)) {
3614 filteredCodecs.push(codecs[idx]);
3615 if (isRtxCodec(codecs[idx + 1])) {
3616 filteredCodecs.push(codecs[idx + 1]);
3617 }
3618 break;
3619 }
3620 }
3621 if (filteredCodecs.length === 0) {
3622 throw new TypeError('no matching codec found');
3623 }
3624 }
3625 return filteredCodecs;
3626 }
3627 ortc$d.reduceCodecs = reduceCodecs;
3628 /**
3629 * Create RTP parameters for a Consumer for the RTP probator.
3630 */
3631 function generateProbatorRtpParameters(videoRtpParameters) {
3632 // Clone given reference video RTP parameters.
3633 videoRtpParameters = utils$g.clone(videoRtpParameters);
3634 // This may throw.
3635 validateRtpParameters(videoRtpParameters);
3636 const rtpParameters = {
3637 mid: RTP_PROBATOR_MID,
3638 codecs: [],
3639 headerExtensions: [],
3640 encodings: [{ ssrc: RTP_PROBATOR_SSRC }],
3641 rtcp: { cname: 'probator' }
3642 };
3643 rtpParameters.codecs.push(videoRtpParameters.codecs[0]);
3644 rtpParameters.codecs[0].payloadType = RTP_PROBATOR_CODEC_PAYLOAD_TYPE;
3645 rtpParameters.headerExtensions = videoRtpParameters.headerExtensions;
3646 return rtpParameters;
3647 }
3648 ortc$d.generateProbatorRtpParameters = generateProbatorRtpParameters;
3649 /**
3650 * Whether media can be sent based on the given RTP capabilities.
3651 */
3652 function canSend(kind, extendedRtpCapabilities) {
3653 return extendedRtpCapabilities.codecs.
3654 some((codec) => codec.kind === kind);
3655 }
3656 ortc$d.canSend = canSend;
3657 /**
3658 * Whether the given RTP parameters can be received with the given RTP
3659 * capabilities.
3660 */
3661 function canReceive(rtpParameters, extendedRtpCapabilities) {
3662 // This may throw.
3663 validateRtpParameters(rtpParameters);
3664 if (rtpParameters.codecs.length === 0) {
3665 return false;
3666 }
3667 const firstMediaCodec = rtpParameters.codecs[0];
3668 return extendedRtpCapabilities.codecs
3669 .some((codec) => codec.remotePayloadType === firstMediaCodec.payloadType);
3670 }
3671 ortc$d.canReceive = canReceive;
3672 function isRtxCodec(codec) {
3673 if (!codec) {
3674 return false;
3675 }
3676 return /.+\/rtx$/i.test(codec.mimeType);
3677 }
3678 function matchCodecs(aCodec, bCodec, { strict = false, modify = false } = {}) {
3679 const aMimeType = aCodec.mimeType.toLowerCase();
3680 const bMimeType = bCodec.mimeType.toLowerCase();
3681 if (aMimeType !== bMimeType) {
3682 return false;
3683 }
3684 if (aCodec.clockRate !== bCodec.clockRate) {
3685 return false;
3686 }
3687 if (aCodec.channels !== bCodec.channels) {
3688 return false;
3689 }
3690 // Per codec special checks.
3691 switch (aMimeType) {
3692 case 'video/h264':
3693 {
3694 if (strict) {
3695 const aPacketizationMode = aCodec.parameters['packetization-mode'] || 0;
3696 const bPacketizationMode = bCodec.parameters['packetization-mode'] || 0;
3697 if (aPacketizationMode !== bPacketizationMode) {
3698 return false;
3699 }
3700 if (!h264.isSameProfile(aCodec.parameters, bCodec.parameters)) {
3701 return false;
3702 }
3703 let selectedProfileLevelId;
3704 try {
3705 selectedProfileLevelId =
3706 h264.generateProfileLevelIdForAnswer(aCodec.parameters, bCodec.parameters);
3707 }
3708 catch (error) {
3709 return false;
3710 }
3711 if (modify) {
3712 if (selectedProfileLevelId) {
3713 aCodec.parameters['profile-level-id'] = selectedProfileLevelId;
3714 bCodec.parameters['profile-level-id'] = selectedProfileLevelId;
3715 }
3716 else {
3717 delete aCodec.parameters['profile-level-id'];
3718 delete bCodec.parameters['profile-level-id'];
3719 }
3720 }
3721 }
3722 break;
3723 }
3724 case 'video/vp9':
3725 {
3726 if (strict) {
3727 const aProfileId = aCodec.parameters['profile-id'] || 0;
3728 const bProfileId = bCodec.parameters['profile-id'] || 0;
3729 if (aProfileId !== bProfileId) {
3730 return false;
3731 }
3732 }
3733 break;
3734 }
3735 }
3736 return true;
3737 }
3738 function matchHeaderExtensions(aExt, bExt) {
3739 if (aExt.kind && bExt.kind && aExt.kind !== bExt.kind) {
3740 return false;
3741 }
3742 if (aExt.uri !== bExt.uri) {
3743 return false;
3744 }
3745 return true;
3746 }
3747 function reduceRtcpFeedback(codecA, codecB) {
3748 const reducedRtcpFeedback = [];
3749 for (const aFb of codecA.rtcpFeedback || []) {
3750 const matchingBFb = (codecB.rtcpFeedback || [])
3751 .find((bFb) => (bFb.type === aFb.type &&
3752 (bFb.parameter === aFb.parameter || (!bFb.parameter && !aFb.parameter))));
3753 if (matchingBFb) {
3754 reducedRtcpFeedback.push(matchingBFb);
3755 }
3756 }
3757 return reducedRtcpFeedback;
3758 }
3759
3760 var Transport$1 = {};
3761
3762 var lib$1 = {};
3763
3764 var Logger$1 = {};
3765
3766 Object.defineProperty(Logger$1, "__esModule", { value: true });
3767 Logger$1.Logger = void 0;
3768 const debug_1 = browserExports;
3769 const LIB_NAME = 'awaitqueue';
3770 class Logger {
3771 constructor(prefix) {
3772 if (prefix) {
3773 this._debug = (0, debug_1.default)(`${LIB_NAME}:${prefix}`);
3774 this._warn = (0, debug_1.default)(`${LIB_NAME}:WARN:${prefix}`);
3775 this._error = (0, debug_1.default)(`${LIB_NAME}:ERROR:${prefix}`);
3776 }
3777 else {
3778 this._debug = (0, debug_1.default)(LIB_NAME);
3779 this._warn = (0, debug_1.default)(`${LIB_NAME}:WARN`);
3780 this._error = (0, debug_1.default)(`${LIB_NAME}:ERROR`);
3781 }
3782 /* eslint-disable no-console */
3783 this._debug.log = console.info.bind(console);
3784 this._warn.log = console.warn.bind(console);
3785 this._error.log = console.error.bind(console);
3786 /* eslint-enable no-console */
3787 }
3788 get debug() {
3789 return this._debug;
3790 }
3791 get warn() {
3792 return this._warn;
3793 }
3794 get error() {
3795 return this._error;
3796 }
3797 }
3798 Logger$1.Logger = Logger;
3799
3800 Object.defineProperty(lib$1, "__esModule", { value: true });
3801 lib$1.AwaitQueue = lib$1.AwaitQueueRemovedTaskError = lib$1.AwaitQueueStoppedError = void 0;
3802 const Logger_1$i = Logger$1;
3803 const logger$i = new Logger_1$i.Logger();
3804 /**
3805 * Custom Error derived class used to reject pending tasks once stop() method
3806 * has been called.
3807 */
3808 class AwaitQueueStoppedError extends Error {
3809 constructor(message) {
3810 super(message ?? 'AwaitQueue stopped');
3811 this.name = 'AwaitQueueStoppedError';
3812 // @ts-ignore
3813 if (typeof Error.captureStackTrace === 'function') {
3814 // @ts-ignore
3815 Error.captureStackTrace(this, AwaitQueueStoppedError);
3816 }
3817 }
3818 }
3819 lib$1.AwaitQueueStoppedError = AwaitQueueStoppedError;
3820 /**
3821 * Custom Error derived class used to reject pending tasks once removeTask()
3822 * method has been called.
3823 */
3824 class AwaitQueueRemovedTaskError extends Error {
3825 constructor(message) {
3826 super(message ?? 'AwaitQueue task removed');
3827 this.name = 'AwaitQueueRemovedTaskError';
3828 // @ts-ignore
3829 if (typeof Error.captureStackTrace === 'function') {
3830 // @ts-ignore
3831 Error.captureStackTrace(this, AwaitQueueRemovedTaskError);
3832 }
3833 }
3834 }
3835 lib$1.AwaitQueueRemovedTaskError = AwaitQueueRemovedTaskError;
3836 class AwaitQueue {
3837 constructor() {
3838 // Queue of pending tasks (map of PendingTasks indexed by id).
3839 this.pendingTasks = new Map();
3840 // Incrementing PendingTask id.
3841 this.nextTaskId = 0;
3842 // Whether stop() method is stopping all pending tasks.
3843 this.stopping = false;
3844 }
3845 get size() {
3846 return this.pendingTasks.size;
3847 }
3848 async push(task, name) {
3849 name = name ?? task.name;
3850 logger$i.debug(`push() [name:${name}]`);
3851 if (typeof task !== 'function') {
3852 throw new TypeError('given task is not a function');
3853 }
3854 if (name) {
3855 try {
3856 Object.defineProperty(task, 'name', { value: name });
3857 }
3858 catch (error) { }
3859 }
3860 return new Promise((resolve, reject) => {
3861 const pendingTask = {
3862 id: this.nextTaskId++,
3863 task: task,
3864 name: name,
3865 enqueuedAt: Date.now(),
3866 executedAt: undefined,
3867 completed: false,
3868 resolve: (result) => {
3869 // pendingTask.resolve() can only be called in execute() method. Since
3870 // resolve() was called it means that the task successfully completed.
3871 // However the task may have been stopped before it completed (via
3872 // stop() or remove()) so its completed flag was already set. If this
3873 // is the case, abort here since next task (if any) is already being
3874 // executed.
3875 if (pendingTask.completed) {
3876 return;
3877 }
3878 pendingTask.completed = true;
3879 // Remove the task from the queue.
3880 this.pendingTasks.delete(pendingTask.id);
3881 logger$i.debug(`resolving task [name:${pendingTask.name}]`);
3882 // Resolve the task with the obtained result.
3883 resolve(result);
3884 // Execute the next pending task (if any).
3885 const [nextPendingTask] = this.pendingTasks.values();
3886 // NOTE: During the resolve() callback the user app may have interacted
3887 // with the queue. For instance, the app may have pushed a task while
3888 // the queue was empty so such a task is already being executed. If so,
3889 // don't execute it twice.
3890 if (nextPendingTask && !nextPendingTask.executedAt) {
3891 void this.execute(nextPendingTask);
3892 }
3893 },
3894 reject: (error) => {
3895 // pendingTask.reject() can be called within execute() method if the
3896 // task completed with error. However it may have also been called in
3897 // stop() or remove() methods (before or while being executed) so its
3898 // completed flag was already set. If so, abort here since next task
3899 // (if any) is already being executed.
3900 if (pendingTask.completed) {
3901 return;
3902 }
3903 pendingTask.completed = true;
3904 // Remove the task from the queue.
3905 this.pendingTasks.delete(pendingTask.id);
3906 logger$i.debug(`rejecting task [name:${pendingTask.name}]: %s`, String(error));
3907 // Reject the task with the obtained error.
3908 reject(error);
3909 // Execute the next pending task (if any) unless stop() is running.
3910 if (!this.stopping) {
3911 const [nextPendingTask] = this.pendingTasks.values();
3912 // NOTE: During the reject() callback the user app may have interacted
3913 // with the queue. For instance, the app may have pushed a task while
3914 // the queue was empty so such a task is already being executed. If so,
3915 // don't execute it twice.
3916 if (nextPendingTask && !nextPendingTask.executedAt) {
3917 void this.execute(nextPendingTask);
3918 }
3919 }
3920 }
3921 };
3922 // Append task to the queue.
3923 this.pendingTasks.set(pendingTask.id, pendingTask);
3924 // And execute it if this is the only task in the queue.
3925 if (this.pendingTasks.size === 1) {
3926 void this.execute(pendingTask);
3927 }
3928 });
3929 }
3930 stop() {
3931 logger$i.debug('stop()');
3932 this.stopping = true;
3933 for (const pendingTask of this.pendingTasks.values()) {
3934 logger$i.debug(`stop() | stopping task [name:${pendingTask.name}]`);
3935 pendingTask.reject(new AwaitQueueStoppedError());
3936 }
3937 this.stopping = false;
3938 }
3939 remove(taskIdx) {
3940 logger$i.debug(`remove() [taskIdx:${taskIdx}]`);
3941 const pendingTask = Array.from(this.pendingTasks.values())[taskIdx];
3942 if (!pendingTask) {
3943 logger$i.debug(`stop() | no task with given idx [taskIdx:${taskIdx}]`);
3944 return;
3945 }
3946 pendingTask.reject(new AwaitQueueRemovedTaskError());
3947 }
3948 dump() {
3949 const now = Date.now();
3950 let idx = 0;
3951 return Array.from(this.pendingTasks.values()).map((pendingTask) => ({
3952 idx: idx++,
3953 task: pendingTask.task,
3954 name: pendingTask.name,
3955 enqueuedTime: pendingTask.executedAt
3956 ? pendingTask.executedAt - pendingTask.enqueuedAt
3957 : now - pendingTask.enqueuedAt,
3958 executionTime: pendingTask.executedAt
3959 ? now - pendingTask.executedAt
3960 : 0
3961 }));
3962 }
3963 async execute(pendingTask) {
3964 logger$i.debug(`execute() [name:${pendingTask.name}]`);
3965 if (pendingTask.executedAt) {
3966 throw new Error('task already being executed');
3967 }
3968 pendingTask.executedAt = Date.now();
3969 try {
3970 const result = await pendingTask.task();
3971 // Resolve the task with its resolved result (if any).
3972 pendingTask.resolve(result);
3973 }
3974 catch (error) {
3975 // Reject the task with its rejected error.
3976 pendingTask.reject(error);
3977 }
3978 }
3979 }
3980 lib$1.AwaitQueue = AwaitQueue;
3981
3982 /*! queue-microtask. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */
3983
3984 let promise;
3985
3986 var queueMicrotask_1 = typeof queueMicrotask === 'function'
3987 ? queueMicrotask.bind(typeof window !== 'undefined' ? window : commonjsGlobal)
3988 // reuse resolved promise, and allocate it lazily
3989 : cb => (promise || (promise = Promise.resolve()))
3990 .then(cb)
3991 .catch(err => setTimeout(() => { throw err }, 0));
3992
3993 var Producer$1 = {};
3994
3995 Object.defineProperty(Producer$1, "__esModule", { value: true });
3996 Producer$1.Producer = void 0;
3997 const Logger_1$h = Logger$3;
3998 const EnhancedEventEmitter_1$6 = EnhancedEventEmitter$1;
3999 const errors_1$c = errors;
4000 const logger$h = new Logger_1$h.Logger('Producer');
4001 class Producer extends EnhancedEventEmitter_1$6.EnhancedEventEmitter {
4002 constructor({ id, localId, rtpSender, track, rtpParameters, stopTracks, disableTrackOnPause, zeroRtpOnPause, appData }) {
4003 super();
4004 // Closed flag.
4005 this._closed = false;
4006 // Observer instance.
4007 this._observer = new EnhancedEventEmitter_1$6.EnhancedEventEmitter();
4008 logger$h.debug('constructor()');
4009 this._id = id;
4010 this._localId = localId;
4011 this._rtpSender = rtpSender;
4012 this._track = track;
4013 this._kind = track.kind;
4014 this._rtpParameters = rtpParameters;
4015 this._paused = disableTrackOnPause ? !track.enabled : false;
4016 this._maxSpatialLayer = undefined;
4017 this._stopTracks = stopTracks;
4018 this._disableTrackOnPause = disableTrackOnPause;
4019 this._zeroRtpOnPause = zeroRtpOnPause;
4020 this._appData = appData || {};
4021 this.onTrackEnded = this.onTrackEnded.bind(this);
4022 // NOTE: Minor issue. If zeroRtpOnPause is true, we cannot emit the
4023 // '@replacetrack' event here, so RTCRtpSender.track won't be null.
4024 this.handleTrack();
4025 }
4026 /**
4027 * Producer id.
4028 */
4029 get id() {
4030 return this._id;
4031 }
4032 /**
4033 * Local id.
4034 */
4035 get localId() {
4036 return this._localId;
4037 }
4038 /**
4039 * Whether the Producer is closed.
4040 */
4041 get closed() {
4042 return this._closed;
4043 }
4044 /**
4045 * Media kind.
4046 */
4047 get kind() {
4048 return this._kind;
4049 }
4050 /**
4051 * Associated RTCRtpSender.
4052 */
4053 get rtpSender() {
4054 return this._rtpSender;
4055 }
4056 /**
4057 * The associated track.
4058 */
4059 get track() {
4060 return this._track;
4061 }
4062 /**
4063 * RTP parameters.
4064 */
4065 get rtpParameters() {
4066 return this._rtpParameters;
4067 }
4068 /**
4069 * Whether the Producer is paused.
4070 */
4071 get paused() {
4072 return this._paused;
4073 }
4074 /**
4075 * Max spatial layer.
4076 *
4077 * @type {Number | undefined}
4078 */
4079 get maxSpatialLayer() {
4080 return this._maxSpatialLayer;
4081 }
4082 /**
4083 * App custom data.
4084 */
4085 get appData() {
4086 return this._appData;
4087 }
4088 /**
4089 * App custom data setter.
4090 */
4091 set appData(appData) {
4092 this._appData = appData;
4093 }
4094 get observer() {
4095 return this._observer;
4096 }
4097 /**
4098 * Closes the Producer.
4099 */
4100 close() {
4101 if (this._closed) {
4102 return;
4103 }
4104 logger$h.debug('close()');
4105 this._closed = true;
4106 this.destroyTrack();
4107 this.emit('@close');
4108 // Emit observer event.
4109 this._observer.safeEmit('close');
4110 }
4111 /**
4112 * Transport was closed.
4113 */
4114 transportClosed() {
4115 if (this._closed) {
4116 return;
4117 }
4118 logger$h.debug('transportClosed()');
4119 this._closed = true;
4120 this.destroyTrack();
4121 this.safeEmit('transportclose');
4122 // Emit observer event.
4123 this._observer.safeEmit('close');
4124 }
4125 /**
4126 * Get associated RTCRtpSender stats.
4127 */
4128 async getStats() {
4129 if (this._closed) {
4130 throw new errors_1$c.InvalidStateError('closed');
4131 }
4132 return new Promise((resolve, reject) => {
4133 this.safeEmit('@getstats', resolve, reject);
4134 });
4135 }
4136 /**
4137 * Pauses sending media.
4138 */
4139 pause() {
4140 logger$h.debug('pause()');
4141 if (this._closed) {
4142 logger$h.error('pause() | Producer closed');
4143 return;
4144 }
4145 this._paused = true;
4146 if (this._track && this._disableTrackOnPause) {
4147 this._track.enabled = false;
4148 }
4149 if (this._zeroRtpOnPause) {
4150 new Promise((resolve, reject) => {
4151 this.safeEmit('@pause', resolve, reject);
4152 }).catch(() => { });
4153 }
4154 // Emit observer event.
4155 this._observer.safeEmit('pause');
4156 }
4157 /**
4158 * Resumes sending media.
4159 */
4160 resume() {
4161 logger$h.debug('resume()');
4162 if (this._closed) {
4163 logger$h.error('resume() | Producer closed');
4164 return;
4165 }
4166 this._paused = false;
4167 if (this._track && this._disableTrackOnPause) {
4168 this._track.enabled = true;
4169 }
4170 if (this._zeroRtpOnPause) {
4171 new Promise((resolve, reject) => {
4172 this.safeEmit('@resume', resolve, reject);
4173 }).catch(() => { });
4174 }
4175 // Emit observer event.
4176 this._observer.safeEmit('resume');
4177 }
4178 /**
4179 * Replaces the current track with a new one or null.
4180 */
4181 async replaceTrack({ track }) {
4182 logger$h.debug('replaceTrack() [track:%o]', track);
4183 if (this._closed) {
4184 // This must be done here. Otherwise there is no chance to stop the given
4185 // track.
4186 if (track && this._stopTracks) {
4187 try {
4188 track.stop();
4189 }
4190 catch (error) { }
4191 }
4192 throw new errors_1$c.InvalidStateError('closed');
4193 }
4194 else if (track && track.readyState === 'ended') {
4195 throw new errors_1$c.InvalidStateError('track ended');
4196 }
4197 // Do nothing if this is the same track as the current handled one.
4198 if (track === this._track) {
4199 logger$h.debug('replaceTrack() | same track, ignored');
4200 return;
4201 }
4202 await new Promise((resolve, reject) => {
4203 this.safeEmit('@replacetrack', track, resolve, reject);
4204 });
4205 // Destroy the previous track.
4206 this.destroyTrack();
4207 // Set the new track.
4208 this._track = track;
4209 // If this Producer was paused/resumed and the state of the new
4210 // track does not match, fix it.
4211 if (this._track && this._disableTrackOnPause) {
4212 if (!this._paused) {
4213 this._track.enabled = true;
4214 }
4215 else if (this._paused) {
4216 this._track.enabled = false;
4217 }
4218 }
4219 // Handle the effective track.
4220 this.handleTrack();
4221 }
4222 /**
4223 * Sets the video max spatial layer to be sent.
4224 */
4225 async setMaxSpatialLayer(spatialLayer) {
4226 if (this._closed) {
4227 throw new errors_1$c.InvalidStateError('closed');
4228 }
4229 else if (this._kind !== 'video') {
4230 throw new errors_1$c.UnsupportedError('not a video Producer');
4231 }
4232 else if (typeof spatialLayer !== 'number') {
4233 throw new TypeError('invalid spatialLayer');
4234 }
4235 if (spatialLayer === this._maxSpatialLayer) {
4236 return;
4237 }
4238 await new Promise((resolve, reject) => {
4239 this.safeEmit('@setmaxspatiallayer', spatialLayer, resolve, reject);
4240 }).catch(() => { });
4241 this._maxSpatialLayer = spatialLayer;
4242 }
4243 async setRtpEncodingParameters(params) {
4244 if (this._closed) {
4245 throw new errors_1$c.InvalidStateError('closed');
4246 }
4247 else if (typeof params !== 'object') {
4248 throw new TypeError('invalid params');
4249 }
4250 await new Promise((resolve, reject) => {
4251 this.safeEmit('@setrtpencodingparameters', params, resolve, reject);
4252 });
4253 }
4254 onTrackEnded() {
4255 logger$h.debug('track "ended" event');
4256 this.safeEmit('trackended');
4257 // Emit observer event.
4258 this._observer.safeEmit('trackended');
4259 }
4260 handleTrack() {
4261 if (!this._track) {
4262 return;
4263 }
4264 this._track.addEventListener('ended', this.onTrackEnded);
4265 }
4266 destroyTrack() {
4267 if (!this._track) {
4268 return;
4269 }
4270 try {
4271 this._track.removeEventListener('ended', this.onTrackEnded);
4272 // Just stop the track unless the app set stopTracks: false.
4273 if (this._stopTracks) {
4274 this._track.stop();
4275 }
4276 }
4277 catch (error) { }
4278 }
4279 }
4280 Producer$1.Producer = Producer;
4281
4282 var Consumer$1 = {};
4283
4284 Object.defineProperty(Consumer$1, "__esModule", { value: true });
4285 Consumer$1.Consumer = void 0;
4286 const Logger_1$g = Logger$3;
4287 const EnhancedEventEmitter_1$5 = EnhancedEventEmitter$1;
4288 const errors_1$b = errors;
4289 const logger$g = new Logger_1$g.Logger('Consumer');
4290 class Consumer extends EnhancedEventEmitter_1$5.EnhancedEventEmitter {
4291 constructor({ id, localId, producerId, rtpReceiver, track, rtpParameters, appData }) {
4292 super();
4293 // Closed flag.
4294 this._closed = false;
4295 // Observer instance.
4296 this._observer = new EnhancedEventEmitter_1$5.EnhancedEventEmitter();
4297 logger$g.debug('constructor()');
4298 this._id = id;
4299 this._localId = localId;
4300 this._producerId = producerId;
4301 this._rtpReceiver = rtpReceiver;
4302 this._track = track;
4303 this._rtpParameters = rtpParameters;
4304 this._paused = !track.enabled;
4305 this._appData = appData || {};
4306 this.onTrackEnded = this.onTrackEnded.bind(this);
4307 this.handleTrack();
4308 }
4309 /**
4310 * Consumer id.
4311 */
4312 get id() {
4313 return this._id;
4314 }
4315 /**
4316 * Local id.
4317 */
4318 get localId() {
4319 return this._localId;
4320 }
4321 /**
4322 * Associated Producer id.
4323 */
4324 get producerId() {
4325 return this._producerId;
4326 }
4327 /**
4328 * Whether the Consumer is closed.
4329 */
4330 get closed() {
4331 return this._closed;
4332 }
4333 /**
4334 * Media kind.
4335 */
4336 get kind() {
4337 return this._track.kind;
4338 }
4339 /**
4340 * Associated RTCRtpReceiver.
4341 */
4342 get rtpReceiver() {
4343 return this._rtpReceiver;
4344 }
4345 /**
4346 * The associated track.
4347 */
4348 get track() {
4349 return this._track;
4350 }
4351 /**
4352 * RTP parameters.
4353 */
4354 get rtpParameters() {
4355 return this._rtpParameters;
4356 }
4357 /**
4358 * Whether the Consumer is paused.
4359 */
4360 get paused() {
4361 return this._paused;
4362 }
4363 /**
4364 * App custom data.
4365 */
4366 get appData() {
4367 return this._appData;
4368 }
4369 /**
4370 * App custom data setter.
4371 */
4372 set appData(appData) {
4373 this._appData = appData;
4374 }
4375 get observer() {
4376 return this._observer;
4377 }
4378 /**
4379 * Closes the Consumer.
4380 */
4381 close() {
4382 if (this._closed) {
4383 return;
4384 }
4385 logger$g.debug('close()');
4386 this._closed = true;
4387 this.destroyTrack();
4388 this.emit('@close');
4389 // Emit observer event.
4390 this._observer.safeEmit('close');
4391 }
4392 /**
4393 * Transport was closed.
4394 */
4395 transportClosed() {
4396 if (this._closed) {
4397 return;
4398 }
4399 logger$g.debug('transportClosed()');
4400 this._closed = true;
4401 this.destroyTrack();
4402 this.safeEmit('transportclose');
4403 // Emit observer event.
4404 this._observer.safeEmit('close');
4405 }
4406 /**
4407 * Get associated RTCRtpReceiver stats.
4408 */
4409 async getStats() {
4410 if (this._closed) {
4411 throw new errors_1$b.InvalidStateError('closed');
4412 }
4413 return new Promise((resolve, reject) => {
4414 this.safeEmit('@getstats', resolve, reject);
4415 });
4416 }
4417 /**
4418 * Pauses receiving media.
4419 */
4420 pause() {
4421 logger$g.debug('pause()');
4422 if (this._closed) {
4423 logger$g.error('pause() | Consumer closed');
4424 return;
4425 }
4426 if (this._paused) {
4427 logger$g.debug('pause() | Consumer is already paused');
4428 return;
4429 }
4430 this._paused = true;
4431 this._track.enabled = false;
4432 this.emit('@pause');
4433 // Emit observer event.
4434 this._observer.safeEmit('pause');
4435 }
4436 /**
4437 * Resumes receiving media.
4438 */
4439 resume() {
4440 logger$g.debug('resume()');
4441 if (this._closed) {
4442 logger$g.error('resume() | Consumer closed');
4443 return;
4444 }
4445 if (!this._paused) {
4446 logger$g.debug('resume() | Consumer is already resumed');
4447 return;
4448 }
4449 this._paused = false;
4450 this._track.enabled = true;
4451 this.emit('@resume');
4452 // Emit observer event.
4453 this._observer.safeEmit('resume');
4454 }
4455 onTrackEnded() {
4456 logger$g.debug('track "ended" event');
4457 this.safeEmit('trackended');
4458 // Emit observer event.
4459 this._observer.safeEmit('trackended');
4460 }
4461 handleTrack() {
4462 this._track.addEventListener('ended', this.onTrackEnded);
4463 }
4464 destroyTrack() {
4465 try {
4466 this._track.removeEventListener('ended', this.onTrackEnded);
4467 this._track.stop();
4468 }
4469 catch (error) { }
4470 }
4471 }
4472 Consumer$1.Consumer = Consumer;
4473
4474 var DataProducer$1 = {};
4475
4476 Object.defineProperty(DataProducer$1, "__esModule", { value: true });
4477 DataProducer$1.DataProducer = void 0;
4478 const Logger_1$f = Logger$3;
4479 const EnhancedEventEmitter_1$4 = EnhancedEventEmitter$1;
4480 const errors_1$a = errors;
4481 const logger$f = new Logger_1$f.Logger('DataProducer');
4482 class DataProducer extends EnhancedEventEmitter_1$4.EnhancedEventEmitter {
4483 constructor({ id, dataChannel, sctpStreamParameters, appData }) {
4484 super();
4485 // Closed flag.
4486 this._closed = false;
4487 // Observer instance.
4488 this._observer = new EnhancedEventEmitter_1$4.EnhancedEventEmitter();
4489 logger$f.debug('constructor()');
4490 this._id = id;
4491 this._dataChannel = dataChannel;
4492 this._sctpStreamParameters = sctpStreamParameters;
4493 this._appData = appData || {};
4494 this.handleDataChannel();
4495 }
4496 /**
4497 * DataProducer id.
4498 */
4499 get id() {
4500 return this._id;
4501 }
4502 /**
4503 * Whether the DataProducer is closed.
4504 */
4505 get closed() {
4506 return this._closed;
4507 }
4508 /**
4509 * SCTP stream parameters.
4510 */
4511 get sctpStreamParameters() {
4512 return this._sctpStreamParameters;
4513 }
4514 /**
4515 * DataChannel readyState.
4516 */
4517 get readyState() {
4518 return this._dataChannel.readyState;
4519 }
4520 /**
4521 * DataChannel label.
4522 */
4523 get label() {
4524 return this._dataChannel.label;
4525 }
4526 /**
4527 * DataChannel protocol.
4528 */
4529 get protocol() {
4530 return this._dataChannel.protocol;
4531 }
4532 /**
4533 * DataChannel bufferedAmount.
4534 */
4535 get bufferedAmount() {
4536 return this._dataChannel.bufferedAmount;
4537 }
4538 /**
4539 * DataChannel bufferedAmountLowThreshold.
4540 */
4541 get bufferedAmountLowThreshold() {
4542 return this._dataChannel.bufferedAmountLowThreshold;
4543 }
4544 /**
4545 * Set DataChannel bufferedAmountLowThreshold.
4546 */
4547 set bufferedAmountLowThreshold(bufferedAmountLowThreshold) {
4548 this._dataChannel.bufferedAmountLowThreshold = bufferedAmountLowThreshold;
4549 }
4550 /**
4551 * App custom data.
4552 */
4553 get appData() {
4554 return this._appData;
4555 }
4556 /**
4557 * App custom data setter.
4558 */
4559 set appData(appData) {
4560 this._appData = appData;
4561 }
4562 get observer() {
4563 return this._observer;
4564 }
4565 /**
4566 * Closes the DataProducer.
4567 */
4568 close() {
4569 if (this._closed) {
4570 return;
4571 }
4572 logger$f.debug('close()');
4573 this._closed = true;
4574 this._dataChannel.close();
4575 this.emit('@close');
4576 // Emit observer event.
4577 this._observer.safeEmit('close');
4578 }
4579 /**
4580 * Transport was closed.
4581 */
4582 transportClosed() {
4583 if (this._closed) {
4584 return;
4585 }
4586 logger$f.debug('transportClosed()');
4587 this._closed = true;
4588 this._dataChannel.close();
4589 this.safeEmit('transportclose');
4590 // Emit observer event.
4591 this._observer.safeEmit('close');
4592 }
4593 /**
4594 * Send a message.
4595 *
4596 * @param {String|Blob|ArrayBuffer|ArrayBufferView} data.
4597 */
4598 send(data) {
4599 logger$f.debug('send()');
4600 if (this._closed) {
4601 throw new errors_1$a.InvalidStateError('closed');
4602 }
4603 this._dataChannel.send(data);
4604 }
4605 handleDataChannel() {
4606 this._dataChannel.addEventListener('open', () => {
4607 if (this._closed) {
4608 return;
4609 }
4610 logger$f.debug('DataChannel "open" event');
4611 this.safeEmit('open');
4612 });
4613 this._dataChannel.addEventListener('error', (event) => {
4614 if (this._closed) {
4615 return;
4616 }
4617 let { error } = event;
4618 if (!error) {
4619 error = new Error('unknown DataChannel error');
4620 }
4621 if (error.errorDetail === 'sctp-failure') {
4622 logger$f.error('DataChannel SCTP error [sctpCauseCode:%s]: %s', error.sctpCauseCode, error.message);
4623 }
4624 else {
4625 logger$f.error('DataChannel "error" event: %o', error);
4626 }
4627 this.safeEmit('error', error);
4628 });
4629 this._dataChannel.addEventListener('close', () => {
4630 if (this._closed) {
4631 return;
4632 }
4633 logger$f.warn('DataChannel "close" event');
4634 this._closed = true;
4635 this.emit('@close');
4636 this.safeEmit('close');
4637 // Emit observer event.
4638 this._observer.safeEmit('close');
4639 });
4640 this._dataChannel.addEventListener('message', () => {
4641 if (this._closed) {
4642 return;
4643 }
4644 logger$f.warn('DataChannel "message" event in a DataProducer, message discarded');
4645 });
4646 this._dataChannel.addEventListener('bufferedamountlow', () => {
4647 if (this._closed) {
4648 return;
4649 }
4650 this.safeEmit('bufferedamountlow');
4651 });
4652 }
4653 }
4654 DataProducer$1.DataProducer = DataProducer;
4655
4656 var DataConsumer$1 = {};
4657
4658 Object.defineProperty(DataConsumer$1, "__esModule", { value: true });
4659 DataConsumer$1.DataConsumer = void 0;
4660 const Logger_1$e = Logger$3;
4661 const EnhancedEventEmitter_1$3 = EnhancedEventEmitter$1;
4662 const logger$e = new Logger_1$e.Logger('DataConsumer');
4663 class DataConsumer extends EnhancedEventEmitter_1$3.EnhancedEventEmitter {
4664 constructor({ id, dataProducerId, dataChannel, sctpStreamParameters, appData }) {
4665 super();
4666 // Closed flag.
4667 this._closed = false;
4668 // Observer instance.
4669 this._observer = new EnhancedEventEmitter_1$3.EnhancedEventEmitter();
4670 logger$e.debug('constructor()');
4671 this._id = id;
4672 this._dataProducerId = dataProducerId;
4673 this._dataChannel = dataChannel;
4674 this._sctpStreamParameters = sctpStreamParameters;
4675 this._appData = appData || {};
4676 this.handleDataChannel();
4677 }
4678 /**
4679 * DataConsumer id.
4680 */
4681 get id() {
4682 return this._id;
4683 }
4684 /**
4685 * Associated DataProducer id.
4686 */
4687 get dataProducerId() {
4688 return this._dataProducerId;
4689 }
4690 /**
4691 * Whether the DataConsumer is closed.
4692 */
4693 get closed() {
4694 return this._closed;
4695 }
4696 /**
4697 * SCTP stream parameters.
4698 */
4699 get sctpStreamParameters() {
4700 return this._sctpStreamParameters;
4701 }
4702 /**
4703 * DataChannel readyState.
4704 */
4705 get readyState() {
4706 return this._dataChannel.readyState;
4707 }
4708 /**
4709 * DataChannel label.
4710 */
4711 get label() {
4712 return this._dataChannel.label;
4713 }
4714 /**
4715 * DataChannel protocol.
4716 */
4717 get protocol() {
4718 return this._dataChannel.protocol;
4719 }
4720 /**
4721 * DataChannel binaryType.
4722 */
4723 get binaryType() {
4724 return this._dataChannel.binaryType;
4725 }
4726 /**
4727 * Set DataChannel binaryType.
4728 */
4729 set binaryType(binaryType) {
4730 this._dataChannel.binaryType = binaryType;
4731 }
4732 /**
4733 * App custom data.
4734 */
4735 get appData() {
4736 return this._appData;
4737 }
4738 /**
4739 * App custom data setter.
4740 */
4741 set appData(appData) {
4742 this._appData = appData;
4743 }
4744 get observer() {
4745 return this._observer;
4746 }
4747 /**
4748 * Closes the DataConsumer.
4749 */
4750 close() {
4751 if (this._closed) {
4752 return;
4753 }
4754 logger$e.debug('close()');
4755 this._closed = true;
4756 this._dataChannel.close();
4757 this.emit('@close');
4758 // Emit observer event.
4759 this._observer.safeEmit('close');
4760 }
4761 /**
4762 * Transport was closed.
4763 */
4764 transportClosed() {
4765 if (this._closed) {
4766 return;
4767 }
4768 logger$e.debug('transportClosed()');
4769 this._closed = true;
4770 this._dataChannel.close();
4771 this.safeEmit('transportclose');
4772 // Emit observer event.
4773 this._observer.safeEmit('close');
4774 }
4775 handleDataChannel() {
4776 this._dataChannel.addEventListener('open', () => {
4777 if (this._closed) {
4778 return;
4779 }
4780 logger$e.debug('DataChannel "open" event');
4781 this.safeEmit('open');
4782 });
4783 this._dataChannel.addEventListener('error', (event) => {
4784 if (this._closed) {
4785 return;
4786 }
4787 let { error } = event;
4788 if (!error) {
4789 error = new Error('unknown DataChannel error');
4790 }
4791 if (error.errorDetail === 'sctp-failure') {
4792 logger$e.error('DataChannel SCTP error [sctpCauseCode:%s]: %s', error.sctpCauseCode, error.message);
4793 }
4794 else {
4795 logger$e.error('DataChannel "error" event: %o', error);
4796 }
4797 this.safeEmit('error', error);
4798 });
4799 this._dataChannel.addEventListener('close', () => {
4800 if (this._closed) {
4801 return;
4802 }
4803 logger$e.warn('DataChannel "close" event');
4804 this._closed = true;
4805 this.emit('@close');
4806 this.safeEmit('close');
4807 // Emit observer event.
4808 this._observer.safeEmit('close');
4809 });
4810 this._dataChannel.addEventListener('message', (event) => {
4811 if (this._closed) {
4812 return;
4813 }
4814 this.safeEmit('message', event.data);
4815 });
4816 }
4817 }
4818 DataConsumer$1.DataConsumer = DataConsumer;
4819
4820 var __createBinding$g = (commonjsGlobal && commonjsGlobal.__createBinding) || (Object.create ? (function(o, m, k, k2) {
4821 if (k2 === undefined) k2 = k;
4822 var desc = Object.getOwnPropertyDescriptor(m, k);
4823 if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
4824 desc = { enumerable: true, get: function() { return m[k]; } };
4825 }
4826 Object.defineProperty(o, k2, desc);
4827 }) : (function(o, m, k, k2) {
4828 if (k2 === undefined) k2 = k;
4829 o[k2] = m[k];
4830 }));
4831 var __setModuleDefault$g = (commonjsGlobal && commonjsGlobal.__setModuleDefault) || (Object.create ? (function(o, v) {
4832 Object.defineProperty(o, "default", { enumerable: true, value: v });
4833 }) : function(o, v) {
4834 o["default"] = v;
4835 });
4836 var __importStar$g = (commonjsGlobal && commonjsGlobal.__importStar) || function (mod) {
4837 if (mod && mod.__esModule) return mod;
4838 var result = {};
4839 if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding$g(result, mod, k);
4840 __setModuleDefault$g(result, mod);
4841 return result;
4842 };
4843 var __importDefault = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) {
4844 return (mod && mod.__esModule) ? mod : { "default": mod };
4845 };
4846 Object.defineProperty(Transport$1, "__esModule", { value: true });
4847 Transport$1.Transport = void 0;
4848 const awaitqueue_1 = lib$1;
4849 const queue_microtask_1 = __importDefault(queueMicrotask_1);
4850 const Logger_1$d = Logger$3;
4851 const EnhancedEventEmitter_1$2 = EnhancedEventEmitter$1;
4852 const errors_1$9 = errors;
4853 const utils$f = __importStar$g(utils$h);
4854 const ortc$c = __importStar$g(ortc$d);
4855 const Producer_1 = Producer$1;
4856 const Consumer_1 = Consumer$1;
4857 const DataProducer_1 = DataProducer$1;
4858 const DataConsumer_1 = DataConsumer$1;
4859 const logger$d = new Logger_1$d.Logger('Transport');
4860 class ConsumerCreationTask {
4861 constructor(consumerOptions) {
4862 this.consumerOptions = consumerOptions;
4863 this.promise = new Promise((resolve, reject) => {
4864 this.resolve = resolve;
4865 this.reject = reject;
4866 });
4867 }
4868 }
4869 class Transport extends EnhancedEventEmitter_1$2.EnhancedEventEmitter {
4870 constructor({ direction, id, iceParameters, iceCandidates, dtlsParameters, sctpParameters, iceServers, iceTransportPolicy, additionalSettings, proprietaryConstraints, appData, handlerFactory, extendedRtpCapabilities, canProduceByKind }) {
4871 super();
4872 // Closed flag.
4873 this._closed = false;
4874 // Transport ICE gathering state.
4875 this._iceGatheringState = 'new';
4876 // Transport connection state.
4877 this._connectionState = 'new';
4878 // Map of Producers indexed by id.
4879 this._producers = new Map();
4880 // Map of Consumers indexed by id.
4881 this._consumers = new Map();
4882 // Map of DataProducers indexed by id.
4883 this._dataProducers = new Map();
4884 // Map of DataConsumers indexed by id.
4885 this._dataConsumers = new Map();
4886 // Whether the Consumer for RTP probation has been created.
4887 this._probatorConsumerCreated = false;
4888 // AwaitQueue instance to make async tasks happen sequentially.
4889 this._awaitQueue = new awaitqueue_1.AwaitQueue();
4890 // Consumer creation tasks awaiting to be processed.
4891 this._pendingConsumerTasks = [];
4892 // Consumer creation in progress flag.
4893 this._consumerCreationInProgress = false;
4894 // Consumers pending to be paused.
4895 this._pendingPauseConsumers = new Map();
4896 // Consumer pause in progress flag.
4897 this._consumerPauseInProgress = false;
4898 // Consumers pending to be resumed.
4899 this._pendingResumeConsumers = new Map();
4900 // Consumer resume in progress flag.
4901 this._consumerResumeInProgress = false;
4902 // Consumers pending to be closed.
4903 this._pendingCloseConsumers = new Map();
4904 // Consumer close in progress flag.
4905 this._consumerCloseInProgress = false;
4906 // Observer instance.
4907 this._observer = new EnhancedEventEmitter_1$2.EnhancedEventEmitter();
4908 logger$d.debug('constructor() [id:%s, direction:%s]', id, direction);
4909 this._id = id;
4910 this._direction = direction;
4911 this._extendedRtpCapabilities = extendedRtpCapabilities;
4912 this._canProduceByKind = canProduceByKind;
4913 this._maxSctpMessageSize =
4914 sctpParameters ? sctpParameters.maxMessageSize : null;
4915 // Clone and sanitize additionalSettings.
4916 additionalSettings = utils$f.clone(additionalSettings) || {};
4917 delete additionalSettings.iceServers;
4918 delete additionalSettings.iceTransportPolicy;
4919 delete additionalSettings.bundlePolicy;
4920 delete additionalSettings.rtcpMuxPolicy;
4921 delete additionalSettings.sdpSemantics;
4922 this._handler = handlerFactory();
4923 this._handler.run({
4924 direction,
4925 iceParameters,
4926 iceCandidates,
4927 dtlsParameters,
4928 sctpParameters,
4929 iceServers,
4930 iceTransportPolicy,
4931 additionalSettings,
4932 proprietaryConstraints,
4933 extendedRtpCapabilities
4934 });
4935 this._appData = appData || {};
4936 this.handleHandler();
4937 }
4938 /**
4939 * Transport id.
4940 */
4941 get id() {
4942 return this._id;
4943 }
4944 /**
4945 * Whether the Transport is closed.
4946 */
4947 get closed() {
4948 return this._closed;
4949 }
4950 /**
4951 * Transport direction.
4952 */
4953 get direction() {
4954 return this._direction;
4955 }
4956 /**
4957 * RTC handler instance.
4958 */
4959 get handler() {
4960 return this._handler;
4961 }
4962 /**
4963 * ICE gathering state.
4964 */
4965 get iceGatheringState() {
4966 return this._iceGatheringState;
4967 }
4968 /**
4969 * Connection state.
4970 */
4971 get connectionState() {
4972 return this._connectionState;
4973 }
4974 /**
4975 * App custom data.
4976 */
4977 get appData() {
4978 return this._appData;
4979 }
4980 /**
4981 * App custom data setter.
4982 */
4983 set appData(appData) {
4984 this._appData = appData;
4985 }
4986 get observer() {
4987 return this._observer;
4988 }
4989 /**
4990 * Close the Transport.
4991 */
4992 close() {
4993 if (this._closed) {
4994 return;
4995 }
4996 logger$d.debug('close()');
4997 this._closed = true;
4998 // Stop the AwaitQueue.
4999 this._awaitQueue.stop();
5000 // Close the handler.
5001 this._handler.close();
5002 // Change connection state to 'closed' since the handler may not emit
5003 // '@connectionstatechange' event.
5004 this._connectionState = 'closed';
5005 // Close all Producers.
5006 for (const producer of this._producers.values()) {
5007 producer.transportClosed();
5008 }
5009 this._producers.clear();
5010 // Close all Consumers.
5011 for (const consumer of this._consumers.values()) {
5012 consumer.transportClosed();
5013 }
5014 this._consumers.clear();
5015 // Close all DataProducers.
5016 for (const dataProducer of this._dataProducers.values()) {
5017 dataProducer.transportClosed();
5018 }
5019 this._dataProducers.clear();
5020 // Close all DataConsumers.
5021 for (const dataConsumer of this._dataConsumers.values()) {
5022 dataConsumer.transportClosed();
5023 }
5024 this._dataConsumers.clear();
5025 // Emit observer event.
5026 this._observer.safeEmit('close');
5027 }
5028 /**
5029 * Get associated Transport (RTCPeerConnection) stats.
5030 *
5031 * @returns {RTCStatsReport}
5032 */
5033 async getStats() {
5034 if (this._closed) {
5035 throw new errors_1$9.InvalidStateError('closed');
5036 }
5037 return this._handler.getTransportStats();
5038 }
5039 /**
5040 * Restart ICE connection.
5041 */
5042 async restartIce({ iceParameters }) {
5043 logger$d.debug('restartIce()');
5044 if (this._closed) {
5045 throw new errors_1$9.InvalidStateError('closed');
5046 }
5047 else if (!iceParameters) {
5048 throw new TypeError('missing iceParameters');
5049 }
5050 // Enqueue command.
5051 return this._awaitQueue.push(async () => await this._handler.restartIce(iceParameters), 'transport.restartIce()');
5052 }
5053 /**
5054 * Update ICE servers.
5055 */
5056 async updateIceServers({ iceServers } = {}) {
5057 logger$d.debug('updateIceServers()');
5058 if (this._closed) {
5059 throw new errors_1$9.InvalidStateError('closed');
5060 }
5061 else if (!Array.isArray(iceServers)) {
5062 throw new TypeError('missing iceServers');
5063 }
5064 // Enqueue command.
5065 return this._awaitQueue.push(async () => this._handler.updateIceServers(iceServers), 'transport.updateIceServers()');
5066 }
5067 /**
5068 * Create a Producer.
5069 */
5070 async produce({ track, encodings, codecOptions, codec, stopTracks = true, disableTrackOnPause = true, zeroRtpOnPause = false, appData = {} } = {}) {
5071 logger$d.debug('produce() [track:%o]', track);
5072 if (this._closed) {
5073 throw new errors_1$9.InvalidStateError('closed');
5074 }
5075 else if (!track) {
5076 throw new TypeError('missing track');
5077 }
5078 else if (this._direction !== 'send') {
5079 throw new errors_1$9.UnsupportedError('not a sending Transport');
5080 }
5081 else if (!this._canProduceByKind[track.kind]) {
5082 throw new errors_1$9.UnsupportedError(`cannot produce ${track.kind}`);
5083 }
5084 else if (track.readyState === 'ended') {
5085 throw new errors_1$9.InvalidStateError('track ended');
5086 }
5087 else if (this.listenerCount('connect') === 0 && this._connectionState === 'new') {
5088 throw new TypeError('no "connect" listener set into this transport');
5089 }
5090 else if (this.listenerCount('produce') === 0) {
5091 throw new TypeError('no "produce" listener set into this transport');
5092 }
5093 else if (appData && typeof appData !== 'object') {
5094 throw new TypeError('if given, appData must be an object');
5095 }
5096 // Enqueue command.
5097 return this._awaitQueue.push(async () => {
5098 let normalizedEncodings;
5099 if (encodings && !Array.isArray(encodings)) {
5100 throw TypeError('encodings must be an array');
5101 }
5102 else if (encodings && encodings.length === 0) {
5103 normalizedEncodings = undefined;
5104 }
5105 else if (encodings) {
5106 normalizedEncodings = encodings
5107 .map((encoding) => {
5108 const normalizedEncoding = { active: true };
5109 if (encoding.active === false) {
5110 normalizedEncoding.active = false;
5111 }
5112 if (typeof encoding.dtx === 'boolean') {
5113 normalizedEncoding.dtx = encoding.dtx;
5114 }
5115 if (typeof encoding.scalabilityMode === 'string') {
5116 normalizedEncoding.scalabilityMode = encoding.scalabilityMode;
5117 }
5118 if (typeof encoding.scaleResolutionDownBy === 'number') {
5119 normalizedEncoding.scaleResolutionDownBy = encoding.scaleResolutionDownBy;
5120 }
5121 if (typeof encoding.maxBitrate === 'number') {
5122 normalizedEncoding.maxBitrate = encoding.maxBitrate;
5123 }
5124 if (typeof encoding.maxFramerate === 'number') {
5125 normalizedEncoding.maxFramerate = encoding.maxFramerate;
5126 }
5127 if (typeof encoding.adaptivePtime === 'boolean') {
5128 normalizedEncoding.adaptivePtime = encoding.adaptivePtime;
5129 }
5130 if (typeof encoding.priority === 'string') {
5131 normalizedEncoding.priority = encoding.priority;
5132 }
5133 if (typeof encoding.networkPriority === 'string') {
5134 normalizedEncoding.networkPriority = encoding.networkPriority;
5135 }
5136 return normalizedEncoding;
5137 });
5138 }
5139 const { localId, rtpParameters, rtpSender } = await this._handler.send({
5140 track,
5141 encodings: normalizedEncodings,
5142 codecOptions,
5143 codec
5144 });
5145 try {
5146 // This will fill rtpParameters's missing fields with default values.
5147 ortc$c.validateRtpParameters(rtpParameters);
5148 const { id } = await new Promise((resolve, reject) => {
5149 this.safeEmit('produce', {
5150 kind: track.kind,
5151 rtpParameters,
5152 appData
5153 }, resolve, reject);
5154 });
5155 const producer = new Producer_1.Producer({
5156 id,
5157 localId,
5158 rtpSender,
5159 track,
5160 rtpParameters,
5161 stopTracks,
5162 disableTrackOnPause,
5163 zeroRtpOnPause,
5164 appData
5165 });
5166 this._producers.set(producer.id, producer);
5167 this.handleProducer(producer);
5168 // Emit observer event.
5169 this._observer.safeEmit('newproducer', producer);
5170 return producer;
5171 }
5172 catch (error) {
5173 this._handler.stopSending(localId)
5174 .catch(() => { });
5175 throw error;
5176 }
5177 }, 'transport.produce()')
5178 // This catch is needed to stop the given track if the command above
5179 // failed due to closed Transport.
5180 .catch((error) => {
5181 if (stopTracks) {
5182 try {
5183 track.stop();
5184 }
5185 catch (error2) { }
5186 }
5187 throw error;
5188 });
5189 }
5190 /**
5191 * Create a Consumer to consume a remote Producer.
5192 */
5193 async consume({ id, producerId, kind, rtpParameters, streamId, appData = {} }) {
5194 logger$d.debug('consume()');
5195 rtpParameters = utils$f.clone(rtpParameters);
5196 if (this._closed) {
5197 throw new errors_1$9.InvalidStateError('closed');
5198 }
5199 else if (this._direction !== 'recv') {
5200 throw new errors_1$9.UnsupportedError('not a receiving Transport');
5201 }
5202 else if (typeof id !== 'string') {
5203 throw new TypeError('missing id');
5204 }
5205 else if (typeof producerId !== 'string') {
5206 throw new TypeError('missing producerId');
5207 }
5208 else if (kind !== 'audio' && kind !== 'video') {
5209 throw new TypeError(`invalid kind '${kind}'`);
5210 }
5211 else if (this.listenerCount('connect') === 0 && this._connectionState === 'new') {
5212 throw new TypeError('no "connect" listener set into this transport');
5213 }
5214 else if (appData && typeof appData !== 'object') {
5215 throw new TypeError('if given, appData must be an object');
5216 }
5217 // Ensure the device can consume it.
5218 const canConsume = ortc$c.canReceive(rtpParameters, this._extendedRtpCapabilities);
5219 if (!canConsume) {
5220 throw new errors_1$9.UnsupportedError('cannot consume this Producer');
5221 }
5222 const consumerCreationTask = new ConsumerCreationTask({
5223 id,
5224 producerId,
5225 kind,
5226 rtpParameters,
5227 streamId,
5228 appData
5229 });
5230 // Store the Consumer creation task.
5231 this._pendingConsumerTasks.push(consumerCreationTask);
5232 // There is no Consumer creation in progress, create it now.
5233 (0, queue_microtask_1.default)(() => {
5234 if (this._closed) {
5235 return;
5236 }
5237 if (this._consumerCreationInProgress === false) {
5238 this.createPendingConsumers();
5239 }
5240 });
5241 return consumerCreationTask.promise;
5242 }
5243 /**
5244 * Create a DataProducer
5245 */
5246 async produceData({ ordered = true, maxPacketLifeTime, maxRetransmits, label = '', protocol = '', appData = {} } = {}) {
5247 logger$d.debug('produceData()');
5248 if (this._closed) {
5249 throw new errors_1$9.InvalidStateError('closed');
5250 }
5251 else if (this._direction !== 'send') {
5252 throw new errors_1$9.UnsupportedError('not a sending Transport');
5253 }
5254 else if (!this._maxSctpMessageSize) {
5255 throw new errors_1$9.UnsupportedError('SCTP not enabled by remote Transport');
5256 }
5257 else if (this.listenerCount('connect') === 0 && this._connectionState === 'new') {
5258 throw new TypeError('no "connect" listener set into this transport');
5259 }
5260 else if (this.listenerCount('producedata') === 0) {
5261 throw new TypeError('no "producedata" listener set into this transport');
5262 }
5263 else if (appData && typeof appData !== 'object') {
5264 throw new TypeError('if given, appData must be an object');
5265 }
5266 if (maxPacketLifeTime || maxRetransmits) {
5267 ordered = false;
5268 }
5269 // Enqueue command.
5270 return this._awaitQueue.push(async () => {
5271 const { dataChannel, sctpStreamParameters } = await this._handler.sendDataChannel({
5272 ordered,
5273 maxPacketLifeTime,
5274 maxRetransmits,
5275 label,
5276 protocol
5277 });
5278 // This will fill sctpStreamParameters's missing fields with default values.
5279 ortc$c.validateSctpStreamParameters(sctpStreamParameters);
5280 const { id } = await new Promise((resolve, reject) => {
5281 this.safeEmit('producedata', {
5282 sctpStreamParameters,
5283 label,
5284 protocol,
5285 appData
5286 }, resolve, reject);
5287 });
5288 const dataProducer = new DataProducer_1.DataProducer({
5289 id,
5290 dataChannel,
5291 sctpStreamParameters,
5292 appData
5293 });
5294 this._dataProducers.set(dataProducer.id, dataProducer);
5295 this.handleDataProducer(dataProducer);
5296 // Emit observer event.
5297 this._observer.safeEmit('newdataproducer', dataProducer);
5298 return dataProducer;
5299 }, 'transport.produceData()');
5300 }
5301 /**
5302 * Create a DataConsumer
5303 */
5304 async consumeData({ id, dataProducerId, sctpStreamParameters, label = '', protocol = '', appData = {} }) {
5305 logger$d.debug('consumeData()');
5306 sctpStreamParameters = utils$f.clone(sctpStreamParameters);
5307 if (this._closed) {
5308 throw new errors_1$9.InvalidStateError('closed');
5309 }
5310 else if (this._direction !== 'recv') {
5311 throw new errors_1$9.UnsupportedError('not a receiving Transport');
5312 }
5313 else if (!this._maxSctpMessageSize) {
5314 throw new errors_1$9.UnsupportedError('SCTP not enabled by remote Transport');
5315 }
5316 else if (typeof id !== 'string') {
5317 throw new TypeError('missing id');
5318 }
5319 else if (typeof dataProducerId !== 'string') {
5320 throw new TypeError('missing dataProducerId');
5321 }
5322 else if (this.listenerCount('connect') === 0 && this._connectionState === 'new') {
5323 throw new TypeError('no "connect" listener set into this transport');
5324 }
5325 else if (appData && typeof appData !== 'object') {
5326 throw new TypeError('if given, appData must be an object');
5327 }
5328 // This may throw.
5329 ortc$c.validateSctpStreamParameters(sctpStreamParameters);
5330 // Enqueue command.
5331 return this._awaitQueue.push(async () => {
5332 const { dataChannel } = await this._handler.receiveDataChannel({
5333 sctpStreamParameters,
5334 label,
5335 protocol
5336 });
5337 const dataConsumer = new DataConsumer_1.DataConsumer({
5338 id,
5339 dataProducerId,
5340 dataChannel,
5341 sctpStreamParameters,
5342 appData
5343 });
5344 this._dataConsumers.set(dataConsumer.id, dataConsumer);
5345 this.handleDataConsumer(dataConsumer);
5346 // Emit observer event.
5347 this._observer.safeEmit('newdataconsumer', dataConsumer);
5348 return dataConsumer;
5349 }, 'transport.consumeData()');
5350 }
5351 // This method is guaranteed to never throw.
5352 async createPendingConsumers() {
5353 this._consumerCreationInProgress = true;
5354 this._awaitQueue.push(async () => {
5355 if (this._pendingConsumerTasks.length === 0) {
5356 logger$d.debug('createPendingConsumers() | there is no Consumer to be created');
5357 return;
5358 }
5359 const pendingConsumerTasks = [...this._pendingConsumerTasks];
5360 // Clear pending Consumer tasks.
5361 this._pendingConsumerTasks = [];
5362 // Video Consumer in order to create the probator.
5363 let videoConsumerForProbator = undefined;
5364 // Fill options list.
5365 const optionsList = [];
5366 for (const task of pendingConsumerTasks) {
5367 const { id, kind, rtpParameters, streamId } = task.consumerOptions;
5368 optionsList.push({
5369 trackId: id,
5370 kind: kind,
5371 rtpParameters,
5372 streamId
5373 });
5374 }
5375 try {
5376 const results = await this._handler.receive(optionsList);
5377 for (let idx = 0; idx < results.length; ++idx) {
5378 const task = pendingConsumerTasks[idx];
5379 const result = results[idx];
5380 const { id, producerId, kind, rtpParameters, appData } = task.consumerOptions;
5381 const { localId, rtpReceiver, track } = result;
5382 const consumer = new Consumer_1.Consumer({
5383 id: id,
5384 localId,
5385 producerId: producerId,
5386 rtpReceiver,
5387 track,
5388 rtpParameters,
5389 appData: appData
5390 });
5391 this._consumers.set(consumer.id, consumer);
5392 this.handleConsumer(consumer);
5393 // If this is the first video Consumer and the Consumer for RTP probation
5394 // has not yet been created, it's time to create it.
5395 if (!this._probatorConsumerCreated &&
5396 !videoConsumerForProbator && kind === 'video') {
5397 videoConsumerForProbator = consumer;
5398 }
5399 // Emit observer event.
5400 this._observer.safeEmit('newconsumer', consumer);
5401 task.resolve(consumer);
5402 }
5403 }
5404 catch (error) {
5405 for (const task of pendingConsumerTasks) {
5406 task.reject(error);
5407 }
5408 }
5409 // If RTP probation must be handled, do it now.
5410 if (videoConsumerForProbator) {
5411 try {
5412 const probatorRtpParameters = ortc$c.generateProbatorRtpParameters(videoConsumerForProbator.rtpParameters);
5413 await this._handler.receive([{
5414 trackId: 'probator',
5415 kind: 'video',
5416 rtpParameters: probatorRtpParameters
5417 }]);
5418 logger$d.debug('createPendingConsumers() | Consumer for RTP probation created');
5419 this._probatorConsumerCreated = true;
5420 }
5421 catch (error) {
5422 logger$d.error('createPendingConsumers() | failed to create Consumer for RTP probation:%o', error);
5423 }
5424 }
5425 }, 'transport.createPendingConsumers()')
5426 .then(() => {
5427 this._consumerCreationInProgress = false;
5428 // There are pending Consumer tasks, enqueue their creation.
5429 if (this._pendingConsumerTasks.length > 0) {
5430 this.createPendingConsumers();
5431 }
5432 })
5433 // NOTE: We only get here when the await queue is closed.
5434 .catch(() => { });
5435 }
5436 pausePendingConsumers() {
5437 this._consumerPauseInProgress = true;
5438 this._awaitQueue.push(async () => {
5439 if (this._pendingPauseConsumers.size === 0) {
5440 logger$d.debug('pausePendingConsumers() | there is no Consumer to be paused');
5441 return;
5442 }
5443 const pendingPauseConsumers = Array.from(this._pendingPauseConsumers.values());
5444 // Clear pending pause Consumer map.
5445 this._pendingPauseConsumers.clear();
5446 try {
5447 const localIds = pendingPauseConsumers
5448 .map((consumer) => consumer.localId);
5449 await this._handler.pauseReceiving(localIds);
5450 }
5451 catch (error) {
5452 logger$d.error('pausePendingConsumers() | failed to pause Consumers:', error);
5453 }
5454 }, 'transport.pausePendingConsumers')
5455 .then(() => {
5456 this._consumerPauseInProgress = false;
5457 // There are pending Consumers to be paused, do it.
5458 if (this._pendingPauseConsumers.size > 0) {
5459 this.pausePendingConsumers();
5460 }
5461 })
5462 // NOTE: We only get here when the await queue is closed.
5463 .catch(() => { });
5464 }
5465 resumePendingConsumers() {
5466 this._consumerResumeInProgress = true;
5467 this._awaitQueue.push(async () => {
5468 if (this._pendingResumeConsumers.size === 0) {
5469 logger$d.debug('resumePendingConsumers() | there is no Consumer to be resumed');
5470 return;
5471 }
5472 const pendingResumeConsumers = Array.from(this._pendingResumeConsumers.values());
5473 // Clear pending resume Consumer map.
5474 this._pendingResumeConsumers.clear();
5475 try {
5476 const localIds = pendingResumeConsumers
5477 .map((consumer) => consumer.localId);
5478 await this._handler.resumeReceiving(localIds);
5479 }
5480 catch (error) {
5481 logger$d.error('resumePendingConsumers() | failed to resume Consumers:', error);
5482 }
5483 }, 'transport.resumePendingConsumers')
5484 .then(() => {
5485 this._consumerResumeInProgress = false;
5486 // There are pending Consumer to be resumed, do it.
5487 if (this._pendingResumeConsumers.size > 0) {
5488 this.resumePendingConsumers();
5489 }
5490 })
5491 // NOTE: We only get here when the await queue is closed.
5492 .catch(() => { });
5493 }
5494 closePendingConsumers() {
5495 this._consumerCloseInProgress = true;
5496 this._awaitQueue.push(async () => {
5497 if (this._pendingCloseConsumers.size === 0) {
5498 logger$d.debug('closePendingConsumers() | there is no Consumer to be closed');
5499 return;
5500 }
5501 const pendingCloseConsumers = Array.from(this._pendingCloseConsumers.values());
5502 // Clear pending close Consumer map.
5503 this._pendingCloseConsumers.clear();
5504 try {
5505 await this._handler.stopReceiving(pendingCloseConsumers.map((consumer) => consumer.localId));
5506 }
5507 catch (error) {
5508 logger$d.error('closePendingConsumers() | failed to close Consumers:', error);
5509 }
5510 }, 'transport.closePendingConsumers')
5511 .then(() => {
5512 this._consumerCloseInProgress = false;
5513 // There are pending Consumer to be resumed, do it.
5514 if (this._pendingCloseConsumers.size > 0) {
5515 this.closePendingConsumers();
5516 }
5517 })
5518 // NOTE: We only get here when the await queue is closed.
5519 .catch(() => { });
5520 }
5521 handleHandler() {
5522 const handler = this._handler;
5523 handler.on('@connect', ({ dtlsParameters }, callback, errback) => {
5524 if (this._closed) {
5525 errback(new errors_1$9.InvalidStateError('closed'));
5526 return;
5527 }
5528 this.safeEmit('connect', { dtlsParameters }, callback, errback);
5529 });
5530 handler.on('@icegatheringstatechange', (iceGatheringState) => {
5531 if (iceGatheringState === this._iceGatheringState) {
5532 return;
5533 }
5534 logger$d.debug('ICE gathering state changed to %s', iceGatheringState);
5535 this._iceGatheringState = iceGatheringState;
5536 if (!this._closed) {
5537 this.safeEmit('icegatheringstatechange', iceGatheringState);
5538 }
5539 });
5540 handler.on('@connectionstatechange', (connectionState) => {
5541 if (connectionState === this._connectionState) {
5542 return;
5543 }
5544 logger$d.debug('connection state changed to %s', connectionState);
5545 this._connectionState = connectionState;
5546 if (!this._closed) {
5547 this.safeEmit('connectionstatechange', connectionState);
5548 }
5549 });
5550 }
5551 handleProducer(producer) {
5552 producer.on('@close', () => {
5553 this._producers.delete(producer.id);
5554 if (this._closed) {
5555 return;
5556 }
5557 this._awaitQueue.push(async () => await this._handler.stopSending(producer.localId), 'producer @close event')
5558 .catch((error) => logger$d.warn('producer.close() failed:%o', error));
5559 });
5560 producer.on('@pause', (callback, errback) => {
5561 this._awaitQueue.push(async () => await this._handler.pauseSending(producer.localId), 'producer @pause event')
5562 .then(callback)
5563 .catch(errback);
5564 });
5565 producer.on('@resume', (callback, errback) => {
5566 this._awaitQueue.push(async () => await this._handler.resumeSending(producer.localId), 'producer @resume event')
5567 .then(callback)
5568 .catch(errback);
5569 });
5570 producer.on('@replacetrack', (track, callback, errback) => {
5571 this._awaitQueue.push(async () => await this._handler.replaceTrack(producer.localId, track), 'producer @replacetrack event')
5572 .then(callback)
5573 .catch(errback);
5574 });
5575 producer.on('@setmaxspatiallayer', (spatialLayer, callback, errback) => {
5576 this._awaitQueue.push(async () => (await this._handler.setMaxSpatialLayer(producer.localId, spatialLayer)), 'producer @setmaxspatiallayer event')
5577 .then(callback)
5578 .catch(errback);
5579 });
5580 producer.on('@setrtpencodingparameters', (params, callback, errback) => {
5581 this._awaitQueue.push(async () => (await this._handler.setRtpEncodingParameters(producer.localId, params)), 'producer @setrtpencodingparameters event')
5582 .then(callback)
5583 .catch(errback);
5584 });
5585 producer.on('@getstats', (callback, errback) => {
5586 if (this._closed) {
5587 return errback(new errors_1$9.InvalidStateError('closed'));
5588 }
5589 this._handler.getSenderStats(producer.localId)
5590 .then(callback)
5591 .catch(errback);
5592 });
5593 }
5594 handleConsumer(consumer) {
5595 consumer.on('@close', () => {
5596 this._consumers.delete(consumer.id);
5597 this._pendingPauseConsumers.delete(consumer.id);
5598 this._pendingResumeConsumers.delete(consumer.id);
5599 if (this._closed) {
5600 return;
5601 }
5602 // Store the Consumer into the close list.
5603 this._pendingCloseConsumers.set(consumer.id, consumer);
5604 // There is no Consumer close in progress, do it now.
5605 if (this._consumerCloseInProgress === false) {
5606 this.closePendingConsumers();
5607 }
5608 });
5609 consumer.on('@pause', () => {
5610 // If Consumer is pending to be resumed, remove from pending resume list.
5611 if (this._pendingResumeConsumers.has(consumer.id)) {
5612 this._pendingResumeConsumers.delete(consumer.id);
5613 }
5614 // Store the Consumer into the pending list.
5615 this._pendingPauseConsumers.set(consumer.id, consumer);
5616 // There is no Consumer pause in progress, do it now.
5617 (0, queue_microtask_1.default)(() => {
5618 if (this._closed) {
5619 return;
5620 }
5621 if (this._consumerPauseInProgress === false) {
5622 this.pausePendingConsumers();
5623 }
5624 });
5625 });
5626 consumer.on('@resume', () => {
5627 // If Consumer is pending to be paused, remove from pending pause list.
5628 if (this._pendingPauseConsumers.has(consumer.id)) {
5629 this._pendingPauseConsumers.delete(consumer.id);
5630 }
5631 // Store the Consumer into the pending list.
5632 this._pendingResumeConsumers.set(consumer.id, consumer);
5633 // There is no Consumer resume in progress, do it now.
5634 (0, queue_microtask_1.default)(() => {
5635 if (this._closed) {
5636 return;
5637 }
5638 if (this._consumerResumeInProgress === false) {
5639 this.resumePendingConsumers();
5640 }
5641 });
5642 });
5643 consumer.on('@getstats', (callback, errback) => {
5644 if (this._closed) {
5645 return errback(new errors_1$9.InvalidStateError('closed'));
5646 }
5647 this._handler.getReceiverStats(consumer.localId)
5648 .then(callback)
5649 .catch(errback);
5650 });
5651 }
5652 handleDataProducer(dataProducer) {
5653 dataProducer.on('@close', () => {
5654 this._dataProducers.delete(dataProducer.id);
5655 });
5656 }
5657 handleDataConsumer(dataConsumer) {
5658 dataConsumer.on('@close', () => {
5659 this._dataConsumers.delete(dataConsumer.id);
5660 });
5661 }
5662 }
5663 Transport$1.Transport = Transport;
5664
5665 var Chrome111$1 = {};
5666
5667 var lib = {};
5668
5669 var parser$1 = {};
5670
5671 var grammar$2 = {exports: {}};
5672
5673 var grammar$1 = grammar$2.exports = {
5674 v: [{
5675 name: 'version',
5676 reg: /^(\d*)$/
5677 }],
5678 o: [{
5679 // o=- 20518 0 IN IP4 203.0.113.1
5680 // NB: sessionId will be a String in most cases because it is huge
5681 name: 'origin',
5682 reg: /^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,
5683 names: ['username', 'sessionId', 'sessionVersion', 'netType', 'ipVer', 'address'],
5684 format: '%s %s %d %s IP%d %s'
5685 }],
5686 // default parsing of these only (though some of these feel outdated)
5687 s: [{ name: 'name' }],
5688 i: [{ name: 'description' }],
5689 u: [{ name: 'uri' }],
5690 e: [{ name: 'email' }],
5691 p: [{ name: 'phone' }],
5692 z: [{ name: 'timezones' }], // TODO: this one can actually be parsed properly...
5693 r: [{ name: 'repeats' }], // TODO: this one can also be parsed properly
5694 // k: [{}], // outdated thing ignored
5695 t: [{
5696 // t=0 0
5697 name: 'timing',
5698 reg: /^(\d*) (\d*)/,
5699 names: ['start', 'stop'],
5700 format: '%d %d'
5701 }],
5702 c: [{
5703 // c=IN IP4 10.47.197.26
5704 name: 'connection',
5705 reg: /^IN IP(\d) (\S*)/,
5706 names: ['version', 'ip'],
5707 format: 'IN IP%d %s'
5708 }],
5709 b: [{
5710 // b=AS:4000
5711 push: 'bandwidth',
5712 reg: /^(TIAS|AS|CT|RR|RS):(\d*)/,
5713 names: ['type', 'limit'],
5714 format: '%s:%s'
5715 }],
5716 m: [{
5717 // m=video 51744 RTP/AVP 126 97 98 34 31
5718 // NB: special - pushes to session
5719 // TODO: rtp/fmtp should be filtered by the payloads found here?
5720 reg: /^(\w*) (\d*) ([\w/]*)(?: (.*))?/,
5721 names: ['type', 'port', 'protocol', 'payloads'],
5722 format: '%s %d %s %s'
5723 }],
5724 a: [
5725 {
5726 // a=rtpmap:110 opus/48000/2
5727 push: 'rtp',
5728 reg: /^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,
5729 names: ['payload', 'codec', 'rate', 'encoding'],
5730 format: function (o) {
5731 return (o.encoding)
5732 ? 'rtpmap:%d %s/%s/%s'
5733 : o.rate
5734 ? 'rtpmap:%d %s/%s'
5735 : 'rtpmap:%d %s';
5736 }
5737 },
5738 {
5739 // a=fmtp:108 profile-level-id=24;object=23;bitrate=64000
5740 // a=fmtp:111 minptime=10; useinbandfec=1
5741 push: 'fmtp',
5742 reg: /^fmtp:(\d*) ([\S| ]*)/,
5743 names: ['payload', 'config'],
5744 format: 'fmtp:%d %s'
5745 },
5746 {
5747 // a=control:streamid=0
5748 name: 'control',
5749 reg: /^control:(.*)/,
5750 format: 'control:%s'
5751 },
5752 {
5753 // a=rtcp:65179 IN IP4 193.84.77.194
5754 name: 'rtcp',
5755 reg: /^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,
5756 names: ['port', 'netType', 'ipVer', 'address'],
5757 format: function (o) {
5758 return (o.address != null)
5759 ? 'rtcp:%d %s IP%d %s'
5760 : 'rtcp:%d';
5761 }
5762 },
5763 {
5764 // a=rtcp-fb:98 trr-int 100
5765 push: 'rtcpFbTrrInt',
5766 reg: /^rtcp-fb:(\*|\d*) trr-int (\d*)/,
5767 names: ['payload', 'value'],
5768 format: 'rtcp-fb:%s trr-int %d'
5769 },
5770 {
5771 // a=rtcp-fb:98 nack rpsi
5772 push: 'rtcpFb',
5773 reg: /^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,
5774 names: ['payload', 'type', 'subtype'],
5775 format: function (o) {
5776 return (o.subtype != null)
5777 ? 'rtcp-fb:%s %s %s'
5778 : 'rtcp-fb:%s %s';
5779 }
5780 },
5781 {
5782 // a=extmap:2 urn:ietf:params:rtp-hdrext:toffset
5783 // a=extmap:1/recvonly URI-gps-string
5784 // a=extmap:3 urn:ietf:params:rtp-hdrext:encrypt urn:ietf:params:rtp-hdrext:smpte-tc 25@600/24
5785 push: 'ext',
5786 reg: /^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,
5787 names: ['value', 'direction', 'encrypt-uri', 'uri', 'config'],
5788 format: function (o) {
5789 return (
5790 'extmap:%d' +
5791 (o.direction ? '/%s' : '%v') +
5792 (o['encrypt-uri'] ? ' %s' : '%v') +
5793 ' %s' +
5794 (o.config ? ' %s' : '')
5795 );
5796 }
5797 },
5798 {
5799 // a=extmap-allow-mixed
5800 name: 'extmapAllowMixed',
5801 reg: /^(extmap-allow-mixed)/
5802 },
5803 {
5804 // a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:PS1uQCVeeCFCanVmcjkpPywjNWhcYD0mXXtxaVBR|2^20|1:32
5805 push: 'crypto',
5806 reg: /^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,
5807 names: ['id', 'suite', 'config', 'sessionConfig'],
5808 format: function (o) {
5809 return (o.sessionConfig != null)
5810 ? 'crypto:%d %s %s %s'
5811 : 'crypto:%d %s %s';
5812 }
5813 },
5814 {
5815 // a=setup:actpass
5816 name: 'setup',
5817 reg: /^setup:(\w*)/,
5818 format: 'setup:%s'
5819 },
5820 {
5821 // a=connection:new
5822 name: 'connectionType',
5823 reg: /^connection:(new|existing)/,
5824 format: 'connection:%s'
5825 },
5826 {
5827 // a=mid:1
5828 name: 'mid',
5829 reg: /^mid:([^\s]*)/,
5830 format: 'mid:%s'
5831 },
5832 {
5833 // a=msid:0c8b064d-d807-43b4-b434-f92a889d8587 98178685-d409-46e0-8e16-7ef0db0db64a
5834 name: 'msid',
5835 reg: /^msid:(.*)/,
5836 format: 'msid:%s'
5837 },
5838 {
5839 // a=ptime:20
5840 name: 'ptime',
5841 reg: /^ptime:(\d*(?:\.\d*)*)/,
5842 format: 'ptime:%d'
5843 },
5844 {
5845 // a=maxptime:60
5846 name: 'maxptime',
5847 reg: /^maxptime:(\d*(?:\.\d*)*)/,
5848 format: 'maxptime:%d'
5849 },
5850 {
5851 // a=sendrecv
5852 name: 'direction',
5853 reg: /^(sendrecv|recvonly|sendonly|inactive)/
5854 },
5855 {
5856 // a=ice-lite
5857 name: 'icelite',
5858 reg: /^(ice-lite)/
5859 },
5860 {
5861 // a=ice-ufrag:F7gI
5862 name: 'iceUfrag',
5863 reg: /^ice-ufrag:(\S*)/,
5864 format: 'ice-ufrag:%s'
5865 },
5866 {
5867 // a=ice-pwd:x9cml/YzichV2+XlhiMu8g
5868 name: 'icePwd',
5869 reg: /^ice-pwd:(\S*)/,
5870 format: 'ice-pwd:%s'
5871 },
5872 {
5873 // a=fingerprint:SHA-1 00:11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33
5874 name: 'fingerprint',
5875 reg: /^fingerprint:(\S*) (\S*)/,
5876 names: ['type', 'hash'],
5877 format: 'fingerprint:%s %s'
5878 },
5879 {
5880 // a=candidate:0 1 UDP 2113667327 203.0.113.1 54400 typ host
5881 // a=candidate:1162875081 1 udp 2113937151 192.168.34.75 60017 typ host generation 0 network-id 3 network-cost 10
5882 // a=candidate:3289912957 2 udp 1845501695 193.84.77.194 60017 typ srflx raddr 192.168.34.75 rport 60017 generation 0 network-id 3 network-cost 10
5883 // a=candidate:229815620 1 tcp 1518280447 192.168.150.19 60017 typ host tcptype active generation 0 network-id 3 network-cost 10
5884 // a=candidate:3289912957 2 tcp 1845501695 193.84.77.194 60017 typ srflx raddr 192.168.34.75 rport 60017 tcptype passive generation 0 network-id 3 network-cost 10
5885 push:'candidates',
5886 reg: /^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,
5887 names: ['foundation', 'component', 'transport', 'priority', 'ip', 'port', 'type', 'raddr', 'rport', 'tcptype', 'generation', 'network-id', 'network-cost'],
5888 format: function (o) {
5889 var str = 'candidate:%s %d %s %d %s %d typ %s';
5890
5891 str += (o.raddr != null) ? ' raddr %s rport %d' : '%v%v';
5892
5893 // NB: candidate has three optional chunks, so %void middles one if it's missing
5894 str += (o.tcptype != null) ? ' tcptype %s' : '%v';
5895
5896 if (o.generation != null) {
5897 str += ' generation %d';
5898 }
5899
5900 str += (o['network-id'] != null) ? ' network-id %d' : '%v';
5901 str += (o['network-cost'] != null) ? ' network-cost %d' : '%v';
5902 return str;
5903 }
5904 },
5905 {
5906 // a=end-of-candidates (keep after the candidates line for readability)
5907 name: 'endOfCandidates',
5908 reg: /^(end-of-candidates)/
5909 },
5910 {
5911 // a=remote-candidates:1 203.0.113.1 54400 2 203.0.113.1 54401 ...
5912 name: 'remoteCandidates',
5913 reg: /^remote-candidates:(.*)/,
5914 format: 'remote-candidates:%s'
5915 },
5916 {
5917 // a=ice-options:google-ice
5918 name: 'iceOptions',
5919 reg: /^ice-options:(\S*)/,
5920 format: 'ice-options:%s'
5921 },
5922 {
5923 // a=ssrc:2566107569 cname:t9YU8M1UxTF8Y1A1
5924 push: 'ssrcs',
5925 reg: /^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,
5926 names: ['id', 'attribute', 'value'],
5927 format: function (o) {
5928 var str = 'ssrc:%d';
5929 if (o.attribute != null) {
5930 str += ' %s';
5931 if (o.value != null) {
5932 str += ':%s';
5933 }
5934 }
5935 return str;
5936 }
5937 },
5938 {
5939 // a=ssrc-group:FEC 1 2
5940 // a=ssrc-group:FEC-FR 3004364195 1080772241
5941 push: 'ssrcGroups',
5942 // token-char = %x21 / %x23-27 / %x2A-2B / %x2D-2E / %x30-39 / %x41-5A / %x5E-7E
5943 reg: /^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,
5944 names: ['semantics', 'ssrcs'],
5945 format: 'ssrc-group:%s %s'
5946 },
5947 {
5948 // a=msid-semantic: WMS Jvlam5X3SX1OP6pn20zWogvaKJz5Hjf9OnlV
5949 name: 'msidSemantic',
5950 reg: /^msid-semantic:\s?(\w*) (\S*)/,
5951 names: ['semantic', 'token'],
5952 format: 'msid-semantic: %s %s' // space after ':' is not accidental
5953 },
5954 {
5955 // a=group:BUNDLE audio video
5956 push: 'groups',
5957 reg: /^group:(\w*) (.*)/,
5958 names: ['type', 'mids'],
5959 format: 'group:%s %s'
5960 },
5961 {
5962 // a=rtcp-mux
5963 name: 'rtcpMux',
5964 reg: /^(rtcp-mux)/
5965 },
5966 {
5967 // a=rtcp-rsize
5968 name: 'rtcpRsize',
5969 reg: /^(rtcp-rsize)/
5970 },
5971 {
5972 // a=sctpmap:5000 webrtc-datachannel 1024
5973 name: 'sctpmap',
5974 reg: /^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,
5975 names: ['sctpmapNumber', 'app', 'maxMessageSize'],
5976 format: function (o) {
5977 return (o.maxMessageSize != null)
5978 ? 'sctpmap:%s %s %s'
5979 : 'sctpmap:%s %s';
5980 }
5981 },
5982 {
5983 // a=x-google-flag:conference
5984 name: 'xGoogleFlag',
5985 reg: /^x-google-flag:([^\s]*)/,
5986 format: 'x-google-flag:%s'
5987 },
5988 {
5989 // a=rid:1 send max-width=1280;max-height=720;max-fps=30;depend=0
5990 push: 'rids',
5991 reg: /^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,
5992 names: ['id', 'direction', 'params'],
5993 format: function (o) {
5994 return (o.params) ? 'rid:%s %s %s' : 'rid:%s %s';
5995 }
5996 },
5997 {
5998 // a=imageattr:97 send [x=800,y=640,sar=1.1,q=0.6] [x=480,y=320] recv [x=330,y=250]
5999 // a=imageattr:* send [x=800,y=640] recv *
6000 // a=imageattr:100 recv [x=320,y=240]
6001 push: 'imageattrs',
6002 reg: new RegExp(
6003 // a=imageattr:97
6004 '^imageattr:(\\d+|\\*)' +
6005 // send [x=800,y=640,sar=1.1,q=0.6] [x=480,y=320]
6006 '[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)' +
6007 // recv [x=330,y=250]
6008 '(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?'
6009 ),
6010 names: ['pt', 'dir1', 'attrs1', 'dir2', 'attrs2'],
6011 format: function (o) {
6012 return 'imageattr:%s %s %s' + (o.dir2 ? ' %s %s' : '');
6013 }
6014 },
6015 {
6016 // a=simulcast:send 1,2,3;~4,~5 recv 6;~7,~8
6017 // a=simulcast:recv 1;4,5 send 6;7
6018 name: 'simulcast',
6019 reg: new RegExp(
6020 // a=simulcast:
6021 '^simulcast:' +
6022 // send 1,2,3;~4,~5
6023 '(send|recv) ([a-zA-Z0-9\\-_~;,]+)' +
6024 // space + recv 6;~7,~8
6025 '(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?' +
6026 // end
6027 '$'
6028 ),
6029 names: ['dir1', 'list1', 'dir2', 'list2'],
6030 format: function (o) {
6031 return 'simulcast:%s %s' + (o.dir2 ? ' %s %s' : '');
6032 }
6033 },
6034 {
6035 // old simulcast draft 03 (implemented by Firefox)
6036 // https://tools.ietf.org/html/draft-ietf-mmusic-sdp-simulcast-03
6037 // a=simulcast: recv pt=97;98 send pt=97
6038 // a=simulcast: send rid=5;6;7 paused=6,7
6039 name: 'simulcast_03',
6040 reg: /^simulcast:[\s\t]+([\S+\s\t]+)$/,
6041 names: ['value'],
6042 format: 'simulcast: %s'
6043 },
6044 {
6045 // a=framerate:25
6046 // a=framerate:29.97
6047 name: 'framerate',
6048 reg: /^framerate:(\d+(?:$|\.\d+))/,
6049 format: 'framerate:%s'
6050 },
6051 {
6052 // RFC4570
6053 // a=source-filter: incl IN IP4 239.5.2.31 10.1.15.5
6054 name: 'sourceFilter',
6055 reg: /^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,
6056 names: ['filterMode', 'netType', 'addressTypes', 'destAddress', 'srcList'],
6057 format: 'source-filter: %s %s %s %s %s'
6058 },
6059 {
6060 // a=bundle-only
6061 name: 'bundleOnly',
6062 reg: /^(bundle-only)/
6063 },
6064 {
6065 // a=label:1
6066 name: 'label',
6067 reg: /^label:(.+)/,
6068 format: 'label:%s'
6069 },
6070 {
6071 // RFC version 26 for SCTP over DTLS
6072 // https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-26#section-5
6073 name: 'sctpPort',
6074 reg: /^sctp-port:(\d+)$/,
6075 format: 'sctp-port:%s'
6076 },
6077 {
6078 // RFC version 26 for SCTP over DTLS
6079 // https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-26#section-6
6080 name: 'maxMessageSize',
6081 reg: /^max-message-size:(\d+)$/,
6082 format: 'max-message-size:%s'
6083 },
6084 {
6085 // RFC7273
6086 // a=ts-refclk:ptp=IEEE1588-2008:39-A7-94-FF-FE-07-CB-D0:37
6087 push:'tsRefClocks',
6088 reg: /^ts-refclk:([^\s=]*)(?:=(\S*))?/,
6089 names: ['clksrc', 'clksrcExt'],
6090 format: function (o) {
6091 return 'ts-refclk:%s' + (o.clksrcExt != null ? '=%s' : '');
6092 }
6093 },
6094 {
6095 // RFC7273
6096 // a=mediaclk:direct=963214424
6097 name:'mediaClk',
6098 reg: /^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,
6099 names: ['id', 'mediaClockName', 'mediaClockValue', 'rateNumerator', 'rateDenominator'],
6100 format: function (o) {
6101 var str = 'mediaclk:';
6102 str += (o.id != null ? 'id=%s %s' : '%v%s');
6103 str += (o.mediaClockValue != null ? '=%s' : '');
6104 str += (o.rateNumerator != null ? ' rate=%s' : '');
6105 str += (o.rateDenominator != null ? '/%s' : '');
6106 return str;
6107 }
6108 },
6109 {
6110 // a=keywds:keywords
6111 name: 'keywords',
6112 reg: /^keywds:(.+)$/,
6113 format: 'keywds:%s'
6114 },
6115 {
6116 // a=content:main
6117 name: 'content',
6118 reg: /^content:(.+)/,
6119 format: 'content:%s'
6120 },
6121 // BFCP https://tools.ietf.org/html/rfc4583
6122 {
6123 // a=floorctrl:c-s
6124 name: 'bfcpFloorCtrl',
6125 reg: /^floorctrl:(c-only|s-only|c-s)/,
6126 format: 'floorctrl:%s'
6127 },
6128 {
6129 // a=confid:1
6130 name: 'bfcpConfId',
6131 reg: /^confid:(\d+)/,
6132 format: 'confid:%s'
6133 },
6134 {
6135 // a=userid:1
6136 name: 'bfcpUserId',
6137 reg: /^userid:(\d+)/,
6138 format: 'userid:%s'
6139 },
6140 {
6141 // a=floorid:1
6142 name: 'bfcpFloorId',
6143 reg: /^floorid:(.+) (?:m-stream|mstrm):(.+)/,
6144 names: ['id', 'mStream'],
6145 format: 'floorid:%s mstrm:%s'
6146 },
6147 {
6148 // any a= that we don't understand is kept verbatim on media.invalid
6149 push: 'invalid',
6150 names: ['value']
6151 }
6152 ]
6153 };
6154
6155 // set sensible defaults to avoid polluting the grammar with boring details
6156 Object.keys(grammar$1).forEach(function (key) {
6157 var objs = grammar$1[key];
6158 objs.forEach(function (obj) {
6159 if (!obj.reg) {
6160 obj.reg = /(.*)/;
6161 }
6162 if (!obj.format) {
6163 obj.format = '%s';
6164 }
6165 });
6166 });
6167
6168 var grammarExports = grammar$2.exports;
6169
6170 (function (exports) {
6171 var toIntIfInt = function (v) {
6172 return String(Number(v)) === v ? Number(v) : v;
6173 };
6174
6175 var attachProperties = function (match, location, names, rawName) {
6176 if (rawName && !names) {
6177 location[rawName] = toIntIfInt(match[1]);
6178 }
6179 else {
6180 for (var i = 0; i < names.length; i += 1) {
6181 if (match[i+1] != null) {
6182 location[names[i]] = toIntIfInt(match[i+1]);
6183 }
6184 }
6185 }
6186 };
6187
6188 var parseReg = function (obj, location, content) {
6189 var needsBlank = obj.name && obj.names;
6190 if (obj.push && !location[obj.push]) {
6191 location[obj.push] = [];
6192 }
6193 else if (needsBlank && !location[obj.name]) {
6194 location[obj.name] = {};
6195 }
6196 var keyLocation = obj.push ?
6197 {} : // blank object that will be pushed
6198 needsBlank ? location[obj.name] : location; // otherwise, named location or root
6199
6200 attachProperties(content.match(obj.reg), keyLocation, obj.names, obj.name);
6201
6202 if (obj.push) {
6203 location[obj.push].push(keyLocation);
6204 }
6205 };
6206
6207 var grammar = grammarExports;
6208 var validLine = RegExp.prototype.test.bind(/^([a-z])=(.*)/);
6209
6210 exports.parse = function (sdp) {
6211 var session = {}
6212 , media = []
6213 , location = session; // points at where properties go under (one of the above)
6214
6215 // parse lines we understand
6216 sdp.split(/(\r\n|\r|\n)/).filter(validLine).forEach(function (l) {
6217 var type = l[0];
6218 var content = l.slice(2);
6219 if (type === 'm') {
6220 media.push({rtp: [], fmtp: []});
6221 location = media[media.length-1]; // point at latest media line
6222 }
6223
6224 for (var j = 0; j < (grammar[type] || []).length; j += 1) {
6225 var obj = grammar[type][j];
6226 if (obj.reg.test(content)) {
6227 return parseReg(obj, location, content);
6228 }
6229 }
6230 });
6231
6232 session.media = media; // link it up
6233 return session;
6234 };
6235
6236 var paramReducer = function (acc, expr) {
6237 var s = expr.split(/=(.+)/, 2);
6238 if (s.length === 2) {
6239 acc[s[0]] = toIntIfInt(s[1]);
6240 } else if (s.length === 1 && expr.length > 1) {
6241 acc[s[0]] = undefined;
6242 }
6243 return acc;
6244 };
6245
6246 exports.parseParams = function (str) {
6247 return str.split(/;\s?/).reduce(paramReducer, {});
6248 };
6249
6250 // For backward compatibility - alias will be removed in 3.0.0
6251 exports.parseFmtpConfig = exports.parseParams;
6252
6253 exports.parsePayloads = function (str) {
6254 return str.toString().split(' ').map(Number);
6255 };
6256
6257 exports.parseRemoteCandidates = function (str) {
6258 var candidates = [];
6259 var parts = str.split(' ').map(toIntIfInt);
6260 for (var i = 0; i < parts.length; i += 3) {
6261 candidates.push({
6262 component: parts[i],
6263 ip: parts[i + 1],
6264 port: parts[i + 2]
6265 });
6266 }
6267 return candidates;
6268 };
6269
6270 exports.parseImageAttributes = function (str) {
6271 return str.split(' ').map(function (item) {
6272 return item.substring(1, item.length-1).split(',').reduce(paramReducer, {});
6273 });
6274 };
6275
6276 exports.parseSimulcastStreamList = function (str) {
6277 return str.split(';').map(function (stream) {
6278 return stream.split(',').map(function (format) {
6279 var scid, paused = false;
6280
6281 if (format[0] !== '~') {
6282 scid = toIntIfInt(format);
6283 } else {
6284 scid = toIntIfInt(format.substring(1, format.length));
6285 paused = true;
6286 }
6287
6288 return {
6289 scid: scid,
6290 paused: paused
6291 };
6292 });
6293 });
6294 };
6295 } (parser$1));
6296
6297 var grammar = grammarExports;
6298
6299 // customized util.format - discards excess arguments and can void middle ones
6300 var formatRegExp = /%[sdv%]/g;
6301 var format = function (formatStr) {
6302 var i = 1;
6303 var args = arguments;
6304 var len = args.length;
6305 return formatStr.replace(formatRegExp, function (x) {
6306 if (i >= len) {
6307 return x; // missing argument
6308 }
6309 var arg = args[i];
6310 i += 1;
6311 switch (x) {
6312 case '%%':
6313 return '%';
6314 case '%s':
6315 return String(arg);
6316 case '%d':
6317 return Number(arg);
6318 case '%v':
6319 return '';
6320 }
6321 });
6322 // NB: we discard excess arguments - they are typically undefined from makeLine
6323 };
6324
6325 var makeLine = function (type, obj, location) {
6326 var str = obj.format instanceof Function ?
6327 (obj.format(obj.push ? location : location[obj.name])) :
6328 obj.format;
6329
6330 var args = [type + '=' + str];
6331 if (obj.names) {
6332 for (var i = 0; i < obj.names.length; i += 1) {
6333 var n = obj.names[i];
6334 if (obj.name) {
6335 args.push(location[obj.name][n]);
6336 }
6337 else { // for mLine and push attributes
6338 args.push(location[obj.names[i]]);
6339 }
6340 }
6341 }
6342 else {
6343 args.push(location[obj.name]);
6344 }
6345 return format.apply(null, args);
6346 };
6347
6348 // RFC specified order
6349 // TODO: extend this with all the rest
6350 var defaultOuterOrder = [
6351 'v', 'o', 's', 'i',
6352 'u', 'e', 'p', 'c',
6353 'b', 't', 'r', 'z', 'a'
6354 ];
6355 var defaultInnerOrder = ['i', 'c', 'b', 'a'];
6356
6357
6358 var writer$1 = function (session, opts) {
6359 opts = opts || {};
6360 // ensure certain properties exist
6361 if (session.version == null) {
6362 session.version = 0; // 'v=0' must be there (only defined version atm)
6363 }
6364 if (session.name == null) {
6365 session.name = ' '; // 's= ' must be there if no meaningful name set
6366 }
6367 session.media.forEach(function (mLine) {
6368 if (mLine.payloads == null) {
6369 mLine.payloads = '';
6370 }
6371 });
6372
6373 var outerOrder = opts.outerOrder || defaultOuterOrder;
6374 var innerOrder = opts.innerOrder || defaultInnerOrder;
6375 var sdp = [];
6376
6377 // loop through outerOrder for matching properties on session
6378 outerOrder.forEach(function (type) {
6379 grammar[type].forEach(function (obj) {
6380 if (obj.name in session && session[obj.name] != null) {
6381 sdp.push(makeLine(type, obj, session));
6382 }
6383 else if (obj.push in session && session[obj.push] != null) {
6384 session[obj.push].forEach(function (el) {
6385 sdp.push(makeLine(type, obj, el));
6386 });
6387 }
6388 });
6389 });
6390
6391 // then for each media line, follow the innerOrder
6392 session.media.forEach(function (mLine) {
6393 sdp.push(makeLine('m', grammar.m[0], mLine));
6394
6395 innerOrder.forEach(function (type) {
6396 grammar[type].forEach(function (obj) {
6397 if (obj.name in mLine && mLine[obj.name] != null) {
6398 sdp.push(makeLine(type, obj, mLine));
6399 }
6400 else if (obj.push in mLine && mLine[obj.push] != null) {
6401 mLine[obj.push].forEach(function (el) {
6402 sdp.push(makeLine(type, obj, el));
6403 });
6404 }
6405 });
6406 });
6407 });
6408
6409 return sdp.join('\r\n') + '\r\n';
6410 };
6411
6412 var parser = parser$1;
6413 var writer = writer$1;
6414
6415 lib.write = writer;
6416 lib.parse = parser.parse;
6417 lib.parseParams = parser.parseParams;
6418 lib.parseFmtpConfig = parser.parseFmtpConfig; // Alias of parseParams().
6419 lib.parsePayloads = parser.parsePayloads;
6420 lib.parseRemoteCandidates = parser.parseRemoteCandidates;
6421 lib.parseImageAttributes = parser.parseImageAttributes;
6422 lib.parseSimulcastStreamList = parser.parseSimulcastStreamList;
6423
6424 var commonUtils = {};
6425
6426 var __createBinding$f = (commonjsGlobal && commonjsGlobal.__createBinding) || (Object.create ? (function(o, m, k, k2) {
6427 if (k2 === undefined) k2 = k;
6428 var desc = Object.getOwnPropertyDescriptor(m, k);
6429 if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6430 desc = { enumerable: true, get: function() { return m[k]; } };
6431 }
6432 Object.defineProperty(o, k2, desc);
6433 }) : (function(o, m, k, k2) {
6434 if (k2 === undefined) k2 = k;
6435 o[k2] = m[k];
6436 }));
6437 var __setModuleDefault$f = (commonjsGlobal && commonjsGlobal.__setModuleDefault) || (Object.create ? (function(o, v) {
6438 Object.defineProperty(o, "default", { enumerable: true, value: v });
6439 }) : function(o, v) {
6440 o["default"] = v;
6441 });
6442 var __importStar$f = (commonjsGlobal && commonjsGlobal.__importStar) || function (mod) {
6443 if (mod && mod.__esModule) return mod;
6444 var result = {};
6445 if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding$f(result, mod, k);
6446 __setModuleDefault$f(result, mod);
6447 return result;
6448 };
6449 Object.defineProperty(commonUtils, "__esModule", { value: true });
6450 commonUtils.applyCodecParameters = commonUtils.getCname = commonUtils.extractDtlsParameters = commonUtils.extractRtpCapabilities = void 0;
6451 const sdpTransform$c = __importStar$f(lib);
6452 /**
6453 * This function must be called with an SDP with 1 m=audio and 1 m=video
6454 * sections.
6455 */
6456 function extractRtpCapabilities({ sdpObject }) {
6457 // Map of RtpCodecParameters indexed by payload type.
6458 const codecsMap = new Map();
6459 // Array of RtpHeaderExtensions.
6460 const headerExtensions = [];
6461 // Whether a m=audio/video section has been already found.
6462 let gotAudio = false;
6463 let gotVideo = false;
6464 for (const m of sdpObject.media) {
6465 const kind = m.type;
6466 switch (kind) {
6467 case 'audio':
6468 {
6469 if (gotAudio) {
6470 continue;
6471 }
6472 gotAudio = true;
6473 break;
6474 }
6475 case 'video':
6476 {
6477 if (gotVideo) {
6478 continue;
6479 }
6480 gotVideo = true;
6481 break;
6482 }
6483 default:
6484 {
6485 continue;
6486 }
6487 }
6488 // Get codecs.
6489 for (const rtp of m.rtp) {
6490 const codec = {
6491 kind: kind,
6492 mimeType: `${kind}/${rtp.codec}`,
6493 preferredPayloadType: rtp.payload,
6494 clockRate: rtp.rate,
6495 channels: rtp.encoding,
6496 parameters: {},
6497 rtcpFeedback: []
6498 };
6499 codecsMap.set(codec.preferredPayloadType, codec);
6500 }
6501 // Get codec parameters.
6502 for (const fmtp of m.fmtp || []) {
6503 const parameters = sdpTransform$c.parseParams(fmtp.config);
6504 const codec = codecsMap.get(fmtp.payload);
6505 if (!codec) {
6506 continue;
6507 }
6508 // Specials case to convert parameter value to string.
6509 if (parameters && parameters.hasOwnProperty('profile-level-id')) {
6510 parameters['profile-level-id'] = String(parameters['profile-level-id']);
6511 }
6512 codec.parameters = parameters;
6513 }
6514 // Get RTCP feedback for each codec.
6515 for (const fb of m.rtcpFb || []) {
6516 const feedback = {
6517 type: fb.type,
6518 parameter: fb.subtype
6519 };
6520 if (!feedback.parameter) {
6521 delete feedback.parameter;
6522 }
6523 // rtcp-fb payload is not '*', so just apply it to its corresponding
6524 // codec.
6525 if (fb.payload !== '*') {
6526 const codec = codecsMap.get(fb.payload);
6527 if (!codec) {
6528 continue;
6529 }
6530 codec.rtcpFeedback.push(feedback);
6531 }
6532 // If rtcp-fb payload is '*' it must be applied to all codecs with same
6533 // kind (with some exceptions such as RTX codec).
6534 else {
6535 for (const codec of codecsMap.values()) {
6536 if (codec.kind === kind && !/.+\/rtx$/i.test(codec.mimeType)) {
6537 codec.rtcpFeedback.push(feedback);
6538 }
6539 }
6540 }
6541 }
6542 // Get RTP header extensions.
6543 for (const ext of m.ext || []) {
6544 // Ignore encrypted extensions (not yet supported in mediasoup).
6545 if (ext['encrypt-uri']) {
6546 continue;
6547 }
6548 const headerExtension = {
6549 kind: kind,
6550 uri: ext.uri,
6551 preferredId: ext.value
6552 };
6553 headerExtensions.push(headerExtension);
6554 }
6555 }
6556 const rtpCapabilities = {
6557 codecs: Array.from(codecsMap.values()),
6558 headerExtensions: headerExtensions
6559 };
6560 return rtpCapabilities;
6561 }
6562 commonUtils.extractRtpCapabilities = extractRtpCapabilities;
6563 function extractDtlsParameters({ sdpObject }) {
6564 let setup = sdpObject.setup;
6565 let fingerprint = sdpObject.fingerprint;
6566 if (!setup || !fingerprint) {
6567 const mediaObject = (sdpObject.media || [])
6568 .find((m) => (m.port !== 0));
6569 if (mediaObject) {
6570 setup ?? (setup = mediaObject.setup);
6571 fingerprint ?? (fingerprint = mediaObject.fingerprint);
6572 }
6573 }
6574 if (!setup) {
6575 throw new Error('no a=setup found at SDP session or media level');
6576 }
6577 else if (!fingerprint) {
6578 throw new Error('no a=fingerprint found at SDP session or media level');
6579 }
6580 let role;
6581 switch (setup) {
6582 case 'active':
6583 role = 'client';
6584 break;
6585 case 'passive':
6586 role = 'server';
6587 break;
6588 case 'actpass':
6589 role = 'auto';
6590 break;
6591 }
6592 const dtlsParameters = {
6593 role,
6594 fingerprints: [
6595 {
6596 algorithm: fingerprint.type,
6597 value: fingerprint.hash
6598 }
6599 ]
6600 };
6601 return dtlsParameters;
6602 }
6603 commonUtils.extractDtlsParameters = extractDtlsParameters;
6604 function getCname({ offerMediaObject }) {
6605 const ssrcCnameLine = (offerMediaObject.ssrcs || [])
6606 .find((line) => line.attribute === 'cname');
6607 if (!ssrcCnameLine) {
6608 return '';
6609 }
6610 return ssrcCnameLine.value;
6611 }
6612 commonUtils.getCname = getCname;
6613 /**
6614 * Apply codec parameters in the given SDP m= section answer based on the
6615 * given RTP parameters of an offer.
6616 */
6617 function applyCodecParameters({ offerRtpParameters, answerMediaObject }) {
6618 for (const codec of offerRtpParameters.codecs) {
6619 const mimeType = codec.mimeType.toLowerCase();
6620 // Avoid parsing codec parameters for unhandled codecs.
6621 if (mimeType !== 'audio/opus') {
6622 continue;
6623 }
6624 const rtp = (answerMediaObject.rtp || [])
6625 .find((r) => r.payload === codec.payloadType);
6626 if (!rtp) {
6627 continue;
6628 }
6629 // Just in case.
6630 answerMediaObject.fmtp = answerMediaObject.fmtp || [];
6631 let fmtp = answerMediaObject.fmtp
6632 .find((f) => f.payload === codec.payloadType);
6633 if (!fmtp) {
6634 fmtp = { payload: codec.payloadType, config: '' };
6635 answerMediaObject.fmtp.push(fmtp);
6636 }
6637 const parameters = sdpTransform$c.parseParams(fmtp.config);
6638 switch (mimeType) {
6639 case 'audio/opus':
6640 {
6641 const spropStereo = codec.parameters['sprop-stereo'];
6642 if (spropStereo !== undefined) {
6643 parameters.stereo = spropStereo ? 1 : 0;
6644 }
6645 break;
6646 }
6647 }
6648 // Write the codec fmtp.config back.
6649 fmtp.config = '';
6650 for (const key of Object.keys(parameters)) {
6651 if (fmtp.config) {
6652 fmtp.config += ';';
6653 }
6654 fmtp.config += `${key}=${parameters[key]}`;
6655 }
6656 }
6657 }
6658 commonUtils.applyCodecParameters = applyCodecParameters;
6659
6660 var unifiedPlanUtils = {};
6661
6662 Object.defineProperty(unifiedPlanUtils, "__esModule", { value: true });
6663 unifiedPlanUtils.addLegacySimulcast = unifiedPlanUtils.getRtpEncodings = void 0;
6664 function getRtpEncodings$1({ offerMediaObject }) {
6665 const ssrcs = new Set();
6666 for (const line of offerMediaObject.ssrcs || []) {
6667 const ssrc = line.id;
6668 ssrcs.add(ssrc);
6669 }
6670 if (ssrcs.size === 0) {
6671 throw new Error('no a=ssrc lines found');
6672 }
6673 const ssrcToRtxSsrc = new Map();
6674 // First assume RTX is used.
6675 for (const line of offerMediaObject.ssrcGroups || []) {
6676 if (line.semantics !== 'FID') {
6677 continue;
6678 }
6679 let [ssrc, rtxSsrc] = line.ssrcs.split(/\s+/);
6680 ssrc = Number(ssrc);
6681 rtxSsrc = Number(rtxSsrc);
6682 if (ssrcs.has(ssrc)) {
6683 // Remove both the SSRC and RTX SSRC from the set so later we know
6684 // that they are already handled.
6685 ssrcs.delete(ssrc);
6686 ssrcs.delete(rtxSsrc);
6687 // Add to the map.
6688 ssrcToRtxSsrc.set(ssrc, rtxSsrc);
6689 }
6690 }
6691 // If the set of SSRCs is not empty it means that RTX is not being used, so
6692 // take media SSRCs from there.
6693 for (const ssrc of ssrcs) {
6694 // Add to the map.
6695 ssrcToRtxSsrc.set(ssrc, null);
6696 }
6697 const encodings = [];
6698 for (const [ssrc, rtxSsrc] of ssrcToRtxSsrc) {
6699 const encoding = { ssrc };
6700 if (rtxSsrc) {
6701 encoding.rtx = { ssrc: rtxSsrc };
6702 }
6703 encodings.push(encoding);
6704 }
6705 return encodings;
6706 }
6707 unifiedPlanUtils.getRtpEncodings = getRtpEncodings$1;
6708 /**
6709 * Adds multi-ssrc based simulcast into the given SDP media section offer.
6710 */
6711 function addLegacySimulcast$1({ offerMediaObject, numStreams }) {
6712 if (numStreams <= 1) {
6713 throw new TypeError('numStreams must be greater than 1');
6714 }
6715 // Get the SSRC.
6716 const ssrcMsidLine = (offerMediaObject.ssrcs || [])
6717 .find((line) => line.attribute === 'msid');
6718 if (!ssrcMsidLine) {
6719 throw new Error('a=ssrc line with msid information not found');
6720 }
6721 const [streamId, trackId] = ssrcMsidLine.value.split(' ');
6722 const firstSsrc = ssrcMsidLine.id;
6723 let firstRtxSsrc;
6724 // Get the SSRC for RTX.
6725 (offerMediaObject.ssrcGroups || [])
6726 .some((line) => {
6727 if (line.semantics !== 'FID') {
6728 return false;
6729 }
6730 const ssrcs = line.ssrcs.split(/\s+/);
6731 if (Number(ssrcs[0]) === firstSsrc) {
6732 firstRtxSsrc = Number(ssrcs[1]);
6733 return true;
6734 }
6735 else {
6736 return false;
6737 }
6738 });
6739 const ssrcCnameLine = offerMediaObject.ssrcs
6740 .find((line) => line.attribute === 'cname');
6741 if (!ssrcCnameLine) {
6742 throw new Error('a=ssrc line with cname information not found');
6743 }
6744 const cname = ssrcCnameLine.value;
6745 const ssrcs = [];
6746 const rtxSsrcs = [];
6747 for (let i = 0; i < numStreams; ++i) {
6748 ssrcs.push(firstSsrc + i);
6749 if (firstRtxSsrc) {
6750 rtxSsrcs.push(firstRtxSsrc + i);
6751 }
6752 }
6753 offerMediaObject.ssrcGroups = [];
6754 offerMediaObject.ssrcs = [];
6755 offerMediaObject.ssrcGroups.push({
6756 semantics: 'SIM',
6757 ssrcs: ssrcs.join(' ')
6758 });
6759 for (let i = 0; i < ssrcs.length; ++i) {
6760 const ssrc = ssrcs[i];
6761 offerMediaObject.ssrcs.push({
6762 id: ssrc,
6763 attribute: 'cname',
6764 value: cname
6765 });
6766 offerMediaObject.ssrcs.push({
6767 id: ssrc,
6768 attribute: 'msid',
6769 value: `${streamId} ${trackId}`
6770 });
6771 }
6772 for (let i = 0; i < rtxSsrcs.length; ++i) {
6773 const ssrc = ssrcs[i];
6774 const rtxSsrc = rtxSsrcs[i];
6775 offerMediaObject.ssrcs.push({
6776 id: rtxSsrc,
6777 attribute: 'cname',
6778 value: cname
6779 });
6780 offerMediaObject.ssrcs.push({
6781 id: rtxSsrc,
6782 attribute: 'msid',
6783 value: `${streamId} ${trackId}`
6784 });
6785 offerMediaObject.ssrcGroups.push({
6786 semantics: 'FID',
6787 ssrcs: `${ssrc} ${rtxSsrc}`
6788 });
6789 }
6790 }
6791 unifiedPlanUtils.addLegacySimulcast = addLegacySimulcast$1;
6792
6793 var utils$e = {};
6794
6795 Object.defineProperty(utils$e, "__esModule", { value: true });
6796 utils$e.addNackSuppportForOpus = void 0;
6797 /**
6798 * This function adds RTCP NACK support for OPUS codec in given capabilities.
6799 */
6800 function addNackSuppportForOpus(rtpCapabilities) {
6801 for (const codec of (rtpCapabilities.codecs || [])) {
6802 if ((codec.mimeType.toLowerCase() === 'audio/opus' ||
6803 codec.mimeType.toLowerCase() === 'audio/multiopus') &&
6804 !codec.rtcpFeedback?.some((fb) => fb.type === 'nack' && !fb.parameter)) {
6805 if (!codec.rtcpFeedback) {
6806 codec.rtcpFeedback = [];
6807 }
6808 codec.rtcpFeedback.push({ type: 'nack' });
6809 }
6810 }
6811 }
6812 utils$e.addNackSuppportForOpus = addNackSuppportForOpus;
6813
6814 var HandlerInterface$1 = {};
6815
6816 Object.defineProperty(HandlerInterface$1, "__esModule", { value: true });
6817 HandlerInterface$1.HandlerInterface = void 0;
6818 const EnhancedEventEmitter_1$1 = EnhancedEventEmitter$1;
6819 class HandlerInterface extends EnhancedEventEmitter_1$1.EnhancedEventEmitter {
6820 constructor() {
6821 super();
6822 }
6823 }
6824 HandlerInterface$1.HandlerInterface = HandlerInterface;
6825
6826 var RemoteSdp$1 = {};
6827
6828 var MediaSection$1 = {};
6829
6830 var __createBinding$e = (commonjsGlobal && commonjsGlobal.__createBinding) || (Object.create ? (function(o, m, k, k2) {
6831 if (k2 === undefined) k2 = k;
6832 var desc = Object.getOwnPropertyDescriptor(m, k);
6833 if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6834 desc = { enumerable: true, get: function() { return m[k]; } };
6835 }
6836 Object.defineProperty(o, k2, desc);
6837 }) : (function(o, m, k, k2) {
6838 if (k2 === undefined) k2 = k;
6839 o[k2] = m[k];
6840 }));
6841 var __setModuleDefault$e = (commonjsGlobal && commonjsGlobal.__setModuleDefault) || (Object.create ? (function(o, v) {
6842 Object.defineProperty(o, "default", { enumerable: true, value: v });
6843 }) : function(o, v) {
6844 o["default"] = v;
6845 });
6846 var __importStar$e = (commonjsGlobal && commonjsGlobal.__importStar) || function (mod) {
6847 if (mod && mod.__esModule) return mod;
6848 var result = {};
6849 if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding$e(result, mod, k);
6850 __setModuleDefault$e(result, mod);
6851 return result;
6852 };
6853 Object.defineProperty(MediaSection$1, "__esModule", { value: true });
6854 MediaSection$1.OfferMediaSection = MediaSection$1.AnswerMediaSection = MediaSection$1.MediaSection = void 0;
6855 const sdpTransform$b = __importStar$e(lib);
6856 const utils$d = __importStar$e(utils$h);
6857 class MediaSection {
6858 constructor({ iceParameters, iceCandidates, dtlsParameters, planB = false }) {
6859 this._mediaObject = {};
6860 this._planB = planB;
6861 if (iceParameters) {
6862 this.setIceParameters(iceParameters);
6863 }
6864 if (iceCandidates) {
6865 this._mediaObject.candidates = [];
6866 for (const candidate of iceCandidates) {
6867 const candidateObject = {};
6868 // mediasoup does mandates rtcp-mux so candidates component is always
6869 // RTP (1).
6870 candidateObject.component = 1;
6871 candidateObject.foundation = candidate.foundation;
6872 candidateObject.ip = candidate.ip;
6873 candidateObject.port = candidate.port;
6874 candidateObject.priority = candidate.priority;
6875 candidateObject.transport = candidate.protocol;
6876 candidateObject.type = candidate.type;
6877 if (candidate.tcpType) {
6878 candidateObject.tcptype = candidate.tcpType;
6879 }
6880 this._mediaObject.candidates.push(candidateObject);
6881 }
6882 this._mediaObject.endOfCandidates = 'end-of-candidates';
6883 this._mediaObject.iceOptions = 'renomination';
6884 }
6885 if (dtlsParameters) {
6886 this.setDtlsRole(dtlsParameters.role);
6887 }
6888 }
6889 get mid() {
6890 return String(this._mediaObject.mid);
6891 }
6892 get closed() {
6893 return this._mediaObject.port === 0;
6894 }
6895 getObject() {
6896 return this._mediaObject;
6897 }
6898 setIceParameters(iceParameters) {
6899 this._mediaObject.iceUfrag = iceParameters.usernameFragment;
6900 this._mediaObject.icePwd = iceParameters.password;
6901 }
6902 pause() {
6903 this._mediaObject.direction = 'inactive';
6904 }
6905 disable() {
6906 this.pause();
6907 delete this._mediaObject.ext;
6908 delete this._mediaObject.ssrcs;
6909 delete this._mediaObject.ssrcGroups;
6910 delete this._mediaObject.simulcast;
6911 delete this._mediaObject.simulcast_03;
6912 delete this._mediaObject.rids;
6913 delete this._mediaObject.extmapAllowMixed;
6914 }
6915 close() {
6916 this.disable();
6917 this._mediaObject.port = 0;
6918 }
6919 }
6920 MediaSection$1.MediaSection = MediaSection;
6921 class AnswerMediaSection extends MediaSection {
6922 constructor({ iceParameters, iceCandidates, dtlsParameters, sctpParameters, plainRtpParameters, planB = false, offerMediaObject, offerRtpParameters, answerRtpParameters, codecOptions, extmapAllowMixed = false }) {
6923 super({ iceParameters, iceCandidates, dtlsParameters, planB });
6924 this._mediaObject.mid = String(offerMediaObject.mid);
6925 this._mediaObject.type = offerMediaObject.type;
6926 this._mediaObject.protocol = offerMediaObject.protocol;
6927 if (!plainRtpParameters) {
6928 this._mediaObject.connection = { ip: '127.0.0.1', version: 4 };
6929 this._mediaObject.port = 7;
6930 }
6931 else {
6932 this._mediaObject.connection =
6933 {
6934 ip: plainRtpParameters.ip,
6935 version: plainRtpParameters.ipVersion
6936 };
6937 this._mediaObject.port = plainRtpParameters.port;
6938 }
6939 switch (offerMediaObject.type) {
6940 case 'audio':
6941 case 'video':
6942 {
6943 this._mediaObject.direction = 'recvonly';
6944 this._mediaObject.rtp = [];
6945 this._mediaObject.rtcpFb = [];
6946 this._mediaObject.fmtp = [];
6947 for (const codec of answerRtpParameters.codecs) {
6948 const rtp = {
6949 payload: codec.payloadType,
6950 codec: getCodecName(codec),
6951 rate: codec.clockRate
6952 };
6953 if (codec.channels > 1) {
6954 rtp.encoding = codec.channels;
6955 }
6956 this._mediaObject.rtp.push(rtp);
6957 const codecParameters = utils$d.clone(codec.parameters) ?? {};
6958 let codecRtcpFeedback = utils$d.clone(codec.rtcpFeedback) ?? [];
6959 if (codecOptions) {
6960 const { opusStereo, opusFec, opusDtx, opusMaxPlaybackRate, opusMaxAverageBitrate, opusPtime, opusNack, videoGoogleStartBitrate, videoGoogleMaxBitrate, videoGoogleMinBitrate } = codecOptions;
6961 const offerCodec = offerRtpParameters.codecs
6962 .find((c) => (c.payloadType === codec.payloadType));
6963 switch (codec.mimeType.toLowerCase()) {
6964 case 'audio/opus':
6965 case 'audio/multiopus':
6966 {
6967 if (opusStereo !== undefined) {
6968 offerCodec.parameters['sprop-stereo'] = opusStereo ? 1 : 0;
6969 codecParameters.stereo = opusStereo ? 1 : 0;
6970 }
6971 if (opusFec !== undefined) {
6972 offerCodec.parameters.useinbandfec = opusFec ? 1 : 0;
6973 codecParameters.useinbandfec = opusFec ? 1 : 0;
6974 }
6975 if (opusDtx !== undefined) {
6976 offerCodec.parameters.usedtx = opusDtx ? 1 : 0;
6977 codecParameters.usedtx = opusDtx ? 1 : 0;
6978 }
6979 if (opusMaxPlaybackRate !== undefined) {
6980 codecParameters.maxplaybackrate = opusMaxPlaybackRate;
6981 }
6982 if (opusMaxAverageBitrate !== undefined) {
6983 codecParameters.maxaveragebitrate = opusMaxAverageBitrate;
6984 }
6985 if (opusPtime !== undefined) {
6986 offerCodec.parameters.ptime = opusPtime;
6987 codecParameters.ptime = opusPtime;
6988 }
6989 // If opusNack is not set, we must remove NACK support for OPUS.
6990 // Otherwise it would be enabled for those handlers that artificially
6991 // announce it in their RTP capabilities.
6992 if (!opusNack) {
6993 offerCodec.rtcpFeedback = offerCodec
6994 .rtcpFeedback
6995 .filter((fb) => fb.type !== 'nack' || fb.parameter);
6996 codecRtcpFeedback = codecRtcpFeedback
6997 .filter((fb) => fb.type !== 'nack' || fb.parameter);
6998 }
6999 break;
7000 }
7001 case 'video/vp8':
7002 case 'video/vp9':
7003 case 'video/h264':
7004 case 'video/h265':
7005 {
7006 if (videoGoogleStartBitrate !== undefined) {
7007 codecParameters['x-google-start-bitrate'] = videoGoogleStartBitrate;
7008 }
7009 if (videoGoogleMaxBitrate !== undefined) {
7010 codecParameters['x-google-max-bitrate'] = videoGoogleMaxBitrate;
7011 }
7012 if (videoGoogleMinBitrate !== undefined) {
7013 codecParameters['x-google-min-bitrate'] = videoGoogleMinBitrate;
7014 }
7015 break;
7016 }
7017 }
7018 }
7019 const fmtp = {
7020 payload: codec.payloadType,
7021 config: ''
7022 };
7023 for (const key of Object.keys(codecParameters)) {
7024 if (fmtp.config) {
7025 fmtp.config += ';';
7026 }
7027 fmtp.config += `${key}=${codecParameters[key]}`;
7028 }
7029 if (fmtp.config) {
7030 this._mediaObject.fmtp.push(fmtp);
7031 }
7032 for (const fb of codecRtcpFeedback) {
7033 this._mediaObject.rtcpFb.push({
7034 payload: codec.payloadType,
7035 type: fb.type,
7036 subtype: fb.parameter
7037 });
7038 }
7039 }
7040 this._mediaObject.payloads = answerRtpParameters.codecs
7041 .map((codec) => codec.payloadType)
7042 .join(' ');
7043 this._mediaObject.ext = [];
7044 for (const ext of answerRtpParameters.headerExtensions) {
7045 // Don't add a header extension if not present in the offer.
7046 const found = (offerMediaObject.ext || [])
7047 .some((localExt) => localExt.uri === ext.uri);
7048 if (!found) {
7049 continue;
7050 }
7051 this._mediaObject.ext.push({
7052 uri: ext.uri,
7053 value: ext.id
7054 });
7055 }
7056 // Allow both 1 byte and 2 bytes length header extensions.
7057 if (extmapAllowMixed &&
7058 offerMediaObject.extmapAllowMixed === 'extmap-allow-mixed') {
7059 this._mediaObject.extmapAllowMixed = 'extmap-allow-mixed';
7060 }
7061 // Simulcast.
7062 if (offerMediaObject.simulcast) {
7063 this._mediaObject.simulcast =
7064 {
7065 dir1: 'recv',
7066 list1: offerMediaObject.simulcast.list1
7067 };
7068 this._mediaObject.rids = [];
7069 for (const rid of offerMediaObject.rids || []) {
7070 if (rid.direction !== 'send') {
7071 continue;
7072 }
7073 this._mediaObject.rids.push({
7074 id: rid.id,
7075 direction: 'recv'
7076 });
7077 }
7078 }
7079 // Simulcast (draft version 03).
7080 else if (offerMediaObject.simulcast_03) {
7081 // eslint-disable-next-line camelcase
7082 this._mediaObject.simulcast_03 =
7083 {
7084 value: offerMediaObject.simulcast_03.value.replace(/send/g, 'recv')
7085 };
7086 this._mediaObject.rids = [];
7087 for (const rid of offerMediaObject.rids || []) {
7088 if (rid.direction !== 'send') {
7089 continue;
7090 }
7091 this._mediaObject.rids.push({
7092 id: rid.id,
7093 direction: 'recv'
7094 });
7095 }
7096 }
7097 this._mediaObject.rtcpMux = 'rtcp-mux';
7098 this._mediaObject.rtcpRsize = 'rtcp-rsize';
7099 if (this._planB && this._mediaObject.type === 'video') {
7100 this._mediaObject.xGoogleFlag = 'conference';
7101 }
7102 break;
7103 }
7104 case 'application':
7105 {
7106 // New spec.
7107 if (typeof offerMediaObject.sctpPort === 'number') {
7108 this._mediaObject.payloads = 'webrtc-datachannel';
7109 this._mediaObject.sctpPort = sctpParameters.port;
7110 this._mediaObject.maxMessageSize = sctpParameters.maxMessageSize;
7111 }
7112 // Old spec.
7113 else if (offerMediaObject.sctpmap) {
7114 this._mediaObject.payloads = sctpParameters.port;
7115 this._mediaObject.sctpmap =
7116 {
7117 app: 'webrtc-datachannel',
7118 sctpmapNumber: sctpParameters.port,
7119 maxMessageSize: sctpParameters.maxMessageSize
7120 };
7121 }
7122 break;
7123 }
7124 }
7125 }
7126 setDtlsRole(role) {
7127 switch (role) {
7128 case 'client':
7129 this._mediaObject.setup = 'active';
7130 break;
7131 case 'server':
7132 this._mediaObject.setup = 'passive';
7133 break;
7134 case 'auto':
7135 this._mediaObject.setup = 'actpass';
7136 break;
7137 }
7138 }
7139 resume() {
7140 this._mediaObject.direction = 'recvonly';
7141 }
7142 muxSimulcastStreams(encodings) {
7143 if (!this._mediaObject.simulcast || !this._mediaObject.simulcast.list1) {
7144 return;
7145 }
7146 const layers = {};
7147 for (const encoding of encodings) {
7148 if (encoding.rid) {
7149 layers[encoding.rid] = encoding;
7150 }
7151 }
7152 const raw = this._mediaObject.simulcast.list1;
7153 const simulcastStreams = sdpTransform$b.parseSimulcastStreamList(raw);
7154 for (const simulcastStream of simulcastStreams) {
7155 for (const simulcastFormat of simulcastStream) {
7156 simulcastFormat.paused = !layers[simulcastFormat.scid]?.active;
7157 }
7158 }
7159 this._mediaObject.simulcast.list1 = simulcastStreams.map((simulcastFormats) => simulcastFormats.map((f) => `${f.paused ? '~' : ''}${f.scid}`).join(',')).join(';');
7160 }
7161 }
7162 MediaSection$1.AnswerMediaSection = AnswerMediaSection;
7163 class OfferMediaSection extends MediaSection {
7164 constructor({ iceParameters, iceCandidates, dtlsParameters, sctpParameters, plainRtpParameters, planB = false, mid, kind, offerRtpParameters, streamId, trackId, oldDataChannelSpec = false }) {
7165 super({ iceParameters, iceCandidates, dtlsParameters, planB });
7166 this._mediaObject.mid = String(mid);
7167 this._mediaObject.type = kind;
7168 if (!plainRtpParameters) {
7169 this._mediaObject.connection = { ip: '127.0.0.1', version: 4 };
7170 if (!sctpParameters) {
7171 this._mediaObject.protocol = 'UDP/TLS/RTP/SAVPF';
7172 }
7173 else {
7174 this._mediaObject.protocol = 'UDP/DTLS/SCTP';
7175 }
7176 this._mediaObject.port = 7;
7177 }
7178 else {
7179 this._mediaObject.connection =
7180 {
7181 ip: plainRtpParameters.ip,
7182 version: plainRtpParameters.ipVersion
7183 };
7184 this._mediaObject.protocol = 'RTP/AVP';
7185 this._mediaObject.port = plainRtpParameters.port;
7186 }
7187 switch (kind) {
7188 case 'audio':
7189 case 'video':
7190 {
7191 this._mediaObject.direction = 'sendonly';
7192 this._mediaObject.rtp = [];
7193 this._mediaObject.rtcpFb = [];
7194 this._mediaObject.fmtp = [];
7195 if (!this._planB) {
7196 this._mediaObject.msid = `${streamId || '-'} ${trackId}`;
7197 }
7198 for (const codec of offerRtpParameters.codecs) {
7199 const rtp = {
7200 payload: codec.payloadType,
7201 codec: getCodecName(codec),
7202 rate: codec.clockRate
7203 };
7204 if (codec.channels > 1) {
7205 rtp.encoding = codec.channels;
7206 }
7207 this._mediaObject.rtp.push(rtp);
7208 const fmtp = {
7209 payload: codec.payloadType,
7210 config: ''
7211 };
7212 for (const key of Object.keys(codec.parameters)) {
7213 if (fmtp.config) {
7214 fmtp.config += ';';
7215 }
7216 fmtp.config += `${key}=${codec.parameters[key]}`;
7217 }
7218 if (fmtp.config) {
7219 this._mediaObject.fmtp.push(fmtp);
7220 }
7221 for (const fb of codec.rtcpFeedback) {
7222 this._mediaObject.rtcpFb.push({
7223 payload: codec.payloadType,
7224 type: fb.type,
7225 subtype: fb.parameter
7226 });
7227 }
7228 }
7229 this._mediaObject.payloads = offerRtpParameters.codecs
7230 .map((codec) => codec.payloadType)
7231 .join(' ');
7232 this._mediaObject.ext = [];
7233 for (const ext of offerRtpParameters.headerExtensions) {
7234 this._mediaObject.ext.push({
7235 uri: ext.uri,
7236 value: ext.id
7237 });
7238 }
7239 this._mediaObject.rtcpMux = 'rtcp-mux';
7240 this._mediaObject.rtcpRsize = 'rtcp-rsize';
7241 const encoding = offerRtpParameters.encodings[0];
7242 const ssrc = encoding.ssrc;
7243 const rtxSsrc = (encoding.rtx && encoding.rtx.ssrc)
7244 ? encoding.rtx.ssrc
7245 : undefined;
7246 this._mediaObject.ssrcs = [];
7247 this._mediaObject.ssrcGroups = [];
7248 if (offerRtpParameters.rtcp.cname) {
7249 this._mediaObject.ssrcs.push({
7250 id: ssrc,
7251 attribute: 'cname',
7252 value: offerRtpParameters.rtcp.cname
7253 });
7254 }
7255 if (this._planB) {
7256 this._mediaObject.ssrcs.push({
7257 id: ssrc,
7258 attribute: 'msid',
7259 value: `${streamId || '-'} ${trackId}`
7260 });
7261 }
7262 if (rtxSsrc) {
7263 if (offerRtpParameters.rtcp.cname) {
7264 this._mediaObject.ssrcs.push({
7265 id: rtxSsrc,
7266 attribute: 'cname',
7267 value: offerRtpParameters.rtcp.cname
7268 });
7269 }
7270 if (this._planB) {
7271 this._mediaObject.ssrcs.push({
7272 id: rtxSsrc,
7273 attribute: 'msid',
7274 value: `${streamId || '-'} ${trackId}`
7275 });
7276 }
7277 // Associate original and retransmission SSRCs.
7278 this._mediaObject.ssrcGroups.push({
7279 semantics: 'FID',
7280 ssrcs: `${ssrc} ${rtxSsrc}`
7281 });
7282 }
7283 break;
7284 }
7285 case 'application':
7286 {
7287 // New spec.
7288 if (!oldDataChannelSpec) {
7289 this._mediaObject.payloads = 'webrtc-datachannel';
7290 this._mediaObject.sctpPort = sctpParameters.port;
7291 this._mediaObject.maxMessageSize = sctpParameters.maxMessageSize;
7292 }
7293 // Old spec.
7294 else {
7295 this._mediaObject.payloads = sctpParameters.port;
7296 this._mediaObject.sctpmap =
7297 {
7298 app: 'webrtc-datachannel',
7299 sctpmapNumber: sctpParameters.port,
7300 maxMessageSize: sctpParameters.maxMessageSize
7301 };
7302 }
7303 break;
7304 }
7305 }
7306 }
7307 // eslint-disable-next-line @typescript-eslint/no-unused-vars
7308 setDtlsRole(role) {
7309 // Always 'actpass'.
7310 this._mediaObject.setup = 'actpass';
7311 }
7312 resume() {
7313 this._mediaObject.direction = 'sendonly';
7314 }
7315 planBReceive({ offerRtpParameters, streamId, trackId }) {
7316 const encoding = offerRtpParameters.encodings[0];
7317 const ssrc = encoding.ssrc;
7318 const rtxSsrc = (encoding.rtx && encoding.rtx.ssrc)
7319 ? encoding.rtx.ssrc
7320 : undefined;
7321 const payloads = this._mediaObject.payloads.split(' ');
7322 for (const codec of offerRtpParameters.codecs) {
7323 if (payloads.includes(String(codec.payloadType))) {
7324 continue;
7325 }
7326 const rtp = {
7327 payload: codec.payloadType,
7328 codec: getCodecName(codec),
7329 rate: codec.clockRate
7330 };
7331 if (codec.channels > 1) {
7332 rtp.encoding = codec.channels;
7333 }
7334 this._mediaObject.rtp.push(rtp);
7335 const fmtp = {
7336 payload: codec.payloadType,
7337 config: ''
7338 };
7339 for (const key of Object.keys(codec.parameters)) {
7340 if (fmtp.config) {
7341 fmtp.config += ';';
7342 }
7343 fmtp.config += `${key}=${codec.parameters[key]}`;
7344 }
7345 if (fmtp.config) {
7346 this._mediaObject.fmtp.push(fmtp);
7347 }
7348 for (const fb of codec.rtcpFeedback) {
7349 this._mediaObject.rtcpFb.push({
7350 payload: codec.payloadType,
7351 type: fb.type,
7352 subtype: fb.parameter
7353 });
7354 }
7355 }
7356 this._mediaObject.payloads += ` ${offerRtpParameters
7357 .codecs
7358 .filter((codec) => !this._mediaObject.payloads.includes(codec.payloadType))
7359 .map((codec) => codec.payloadType)
7360 .join(' ')}`;
7361 this._mediaObject.payloads = this._mediaObject.payloads.trim();
7362 if (offerRtpParameters.rtcp.cname) {
7363 this._mediaObject.ssrcs.push({
7364 id: ssrc,
7365 attribute: 'cname',
7366 value: offerRtpParameters.rtcp.cname
7367 });
7368 }
7369 this._mediaObject.ssrcs.push({
7370 id: ssrc,
7371 attribute: 'msid',
7372 value: `${streamId || '-'} ${trackId}`
7373 });
7374 if (rtxSsrc) {
7375 if (offerRtpParameters.rtcp.cname) {
7376 this._mediaObject.ssrcs.push({
7377 id: rtxSsrc,
7378 attribute: 'cname',
7379 value: offerRtpParameters.rtcp.cname
7380 });
7381 }
7382 this._mediaObject.ssrcs.push({
7383 id: rtxSsrc,
7384 attribute: 'msid',
7385 value: `${streamId || '-'} ${trackId}`
7386 });
7387 // Associate original and retransmission SSRCs.
7388 this._mediaObject.ssrcGroups.push({
7389 semantics: 'FID',
7390 ssrcs: `${ssrc} ${rtxSsrc}`
7391 });
7392 }
7393 }
7394 planBStopReceiving({ offerRtpParameters }) {
7395 const encoding = offerRtpParameters.encodings[0];
7396 const ssrc = encoding.ssrc;
7397 const rtxSsrc = (encoding.rtx && encoding.rtx.ssrc)
7398 ? encoding.rtx.ssrc
7399 : undefined;
7400 this._mediaObject.ssrcs = this._mediaObject.ssrcs
7401 .filter((s) => s.id !== ssrc && s.id !== rtxSsrc);
7402 if (rtxSsrc) {
7403 this._mediaObject.ssrcGroups = this._mediaObject.ssrcGroups
7404 .filter((group) => group.ssrcs !== `${ssrc} ${rtxSsrc}`);
7405 }
7406 }
7407 }
7408 MediaSection$1.OfferMediaSection = OfferMediaSection;
7409 function getCodecName(codec) {
7410 const MimeTypeRegex = new RegExp('^(audio|video)/(.+)', 'i');
7411 const mimeTypeMatch = MimeTypeRegex.exec(codec.mimeType);
7412 if (!mimeTypeMatch) {
7413 throw new TypeError('invalid codec.mimeType');
7414 }
7415 return mimeTypeMatch[2];
7416 }
7417
7418 var __createBinding$d = (commonjsGlobal && commonjsGlobal.__createBinding) || (Object.create ? (function(o, m, k, k2) {
7419 if (k2 === undefined) k2 = k;
7420 var desc = Object.getOwnPropertyDescriptor(m, k);
7421 if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
7422 desc = { enumerable: true, get: function() { return m[k]; } };
7423 }
7424 Object.defineProperty(o, k2, desc);
7425 }) : (function(o, m, k, k2) {
7426 if (k2 === undefined) k2 = k;
7427 o[k2] = m[k];
7428 }));
7429 var __setModuleDefault$d = (commonjsGlobal && commonjsGlobal.__setModuleDefault) || (Object.create ? (function(o, v) {
7430 Object.defineProperty(o, "default", { enumerable: true, value: v });
7431 }) : function(o, v) {
7432 o["default"] = v;
7433 });
7434 var __importStar$d = (commonjsGlobal && commonjsGlobal.__importStar) || function (mod) {
7435 if (mod && mod.__esModule) return mod;
7436 var result = {};
7437 if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding$d(result, mod, k);
7438 __setModuleDefault$d(result, mod);
7439 return result;
7440 };
7441 Object.defineProperty(RemoteSdp$1, "__esModule", { value: true });
7442 RemoteSdp$1.RemoteSdp = void 0;
7443 const sdpTransform$a = __importStar$d(lib);
7444 const Logger_1$c = Logger$3;
7445 const MediaSection_1 = MediaSection$1;
7446 const logger$c = new Logger_1$c.Logger('RemoteSdp');
7447 class RemoteSdp {
7448 constructor({ iceParameters, iceCandidates, dtlsParameters, sctpParameters, plainRtpParameters, planB = false }) {
7449 // MediaSection instances with same order as in the SDP.
7450 this._mediaSections = [];
7451 // MediaSection indices indexed by MID.
7452 this._midToIndex = new Map();
7453 this._iceParameters = iceParameters;
7454 this._iceCandidates = iceCandidates;
7455 this._dtlsParameters = dtlsParameters;
7456 this._sctpParameters = sctpParameters;
7457 this._plainRtpParameters = plainRtpParameters;
7458 this._planB = planB;
7459 this._sdpObject =
7460 {
7461 version: 0,
7462 origin: {
7463 address: '0.0.0.0',
7464 ipVer: 4,
7465 netType: 'IN',
7466 sessionId: 10000,
7467 sessionVersion: 0,
7468 username: 'mediasoup-client'
7469 },
7470 name: '-',
7471 timing: { start: 0, stop: 0 },
7472 media: []
7473 };
7474 // If ICE parameters are given, add ICE-Lite indicator.
7475 if (iceParameters && iceParameters.iceLite) {
7476 this._sdpObject.icelite = 'ice-lite';
7477 }
7478 // If DTLS parameters are given, assume WebRTC and BUNDLE.
7479 if (dtlsParameters) {
7480 this._sdpObject.msidSemantic = { semantic: 'WMS', token: '*' };
7481 // NOTE: We take the latest fingerprint.
7482 const numFingerprints = this._dtlsParameters.fingerprints.length;
7483 this._sdpObject.fingerprint =
7484 {
7485 type: dtlsParameters.fingerprints[numFingerprints - 1].algorithm,
7486 hash: dtlsParameters.fingerprints[numFingerprints - 1].value
7487 };
7488 this._sdpObject.groups = [{ type: 'BUNDLE', mids: '' }];
7489 }
7490 // If there are plain RPT parameters, override SDP origin.
7491 if (plainRtpParameters) {
7492 this._sdpObject.origin.address = plainRtpParameters.ip;
7493 this._sdpObject.origin.ipVer = plainRtpParameters.ipVersion;
7494 }
7495 }
7496 updateIceParameters(iceParameters) {
7497 logger$c.debug('updateIceParameters() [iceParameters:%o]', iceParameters);
7498 this._iceParameters = iceParameters;
7499 this._sdpObject.icelite = iceParameters.iceLite ? 'ice-lite' : undefined;
7500 for (const mediaSection of this._mediaSections) {
7501 mediaSection.setIceParameters(iceParameters);
7502 }
7503 }
7504 updateDtlsRole(role) {
7505 logger$c.debug('updateDtlsRole() [role:%s]', role);
7506 this._dtlsParameters.role = role;
7507 for (const mediaSection of this._mediaSections) {
7508 mediaSection.setDtlsRole(role);
7509 }
7510 }
7511 getNextMediaSectionIdx() {
7512 // If a closed media section is found, return its index.
7513 for (let idx = 0; idx < this._mediaSections.length; ++idx) {
7514 const mediaSection = this._mediaSections[idx];
7515 if (mediaSection.closed) {
7516 return { idx, reuseMid: mediaSection.mid };
7517 }
7518 }
7519 // If no closed media section is found, return next one.
7520 return { idx: this._mediaSections.length };
7521 }
7522 send({ offerMediaObject, reuseMid, offerRtpParameters, answerRtpParameters, codecOptions, extmapAllowMixed = false }) {
7523 const mediaSection = new MediaSection_1.AnswerMediaSection({
7524 iceParameters: this._iceParameters,
7525 iceCandidates: this._iceCandidates,
7526 dtlsParameters: this._dtlsParameters,
7527 plainRtpParameters: this._plainRtpParameters,
7528 planB: this._planB,
7529 offerMediaObject,
7530 offerRtpParameters,
7531 answerRtpParameters,
7532 codecOptions,
7533 extmapAllowMixed
7534 });
7535 // Unified-Plan with closed media section replacement.
7536 if (reuseMid) {
7537 this._replaceMediaSection(mediaSection, reuseMid);
7538 }
7539 // Unified-Plan or Plan-B with different media kind.
7540 else if (!this._midToIndex.has(mediaSection.mid)) {
7541 this._addMediaSection(mediaSection);
7542 }
7543 // Plan-B with same media kind.
7544 else {
7545 this._replaceMediaSection(mediaSection);
7546 }
7547 }
7548 receive({ mid, kind, offerRtpParameters, streamId, trackId }) {
7549 const idx = this._midToIndex.get(mid);
7550 let mediaSection;
7551 if (idx !== undefined) {
7552 mediaSection = this._mediaSections[idx];
7553 }
7554 // Unified-Plan or different media kind.
7555 if (!mediaSection) {
7556 mediaSection = new MediaSection_1.OfferMediaSection({
7557 iceParameters: this._iceParameters,
7558 iceCandidates: this._iceCandidates,
7559 dtlsParameters: this._dtlsParameters,
7560 plainRtpParameters: this._plainRtpParameters,
7561 planB: this._planB,
7562 mid,
7563 kind,
7564 offerRtpParameters,
7565 streamId,
7566 trackId
7567 });
7568 // Let's try to recycle a closed media section (if any).
7569 // NOTE: Yes, we can recycle a closed m=audio section with a new m=video.
7570 const oldMediaSection = this._mediaSections.find((m) => (m.closed));
7571 if (oldMediaSection) {
7572 this._replaceMediaSection(mediaSection, oldMediaSection.mid);
7573 }
7574 else {
7575 this._addMediaSection(mediaSection);
7576 }
7577 }
7578 // Plan-B.
7579 else {
7580 mediaSection.planBReceive({ offerRtpParameters, streamId, trackId });
7581 this._replaceMediaSection(mediaSection);
7582 }
7583 }
7584 pauseMediaSection(mid) {
7585 const mediaSection = this._findMediaSection(mid);
7586 mediaSection.pause();
7587 }
7588 resumeSendingMediaSection(mid) {
7589 const mediaSection = this._findMediaSection(mid);
7590 mediaSection.resume();
7591 }
7592 resumeReceivingMediaSection(mid) {
7593 const mediaSection = this._findMediaSection(mid);
7594 mediaSection.resume();
7595 }
7596 disableMediaSection(mid) {
7597 const mediaSection = this._findMediaSection(mid);
7598 mediaSection.disable();
7599 }
7600 /**
7601 * Closes media section. Returns true if the given MID corresponds to a m
7602 * section that has been indeed closed. False otherwise.
7603 *
7604 * NOTE: Closing the first m section is a pain since it invalidates the bundled
7605 * transport, so instead closing it we just disable it.
7606 */
7607 closeMediaSection(mid) {
7608 const mediaSection = this._findMediaSection(mid);
7609 // NOTE: Closing the first m section is a pain since it invalidates the
7610 // bundled transport, so let's avoid it.
7611 if (mid === this._firstMid) {
7612 logger$c.debug('closeMediaSection() | cannot close first media section, disabling it instead [mid:%s]', mid);
7613 this.disableMediaSection(mid);
7614 return false;
7615 }
7616 mediaSection.close();
7617 // Regenerate BUNDLE mids.
7618 this._regenerateBundleMids();
7619 return true;
7620 }
7621 muxMediaSectionSimulcast(mid, encodings) {
7622 const mediaSection = this._findMediaSection(mid);
7623 mediaSection.muxSimulcastStreams(encodings);
7624 this._replaceMediaSection(mediaSection);
7625 }
7626 planBStopReceiving({ mid, offerRtpParameters }) {
7627 const mediaSection = this._findMediaSection(mid);
7628 mediaSection.planBStopReceiving({ offerRtpParameters });
7629 this._replaceMediaSection(mediaSection);
7630 }
7631 sendSctpAssociation({ offerMediaObject }) {
7632 const mediaSection = new MediaSection_1.AnswerMediaSection({
7633 iceParameters: this._iceParameters,
7634 iceCandidates: this._iceCandidates,
7635 dtlsParameters: this._dtlsParameters,
7636 sctpParameters: this._sctpParameters,
7637 plainRtpParameters: this._plainRtpParameters,
7638 offerMediaObject
7639 });
7640 this._addMediaSection(mediaSection);
7641 }
7642 receiveSctpAssociation({ oldDataChannelSpec = false } = {}) {
7643 const mediaSection = new MediaSection_1.OfferMediaSection({
7644 iceParameters: this._iceParameters,
7645 iceCandidates: this._iceCandidates,
7646 dtlsParameters: this._dtlsParameters,
7647 sctpParameters: this._sctpParameters,
7648 plainRtpParameters: this._plainRtpParameters,
7649 mid: 'datachannel',
7650 kind: 'application',
7651 oldDataChannelSpec
7652 });
7653 this._addMediaSection(mediaSection);
7654 }
7655 getSdp() {
7656 // Increase SDP version.
7657 this._sdpObject.origin.sessionVersion++;
7658 return sdpTransform$a.write(this._sdpObject);
7659 }
7660 _addMediaSection(newMediaSection) {
7661 if (!this._firstMid) {
7662 this._firstMid = newMediaSection.mid;
7663 }
7664 // Add to the vector.
7665 this._mediaSections.push(newMediaSection);
7666 // Add to the map.
7667 this._midToIndex.set(newMediaSection.mid, this._mediaSections.length - 1);
7668 // Add to the SDP object.
7669 this._sdpObject.media.push(newMediaSection.getObject());
7670 // Regenerate BUNDLE mids.
7671 this._regenerateBundleMids();
7672 }
7673 _replaceMediaSection(newMediaSection, reuseMid) {
7674 // Store it in the map.
7675 if (typeof reuseMid === 'string') {
7676 const idx = this._midToIndex.get(reuseMid);
7677 if (idx === undefined) {
7678 throw new Error(`no media section found for reuseMid '${reuseMid}'`);
7679 }
7680 const oldMediaSection = this._mediaSections[idx];
7681 // Replace the index in the vector with the new media section.
7682 this._mediaSections[idx] = newMediaSection;
7683 // Update the map.
7684 this._midToIndex.delete(oldMediaSection.mid);
7685 this._midToIndex.set(newMediaSection.mid, idx);
7686 // Update the SDP object.
7687 this._sdpObject.media[idx] = newMediaSection.getObject();
7688 // Regenerate BUNDLE mids.
7689 this._regenerateBundleMids();
7690 }
7691 else {
7692 const idx = this._midToIndex.get(newMediaSection.mid);
7693 if (idx === undefined) {
7694 throw new Error(`no media section found with mid '${newMediaSection.mid}'`);
7695 }
7696 // Replace the index in the vector with the new media section.
7697 this._mediaSections[idx] = newMediaSection;
7698 // Update the SDP object.
7699 this._sdpObject.media[idx] = newMediaSection.getObject();
7700 }
7701 }
7702 _findMediaSection(mid) {
7703 const idx = this._midToIndex.get(mid);
7704 if (idx === undefined) {
7705 throw new Error(`no media section found with mid '${mid}'`);
7706 }
7707 return this._mediaSections[idx];
7708 }
7709 _regenerateBundleMids() {
7710 if (!this._dtlsParameters) {
7711 return;
7712 }
7713 this._sdpObject.groups[0].mids = this._mediaSections
7714 .filter((mediaSection) => !mediaSection.closed)
7715 .map((mediaSection) => mediaSection.mid)
7716 .join(' ');
7717 }
7718 }
7719 RemoteSdp$1.RemoteSdp = RemoteSdp;
7720
7721 var scalabilityModes = {};
7722
7723 Object.defineProperty(scalabilityModes, "__esModule", { value: true });
7724 scalabilityModes.parse = void 0;
7725 const ScalabilityModeRegex = new RegExp('^[LS]([1-9]\\d{0,1})T([1-9]\\d{0,1})');
7726 function parse(scalabilityMode) {
7727 const match = ScalabilityModeRegex.exec(scalabilityMode || '');
7728 if (match) {
7729 return {
7730 spatialLayers: Number(match[1]),
7731 temporalLayers: Number(match[2])
7732 };
7733 }
7734 else {
7735 return {
7736 spatialLayers: 1,
7737 temporalLayers: 1
7738 };
7739 }
7740 }
7741 scalabilityModes.parse = parse;
7742
7743 var __createBinding$c = (commonjsGlobal && commonjsGlobal.__createBinding) || (Object.create ? (function(o, m, k, k2) {
7744 if (k2 === undefined) k2 = k;
7745 var desc = Object.getOwnPropertyDescriptor(m, k);
7746 if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
7747 desc = { enumerable: true, get: function() { return m[k]; } };
7748 }
7749 Object.defineProperty(o, k2, desc);
7750 }) : (function(o, m, k, k2) {
7751 if (k2 === undefined) k2 = k;
7752 o[k2] = m[k];
7753 }));
7754 var __setModuleDefault$c = (commonjsGlobal && commonjsGlobal.__setModuleDefault) || (Object.create ? (function(o, v) {
7755 Object.defineProperty(o, "default", { enumerable: true, value: v });
7756 }) : function(o, v) {
7757 o["default"] = v;
7758 });
7759 var __importStar$c = (commonjsGlobal && commonjsGlobal.__importStar) || function (mod) {
7760 if (mod && mod.__esModule) return mod;
7761 var result = {};
7762 if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding$c(result, mod, k);
7763 __setModuleDefault$c(result, mod);
7764 return result;
7765 };
7766 Object.defineProperty(Chrome111$1, "__esModule", { value: true });
7767 Chrome111$1.Chrome111 = void 0;
7768 const sdpTransform$9 = __importStar$c(lib);
7769 const Logger_1$b = Logger$3;
7770 const utils$c = __importStar$c(utils$h);
7771 const ortc$b = __importStar$c(ortc$d);
7772 const sdpCommonUtils$9 = __importStar$c(commonUtils);
7773 const sdpUnifiedPlanUtils$5 = __importStar$c(unifiedPlanUtils);
7774 const ortcUtils$3 = __importStar$c(utils$e);
7775 const errors_1$8 = errors;
7776 const HandlerInterface_1$a = HandlerInterface$1;
7777 const RemoteSdp_1$9 = RemoteSdp$1;
7778 const scalabilityModes_1$5 = scalabilityModes;
7779 const logger$b = new Logger_1$b.Logger('Chrome111');
7780 const SCTP_NUM_STREAMS$9 = { OS: 1024, MIS: 1024 };
7781 class Chrome111 extends HandlerInterface_1$a.HandlerInterface {
7782 /**
7783 * Creates a factory function.
7784 */
7785 static createFactory() {
7786 return () => new Chrome111();
7787 }
7788 constructor() {
7789 super();
7790 // Closed flag.
7791 this._closed = false;
7792 // Map of RTCTransceivers indexed by MID.
7793 this._mapMidTransceiver = new Map();
7794 // Local stream for sending.
7795 this._sendStream = new MediaStream();
7796 // Whether a DataChannel m=application section has been created.
7797 this._hasDataChannelMediaSection = false;
7798 // Sending DataChannel id value counter. Incremented for each new DataChannel.
7799 this._nextSendSctpStreamId = 0;
7800 // Got transport local and remote parameters.
7801 this._transportReady = false;
7802 }
7803 get name() {
7804 return 'Chrome111';
7805 }
7806 close() {
7807 logger$b.debug('close()');
7808 if (this._closed) {
7809 return;
7810 }
7811 this._closed = true;
7812 // Close RTCPeerConnection.
7813 if (this._pc) {
7814 try {
7815 this._pc.close();
7816 }
7817 catch (error) { }
7818 }
7819 this.emit('@close');
7820 }
7821 async getNativeRtpCapabilities() {
7822 logger$b.debug('getNativeRtpCapabilities()');
7823 const pc = new RTCPeerConnection({
7824 iceServers: [],
7825 iceTransportPolicy: 'all',
7826 bundlePolicy: 'max-bundle',
7827 rtcpMuxPolicy: 'require',
7828 sdpSemantics: 'unified-plan'
7829 });
7830 try {
7831 pc.addTransceiver('audio');
7832 pc.addTransceiver('video');
7833 const offer = await pc.createOffer();
7834 try {
7835 pc.close();
7836 }
7837 catch (error) { }
7838 const sdpObject = sdpTransform$9.parse(offer.sdp);
7839 const nativeRtpCapabilities = sdpCommonUtils$9.extractRtpCapabilities({ sdpObject });
7840 // libwebrtc supports NACK for OPUS but doesn't announce it.
7841 ortcUtils$3.addNackSuppportForOpus(nativeRtpCapabilities);
7842 return nativeRtpCapabilities;
7843 }
7844 catch (error) {
7845 try {
7846 pc.close();
7847 }
7848 catch (error2) { }
7849 throw error;
7850 }
7851 }
7852 async getNativeSctpCapabilities() {
7853 logger$b.debug('getNativeSctpCapabilities()');
7854 return {
7855 numStreams: SCTP_NUM_STREAMS$9
7856 };
7857 }
7858 run({ direction, iceParameters, iceCandidates, dtlsParameters, sctpParameters, iceServers, iceTransportPolicy, additionalSettings, proprietaryConstraints, extendedRtpCapabilities }) {
7859 this.assertNotClosed();
7860 logger$b.debug('run()');
7861 this._direction = direction;
7862 this._remoteSdp = new RemoteSdp_1$9.RemoteSdp({
7863 iceParameters,
7864 iceCandidates,
7865 dtlsParameters,
7866 sctpParameters
7867 });
7868 this._sendingRtpParametersByKind =
7869 {
7870 audio: ortc$b.getSendingRtpParameters('audio', extendedRtpCapabilities),
7871 video: ortc$b.getSendingRtpParameters('video', extendedRtpCapabilities)
7872 };
7873 this._sendingRemoteRtpParametersByKind =
7874 {
7875 audio: ortc$b.getSendingRemoteRtpParameters('audio', extendedRtpCapabilities),
7876 video: ortc$b.getSendingRemoteRtpParameters('video', extendedRtpCapabilities)
7877 };
7878 if (dtlsParameters.role && dtlsParameters.role !== 'auto') {
7879 this._forcedLocalDtlsRole = dtlsParameters.role === 'server'
7880 ? 'client'
7881 : 'server';
7882 }
7883 this._pc = new RTCPeerConnection({
7884 iceServers: iceServers || [],
7885 iceTransportPolicy: iceTransportPolicy || 'all',
7886 bundlePolicy: 'max-bundle',
7887 rtcpMuxPolicy: 'require',
7888 sdpSemantics: 'unified-plan',
7889 ...additionalSettings
7890 }, proprietaryConstraints);
7891 this._pc.addEventListener('icegatheringstatechange', () => {
7892 this.emit('@icegatheringstatechange', this._pc.iceGatheringState);
7893 });
7894 if (this._pc.connectionState) {
7895 this._pc.addEventListener('connectionstatechange', () => {
7896 this.emit('@connectionstatechange', this._pc.connectionState);
7897 });
7898 }
7899 else {
7900 logger$b.warn('run() | pc.connectionState not supported, using pc.iceConnectionState');
7901 this._pc.addEventListener('iceconnectionstatechange', () => {
7902 switch (this._pc.iceConnectionState) {
7903 case 'checking':
7904 this.emit('@connectionstatechange', 'connecting');
7905 break;
7906 case 'connected':
7907 case 'completed':
7908 this.emit('@connectionstatechange', 'connected');
7909 break;
7910 case 'failed':
7911 this.emit('@connectionstatechange', 'failed');
7912 break;
7913 case 'disconnected':
7914 this.emit('@connectionstatechange', 'disconnected');
7915 break;
7916 case 'closed':
7917 this.emit('@connectionstatechange', 'closed');
7918 break;
7919 }
7920 });
7921 }
7922 }
7923 async updateIceServers(iceServers) {
7924 this.assertNotClosed();
7925 logger$b.debug('updateIceServers()');
7926 const configuration = this._pc.getConfiguration();
7927 configuration.iceServers = iceServers;
7928 this._pc.setConfiguration(configuration);
7929 }
7930 async restartIce(iceParameters) {
7931 this.assertNotClosed();
7932 logger$b.debug('restartIce()');
7933 // Provide the remote SDP handler with new remote ICE parameters.
7934 this._remoteSdp.updateIceParameters(iceParameters);
7935 if (!this._transportReady) {
7936 return;
7937 }
7938 if (this._direction === 'send') {
7939 const offer = await this._pc.createOffer({ iceRestart: true });
7940 logger$b.debug('restartIce() | calling pc.setLocalDescription() [offer:%o]', offer);
7941 await this._pc.setLocalDescription(offer);
7942 const answer = { type: 'answer', sdp: this._remoteSdp.getSdp() };
7943 logger$b.debug('restartIce() | calling pc.setRemoteDescription() [answer:%o]', answer);
7944 await this._pc.setRemoteDescription(answer);
7945 }
7946 else {
7947 const offer = { type: 'offer', sdp: this._remoteSdp.getSdp() };
7948 logger$b.debug('restartIce() | calling pc.setRemoteDescription() [offer:%o]', offer);
7949 await this._pc.setRemoteDescription(offer);
7950 const answer = await this._pc.createAnswer();
7951 logger$b.debug('restartIce() | calling pc.setLocalDescription() [answer:%o]', answer);
7952 await this._pc.setLocalDescription(answer);
7953 }
7954 }
7955 async getTransportStats() {
7956 this.assertNotClosed();
7957 return this._pc.getStats();
7958 }
7959 async send({ track, encodings, codecOptions, codec }) {
7960 this.assertNotClosed();
7961 this.assertSendDirection();
7962 logger$b.debug('send() [kind:%s, track.id:%s]', track.kind, track.id);
7963 if (encodings && encodings.length > 1) {
7964 encodings.forEach((encoding, idx) => {
7965 encoding.rid = `r${idx}`;
7966 });
7967 // Set rid and verify scalabilityMode in each encoding.
7968 // NOTE: Even if WebRTC allows different scalabilityMode (different number
7969 // of temporal layers) per simulcast stream, we need that those are the
7970 // same in all them, so let's pick up the highest value.
7971 // NOTE: If scalabilityMode is not given, Chrome will use L1T3.
7972 let nextRid = 1;
7973 let maxTemporalLayers = 1;
7974 for (const encoding of encodings) {
7975 const temporalLayers = encoding.scalabilityMode
7976 ? (0, scalabilityModes_1$5.parse)(encoding.scalabilityMode).temporalLayers
7977 : 3;
7978 if (temporalLayers > maxTemporalLayers) {
7979 maxTemporalLayers = temporalLayers;
7980 }
7981 }
7982 for (const encoding of encodings) {
7983 encoding.rid = `r${nextRid++}`;
7984 encoding.scalabilityMode = `L1T${maxTemporalLayers}`;
7985 }
7986 }
7987 const sendingRtpParameters = utils$c.clone(this._sendingRtpParametersByKind[track.kind]);
7988 // This may throw.
7989 sendingRtpParameters.codecs =
7990 ortc$b.reduceCodecs(sendingRtpParameters.codecs, codec);
7991 const sendingRemoteRtpParameters = utils$c.clone(this._sendingRemoteRtpParametersByKind[track.kind]);
7992 // This may throw.
7993 sendingRemoteRtpParameters.codecs =
7994 ortc$b.reduceCodecs(sendingRemoteRtpParameters.codecs, codec);
7995 const mediaSectionIdx = this._remoteSdp.getNextMediaSectionIdx();
7996 const transceiver = this._pc.addTransceiver(track, {
7997 direction: 'sendonly',
7998 streams: [this._sendStream],
7999 sendEncodings: encodings
8000 });
8001 const offer = await this._pc.createOffer();
8002 let localSdpObject = sdpTransform$9.parse(offer.sdp);
8003 if (!this._transportReady) {
8004 await this.setupTransport({
8005 localDtlsRole: this._forcedLocalDtlsRole ?? 'client',
8006 localSdpObject
8007 });
8008 }
8009 logger$b.debug('send() | calling pc.setLocalDescription() [offer:%o]', offer);
8010 await this._pc.setLocalDescription(offer);
8011 // We can now get the transceiver.mid.
8012 const localId = transceiver.mid;
8013 // Set MID.
8014 sendingRtpParameters.mid = localId;
8015 localSdpObject = sdpTransform$9.parse(this._pc.localDescription.sdp);
8016 const offerMediaObject = localSdpObject.media[mediaSectionIdx.idx];
8017 // Set RTCP CNAME.
8018 sendingRtpParameters.rtcp.cname =
8019 sdpCommonUtils$9.getCname({ offerMediaObject });
8020 // Set RTP encodings by parsing the SDP offer if no encodings are given.
8021 if (!encodings) {
8022 sendingRtpParameters.encodings =
8023 sdpUnifiedPlanUtils$5.getRtpEncodings({ offerMediaObject });
8024 }
8025 // Set RTP encodings by parsing the SDP offer and complete them with given
8026 // one if just a single encoding has been given.
8027 else if (encodings.length === 1) {
8028 const newEncodings = sdpUnifiedPlanUtils$5.getRtpEncodings({ offerMediaObject });
8029 Object.assign(newEncodings[0], encodings[0]);
8030 sendingRtpParameters.encodings = newEncodings;
8031 }
8032 // Otherwise if more than 1 encoding are given use them verbatim.
8033 else {
8034 sendingRtpParameters.encodings = encodings;
8035 }
8036 this._remoteSdp.send({
8037 offerMediaObject,
8038 reuseMid: mediaSectionIdx.reuseMid,
8039 offerRtpParameters: sendingRtpParameters,
8040 answerRtpParameters: sendingRemoteRtpParameters,
8041 codecOptions,
8042 extmapAllowMixed: true
8043 });
8044 const answer = { type: 'answer', sdp: this._remoteSdp.getSdp() };
8045 logger$b.debug('send() | calling pc.setRemoteDescription() [answer:%o]', answer);
8046 await this._pc.setRemoteDescription(answer);
8047 // Store in the map.
8048 this._mapMidTransceiver.set(localId, transceiver);
8049 return {
8050 localId,
8051 rtpParameters: sendingRtpParameters,
8052 rtpSender: transceiver.sender
8053 };
8054 }
8055 async stopSending(localId) {
8056 this.assertSendDirection();
8057 logger$b.debug('stopSending() [localId:%s]', localId);
8058 if (this._closed) {
8059 return;
8060 }
8061 const transceiver = this._mapMidTransceiver.get(localId);
8062 if (!transceiver) {
8063 throw new Error('associated RTCRtpTransceiver not found');
8064 }
8065 transceiver.sender.replaceTrack(null);
8066 this._pc.removeTrack(transceiver.sender);
8067 const mediaSectionClosed = this._remoteSdp.closeMediaSection(transceiver.mid);
8068 if (mediaSectionClosed) {
8069 try {
8070 transceiver.stop();
8071 }
8072 catch (error) { }
8073 }
8074 const offer = await this._pc.createOffer();
8075 logger$b.debug('stopSending() | calling pc.setLocalDescription() [offer:%o]', offer);
8076 await this._pc.setLocalDescription(offer);
8077 const answer = { type: 'answer', sdp: this._remoteSdp.getSdp() };
8078 logger$b.debug('stopSending() | calling pc.setRemoteDescription() [answer:%o]', answer);
8079 await this._pc.setRemoteDescription(answer);
8080 this._mapMidTransceiver.delete(localId);
8081 }
8082 async pauseSending(localId) {
8083 this.assertNotClosed();
8084 this.assertSendDirection();
8085 logger$b.debug('pauseSending() [localId:%s]', localId);
8086 const transceiver = this._mapMidTransceiver.get(localId);
8087 if (!transceiver) {
8088 throw new Error('associated RTCRtpTransceiver not found');
8089 }
8090 transceiver.direction = 'inactive';
8091 this._remoteSdp.pauseMediaSection(localId);
8092 const offer = await this._pc.createOffer();
8093 logger$b.debug('pauseSending() | calling pc.setLocalDescription() [offer:%o]', offer);
8094 await this._pc.setLocalDescription(offer);
8095 const answer = { type: 'answer', sdp: this._remoteSdp.getSdp() };
8096 logger$b.debug('pauseSending() | calling pc.setRemoteDescription() [answer:%o]', answer);
8097 await this._pc.setRemoteDescription(answer);
8098 }
8099 async resumeSending(localId) {
8100 this.assertNotClosed();
8101 this.assertSendDirection();
8102 logger$b.debug('resumeSending() [localId:%s]', localId);
8103 const transceiver = this._mapMidTransceiver.get(localId);
8104 this._remoteSdp.resumeSendingMediaSection(localId);
8105 if (!transceiver) {
8106 throw new Error('associated RTCRtpTransceiver not found');
8107 }
8108 transceiver.direction = 'sendonly';
8109 const offer = await this._pc.createOffer();
8110 logger$b.debug('resumeSending() | calling pc.setLocalDescription() [offer:%o]', offer);
8111 await this._pc.setLocalDescription(offer);
8112 const answer = { type: 'answer', sdp: this._remoteSdp.getSdp() };
8113 logger$b.debug('resumeSending() | calling pc.setRemoteDescription() [answer:%o]', answer);
8114 await this._pc.setRemoteDescription(answer);
8115 }
8116 async replaceTrack(localId, track) {
8117 this.assertNotClosed();
8118 this.assertSendDirection();
8119 if (track) {
8120 logger$b.debug('replaceTrack() [localId:%s, track.id:%s]', localId, track.id);
8121 }
8122 else {
8123 logger$b.debug('replaceTrack() [localId:%s, no track]', localId);
8124 }
8125 const transceiver = this._mapMidTransceiver.get(localId);
8126 if (!transceiver) {
8127 throw new Error('associated RTCRtpTransceiver not found');
8128 }
8129 await transceiver.sender.replaceTrack(track);
8130 }
8131 async setMaxSpatialLayer(localId, spatialLayer) {
8132 this.assertNotClosed();
8133 this.assertSendDirection();
8134 logger$b.debug('setMaxSpatialLayer() [localId:%s, spatialLayer:%s]', localId, spatialLayer);
8135 const transceiver = this._mapMidTransceiver.get(localId);
8136 if (!transceiver) {
8137 throw new Error('associated RTCRtpTransceiver not found');
8138 }
8139 const parameters = transceiver.sender.getParameters();
8140 parameters.encodings.forEach((encoding, idx) => {
8141 if (idx <= spatialLayer) {
8142 encoding.active = true;
8143 }
8144 else {
8145 encoding.active = false;
8146 }
8147 });
8148 await transceiver.sender.setParameters(parameters);
8149 this._remoteSdp.muxMediaSectionSimulcast(localId, parameters.encodings);
8150 const offer = await this._pc.createOffer();
8151 logger$b.debug('setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]', offer);
8152 await this._pc.setLocalDescription(offer);
8153 const answer = { type: 'answer', sdp: this._remoteSdp.getSdp() };
8154 logger$b.debug('setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]', answer);
8155 await this._pc.setRemoteDescription(answer);
8156 }
8157 async setRtpEncodingParameters(localId, params) {
8158 this.assertNotClosed();
8159 this.assertSendDirection();
8160 logger$b.debug('setRtpEncodingParameters() [localId:%s, params:%o]', localId, params);
8161 const transceiver = this._mapMidTransceiver.get(localId);
8162 if (!transceiver) {
8163 throw new Error('associated RTCRtpTransceiver not found');
8164 }
8165 const parameters = transceiver.sender.getParameters();
8166 parameters.encodings.forEach((encoding, idx) => {
8167 parameters.encodings[idx] = { ...encoding, ...params };
8168 });
8169 await transceiver.sender.setParameters(parameters);
8170 this._remoteSdp.muxMediaSectionSimulcast(localId, parameters.encodings);
8171 const offer = await this._pc.createOffer();
8172 logger$b.debug('setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]', offer);
8173 await this._pc.setLocalDescription(offer);
8174 const answer = { type: 'answer', sdp: this._remoteSdp.getSdp() };
8175 logger$b.debug('setRtpEncodingParameters() | calling pc.setRemoteDescription() [answer:%o]', answer);
8176 await this._pc.setRemoteDescription(answer);
8177 }
8178 async getSenderStats(localId) {
8179 this.assertNotClosed();
8180 this.assertSendDirection();
8181 const transceiver = this._mapMidTransceiver.get(localId);
8182 if (!transceiver) {
8183 throw new Error('associated RTCRtpTransceiver not found');
8184 }
8185 return transceiver.sender.getStats();
8186 }
8187 async sendDataChannel({ ordered, maxPacketLifeTime, maxRetransmits, label, protocol }) {
8188 this.assertNotClosed();
8189 this.assertSendDirection();
8190 const options = {
8191 negotiated: true,
8192 id: this._nextSendSctpStreamId,
8193 ordered,
8194 maxPacketLifeTime,
8195 maxRetransmits,
8196 protocol
8197 };
8198 logger$b.debug('sendDataChannel() [options:%o]', options);
8199 const dataChannel = this._pc.createDataChannel(label, options);
8200 // Increase next id.
8201 this._nextSendSctpStreamId =
8202 ++this._nextSendSctpStreamId % SCTP_NUM_STREAMS$9.MIS;
8203 // If this is the first DataChannel we need to create the SDP answer with
8204 // m=application section.
8205 if (!this._hasDataChannelMediaSection) {
8206 const offer = await this._pc.createOffer();
8207 const localSdpObject = sdpTransform$9.parse(offer.sdp);
8208 const offerMediaObject = localSdpObject.media
8209 .find((m) => m.type === 'application');
8210 if (!this._transportReady) {
8211 await this.setupTransport({
8212 localDtlsRole: this._forcedLocalDtlsRole ?? 'client',
8213 localSdpObject
8214 });
8215 }
8216 logger$b.debug('sendDataChannel() | calling pc.setLocalDescription() [offer:%o]', offer);
8217 await this._pc.setLocalDescription(offer);
8218 this._remoteSdp.sendSctpAssociation({ offerMediaObject });
8219 const answer = { type: 'answer', sdp: this._remoteSdp.getSdp() };
8220 logger$b.debug('sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]', answer);
8221 await this._pc.setRemoteDescription(answer);
8222 this._hasDataChannelMediaSection = true;
8223 }
8224 const sctpStreamParameters = {
8225 streamId: options.id,
8226 ordered: options.ordered,
8227 maxPacketLifeTime: options.maxPacketLifeTime,
8228 maxRetransmits: options.maxRetransmits
8229 };
8230 return { dataChannel, sctpStreamParameters };
8231 }
8232 async receive(optionsList) {
8233 this.assertNotClosed();
8234 this.assertRecvDirection();
8235 const results = [];
8236 const mapLocalId = new Map();
8237 for (const options of optionsList) {
8238 const { trackId, kind, rtpParameters, streamId } = options;
8239 logger$b.debug('receive() [trackId:%s, kind:%s]', trackId, kind);
8240 const localId = rtpParameters.mid || String(this._mapMidTransceiver.size);
8241 mapLocalId.set(trackId, localId);
8242 this._remoteSdp.receive({
8243 mid: localId,
8244 kind,
8245 offerRtpParameters: rtpParameters,
8246 streamId: streamId || rtpParameters.rtcp.cname,
8247 trackId
8248 });
8249 }
8250 const offer = { type: 'offer', sdp: this._remoteSdp.getSdp() };
8251 logger$b.debug('receive() | calling pc.setRemoteDescription() [offer:%o]', offer);
8252 await this._pc.setRemoteDescription(offer);
8253 let answer = await this._pc.createAnswer();
8254 const localSdpObject = sdpTransform$9.parse(answer.sdp);
8255 for (const options of optionsList) {
8256 const { trackId, rtpParameters } = options;
8257 const localId = mapLocalId.get(trackId);
8258 const answerMediaObject = localSdpObject.media
8259 .find((m) => String(m.mid) === localId);
8260 // May need to modify codec parameters in the answer based on codec
8261 // parameters in the offer.
8262 sdpCommonUtils$9.applyCodecParameters({
8263 offerRtpParameters: rtpParameters,
8264 answerMediaObject
8265 });
8266 }
8267 answer = { type: 'answer', sdp: sdpTransform$9.write(localSdpObject) };
8268 if (!this._transportReady) {
8269 await this.setupTransport({
8270 localDtlsRole: this._forcedLocalDtlsRole ?? 'client',
8271 localSdpObject
8272 });
8273 }
8274 logger$b.debug('receive() | calling pc.setLocalDescription() [answer:%o]', answer);
8275 await this._pc.setLocalDescription(answer);
8276 for (const options of optionsList) {
8277 const { trackId } = options;
8278 const localId = mapLocalId.get(trackId);
8279 const transceiver = this._pc.getTransceivers()
8280 .find((t) => t.mid === localId);
8281 if (!transceiver) {
8282 throw new Error('new RTCRtpTransceiver not found');
8283 }
8284 else {
8285 // Store in the map.
8286 this._mapMidTransceiver.set(localId, transceiver);
8287 results.push({
8288 localId,
8289 track: transceiver.receiver.track,
8290 rtpReceiver: transceiver.receiver
8291 });
8292 }
8293 }
8294 return results;
8295 }
8296 async stopReceiving(localIds) {
8297 this.assertRecvDirection();
8298 if (this._closed) {
8299 return;
8300 }
8301 for (const localId of localIds) {
8302 logger$b.debug('stopReceiving() [localId:%s]', localId);
8303 const transceiver = this._mapMidTransceiver.get(localId);
8304 if (!transceiver) {
8305 throw new Error('associated RTCRtpTransceiver not found');
8306 }
8307 this._remoteSdp.closeMediaSection(transceiver.mid);
8308 }
8309 const offer = { type: 'offer', sdp: this._remoteSdp.getSdp() };
8310 logger$b.debug('stopReceiving() | calling pc.setRemoteDescription() [offer:%o]', offer);
8311 await this._pc.setRemoteDescription(offer);
8312 const answer = await this._pc.createAnswer();
8313 logger$b.debug('stopReceiving() | calling pc.setLocalDescription() [answer:%o]', answer);
8314 await this._pc.setLocalDescription(answer);
8315 for (const localId of localIds) {
8316 this._mapMidTransceiver.delete(localId);
8317 }
8318 }
8319 async pauseReceiving(localIds) {
8320 this.assertNotClosed();
8321 this.assertRecvDirection();
8322 for (const localId of localIds) {
8323 logger$b.debug('pauseReceiving() [localId:%s]', localId);
8324 const transceiver = this._mapMidTransceiver.get(localId);
8325 if (!transceiver) {
8326 throw new Error('associated RTCRtpTransceiver not found');
8327 }
8328 transceiver.direction = 'inactive';
8329 this._remoteSdp.pauseMediaSection(localId);
8330 }
8331 const offer = { type: 'offer', sdp: this._remoteSdp.getSdp() };
8332 logger$b.debug('pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]', offer);
8333 await this._pc.setRemoteDescription(offer);
8334 const answer = await this._pc.createAnswer();
8335 logger$b.debug('pauseReceiving() | calling pc.setLocalDescription() [answer:%o]', answer);
8336 await this._pc.setLocalDescription(answer);
8337 }
8338 async resumeReceiving(localIds) {
8339 this.assertNotClosed();
8340 this.assertRecvDirection();
8341 for (const localId of localIds) {
8342 logger$b.debug('resumeReceiving() [localId:%s]', localId);
8343 const transceiver = this._mapMidTransceiver.get(localId);
8344 if (!transceiver) {
8345 throw new Error('associated RTCRtpTransceiver not found');
8346 }
8347 transceiver.direction = 'recvonly';
8348 this._remoteSdp.resumeReceivingMediaSection(localId);
8349 }
8350 const offer = { type: 'offer', sdp: this._remoteSdp.getSdp() };
8351 logger$b.debug('resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]', offer);
8352 await this._pc.setRemoteDescription(offer);
8353 const answer = await this._pc.createAnswer();
8354 logger$b.debug('resumeReceiving() | calling pc.setLocalDescription() [answer:%o]', answer);
8355 await this._pc.setLocalDescription(answer);
8356 }
8357 async getReceiverStats(localId) {
8358 this.assertNotClosed();
8359 this.assertRecvDirection();
8360 const transceiver = this._mapMidTransceiver.get(localId);
8361 if (!transceiver) {
8362 throw new Error('associated RTCRtpTransceiver not found');
8363 }
8364 return transceiver.receiver.getStats();
8365 }
8366 async receiveDataChannel({ sctpStreamParameters, label, protocol }) {
8367 this.assertNotClosed();
8368 this.assertRecvDirection();
8369 const { streamId, ordered, maxPacketLifeTime, maxRetransmits } = sctpStreamParameters;
8370 const options = {
8371 negotiated: true,
8372 id: streamId,
8373 ordered,
8374 maxPacketLifeTime,
8375 maxRetransmits,
8376 protocol
8377 };
8378 logger$b.debug('receiveDataChannel() [options:%o]', options);
8379 const dataChannel = this._pc.createDataChannel(label, options);
8380 // If this is the first DataChannel we need to create the SDP offer with
8381 // m=application section.
8382 if (!this._hasDataChannelMediaSection) {
8383 this._remoteSdp.receiveSctpAssociation();
8384 const offer = { type: 'offer', sdp: this._remoteSdp.getSdp() };
8385 logger$b.debug('receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]', offer);
8386 await this._pc.setRemoteDescription(offer);
8387 const answer = await this._pc.createAnswer();
8388 if (!this._transportReady) {
8389 const localSdpObject = sdpTransform$9.parse(answer.sdp);
8390 await this.setupTransport({
8391 localDtlsRole: this._forcedLocalDtlsRole ?? 'client',
8392 localSdpObject
8393 });
8394 }
8395 logger$b.debug('receiveDataChannel() | calling pc.setRemoteDescription() [answer:%o]', answer);
8396 await this._pc.setLocalDescription(answer);
8397 this._hasDataChannelMediaSection = true;
8398 }
8399 return { dataChannel };
8400 }
8401 async setupTransport({ localDtlsRole, localSdpObject }) {
8402 if (!localSdpObject) {
8403 localSdpObject = sdpTransform$9.parse(this._pc.localDescription.sdp);
8404 }
8405 // Get our local DTLS parameters.
8406 const dtlsParameters = sdpCommonUtils$9.extractDtlsParameters({ sdpObject: localSdpObject });
8407 // Set our DTLS role.
8408 dtlsParameters.role = localDtlsRole;
8409 // Update the remote DTLS role in the SDP.
8410 this._remoteSdp.updateDtlsRole(localDtlsRole === 'client' ? 'server' : 'client');
8411 // Need to tell the remote transport about our parameters.
8412 await new Promise((resolve, reject) => {
8413 this.safeEmit('@connect', { dtlsParameters }, resolve, reject);
8414 });
8415 this._transportReady = true;
8416 }
8417 assertNotClosed() {
8418 if (this._closed) {
8419 throw new errors_1$8.InvalidStateError('method called in a closed handler');
8420 }
8421 }
8422 assertSendDirection() {
8423 if (this._direction !== 'send') {
8424 throw new Error('method can just be called for handlers with "send" direction');
8425 }
8426 }
8427 assertRecvDirection() {
8428 if (this._direction !== 'recv') {
8429 throw new Error('method can just be called for handlers with "recv" direction');
8430 }
8431 }
8432 }
8433 Chrome111$1.Chrome111 = Chrome111;
8434
8435 var Chrome74$1 = {};
8436
8437 var __createBinding$b = (commonjsGlobal && commonjsGlobal.__createBinding) || (Object.create ? (function(o, m, k, k2) {
8438 if (k2 === undefined) k2 = k;
8439 var desc = Object.getOwnPropertyDescriptor(m, k);
8440 if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
8441 desc = { enumerable: true, get: function() { return m[k]; } };
8442 }
8443 Object.defineProperty(o, k2, desc);
8444 }) : (function(o, m, k, k2) {
8445 if (k2 === undefined) k2 = k;
8446 o[k2] = m[k];
8447 }));
8448 var __setModuleDefault$b = (commonjsGlobal && commonjsGlobal.__setModuleDefault) || (Object.create ? (function(o, v) {
8449 Object.defineProperty(o, "default", { enumerable: true, value: v });
8450 }) : function(o, v) {
8451 o["default"] = v;
8452 });
8453 var __importStar$b = (commonjsGlobal && commonjsGlobal.__importStar) || function (mod) {
8454 if (mod && mod.__esModule) return mod;
8455 var result = {};
8456 if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding$b(result, mod, k);
8457 __setModuleDefault$b(result, mod);
8458 return result;
8459 };
8460 Object.defineProperty(Chrome74$1, "__esModule", { value: true });
8461 Chrome74$1.Chrome74 = void 0;
8462 const sdpTransform$8 = __importStar$b(lib);
8463 const Logger_1$a = Logger$3;
8464 const utils$b = __importStar$b(utils$h);
8465 const ortc$a = __importStar$b(ortc$d);
8466 const sdpCommonUtils$8 = __importStar$b(commonUtils);
8467 const sdpUnifiedPlanUtils$4 = __importStar$b(unifiedPlanUtils);
8468 const ortcUtils$2 = __importStar$b(utils$e);
8469 const errors_1$7 = errors;
8470 const HandlerInterface_1$9 = HandlerInterface$1;
8471 const RemoteSdp_1$8 = RemoteSdp$1;
8472 const scalabilityModes_1$4 = scalabilityModes;
8473 const logger$a = new Logger_1$a.Logger('Chrome74');
8474 const SCTP_NUM_STREAMS$8 = { OS: 1024, MIS: 1024 };
8475 class Chrome74 extends HandlerInterface_1$9.HandlerInterface {
8476 /**
8477 * Creates a factory function.
8478 */
8479 static createFactory() {
8480 return () => new Chrome74();
8481 }
8482 constructor() {
8483 super();
8484 // Closed flag.
8485 this._closed = false;
8486 // Map of RTCTransceivers indexed by MID.
8487 this._mapMidTransceiver = new Map();
8488 // Local stream for sending.
8489 this._sendStream = new MediaStream();
8490 // Whether a DataChannel m=application section has been created.
8491 this._hasDataChannelMediaSection = false;
8492 // Sending DataChannel id value counter. Incremented for each new DataChannel.
8493 this._nextSendSctpStreamId = 0;
8494 // Got transport local and remote parameters.
8495 this._transportReady = false;
8496 }
8497 get name() {
8498 return 'Chrome74';
8499 }
8500 close() {
8501 logger$a.debug('close()');
8502 if (this._closed) {
8503 return;
8504 }
8505 this._closed = true;
8506 // Close RTCPeerConnection.
8507 if (this._pc) {
8508 try {
8509 this._pc.close();
8510 }
8511 catch (error) { }
8512 }
8513 this.emit('@close');
8514 }
8515 async getNativeRtpCapabilities() {
8516 logger$a.debug('getNativeRtpCapabilities()');
8517 const pc = new RTCPeerConnection({
8518 iceServers: [],
8519 iceTransportPolicy: 'all',
8520 bundlePolicy: 'max-bundle',
8521 rtcpMuxPolicy: 'require',
8522 sdpSemantics: 'unified-plan'
8523 });
8524 try {
8525 pc.addTransceiver('audio');
8526 pc.addTransceiver('video');
8527 const offer = await pc.createOffer();
8528 try {
8529 pc.close();
8530 }
8531 catch (error) { }
8532 const sdpObject = sdpTransform$8.parse(offer.sdp);
8533 const nativeRtpCapabilities = sdpCommonUtils$8.extractRtpCapabilities({ sdpObject });
8534 // libwebrtc supports NACK for OPUS but doesn't announce it.
8535 ortcUtils$2.addNackSuppportForOpus(nativeRtpCapabilities);
8536 return nativeRtpCapabilities;
8537 }
8538 catch (error) {
8539 try {
8540 pc.close();
8541 }
8542 catch (error2) { }
8543 throw error;
8544 }
8545 }
8546 async getNativeSctpCapabilities() {
8547 logger$a.debug('getNativeSctpCapabilities()');
8548 return {
8549 numStreams: SCTP_NUM_STREAMS$8
8550 };
8551 }
8552 run({ direction, iceParameters, iceCandidates, dtlsParameters, sctpParameters, iceServers, iceTransportPolicy, additionalSettings, proprietaryConstraints, extendedRtpCapabilities }) {
8553 logger$a.debug('run()');
8554 this._direction = direction;
8555 this._remoteSdp = new RemoteSdp_1$8.RemoteSdp({
8556 iceParameters,
8557 iceCandidates,
8558 dtlsParameters,
8559 sctpParameters
8560 });
8561 this._sendingRtpParametersByKind =
8562 {
8563 audio: ortc$a.getSendingRtpParameters('audio', extendedRtpCapabilities),
8564 video: ortc$a.getSendingRtpParameters('video', extendedRtpCapabilities)
8565 };
8566 this._sendingRemoteRtpParametersByKind =
8567 {
8568 audio: ortc$a.getSendingRemoteRtpParameters('audio', extendedRtpCapabilities),
8569 video: ortc$a.getSendingRemoteRtpParameters('video', extendedRtpCapabilities)
8570 };
8571 if (dtlsParameters.role && dtlsParameters.role !== 'auto') {
8572 this._forcedLocalDtlsRole = dtlsParameters.role === 'server'
8573 ? 'client'
8574 : 'server';
8575 }
8576 this._pc = new RTCPeerConnection({
8577 iceServers: iceServers || [],
8578 iceTransportPolicy: iceTransportPolicy || 'all',
8579 bundlePolicy: 'max-bundle',
8580 rtcpMuxPolicy: 'require',
8581 sdpSemantics: 'unified-plan',
8582 ...additionalSettings
8583 }, proprietaryConstraints);
8584 this._pc.addEventListener('icegatheringstatechange', () => {
8585 this.emit('@icegatheringstatechange', this._pc.iceGatheringState);
8586 });
8587 if (this._pc.connectionState) {
8588 this._pc.addEventListener('connectionstatechange', () => {
8589 this.emit('@connectionstatechange', this._pc.connectionState);
8590 });
8591 }
8592 else {
8593 logger$a.warn('run() | pc.connectionState not supported, using pc.iceConnectionState');
8594 this._pc.addEventListener('iceconnectionstatechange', () => {
8595 switch (this._pc.iceConnectionState) {
8596 case 'checking':
8597 this.emit('@connectionstatechange', 'connecting');
8598 break;
8599 case 'connected':
8600 case 'completed':
8601 this.emit('@connectionstatechange', 'connected');
8602 break;
8603 case 'failed':
8604 this.emit('@connectionstatechange', 'failed');
8605 break;
8606 case 'disconnected':
8607 this.emit('@connectionstatechange', 'disconnected');
8608 break;
8609 case 'closed':
8610 this.emit('@connectionstatechange', 'closed');
8611 break;
8612 }
8613 });
8614 }
8615 }
8616 async updateIceServers(iceServers) {
8617 this.assertNotClosed();
8618 logger$a.debug('updateIceServers()');
8619 const configuration = this._pc.getConfiguration();
8620 configuration.iceServers = iceServers;
8621 this._pc.setConfiguration(configuration);
8622 }
8623 async restartIce(iceParameters) {
8624 this.assertNotClosed();
8625 logger$a.debug('restartIce()');
8626 // Provide the remote SDP handler with new remote ICE parameters.
8627 this._remoteSdp.updateIceParameters(iceParameters);
8628 if (!this._transportReady) {
8629 return;
8630 }
8631 if (this._direction === 'send') {
8632 const offer = await this._pc.createOffer({ iceRestart: true });
8633 logger$a.debug('restartIce() | calling pc.setLocalDescription() [offer:%o]', offer);
8634 await this._pc.setLocalDescription(offer);
8635 const answer = { type: 'answer', sdp: this._remoteSdp.getSdp() };
8636 logger$a.debug('restartIce() | calling pc.setRemoteDescription() [answer:%o]', answer);
8637 await this._pc.setRemoteDescription(answer);
8638 }
8639 else {
8640 const offer = { type: 'offer', sdp: this._remoteSdp.getSdp() };
8641 logger$a.debug('restartIce() | calling pc.setRemoteDescription() [offer:%o]', offer);
8642 await this._pc.setRemoteDescription(offer);
8643 const answer = await this._pc.createAnswer();
8644 logger$a.debug('restartIce() | calling pc.setLocalDescription() [answer:%o]', answer);
8645 await this._pc.setLocalDescription(answer);
8646 }
8647 }
8648 async getTransportStats() {
8649 this.assertNotClosed();
8650 return this._pc.getStats();
8651 }
8652 async send({ track, encodings, codecOptions, codec }) {
8653 this.assertNotClosed();
8654 this.assertSendDirection();
8655 logger$a.debug('send() [kind:%s, track.id:%s]', track.kind, track.id);
8656 if (encodings && encodings.length > 1) {
8657 encodings.forEach((encoding, idx) => {
8658 encoding.rid = `r${idx}`;
8659 });
8660 }
8661 const sendingRtpParameters = utils$b.clone(this._sendingRtpParametersByKind[track.kind]);
8662 // This may throw.
8663 sendingRtpParameters.codecs =
8664 ortc$a.reduceCodecs(sendingRtpParameters.codecs, codec);
8665 const sendingRemoteRtpParameters = utils$b.clone(this._sendingRemoteRtpParametersByKind[track.kind]);
8666 // This may throw.
8667 sendingRemoteRtpParameters.codecs =
8668 ortc$a.reduceCodecs(sendingRemoteRtpParameters.codecs, codec);
8669 const mediaSectionIdx = this._remoteSdp.getNextMediaSectionIdx();
8670 const transceiver = this._pc.addTransceiver(track, {
8671 direction: 'sendonly',
8672 streams: [this._sendStream],
8673 sendEncodings: encodings
8674 });
8675 let offer = await this._pc.createOffer();
8676 let localSdpObject = sdpTransform$8.parse(offer.sdp);
8677 let offerMediaObject;
8678 if (!this._transportReady) {
8679 await this.setupTransport({
8680 localDtlsRole: this._forcedLocalDtlsRole ?? 'client',
8681 localSdpObject
8682 });
8683 }
8684 // Special case for VP9 with SVC.
8685 let hackVp9Svc = false;
8686 const layers = (0, scalabilityModes_1$4.parse)((encodings || [{}])[0].scalabilityMode);
8687 if (encodings &&
8688 encodings.length === 1 &&
8689 layers.spatialLayers > 1 &&
8690 sendingRtpParameters.codecs[0].mimeType.toLowerCase() === 'video/vp9') {
8691 logger$a.debug('send() | enabling legacy simulcast for VP9 SVC');
8692 hackVp9Svc = true;
8693 localSdpObject = sdpTransform$8.parse(offer.sdp);
8694 offerMediaObject = localSdpObject.media[mediaSectionIdx.idx];
8695 sdpUnifiedPlanUtils$4.addLegacySimulcast({
8696 offerMediaObject,
8697 numStreams: layers.spatialLayers
8698 });
8699 offer = { type: 'offer', sdp: sdpTransform$8.write(localSdpObject) };
8700 }
8701 logger$a.debug('send() | calling pc.setLocalDescription() [offer:%o]', offer);
8702 await this._pc.setLocalDescription(offer);
8703 // We can now get the transceiver.mid.
8704 const localId = transceiver.mid;
8705 // Set MID.
8706 sendingRtpParameters.mid = localId;
8707 localSdpObject = sdpTransform$8.parse(this._pc.localDescription.sdp);
8708 offerMediaObject = localSdpObject.media[mediaSectionIdx.idx];
8709 // Set RTCP CNAME.
8710 sendingRtpParameters.rtcp.cname =
8711 sdpCommonUtils$8.getCname({ offerMediaObject });
8712 // Set RTP encodings by parsing the SDP offer if no encodings are given.
8713 if (!encodings) {
8714 sendingRtpParameters.encodings =
8715 sdpUnifiedPlanUtils$4.getRtpEncodings({ offerMediaObject });
8716 }
8717 // Set RTP encodings by parsing the SDP offer and complete them with given
8718 // one if just a single encoding has been given.
8719 else if (encodings.length === 1) {
8720 let newEncodings = sdpUnifiedPlanUtils$4.getRtpEncodings({ offerMediaObject });
8721 Object.assign(newEncodings[0], encodings[0]);
8722 // Hack for VP9 SVC.
8723 if (hackVp9Svc) {
8724 newEncodings = [newEncodings[0]];
8725 }
8726 sendingRtpParameters.encodings = newEncodings;
8727 }
8728 // Otherwise if more than 1 encoding are given use them verbatim.
8729 else {
8730 sendingRtpParameters.encodings = encodings;
8731 }
8732 // If VP8 or H264 and there is effective simulcast, add scalabilityMode to
8733 // each encoding.
8734 if (sendingRtpParameters.encodings.length > 1 &&
8735 (sendingRtpParameters.codecs[0].mimeType.toLowerCase() === 'video/vp8' ||
8736 sendingRtpParameters.codecs[0].mimeType.toLowerCase() === 'video/h264')) {
8737 for (const encoding of sendingRtpParameters.encodings) {
8738 if (encoding.scalabilityMode) {
8739 encoding.scalabilityMode = `L1T${layers.temporalLayers}`;
8740 }
8741 else {
8742 encoding.scalabilityMode = 'L1T3';
8743 }
8744 }
8745 }
8746 this._remoteSdp.send({
8747 offerMediaObject,
8748 reuseMid: mediaSectionIdx.reuseMid,
8749 offerRtpParameters: sendingRtpParameters,
8750 answerRtpParameters: sendingRemoteRtpParameters,
8751 codecOptions,
8752 extmapAllowMixed: true
8753 });
8754 const answer = { type: 'answer', sdp: this._remoteSdp.getSdp() };
8755 logger$a.debug('send() | calling pc.setRemoteDescription() [answer:%o]', answer);
8756 await this._pc.setRemoteDescription(answer);
8757 // Store in the map.
8758 this._mapMidTransceiver.set(localId, transceiver);
8759 return {
8760 localId,
8761 rtpParameters: sendingRtpParameters,
8762 rtpSender: transceiver.sender
8763 };
8764 }
8765 async stopSending(localId) {
8766 this.assertSendDirection();
8767 logger$a.debug('stopSending() [localId:%s]', localId);
8768 if (this._closed) {
8769 return;
8770 }
8771 const transceiver = this._mapMidTransceiver.get(localId);
8772 if (!transceiver) {
8773 throw new Error('associated RTCRtpTransceiver not found');
8774 }
8775 transceiver.sender.replaceTrack(null);
8776 this._pc.removeTrack(transceiver.sender);
8777 const mediaSectionClosed = this._remoteSdp.closeMediaSection(transceiver.mid);
8778 if (mediaSectionClosed) {
8779 try {
8780 transceiver.stop();
8781 }
8782 catch (error) { }
8783 }
8784 const offer = await this._pc.createOffer();
8785 logger$a.debug('stopSending() | calling pc.setLocalDescription() [offer:%o]', offer);
8786 await this._pc.setLocalDescription(offer);
8787 const answer = { type: 'answer', sdp: this._remoteSdp.getSdp() };
8788 logger$a.debug('stopSending() | calling pc.setRemoteDescription() [answer:%o]', answer);
8789 await this._pc.setRemoteDescription(answer);
8790 this._mapMidTransceiver.delete(localId);
8791 }
8792 async pauseSending(localId) {
8793 this.assertNotClosed();
8794 this.assertSendDirection();
8795 logger$a.debug('pauseSending() [localId:%s]', localId);
8796 const transceiver = this._mapMidTransceiver.get(localId);
8797 if (!transceiver) {
8798 throw new Error('associated RTCRtpTransceiver not found');
8799 }
8800 transceiver.direction = 'inactive';
8801 this._remoteSdp.pauseMediaSection(localId);
8802 const offer = await this._pc.createOffer();
8803 logger$a.debug('pauseSending() | calling pc.setLocalDescription() [offer:%o]', offer);
8804 await this._pc.setLocalDescription(offer);
8805 const answer = { type: 'answer', sdp: this._remoteSdp.getSdp() };
8806 logger$a.debug('pauseSending() | calling pc.setRemoteDescription() [answer:%o]', answer);
8807 await this._pc.setRemoteDescription(answer);
8808 }
8809 async resumeSending(localId) {
8810 this.assertNotClosed();
8811 this.assertSendDirection();
8812 logger$a.debug('resumeSending() [localId:%s]', localId);
8813 const transceiver = this._mapMidTransceiver.get(localId);
8814 this._remoteSdp.resumeSendingMediaSection(localId);
8815 if (!transceiver) {
8816 throw new Error('associated RTCRtpTransceiver not found');
8817 }
8818 transceiver.direction = 'sendonly';
8819 const offer = await this._pc.createOffer();
8820 logger$a.debug('resumeSending() | calling pc.setLocalDescription() [offer:%o]', offer);
8821 await this._pc.setLocalDescription(offer);
8822 const answer = { type: 'answer', sdp: this._remoteSdp.getSdp() };
8823 logger$a.debug('resumeSending() | calling pc.setRemoteDescription() [answer:%o]', answer);
8824 await this._pc.setRemoteDescription(answer);
8825 }
8826 async replaceTrack(localId, track) {
8827 this.assertNotClosed();
8828 this.assertSendDirection();
8829 if (track) {
8830 logger$a.debug('replaceTrack() [localId:%s, track.id:%s]', localId, track.id);
8831 }
8832 else {
8833 logger$a.debug('replaceTrack() [localId:%s, no track]', localId);
8834 }
8835 const transceiver = this._mapMidTransceiver.get(localId);
8836 if (!transceiver) {
8837 throw new Error('associated RTCRtpTransceiver not found');
8838 }
8839 await transceiver.sender.replaceTrack(track);
8840 }
8841 async setMaxSpatialLayer(localId, spatialLayer) {
8842 this.assertNotClosed();
8843 this.assertSendDirection();
8844 logger$a.debug('setMaxSpatialLayer() [localId:%s, spatialLayer:%s]', localId, spatialLayer);
8845 const transceiver = this._mapMidTransceiver.get(localId);
8846 if (!transceiver) {
8847 throw new Error('associated RTCRtpTransceiver not found');
8848 }
8849 const parameters = transceiver.sender.getParameters();
8850 parameters.encodings.forEach((encoding, idx) => {
8851 if (idx <= spatialLayer) {
8852 encoding.active = true;
8853 }
8854 else {
8855 encoding.active = false;
8856 }
8857 });
8858 await transceiver.sender.setParameters(parameters);
8859 this._remoteSdp.muxMediaSectionSimulcast(localId, parameters.encodings);
8860 const offer = await this._pc.createOffer();
8861 logger$a.debug('setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]', offer);
8862 await this._pc.setLocalDescription(offer);
8863 const answer = { type: 'answer', sdp: this._remoteSdp.getSdp() };
8864 logger$a.debug('setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]', answer);
8865 await this._pc.setRemoteDescription(answer);
8866 }
8867 async setRtpEncodingParameters(localId, params) {
8868 this.assertNotClosed();
8869 this.assertSendDirection();
8870 logger$a.debug('setRtpEncodingParameters() [localId:%s, params:%o]', localId, params);
8871 const transceiver = this._mapMidTransceiver.get(localId);
8872 if (!transceiver) {
8873 throw new Error('associated RTCRtpTransceiver not found');
8874 }
8875 const parameters = transceiver.sender.getParameters();
8876 parameters.encodings.forEach((encoding, idx) => {
8877 parameters.encodings[idx] = { ...encoding, ...params };
8878 });
8879 await transceiver.sender.setParameters(parameters);
8880 this._remoteSdp.muxMediaSectionSimulcast(localId, parameters.encodings);
8881 const offer = await this._pc.createOffer();
8882 logger$a.debug('setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]', offer);
8883 await this._pc.setLocalDescription(offer);
8884 const answer = { type: 'answer', sdp: this._remoteSdp.getSdp() };
8885 logger$a.debug('setRtpEncodingParameters() | calling pc.setRemoteDescription() [answer:%o]', answer);
8886 await this._pc.setRemoteDescription(answer);
8887 }
8888 async getSenderStats(localId) {
8889 this.assertNotClosed();
8890 this.assertSendDirection();
8891 const transceiver = this._mapMidTransceiver.get(localId);
8892 if (!transceiver) {
8893 throw new Error('associated RTCRtpTransceiver not found');
8894 }
8895 return transceiver.sender.getStats();
8896 }
8897 async sendDataChannel({ ordered, maxPacketLifeTime, maxRetransmits, label, protocol }) {
8898 this.assertNotClosed();
8899 this.assertSendDirection();
8900 const options = {
8901 negotiated: true,
8902 id: this._nextSendSctpStreamId,
8903 ordered,
8904 maxPacketLifeTime,
8905 maxRetransmits,
8906 protocol
8907 };
8908 logger$a.debug('sendDataChannel() [options:%o]', options);
8909 const dataChannel = this._pc.createDataChannel(label, options);
8910 // Increase next id.
8911 this._nextSendSctpStreamId =
8912 ++this._nextSendSctpStreamId % SCTP_NUM_STREAMS$8.MIS;
8913 // If this is the first DataChannel we need to create the SDP answer with
8914 // m=application section.
8915 if (!this._hasDataChannelMediaSection) {
8916 const offer = await this._pc.createOffer();
8917 const localSdpObject = sdpTransform$8.parse(offer.sdp);
8918 const offerMediaObject = localSdpObject.media
8919 .find((m) => m.type === 'application');
8920 if (!this._transportReady) {
8921 await this.setupTransport({
8922 localDtlsRole: this._forcedLocalDtlsRole ?? 'client',
8923 localSdpObject
8924 });
8925 }
8926 logger$a.debug('sendDataChannel() | calling pc.setLocalDescription() [offer:%o]', offer);
8927 await this._pc.setLocalDescription(offer);
8928 this._remoteSdp.sendSctpAssociation({ offerMediaObject });
8929 const answer = { type: 'answer', sdp: this._remoteSdp.getSdp() };
8930 logger$a.debug('sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]', answer);
8931 await this._pc.setRemoteDescription(answer);
8932 this._hasDataChannelMediaSection = true;
8933 }
8934 const sctpStreamParameters = {
8935 streamId: options.id,
8936 ordered: options.ordered,
8937 maxPacketLifeTime: options.maxPacketLifeTime,
8938 maxRetransmits: options.maxRetransmits
8939 };
8940 return { dataChannel, sctpStreamParameters };
8941 }
8942 async receive(optionsList) {
8943 this.assertNotClosed();
8944 this.assertRecvDirection();
8945 const results = [];
8946 const mapLocalId = new Map();
8947 for (const options of optionsList) {
8948 const { trackId, kind, rtpParameters, streamId } = options;
8949 logger$a.debug('receive() [trackId:%s, kind:%s]', trackId, kind);
8950 const localId = rtpParameters.mid || String(this._mapMidTransceiver.size);
8951 mapLocalId.set(trackId, localId);
8952 this._remoteSdp.receive({
8953 mid: localId,
8954 kind,
8955 offerRtpParameters: rtpParameters,
8956 streamId: streamId || rtpParameters.rtcp.cname,
8957 trackId
8958 });
8959 }
8960 const offer = { type: 'offer', sdp: this._remoteSdp.getSdp() };
8961 logger$a.debug('receive() | calling pc.setRemoteDescription() [offer:%o]', offer);
8962 await this._pc.setRemoteDescription(offer);
8963 let answer = await this._pc.createAnswer();
8964 const localSdpObject = sdpTransform$8.parse(answer.sdp);
8965 for (const options of optionsList) {
8966 const { trackId, rtpParameters } = options;
8967 const localId = mapLocalId.get(trackId);
8968 const answerMediaObject = localSdpObject.media
8969 .find((m) => String(m.mid) === localId);
8970 // May need to modify codec parameters in the answer based on codec
8971 // parameters in the offer.
8972 sdpCommonUtils$8.applyCodecParameters({
8973 offerRtpParameters: rtpParameters,
8974 answerMediaObject
8975 });
8976 }
8977 answer = { type: 'answer', sdp: sdpTransform$8.write(localSdpObject) };
8978 if (!this._transportReady) {
8979 await this.setupTransport({
8980 localDtlsRole: this._forcedLocalDtlsRole ?? 'client',
8981 localSdpObject
8982 });
8983 }
8984 logger$a.debug('receive() | calling pc.setLocalDescription() [answer:%o]', answer);
8985 await this._pc.setLocalDescription(answer);
8986 for (const options of optionsList) {
8987 const { trackId } = options;
8988 const localId = mapLocalId.get(trackId);
8989 const transceiver = this._pc.getTransceivers()
8990 .find((t) => t.mid === localId);
8991 if (!transceiver) {
8992 throw new Error('new RTCRtpTransceiver not found');
8993 }
8994 else {
8995 // Store in the map.
8996 this._mapMidTransceiver.set(localId, transceiver);
8997 results.push({
8998 localId,
8999 track: transceiver.receiver.track,
9000 rtpReceiver: transceiver.receiver
9001 });
9002 }
9003 }
9004 return results;
9005 }
9006 async stopReceiving(localIds) {
9007 this.assertRecvDirection();
9008 if (this._closed) {
9009 return;
9010 }
9011 for (const localId of localIds) {
9012 logger$a.debug('stopReceiving() [localId:%s]', localId);
9013 const transceiver = this._mapMidTransceiver.get(localId);
9014 if (!transceiver) {
9015 throw new Error('associated RTCRtpTransceiver not found');
9016 }
9017 this._remoteSdp.closeMediaSection(transceiver.mid);
9018 }
9019 const offer = { type: 'offer', sdp: this._remoteSdp.getSdp() };
9020 logger$a.debug('stopReceiving() | calling pc.setRemoteDescription() [offer:%o]', offer);
9021 await this._pc.setRemoteDescription(offer);
9022 const answer = await this._pc.createAnswer();
9023 logger$a.debug('stopReceiving() | calling pc.setLocalDescription() [answer:%o]', answer);
9024 await this._pc.setLocalDescription(answer);
9025 for (const localId of localIds) {
9026 this._mapMidTransceiver.delete(localId);
9027 }
9028 }
9029 async pauseReceiving(localIds) {
9030 this.assertNotClosed();
9031 this.assertRecvDirection();
9032 for (const localId of localIds) {
9033 logger$a.debug('pauseReceiving() [localId:%s]', localId);
9034 const transceiver = this._mapMidTransceiver.get(localId);
9035 if (!transceiver) {
9036 throw new Error('associated RTCRtpTransceiver not found');
9037 }
9038 transceiver.direction = 'inactive';
9039 this._remoteSdp.pauseMediaSection(localId);
9040 }
9041 const offer = { type: 'offer', sdp: this._remoteSdp.getSdp() };
9042 logger$a.debug('pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]', offer);
9043 await this._pc.setRemoteDescription(offer);
9044 const answer = await this._pc.createAnswer();
9045 logger$a.debug('pauseReceiving() | calling pc.setLocalDescription() [answer:%o]', answer);
9046 await this._pc.setLocalDescription(answer);
9047 }
9048 async resumeReceiving(localIds) {
9049 this.assertNotClosed();
9050 this.assertRecvDirection();
9051 for (const localId of localIds) {
9052 logger$a.debug('resumeReceiving() [localId:%s]', localId);
9053 const transceiver = this._mapMidTransceiver.get(localId);
9054 if (!transceiver) {
9055 throw new Error('associated RTCRtpTransceiver not found');
9056 }
9057 transceiver.direction = 'recvonly';
9058 this._remoteSdp.resumeReceivingMediaSection(localId);
9059 }
9060 const offer = { type: 'offer', sdp: this._remoteSdp.getSdp() };
9061 logger$a.debug('resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]', offer);
9062 await this._pc.setRemoteDescription(offer);
9063 const answer = await this._pc.createAnswer();
9064 logger$a.debug('resumeReceiving() | calling pc.setLocalDescription() [answer:%o]', answer);
9065 await this._pc.setLocalDescription(answer);
9066 }
9067 async getReceiverStats(localId) {
9068 this.assertNotClosed();
9069 this.assertRecvDirection();
9070 const transceiver = this._mapMidTransceiver.get(localId);
9071 if (!transceiver) {
9072 throw new Error('associated RTCRtpTransceiver not found');
9073 }
9074 return transceiver.receiver.getStats();
9075 }
9076 async receiveDataChannel({ sctpStreamParameters, label, protocol }) {
9077 this.assertNotClosed();
9078 this.assertRecvDirection();
9079 const { streamId, ordered, maxPacketLifeTime, maxRetransmits } = sctpStreamParameters;
9080 const options = {
9081 negotiated: true,
9082 id: streamId,
9083 ordered,
9084 maxPacketLifeTime,
9085 maxRetransmits,
9086 protocol
9087 };
9088 logger$a.debug('receiveDataChannel() [options:%o]', options);
9089 const dataChannel = this._pc.createDataChannel(label, options);
9090 // If this is the first DataChannel we need to create the SDP offer with
9091 // m=application section.
9092 if (!this._hasDataChannelMediaSection) {
9093 this._remoteSdp.receiveSctpAssociation();
9094 const offer = { type: 'offer', sdp: this._remoteSdp.getSdp() };
9095 logger$a.debug('receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]', offer);
9096 await this._pc.setRemoteDescription(offer);
9097 const answer = await this._pc.createAnswer();
9098 if (!this._transportReady) {
9099 const localSdpObject = sdpTransform$8.parse(answer.sdp);
9100 await this.setupTransport({
9101 localDtlsRole: this._forcedLocalDtlsRole ?? 'client',
9102 localSdpObject
9103 });
9104 }
9105 logger$a.debug('receiveDataChannel() | calling pc.setRemoteDescription() [answer:%o]', answer);
9106 await this._pc.setLocalDescription(answer);
9107 this._hasDataChannelMediaSection = true;
9108 }
9109 return { dataChannel };
9110 }
9111 async setupTransport({ localDtlsRole, localSdpObject }) {
9112 if (!localSdpObject) {
9113 localSdpObject = sdpTransform$8.parse(this._pc.localDescription.sdp);
9114 }
9115 // Get our local DTLS parameters.
9116 const dtlsParameters = sdpCommonUtils$8.extractDtlsParameters({ sdpObject: localSdpObject });
9117 // Set our DTLS role.
9118 dtlsParameters.role = localDtlsRole;
9119 // Update the remote DTLS role in the SDP.
9120 this._remoteSdp.updateDtlsRole(localDtlsRole === 'client' ? 'server' : 'client');
9121 // Need to tell the remote transport about our parameters.
9122 await new Promise((resolve, reject) => {
9123 this.safeEmit('@connect', { dtlsParameters }, resolve, reject);
9124 });
9125 this._transportReady = true;
9126 }
9127 assertNotClosed() {
9128 if (this._closed) {
9129 throw new errors_1$7.InvalidStateError('method called in a closed handler');
9130 }
9131 }
9132 assertSendDirection() {
9133 if (this._direction !== 'send') {
9134 throw new Error('method can just be called for handlers with "send" direction');
9135 }
9136 }
9137 assertRecvDirection() {
9138 if (this._direction !== 'recv') {
9139 throw new Error('method can just be called for handlers with "recv" direction');
9140 }
9141 }
9142 }
9143 Chrome74$1.Chrome74 = Chrome74;
9144
9145 var Chrome70$1 = {};
9146
9147 var __createBinding$a = (commonjsGlobal && commonjsGlobal.__createBinding) || (Object.create ? (function(o, m, k, k2) {
9148 if (k2 === undefined) k2 = k;
9149 var desc = Object.getOwnPropertyDescriptor(m, k);
9150 if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
9151 desc = { enumerable: true, get: function() { return m[k]; } };
9152 }
9153 Object.defineProperty(o, k2, desc);
9154 }) : (function(o, m, k, k2) {
9155 if (k2 === undefined) k2 = k;
9156 o[k2] = m[k];
9157 }));
9158 var __setModuleDefault$a = (commonjsGlobal && commonjsGlobal.__setModuleDefault) || (Object.create ? (function(o, v) {
9159 Object.defineProperty(o, "default", { enumerable: true, value: v });
9160 }) : function(o, v) {
9161 o["default"] = v;
9162 });
9163 var __importStar$a = (commonjsGlobal && commonjsGlobal.__importStar) || function (mod) {
9164 if (mod && mod.__esModule) return mod;
9165 var result = {};
9166 if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding$a(result, mod, k);
9167 __setModuleDefault$a(result, mod);
9168 return result;
9169 };
9170 Object.defineProperty(Chrome70$1, "__esModule", { value: true });
9171 Chrome70$1.Chrome70 = void 0;
9172 const sdpTransform$7 = __importStar$a(lib);
9173 const Logger_1$9 = Logger$3;
9174 const utils$a = __importStar$a(utils$h);
9175 const ortc$9 = __importStar$a(ortc$d);
9176 const sdpCommonUtils$7 = __importStar$a(commonUtils);
9177 const sdpUnifiedPlanUtils$3 = __importStar$a(unifiedPlanUtils);
9178 const HandlerInterface_1$8 = HandlerInterface$1;
9179 const RemoteSdp_1$7 = RemoteSdp$1;
9180 const scalabilityModes_1$3 = scalabilityModes;
9181 const logger$9 = new Logger_1$9.Logger('Chrome70');
9182 const SCTP_NUM_STREAMS$7 = { OS: 1024, MIS: 1024 };
9183 class Chrome70 extends HandlerInterface_1$8.HandlerInterface {
9184 /**
9185 * Creates a factory function.
9186 */
9187 static createFactory() {
9188 return () => new Chrome70();
9189 }
9190 constructor() {
9191 super();
9192 // Map of RTCTransceivers indexed by MID.
9193 this._mapMidTransceiver = new Map();
9194 // Local stream for sending.
9195 this._sendStream = new MediaStream();
9196 // Whether a DataChannel m=application section has been created.
9197 this._hasDataChannelMediaSection = false;
9198 // Sending DataChannel id value counter. Incremented for each new DataChannel.
9199 this._nextSendSctpStreamId = 0;
9200 // Got transport local and remote parameters.
9201 this._transportReady = false;
9202 }
9203 get name() {
9204 return 'Chrome70';
9205 }
9206 close() {
9207 logger$9.debug('close()');
9208 // Close RTCPeerConnection.
9209 if (this._pc) {
9210 try {
9211 this._pc.close();
9212 }
9213 catch (error) { }
9214 }
9215 this.emit('@close');
9216 }
9217 async getNativeRtpCapabilities() {
9218 logger$9.debug('getNativeRtpCapabilities()');
9219 const pc = new RTCPeerConnection({
9220 iceServers: [],
9221 iceTransportPolicy: 'all',
9222 bundlePolicy: 'max-bundle',
9223 rtcpMuxPolicy: 'require',
9224 sdpSemantics: 'unified-plan'
9225 });
9226 try {
9227 pc.addTransceiver('audio');
9228 pc.addTransceiver('video');
9229 const offer = await pc.createOffer();
9230 try {
9231 pc.close();
9232 }
9233 catch (error) { }
9234 const sdpObject = sdpTransform$7.parse(offer.sdp);
9235 const nativeRtpCapabilities = sdpCommonUtils$7.extractRtpCapabilities({ sdpObject });
9236 return nativeRtpCapabilities;
9237 }
9238 catch (error) {
9239 try {
9240 pc.close();
9241 }
9242 catch (error2) { }
9243 throw error;
9244 }
9245 }
9246 async getNativeSctpCapabilities() {
9247 logger$9.debug('getNativeSctpCapabilities()');
9248 return {
9249 numStreams: SCTP_NUM_STREAMS$7
9250 };
9251 }
9252 run({ direction, iceParameters, iceCandidates, dtlsParameters, sctpParameters, iceServers, iceTransportPolicy, additionalSettings, proprietaryConstraints, extendedRtpCapabilities }) {
9253 logger$9.debug('run()');
9254 this._direction = direction;
9255 this._remoteSdp = new RemoteSdp_1$7.RemoteSdp({
9256 iceParameters,
9257 iceCandidates,
9258 dtlsParameters,
9259 sctpParameters
9260 });
9261 this._sendingRtpParametersByKind =
9262 {
9263 audio: ortc$9.getSendingRtpParameters('audio', extendedRtpCapabilities),
9264 video: ortc$9.getSendingRtpParameters('video', extendedRtpCapabilities)
9265 };
9266 this._sendingRemoteRtpParametersByKind =
9267 {
9268 audio: ortc$9.getSendingRemoteRtpParameters('audio', extendedRtpCapabilities),
9269 video: ortc$9.getSendingRemoteRtpParameters('video', extendedRtpCapabilities)
9270 };
9271 if (dtlsParameters.role && dtlsParameters.role !== 'auto') {
9272 this._forcedLocalDtlsRole = dtlsParameters.role === 'server'
9273 ? 'client'
9274 : 'server';
9275 }
9276 this._pc = new RTCPeerConnection({
9277 iceServers: iceServers || [],
9278 iceTransportPolicy: iceTransportPolicy || 'all',
9279 bundlePolicy: 'max-bundle',
9280 rtcpMuxPolicy: 'require',
9281 sdpSemantics: 'unified-plan',
9282 ...additionalSettings
9283 }, proprietaryConstraints);
9284 this._pc.addEventListener('icegatheringstatechange', () => {
9285 this.emit('@icegatheringstatechange', this._pc.iceGatheringState);
9286 });
9287 if (this._pc.connectionState) {
9288 this._pc.addEventListener('connectionstatechange', () => {
9289 this.emit('@connectionstatechange', this._pc.connectionState);
9290 });
9291 }
9292 else {
9293 this._pc.addEventListener('iceconnectionstatechange', () => {
9294 logger$9.warn('run() | pc.connectionState not supported, using pc.iceConnectionState');
9295 switch (this._pc.iceConnectionState) {
9296 case 'checking':
9297 this.emit('@connectionstatechange', 'connecting');
9298 break;
9299 case 'connected':
9300 case 'completed':
9301 this.emit('@connectionstatechange', 'connected');
9302 break;
9303 case 'failed':
9304 this.emit('@connectionstatechange', 'failed');
9305 break;
9306 case 'disconnected':
9307 this.emit('@connectionstatechange', 'disconnected');
9308 break;
9309 case 'closed':
9310 this.emit('@connectionstatechange', 'closed');
9311 break;
9312 }
9313 });
9314 }
9315 }
9316 async updateIceServers(iceServers) {
9317 logger$9.debug('updateIceServers()');
9318 const configuration = this._pc.getConfiguration();
9319 configuration.iceServers = iceServers;
9320 this._pc.setConfiguration(configuration);
9321 }
9322 async restartIce(iceParameters) {
9323 logger$9.debug('restartIce()');
9324 // Provide the remote SDP handler with new remote ICE parameters.
9325 this._remoteSdp.updateIceParameters(iceParameters);
9326 if (!this._transportReady) {
9327 return;
9328 }
9329 if (this._direction === 'send') {
9330 const offer = await this._pc.createOffer({ iceRestart: true });
9331 logger$9.debug('restartIce() | calling pc.setLocalDescription() [offer:%o]', offer);
9332 await this._pc.setLocalDescription(offer);
9333 const answer = { type: 'answer', sdp: this._remoteSdp.getSdp() };
9334 logger$9.debug('restartIce() | calling pc.setRemoteDescription() [answer:%o]', answer);
9335 await this._pc.setRemoteDescription(answer);
9336 }
9337 else {
9338 const offer = { type: 'offer', sdp: this._remoteSdp.getSdp() };
9339 logger$9.debug('restartIce() | calling pc.setRemoteDescription() [offer:%o]', offer);
9340 await this._pc.setRemoteDescription(offer);
9341 const answer = await this._pc.createAnswer();
9342 logger$9.debug('restartIce() | calling pc.setLocalDescription() [answer:%o]', answer);
9343 await this._pc.setLocalDescription(answer);
9344 }
9345 }
9346 async getTransportStats() {
9347 return this._pc.getStats();
9348 }
9349 async send({ track, encodings, codecOptions, codec }) {
9350 this.assertSendDirection();
9351 logger$9.debug('send() [kind:%s, track.id:%s]', track.kind, track.id);
9352 const sendingRtpParameters = utils$a.clone(this._sendingRtpParametersByKind[track.kind]);
9353 // This may throw.
9354 sendingRtpParameters.codecs =
9355 ortc$9.reduceCodecs(sendingRtpParameters.codecs, codec);
9356 const sendingRemoteRtpParameters = utils$a.clone(this._sendingRemoteRtpParametersByKind[track.kind]);
9357 // This may throw.
9358 sendingRemoteRtpParameters.codecs =
9359 ortc$9.reduceCodecs(sendingRemoteRtpParameters.codecs, codec);
9360 const mediaSectionIdx = this._remoteSdp.getNextMediaSectionIdx();
9361 const transceiver = this._pc.addTransceiver(track, { direction: 'sendonly', streams: [this._sendStream] });
9362 let offer = await this._pc.createOffer();
9363 let localSdpObject = sdpTransform$7.parse(offer.sdp);
9364 let offerMediaObject;
9365 if (!this._transportReady) {
9366 await this.setupTransport({
9367 localDtlsRole: this._forcedLocalDtlsRole ?? 'client',
9368 localSdpObject
9369 });
9370 }
9371 if (encodings && encodings.length > 1) {
9372 logger$9.debug('send() | enabling legacy simulcast');
9373 localSdpObject = sdpTransform$7.parse(offer.sdp);
9374 offerMediaObject = localSdpObject.media[mediaSectionIdx.idx];
9375 sdpUnifiedPlanUtils$3.addLegacySimulcast({
9376 offerMediaObject,
9377 numStreams: encodings.length
9378 });
9379 offer = { type: 'offer', sdp: sdpTransform$7.write(localSdpObject) };
9380 }
9381 // Special case for VP9 with SVC.
9382 let hackVp9Svc = false;
9383 const layers = (0, scalabilityModes_1$3.parse)((encodings || [{}])[0].scalabilityMode);
9384 if (encodings &&
9385 encodings.length === 1 &&
9386 layers.spatialLayers > 1 &&
9387 sendingRtpParameters.codecs[0].mimeType.toLowerCase() === 'video/vp9') {
9388 logger$9.debug('send() | enabling legacy simulcast for VP9 SVC');
9389 hackVp9Svc = true;
9390 localSdpObject = sdpTransform$7.parse(offer.sdp);
9391 offerMediaObject = localSdpObject.media[mediaSectionIdx.idx];
9392 sdpUnifiedPlanUtils$3.addLegacySimulcast({
9393 offerMediaObject,
9394 numStreams: layers.spatialLayers
9395 });
9396 offer = { type: 'offer', sdp: sdpTransform$7.write(localSdpObject) };
9397 }
9398 logger$9.debug('send() | calling pc.setLocalDescription() [offer:%o]', offer);
9399 await this._pc.setLocalDescription(offer);
9400 // If encodings are given, apply them now.
9401 if (encodings) {
9402 logger$9.debug('send() | applying given encodings');
9403 const parameters = transceiver.sender.getParameters();
9404 for (let idx = 0; idx < (parameters.encodings || []).length; ++idx) {
9405 const encoding = parameters.encodings[idx];
9406 const desiredEncoding = encodings[idx];
9407 // Should not happen but just in case.
9408 if (!desiredEncoding) {
9409 break;
9410 }
9411 parameters.encodings[idx] = Object.assign(encoding, desiredEncoding);
9412 }
9413 await transceiver.sender.setParameters(parameters);
9414 }
9415 // We can now get the transceiver.mid.
9416 const localId = transceiver.mid;
9417 // Set MID.
9418 sendingRtpParameters.mid = localId;
9419 localSdpObject = sdpTransform$7.parse(this._pc.localDescription.sdp);
9420 offerMediaObject = localSdpObject.media[mediaSectionIdx.idx];
9421 // Set RTCP CNAME.
9422 sendingRtpParameters.rtcp.cname =
9423 sdpCommonUtils$7.getCname({ offerMediaObject });
9424 // Set RTP encodings.
9425 sendingRtpParameters.encodings =
9426 sdpUnifiedPlanUtils$3.getRtpEncodings({ offerMediaObject });
9427 // Complete encodings with given values.
9428 if (encodings) {
9429 for (let idx = 0; idx < sendingRtpParameters.encodings.length; ++idx) {
9430 if (encodings[idx]) {
9431 Object.assign(sendingRtpParameters.encodings[idx], encodings[idx]);
9432 }
9433 }
9434 }
9435 // Hack for VP9 SVC.
9436 if (hackVp9Svc) {
9437 sendingRtpParameters.encodings = [sendingRtpParameters.encodings[0]];
9438 }
9439 // If VP8 or H264 and there is effective simulcast, add scalabilityMode to
9440 // each encoding.
9441 if (sendingRtpParameters.encodings.length > 1 &&
9442 (sendingRtpParameters.codecs[0].mimeType.toLowerCase() === 'video/vp8' ||
9443 sendingRtpParameters.codecs[0].mimeType.toLowerCase() === 'video/h264')) {
9444 for (const encoding of sendingRtpParameters.encodings) {
9445 encoding.scalabilityMode = 'L1T3';
9446 }
9447 }
9448 this._remoteSdp.send({
9449 offerMediaObject,
9450 reuseMid: mediaSectionIdx.reuseMid,
9451 offerRtpParameters: sendingRtpParameters,
9452 answerRtpParameters: sendingRemoteRtpParameters,
9453 codecOptions
9454 });
9455 const answer = { type: 'answer', sdp: this._remoteSdp.getSdp() };
9456 logger$9.debug('send() | calling pc.setRemoteDescription() [answer:%o]', answer);
9457 await this._pc.setRemoteDescription(answer);
9458 // Store in the map.
9459 this._mapMidTransceiver.set(localId, transceiver);
9460 return {
9461 localId,
9462 rtpParameters: sendingRtpParameters,
9463 rtpSender: transceiver.sender
9464 };
9465 }
9466 async stopSending(localId) {
9467 this.assertSendDirection();
9468 logger$9.debug('stopSending() [localId:%s]', localId);
9469 const transceiver = this._mapMidTransceiver.get(localId);
9470 if (!transceiver) {
9471 throw new Error('associated RTCRtpTransceiver not found');
9472 }
9473 transceiver.sender.replaceTrack(null);
9474 this._pc.removeTrack(transceiver.sender);
9475 const mediaSectionClosed = this._remoteSdp.closeMediaSection(transceiver.mid);
9476 if (mediaSectionClosed) {
9477 try {
9478 transceiver.stop();
9479 }
9480 catch (error) { }
9481 }
9482 const offer = await this._pc.createOffer();
9483 logger$9.debug('stopSending() | calling pc.setLocalDescription() [offer:%o]', offer);
9484 await this._pc.setLocalDescription(offer);
9485 const answer = { type: 'answer', sdp: this._remoteSdp.getSdp() };
9486 logger$9.debug('stopSending() | calling pc.setRemoteDescription() [answer:%o]', answer);
9487 await this._pc.setRemoteDescription(answer);
9488 this._mapMidTransceiver.delete(localId);
9489 }
9490 // eslint-disable-next-line @typescript-eslint/no-unused-vars
9491 async pauseSending(localId) {
9492 // Unimplemented.
9493 }
9494 // eslint-disable-next-line @typescript-eslint/no-unused-vars
9495 async resumeSending(localId) {
9496 // Unimplemented.
9497 }
9498 async replaceTrack(localId, track) {
9499 this.assertSendDirection();
9500 if (track) {
9501 logger$9.debug('replaceTrack() [localId:%s, track.id:%s]', localId, track.id);
9502 }
9503 else {
9504 logger$9.debug('replaceTrack() [localId:%s, no track]', localId);
9505 }
9506 const transceiver = this._mapMidTransceiver.get(localId);
9507 if (!transceiver) {
9508 throw new Error('associated RTCRtpTransceiver not found');
9509 }
9510 await transceiver.sender.replaceTrack(track);
9511 }
9512 async setMaxSpatialLayer(localId, spatialLayer) {
9513 this.assertSendDirection();
9514 logger$9.debug('setMaxSpatialLayer() [localId:%s, spatialLayer:%s]', localId, spatialLayer);
9515 const transceiver = this._mapMidTransceiver.get(localId);
9516 if (!transceiver) {
9517 throw new Error('associated RTCRtpTransceiver not found');
9518 }
9519 const parameters = transceiver.sender.getParameters();
9520 parameters.encodings.forEach((encoding, idx) => {
9521 if (idx <= spatialLayer) {
9522 encoding.active = true;
9523 }
9524 else {
9525 encoding.active = false;
9526 }
9527 });
9528 await transceiver.sender.setParameters(parameters);
9529 this._remoteSdp.muxMediaSectionSimulcast(localId, parameters.encodings);
9530 const offer = await this._pc.createOffer();
9531 logger$9.debug('setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]', offer);
9532 await this._pc.setLocalDescription(offer);
9533 const answer = { type: 'answer', sdp: this._remoteSdp.getSdp() };
9534 logger$9.debug('setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]', answer);
9535 await this._pc.setRemoteDescription(answer);
9536 }
9537 async setRtpEncodingParameters(localId, params) {
9538 this.assertSendDirection();
9539 logger$9.debug('setRtpEncodingParameters() [localId:%s, params:%o]', localId, params);
9540 const transceiver = this._mapMidTransceiver.get(localId);
9541 if (!transceiver) {
9542 throw new Error('associated RTCRtpTransceiver not found');
9543 }
9544 const parameters = transceiver.sender.getParameters();
9545 parameters.encodings.forEach((encoding, idx) => {
9546 parameters.encodings[idx] = { ...encoding, ...params };
9547 });
9548 await transceiver.sender.setParameters(parameters);
9549 this._remoteSdp.muxMediaSectionSimulcast(localId, parameters.encodings);
9550 const offer = await this._pc.createOffer();
9551 logger$9.debug('setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]', offer);
9552 await this._pc.setLocalDescription(offer);
9553 const answer = { type: 'answer', sdp: this._remoteSdp.getSdp() };
9554 logger$9.debug('setRtpEncodingParameters() | calling pc.setRemoteDescription() [answer:%o]', answer);
9555 await this._pc.setRemoteDescription(answer);
9556 }
9557 async getSenderStats(localId) {
9558 this.assertSendDirection();
9559 const transceiver = this._mapMidTransceiver.get(localId);
9560 if (!transceiver) {
9561 throw new Error('associated RTCRtpTransceiver not found');
9562 }
9563 return transceiver.sender.getStats();
9564 }
9565 async sendDataChannel({ ordered, maxPacketLifeTime, maxRetransmits, label, protocol }) {
9566 this.assertSendDirection();
9567 const options = {
9568 negotiated: true,
9569 id: this._nextSendSctpStreamId,
9570 ordered,
9571 maxPacketLifeTime,
9572 maxRetransmitTime: maxPacketLifeTime,
9573 maxRetransmits,
9574 protocol
9575 };
9576 logger$9.debug('sendDataChannel() [options:%o]', options);
9577 const dataChannel = this._pc.createDataChannel(label, options);
9578 // Increase next id.
9579 this._nextSendSctpStreamId =
9580 ++this._nextSendSctpStreamId % SCTP_NUM_STREAMS$7.MIS;
9581 // If this is the first DataChannel we need to create the SDP answer with
9582 // m=application section.
9583 if (!this._hasDataChannelMediaSection) {
9584 const offer = await this._pc.createOffer();
9585 const localSdpObject = sdpTransform$7.parse(offer.sdp);
9586 const offerMediaObject = localSdpObject.media
9587 .find((m) => m.type === 'application');
9588 if (!this._transportReady) {
9589 await this.setupTransport({
9590 localDtlsRole: this._forcedLocalDtlsRole ?? 'client',
9591 localSdpObject
9592 });
9593 }
9594 logger$9.debug('sendDataChannel() | calling pc.setLocalDescription() [offer:%o]', offer);
9595 await this._pc.setLocalDescription(offer);
9596 this._remoteSdp.sendSctpAssociation({ offerMediaObject });
9597 const answer = { type: 'answer', sdp: this._remoteSdp.getSdp() };
9598 logger$9.debug('sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]', answer);
9599 await this._pc.setRemoteDescription(answer);
9600 this._hasDataChannelMediaSection = true;
9601 }
9602 const sctpStreamParameters = {
9603 streamId: options.id,
9604 ordered: options.ordered,
9605 maxPacketLifeTime: options.maxPacketLifeTime,
9606 maxRetransmits: options.maxRetransmits
9607 };
9608 return { dataChannel, sctpStreamParameters };
9609 }
9610 async receive(optionsList) {
9611 this.assertRecvDirection();
9612 const results = [];
9613 const mapLocalId = new Map();
9614 for (const options of optionsList) {
9615 const { trackId, kind, rtpParameters, streamId } = options;
9616 logger$9.debug('receive() [trackId:%s, kind:%s]', trackId, kind);
9617 const localId = rtpParameters.mid || String(this._mapMidTransceiver.size);
9618 mapLocalId.set(trackId, localId);
9619 this._remoteSdp.receive({
9620 mid: localId,
9621 kind,
9622 offerRtpParameters: rtpParameters,
9623 streamId: streamId || rtpParameters.rtcp.cname,
9624 trackId
9625 });
9626 }
9627 const offer = { type: 'offer', sdp: this._remoteSdp.getSdp() };
9628 logger$9.debug('receive() | calling pc.setRemoteDescription() [offer:%o]', offer);
9629 await this._pc.setRemoteDescription(offer);
9630 let answer = await this._pc.createAnswer();
9631 const localSdpObject = sdpTransform$7.parse(answer.sdp);
9632 for (const options of optionsList) {
9633 const { trackId, rtpParameters } = options;
9634 const localId = mapLocalId.get(trackId);
9635 const answerMediaObject = localSdpObject.media
9636 .find((m) => String(m.mid) === localId);
9637 // May need to modify codec parameters in the answer based on codec
9638 // parameters in the offer.
9639 sdpCommonUtils$7.applyCodecParameters({
9640 offerRtpParameters: rtpParameters,
9641 answerMediaObject
9642 });
9643 }
9644 answer = { type: 'answer', sdp: sdpTransform$7.write(localSdpObject) };
9645 if (!this._transportReady) {
9646 await this.setupTransport({
9647 localDtlsRole: this._forcedLocalDtlsRole ?? 'client',
9648 localSdpObject
9649 });
9650 }
9651 logger$9.debug('receive() | calling pc.setLocalDescription() [answer:%o]', answer);
9652 await this._pc.setLocalDescription(answer);
9653 for (const options of optionsList) {
9654 const { trackId } = options;
9655 const localId = mapLocalId.get(trackId);
9656 const transceiver = this._pc.getTransceivers()
9657 .find((t) => t.mid === localId);
9658 if (!transceiver) {
9659 throw new Error('new RTCRtpTransceiver not found');
9660 }
9661 // Store in the map.
9662 this._mapMidTransceiver.set(localId, transceiver);
9663 results.push({
9664 localId,
9665 track: transceiver.receiver.track,
9666 rtpReceiver: transceiver.receiver
9667 });
9668 }
9669 return results;
9670 }
9671 async stopReceiving(localIds) {
9672 this.assertRecvDirection();
9673 for (const localId of localIds) {
9674 logger$9.debug('stopReceiving() [localId:%s]', localId);
9675 const transceiver = this._mapMidTransceiver.get(localId);
9676 if (!transceiver) {
9677 throw new Error('associated RTCRtpTransceiver not found');
9678 }
9679 this._remoteSdp.closeMediaSection(transceiver.mid);
9680 }
9681 const offer = { type: 'offer', sdp: this._remoteSdp.getSdp() };
9682 logger$9.debug('stopReceiving() | calling pc.setRemoteDescription() [offer:%o]', offer);
9683 await this._pc.setRemoteDescription(offer);
9684 const answer = await this._pc.createAnswer();
9685 logger$9.debug('stopReceiving() | calling pc.setLocalDescription() [answer:%o]', answer);
9686 await this._pc.setLocalDescription(answer);
9687 for (const localId of localIds) {
9688 this._mapMidTransceiver.delete(localId);
9689 }
9690 }
9691 async pauseReceiving(
9692 // eslint-disable-next-line @typescript-eslint/no-unused-vars
9693 localIds) {
9694 // Unimplemented.
9695 }
9696 async resumeReceiving(
9697 // eslint-disable-next-line @typescript-eslint/no-unused-vars
9698 localIds) {
9699 // Unimplemented.
9700 }
9701 async getReceiverStats(localId) {
9702 this.assertRecvDirection();
9703 const transceiver = this._mapMidTransceiver.get(localId);
9704 if (!transceiver) {
9705 throw new Error('associated RTCRtpTransceiver not found');
9706 }
9707 return transceiver.receiver.getStats();
9708 }
9709 async receiveDataChannel({ sctpStreamParameters, label, protocol }) {
9710 this.assertRecvDirection();
9711 const { streamId, ordered, maxPacketLifeTime, maxRetransmits } = sctpStreamParameters;
9712 const options = {
9713 negotiated: true,
9714 id: streamId,
9715 ordered,
9716 maxPacketLifeTime,
9717 maxRetransmitTime: maxPacketLifeTime,
9718 maxRetransmits,
9719 protocol
9720 };
9721 logger$9.debug('receiveDataChannel() [options:%o]', options);
9722 const dataChannel = this._pc.createDataChannel(label, options);
9723 // If this is the first DataChannel we need to create the SDP offer with
9724 // m=application section.
9725 if (!this._hasDataChannelMediaSection) {
9726 this._remoteSdp.receiveSctpAssociation();
9727 const offer = { type: 'offer', sdp: this._remoteSdp.getSdp() };
9728 logger$9.debug('receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]', offer);
9729 await this._pc.setRemoteDescription(offer);
9730 const answer = await this._pc.createAnswer();
9731 if (!this._transportReady) {
9732 const localSdpObject = sdpTransform$7.parse(answer.sdp);
9733 await this.setupTransport({
9734 localDtlsRole: this._forcedLocalDtlsRole ?? 'client',
9735 localSdpObject
9736 });
9737 }
9738 logger$9.debug('receiveDataChannel() | calling pc.setRemoteDescription() [answer:%o]', answer);
9739 await this._pc.setLocalDescription(answer);
9740 this._hasDataChannelMediaSection = true;
9741 }
9742 return { dataChannel };
9743 }
9744 async setupTransport({ localDtlsRole, localSdpObject }) {
9745 if (!localSdpObject) {
9746 localSdpObject = sdpTransform$7.parse(this._pc.localDescription.sdp);
9747 }
9748 // Get our local DTLS parameters.
9749 const dtlsParameters = sdpCommonUtils$7.extractDtlsParameters({ sdpObject: localSdpObject });
9750 // Set our DTLS role.
9751 dtlsParameters.role = localDtlsRole;
9752 // Update the remote DTLS role in the SDP.
9753 this._remoteSdp.updateDtlsRole(localDtlsRole === 'client' ? 'server' : 'client');
9754 // Need to tell the remote transport about our parameters.
9755 await new Promise((resolve, reject) => {
9756 this.safeEmit('@connect', { dtlsParameters }, resolve, reject);
9757 });
9758 this._transportReady = true;
9759 }
9760 assertSendDirection() {
9761 if (this._direction !== 'send') {
9762 throw new Error('method can just be called for handlers with "send" direction');
9763 }
9764 }
9765 assertRecvDirection() {
9766 if (this._direction !== 'recv') {
9767 throw new Error('method can just be called for handlers with "recv" direction');
9768 }
9769 }
9770 }
9771 Chrome70$1.Chrome70 = Chrome70;
9772
9773 var Chrome67$1 = {};
9774
9775 var planBUtils = {};
9776
9777 Object.defineProperty(planBUtils, "__esModule", { value: true });
9778 planBUtils.addLegacySimulcast = planBUtils.getRtpEncodings = void 0;
9779 function getRtpEncodings({ offerMediaObject, track }) {
9780 const ssrcs = new Set();
9781 for (const line of offerMediaObject.ssrcs || []) {
9782 if (line.attribute !== 'msid') {
9783 continue;
9784 }
9785 const trackId = line.value.split(' ')[1];
9786 if (trackId === track.id) {
9787 const ssrc = line.id;
9788 ssrcs.add(ssrc);
9789 }
9790 }
9791 if (ssrcs.size === 0) {
9792 throw new Error(`a=ssrc line with msid information not found [track.id:${track.id}]`);
9793 }
9794 const ssrcToRtxSsrc = new Map();
9795 // First assume RTX is used.
9796 for (const line of offerMediaObject.ssrcGroups || []) {
9797 if (line.semantics !== 'FID') {
9798 continue;
9799 }
9800 let [ssrc, rtxSsrc] = line.ssrcs.split(/\s+/);
9801 ssrc = Number(ssrc);
9802 rtxSsrc = Number(rtxSsrc);
9803 if (ssrcs.has(ssrc)) {
9804 // Remove both the SSRC and RTX SSRC from the set so later we know that they
9805 // are already handled.
9806 ssrcs.delete(ssrc);
9807 ssrcs.delete(rtxSsrc);
9808 // Add to the map.
9809 ssrcToRtxSsrc.set(ssrc, rtxSsrc);
9810 }
9811 }
9812 // If the set of SSRCs is not empty it means that RTX is not being used, so take
9813 // media SSRCs from there.
9814 for (const ssrc of ssrcs) {
9815 // Add to the map.
9816 ssrcToRtxSsrc.set(ssrc, null);
9817 }
9818 const encodings = [];
9819 for (const [ssrc, rtxSsrc] of ssrcToRtxSsrc) {
9820 const encoding = { ssrc };
9821 if (rtxSsrc) {
9822 encoding.rtx = { ssrc: rtxSsrc };
9823 }
9824 encodings.push(encoding);
9825 }
9826 return encodings;
9827 }
9828 planBUtils.getRtpEncodings = getRtpEncodings;
9829 /**
9830 * Adds multi-ssrc based simulcast into the given SDP media section offer.
9831 */
9832 function addLegacySimulcast({ offerMediaObject, track, numStreams }) {
9833 if (numStreams <= 1) {
9834 throw new TypeError('numStreams must be greater than 1');
9835 }
9836 let firstSsrc;
9837 let firstRtxSsrc;
9838 let streamId;
9839 // Get the SSRC.
9840 const ssrcMsidLine = (offerMediaObject.ssrcs || [])
9841 .find((line) => {
9842 if (line.attribute !== 'msid') {
9843 return false;
9844 }
9845 const trackId = line.value.split(' ')[1];
9846 if (trackId === track.id) {
9847 firstSsrc = line.id;
9848 streamId = line.value.split(' ')[0];
9849 return true;
9850 }
9851 else {
9852 return false;
9853 }
9854 });
9855 if (!ssrcMsidLine) {
9856 throw new Error(`a=ssrc line with msid information not found [track.id:${track.id}]`);
9857 }
9858 // Get the SSRC for RTX.
9859 (offerMediaObject.ssrcGroups || [])
9860 .some((line) => {
9861 if (line.semantics !== 'FID') {
9862 return false;
9863 }
9864 const ssrcs = line.ssrcs.split(/\s+/);
9865 if (Number(ssrcs[0]) === firstSsrc) {
9866 firstRtxSsrc = Number(ssrcs[1]);
9867 return true;
9868 }
9869 else {
9870 return false;
9871 }
9872 });
9873 const ssrcCnameLine = offerMediaObject.ssrcs
9874 .find((line) => (line.attribute === 'cname' && line.id === firstSsrc));
9875 if (!ssrcCnameLine) {
9876 throw new Error(`a=ssrc line with cname information not found [track.id:${track.id}]`);
9877 }
9878 const cname = ssrcCnameLine.value;
9879 const ssrcs = [];
9880 const rtxSsrcs = [];
9881 for (let i = 0; i < numStreams; ++i) {
9882 ssrcs.push(firstSsrc + i);
9883 if (firstRtxSsrc) {
9884 rtxSsrcs.push(firstRtxSsrc + i);
9885 }
9886 }
9887 offerMediaObject.ssrcGroups = offerMediaObject.ssrcGroups || [];
9888 offerMediaObject.ssrcs = offerMediaObject.ssrcs || [];
9889 offerMediaObject.ssrcGroups.push({
9890 semantics: 'SIM',
9891 ssrcs: ssrcs.join(' ')
9892 });
9893 for (let i = 0; i < ssrcs.length; ++i) {
9894 const ssrc = ssrcs[i];
9895 offerMediaObject.ssrcs.push({
9896 id: ssrc,
9897 attribute: 'cname',
9898 value: cname
9899 });
9900 offerMediaObject.ssrcs.push({
9901 id: ssrc,
9902 attribute: 'msid',
9903 value: `${streamId} ${track.id}`
9904 });
9905 }
9906 for (let i = 0; i < rtxSsrcs.length; ++i) {
9907 const ssrc = ssrcs[i];
9908 const rtxSsrc = rtxSsrcs[i];
9909 offerMediaObject.ssrcs.push({
9910 id: rtxSsrc,
9911 attribute: 'cname',
9912 value: cname
9913 });
9914 offerMediaObject.ssrcs.push({
9915 id: rtxSsrc,
9916 attribute: 'msid',
9917 value: `${streamId} ${track.id}`
9918 });
9919 offerMediaObject.ssrcGroups.push({
9920 semantics: 'FID',
9921 ssrcs: `${ssrc} ${rtxSsrc}`
9922 });
9923 }
9924 }
9925 planBUtils.addLegacySimulcast = addLegacySimulcast;
9926
9927 var __createBinding$9 = (commonjsGlobal && commonjsGlobal.__createBinding) || (Object.create ? (function(o, m, k, k2) {
9928 if (k2 === undefined) k2 = k;
9929 var desc = Object.getOwnPropertyDescriptor(m, k);
9930 if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
9931 desc = { enumerable: true, get: function() { return m[k]; } };
9932 }
9933 Object.defineProperty(o, k2, desc);
9934 }) : (function(o, m, k, k2) {
9935 if (k2 === undefined) k2 = k;
9936 o[k2] = m[k];
9937 }));
9938 var __setModuleDefault$9 = (commonjsGlobal && commonjsGlobal.__setModuleDefault) || (Object.create ? (function(o, v) {
9939 Object.defineProperty(o, "default", { enumerable: true, value: v });
9940 }) : function(o, v) {
9941 o["default"] = v;
9942 });
9943 var __importStar$9 = (commonjsGlobal && commonjsGlobal.__importStar) || function (mod) {
9944 if (mod && mod.__esModule) return mod;
9945 var result = {};
9946 if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding$9(result, mod, k);
9947 __setModuleDefault$9(result, mod);
9948 return result;
9949 };
9950 Object.defineProperty(Chrome67$1, "__esModule", { value: true });
9951 Chrome67$1.Chrome67 = void 0;
9952 const sdpTransform$6 = __importStar$9(lib);
9953 const Logger_1$8 = Logger$3;
9954 const utils$9 = __importStar$9(utils$h);
9955 const ortc$8 = __importStar$9(ortc$d);
9956 const sdpCommonUtils$6 = __importStar$9(commonUtils);
9957 const sdpPlanBUtils$3 = __importStar$9(planBUtils);
9958 const HandlerInterface_1$7 = HandlerInterface$1;
9959 const RemoteSdp_1$6 = RemoteSdp$1;
9960 const logger$8 = new Logger_1$8.Logger('Chrome67');
9961 const SCTP_NUM_STREAMS$6 = { OS: 1024, MIS: 1024 };
9962 class Chrome67 extends HandlerInterface_1$7.HandlerInterface {
9963 /**
9964 * Creates a factory function.
9965 */
9966 static createFactory() {
9967 return () => new Chrome67();
9968 }
9969 constructor() {
9970 super();
9971 // Local stream for sending.
9972 this._sendStream = new MediaStream();
9973 // Map of RTCRtpSender indexed by localId.
9974 this._mapSendLocalIdRtpSender = new Map();
9975 // Next sending localId.
9976 this._nextSendLocalId = 0;
9977 // Map of MID, RTP parameters and RTCRtpReceiver indexed by local id.
9978 // Value is an Object with mid, rtpParameters and rtpReceiver.
9979 this._mapRecvLocalIdInfo = new Map();
9980 // Whether a DataChannel m=application section has been created.
9981 this._hasDataChannelMediaSection = false;
9982 // Sending DataChannel id value counter. Incremented for each new DataChannel.
9983 this._nextSendSctpStreamId = 0;
9984 // Got transport local and remote parameters.
9985 this._transportReady = false;
9986 }
9987 get name() {
9988 return 'Chrome67';
9989 }
9990 close() {
9991 logger$8.debug('close()');
9992 // Close RTCPeerConnection.
9993 if (this._pc) {
9994 try {
9995 this._pc.close();
9996 }
9997 catch (error) { }
9998 }
9999 this.emit('@close');
10000 }
10001 async getNativeRtpCapabilities() {
10002 logger$8.debug('getNativeRtpCapabilities()');
10003 const pc = new RTCPeerConnection({
10004 iceServers: [],
10005 iceTransportPolicy: 'all',
10006 bundlePolicy: 'max-bundle',
10007 rtcpMuxPolicy: 'require',
10008 sdpSemantics: 'plan-b'
10009 });
10010 try {
10011 const offer = await pc.createOffer({
10012 offerToReceiveAudio: true,
10013 offerToReceiveVideo: true
10014 });
10015 try {
10016 pc.close();
10017 }
10018 catch (error) { }
10019 const sdpObject = sdpTransform$6.parse(offer.sdp);
10020 const nativeRtpCapabilities = sdpCommonUtils$6.extractRtpCapabilities({ sdpObject });
10021 return nativeRtpCapabilities;
10022 }
10023 catch (error) {
10024 try {
10025 pc.close();
10026 }
10027 catch (error2) { }
10028 throw error;
10029 }
10030 }
10031 async getNativeSctpCapabilities() {
10032 logger$8.debug('getNativeSctpCapabilities()');
10033 return {
10034 numStreams: SCTP_NUM_STREAMS$6
10035 };
10036 }
10037 run({ direction, iceParameters, iceCandidates, dtlsParameters, sctpParameters, iceServers, iceTransportPolicy, additionalSettings, proprietaryConstraints, extendedRtpCapabilities }) {
10038 logger$8.debug('run()');
10039 this._direction = direction;
10040 this._remoteSdp = new RemoteSdp_1$6.RemoteSdp({
10041 iceParameters,
10042 iceCandidates,
10043 dtlsParameters,
10044 sctpParameters,
10045 planB: true
10046 });
10047 this._sendingRtpParametersByKind =
10048 {
10049 audio: ortc$8.getSendingRtpParameters('audio', extendedRtpCapabilities),
10050 video: ortc$8.getSendingRtpParameters('video', extendedRtpCapabilities)
10051 };
10052 this._sendingRemoteRtpParametersByKind =
10053 {
10054 audio: ortc$8.getSendingRemoteRtpParameters('audio', extendedRtpCapabilities),
10055 video: ortc$8.getSendingRemoteRtpParameters('video', extendedRtpCapabilities)
10056 };
10057 if (dtlsParameters.role && dtlsParameters.role !== 'auto') {
10058 this._forcedLocalDtlsRole = dtlsParameters.role === 'server'
10059 ? 'client'
10060 : 'server';
10061 }
10062 this._pc = new RTCPeerConnection({
10063 iceServers: iceServers || [],
10064 iceTransportPolicy: iceTransportPolicy || 'all',
10065 bundlePolicy: 'max-bundle',
10066 rtcpMuxPolicy: 'require',
10067 sdpSemantics: 'plan-b',
10068 ...additionalSettings
10069 }, proprietaryConstraints);
10070 this._pc.addEventListener('icegatheringstatechange', () => {
10071 this.emit('@icegatheringstatechange', this._pc.iceGatheringState);
10072 });
10073 if (this._pc.connectionState) {
10074 this._pc.addEventListener('connectionstatechange', () => {
10075 this.emit('@connectionstatechange', this._pc.connectionState);
10076 });
10077 }
10078 else {
10079 this._pc.addEventListener('iceconnectionstatechange', () => {
10080 logger$8.warn('run() | pc.connectionState not supported, using pc.iceConnectionState');
10081 switch (this._pc.iceConnectionState) {
10082 case 'checking':
10083 this.emit('@connectionstatechange', 'connecting');
10084 break;
10085 case 'connected':
10086 case 'completed':
10087 this.emit('@connectionstatechange', 'connected');
10088 break;
10089 case 'failed':
10090 this.emit('@connectionstatechange', 'failed');
10091 break;
10092 case 'disconnected':
10093 this.emit('@connectionstatechange', 'disconnected');
10094 break;
10095 case 'closed':
10096 this.emit('@connectionstatechange', 'closed');
10097 break;
10098 }
10099 });
10100 }
10101 }
10102 async updateIceServers(iceServers) {
10103 logger$8.debug('updateIceServers()');
10104 const configuration = this._pc.getConfiguration();
10105 configuration.iceServers = iceServers;
10106 this._pc.setConfiguration(configuration);
10107 }
10108 async restartIce(iceParameters) {
10109 logger$8.debug('restartIce()');
10110 // Provide the remote SDP handler with new remote ICE parameters.
10111 this._remoteSdp.updateIceParameters(iceParameters);
10112 if (!this._transportReady) {
10113 return;
10114 }
10115 if (this._direction === 'send') {
10116 const offer = await this._pc.createOffer({ iceRestart: true });
10117 logger$8.debug('restartIce() | calling pc.setLocalDescription() [offer:%o]', offer);
10118 await this._pc.setLocalDescription(offer);
10119 const answer = { type: 'answer', sdp: this._remoteSdp.getSdp() };
10120 logger$8.debug('restartIce() | calling pc.setRemoteDescription() [answer:%o]', answer);
10121 await this._pc.setRemoteDescription(answer);
10122 }
10123 else {
10124 const offer = { type: 'offer', sdp: this._remoteSdp.getSdp() };
10125 logger$8.debug('restartIce() | calling pc.setRemoteDescription() [offer:%o]', offer);
10126 await this._pc.setRemoteDescription(offer);
10127 const answer = await this._pc.createAnswer();
10128 logger$8.debug('restartIce() | calling pc.setLocalDescription() [answer:%o]', answer);
10129 await this._pc.setLocalDescription(answer);
10130 }
10131 }
10132 async getTransportStats() {
10133 return this._pc.getStats();
10134 }
10135 async send({ track, encodings, codecOptions, codec }) {
10136 this.assertSendDirection();
10137 logger$8.debug('send() [kind:%s, track.id:%s]', track.kind, track.id);
10138 if (codec) {
10139 logger$8.warn('send() | codec selection is not available in %s handler', this.name);
10140 }
10141 this._sendStream.addTrack(track);
10142 this._pc.addTrack(track, this._sendStream);
10143 let offer = await this._pc.createOffer();
10144 let localSdpObject = sdpTransform$6.parse(offer.sdp);
10145 let offerMediaObject;
10146 const sendingRtpParameters = utils$9.clone(this._sendingRtpParametersByKind[track.kind]);
10147 sendingRtpParameters.codecs =
10148 ortc$8.reduceCodecs(sendingRtpParameters.codecs);
10149 const sendingRemoteRtpParameters = utils$9.clone(this._sendingRemoteRtpParametersByKind[track.kind]);
10150 sendingRemoteRtpParameters.codecs =
10151 ortc$8.reduceCodecs(sendingRemoteRtpParameters.codecs);
10152 if (!this._transportReady) {
10153 await this.setupTransport({
10154 localDtlsRole: this._forcedLocalDtlsRole ?? 'client',
10155 localSdpObject
10156 });
10157 }
10158 if (track.kind === 'video' && encodings && encodings.length > 1) {
10159 logger$8.debug('send() | enabling simulcast');
10160 localSdpObject = sdpTransform$6.parse(offer.sdp);
10161 offerMediaObject = localSdpObject.media
10162 .find((m) => m.type === 'video');
10163 sdpPlanBUtils$3.addLegacySimulcast({
10164 offerMediaObject,
10165 track,
10166 numStreams: encodings.length
10167 });
10168 offer = { type: 'offer', sdp: sdpTransform$6.write(localSdpObject) };
10169 }
10170 logger$8.debug('send() | calling pc.setLocalDescription() [offer:%o]', offer);
10171 await this._pc.setLocalDescription(offer);
10172 localSdpObject = sdpTransform$6.parse(this._pc.localDescription.sdp);
10173 offerMediaObject = localSdpObject.media
10174 .find((m) => m.type === track.kind);
10175 // Set RTCP CNAME.
10176 sendingRtpParameters.rtcp.cname =
10177 sdpCommonUtils$6.getCname({ offerMediaObject });
10178 // Set RTP encodings.
10179 sendingRtpParameters.encodings =
10180 sdpPlanBUtils$3.getRtpEncodings({ offerMediaObject, track });
10181 // Complete encodings with given values.
10182 if (encodings) {
10183 for (let idx = 0; idx < sendingRtpParameters.encodings.length; ++idx) {
10184 if (encodings[idx]) {
10185 Object.assign(sendingRtpParameters.encodings[idx], encodings[idx]);
10186 }
10187 }
10188 }
10189 // If VP8 and there is effective simulcast, add scalabilityMode to each
10190 // encoding.
10191 if (sendingRtpParameters.encodings.length > 1 &&
10192 sendingRtpParameters.codecs[0].mimeType.toLowerCase() === 'video/vp8') {
10193 for (const encoding of sendingRtpParameters.encodings) {
10194 encoding.scalabilityMode = 'L1T3';
10195 }
10196 }
10197 this._remoteSdp.send({
10198 offerMediaObject,
10199 offerRtpParameters: sendingRtpParameters,
10200 answerRtpParameters: sendingRemoteRtpParameters,
10201 codecOptions
10202 });
10203 const answer = { type: 'answer', sdp: this._remoteSdp.getSdp() };
10204 logger$8.debug('send() | calling pc.setRemoteDescription() [answer:%o]', answer);
10205 await this._pc.setRemoteDescription(answer);
10206 const localId = String(this._nextSendLocalId);
10207 this._nextSendLocalId++;
10208 const rtpSender = this._pc.getSenders()
10209 .find((s) => s.track === track);
10210 // Insert into the map.
10211 this._mapSendLocalIdRtpSender.set(localId, rtpSender);
10212 return {
10213 localId: localId,
10214 rtpParameters: sendingRtpParameters,
10215 rtpSender
10216 };
10217 }
10218 async stopSending(localId) {
10219 this.assertSendDirection();
10220 logger$8.debug('stopSending() [localId:%s]', localId);
10221 const rtpSender = this._mapSendLocalIdRtpSender.get(localId);
10222 if (!rtpSender) {
10223 throw new Error('associated RTCRtpSender not found');
10224 }
10225 this._pc.removeTrack(rtpSender);
10226 if (rtpSender.track) {
10227 this._sendStream.removeTrack(rtpSender.track);
10228 }
10229 this._mapSendLocalIdRtpSender.delete(localId);
10230 const offer = await this._pc.createOffer();
10231 logger$8.debug('stopSending() | calling pc.setLocalDescription() [offer:%o]', offer);
10232 try {
10233 await this._pc.setLocalDescription(offer);
10234 }
10235 catch (error) {
10236 // NOTE: If there are no sending tracks, setLocalDescription() will fail with
10237 // "Failed to create channels". If so, ignore it.
10238 if (this._sendStream.getTracks().length === 0) {
10239 logger$8.warn('stopSending() | ignoring expected error due no sending tracks: %s', error.toString());
10240 return;
10241 }
10242 throw error;
10243 }
10244 if (this._pc.signalingState === 'stable') {
10245 return;
10246 }
10247 const answer = { type: 'answer', sdp: this._remoteSdp.getSdp() };
10248 logger$8.debug('stopSending() | calling pc.setRemoteDescription() [answer:%o]', answer);
10249 await this._pc.setRemoteDescription(answer);
10250 }
10251 // eslint-disable-next-line @typescript-eslint/no-unused-vars
10252 async pauseSending(localId) {
10253 // Unimplemented.
10254 }
10255 // eslint-disable-next-line @typescript-eslint/no-unused-vars
10256 async resumeSending(localId) {
10257 // Unimplemented.
10258 }
10259 async replaceTrack(localId, track) {
10260 this.assertSendDirection();
10261 if (track) {
10262 logger$8.debug('replaceTrack() [localId:%s, track.id:%s]', localId, track.id);
10263 }
10264 else {
10265 logger$8.debug('replaceTrack() [localId:%s, no track]', localId);
10266 }
10267 const rtpSender = this._mapSendLocalIdRtpSender.get(localId);
10268 if (!rtpSender) {
10269 throw new Error('associated RTCRtpSender not found');
10270 }
10271 const oldTrack = rtpSender.track;
10272 await rtpSender.replaceTrack(track);
10273 // Remove the old track from the local stream.
10274 if (oldTrack) {
10275 this._sendStream.removeTrack(oldTrack);
10276 }
10277 // Add the new track to the local stream.
10278 if (track) {
10279 this._sendStream.addTrack(track);
10280 }
10281 }
10282 async setMaxSpatialLayer(localId, spatialLayer) {
10283 this.assertSendDirection();
10284 logger$8.debug('setMaxSpatialLayer() [localId:%s, spatialLayer:%s]', localId, spatialLayer);
10285 const rtpSender = this._mapSendLocalIdRtpSender.get(localId);
10286 if (!rtpSender) {
10287 throw new Error('associated RTCRtpSender not found');
10288 }
10289 const parameters = rtpSender.getParameters();
10290 parameters.encodings.forEach((encoding, idx) => {
10291 if (idx <= spatialLayer) {
10292 encoding.active = true;
10293 }
10294 else {
10295 encoding.active = false;
10296 }
10297 });
10298 await rtpSender.setParameters(parameters);
10299 }
10300 async setRtpEncodingParameters(localId, params) {
10301 this.assertSendDirection();
10302 logger$8.debug('setRtpEncodingParameters() [localId:%s, params:%o]', localId, params);
10303 const rtpSender = this._mapSendLocalIdRtpSender.get(localId);
10304 if (!rtpSender) {
10305 throw new Error('associated RTCRtpSender not found');
10306 }
10307 const parameters = rtpSender.getParameters();
10308 parameters.encodings.forEach((encoding, idx) => {
10309 parameters.encodings[idx] = { ...encoding, ...params };
10310 });
10311 await rtpSender.setParameters(parameters);
10312 }
10313 async getSenderStats(localId) {
10314 this.assertSendDirection();
10315 const rtpSender = this._mapSendLocalIdRtpSender.get(localId);
10316 if (!rtpSender) {
10317 throw new Error('associated RTCRtpSender not found');
10318 }
10319 return rtpSender.getStats();
10320 }
10321 async sendDataChannel({ ordered, maxPacketLifeTime, maxRetransmits, label, protocol }) {
10322 this.assertSendDirection();
10323 const options = {
10324 negotiated: true,
10325 id: this._nextSendSctpStreamId,
10326 ordered,
10327 maxPacketLifeTime,
10328 maxRetransmitTime: maxPacketLifeTime,
10329 maxRetransmits,
10330 protocol
10331 };
10332 logger$8.debug('sendDataChannel() [options:%o]', options);
10333 const dataChannel = this._pc.createDataChannel(label, options);
10334 // Increase next id.
10335 this._nextSendSctpStreamId =
10336 ++this._nextSendSctpStreamId % SCTP_NUM_STREAMS$6.MIS;
10337 // If this is the first DataChannel we need to create the SDP answer with
10338 // m=application section.
10339 if (!this._hasDataChannelMediaSection) {
10340 const offer = await this._pc.createOffer();
10341 const localSdpObject = sdpTransform$6.parse(offer.sdp);
10342 const offerMediaObject = localSdpObject.media
10343 .find((m) => m.type === 'application');
10344 if (!this._transportReady) {
10345 await this.setupTransport({
10346 localDtlsRole: this._forcedLocalDtlsRole ?? 'client',
10347 localSdpObject
10348 });
10349 }
10350 logger$8.debug('sendDataChannel() | calling pc.setLocalDescription() [offer:%o]', offer);
10351 await this._pc.setLocalDescription(offer);
10352 this._remoteSdp.sendSctpAssociation({ offerMediaObject });
10353 const answer = { type: 'answer', sdp: this._remoteSdp.getSdp() };
10354 logger$8.debug('sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]', answer);
10355 await this._pc.setRemoteDescription(answer);
10356 this._hasDataChannelMediaSection = true;
10357 }
10358 const sctpStreamParameters = {
10359 streamId: options.id,
10360 ordered: options.ordered,
10361 maxPacketLifeTime: options.maxPacketLifeTime,
10362 maxRetransmits: options.maxRetransmits
10363 };
10364 return { dataChannel, sctpStreamParameters };
10365 }
10366 async receive(optionsList) {
10367 this.assertRecvDirection();
10368 const results = [];
10369 for (const options of optionsList) {
10370 const { trackId, kind, rtpParameters, streamId } = options;
10371 logger$8.debug('receive() [trackId:%s, kind:%s]', trackId, kind);
10372 const mid = kind;
10373 this._remoteSdp.receive({
10374 mid,
10375 kind,
10376 offerRtpParameters: rtpParameters,
10377 streamId: streamId || rtpParameters.rtcp.cname,
10378 trackId
10379 });
10380 }
10381 const offer = { type: 'offer', sdp: this._remoteSdp.getSdp() };
10382 logger$8.debug('receive() | calling pc.setRemoteDescription() [offer:%o]', offer);
10383 await this._pc.setRemoteDescription(offer);
10384 let answer = await this._pc.createAnswer();
10385 const localSdpObject = sdpTransform$6.parse(answer.sdp);
10386 for (const options of optionsList) {
10387 const { kind, rtpParameters } = options;
10388 const mid = kind;
10389 const answerMediaObject = localSdpObject.media
10390 .find((m) => String(m.mid) === mid);
10391 // May need to modify codec parameters in the answer based on codec
10392 // parameters in the offer.
10393 sdpCommonUtils$6.applyCodecParameters({
10394 offerRtpParameters: rtpParameters,
10395 answerMediaObject
10396 });
10397 }
10398 answer = { type: 'answer', sdp: sdpTransform$6.write(localSdpObject) };
10399 if (!this._transportReady) {
10400 await this.setupTransport({
10401 localDtlsRole: this._forcedLocalDtlsRole ?? 'client',
10402 localSdpObject
10403 });
10404 }
10405 logger$8.debug('receive() | calling pc.setLocalDescription() [answer:%o]', answer);
10406 await this._pc.setLocalDescription(answer);
10407 for (const options of optionsList) {
10408 const { kind, trackId, rtpParameters } = options;
10409 const localId = trackId;
10410 const mid = kind;
10411 const rtpReceiver = this._pc.getReceivers()
10412 .find((r) => r.track && r.track.id === localId);
10413 if (!rtpReceiver) {
10414 throw new Error('new RTCRtpReceiver not');
10415 }
10416 // Insert into the map.
10417 this._mapRecvLocalIdInfo.set(localId, { mid, rtpParameters, rtpReceiver });
10418 results.push({
10419 localId,
10420 track: rtpReceiver.track,
10421 rtpReceiver
10422 });
10423 }
10424 return results;
10425 }
10426 async stopReceiving(localIds) {
10427 this.assertRecvDirection();
10428 for (const localId of localIds) {
10429 logger$8.debug('stopReceiving() [localId:%s]', localId);
10430 const { mid, rtpParameters } = this._mapRecvLocalIdInfo.get(localId) || {};
10431 // Remove from the map.
10432 this._mapRecvLocalIdInfo.delete(localId);
10433 this._remoteSdp.planBStopReceiving({ mid: mid, offerRtpParameters: rtpParameters });
10434 }
10435 const offer = { type: 'offer', sdp: this._remoteSdp.getSdp() };
10436 logger$8.debug('stopReceiving() | calling pc.setRemoteDescription() [offer:%o]', offer);
10437 await this._pc.setRemoteDescription(offer);
10438 const answer = await this._pc.createAnswer();
10439 logger$8.debug('stopReceiving() | calling pc.setLocalDescription() [answer:%o]', answer);
10440 await this._pc.setLocalDescription(answer);
10441 }
10442 async pauseReceiving(
10443 // eslint-disable-next-line @typescript-eslint/no-unused-vars
10444 localIds) {
10445 // Unimplemented.
10446 }
10447 async resumeReceiving(
10448 // eslint-disable-next-line @typescript-eslint/no-unused-vars
10449 localIds) {
10450 // Unimplemented.
10451 }
10452 async getReceiverStats(localId) {
10453 this.assertRecvDirection();
10454 const { rtpReceiver } = this._mapRecvLocalIdInfo.get(localId) || {};
10455 if (!rtpReceiver) {
10456 throw new Error('associated RTCRtpReceiver not found');
10457 }
10458 return rtpReceiver.getStats();
10459 }
10460 async receiveDataChannel({ sctpStreamParameters, label, protocol }) {
10461 this.assertRecvDirection();
10462 const { streamId, ordered, maxPacketLifeTime, maxRetransmits } = sctpStreamParameters;
10463 const options = {
10464 negotiated: true,
10465 id: streamId,
10466 ordered,
10467 maxPacketLifeTime,
10468 maxRetransmitTime: maxPacketLifeTime,
10469 maxRetransmits,
10470 protocol
10471 };
10472 logger$8.debug('receiveDataChannel() [options:%o]', options);
10473 const dataChannel = this._pc.createDataChannel(label, options);
10474 // If this is the first DataChannel we need to create the SDP offer with
10475 // m=application section.
10476 if (!this._hasDataChannelMediaSection) {
10477 this._remoteSdp.receiveSctpAssociation({ oldDataChannelSpec: true });
10478 const offer = { type: 'offer', sdp: this._remoteSdp.getSdp() };
10479 logger$8.debug('receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]', offer);
10480 await this._pc.setRemoteDescription(offer);
10481 const answer = await this._pc.createAnswer();
10482 if (!this._transportReady) {
10483 const localSdpObject = sdpTransform$6.parse(answer.sdp);
10484 await this.setupTransport({
10485 localDtlsRole: this._forcedLocalDtlsRole ?? 'client',
10486 localSdpObject
10487 });
10488 }
10489 logger$8.debug('receiveDataChannel() | calling pc.setRemoteDescription() [answer:%o]', answer);
10490 await this._pc.setLocalDescription(answer);
10491 this._hasDataChannelMediaSection = true;
10492 }
10493 return { dataChannel };
10494 }
10495 async setupTransport({ localDtlsRole, localSdpObject }) {
10496 if (!localSdpObject) {
10497 localSdpObject = sdpTransform$6.parse(this._pc.localDescription.sdp);
10498 }
10499 // Get our local DTLS parameters.
10500 const dtlsParameters = sdpCommonUtils$6.extractDtlsParameters({ sdpObject: localSdpObject });
10501 // Set our DTLS role.
10502 dtlsParameters.role = localDtlsRole;
10503 // Update the remote DTLS role in the SDP.
10504 this._remoteSdp.updateDtlsRole(localDtlsRole === 'client' ? 'server' : 'client');
10505 // Need to tell the remote transport about our parameters.
10506 await new Promise((resolve, reject) => {
10507 this.safeEmit('@connect', { dtlsParameters }, resolve, reject);
10508 });
10509 this._transportReady = true;
10510 }
10511 assertSendDirection() {
10512 if (this._direction !== 'send') {
10513 throw new Error('method can just be called for handlers with "send" direction');
10514 }
10515 }
10516 assertRecvDirection() {
10517 if (this._direction !== 'recv') {
10518 throw new Error('method can just be called for handlers with "recv" direction');
10519 }
10520 }
10521 }
10522 Chrome67$1.Chrome67 = Chrome67;
10523
10524 var Chrome55$1 = {};
10525
10526 var __createBinding$8 = (commonjsGlobal && commonjsGlobal.__createBinding) || (Object.create ? (function(o, m, k, k2) {
10527 if (k2 === undefined) k2 = k;
10528 var desc = Object.getOwnPropertyDescriptor(m, k);
10529 if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
10530 desc = { enumerable: true, get: function() { return m[k]; } };
10531 }
10532 Object.defineProperty(o, k2, desc);
10533 }) : (function(o, m, k, k2) {
10534 if (k2 === undefined) k2 = k;
10535 o[k2] = m[k];
10536 }));
10537 var __setModuleDefault$8 = (commonjsGlobal && commonjsGlobal.__setModuleDefault) || (Object.create ? (function(o, v) {
10538 Object.defineProperty(o, "default", { enumerable: true, value: v });
10539 }) : function(o, v) {
10540 o["default"] = v;
10541 });
10542 var __importStar$8 = (commonjsGlobal && commonjsGlobal.__importStar) || function (mod) {
10543 if (mod && mod.__esModule) return mod;
10544 var result = {};
10545 if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding$8(result, mod, k);
10546 __setModuleDefault$8(result, mod);
10547 return result;
10548 };
10549 Object.defineProperty(Chrome55$1, "__esModule", { value: true });
10550 Chrome55$1.Chrome55 = void 0;
10551 const sdpTransform$5 = __importStar$8(lib);
10552 const Logger_1$7 = Logger$3;
10553 const errors_1$6 = errors;
10554 const utils$8 = __importStar$8(utils$h);
10555 const ortc$7 = __importStar$8(ortc$d);
10556 const sdpCommonUtils$5 = __importStar$8(commonUtils);
10557 const sdpPlanBUtils$2 = __importStar$8(planBUtils);
10558 const HandlerInterface_1$6 = HandlerInterface$1;
10559 const RemoteSdp_1$5 = RemoteSdp$1;
10560 const logger$7 = new Logger_1$7.Logger('Chrome55');
10561 const SCTP_NUM_STREAMS$5 = { OS: 1024, MIS: 1024 };
10562 class Chrome55 extends HandlerInterface_1$6.HandlerInterface {
10563 /**
10564 * Creates a factory function.
10565 */
10566 static createFactory() {
10567 return () => new Chrome55();
10568 }
10569 constructor() {
10570 super();
10571 // Local stream for sending.
10572 this._sendStream = new MediaStream();
10573 // Map of sending MediaStreamTracks indexed by localId.
10574 this._mapSendLocalIdTrack = new Map();
10575 // Next sending localId.
10576 this._nextSendLocalId = 0;
10577 // Map of MID, RTP parameters and RTCRtpReceiver indexed by local id.
10578 // Value is an Object with mid, rtpParameters and rtpReceiver.
10579 this._mapRecvLocalIdInfo = new Map();
10580 // Whether a DataChannel m=application section has been created.
10581 this._hasDataChannelMediaSection = false;
10582 // Sending DataChannel id value counter. Incremented for each new DataChannel.
10583 this._nextSendSctpStreamId = 0;
10584 // Got transport local and remote parameters.
10585 this._transportReady = false;
10586 }
10587 get name() {
10588 return 'Chrome55';
10589 }
10590 close() {
10591 logger$7.debug('close()');
10592 // Close RTCPeerConnection.
10593 if (this._pc) {
10594 try {
10595 this._pc.close();
10596 }
10597 catch (error) { }
10598 }
10599 this.emit('@close');
10600 }
10601 async getNativeRtpCapabilities() {
10602 logger$7.debug('getNativeRtpCapabilities()');
10603 const pc = new RTCPeerConnection({
10604 iceServers: [],
10605 iceTransportPolicy: 'all',
10606 bundlePolicy: 'max-bundle',
10607 rtcpMuxPolicy: 'require',
10608 sdpSemantics: 'plan-b'
10609 });
10610 try {
10611 const offer = await pc.createOffer({
10612 offerToReceiveAudio: true,
10613 offerToReceiveVideo: true
10614 });
10615 try {
10616 pc.close();
10617 }
10618 catch (error) { }
10619 const sdpObject = sdpTransform$5.parse(offer.sdp);
10620 const nativeRtpCapabilities = sdpCommonUtils$5.extractRtpCapabilities({ sdpObject });
10621 return nativeRtpCapabilities;
10622 }
10623 catch (error) {
10624 try {
10625 pc.close();
10626 }
10627 catch (error2) { }
10628 throw error;
10629 }
10630 }
10631 async getNativeSctpCapabilities() {
10632 logger$7.debug('getNativeSctpCapabilities()');
10633 return {
10634 numStreams: SCTP_NUM_STREAMS$5
10635 };
10636 }
10637 run({ direction, iceParameters, iceCandidates, dtlsParameters, sctpParameters, iceServers, iceTransportPolicy, additionalSettings, proprietaryConstraints, extendedRtpCapabilities }) {
10638 logger$7.debug('run()');
10639 this._direction = direction;
10640 this._remoteSdp = new RemoteSdp_1$5.RemoteSdp({
10641 iceParameters,
10642 iceCandidates,
10643 dtlsParameters,
10644 sctpParameters,
10645 planB: true
10646 });
10647 this._sendingRtpParametersByKind =
10648 {
10649 audio: ortc$7.getSendingRtpParameters('audio', extendedRtpCapabilities),
10650 video: ortc$7.getSendingRtpParameters('video', extendedRtpCapabilities)
10651 };
10652 this._sendingRemoteRtpParametersByKind =
10653 {
10654 audio: ortc$7.getSendingRemoteRtpParameters('audio', extendedRtpCapabilities),
10655 video: ortc$7.getSendingRemoteRtpParameters('video', extendedRtpCapabilities)
10656 };
10657 if (dtlsParameters.role && dtlsParameters.role !== 'auto') {
10658 this._forcedLocalDtlsRole = dtlsParameters.role === 'server'
10659 ? 'client'
10660 : 'server';
10661 }
10662 this._pc = new RTCPeerConnection({
10663 iceServers: iceServers || [],
10664 iceTransportPolicy: iceTransportPolicy || 'all',
10665 bundlePolicy: 'max-bundle',
10666 rtcpMuxPolicy: 'require',
10667 sdpSemantics: 'plan-b',
10668 ...additionalSettings
10669 }, proprietaryConstraints);
10670 this._pc.addEventListener('icegatheringstatechange', () => {
10671 this.emit('@icegatheringstatechange', this._pc.iceGatheringState);
10672 });
10673 if (this._pc.connectionState) {
10674 this._pc.addEventListener('connectionstatechange', () => {
10675 this.emit('@connectionstatechange', this._pc.connectionState);
10676 });
10677 }
10678 else {
10679 this._pc.addEventListener('iceconnectionstatechange', () => {
10680 logger$7.warn('run() | pc.connectionState not supported, using pc.iceConnectionState');
10681 switch (this._pc.iceConnectionState) {
10682 case 'checking':
10683 this.emit('@connectionstatechange', 'connecting');
10684 break;
10685 case 'connected':
10686 case 'completed':
10687 this.emit('@connectionstatechange', 'connected');
10688 break;
10689 case 'failed':
10690 this.emit('@connectionstatechange', 'failed');
10691 break;
10692 case 'disconnected':
10693 this.emit('@connectionstatechange', 'disconnected');
10694 break;
10695 case 'closed':
10696 this.emit('@connectionstatechange', 'closed');
10697 break;
10698 }
10699 });
10700 }
10701 }
10702 async updateIceServers(iceServers) {
10703 logger$7.debug('updateIceServers()');
10704 const configuration = this._pc.getConfiguration();
10705 configuration.iceServers = iceServers;
10706 this._pc.setConfiguration(configuration);
10707 }
10708 async restartIce(iceParameters) {
10709 logger$7.debug('restartIce()');
10710 // Provide the remote SDP handler with new remote ICE parameters.
10711 this._remoteSdp.updateIceParameters(iceParameters);
10712 if (!this._transportReady) {
10713 return;
10714 }
10715 if (this._direction === 'send') {
10716 const offer = await this._pc.createOffer({ iceRestart: true });
10717 logger$7.debug('restartIce() | calling pc.setLocalDescription() [offer:%o]', offer);
10718 await this._pc.setLocalDescription(offer);
10719 const answer = { type: 'answer', sdp: this._remoteSdp.getSdp() };
10720 logger$7.debug('restartIce() | calling pc.setRemoteDescription() [answer:%o]', answer);
10721 await this._pc.setRemoteDescription(answer);
10722 }
10723 else {
10724 const offer = { type: 'offer', sdp: this._remoteSdp.getSdp() };
10725 logger$7.debug('restartIce() | calling pc.setRemoteDescription() [offer:%o]', offer);
10726 await this._pc.setRemoteDescription(offer);
10727 const answer = await this._pc.createAnswer();
10728 logger$7.debug('restartIce() | calling pc.setLocalDescription() [answer:%o]', answer);
10729 await this._pc.setLocalDescription(answer);
10730 }
10731 }
10732 async getTransportStats() {
10733 return this._pc.getStats();
10734 }
10735 async send({ track, encodings, codecOptions, codec }) {
10736 this.assertSendDirection();
10737 logger$7.debug('send() [kind:%s, track.id:%s]', track.kind, track.id);
10738 if (codec) {
10739 logger$7.warn('send() | codec selection is not available in %s handler', this.name);
10740 }
10741 this._sendStream.addTrack(track);
10742 this._pc.addStream(this._sendStream);
10743 let offer = await this._pc.createOffer();
10744 let localSdpObject = sdpTransform$5.parse(offer.sdp);
10745 let offerMediaObject;
10746 const sendingRtpParameters = utils$8.clone(this._sendingRtpParametersByKind[track.kind]);
10747 sendingRtpParameters.codecs =
10748 ortc$7.reduceCodecs(sendingRtpParameters.codecs);
10749 const sendingRemoteRtpParameters = utils$8.clone(this._sendingRemoteRtpParametersByKind[track.kind]);
10750 sendingRemoteRtpParameters.codecs =
10751 ortc$7.reduceCodecs(sendingRemoteRtpParameters.codecs);
10752 if (!this._transportReady) {
10753 await this.setupTransport({
10754 localDtlsRole: this._forcedLocalDtlsRole ?? 'client',
10755 localSdpObject
10756 });
10757 }
10758 if (track.kind === 'video' && encodings && encodings.length > 1) {
10759 logger$7.debug('send() | enabling simulcast');
10760 localSdpObject = sdpTransform$5.parse(offer.sdp);
10761 offerMediaObject = localSdpObject.media.find((m) => m.type === 'video');
10762 sdpPlanBUtils$2.addLegacySimulcast({
10763 offerMediaObject,
10764 track,
10765 numStreams: encodings.length
10766 });
10767 offer = { type: 'offer', sdp: sdpTransform$5.write(localSdpObject) };
10768 }
10769 logger$7.debug('send() | calling pc.setLocalDescription() [offer:%o]', offer);
10770 await this._pc.setLocalDescription(offer);
10771 localSdpObject = sdpTransform$5.parse(this._pc.localDescription.sdp);
10772 offerMediaObject = localSdpObject.media
10773 .find((m) => m.type === track.kind);
10774 // Set RTCP CNAME.
10775 sendingRtpParameters.rtcp.cname =
10776 sdpCommonUtils$5.getCname({ offerMediaObject });
10777 // Set RTP encodings.
10778 sendingRtpParameters.encodings =
10779 sdpPlanBUtils$2.getRtpEncodings({ offerMediaObject, track });
10780 // Complete encodings with given values.
10781 if (encodings) {
10782 for (let idx = 0; idx < sendingRtpParameters.encodings.length; ++idx) {
10783 if (encodings[idx]) {
10784 Object.assign(sendingRtpParameters.encodings[idx], encodings[idx]);
10785 }
10786 }
10787 }
10788 // If VP8 and there is effective simulcast, add scalabilityMode to each
10789 // encoding.
10790 if (sendingRtpParameters.encodings.length > 1 &&
10791 sendingRtpParameters.codecs[0].mimeType.toLowerCase() === 'video/vp8') {
10792 for (const encoding of sendingRtpParameters.encodings) {
10793 encoding.scalabilityMode = 'L1T3';
10794 }
10795 }
10796 this._remoteSdp.send({
10797 offerMediaObject,
10798 offerRtpParameters: sendingRtpParameters,
10799 answerRtpParameters: sendingRemoteRtpParameters,
10800 codecOptions
10801 });
10802 const answer = { type: 'answer', sdp: this._remoteSdp.getSdp() };
10803 logger$7.debug('send() | calling pc.setRemoteDescription() [answer:%o]', answer);
10804 await this._pc.setRemoteDescription(answer);
10805 const localId = String(this._nextSendLocalId);
10806 this._nextSendLocalId++;
10807 // Insert into the map.
10808 this._mapSendLocalIdTrack.set(localId, track);
10809 return {
10810 localId: localId,
10811 rtpParameters: sendingRtpParameters
10812 };
10813 }
10814 async stopSending(localId) {
10815 this.assertSendDirection();
10816 logger$7.debug('stopSending() [localId:%s]', localId);
10817 const track = this._mapSendLocalIdTrack.get(localId);
10818 if (!track) {
10819 throw new Error('track not found');
10820 }
10821 this._mapSendLocalIdTrack.delete(localId);
10822 this._sendStream.removeTrack(track);
10823 this._pc.addStream(this._sendStream);
10824 const offer = await this._pc.createOffer();
10825 logger$7.debug('stopSending() | calling pc.setLocalDescription() [offer:%o]', offer);
10826 try {
10827 await this._pc.setLocalDescription(offer);
10828 }
10829 catch (error) {
10830 // NOTE: If there are no sending tracks, setLocalDescription() will fail with
10831 // "Failed to create channels". If so, ignore it.
10832 if (this._sendStream.getTracks().length === 0) {
10833 logger$7.warn('stopSending() | ignoring expected error due no sending tracks: %s', error.toString());
10834 return;
10835 }
10836 throw error;
10837 }
10838 if (this._pc.signalingState === 'stable') {
10839 return;
10840 }
10841 const answer = { type: 'answer', sdp: this._remoteSdp.getSdp() };
10842 logger$7.debug('stopSending() | calling pc.setRemoteDescription() [answer:%o]', answer);
10843 await this._pc.setRemoteDescription(answer);
10844 }
10845 // eslint-disable-next-line @typescript-eslint/no-unused-vars
10846 async pauseSending(localId) {
10847 // Unimplemented.
10848 }
10849 // eslint-disable-next-line @typescript-eslint/no-unused-vars
10850 async resumeSending(localId) {
10851 // Unimplemented.
10852 }
10853 async replaceTrack(
10854 // eslint-disable-next-line @typescript-eslint/no-unused-vars
10855 localId, track) {
10856 throw new errors_1$6.UnsupportedError('not implemented');
10857 }
10858 // eslint-disable-next-line @typescript-eslint/no-unused-vars
10859 async setMaxSpatialLayer(localId, spatialLayer) {
10860 throw new errors_1$6.UnsupportedError(' not implemented');
10861 }
10862 // eslint-disable-next-line @typescript-eslint/no-unused-vars
10863 async setRtpEncodingParameters(localId, params) {
10864 throw new errors_1$6.UnsupportedError('not supported');
10865 }
10866 // eslint-disable-next-line @typescript-eslint/no-unused-vars
10867 async getSenderStats(localId) {
10868 throw new errors_1$6.UnsupportedError('not implemented');
10869 }
10870 async sendDataChannel({ ordered, maxPacketLifeTime, maxRetransmits, label, protocol }) {
10871 this.assertSendDirection();
10872 const options = {
10873 negotiated: true,
10874 id: this._nextSendSctpStreamId,
10875 ordered,
10876 maxPacketLifeTime,
10877 maxRetransmitTime: maxPacketLifeTime,
10878 maxRetransmits,
10879 protocol
10880 };
10881 logger$7.debug('sendDataChannel() [options:%o]', options);
10882 const dataChannel = this._pc.createDataChannel(label, options);
10883 // Increase next id.
10884 this._nextSendSctpStreamId =
10885 ++this._nextSendSctpStreamId % SCTP_NUM_STREAMS$5.MIS;
10886 // If this is the first DataChannel we need to create the SDP answer with
10887 // m=application section.
10888 if (!this._hasDataChannelMediaSection) {
10889 const offer = await this._pc.createOffer();
10890 const localSdpObject = sdpTransform$5.parse(offer.sdp);
10891 const offerMediaObject = localSdpObject.media
10892 .find((m) => m.type === 'application');
10893 if (!this._transportReady) {
10894 await this.setupTransport({
10895 localDtlsRole: this._forcedLocalDtlsRole ?? 'client',
10896 localSdpObject
10897 });
10898 }
10899 logger$7.debug('sendDataChannel() | calling pc.setLocalDescription() [offer:%o]', offer);
10900 await this._pc.setLocalDescription(offer);
10901 this._remoteSdp.sendSctpAssociation({ offerMediaObject });
10902 const answer = { type: 'answer', sdp: this._remoteSdp.getSdp() };
10903 logger$7.debug('sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]', answer);
10904 await this._pc.setRemoteDescription(answer);
10905 this._hasDataChannelMediaSection = true;
10906 }
10907 const sctpStreamParameters = {
10908 streamId: options.id,
10909 ordered: options.ordered,
10910 maxPacketLifeTime: options.maxPacketLifeTime,
10911 maxRetransmits: options.maxRetransmits
10912 };
10913 return { dataChannel, sctpStreamParameters };
10914 }
10915 async receive(optionsList) {
10916 this.assertRecvDirection();
10917 const results = [];
10918 for (const options of optionsList) {
10919 const { trackId, kind, rtpParameters, streamId } = options;
10920 logger$7.debug('receive() [trackId:%s, kind:%s]', trackId, kind);
10921 const mid = kind;
10922 this._remoteSdp.receive({
10923 mid,
10924 kind,
10925 offerRtpParameters: rtpParameters,
10926 streamId: streamId || rtpParameters.rtcp.cname,
10927 trackId
10928 });
10929 }
10930 const offer = { type: 'offer', sdp: this._remoteSdp.getSdp() };
10931 logger$7.debug('receive() | calling pc.setRemoteDescription() [offer:%o]', offer);
10932 await this._pc.setRemoteDescription(offer);
10933 let answer = await this._pc.createAnswer();
10934 const localSdpObject = sdpTransform$5.parse(answer.sdp);
10935 for (const options of optionsList) {
10936 const { kind, rtpParameters } = options;
10937 const mid = kind;
10938 const answerMediaObject = localSdpObject.media
10939 .find((m) => String(m.mid) === mid);
10940 // May need to modify codec parameters in the answer based on codec
10941 // parameters in the offer.
10942 sdpCommonUtils$5.applyCodecParameters({
10943 offerRtpParameters: rtpParameters,
10944 answerMediaObject
10945 });
10946 }
10947 answer = { type: 'answer', sdp: sdpTransform$5.write(localSdpObject) };
10948 if (!this._transportReady) {
10949 await this.setupTransport({
10950 localDtlsRole: this._forcedLocalDtlsRole ?? 'client',
10951 localSdpObject
10952 });
10953 }
10954 logger$7.debug('receive() | calling pc.setLocalDescription() [answer:%o]', answer);
10955 await this._pc.setLocalDescription(answer);
10956 for (const options of optionsList) {
10957 const { kind, trackId, rtpParameters } = options;
10958 const mid = kind;
10959 const localId = trackId;
10960 const streamId = options.streamId || rtpParameters.rtcp.cname;
10961 const stream = this._pc.getRemoteStreams()
10962 .find((s) => s.id === streamId);
10963 const track = stream.getTrackById(localId);
10964 if (!track) {
10965 throw new Error('remote track not found');
10966 }
10967 // Insert into the map.
10968 this._mapRecvLocalIdInfo.set(localId, { mid, rtpParameters });
10969 results.push({ localId, track });
10970 }
10971 return results;
10972 }
10973 async stopReceiving(localIds) {
10974 this.assertRecvDirection();
10975 for (const localId of localIds) {
10976 logger$7.debug('stopReceiving() [localId:%s]', localId);
10977 const { mid, rtpParameters } = this._mapRecvLocalIdInfo.get(localId) || {};
10978 // Remove from the map.
10979 this._mapRecvLocalIdInfo.delete(localId);
10980 this._remoteSdp.planBStopReceiving({ mid: mid, offerRtpParameters: rtpParameters });
10981 }
10982 const offer = { type: 'offer', sdp: this._remoteSdp.getSdp() };
10983 logger$7.debug('stopReceiving() | calling pc.setRemoteDescription() [offer:%o]', offer);
10984 await this._pc.setRemoteDescription(offer);
10985 const answer = await this._pc.createAnswer();
10986 logger$7.debug('stopReceiving() | calling pc.setLocalDescription() [answer:%o]', answer);
10987 await this._pc.setLocalDescription(answer);
10988 }
10989 async pauseReceiving(
10990 // eslint-disable-next-line @typescript-eslint/no-unused-vars
10991 localIds) {
10992 // Unimplemented.
10993 }
10994 async resumeReceiving(
10995 // eslint-disable-next-line @typescript-eslint/no-unused-vars
10996 localIds) {
10997 // Unimplemented.
10998 }
10999 // eslint-disable-next-line @typescript-eslint/no-unused-vars
11000 async getReceiverStats(localId) {
11001 throw new errors_1$6.UnsupportedError('not implemented');
11002 }
11003 async receiveDataChannel({ sctpStreamParameters, label, protocol }) {
11004 this.assertRecvDirection();
11005 const { streamId, ordered, maxPacketLifeTime, maxRetransmits } = sctpStreamParameters;
11006 const options = {
11007 negotiated: true,
11008 id: streamId,
11009 ordered,
11010 maxPacketLifeTime,
11011 maxRetransmitTime: maxPacketLifeTime,
11012 maxRetransmits,
11013 protocol
11014 };
11015 logger$7.debug('receiveDataChannel() [options:%o]', options);
11016 const dataChannel = this._pc.createDataChannel(label, options);
11017 // If this is the first DataChannel we need to create the SDP offer with
11018 // m=application section.
11019 if (!this._hasDataChannelMediaSection) {
11020 this._remoteSdp.receiveSctpAssociation({ oldDataChannelSpec: true });
11021 const offer = { type: 'offer', sdp: this._remoteSdp.getSdp() };
11022 logger$7.debug('receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]', offer);
11023 await this._pc.setRemoteDescription(offer);
11024 const answer = await this._pc.createAnswer();
11025 if (!this._transportReady) {
11026 const localSdpObject = sdpTransform$5.parse(answer.sdp);
11027 await this.setupTransport({
11028 localDtlsRole: this._forcedLocalDtlsRole ?? 'client',
11029 localSdpObject
11030 });
11031 }
11032 logger$7.debug('receiveDataChannel() | calling pc.setRemoteDescription() [answer:%o]', answer);
11033 await this._pc.setLocalDescription(answer);
11034 this._hasDataChannelMediaSection = true;
11035 }
11036 return { dataChannel };
11037 }
11038 async setupTransport({ localDtlsRole, localSdpObject }) {
11039 if (!localSdpObject) {
11040 localSdpObject = sdpTransform$5.parse(this._pc.localDescription.sdp);
11041 }
11042 // Get our local DTLS parameters.
11043 const dtlsParameters = sdpCommonUtils$5.extractDtlsParameters({ sdpObject: localSdpObject });
11044 // Set our DTLS role.
11045 dtlsParameters.role = localDtlsRole;
11046 // Update the remote DTLS role in the SDP.
11047 this._remoteSdp.updateDtlsRole(localDtlsRole === 'client' ? 'server' : 'client');
11048 // Need to tell the remote transport about our parameters.
11049 await new Promise((resolve, reject) => {
11050 this.safeEmit('@connect', { dtlsParameters }, resolve, reject);
11051 });
11052 this._transportReady = true;
11053 }
11054 assertSendDirection() {
11055 if (this._direction !== 'send') {
11056 throw new Error('method can just be called for handlers with "send" direction');
11057 }
11058 }
11059 assertRecvDirection() {
11060 if (this._direction !== 'recv') {
11061 throw new Error('method can just be called for handlers with "recv" direction');
11062 }
11063 }
11064 }
11065 Chrome55$1.Chrome55 = Chrome55;
11066
11067 var Firefox60$1 = {};
11068
11069 var __createBinding$7 = (commonjsGlobal && commonjsGlobal.__createBinding) || (Object.create ? (function(o, m, k, k2) {
11070 if (k2 === undefined) k2 = k;
11071 var desc = Object.getOwnPropertyDescriptor(m, k);
11072 if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
11073 desc = { enumerable: true, get: function() { return m[k]; } };
11074 }
11075 Object.defineProperty(o, k2, desc);
11076 }) : (function(o, m, k, k2) {
11077 if (k2 === undefined) k2 = k;
11078 o[k2] = m[k];
11079 }));
11080 var __setModuleDefault$7 = (commonjsGlobal && commonjsGlobal.__setModuleDefault) || (Object.create ? (function(o, v) {
11081 Object.defineProperty(o, "default", { enumerable: true, value: v });
11082 }) : function(o, v) {
11083 o["default"] = v;
11084 });
11085 var __importStar$7 = (commonjsGlobal && commonjsGlobal.__importStar) || function (mod) {
11086 if (mod && mod.__esModule) return mod;
11087 var result = {};
11088 if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding$7(result, mod, k);
11089 __setModuleDefault$7(result, mod);
11090 return result;
11091 };
11092 Object.defineProperty(Firefox60$1, "__esModule", { value: true });
11093 Firefox60$1.Firefox60 = void 0;
11094 const sdpTransform$4 = __importStar$7(lib);
11095 const Logger_1$6 = Logger$3;
11096 const errors_1$5 = errors;
11097 const utils$7 = __importStar$7(utils$h);
11098 const ortc$6 = __importStar$7(ortc$d);
11099 const sdpCommonUtils$4 = __importStar$7(commonUtils);
11100 const sdpUnifiedPlanUtils$2 = __importStar$7(unifiedPlanUtils);
11101 const HandlerInterface_1$5 = HandlerInterface$1;
11102 const RemoteSdp_1$4 = RemoteSdp$1;
11103 const scalabilityModes_1$2 = scalabilityModes;
11104 const logger$6 = new Logger_1$6.Logger('Firefox60');
11105 const SCTP_NUM_STREAMS$4 = { OS: 16, MIS: 2048 };
11106 class Firefox60 extends HandlerInterface_1$5.HandlerInterface {
11107 /**
11108 * Creates a factory function.
11109 */
11110 static createFactory() {
11111 return () => new Firefox60();
11112 }
11113 constructor() {
11114 super();
11115 // Closed flag.
11116 this._closed = false;
11117 // Map of RTCTransceivers indexed by MID.
11118 this._mapMidTransceiver = new Map();
11119 // Local stream for sending.
11120 this._sendStream = new MediaStream();
11121 // Whether a DataChannel m=application section has been created.
11122 this._hasDataChannelMediaSection = false;
11123 // Sending DataChannel id value counter. Incremented for each new DataChannel.
11124 this._nextSendSctpStreamId = 0;
11125 // Got transport local and remote parameters.
11126 this._transportReady = false;
11127 }
11128 get name() {
11129 return 'Firefox60';
11130 }
11131 close() {
11132 logger$6.debug('close()');
11133 if (this._closed) {
11134 return;
11135 }
11136 this._closed = true;
11137 // Close RTCPeerConnection.
11138 if (this._pc) {
11139 try {
11140 this._pc.close();
11141 }
11142 catch (error) { }
11143 }
11144 this.emit('@close');
11145 }
11146 async getNativeRtpCapabilities() {
11147 logger$6.debug('getNativeRtpCapabilities()');
11148 const pc = new RTCPeerConnection({
11149 iceServers: [],
11150 iceTransportPolicy: 'all',
11151 bundlePolicy: 'max-bundle',
11152 rtcpMuxPolicy: 'require'
11153 });
11154 // NOTE: We need to add a real video track to get the RID extension mapping.
11155 const canvas = document.createElement('canvas');
11156 // NOTE: Otherwise Firefox fails in next line.
11157 canvas.getContext('2d');
11158 const fakeStream = canvas.captureStream();
11159 const fakeVideoTrack = fakeStream.getVideoTracks()[0];
11160 try {
11161 pc.addTransceiver('audio', { direction: 'sendrecv' });
11162 const videoTransceiver = pc.addTransceiver(fakeVideoTrack, { direction: 'sendrecv' });
11163 const parameters = videoTransceiver.sender.getParameters();
11164 const encodings = [
11165 { rid: 'r0', maxBitrate: 100000 },
11166 { rid: 'r1', maxBitrate: 500000 }
11167 ];
11168 parameters.encodings = encodings;
11169 await videoTransceiver.sender.setParameters(parameters);
11170 const offer = await pc.createOffer();
11171 try {
11172 canvas.remove();
11173 }
11174 catch (error) { }
11175 try {
11176 fakeVideoTrack.stop();
11177 }
11178 catch (error) { }
11179 try {
11180 pc.close();
11181 }
11182 catch (error) { }
11183 const sdpObject = sdpTransform$4.parse(offer.sdp);
11184 const nativeRtpCapabilities = sdpCommonUtils$4.extractRtpCapabilities({ sdpObject });
11185 return nativeRtpCapabilities;
11186 }
11187 catch (error) {
11188 try {
11189 canvas.remove();
11190 }
11191 catch (error2) { }
11192 try {
11193 fakeVideoTrack.stop();
11194 }
11195 catch (error2) { }
11196 try {
11197 pc.close();
11198 }
11199 catch (error2) { }
11200 throw error;
11201 }
11202 }
11203 async getNativeSctpCapabilities() {
11204 logger$6.debug('getNativeSctpCapabilities()');
11205 return {
11206 numStreams: SCTP_NUM_STREAMS$4
11207 };
11208 }
11209 run({ direction, iceParameters, iceCandidates, dtlsParameters, sctpParameters, iceServers, iceTransportPolicy, additionalSettings, proprietaryConstraints, extendedRtpCapabilities }) {
11210 this.assertNotClosed();
11211 logger$6.debug('run()');
11212 this._direction = direction;
11213 this._remoteSdp = new RemoteSdp_1$4.RemoteSdp({
11214 iceParameters,
11215 iceCandidates,
11216 dtlsParameters,
11217 sctpParameters
11218 });
11219 this._sendingRtpParametersByKind =
11220 {
11221 audio: ortc$6.getSendingRtpParameters('audio', extendedRtpCapabilities),
11222 video: ortc$6.getSendingRtpParameters('video', extendedRtpCapabilities)
11223 };
11224 this._sendingRemoteRtpParametersByKind =
11225 {
11226 audio: ortc$6.getSendingRemoteRtpParameters('audio', extendedRtpCapabilities),
11227 video: ortc$6.getSendingRemoteRtpParameters('video', extendedRtpCapabilities)
11228 };
11229 this._pc = new RTCPeerConnection({
11230 iceServers: iceServers || [],
11231 iceTransportPolicy: iceTransportPolicy || 'all',
11232 bundlePolicy: 'max-bundle',
11233 rtcpMuxPolicy: 'require',
11234 ...additionalSettings
11235 }, proprietaryConstraints);
11236 this._pc.addEventListener('icegatheringstatechange', () => {
11237 this.emit('@icegatheringstatechange', this._pc.iceGatheringState);
11238 });
11239 if (this._pc.connectionState) {
11240 this._pc.addEventListener('connectionstatechange', () => {
11241 this.emit('@connectionstatechange', this._pc.connectionState);
11242 });
11243 }
11244 else {
11245 this._pc.addEventListener('iceconnectionstatechange', () => {
11246 logger$6.warn('run() | pc.connectionState not supported, using pc.iceConnectionState');
11247 switch (this._pc.iceConnectionState) {
11248 case 'checking':
11249 this.emit('@connectionstatechange', 'connecting');
11250 break;
11251 case 'connected':
11252 case 'completed':
11253 this.emit('@connectionstatechange', 'connected');
11254 break;
11255 case 'failed':
11256 this.emit('@connectionstatechange', 'failed');
11257 break;
11258 case 'disconnected':
11259 this.emit('@connectionstatechange', 'disconnected');
11260 break;
11261 case 'closed':
11262 this.emit('@connectionstatechange', 'closed');
11263 break;
11264 }
11265 });
11266 }
11267 }
11268 // eslint-disable-next-line @typescript-eslint/no-unused-vars
11269 async updateIceServers(iceServers) {
11270 this.assertNotClosed();
11271 // NOTE: Firefox does not implement pc.setConfiguration().
11272 throw new errors_1$5.UnsupportedError('not supported');
11273 }
11274 async restartIce(iceParameters) {
11275 this.assertNotClosed();
11276 logger$6.debug('restartIce()');
11277 // Provide the remote SDP handler with new remote ICE parameters.
11278 this._remoteSdp.updateIceParameters(iceParameters);
11279 if (!this._transportReady) {
11280 return;
11281 }
11282 if (this._direction === 'send') {
11283 const offer = await this._pc.createOffer({ iceRestart: true });
11284 logger$6.debug('restartIce() | calling pc.setLocalDescription() [offer:%o]', offer);
11285 await this._pc.setLocalDescription(offer);
11286 const answer = { type: 'answer', sdp: this._remoteSdp.getSdp() };
11287 logger$6.debug('restartIce() | calling pc.setRemoteDescription() [answer:%o]', answer);
11288 await this._pc.setRemoteDescription(answer);
11289 }
11290 else {
11291 const offer = { type: 'offer', sdp: this._remoteSdp.getSdp() };
11292 logger$6.debug('restartIce() | calling pc.setRemoteDescription() [offer:%o]', offer);
11293 await this._pc.setRemoteDescription(offer);
11294 const answer = await this._pc.createAnswer();
11295 logger$6.debug('restartIce() | calling pc.setLocalDescription() [answer:%o]', answer);
11296 await this._pc.setLocalDescription(answer);
11297 }
11298 }
11299 async getTransportStats() {
11300 this.assertNotClosed();
11301 return this._pc.getStats();
11302 }
11303 async send({ track, encodings, codecOptions, codec }) {
11304 this.assertNotClosed();
11305 this.assertSendDirection();
11306 logger$6.debug('send() [kind:%s, track.id:%s]', track.kind, track.id);
11307 if (encodings) {
11308 encodings = utils$7.clone(encodings);
11309 if (encodings.length > 1) {
11310 encodings.forEach((encoding, idx) => {
11311 encoding.rid = `r${idx}`;
11312 });
11313 // Clone the encodings and reverse them because Firefox likes them
11314 // from high to low.
11315 encodings.reverse();
11316 }
11317 }
11318 const sendingRtpParameters = utils$7.clone(this._sendingRtpParametersByKind[track.kind]);
11319 // This may throw.
11320 sendingRtpParameters.codecs =
11321 ortc$6.reduceCodecs(sendingRtpParameters.codecs, codec);
11322 const sendingRemoteRtpParameters = utils$7.clone(this._sendingRemoteRtpParametersByKind[track.kind]);
11323 // This may throw.
11324 sendingRemoteRtpParameters.codecs =
11325 ortc$6.reduceCodecs(sendingRemoteRtpParameters.codecs, codec);
11326 // NOTE: Firefox fails sometimes to properly anticipate the closed media
11327 // section that it should use, so don't reuse closed media sections.
11328 // https://github.com/versatica/mediasoup-client/issues/104
11329 //
11330 // const mediaSectionIdx = this._remoteSdp!.getNextMediaSectionIdx();
11331 const transceiver = this._pc.addTransceiver(track, { direction: 'sendonly', streams: [this._sendStream] });
11332 // NOTE: This is not spec compliants. Encodings should be given in addTransceiver
11333 // second argument, but Firefox does not support it.
11334 if (encodings) {
11335 const parameters = transceiver.sender.getParameters();
11336 parameters.encodings = encodings;
11337 await transceiver.sender.setParameters(parameters);
11338 }
11339 const offer = await this._pc.createOffer();
11340 let localSdpObject = sdpTransform$4.parse(offer.sdp);
11341 // In Firefox use DTLS role client even if we are the "offerer" since
11342 // Firefox does not respect ICE-Lite.
11343 if (!this._transportReady) {
11344 await this.setupTransport({ localDtlsRole: 'client', localSdpObject });
11345 }
11346 const layers = (0, scalabilityModes_1$2.parse)((encodings || [{}])[0].scalabilityMode);
11347 logger$6.debug('send() | calling pc.setLocalDescription() [offer:%o]', offer);
11348 await this._pc.setLocalDescription(offer);
11349 // We can now get the transceiver.mid.
11350 const localId = transceiver.mid;
11351 // Set MID.
11352 sendingRtpParameters.mid = localId;
11353 localSdpObject = sdpTransform$4.parse(this._pc.localDescription.sdp);
11354 const offerMediaObject = localSdpObject.media[localSdpObject.media.length - 1];
11355 // Set RTCP CNAME.
11356 sendingRtpParameters.rtcp.cname =
11357 sdpCommonUtils$4.getCname({ offerMediaObject });
11358 // Set RTP encodings by parsing the SDP offer if no encodings are given.
11359 if (!encodings) {
11360 sendingRtpParameters.encodings =
11361 sdpUnifiedPlanUtils$2.getRtpEncodings({ offerMediaObject });
11362 }
11363 // Set RTP encodings by parsing the SDP offer and complete them with given
11364 // one if just a single encoding has been given.
11365 else if (encodings.length === 1) {
11366 const newEncodings = sdpUnifiedPlanUtils$2.getRtpEncodings({ offerMediaObject });
11367 Object.assign(newEncodings[0], encodings[0]);
11368 sendingRtpParameters.encodings = newEncodings;
11369 }
11370 // Otherwise if more than 1 encoding are given use them verbatim (but
11371 // reverse them back since we reversed them above to satisfy Firefox).
11372 else {
11373 sendingRtpParameters.encodings = encodings.reverse();
11374 }
11375 // If VP8 or H264 and there is effective simulcast, add scalabilityMode to
11376 // each encoding.
11377 if (sendingRtpParameters.encodings.length > 1 &&
11378 (sendingRtpParameters.codecs[0].mimeType.toLowerCase() === 'video/vp8' ||
11379 sendingRtpParameters.codecs[0].mimeType.toLowerCase() === 'video/h264')) {
11380 for (const encoding of sendingRtpParameters.encodings) {
11381 if (encoding.scalabilityMode) {
11382 encoding.scalabilityMode = `L1T${layers.temporalLayers}`;
11383 }
11384 else {
11385 encoding.scalabilityMode = 'L1T3';
11386 }
11387 }
11388 }
11389 this._remoteSdp.send({
11390 offerMediaObject,
11391 offerRtpParameters: sendingRtpParameters,
11392 answerRtpParameters: sendingRemoteRtpParameters,
11393 codecOptions,
11394 extmapAllowMixed: true
11395 });
11396 const answer = { type: 'answer', sdp: this._remoteSdp.getSdp() };
11397 logger$6.debug('send() | calling pc.setRemoteDescription() [answer:%o]', answer);
11398 await this._pc.setRemoteDescription(answer);
11399 // Store in the map.
11400 this._mapMidTransceiver.set(localId, transceiver);
11401 return {
11402 localId,
11403 rtpParameters: sendingRtpParameters,
11404 rtpSender: transceiver.sender
11405 };
11406 }
11407 async stopSending(localId) {
11408 this.assertSendDirection();
11409 logger$6.debug('stopSending() [localId:%s]', localId);
11410 if (this._closed) {
11411 return;
11412 }
11413 const transceiver = this._mapMidTransceiver.get(localId);
11414 if (!transceiver) {
11415 throw new Error('associated transceiver not found');
11416 }
11417 transceiver.sender.replaceTrack(null);
11418 // NOTE: Cannot use stop() the transceiver due to the the note above in
11419 // send() method.
11420 // try
11421 // {
11422 // transceiver.stop();
11423 // }
11424 // catch (error)
11425 // {}
11426 this._pc.removeTrack(transceiver.sender);
11427 // NOTE: Cannot use closeMediaSection() due to the the note above in send()
11428 // method.
11429 // this._remoteSdp!.closeMediaSection(transceiver.mid);
11430 this._remoteSdp.disableMediaSection(transceiver.mid);
11431 const offer = await this._pc.createOffer();
11432 logger$6.debug('stopSending() | calling pc.setLocalDescription() [offer:%o]', offer);
11433 await this._pc.setLocalDescription(offer);
11434 const answer = { type: 'answer', sdp: this._remoteSdp.getSdp() };
11435 logger$6.debug('stopSending() | calling pc.setRemoteDescription() [answer:%o]', answer);
11436 await this._pc.setRemoteDescription(answer);
11437 this._mapMidTransceiver.delete(localId);
11438 }
11439 // eslint-disable-next-line @typescript-eslint/no-unused-vars
11440 async pauseSending(localId) {
11441 this.assertNotClosed();
11442 this.assertSendDirection();
11443 logger$6.debug('pauseSending() [localId:%s]', localId);
11444 const transceiver = this._mapMidTransceiver.get(localId);
11445 if (!transceiver) {
11446 throw new Error('associated RTCRtpTransceiver not found');
11447 }
11448 transceiver.direction = 'inactive';
11449 this._remoteSdp.pauseMediaSection(localId);
11450 const offer = await this._pc.createOffer();
11451 logger$6.debug('pauseSending() | calling pc.setLocalDescription() [offer:%o]', offer);
11452 await this._pc.setLocalDescription(offer);
11453 const answer = { type: 'answer', sdp: this._remoteSdp.getSdp() };
11454 logger$6.debug('pauseSending() | calling pc.setRemoteDescription() [answer:%o]', answer);
11455 await this._pc.setRemoteDescription(answer);
11456 }
11457 // eslint-disable-next-line @typescript-eslint/no-unused-vars
11458 async resumeSending(localId) {
11459 this.assertNotClosed();
11460 this.assertSendDirection();
11461 logger$6.debug('resumeSending() [localId:%s]', localId);
11462 const transceiver = this._mapMidTransceiver.get(localId);
11463 if (!transceiver) {
11464 throw new Error('associated RTCRtpTransceiver not found');
11465 }
11466 transceiver.direction = 'sendonly';
11467 this._remoteSdp.resumeSendingMediaSection(localId);
11468 const offer = await this._pc.createOffer();
11469 logger$6.debug('resumeSending() | calling pc.setLocalDescription() [offer:%o]', offer);
11470 await this._pc.setLocalDescription(offer);
11471 const answer = { type: 'answer', sdp: this._remoteSdp.getSdp() };
11472 logger$6.debug('resumeSending() | calling pc.setRemoteDescription() [answer:%o]', answer);
11473 await this._pc.setRemoteDescription(answer);
11474 }
11475 async replaceTrack(localId, track) {
11476 this.assertNotClosed();
11477 this.assertSendDirection();
11478 if (track) {
11479 logger$6.debug('replaceTrack() [localId:%s, track.id:%s]', localId, track.id);
11480 }
11481 else {
11482 logger$6.debug('replaceTrack() [localId:%s, no track]', localId);
11483 }
11484 const transceiver = this._mapMidTransceiver.get(localId);
11485 if (!transceiver) {
11486 throw new Error('associated RTCRtpTransceiver not found');
11487 }
11488 await transceiver.sender.replaceTrack(track);
11489 }
11490 async setMaxSpatialLayer(localId, spatialLayer) {
11491 this.assertNotClosed();
11492 this.assertSendDirection();
11493 logger$6.debug('setMaxSpatialLayer() [localId:%s, spatialLayer:%s]', localId, spatialLayer);
11494 const transceiver = this._mapMidTransceiver.get(localId);
11495 if (!transceiver) {
11496 throw new Error('associated transceiver not found');
11497 }
11498 const parameters = transceiver.sender.getParameters();
11499 // NOTE: We require encodings given from low to high, however Firefox
11500 // requires them in reverse order, so do magic here.
11501 spatialLayer = parameters.encodings.length - 1 - spatialLayer;
11502 parameters.encodings.forEach((encoding, idx) => {
11503 if (idx >= spatialLayer) {
11504 encoding.active = true;
11505 }
11506 else {
11507 encoding.active = false;
11508 }
11509 });
11510 await transceiver.sender.setParameters(parameters);
11511 this._remoteSdp.muxMediaSectionSimulcast(localId, parameters.encodings);
11512 const offer = await this._pc.createOffer();
11513 logger$6.debug('setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]', offer);
11514 await this._pc.setLocalDescription(offer);
11515 const answer = { type: 'answer', sdp: this._remoteSdp.getSdp() };
11516 logger$6.debug('setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]', answer);
11517 await this._pc.setRemoteDescription(answer);
11518 }
11519 async setRtpEncodingParameters(localId, params) {
11520 this.assertNotClosed();
11521 this.assertSendDirection();
11522 logger$6.debug('setRtpEncodingParameters() [localId:%s, params:%o]', localId, params);
11523 const transceiver = this._mapMidTransceiver.get(localId);
11524 if (!transceiver) {
11525 throw new Error('associated RTCRtpTransceiver not found');
11526 }
11527 const parameters = transceiver.sender.getParameters();
11528 parameters.encodings.forEach((encoding, idx) => {
11529 parameters.encodings[idx] = { ...encoding, ...params };
11530 });
11531 await transceiver.sender.setParameters(parameters);
11532 this._remoteSdp.muxMediaSectionSimulcast(localId, parameters.encodings);
11533 const offer = await this._pc.createOffer();
11534 logger$6.debug('setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]', offer);
11535 await this._pc.setLocalDescription(offer);
11536 const answer = { type: 'answer', sdp: this._remoteSdp.getSdp() };
11537 logger$6.debug('setRtpEncodingParameters() | calling pc.setRemoteDescription() [answer:%o]', answer);
11538 await this._pc.setRemoteDescription(answer);
11539 }
11540 async getSenderStats(localId) {
11541 this.assertNotClosed();
11542 this.assertSendDirection();
11543 const transceiver = this._mapMidTransceiver.get(localId);
11544 if (!transceiver) {
11545 throw new Error('associated RTCRtpTransceiver not found');
11546 }
11547 return transceiver.sender.getStats();
11548 }
11549 async sendDataChannel({ ordered, maxPacketLifeTime, maxRetransmits, label, protocol }) {
11550 this.assertNotClosed();
11551 this.assertSendDirection();
11552 const options = {
11553 negotiated: true,
11554 id: this._nextSendSctpStreamId,
11555 ordered,
11556 maxPacketLifeTime,
11557 maxRetransmits,
11558 protocol
11559 };
11560 logger$6.debug('sendDataChannel() [options:%o]', options);
11561 const dataChannel = this._pc.createDataChannel(label, options);
11562 // Increase next id.
11563 this._nextSendSctpStreamId =
11564 ++this._nextSendSctpStreamId % SCTP_NUM_STREAMS$4.MIS;
11565 // If this is the first DataChannel we need to create the SDP answer with
11566 // m=application section.
11567 if (!this._hasDataChannelMediaSection) {
11568 const offer = await this._pc.createOffer();
11569 const localSdpObject = sdpTransform$4.parse(offer.sdp);
11570 const offerMediaObject = localSdpObject.media
11571 .find((m) => m.type === 'application');
11572 if (!this._transportReady) {
11573 await this.setupTransport({ localDtlsRole: 'client', localSdpObject });
11574 }
11575 logger$6.debug('sendDataChannel() | calling pc.setLocalDescription() [offer:%o]', offer);
11576 await this._pc.setLocalDescription(offer);
11577 this._remoteSdp.sendSctpAssociation({ offerMediaObject });
11578 const answer = { type: 'answer', sdp: this._remoteSdp.getSdp() };
11579 logger$6.debug('sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]', answer);
11580 await this._pc.setRemoteDescription(answer);
11581 this._hasDataChannelMediaSection = true;
11582 }
11583 const sctpStreamParameters = {
11584 streamId: options.id,
11585 ordered: options.ordered,
11586 maxPacketLifeTime: options.maxPacketLifeTime,
11587 maxRetransmits: options.maxRetransmits
11588 };
11589 return { dataChannel, sctpStreamParameters };
11590 }
11591 async receive(
11592 // eslint-disable-next-line @typescript-eslint/no-unused-vars
11593 optionsList) {
11594 this.assertNotClosed();
11595 this.assertRecvDirection();
11596 const results = [];
11597 const mapLocalId = new Map();
11598 for (const options of optionsList) {
11599 const { trackId, kind, rtpParameters, streamId } = options;
11600 logger$6.debug('receive() [trackId:%s, kind:%s]', trackId, kind);
11601 const localId = rtpParameters.mid || String(this._mapMidTransceiver.size);
11602 mapLocalId.set(trackId, localId);
11603 this._remoteSdp.receive({
11604 mid: localId,
11605 kind,
11606 offerRtpParameters: rtpParameters,
11607 streamId: streamId || rtpParameters.rtcp.cname,
11608 trackId
11609 });
11610 }
11611 const offer = { type: 'offer', sdp: this._remoteSdp.getSdp() };
11612 logger$6.debug('receive() | calling pc.setRemoteDescription() [offer:%o]', offer);
11613 await this._pc.setRemoteDescription(offer);
11614 let answer = await this._pc.createAnswer();
11615 const localSdpObject = sdpTransform$4.parse(answer.sdp);
11616 for (const options of optionsList) {
11617 const { trackId, rtpParameters } = options;
11618 const localId = mapLocalId.get(trackId);
11619 const answerMediaObject = localSdpObject.media
11620 .find((m) => String(m.mid) === localId);
11621 // May need to modify codec parameters in the answer based on codec
11622 // parameters in the offer.
11623 sdpCommonUtils$4.applyCodecParameters({
11624 offerRtpParameters: rtpParameters,
11625 answerMediaObject
11626 });
11627 answer = { type: 'answer', sdp: sdpTransform$4.write(localSdpObject) };
11628 }
11629 if (!this._transportReady) {
11630 await this.setupTransport({ localDtlsRole: 'client', localSdpObject });
11631 }
11632 logger$6.debug('receive() | calling pc.setLocalDescription() [answer:%o]', answer);
11633 await this._pc.setLocalDescription(answer);
11634 for (const options of optionsList) {
11635 const { trackId } = options;
11636 const localId = mapLocalId.get(trackId);
11637 const transceiver = this._pc.getTransceivers()
11638 .find((t) => t.mid === localId);
11639 if (!transceiver) {
11640 throw new Error('new RTCRtpTransceiver not found');
11641 }
11642 // Store in the map.
11643 this._mapMidTransceiver.set(localId, transceiver);
11644 results.push({
11645 localId,
11646 track: transceiver.receiver.track,
11647 rtpReceiver: transceiver.receiver
11648 });
11649 }
11650 return results;
11651 }
11652 async stopReceiving(localIds) {
11653 this.assertRecvDirection();
11654 if (this._closed) {
11655 return;
11656 }
11657 for (const localId of localIds) {
11658 logger$6.debug('stopReceiving() [localId:%s]', localId);
11659 const transceiver = this._mapMidTransceiver.get(localId);
11660 if (!transceiver) {
11661 throw new Error('associated RTCRtpTransceiver not found');
11662 }
11663 this._remoteSdp.closeMediaSection(transceiver.mid);
11664 }
11665 const offer = { type: 'offer', sdp: this._remoteSdp.getSdp() };
11666 logger$6.debug('stopReceiving() | calling pc.setRemoteDescription() [offer:%o]', offer);
11667 await this._pc.setRemoteDescription(offer);
11668 const answer = await this._pc.createAnswer();
11669 logger$6.debug('stopReceiving() | calling pc.setLocalDescription() [answer:%o]', answer);
11670 await this._pc.setLocalDescription(answer);
11671 for (const localId of localIds) {
11672 this._mapMidTransceiver.delete(localId);
11673 }
11674 }
11675 async pauseReceiving(localIds) {
11676 this.assertNotClosed();
11677 this.assertRecvDirection();
11678 for (const localId of localIds) {
11679 logger$6.debug('pauseReceiving() [localId:%s]', localId);
11680 const transceiver = this._mapMidTransceiver.get(localId);
11681 if (!transceiver) {
11682 throw new Error('associated RTCRtpTransceiver not found');
11683 }
11684 transceiver.direction = 'inactive';
11685 this._remoteSdp.pauseMediaSection(localId);
11686 }
11687 const offer = { type: 'offer', sdp: this._remoteSdp.getSdp() };
11688 logger$6.debug('pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]', offer);
11689 await this._pc.setRemoteDescription(offer);
11690 const answer = await this._pc.createAnswer();
11691 logger$6.debug('pauseReceiving() | calling pc.setLocalDescription() [answer:%o]', answer);
11692 await this._pc.setLocalDescription(answer);
11693 }
11694 async resumeReceiving(localIds) {
11695 this.assertNotClosed();
11696 this.assertRecvDirection();
11697 for (const localId of localIds) {
11698 logger$6.debug('resumeReceiving() [localId:%s]', localId);
11699 const transceiver = this._mapMidTransceiver.get(localId);
11700 if (!transceiver) {
11701 throw new Error('associated RTCRtpTransceiver not found');
11702 }
11703 transceiver.direction = 'recvonly';
11704 this._remoteSdp.resumeReceivingMediaSection(localId);
11705 }
11706 const offer = { type: 'offer', sdp: this._remoteSdp.getSdp() };
11707 logger$6.debug('resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]', offer);
11708 await this._pc.setRemoteDescription(offer);
11709 const answer = await this._pc.createAnswer();
11710 logger$6.debug('resumeReceiving() | calling pc.setLocalDescription() [answer:%o]', answer);
11711 await this._pc.setLocalDescription(answer);
11712 }
11713 async getReceiverStats(localId) {
11714 this.assertRecvDirection();
11715 const transceiver = this._mapMidTransceiver.get(localId);
11716 if (!transceiver) {
11717 throw new Error('associated RTCRtpTransceiver not found');
11718 }
11719 return transceiver.receiver.getStats();
11720 }
11721 async receiveDataChannel({ sctpStreamParameters, label, protocol }) {
11722 this.assertNotClosed();
11723 this.assertRecvDirection();
11724 const { streamId, ordered, maxPacketLifeTime, maxRetransmits } = sctpStreamParameters;
11725 const options = {
11726 negotiated: true,
11727 id: streamId,
11728 ordered,
11729 maxPacketLifeTime,
11730 maxRetransmits,
11731 protocol
11732 };
11733 logger$6.debug('receiveDataChannel() [options:%o]', options);
11734 const dataChannel = this._pc.createDataChannel(label, options);
11735 // If this is the first DataChannel we need to create the SDP offer with
11736 // m=application section.
11737 if (!this._hasDataChannelMediaSection) {
11738 this._remoteSdp.receiveSctpAssociation();
11739 const offer = { type: 'offer', sdp: this._remoteSdp.getSdp() };
11740 logger$6.debug('receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]', offer);
11741 await this._pc.setRemoteDescription(offer);
11742 const answer = await this._pc.createAnswer();
11743 if (!this._transportReady) {
11744 const localSdpObject = sdpTransform$4.parse(answer.sdp);
11745 await this.setupTransport({ localDtlsRole: 'client', localSdpObject });
11746 }
11747 logger$6.debug('receiveDataChannel() | calling pc.setRemoteDescription() [answer:%o]', answer);
11748 await this._pc.setLocalDescription(answer);
11749 this._hasDataChannelMediaSection = true;
11750 }
11751 return { dataChannel };
11752 }
11753 async setupTransport({ localDtlsRole, localSdpObject }) {
11754 if (!localSdpObject) {
11755 localSdpObject = sdpTransform$4.parse(this._pc.localDescription.sdp);
11756 }
11757 // Get our local DTLS parameters.
11758 const dtlsParameters = sdpCommonUtils$4.extractDtlsParameters({ sdpObject: localSdpObject });
11759 // Set our DTLS role.
11760 dtlsParameters.role = localDtlsRole;
11761 // Update the remote DTLS role in the SDP.
11762 this._remoteSdp.updateDtlsRole(localDtlsRole === 'client' ? 'server' : 'client');
11763 // Need to tell the remote transport about our parameters.
11764 await new Promise((resolve, reject) => {
11765 this.safeEmit('@connect', { dtlsParameters }, resolve, reject);
11766 });
11767 this._transportReady = true;
11768 }
11769 assertNotClosed() {
11770 if (this._closed) {
11771 throw new errors_1$5.InvalidStateError('method called in a closed handler');
11772 }
11773 }
11774 assertSendDirection() {
11775 if (this._direction !== 'send') {
11776 throw new Error('method can just be called for handlers with "send" direction');
11777 }
11778 }
11779 assertRecvDirection() {
11780 if (this._direction !== 'recv') {
11781 throw new Error('method can just be called for handlers with "recv" direction');
11782 }
11783 }
11784 }
11785 Firefox60$1.Firefox60 = Firefox60;
11786
11787 var Safari12$1 = {};
11788
11789 var __createBinding$6 = (commonjsGlobal && commonjsGlobal.__createBinding) || (Object.create ? (function(o, m, k, k2) {
11790 if (k2 === undefined) k2 = k;
11791 var desc = Object.getOwnPropertyDescriptor(m, k);
11792 if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
11793 desc = { enumerable: true, get: function() { return m[k]; } };
11794 }
11795 Object.defineProperty(o, k2, desc);
11796 }) : (function(o, m, k, k2) {
11797 if (k2 === undefined) k2 = k;
11798 o[k2] = m[k];
11799 }));
11800 var __setModuleDefault$6 = (commonjsGlobal && commonjsGlobal.__setModuleDefault) || (Object.create ? (function(o, v) {
11801 Object.defineProperty(o, "default", { enumerable: true, value: v });
11802 }) : function(o, v) {
11803 o["default"] = v;
11804 });
11805 var __importStar$6 = (commonjsGlobal && commonjsGlobal.__importStar) || function (mod) {
11806 if (mod && mod.__esModule) return mod;
11807 var result = {};
11808 if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding$6(result, mod, k);
11809 __setModuleDefault$6(result, mod);
11810 return result;
11811 };
11812 Object.defineProperty(Safari12$1, "__esModule", { value: true });
11813 Safari12$1.Safari12 = void 0;
11814 const sdpTransform$3 = __importStar$6(lib);
11815 const Logger_1$5 = Logger$3;
11816 const utils$6 = __importStar$6(utils$h);
11817 const ortc$5 = __importStar$6(ortc$d);
11818 const sdpCommonUtils$3 = __importStar$6(commonUtils);
11819 const sdpUnifiedPlanUtils$1 = __importStar$6(unifiedPlanUtils);
11820 const ortcUtils$1 = __importStar$6(utils$e);
11821 const errors_1$4 = errors;
11822 const HandlerInterface_1$4 = HandlerInterface$1;
11823 const RemoteSdp_1$3 = RemoteSdp$1;
11824 const scalabilityModes_1$1 = scalabilityModes;
11825 const logger$5 = new Logger_1$5.Logger('Safari12');
11826 const SCTP_NUM_STREAMS$3 = { OS: 1024, MIS: 1024 };
11827 class Safari12 extends HandlerInterface_1$4.HandlerInterface {
11828 /**
11829 * Creates a factory function.
11830 */
11831 static createFactory() {
11832 return () => new Safari12();
11833 }
11834 constructor() {
11835 super();
11836 // Closed flag.
11837 this._closed = false;
11838 // Map of RTCTransceivers indexed by MID.
11839 this._mapMidTransceiver = new Map();
11840 // Local stream for sending.
11841 this._sendStream = new MediaStream();
11842 // Whether a DataChannel m=application section has been created.
11843 this._hasDataChannelMediaSection = false;
11844 // Sending DataChannel id value counter. Incremented for each new DataChannel.
11845 this._nextSendSctpStreamId = 0;
11846 // Got transport local and remote parameters.
11847 this._transportReady = false;
11848 }
11849 get name() {
11850 return 'Safari12';
11851 }
11852 close() {
11853 logger$5.debug('close()');
11854 if (this._closed) {
11855 return;
11856 }
11857 this._closed = true;
11858 // Close RTCPeerConnection.
11859 if (this._pc) {
11860 try {
11861 this._pc.close();
11862 }
11863 catch (error) { }
11864 }
11865 this.emit('@close');
11866 }
11867 async getNativeRtpCapabilities() {
11868 logger$5.debug('getNativeRtpCapabilities()');
11869 const pc = new RTCPeerConnection({
11870 iceServers: [],
11871 iceTransportPolicy: 'all',
11872 bundlePolicy: 'max-bundle',
11873 rtcpMuxPolicy: 'require'
11874 });
11875 try {
11876 pc.addTransceiver('audio');
11877 pc.addTransceiver('video');
11878 const offer = await pc.createOffer();
11879 try {
11880 pc.close();
11881 }
11882 catch (error) { }
11883 const sdpObject = sdpTransform$3.parse(offer.sdp);
11884 const nativeRtpCapabilities = sdpCommonUtils$3.extractRtpCapabilities({ sdpObject });
11885 // libwebrtc supports NACK for OPUS but doesn't announce it.
11886 ortcUtils$1.addNackSuppportForOpus(nativeRtpCapabilities);
11887 return nativeRtpCapabilities;
11888 }
11889 catch (error) {
11890 try {
11891 pc.close();
11892 }
11893 catch (error2) { }
11894 throw error;
11895 }
11896 }
11897 async getNativeSctpCapabilities() {
11898 logger$5.debug('getNativeSctpCapabilities()');
11899 return {
11900 numStreams: SCTP_NUM_STREAMS$3
11901 };
11902 }
11903 run({ direction, iceParameters, iceCandidates, dtlsParameters, sctpParameters, iceServers, iceTransportPolicy, additionalSettings, proprietaryConstraints, extendedRtpCapabilities }) {
11904 this.assertNotClosed();
11905 logger$5.debug('run()');
11906 this._direction = direction;
11907 this._remoteSdp = new RemoteSdp_1$3.RemoteSdp({
11908 iceParameters,
11909 iceCandidates,
11910 dtlsParameters,
11911 sctpParameters
11912 });
11913 this._sendingRtpParametersByKind =
11914 {
11915 audio: ortc$5.getSendingRtpParameters('audio', extendedRtpCapabilities),
11916 video: ortc$5.getSendingRtpParameters('video', extendedRtpCapabilities)
11917 };
11918 this._sendingRemoteRtpParametersByKind =
11919 {
11920 audio: ortc$5.getSendingRemoteRtpParameters('audio', extendedRtpCapabilities),
11921 video: ortc$5.getSendingRemoteRtpParameters('video', extendedRtpCapabilities)
11922 };
11923 if (dtlsParameters.role && dtlsParameters.role !== 'auto') {
11924 this._forcedLocalDtlsRole = dtlsParameters.role === 'server'
11925 ? 'client'
11926 : 'server';
11927 }
11928 this._pc = new RTCPeerConnection({
11929 iceServers: iceServers || [],
11930 iceTransportPolicy: iceTransportPolicy || 'all',
11931 bundlePolicy: 'max-bundle',
11932 rtcpMuxPolicy: 'require',
11933 ...additionalSettings
11934 }, proprietaryConstraints);
11935 this._pc.addEventListener('icegatheringstatechange', () => {
11936 this.emit('@icegatheringstatechange', this._pc.iceGatheringState);
11937 });
11938 if (this._pc.connectionState) {
11939 this._pc.addEventListener('connectionstatechange', () => {
11940 this.emit('@connectionstatechange', this._pc.connectionState);
11941 });
11942 }
11943 else {
11944 this._pc.addEventListener('iceconnectionstatechange', () => {
11945 logger$5.warn('run() | pc.connectionState not supported, using pc.iceConnectionState');
11946 switch (this._pc.iceConnectionState) {
11947 case 'checking':
11948 this.emit('@connectionstatechange', 'connecting');
11949 break;
11950 case 'connected':
11951 case 'completed':
11952 this.emit('@connectionstatechange', 'connected');
11953 break;
11954 case 'failed':
11955 this.emit('@connectionstatechange', 'failed');
11956 break;
11957 case 'disconnected':
11958 this.emit('@connectionstatechange', 'disconnected');
11959 break;
11960 case 'closed':
11961 this.emit('@connectionstatechange', 'closed');
11962 break;
11963 }
11964 });
11965 }
11966 }
11967 async updateIceServers(iceServers) {
11968 this.assertNotClosed();
11969 logger$5.debug('updateIceServers()');
11970 const configuration = this._pc.getConfiguration();
11971 configuration.iceServers = iceServers;
11972 this._pc.setConfiguration(configuration);
11973 }
11974 async restartIce(iceParameters) {
11975 this.assertNotClosed();
11976 logger$5.debug('restartIce()');
11977 // Provide the remote SDP handler with new remote ICE parameters.
11978 this._remoteSdp.updateIceParameters(iceParameters);
11979 if (!this._transportReady) {
11980 return;
11981 }
11982 if (this._direction === 'send') {
11983 const offer = await this._pc.createOffer({ iceRestart: true });
11984 logger$5.debug('restartIce() | calling pc.setLocalDescription() [offer:%o]', offer);
11985 await this._pc.setLocalDescription(offer);
11986 const answer = { type: 'answer', sdp: this._remoteSdp.getSdp() };
11987 logger$5.debug('restartIce() | calling pc.setRemoteDescription() [answer:%o]', answer);
11988 await this._pc.setRemoteDescription(answer);
11989 }
11990 else {
11991 const offer = { type: 'offer', sdp: this._remoteSdp.getSdp() };
11992 logger$5.debug('restartIce() | calling pc.setRemoteDescription() [offer:%o]', offer);
11993 await this._pc.setRemoteDescription(offer);
11994 const answer = await this._pc.createAnswer();
11995 logger$5.debug('restartIce() | calling pc.setLocalDescription() [answer:%o]', answer);
11996 await this._pc.setLocalDescription(answer);
11997 }
11998 }
11999 async getTransportStats() {
12000 this.assertNotClosed();
12001 return this._pc.getStats();
12002 }
12003 async send({ track, encodings, codecOptions, codec }) {
12004 this.assertNotClosed();
12005 this.assertSendDirection();
12006 logger$5.debug('send() [kind:%s, track.id:%s]', track.kind, track.id);
12007 const sendingRtpParameters = utils$6.clone(this._sendingRtpParametersByKind[track.kind]);
12008 // This may throw.
12009 sendingRtpParameters.codecs =
12010 ortc$5.reduceCodecs(sendingRtpParameters.codecs, codec);
12011 const sendingRemoteRtpParameters = utils$6.clone(this._sendingRemoteRtpParametersByKind[track.kind]);
12012 // This may throw.
12013 sendingRemoteRtpParameters.codecs =
12014 ortc$5.reduceCodecs(sendingRemoteRtpParameters.codecs, codec);
12015 const mediaSectionIdx = this._remoteSdp.getNextMediaSectionIdx();
12016 const transceiver = this._pc.addTransceiver(track, { direction: 'sendonly', streams: [this._sendStream] });
12017 let offer = await this._pc.createOffer();
12018 let localSdpObject = sdpTransform$3.parse(offer.sdp);
12019 let offerMediaObject;
12020 if (!this._transportReady) {
12021 await this.setupTransport({
12022 localDtlsRole: this._forcedLocalDtlsRole ?? 'client',
12023 localSdpObject
12024 });
12025 }
12026 const layers = (0, scalabilityModes_1$1.parse)((encodings || [{}])[0].scalabilityMode);
12027 if (encodings && encodings.length > 1) {
12028 logger$5.debug('send() | enabling legacy simulcast');
12029 localSdpObject = sdpTransform$3.parse(offer.sdp);
12030 offerMediaObject = localSdpObject.media[mediaSectionIdx.idx];
12031 sdpUnifiedPlanUtils$1.addLegacySimulcast({
12032 offerMediaObject,
12033 numStreams: encodings.length
12034 });
12035 offer = { type: 'offer', sdp: sdpTransform$3.write(localSdpObject) };
12036 }
12037 logger$5.debug('send() | calling pc.setLocalDescription() [offer:%o]', offer);
12038 await this._pc.setLocalDescription(offer);
12039 // We can now get the transceiver.mid.
12040 const localId = transceiver.mid;
12041 // Set MID.
12042 sendingRtpParameters.mid = localId;
12043 localSdpObject = sdpTransform$3.parse(this._pc.localDescription.sdp);
12044 offerMediaObject = localSdpObject.media[mediaSectionIdx.idx];
12045 // Set RTCP CNAME.
12046 sendingRtpParameters.rtcp.cname =
12047 sdpCommonUtils$3.getCname({ offerMediaObject });
12048 // Set RTP encodings.
12049 sendingRtpParameters.encodings =
12050 sdpUnifiedPlanUtils$1.getRtpEncodings({ offerMediaObject });
12051 // Complete encodings with given values.
12052 if (encodings) {
12053 for (let idx = 0; idx < sendingRtpParameters.encodings.length; ++idx) {
12054 if (encodings[idx]) {
12055 Object.assign(sendingRtpParameters.encodings[idx], encodings[idx]);
12056 }
12057 }
12058 }
12059 // If VP8 or H264 and there is effective simulcast, add scalabilityMode to
12060 // each encoding.
12061 if (sendingRtpParameters.encodings.length > 1 &&
12062 (sendingRtpParameters.codecs[0].mimeType.toLowerCase() === 'video/vp8' ||
12063 sendingRtpParameters.codecs[0].mimeType.toLowerCase() === 'video/h264')) {
12064 for (const encoding of sendingRtpParameters.encodings) {
12065 if (encoding.scalabilityMode) {
12066 encoding.scalabilityMode = `L1T${layers.temporalLayers}`;
12067 }
12068 else {
12069 encoding.scalabilityMode = 'L1T3';
12070 }
12071 }
12072 }
12073 this._remoteSdp.send({
12074 offerMediaObject,
12075 reuseMid: mediaSectionIdx.reuseMid,
12076 offerRtpParameters: sendingRtpParameters,
12077 answerRtpParameters: sendingRemoteRtpParameters,
12078 codecOptions
12079 });
12080 const answer = { type: 'answer', sdp: this._remoteSdp.getSdp() };
12081 logger$5.debug('send() | calling pc.setRemoteDescription() [answer:%o]', answer);
12082 await this._pc.setRemoteDescription(answer);
12083 // Store in the map.
12084 this._mapMidTransceiver.set(localId, transceiver);
12085 return {
12086 localId,
12087 rtpParameters: sendingRtpParameters,
12088 rtpSender: transceiver.sender
12089 };
12090 }
12091 async stopSending(localId) {
12092 this.assertSendDirection();
12093 if (this._closed) {
12094 return;
12095 }
12096 logger$5.debug('stopSending() [localId:%s]', localId);
12097 const transceiver = this._mapMidTransceiver.get(localId);
12098 if (!transceiver) {
12099 throw new Error('associated RTCRtpTransceiver not found');
12100 }
12101 transceiver.sender.replaceTrack(null);
12102 this._pc.removeTrack(transceiver.sender);
12103 const mediaSectionClosed = this._remoteSdp.closeMediaSection(transceiver.mid);
12104 if (mediaSectionClosed) {
12105 try {
12106 transceiver.stop();
12107 }
12108 catch (error) { }
12109 }
12110 const offer = await this._pc.createOffer();
12111 logger$5.debug('stopSending() | calling pc.setLocalDescription() [offer:%o]', offer);
12112 await this._pc.setLocalDescription(offer);
12113 const answer = { type: 'answer', sdp: this._remoteSdp.getSdp() };
12114 logger$5.debug('stopSending() | calling pc.setRemoteDescription() [answer:%o]', answer);
12115 await this._pc.setRemoteDescription(answer);
12116 this._mapMidTransceiver.delete(localId);
12117 }
12118 // eslint-disable-next-line @typescript-eslint/no-unused-vars
12119 async pauseSending(localId) {
12120 this.assertNotClosed();
12121 this.assertSendDirection();
12122 logger$5.debug('pauseSending() [localId:%s]', localId);
12123 const transceiver = this._mapMidTransceiver.get(localId);
12124 if (!transceiver) {
12125 throw new Error('associated RTCRtpTransceiver not found');
12126 }
12127 transceiver.direction = 'inactive';
12128 this._remoteSdp.pauseMediaSection(localId);
12129 const offer = await this._pc.createOffer();
12130 logger$5.debug('pauseSending() | calling pc.setLocalDescription() [offer:%o]', offer);
12131 await this._pc.setLocalDescription(offer);
12132 const answer = { type: 'answer', sdp: this._remoteSdp.getSdp() };
12133 logger$5.debug('pauseSending() | calling pc.setRemoteDescription() [answer:%o]', answer);
12134 await this._pc.setRemoteDescription(answer);
12135 }
12136 // eslint-disable-next-line @typescript-eslint/no-unused-vars
12137 async resumeSending(localId) {
12138 this.assertNotClosed();
12139 this.assertSendDirection();
12140 logger$5.debug('resumeSending() [localId:%s]', localId);
12141 const transceiver = this._mapMidTransceiver.get(localId);
12142 if (!transceiver) {
12143 throw new Error('associated RTCRtpTransceiver not found');
12144 }
12145 transceiver.direction = 'sendonly';
12146 this._remoteSdp.resumeSendingMediaSection(localId);
12147 const offer = await this._pc.createOffer();
12148 logger$5.debug('resumeSending() | calling pc.setLocalDescription() [offer:%o]', offer);
12149 await this._pc.setLocalDescription(offer);
12150 const answer = { type: 'answer', sdp: this._remoteSdp.getSdp() };
12151 logger$5.debug('resumeSending() | calling pc.setRemoteDescription() [answer:%o]', answer);
12152 await this._pc.setRemoteDescription(answer);
12153 }
12154 async replaceTrack(localId, track) {
12155 this.assertNotClosed();
12156 this.assertSendDirection();
12157 if (track) {
12158 logger$5.debug('replaceTrack() [localId:%s, track.id:%s]', localId, track.id);
12159 }
12160 else {
12161 logger$5.debug('replaceTrack() [localId:%s, no track]', localId);
12162 }
12163 const transceiver = this._mapMidTransceiver.get(localId);
12164 if (!transceiver) {
12165 throw new Error('associated RTCRtpTransceiver not found');
12166 }
12167 await transceiver.sender.replaceTrack(track);
12168 }
12169 async setMaxSpatialLayer(localId, spatialLayer) {
12170 this.assertNotClosed();
12171 this.assertSendDirection();
12172 logger$5.debug('setMaxSpatialLayer() [localId:%s, spatialLayer:%s]', localId, spatialLayer);
12173 const transceiver = this._mapMidTransceiver.get(localId);
12174 if (!transceiver) {
12175 throw new Error('associated RTCRtpTransceiver not found');
12176 }
12177 const parameters = transceiver.sender.getParameters();
12178 parameters.encodings.forEach((encoding, idx) => {
12179 if (idx <= spatialLayer) {
12180 encoding.active = true;
12181 }
12182 else {
12183 encoding.active = false;
12184 }
12185 });
12186 await transceiver.sender.setParameters(parameters);
12187 this._remoteSdp.muxMediaSectionSimulcast(localId, parameters.encodings);
12188 const offer = await this._pc.createOffer();
12189 logger$5.debug('setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]', offer);
12190 await this._pc.setLocalDescription(offer);
12191 const answer = { type: 'answer', sdp: this._remoteSdp.getSdp() };
12192 logger$5.debug('setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]', answer);
12193 await this._pc.setRemoteDescription(answer);
12194 }
12195 async setRtpEncodingParameters(localId, params) {
12196 this.assertNotClosed();
12197 this.assertSendDirection();
12198 logger$5.debug('setRtpEncodingParameters() [localId:%s, params:%o]', localId, params);
12199 const transceiver = this._mapMidTransceiver.get(localId);
12200 if (!transceiver) {
12201 throw new Error('associated RTCRtpTransceiver not found');
12202 }
12203 const parameters = transceiver.sender.getParameters();
12204 parameters.encodings.forEach((encoding, idx) => {
12205 parameters.encodings[idx] = { ...encoding, ...params };
12206 });
12207 await transceiver.sender.setParameters(parameters);
12208 this._remoteSdp.muxMediaSectionSimulcast(localId, parameters.encodings);
12209 const offer = await this._pc.createOffer();
12210 logger$5.debug('setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]', offer);
12211 await this._pc.setLocalDescription(offer);
12212 const answer = { type: 'answer', sdp: this._remoteSdp.getSdp() };
12213 logger$5.debug('setRtpEncodingParameters() | calling pc.setRemoteDescription() [answer:%o]', answer);
12214 await this._pc.setRemoteDescription(answer);
12215 }
12216 async getSenderStats(localId) {
12217 this.assertNotClosed();
12218 this.assertSendDirection();
12219 const transceiver = this._mapMidTransceiver.get(localId);
12220 if (!transceiver) {
12221 throw new Error('associated RTCRtpTransceiver not found');
12222 }
12223 return transceiver.sender.getStats();
12224 }
12225 async sendDataChannel({ ordered, maxPacketLifeTime, maxRetransmits, label, protocol }) {
12226 this.assertNotClosed();
12227 this.assertSendDirection();
12228 const options = {
12229 negotiated: true,
12230 id: this._nextSendSctpStreamId,
12231 ordered,
12232 maxPacketLifeTime,
12233 maxRetransmits,
12234 protocol
12235 };
12236 logger$5.debug('sendDataChannel() [options:%o]', options);
12237 const dataChannel = this._pc.createDataChannel(label, options);
12238 // Increase next id.
12239 this._nextSendSctpStreamId =
12240 ++this._nextSendSctpStreamId % SCTP_NUM_STREAMS$3.MIS;
12241 // If this is the first DataChannel we need to create the SDP answer with
12242 // m=application section.
12243 if (!this._hasDataChannelMediaSection) {
12244 const offer = await this._pc.createOffer();
12245 const localSdpObject = sdpTransform$3.parse(offer.sdp);
12246 const offerMediaObject = localSdpObject.media
12247 .find((m) => m.type === 'application');
12248 if (!this._transportReady) {
12249 await this.setupTransport({
12250 localDtlsRole: this._forcedLocalDtlsRole ?? 'client',
12251 localSdpObject
12252 });
12253 }
12254 logger$5.debug('sendDataChannel() | calling pc.setLocalDescription() [offer:%o]', offer);
12255 await this._pc.setLocalDescription(offer);
12256 this._remoteSdp.sendSctpAssociation({ offerMediaObject });
12257 const answer = { type: 'answer', sdp: this._remoteSdp.getSdp() };
12258 logger$5.debug('sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]', answer);
12259 await this._pc.setRemoteDescription(answer);
12260 this._hasDataChannelMediaSection = true;
12261 }
12262 const sctpStreamParameters = {
12263 streamId: options.id,
12264 ordered: options.ordered,
12265 maxPacketLifeTime: options.maxPacketLifeTime,
12266 maxRetransmits: options.maxRetransmits
12267 };
12268 return { dataChannel, sctpStreamParameters };
12269 }
12270 async receive(optionsList) {
12271 this.assertNotClosed();
12272 this.assertRecvDirection();
12273 const results = [];
12274 const mapLocalId = new Map();
12275 for (const options of optionsList) {
12276 const { trackId, kind, rtpParameters, streamId } = options;
12277 logger$5.debug('receive() [trackId:%s, kind:%s]', trackId, kind);
12278 const localId = rtpParameters.mid || String(this._mapMidTransceiver.size);
12279 mapLocalId.set(trackId, localId);
12280 this._remoteSdp.receive({
12281 mid: localId,
12282 kind,
12283 offerRtpParameters: rtpParameters,
12284 streamId: streamId || rtpParameters.rtcp.cname,
12285 trackId
12286 });
12287 }
12288 const offer = { type: 'offer', sdp: this._remoteSdp.getSdp() };
12289 logger$5.debug('receive() | calling pc.setRemoteDescription() [offer:%o]', offer);
12290 await this._pc.setRemoteDescription(offer);
12291 let answer = await this._pc.createAnswer();
12292 const localSdpObject = sdpTransform$3.parse(answer.sdp);
12293 for (const options of optionsList) {
12294 const { trackId, rtpParameters } = options;
12295 const localId = mapLocalId.get(trackId);
12296 const answerMediaObject = localSdpObject.media
12297 .find((m) => String(m.mid) === localId);
12298 // May need to modify codec parameters in the answer based on codec
12299 // parameters in the offer.
12300 sdpCommonUtils$3.applyCodecParameters({
12301 offerRtpParameters: rtpParameters,
12302 answerMediaObject
12303 });
12304 }
12305 answer = { type: 'answer', sdp: sdpTransform$3.write(localSdpObject) };
12306 if (!this._transportReady) {
12307 await this.setupTransport({
12308 localDtlsRole: this._forcedLocalDtlsRole ?? 'client',
12309 localSdpObject
12310 });
12311 }
12312 logger$5.debug('receive() | calling pc.setLocalDescription() [answer:%o]', answer);
12313 await this._pc.setLocalDescription(answer);
12314 for (const options of optionsList) {
12315 const { trackId } = options;
12316 const localId = mapLocalId.get(trackId);
12317 const transceiver = this._pc.getTransceivers()
12318 .find((t) => t.mid === localId);
12319 if (!transceiver) {
12320 throw new Error('new RTCRtpTransceiver not found');
12321 }
12322 // Store in the map.
12323 this._mapMidTransceiver.set(localId, transceiver);
12324 results.push({
12325 localId,
12326 track: transceiver.receiver.track,
12327 rtpReceiver: transceiver.receiver
12328 });
12329 }
12330 return results;
12331 }
12332 async stopReceiving(localIds) {
12333 this.assertRecvDirection();
12334 if (this._closed) {
12335 return;
12336 }
12337 for (const localId of localIds) {
12338 logger$5.debug('stopReceiving() [localId:%s]', localId);
12339 const transceiver = this._mapMidTransceiver.get(localId);
12340 if (!transceiver) {
12341 throw new Error('associated RTCRtpTransceiver not found');
12342 }
12343 this._remoteSdp.closeMediaSection(transceiver.mid);
12344 }
12345 const offer = { type: 'offer', sdp: this._remoteSdp.getSdp() };
12346 logger$5.debug('stopReceiving() | calling pc.setRemoteDescription() [offer:%o]', offer);
12347 await this._pc.setRemoteDescription(offer);
12348 const answer = await this._pc.createAnswer();
12349 logger$5.debug('stopReceiving() | calling pc.setLocalDescription() [answer:%o]', answer);
12350 await this._pc.setLocalDescription(answer);
12351 for (const localId of localIds) {
12352 this._mapMidTransceiver.delete(localId);
12353 }
12354 }
12355 async pauseReceiving(localIds) {
12356 this.assertNotClosed();
12357 this.assertRecvDirection();
12358 for (const localId of localIds) {
12359 logger$5.debug('pauseReceiving() [localId:%s]', localId);
12360 const transceiver = this._mapMidTransceiver.get(localId);
12361 if (!transceiver) {
12362 throw new Error('associated RTCRtpTransceiver not found');
12363 }
12364 transceiver.direction = 'inactive';
12365 this._remoteSdp.pauseMediaSection(localId);
12366 }
12367 const offer = { type: 'offer', sdp: this._remoteSdp.getSdp() };
12368 logger$5.debug('pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]', offer);
12369 await this._pc.setRemoteDescription(offer);
12370 const answer = await this._pc.createAnswer();
12371 logger$5.debug('pauseReceiving() | calling pc.setLocalDescription() [answer:%o]', answer);
12372 await this._pc.setLocalDescription(answer);
12373 }
12374 async resumeReceiving(localIds) {
12375 this.assertNotClosed();
12376 this.assertRecvDirection();
12377 for (const localId of localIds) {
12378 logger$5.debug('resumeReceiving() [localId:%s]', localId);
12379 const transceiver = this._mapMidTransceiver.get(localId);
12380 if (!transceiver) {
12381 throw new Error('associated RTCRtpTransceiver not found');
12382 }
12383 transceiver.direction = 'recvonly';
12384 this._remoteSdp.resumeReceivingMediaSection(localId);
12385 }
12386 const offer = { type: 'offer', sdp: this._remoteSdp.getSdp() };
12387 logger$5.debug('resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]', offer);
12388 await this._pc.setRemoteDescription(offer);
12389 const answer = await this._pc.createAnswer();
12390 logger$5.debug('resumeReceiving() | calling pc.setLocalDescription() [answer:%o]', answer);
12391 await this._pc.setLocalDescription(answer);
12392 }
12393 async getReceiverStats(localId) {
12394 this.assertNotClosed();
12395 this.assertRecvDirection();
12396 const transceiver = this._mapMidTransceiver.get(localId);
12397 if (!transceiver) {
12398 throw new Error('associated RTCRtpTransceiver not found');
12399 }
12400 return transceiver.receiver.getStats();
12401 }
12402 async receiveDataChannel({ sctpStreamParameters, label, protocol }) {
12403 this.assertNotClosed();
12404 this.assertRecvDirection();
12405 const { streamId, ordered, maxPacketLifeTime, maxRetransmits } = sctpStreamParameters;
12406 const options = {
12407 negotiated: true,
12408 id: streamId,
12409 ordered,
12410 maxPacketLifeTime,
12411 maxRetransmits,
12412 protocol
12413 };
12414 logger$5.debug('receiveDataChannel() [options:%o]', options);
12415 const dataChannel = this._pc.createDataChannel(label, options);
12416 // If this is the first DataChannel we need to create the SDP offer with
12417 // m=application section.
12418 if (!this._hasDataChannelMediaSection) {
12419 this._remoteSdp.receiveSctpAssociation();
12420 const offer = { type: 'offer', sdp: this._remoteSdp.getSdp() };
12421 logger$5.debug('receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]', offer);
12422 await this._pc.setRemoteDescription(offer);
12423 const answer = await this._pc.createAnswer();
12424 if (!this._transportReady) {
12425 const localSdpObject = sdpTransform$3.parse(answer.sdp);
12426 await this.setupTransport({
12427 localDtlsRole: this._forcedLocalDtlsRole ?? 'client',
12428 localSdpObject
12429 });
12430 }
12431 logger$5.debug('receiveDataChannel() | calling pc.setRemoteDescription() [answer:%o]', answer);
12432 await this._pc.setLocalDescription(answer);
12433 this._hasDataChannelMediaSection = true;
12434 }
12435 return { dataChannel };
12436 }
12437 async setupTransport({ localDtlsRole, localSdpObject }) {
12438 if (!localSdpObject) {
12439 localSdpObject = sdpTransform$3.parse(this._pc.localDescription.sdp);
12440 }
12441 // Get our local DTLS parameters.
12442 const dtlsParameters = sdpCommonUtils$3.extractDtlsParameters({ sdpObject: localSdpObject });
12443 // Set our DTLS role.
12444 dtlsParameters.role = localDtlsRole;
12445 // Update the remote DTLS role in the SDP.
12446 this._remoteSdp.updateDtlsRole(localDtlsRole === 'client' ? 'server' : 'client');
12447 // Need to tell the remote transport about our parameters.
12448 await new Promise((resolve, reject) => {
12449 this.safeEmit('@connect', { dtlsParameters }, resolve, reject);
12450 });
12451 this._transportReady = true;
12452 }
12453 assertNotClosed() {
12454 if (this._closed) {
12455 throw new errors_1$4.InvalidStateError('method called in a closed handler');
12456 }
12457 }
12458 assertSendDirection() {
12459 if (this._direction !== 'send') {
12460 throw new Error('method can just be called for handlers with "send" direction');
12461 }
12462 }
12463 assertRecvDirection() {
12464 if (this._direction !== 'recv') {
12465 throw new Error('method can just be called for handlers with "recv" direction');
12466 }
12467 }
12468 }
12469 Safari12$1.Safari12 = Safari12;
12470
12471 var Safari11$1 = {};
12472
12473 var __createBinding$5 = (commonjsGlobal && commonjsGlobal.__createBinding) || (Object.create ? (function(o, m, k, k2) {
12474 if (k2 === undefined) k2 = k;
12475 var desc = Object.getOwnPropertyDescriptor(m, k);
12476 if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
12477 desc = { enumerable: true, get: function() { return m[k]; } };
12478 }
12479 Object.defineProperty(o, k2, desc);
12480 }) : (function(o, m, k, k2) {
12481 if (k2 === undefined) k2 = k;
12482 o[k2] = m[k];
12483 }));
12484 var __setModuleDefault$5 = (commonjsGlobal && commonjsGlobal.__setModuleDefault) || (Object.create ? (function(o, v) {
12485 Object.defineProperty(o, "default", { enumerable: true, value: v });
12486 }) : function(o, v) {
12487 o["default"] = v;
12488 });
12489 var __importStar$5 = (commonjsGlobal && commonjsGlobal.__importStar) || function (mod) {
12490 if (mod && mod.__esModule) return mod;
12491 var result = {};
12492 if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding$5(result, mod, k);
12493 __setModuleDefault$5(result, mod);
12494 return result;
12495 };
12496 Object.defineProperty(Safari11$1, "__esModule", { value: true });
12497 Safari11$1.Safari11 = void 0;
12498 const sdpTransform$2 = __importStar$5(lib);
12499 const Logger_1$4 = Logger$3;
12500 const utils$5 = __importStar$5(utils$h);
12501 const ortc$4 = __importStar$5(ortc$d);
12502 const sdpCommonUtils$2 = __importStar$5(commonUtils);
12503 const sdpPlanBUtils$1 = __importStar$5(planBUtils);
12504 const HandlerInterface_1$3 = HandlerInterface$1;
12505 const RemoteSdp_1$2 = RemoteSdp$1;
12506 const logger$4 = new Logger_1$4.Logger('Safari11');
12507 const SCTP_NUM_STREAMS$2 = { OS: 1024, MIS: 1024 };
12508 class Safari11 extends HandlerInterface_1$3.HandlerInterface {
12509 /**
12510 * Creates a factory function.
12511 */
12512 static createFactory() {
12513 return () => new Safari11();
12514 }
12515 constructor() {
12516 super();
12517 // Local stream for sending.
12518 this._sendStream = new MediaStream();
12519 // Map of RTCRtpSender indexed by localId.
12520 this._mapSendLocalIdRtpSender = new Map();
12521 // Next sending localId.
12522 this._nextSendLocalId = 0;
12523 // Map of MID, RTP parameters and RTCRtpReceiver indexed by local id.
12524 // Value is an Object with mid, rtpParameters and rtpReceiver.
12525 this._mapRecvLocalIdInfo = new Map();
12526 // Whether a DataChannel m=application section has been created.
12527 this._hasDataChannelMediaSection = false;
12528 // Sending DataChannel id value counter. Incremented for each new DataChannel.
12529 this._nextSendSctpStreamId = 0;
12530 // Got transport local and remote parameters.
12531 this._transportReady = false;
12532 }
12533 get name() {
12534 return 'Safari11';
12535 }
12536 close() {
12537 logger$4.debug('close()');
12538 // Close RTCPeerConnection.
12539 if (this._pc) {
12540 try {
12541 this._pc.close();
12542 }
12543 catch (error) { }
12544 }
12545 this.emit('@close');
12546 }
12547 async getNativeRtpCapabilities() {
12548 logger$4.debug('getNativeRtpCapabilities()');
12549 const pc = new RTCPeerConnection({
12550 iceServers: [],
12551 iceTransportPolicy: 'all',
12552 bundlePolicy: 'max-bundle',
12553 rtcpMuxPolicy: 'require',
12554 sdpSemantics: 'plan-b'
12555 });
12556 try {
12557 const offer = await pc.createOffer({
12558 offerToReceiveAudio: true,
12559 offerToReceiveVideo: true
12560 });
12561 try {
12562 pc.close();
12563 }
12564 catch (error) { }
12565 const sdpObject = sdpTransform$2.parse(offer.sdp);
12566 const nativeRtpCapabilities = sdpCommonUtils$2.extractRtpCapabilities({ sdpObject });
12567 return nativeRtpCapabilities;
12568 }
12569 catch (error) {
12570 try {
12571 pc.close();
12572 }
12573 catch (error2) { }
12574 throw error;
12575 }
12576 }
12577 async getNativeSctpCapabilities() {
12578 logger$4.debug('getNativeSctpCapabilities()');
12579 return {
12580 numStreams: SCTP_NUM_STREAMS$2
12581 };
12582 }
12583 run({ direction, iceParameters, iceCandidates, dtlsParameters, sctpParameters, iceServers, iceTransportPolicy, additionalSettings, proprietaryConstraints, extendedRtpCapabilities }) {
12584 logger$4.debug('run()');
12585 this._direction = direction;
12586 this._remoteSdp = new RemoteSdp_1$2.RemoteSdp({
12587 iceParameters,
12588 iceCandidates,
12589 dtlsParameters,
12590 sctpParameters,
12591 planB: true
12592 });
12593 this._sendingRtpParametersByKind =
12594 {
12595 audio: ortc$4.getSendingRtpParameters('audio', extendedRtpCapabilities),
12596 video: ortc$4.getSendingRtpParameters('video', extendedRtpCapabilities)
12597 };
12598 this._sendingRemoteRtpParametersByKind =
12599 {
12600 audio: ortc$4.getSendingRemoteRtpParameters('audio', extendedRtpCapabilities),
12601 video: ortc$4.getSendingRemoteRtpParameters('video', extendedRtpCapabilities)
12602 };
12603 if (dtlsParameters.role && dtlsParameters.role !== 'auto') {
12604 this._forcedLocalDtlsRole = dtlsParameters.role === 'server'
12605 ? 'client'
12606 : 'server';
12607 }
12608 this._pc = new RTCPeerConnection({
12609 iceServers: iceServers || [],
12610 iceTransportPolicy: iceTransportPolicy || 'all',
12611 bundlePolicy: 'max-bundle',
12612 rtcpMuxPolicy: 'require',
12613 ...additionalSettings
12614 }, proprietaryConstraints);
12615 this._pc.addEventListener('icegatheringstatechange', () => {
12616 this.emit('@icegatheringstatechange', this._pc.iceGatheringState);
12617 });
12618 if (this._pc.connectionState) {
12619 this._pc.addEventListener('connectionstatechange', () => {
12620 this.emit('@connectionstatechange', this._pc.connectionState);
12621 });
12622 }
12623 else {
12624 this._pc.addEventListener('iceconnectionstatechange', () => {
12625 logger$4.warn('run() | pc.connectionState not supported, using pc.iceConnectionState');
12626 switch (this._pc.iceConnectionState) {
12627 case 'checking':
12628 this.emit('@connectionstatechange', 'connecting');
12629 break;
12630 case 'connected':
12631 case 'completed':
12632 this.emit('@connectionstatechange', 'connected');
12633 break;
12634 case 'failed':
12635 this.emit('@connectionstatechange', 'failed');
12636 break;
12637 case 'disconnected':
12638 this.emit('@connectionstatechange', 'disconnected');
12639 break;
12640 case 'closed':
12641 this.emit('@connectionstatechange', 'closed');
12642 break;
12643 }
12644 });
12645 }
12646 }
12647 async updateIceServers(iceServers) {
12648 logger$4.debug('updateIceServers()');
12649 const configuration = this._pc.getConfiguration();
12650 configuration.iceServers = iceServers;
12651 this._pc.setConfiguration(configuration);
12652 }
12653 async restartIce(iceParameters) {
12654 logger$4.debug('restartIce()');
12655 // Provide the remote SDP handler with new remote ICE parameters.
12656 this._remoteSdp.updateIceParameters(iceParameters);
12657 if (!this._transportReady) {
12658 return;
12659 }
12660 if (this._direction === 'send') {
12661 const offer = await this._pc.createOffer({ iceRestart: true });
12662 logger$4.debug('restartIce() | calling pc.setLocalDescription() [offer:%o]', offer);
12663 await this._pc.setLocalDescription(offer);
12664 const answer = { type: 'answer', sdp: this._remoteSdp.getSdp() };
12665 logger$4.debug('restartIce() | calling pc.setRemoteDescription() [answer:%o]', answer);
12666 await this._pc.setRemoteDescription(answer);
12667 }
12668 else {
12669 const offer = { type: 'offer', sdp: this._remoteSdp.getSdp() };
12670 logger$4.debug('restartIce() | calling pc.setRemoteDescription() [offer:%o]', offer);
12671 await this._pc.setRemoteDescription(offer);
12672 const answer = await this._pc.createAnswer();
12673 logger$4.debug('restartIce() | calling pc.setLocalDescription() [answer:%o]', answer);
12674 await this._pc.setLocalDescription(answer);
12675 }
12676 }
12677 async getTransportStats() {
12678 return this._pc.getStats();
12679 }
12680 async send({ track, encodings, codecOptions, codec }) {
12681 this.assertSendDirection();
12682 logger$4.debug('send() [kind:%s, track.id:%s]', track.kind, track.id);
12683 if (codec) {
12684 logger$4.warn('send() | codec selection is not available in %s handler', this.name);
12685 }
12686 this._sendStream.addTrack(track);
12687 this._pc.addTrack(track, this._sendStream);
12688 let offer = await this._pc.createOffer();
12689 let localSdpObject = sdpTransform$2.parse(offer.sdp);
12690 let offerMediaObject;
12691 const sendingRtpParameters = utils$5.clone(this._sendingRtpParametersByKind[track.kind]);
12692 sendingRtpParameters.codecs =
12693 ortc$4.reduceCodecs(sendingRtpParameters.codecs);
12694 const sendingRemoteRtpParameters = utils$5.clone(this._sendingRemoteRtpParametersByKind[track.kind]);
12695 sendingRemoteRtpParameters.codecs =
12696 ortc$4.reduceCodecs(sendingRemoteRtpParameters.codecs);
12697 if (!this._transportReady) {
12698 await this.setupTransport({
12699 localDtlsRole: this._forcedLocalDtlsRole ?? 'client',
12700 localSdpObject
12701 });
12702 }
12703 if (track.kind === 'video' && encodings && encodings.length > 1) {
12704 logger$4.debug('send() | enabling simulcast');
12705 localSdpObject = sdpTransform$2.parse(offer.sdp);
12706 offerMediaObject = localSdpObject.media.find((m) => m.type === 'video');
12707 sdpPlanBUtils$1.addLegacySimulcast({
12708 offerMediaObject,
12709 track,
12710 numStreams: encodings.length
12711 });
12712 offer = { type: 'offer', sdp: sdpTransform$2.write(localSdpObject) };
12713 }
12714 logger$4.debug('send() | calling pc.setLocalDescription() [offer:%o]', offer);
12715 await this._pc.setLocalDescription(offer);
12716 localSdpObject = sdpTransform$2.parse(this._pc.localDescription.sdp);
12717 offerMediaObject = localSdpObject.media
12718 .find((m) => m.type === track.kind);
12719 // Set RTCP CNAME.
12720 sendingRtpParameters.rtcp.cname =
12721 sdpCommonUtils$2.getCname({ offerMediaObject });
12722 // Set RTP encodings.
12723 sendingRtpParameters.encodings =
12724 sdpPlanBUtils$1.getRtpEncodings({ offerMediaObject, track });
12725 // Complete encodings with given values.
12726 if (encodings) {
12727 for (let idx = 0; idx < sendingRtpParameters.encodings.length; ++idx) {
12728 if (encodings[idx]) {
12729 Object.assign(sendingRtpParameters.encodings[idx], encodings[idx]);
12730 }
12731 }
12732 }
12733 // If VP8 and there is effective simulcast, add scalabilityMode to each
12734 // encoding.
12735 if (sendingRtpParameters.encodings.length > 1 &&
12736 sendingRtpParameters.codecs[0].mimeType.toLowerCase() === 'video/vp8') {
12737 for (const encoding of sendingRtpParameters.encodings) {
12738 encoding.scalabilityMode = 'L1T3';
12739 }
12740 }
12741 this._remoteSdp.send({
12742 offerMediaObject,
12743 offerRtpParameters: sendingRtpParameters,
12744 answerRtpParameters: sendingRemoteRtpParameters,
12745 codecOptions
12746 });
12747 const answer = { type: 'answer', sdp: this._remoteSdp.getSdp() };
12748 logger$4.debug('send() | calling pc.setRemoteDescription() [answer:%o]', answer);
12749 await this._pc.setRemoteDescription(answer);
12750 const localId = String(this._nextSendLocalId);
12751 this._nextSendLocalId++;
12752 const rtpSender = this._pc.getSenders()
12753 .find((s) => s.track === track);
12754 // Insert into the map.
12755 this._mapSendLocalIdRtpSender.set(localId, rtpSender);
12756 return {
12757 localId: localId,
12758 rtpParameters: sendingRtpParameters,
12759 rtpSender
12760 };
12761 }
12762 async stopSending(localId) {
12763 this.assertSendDirection();
12764 const rtpSender = this._mapSendLocalIdRtpSender.get(localId);
12765 if (!rtpSender) {
12766 throw new Error('associated RTCRtpSender not found');
12767 }
12768 if (rtpSender.track) {
12769 this._sendStream.removeTrack(rtpSender.track);
12770 }
12771 this._mapSendLocalIdRtpSender.delete(localId);
12772 const offer = await this._pc.createOffer();
12773 logger$4.debug('stopSending() | calling pc.setLocalDescription() [offer:%o]', offer);
12774 try {
12775 await this._pc.setLocalDescription(offer);
12776 }
12777 catch (error) {
12778 // NOTE: If there are no sending tracks, setLocalDescription() will fail with
12779 // "Failed to create channels". If so, ignore it.
12780 if (this._sendStream.getTracks().length === 0) {
12781 logger$4.warn('stopSending() | ignoring expected error due no sending tracks: %s', error.toString());
12782 return;
12783 }
12784 throw error;
12785 }
12786 if (this._pc.signalingState === 'stable') {
12787 return;
12788 }
12789 const answer = { type: 'answer', sdp: this._remoteSdp.getSdp() };
12790 logger$4.debug('stopSending() | calling pc.setRemoteDescription() [answer:%o]', answer);
12791 await this._pc.setRemoteDescription(answer);
12792 }
12793 // eslint-disable-next-line @typescript-eslint/no-unused-vars
12794 async pauseSending(localId) {
12795 // Unimplemented.
12796 }
12797 // eslint-disable-next-line @typescript-eslint/no-unused-vars
12798 async resumeSending(localId) {
12799 // Unimplemented.
12800 }
12801 async replaceTrack(localId, track) {
12802 this.assertSendDirection();
12803 if (track) {
12804 logger$4.debug('replaceTrack() [localId:%s, track.id:%s]', localId, track.id);
12805 }
12806 else {
12807 logger$4.debug('replaceTrack() [localId:%s, no track]', localId);
12808 }
12809 const rtpSender = this._mapSendLocalIdRtpSender.get(localId);
12810 if (!rtpSender) {
12811 throw new Error('associated RTCRtpSender not found');
12812 }
12813 const oldTrack = rtpSender.track;
12814 await rtpSender.replaceTrack(track);
12815 // Remove the old track from the local stream.
12816 if (oldTrack) {
12817 this._sendStream.removeTrack(oldTrack);
12818 }
12819 // Add the new track to the local stream.
12820 if (track) {
12821 this._sendStream.addTrack(track);
12822 }
12823 }
12824 async setMaxSpatialLayer(localId, spatialLayer) {
12825 this.assertSendDirection();
12826 logger$4.debug('setMaxSpatialLayer() [localId:%s, spatialLayer:%s]', localId, spatialLayer);
12827 const rtpSender = this._mapSendLocalIdRtpSender.get(localId);
12828 if (!rtpSender) {
12829 throw new Error('associated RTCRtpSender not found');
12830 }
12831 const parameters = rtpSender.getParameters();
12832 parameters.encodings.forEach((encoding, idx) => {
12833 if (idx <= spatialLayer) {
12834 encoding.active = true;
12835 }
12836 else {
12837 encoding.active = false;
12838 }
12839 });
12840 await rtpSender.setParameters(parameters);
12841 }
12842 async setRtpEncodingParameters(localId, params) {
12843 this.assertSendDirection();
12844 logger$4.debug('setRtpEncodingParameters() [localId:%s, params:%o]', localId, params);
12845 const rtpSender = this._mapSendLocalIdRtpSender.get(localId);
12846 if (!rtpSender) {
12847 throw new Error('associated RTCRtpSender not found');
12848 }
12849 const parameters = rtpSender.getParameters();
12850 parameters.encodings.forEach((encoding, idx) => {
12851 parameters.encodings[idx] = { ...encoding, ...params };
12852 });
12853 await rtpSender.setParameters(parameters);
12854 }
12855 async getSenderStats(localId) {
12856 this.assertSendDirection();
12857 const rtpSender = this._mapSendLocalIdRtpSender.get(localId);
12858 if (!rtpSender) {
12859 throw new Error('associated RTCRtpSender not found');
12860 }
12861 return rtpSender.getStats();
12862 }
12863 async sendDataChannel({ ordered, maxPacketLifeTime, maxRetransmits, label, protocol }) {
12864 this.assertSendDirection();
12865 const options = {
12866 negotiated: true,
12867 id: this._nextSendSctpStreamId,
12868 ordered,
12869 maxPacketLifeTime,
12870 maxRetransmits,
12871 protocol
12872 };
12873 logger$4.debug('sendDataChannel() [options:%o]', options);
12874 const dataChannel = this._pc.createDataChannel(label, options);
12875 // Increase next id.
12876 this._nextSendSctpStreamId =
12877 ++this._nextSendSctpStreamId % SCTP_NUM_STREAMS$2.MIS;
12878 // If this is the first DataChannel we need to create the SDP answer with
12879 // m=application section.
12880 if (!this._hasDataChannelMediaSection) {
12881 const offer = await this._pc.createOffer();
12882 const localSdpObject = sdpTransform$2.parse(offer.sdp);
12883 const offerMediaObject = localSdpObject.media
12884 .find((m) => m.type === 'application');
12885 if (!this._transportReady) {
12886 await this.setupTransport({
12887 localDtlsRole: this._forcedLocalDtlsRole ?? 'client',
12888 localSdpObject
12889 });
12890 }
12891 logger$4.debug('sendDataChannel() | calling pc.setLocalDescription() [offer:%o]', offer);
12892 await this._pc.setLocalDescription(offer);
12893 this._remoteSdp.sendSctpAssociation({ offerMediaObject });
12894 const answer = { type: 'answer', sdp: this._remoteSdp.getSdp() };
12895 logger$4.debug('sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]', answer);
12896 await this._pc.setRemoteDescription(answer);
12897 this._hasDataChannelMediaSection = true;
12898 }
12899 const sctpStreamParameters = {
12900 streamId: options.id,
12901 ordered: options.ordered,
12902 maxPacketLifeTime: options.maxPacketLifeTime,
12903 maxRetransmits: options.maxRetransmits
12904 };
12905 return { dataChannel, sctpStreamParameters };
12906 }
12907 async receive(optionsList) {
12908 this.assertRecvDirection();
12909 const results = [];
12910 for (const options of optionsList) {
12911 const { trackId, kind, rtpParameters, streamId } = options;
12912 logger$4.debug('receive() [trackId:%s, kind:%s]', trackId, kind);
12913 const mid = kind;
12914 this._remoteSdp.receive({
12915 mid,
12916 kind,
12917 offerRtpParameters: rtpParameters,
12918 streamId: streamId || rtpParameters.rtcp.cname,
12919 trackId
12920 });
12921 }
12922 const offer = { type: 'offer', sdp: this._remoteSdp.getSdp() };
12923 logger$4.debug('receive() | calling pc.setRemoteDescription() [offer:%o]', offer);
12924 await this._pc.setRemoteDescription(offer);
12925 let answer = await this._pc.createAnswer();
12926 const localSdpObject = sdpTransform$2.parse(answer.sdp);
12927 for (const options of optionsList) {
12928 const { kind, rtpParameters } = options;
12929 const mid = kind;
12930 const answerMediaObject = localSdpObject.media
12931 .find((m) => String(m.mid) === mid);
12932 // May need to modify codec parameters in the answer based on codec
12933 // parameters in the offer.
12934 sdpCommonUtils$2.applyCodecParameters({
12935 offerRtpParameters: rtpParameters,
12936 answerMediaObject
12937 });
12938 }
12939 answer = { type: 'answer', sdp: sdpTransform$2.write(localSdpObject) };
12940 if (!this._transportReady) {
12941 await this.setupTransport({
12942 localDtlsRole: this._forcedLocalDtlsRole ?? 'client',
12943 localSdpObject
12944 });
12945 }
12946 logger$4.debug('receive() | calling pc.setLocalDescription() [answer:%o]', answer);
12947 await this._pc.setLocalDescription(answer);
12948 for (const options of optionsList) {
12949 const { kind, trackId, rtpParameters } = options;
12950 const mid = kind;
12951 const localId = trackId;
12952 const rtpReceiver = this._pc.getReceivers()
12953 .find((r) => r.track && r.track.id === localId);
12954 if (!rtpReceiver) {
12955 throw new Error('new RTCRtpReceiver not');
12956 }
12957 // Insert into the map.
12958 this._mapRecvLocalIdInfo.set(localId, { mid, rtpParameters, rtpReceiver });
12959 results.push({
12960 localId,
12961 track: rtpReceiver.track,
12962 rtpReceiver
12963 });
12964 }
12965 return results;
12966 }
12967 async stopReceiving(localIds) {
12968 this.assertRecvDirection();
12969 for (const localId of localIds) {
12970 logger$4.debug('stopReceiving() [localId:%s]', localId);
12971 const { mid, rtpParameters } = this._mapRecvLocalIdInfo.get(localId) || {};
12972 // Remove from the map.
12973 this._mapRecvLocalIdInfo.delete(localId);
12974 this._remoteSdp.planBStopReceiving({ mid: mid, offerRtpParameters: rtpParameters });
12975 }
12976 const offer = { type: 'offer', sdp: this._remoteSdp.getSdp() };
12977 logger$4.debug('stopReceiving() | calling pc.setRemoteDescription() [offer:%o]', offer);
12978 await this._pc.setRemoteDescription(offer);
12979 const answer = await this._pc.createAnswer();
12980 logger$4.debug('stopReceiving() | calling pc.setLocalDescription() [answer:%o]', answer);
12981 await this._pc.setLocalDescription(answer);
12982 }
12983 async getReceiverStats(localId) {
12984 this.assertRecvDirection();
12985 const { rtpReceiver } = this._mapRecvLocalIdInfo.get(localId) || {};
12986 if (!rtpReceiver) {
12987 throw new Error('associated RTCRtpReceiver not found');
12988 }
12989 return rtpReceiver.getStats();
12990 }
12991 async pauseReceiving(
12992 // eslint-disable-next-line @typescript-eslint/no-unused-vars
12993 localIds) {
12994 // Unimplemented.
12995 }
12996 async resumeReceiving(
12997 // eslint-disable-next-line @typescript-eslint/no-unused-vars
12998 localIds) {
12999 // Unimplemented.
13000 }
13001 async receiveDataChannel({ sctpStreamParameters, label, protocol }) {
13002 this.assertRecvDirection();
13003 const { streamId, ordered, maxPacketLifeTime, maxRetransmits } = sctpStreamParameters;
13004 const options = {
13005 negotiated: true,
13006 id: streamId,
13007 ordered,
13008 maxPacketLifeTime,
13009 maxRetransmits,
13010 protocol
13011 };
13012 logger$4.debug('receiveDataChannel() [options:%o]', options);
13013 const dataChannel = this._pc.createDataChannel(label, options);
13014 // If this is the first DataChannel we need to create the SDP offer with
13015 // m=application section.
13016 if (!this._hasDataChannelMediaSection) {
13017 this._remoteSdp.receiveSctpAssociation({ oldDataChannelSpec: true });
13018 const offer = { type: 'offer', sdp: this._remoteSdp.getSdp() };
13019 logger$4.debug('receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]', offer);
13020 await this._pc.setRemoteDescription(offer);
13021 const answer = await this._pc.createAnswer();
13022 if (!this._transportReady) {
13023 const localSdpObject = sdpTransform$2.parse(answer.sdp);
13024 await this.setupTransport({
13025 localDtlsRole: this._forcedLocalDtlsRole ?? 'client',
13026 localSdpObject
13027 });
13028 }
13029 logger$4.debug('receiveDataChannel() | calling pc.setRemoteDescription() [answer:%o]', answer);
13030 await this._pc.setLocalDescription(answer);
13031 this._hasDataChannelMediaSection = true;
13032 }
13033 return { dataChannel };
13034 }
13035 async setupTransport({ localDtlsRole, localSdpObject }) {
13036 if (!localSdpObject) {
13037 localSdpObject = sdpTransform$2.parse(this._pc.localDescription.sdp);
13038 }
13039 // Get our local DTLS parameters.
13040 const dtlsParameters = sdpCommonUtils$2.extractDtlsParameters({ sdpObject: localSdpObject });
13041 // Set our DTLS role.
13042 dtlsParameters.role = localDtlsRole;
13043 // Update the remote DTLS role in the SDP.
13044 this._remoteSdp.updateDtlsRole(localDtlsRole === 'client' ? 'server' : 'client');
13045 // Need to tell the remote transport about our parameters.
13046 await new Promise((resolve, reject) => {
13047 this.safeEmit('@connect', { dtlsParameters }, resolve, reject);
13048 });
13049 this._transportReady = true;
13050 }
13051 assertSendDirection() {
13052 if (this._direction !== 'send') {
13053 throw new Error('method can just be called for handlers with "send" direction');
13054 }
13055 }
13056 assertRecvDirection() {
13057 if (this._direction !== 'recv') {
13058 throw new Error('method can just be called for handlers with "recv" direction');
13059 }
13060 }
13061 }
13062 Safari11$1.Safari11 = Safari11;
13063
13064 var Edge11$1 = {};
13065
13066 var edgeUtils$1 = {};
13067
13068 var __createBinding$4 = (commonjsGlobal && commonjsGlobal.__createBinding) || (Object.create ? (function(o, m, k, k2) {
13069 if (k2 === undefined) k2 = k;
13070 var desc = Object.getOwnPropertyDescriptor(m, k);
13071 if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
13072 desc = { enumerable: true, get: function() { return m[k]; } };
13073 }
13074 Object.defineProperty(o, k2, desc);
13075 }) : (function(o, m, k, k2) {
13076 if (k2 === undefined) k2 = k;
13077 o[k2] = m[k];
13078 }));
13079 var __setModuleDefault$4 = (commonjsGlobal && commonjsGlobal.__setModuleDefault) || (Object.create ? (function(o, v) {
13080 Object.defineProperty(o, "default", { enumerable: true, value: v });
13081 }) : function(o, v) {
13082 o["default"] = v;
13083 });
13084 var __importStar$4 = (commonjsGlobal && commonjsGlobal.__importStar) || function (mod) {
13085 if (mod && mod.__esModule) return mod;
13086 var result = {};
13087 if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding$4(result, mod, k);
13088 __setModuleDefault$4(result, mod);
13089 return result;
13090 };
13091 Object.defineProperty(edgeUtils$1, "__esModule", { value: true });
13092 edgeUtils$1.mangleRtpParameters = edgeUtils$1.getCapabilities = void 0;
13093 const utils$4 = __importStar$4(utils$h);
13094 /**
13095 * Normalize ORTC based Edge's RTCRtpReceiver.getCapabilities() to produce a full
13096 * compliant ORTC RTCRtpCapabilities.
13097 */
13098 function getCapabilities() {
13099 const nativeCaps = RTCRtpReceiver.getCapabilities();
13100 const caps = utils$4.clone(nativeCaps);
13101 for (const codec of caps.codecs ?? []) {
13102 // Rename numChannels to channels.
13103 // @ts-ignore
13104 codec.channels = codec.numChannels;
13105 // @ts-ignore
13106 delete codec.numChannels;
13107 // Add mimeType.
13108 // @ts-ignore (due to codec.name).
13109 codec.mimeType = codec.mimeType || `${codec.kind}/${codec.name}`;
13110 // NOTE: Edge sets some numeric parameters as string rather than number. Fix them.
13111 if (codec.parameters) {
13112 const parameters = codec.parameters;
13113 if (parameters.apt) {
13114 parameters.apt = Number(parameters.apt);
13115 }
13116 if (parameters['packetization-mode']) {
13117 parameters['packetization-mode'] = Number(parameters['packetization-mode']);
13118 }
13119 }
13120 // Delete emty parameter String in rtcpFeedback.
13121 for (const feedback of codec.rtcpFeedback || []) {
13122 if (!feedback.parameter) {
13123 feedback.parameter = '';
13124 }
13125 }
13126 }
13127 return caps;
13128 }
13129 edgeUtils$1.getCapabilities = getCapabilities;
13130 /**
13131 * Generate RTCRtpParameters as ORTC based Edge likes.
13132 */
13133 function mangleRtpParameters(rtpParameters) {
13134 const params = utils$4.clone(rtpParameters);
13135 // Rename mid to muxId.
13136 if (params.mid) {
13137 // @ts-ignore (due to muxId).
13138 params.muxId = params.mid;
13139 delete params.mid;
13140 }
13141 for (const codec of params.codecs) {
13142 // Rename channels to numChannels.
13143 if (codec.channels) {
13144 // @ts-ignore.
13145 codec.numChannels = codec.channels;
13146 delete codec.channels;
13147 }
13148 // Add codec.name (requried by Edge).
13149 // @ts-ignore (due to name).
13150 if (codec.mimeType && !codec.name) {
13151 // @ts-ignore (due to name).
13152 codec.name = codec.mimeType.split('/')[1];
13153 }
13154 // Remove mimeType.
13155 // @ts-ignore
13156 delete codec.mimeType;
13157 }
13158 return params;
13159 }
13160 edgeUtils$1.mangleRtpParameters = mangleRtpParameters;
13161
13162 var __createBinding$3 = (commonjsGlobal && commonjsGlobal.__createBinding) || (Object.create ? (function(o, m, k, k2) {
13163 if (k2 === undefined) k2 = k;
13164 var desc = Object.getOwnPropertyDescriptor(m, k);
13165 if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
13166 desc = { enumerable: true, get: function() { return m[k]; } };
13167 }
13168 Object.defineProperty(o, k2, desc);
13169 }) : (function(o, m, k, k2) {
13170 if (k2 === undefined) k2 = k;
13171 o[k2] = m[k];
13172 }));
13173 var __setModuleDefault$3 = (commonjsGlobal && commonjsGlobal.__setModuleDefault) || (Object.create ? (function(o, v) {
13174 Object.defineProperty(o, "default", { enumerable: true, value: v });
13175 }) : function(o, v) {
13176 o["default"] = v;
13177 });
13178 var __importStar$3 = (commonjsGlobal && commonjsGlobal.__importStar) || function (mod) {
13179 if (mod && mod.__esModule) return mod;
13180 var result = {};
13181 if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding$3(result, mod, k);
13182 __setModuleDefault$3(result, mod);
13183 return result;
13184 };
13185 Object.defineProperty(Edge11$1, "__esModule", { value: true });
13186 Edge11$1.Edge11 = void 0;
13187 const Logger_1$3 = Logger$3;
13188 const errors_1$3 = errors;
13189 const utils$3 = __importStar$3(utils$h);
13190 const ortc$3 = __importStar$3(ortc$d);
13191 const edgeUtils = __importStar$3(edgeUtils$1);
13192 const HandlerInterface_1$2 = HandlerInterface$1;
13193 const logger$3 = new Logger_1$3.Logger('Edge11');
13194 class Edge11 extends HandlerInterface_1$2.HandlerInterface {
13195 /**
13196 * Creates a factory function.
13197 */
13198 static createFactory() {
13199 return () => new Edge11();
13200 }
13201 constructor() {
13202 super();
13203 // Map of RTCRtpSenders indexed by id.
13204 this._rtpSenders = new Map();
13205 // Map of RTCRtpReceivers indexed by id.
13206 this._rtpReceivers = new Map();
13207 // Next localId for sending tracks.
13208 this._nextSendLocalId = 0;
13209 // Got transport local and remote parameters.
13210 this._transportReady = false;
13211 }
13212 get name() {
13213 return 'Edge11';
13214 }
13215 close() {
13216 logger$3.debug('close()');
13217 // Close the ICE gatherer.
13218 // NOTE: Not yet implemented by Edge.
13219 try {
13220 this._iceGatherer.close();
13221 }
13222 catch (error) { }
13223 // Close the ICE transport.
13224 try {
13225 this._iceTransport.stop();
13226 }
13227 catch (error) { }
13228 // Close the DTLS transport.
13229 try {
13230 this._dtlsTransport.stop();
13231 }
13232 catch (error) { }
13233 // Close RTCRtpSenders.
13234 for (const rtpSender of this._rtpSenders.values()) {
13235 try {
13236 rtpSender.stop();
13237 }
13238 catch (error) { }
13239 }
13240 // Close RTCRtpReceivers.
13241 for (const rtpReceiver of this._rtpReceivers.values()) {
13242 try {
13243 rtpReceiver.stop();
13244 }
13245 catch (error) { }
13246 }
13247 this.emit('@close');
13248 }
13249 async getNativeRtpCapabilities() {
13250 logger$3.debug('getNativeRtpCapabilities()');
13251 return edgeUtils.getCapabilities();
13252 }
13253 async getNativeSctpCapabilities() {
13254 logger$3.debug('getNativeSctpCapabilities()');
13255 return {
13256 numStreams: { OS: 0, MIS: 0 }
13257 };
13258 }
13259 run({ direction, // eslint-disable-line @typescript-eslint/no-unused-vars
13260 iceParameters, iceCandidates, dtlsParameters, sctpParameters, // eslint-disable-line @typescript-eslint/no-unused-vars
13261 iceServers, iceTransportPolicy, additionalSettings, // eslint-disable-line @typescript-eslint/no-unused-vars
13262 proprietaryConstraints, // eslint-disable-line @typescript-eslint/no-unused-vars
13263 extendedRtpCapabilities }) {
13264 logger$3.debug('run()');
13265 this._sendingRtpParametersByKind =
13266 {
13267 audio: ortc$3.getSendingRtpParameters('audio', extendedRtpCapabilities),
13268 video: ortc$3.getSendingRtpParameters('video', extendedRtpCapabilities)
13269 };
13270 this._remoteIceParameters = iceParameters;
13271 this._remoteIceCandidates = iceCandidates;
13272 this._remoteDtlsParameters = dtlsParameters;
13273 this._cname = `CNAME-${utils$3.generateRandomNumber()}`;
13274 this.setIceGatherer({ iceServers, iceTransportPolicy });
13275 this.setIceTransport();
13276 this.setDtlsTransport();
13277 }
13278 // eslint-disable-next-line @typescript-eslint/no-unused-vars
13279 async updateIceServers(iceServers) {
13280 // NOTE: Edge 11 does not implement iceGatherer.gater().
13281 throw new errors_1$3.UnsupportedError('not supported');
13282 }
13283 async restartIce(iceParameters) {
13284 logger$3.debug('restartIce()');
13285 this._remoteIceParameters = iceParameters;
13286 if (!this._transportReady) {
13287 return;
13288 }
13289 logger$3.debug('restartIce() | calling iceTransport.start()');
13290 this._iceTransport.start(this._iceGatherer, iceParameters, 'controlling');
13291 for (const candidate of this._remoteIceCandidates) {
13292 this._iceTransport.addRemoteCandidate(candidate);
13293 }
13294 this._iceTransport.addRemoteCandidate({});
13295 }
13296 async getTransportStats() {
13297 return this._iceTransport.getStats();
13298 }
13299 async send(
13300 // eslint-disable-next-line @typescript-eslint/no-unused-vars
13301 { track, encodings, codecOptions, codec }) {
13302 logger$3.debug('send() [kind:%s, track.id:%s]', track.kind, track.id);
13303 if (!this._transportReady) {
13304 await this.setupTransport({ localDtlsRole: 'server' });
13305 }
13306 logger$3.debug('send() | calling new RTCRtpSender()');
13307 const rtpSender = new RTCRtpSender(track, this._dtlsTransport);
13308 const rtpParameters = utils$3.clone(this._sendingRtpParametersByKind[track.kind]);
13309 rtpParameters.codecs = ortc$3.reduceCodecs(rtpParameters.codecs, codec);
13310 const useRtx = rtpParameters.codecs
13311 .some((_codec) => /.+\/rtx$/i.test(_codec.mimeType));
13312 if (!encodings) {
13313 encodings = [{}];
13314 }
13315 for (const encoding of encodings) {
13316 encoding.ssrc = utils$3.generateRandomNumber();
13317 if (useRtx) {
13318 encoding.rtx = { ssrc: utils$3.generateRandomNumber() };
13319 }
13320 }
13321 rtpParameters.encodings = encodings;
13322 // Fill RTCRtpParameters.rtcp.
13323 rtpParameters.rtcp =
13324 {
13325 cname: this._cname,
13326 reducedSize: true,
13327 mux: true
13328 };
13329 // NOTE: Convert our standard RTCRtpParameters into those that Edge
13330 // expects.
13331 const edgeRtpParameters = edgeUtils.mangleRtpParameters(rtpParameters);
13332 logger$3.debug('send() | calling rtpSender.send() [params:%o]', edgeRtpParameters);
13333 await rtpSender.send(edgeRtpParameters);
13334 const localId = String(this._nextSendLocalId);
13335 this._nextSendLocalId++;
13336 // Store it.
13337 this._rtpSenders.set(localId, rtpSender);
13338 return { localId, rtpParameters, rtpSender };
13339 }
13340 async stopSending(localId) {
13341 logger$3.debug('stopSending() [localId:%s]', localId);
13342 const rtpSender = this._rtpSenders.get(localId);
13343 if (!rtpSender) {
13344 throw new Error('RTCRtpSender not found');
13345 }
13346 this._rtpSenders.delete(localId);
13347 try {
13348 logger$3.debug('stopSending() | calling rtpSender.stop()');
13349 rtpSender.stop();
13350 }
13351 catch (error) {
13352 logger$3.warn('stopSending() | rtpSender.stop() failed:%o', error);
13353 throw error;
13354 }
13355 }
13356 // eslint-disable-next-line @typescript-eslint/no-unused-vars
13357 async pauseSending(localId) {
13358 // Unimplemented.
13359 }
13360 // eslint-disable-next-line @typescript-eslint/no-unused-vars
13361 async resumeSending(localId) {
13362 // Unimplemented.
13363 }
13364 async replaceTrack(localId, track) {
13365 if (track) {
13366 logger$3.debug('replaceTrack() [localId:%s, track.id:%s]', localId, track.id);
13367 }
13368 else {
13369 logger$3.debug('replaceTrack() [localId:%s, no track]', localId);
13370 }
13371 const rtpSender = this._rtpSenders.get(localId);
13372 if (!rtpSender) {
13373 throw new Error('RTCRtpSender not found');
13374 }
13375 rtpSender.setTrack(track);
13376 }
13377 async setMaxSpatialLayer(localId, spatialLayer) {
13378 logger$3.debug('setMaxSpatialLayer() [localId:%s, spatialLayer:%s]', localId, spatialLayer);
13379 const rtpSender = this._rtpSenders.get(localId);
13380 if (!rtpSender) {
13381 throw new Error('RTCRtpSender not found');
13382 }
13383 const parameters = rtpSender.getParameters();
13384 parameters.encodings
13385 .forEach((encoding, idx) => {
13386 if (idx <= spatialLayer) {
13387 encoding.active = true;
13388 }
13389 else {
13390 encoding.active = false;
13391 }
13392 });
13393 await rtpSender.setParameters(parameters);
13394 }
13395 async setRtpEncodingParameters(localId, params) {
13396 logger$3.debug('setRtpEncodingParameters() [localId:%s, params:%o]', localId, params);
13397 const rtpSender = this._rtpSenders.get(localId);
13398 if (!rtpSender) {
13399 throw new Error('RTCRtpSender not found');
13400 }
13401 const parameters = rtpSender.getParameters();
13402 parameters.encodings.forEach((encoding, idx) => {
13403 parameters.encodings[idx] = { ...encoding, ...params };
13404 });
13405 await rtpSender.setParameters(parameters);
13406 }
13407 async getSenderStats(localId) {
13408 const rtpSender = this._rtpSenders.get(localId);
13409 if (!rtpSender) {
13410 throw new Error('RTCRtpSender not found');
13411 }
13412 return rtpSender.getStats();
13413 }
13414 async sendDataChannel(
13415 // eslint-disable-next-line @typescript-eslint/no-unused-vars
13416 options) {
13417 throw new errors_1$3.UnsupportedError('not implemented');
13418 }
13419 async receive(optionsList) {
13420 const results = [];
13421 for (const options of optionsList) {
13422 const { trackId, kind } = options;
13423 logger$3.debug('receive() [trackId:%s, kind:%s]', trackId, kind);
13424 }
13425 if (!this._transportReady) {
13426 await this.setupTransport({ localDtlsRole: 'server' });
13427 }
13428 for (const options of optionsList) {
13429 const { trackId, kind, rtpParameters } = options;
13430 logger$3.debug('receive() | calling new RTCRtpReceiver()');
13431 const rtpReceiver = new RTCRtpReceiver(this._dtlsTransport, kind);
13432 rtpReceiver.addEventListener('error', (event) => {
13433 logger$3.error('rtpReceiver "error" event [event:%o]', event);
13434 });
13435 // NOTE: Convert our standard RTCRtpParameters into those that Edge
13436 // expects.
13437 const edgeRtpParameters = edgeUtils.mangleRtpParameters(rtpParameters);
13438 logger$3.debug('receive() | calling rtpReceiver.receive() [params:%o]', edgeRtpParameters);
13439 await rtpReceiver.receive(edgeRtpParameters);
13440 const localId = trackId;
13441 // Store it.
13442 this._rtpReceivers.set(localId, rtpReceiver);
13443 results.push({
13444 localId,
13445 track: rtpReceiver.track,
13446 rtpReceiver
13447 });
13448 }
13449 return results;
13450 }
13451 async stopReceiving(localIds) {
13452 for (const localId of localIds) {
13453 logger$3.debug('stopReceiving() [localId:%s]', localId);
13454 const rtpReceiver = this._rtpReceivers.get(localId);
13455 if (!rtpReceiver) {
13456 throw new Error('RTCRtpReceiver not found');
13457 }
13458 this._rtpReceivers.delete(localId);
13459 try {
13460 logger$3.debug('stopReceiving() | calling rtpReceiver.stop()');
13461 rtpReceiver.stop();
13462 }
13463 catch (error) {
13464 logger$3.warn('stopReceiving() | rtpReceiver.stop() failed:%o', error);
13465 }
13466 }
13467 }
13468 async pauseReceiving(
13469 // eslint-disable-next-line @typescript-eslint/no-unused-vars
13470 localIds) {
13471 // Unimplemented.
13472 }
13473 async resumeReceiving(
13474 // eslint-disable-next-line @typescript-eslint/no-unused-vars
13475 localIds) {
13476 // Unimplemented.
13477 }
13478 async getReceiverStats(localId) {
13479 const rtpReceiver = this._rtpReceivers.get(localId);
13480 if (!rtpReceiver) {
13481 throw new Error('RTCRtpReceiver not found');
13482 }
13483 return rtpReceiver.getStats();
13484 }
13485 async receiveDataChannel(
13486 // eslint-disable-next-line @typescript-eslint/no-unused-vars
13487 options) {
13488 throw new errors_1$3.UnsupportedError('not implemented');
13489 }
13490 setIceGatherer({ iceServers, iceTransportPolicy }) {
13491 // @ts-ignore
13492 const iceGatherer = new RTCIceGatherer({
13493 iceServers: iceServers || [],
13494 gatherPolicy: iceTransportPolicy || 'all'
13495 });
13496 iceGatherer.addEventListener('error', (event) => {
13497 logger$3.error('iceGatherer "error" event [event:%o]', event);
13498 });
13499 // NOTE: Not yet implemented by Edge, which starts gathering automatically.
13500 try {
13501 iceGatherer.gather();
13502 }
13503 catch (error) {
13504 logger$3.debug('setIceGatherer() | iceGatherer.gather() failed: %s', error.toString());
13505 }
13506 this._iceGatherer = iceGatherer;
13507 }
13508 setIceTransport() {
13509 const iceTransport = new RTCIceTransport(this._iceGatherer);
13510 // NOTE: Not yet implemented by Edge.
13511 iceTransport.addEventListener('statechange', () => {
13512 switch (iceTransport.state) {
13513 case 'checking':
13514 this.emit('@connectionstatechange', 'connecting');
13515 break;
13516 case 'connected':
13517 case 'completed':
13518 this.emit('@connectionstatechange', 'connected');
13519 break;
13520 case 'failed':
13521 this.emit('@connectionstatechange', 'failed');
13522 break;
13523 case 'disconnected':
13524 this.emit('@connectionstatechange', 'disconnected');
13525 break;
13526 case 'closed':
13527 this.emit('@connectionstatechange', 'closed');
13528 break;
13529 }
13530 });
13531 // NOTE: Not standard, but implemented by Edge.
13532 iceTransport.addEventListener('icestatechange', () => {
13533 switch (iceTransport.state) {
13534 case 'checking':
13535 this.emit('@connectionstatechange', 'connecting');
13536 break;
13537 case 'connected':
13538 case 'completed':
13539 this.emit('@connectionstatechange', 'connected');
13540 break;
13541 case 'failed':
13542 this.emit('@connectionstatechange', 'failed');
13543 break;
13544 case 'disconnected':
13545 this.emit('@connectionstatechange', 'disconnected');
13546 break;
13547 case 'closed':
13548 this.emit('@connectionstatechange', 'closed');
13549 break;
13550 }
13551 });
13552 iceTransport.addEventListener('candidatepairchange', (event) => {
13553 logger$3.debug('iceTransport "candidatepairchange" event [pair:%o]', event.pair);
13554 });
13555 this._iceTransport = iceTransport;
13556 }
13557 setDtlsTransport() {
13558 const dtlsTransport = new RTCDtlsTransport(this._iceTransport);
13559 // NOTE: Not yet implemented by Edge.
13560 dtlsTransport.addEventListener('statechange', () => {
13561 logger$3.debug('dtlsTransport "statechange" event [state:%s]', dtlsTransport.state);
13562 });
13563 // NOTE: Not standard, but implemented by Edge.
13564 dtlsTransport.addEventListener('dtlsstatechange', () => {
13565 logger$3.debug('dtlsTransport "dtlsstatechange" event [state:%s]', dtlsTransport.state);
13566 if (dtlsTransport.state === 'closed') {
13567 this.emit('@connectionstatechange', 'closed');
13568 }
13569 });
13570 dtlsTransport.addEventListener('error', (event) => {
13571 logger$3.error('dtlsTransport "error" event [event:%o]', event);
13572 });
13573 this._dtlsTransport = dtlsTransport;
13574 }
13575 async setupTransport({ localDtlsRole }) {
13576 logger$3.debug('setupTransport()');
13577 // Get our local DTLS parameters.
13578 const dtlsParameters = this._dtlsTransport.getLocalParameters();
13579 dtlsParameters.role = localDtlsRole;
13580 // Need to tell the remote transport about our parameters.
13581 await new Promise((resolve, reject) => {
13582 this.safeEmit('@connect', { dtlsParameters }, resolve, reject);
13583 });
13584 // Start the RTCIceTransport.
13585 this._iceTransport.start(this._iceGatherer, this._remoteIceParameters, 'controlling');
13586 // Add remote ICE candidates.
13587 for (const candidate of this._remoteIceCandidates) {
13588 this._iceTransport.addRemoteCandidate(candidate);
13589 }
13590 // Also signal a 'complete' candidate as per spec.
13591 // NOTE: It should be {complete: true} but Edge prefers {}.
13592 // NOTE: If we don't signal end of candidates, the Edge RTCIceTransport
13593 // won't enter the 'completed' state.
13594 this._iceTransport.addRemoteCandidate({});
13595 // NOTE: Edge does not like SHA less than 256.
13596 this._remoteDtlsParameters.fingerprints = this._remoteDtlsParameters.fingerprints
13597 .filter((fingerprint) => {
13598 return (fingerprint.algorithm === 'sha-256' ||
13599 fingerprint.algorithm === 'sha-384' ||
13600 fingerprint.algorithm === 'sha-512');
13601 });
13602 // Start the RTCDtlsTransport.
13603 this._dtlsTransport.start(this._remoteDtlsParameters);
13604 this._transportReady = true;
13605 }
13606 }
13607 Edge11$1.Edge11 = Edge11;
13608
13609 var ReactNativeUnifiedPlan$1 = {};
13610
13611 var __createBinding$2 = (commonjsGlobal && commonjsGlobal.__createBinding) || (Object.create ? (function(o, m, k, k2) {
13612 if (k2 === undefined) k2 = k;
13613 var desc = Object.getOwnPropertyDescriptor(m, k);
13614 if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
13615 desc = { enumerable: true, get: function() { return m[k]; } };
13616 }
13617 Object.defineProperty(o, k2, desc);
13618 }) : (function(o, m, k, k2) {
13619 if (k2 === undefined) k2 = k;
13620 o[k2] = m[k];
13621 }));
13622 var __setModuleDefault$2 = (commonjsGlobal && commonjsGlobal.__setModuleDefault) || (Object.create ? (function(o, v) {
13623 Object.defineProperty(o, "default", { enumerable: true, value: v });
13624 }) : function(o, v) {
13625 o["default"] = v;
13626 });
13627 var __importStar$2 = (commonjsGlobal && commonjsGlobal.__importStar) || function (mod) {
13628 if (mod && mod.__esModule) return mod;
13629 var result = {};
13630 if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding$2(result, mod, k);
13631 __setModuleDefault$2(result, mod);
13632 return result;
13633 };
13634 Object.defineProperty(ReactNativeUnifiedPlan$1, "__esModule", { value: true });
13635 ReactNativeUnifiedPlan$1.ReactNativeUnifiedPlan = void 0;
13636 const sdpTransform$1 = __importStar$2(lib);
13637 const Logger_1$2 = Logger$3;
13638 const utils$2 = __importStar$2(utils$h);
13639 const ortc$2 = __importStar$2(ortc$d);
13640 const sdpCommonUtils$1 = __importStar$2(commonUtils);
13641 const sdpUnifiedPlanUtils = __importStar$2(unifiedPlanUtils);
13642 const ortcUtils = __importStar$2(utils$e);
13643 const errors_1$2 = errors;
13644 const HandlerInterface_1$1 = HandlerInterface$1;
13645 const RemoteSdp_1$1 = RemoteSdp$1;
13646 const scalabilityModes_1 = scalabilityModes;
13647 const logger$2 = new Logger_1$2.Logger('ReactNativeUnifiedPlan');
13648 const SCTP_NUM_STREAMS$1 = { OS: 1024, MIS: 1024 };
13649 class ReactNativeUnifiedPlan extends HandlerInterface_1$1.HandlerInterface {
13650 /**
13651 * Creates a factory function.
13652 */
13653 static createFactory() {
13654 return () => new ReactNativeUnifiedPlan();
13655 }
13656 constructor() {
13657 super();
13658 // Closed flag.
13659 this._closed = false;
13660 // Map of RTCTransceivers indexed by MID.
13661 this._mapMidTransceiver = new Map();
13662 // Local stream for sending.
13663 this._sendStream = new MediaStream();
13664 // Whether a DataChannel m=application section has been created.
13665 this._hasDataChannelMediaSection = false;
13666 // Sending DataChannel id value counter. Incremented for each new DataChannel.
13667 this._nextSendSctpStreamId = 0;
13668 // Got transport local and remote parameters.
13669 this._transportReady = false;
13670 }
13671 get name() {
13672 return 'ReactNativeUnifiedPlan';
13673 }
13674 close() {
13675 logger$2.debug('close()');
13676 if (this._closed) {
13677 return;
13678 }
13679 this._closed = true;
13680 // Free/dispose native MediaStream but DO NOT free/dispose native
13681 // MediaStreamTracks (that is parent's business).
13682 // @ts-ignore (proprietary API in react-native-webrtc).
13683 this._sendStream.release(/* releaseTracks */ false);
13684 // Close RTCPeerConnection.
13685 if (this._pc) {
13686 try {
13687 this._pc.close();
13688 }
13689 catch (error) { }
13690 }
13691 this.emit('@close');
13692 }
13693 async getNativeRtpCapabilities() {
13694 logger$2.debug('getNativeRtpCapabilities()');
13695 const pc = new RTCPeerConnection({
13696 iceServers: [],
13697 iceTransportPolicy: 'all',
13698 bundlePolicy: 'max-bundle',
13699 rtcpMuxPolicy: 'require',
13700 sdpSemantics: 'unified-plan'
13701 });
13702 try {
13703 pc.addTransceiver('audio');
13704 pc.addTransceiver('video');
13705 const offer = await pc.createOffer();
13706 try {
13707 pc.close();
13708 }
13709 catch (error) { }
13710 const sdpObject = sdpTransform$1.parse(offer.sdp);
13711 const nativeRtpCapabilities = sdpCommonUtils$1.extractRtpCapabilities({ sdpObject });
13712 // libwebrtc supports NACK for OPUS but doesn't announce it.
13713 ortcUtils.addNackSuppportForOpus(nativeRtpCapabilities);
13714 return nativeRtpCapabilities;
13715 }
13716 catch (error) {
13717 try {
13718 pc.close();
13719 }
13720 catch (error2) { }
13721 throw error;
13722 }
13723 }
13724 async getNativeSctpCapabilities() {
13725 logger$2.debug('getNativeSctpCapabilities()');
13726 return {
13727 numStreams: SCTP_NUM_STREAMS$1
13728 };
13729 }
13730 run({ direction, iceParameters, iceCandidates, dtlsParameters, sctpParameters, iceServers, iceTransportPolicy, additionalSettings, proprietaryConstraints, extendedRtpCapabilities }) {
13731 this.assertNotClosed();
13732 logger$2.debug('run()');
13733 this._direction = direction;
13734 this._remoteSdp = new RemoteSdp_1$1.RemoteSdp({
13735 iceParameters,
13736 iceCandidates,
13737 dtlsParameters,
13738 sctpParameters
13739 });
13740 this._sendingRtpParametersByKind =
13741 {
13742 audio: ortc$2.getSendingRtpParameters('audio', extendedRtpCapabilities),
13743 video: ortc$2.getSendingRtpParameters('video', extendedRtpCapabilities)
13744 };
13745 this._sendingRemoteRtpParametersByKind =
13746 {
13747 audio: ortc$2.getSendingRemoteRtpParameters('audio', extendedRtpCapabilities),
13748 video: ortc$2.getSendingRemoteRtpParameters('video', extendedRtpCapabilities)
13749 };
13750 if (dtlsParameters.role && dtlsParameters.role !== 'auto') {
13751 this._forcedLocalDtlsRole = dtlsParameters.role === 'server'
13752 ? 'client'
13753 : 'server';
13754 }
13755 this._pc = new RTCPeerConnection({
13756 iceServers: iceServers || [],
13757 iceTransportPolicy: iceTransportPolicy || 'all',
13758 bundlePolicy: 'max-bundle',
13759 rtcpMuxPolicy: 'require',
13760 sdpSemantics: 'unified-plan',
13761 ...additionalSettings
13762 }, proprietaryConstraints);
13763 this._pc.addEventListener('icegatheringstatechange', () => {
13764 this.emit('@icegatheringstatechange', this._pc.iceGatheringState);
13765 });
13766 if (this._pc.connectionState) {
13767 this._pc.addEventListener('connectionstatechange', () => {
13768 this.emit('@connectionstatechange', this._pc.connectionState);
13769 });
13770 }
13771 else {
13772 this._pc.addEventListener('iceconnectionstatechange', () => {
13773 logger$2.warn('run() | pc.connectionState not supported, using pc.iceConnectionState');
13774 switch (this._pc.iceConnectionState) {
13775 case 'checking':
13776 this.emit('@connectionstatechange', 'connecting');
13777 break;
13778 case 'connected':
13779 case 'completed':
13780 this.emit('@connectionstatechange', 'connected');
13781 break;
13782 case 'failed':
13783 this.emit('@connectionstatechange', 'failed');
13784 break;
13785 case 'disconnected':
13786 this.emit('@connectionstatechange', 'disconnected');
13787 break;
13788 case 'closed':
13789 this.emit('@connectionstatechange', 'closed');
13790 break;
13791 }
13792 });
13793 }
13794 }
13795 async updateIceServers(iceServers) {
13796 this.assertNotClosed();
13797 logger$2.debug('updateIceServers()');
13798 const configuration = this._pc.getConfiguration();
13799 configuration.iceServers = iceServers;
13800 this._pc.setConfiguration(configuration);
13801 }
13802 async restartIce(iceParameters) {
13803 this.assertNotClosed();
13804 logger$2.debug('restartIce()');
13805 // Provide the remote SDP handler with new remote ICE parameters.
13806 this._remoteSdp.updateIceParameters(iceParameters);
13807 if (!this._transportReady) {
13808 return;
13809 }
13810 if (this._direction === 'send') {
13811 const offer = await this._pc.createOffer({ iceRestart: true });
13812 logger$2.debug('restartIce() | calling pc.setLocalDescription() [offer:%o]', offer);
13813 await this._pc.setLocalDescription(offer);
13814 const answer = { type: 'answer', sdp: this._remoteSdp.getSdp() };
13815 logger$2.debug('restartIce() | calling pc.setRemoteDescription() [answer:%o]', answer);
13816 await this._pc.setRemoteDescription(answer);
13817 }
13818 else {
13819 const offer = { type: 'offer', sdp: this._remoteSdp.getSdp() };
13820 logger$2.debug('restartIce() | calling pc.setRemoteDescription() [offer:%o]', offer);
13821 await this._pc.setRemoteDescription(offer);
13822 const answer = await this._pc.createAnswer();
13823 logger$2.debug('restartIce() | calling pc.setLocalDescription() [answer:%o]', answer);
13824 await this._pc.setLocalDescription(answer);
13825 }
13826 }
13827 async getTransportStats() {
13828 this.assertNotClosed();
13829 return this._pc.getStats();
13830 }
13831 async send({ track, encodings, codecOptions, codec }) {
13832 this.assertNotClosed();
13833 this.assertSendDirection();
13834 logger$2.debug('send() [kind:%s, track.id:%s]', track.kind, track.id);
13835 if (encodings && encodings.length > 1) {
13836 encodings.forEach((encoding, idx) => {
13837 encoding.rid = `r${idx}`;
13838 });
13839 }
13840 const sendingRtpParameters = utils$2.clone(this._sendingRtpParametersByKind[track.kind]);
13841 // This may throw.
13842 sendingRtpParameters.codecs =
13843 ortc$2.reduceCodecs(sendingRtpParameters.codecs, codec);
13844 const sendingRemoteRtpParameters = utils$2.clone(this._sendingRemoteRtpParametersByKind[track.kind]);
13845 // This may throw.
13846 sendingRemoteRtpParameters.codecs =
13847 ortc$2.reduceCodecs(sendingRemoteRtpParameters.codecs, codec);
13848 const mediaSectionIdx = this._remoteSdp.getNextMediaSectionIdx();
13849 const transceiver = this._pc.addTransceiver(track, {
13850 direction: 'sendonly',
13851 streams: [this._sendStream],
13852 sendEncodings: encodings
13853 });
13854 let offer = await this._pc.createOffer();
13855 let localSdpObject = sdpTransform$1.parse(offer.sdp);
13856 let offerMediaObject;
13857 if (!this._transportReady) {
13858 await this.setupTransport({
13859 localDtlsRole: this._forcedLocalDtlsRole ?? 'client',
13860 localSdpObject
13861 });
13862 }
13863 // Special case for VP9 with SVC.
13864 let hackVp9Svc = false;
13865 const layers = (0, scalabilityModes_1.parse)((encodings || [{}])[0].scalabilityMode);
13866 if (encodings &&
13867 encodings.length === 1 &&
13868 layers.spatialLayers > 1 &&
13869 sendingRtpParameters.codecs[0].mimeType.toLowerCase() === 'video/vp9') {
13870 logger$2.debug('send() | enabling legacy simulcast for VP9 SVC');
13871 hackVp9Svc = true;
13872 localSdpObject = sdpTransform$1.parse(offer.sdp);
13873 offerMediaObject = localSdpObject.media[mediaSectionIdx.idx];
13874 sdpUnifiedPlanUtils.addLegacySimulcast({
13875 offerMediaObject,
13876 numStreams: layers.spatialLayers
13877 });
13878 offer = { type: 'offer', sdp: sdpTransform$1.write(localSdpObject) };
13879 }
13880 logger$2.debug('send() | calling pc.setLocalDescription() [offer:%o]', offer);
13881 await this._pc.setLocalDescription(offer);
13882 // We can now get the transceiver.mid.
13883 // NOTE: We cannot read generated MID on iOS react-native-webrtc 111.0.0
13884 // because transceiver.mid is not available until setRemoteDescription()
13885 // is called, so this is best effort.
13886 // Issue: https://github.com/react-native-webrtc/react-native-webrtc/issues/1404
13887 // NOTE: So let's fill MID in sendingRtpParameters later.
13888 // NOTE: This is fixed in react-native-webrtc 111.0.3.
13889 let localId = transceiver.mid ?? undefined;
13890 if (!localId) {
13891 logger$2.warn('send() | missing transceiver.mid (bug in react-native-webrtc, using a workaround');
13892 }
13893 // Set MID.
13894 // NOTE: As per above, it could be unset yet.
13895 sendingRtpParameters.mid = localId;
13896 localSdpObject = sdpTransform$1.parse(this._pc.localDescription.sdp);
13897 offerMediaObject = localSdpObject.media[mediaSectionIdx.idx];
13898 // Set RTCP CNAME.
13899 sendingRtpParameters.rtcp.cname =
13900 sdpCommonUtils$1.getCname({ offerMediaObject });
13901 // Set RTP encodings by parsing the SDP offer if no encodings are given.
13902 if (!encodings) {
13903 sendingRtpParameters.encodings =
13904 sdpUnifiedPlanUtils.getRtpEncodings({ offerMediaObject });
13905 }
13906 // Set RTP encodings by parsing the SDP offer and complete them with given
13907 // one if just a single encoding has been given.
13908 else if (encodings.length === 1) {
13909 let newEncodings = sdpUnifiedPlanUtils.getRtpEncodings({ offerMediaObject });
13910 Object.assign(newEncodings[0], encodings[0]);
13911 // Hack for VP9 SVC.
13912 if (hackVp9Svc) {
13913 newEncodings = [newEncodings[0]];
13914 }
13915 sendingRtpParameters.encodings = newEncodings;
13916 }
13917 // Otherwise if more than 1 encoding are given use them verbatim.
13918 else {
13919 sendingRtpParameters.encodings = encodings;
13920 }
13921 // If VP8 or H264 and there is effective simulcast, add scalabilityMode to
13922 // each encoding.
13923 if (sendingRtpParameters.encodings.length > 1 &&
13924 (sendingRtpParameters.codecs[0].mimeType.toLowerCase() === 'video/vp8' ||
13925 sendingRtpParameters.codecs[0].mimeType.toLowerCase() === 'video/h264')) {
13926 for (const encoding of sendingRtpParameters.encodings) {
13927 if (encoding.scalabilityMode) {
13928 encoding.scalabilityMode = `L1T${layers.temporalLayers}`;
13929 }
13930 else {
13931 encoding.scalabilityMode = 'L1T3';
13932 }
13933 }
13934 }
13935 this._remoteSdp.send({
13936 offerMediaObject,
13937 reuseMid: mediaSectionIdx.reuseMid,
13938 offerRtpParameters: sendingRtpParameters,
13939 answerRtpParameters: sendingRemoteRtpParameters,
13940 codecOptions,
13941 extmapAllowMixed: true
13942 });
13943 const answer = { type: 'answer', sdp: this._remoteSdp.getSdp() };
13944 logger$2.debug('send() | calling pc.setRemoteDescription() [answer:%o]', answer);
13945 await this._pc.setRemoteDescription(answer);
13946 // Follow up of iOS react-native-webrtc 111.0.0 issue told above. Now yes,
13947 // we can read generated MID (if not done above) and fill sendingRtpParameters.
13948 // NOTE: This is fixed in react-native-webrtc 111.0.3 so this block isn't
13949 // needed starting from that version.
13950 if (!localId) {
13951 localId = transceiver.mid;
13952 sendingRtpParameters.mid = localId;
13953 }
13954 // Store in the map.
13955 this._mapMidTransceiver.set(localId, transceiver);
13956 return {
13957 localId,
13958 rtpParameters: sendingRtpParameters,
13959 rtpSender: transceiver.sender
13960 };
13961 }
13962 async stopSending(localId) {
13963 this.assertSendDirection();
13964 if (this._closed) {
13965 return;
13966 }
13967 logger$2.debug('stopSending() [localId:%s]', localId);
13968 const transceiver = this._mapMidTransceiver.get(localId);
13969 if (!transceiver) {
13970 throw new Error('associated RTCRtpTransceiver not found');
13971 }
13972 transceiver.sender.replaceTrack(null);
13973 this._pc.removeTrack(transceiver.sender);
13974 const mediaSectionClosed = this._remoteSdp.closeMediaSection(transceiver.mid);
13975 if (mediaSectionClosed) {
13976 try {
13977 transceiver.stop();
13978 }
13979 catch (error) { }
13980 }
13981 const offer = await this._pc.createOffer();
13982 logger$2.debug('stopSending() | calling pc.setLocalDescription() [offer:%o]', offer);
13983 await this._pc.setLocalDescription(offer);
13984 const answer = { type: 'answer', sdp: this._remoteSdp.getSdp() };
13985 logger$2.debug('stopSending() | calling pc.setRemoteDescription() [answer:%o]', answer);
13986 await this._pc.setRemoteDescription(answer);
13987 this._mapMidTransceiver.delete(localId);
13988 }
13989 async pauseSending(localId) {
13990 this.assertNotClosed();
13991 this.assertSendDirection();
13992 logger$2.debug('pauseSending() [localId:%s]', localId);
13993 const transceiver = this._mapMidTransceiver.get(localId);
13994 if (!transceiver) {
13995 throw new Error('associated RTCRtpTransceiver not found');
13996 }
13997 transceiver.direction = 'inactive';
13998 this._remoteSdp.pauseMediaSection(localId);
13999 const offer = await this._pc.createOffer();
14000 logger$2.debug('pauseSending() | calling pc.setLocalDescription() [offer:%o]', offer);
14001 await this._pc.setLocalDescription(offer);
14002 const answer = { type: 'answer', sdp: this._remoteSdp.getSdp() };
14003 logger$2.debug('pauseSending() | calling pc.setRemoteDescription() [answer:%o]', answer);
14004 await this._pc.setRemoteDescription(answer);
14005 }
14006 async resumeSending(localId) {
14007 this.assertNotClosed();
14008 this.assertSendDirection();
14009 logger$2.debug('resumeSending() [localId:%s]', localId);
14010 const transceiver = this._mapMidTransceiver.get(localId);
14011 this._remoteSdp.resumeSendingMediaSection(localId);
14012 if (!transceiver) {
14013 throw new Error('associated RTCRtpTransceiver not found');
14014 }
14015 transceiver.direction = 'sendonly';
14016 const offer = await this._pc.createOffer();
14017 logger$2.debug('resumeSending() | calling pc.setLocalDescription() [offer:%o]', offer);
14018 await this._pc.setLocalDescription(offer);
14019 const answer = { type: 'answer', sdp: this._remoteSdp.getSdp() };
14020 logger$2.debug('resumeSending() | calling pc.setRemoteDescription() [answer:%o]', answer);
14021 await this._pc.setRemoteDescription(answer);
14022 }
14023 async replaceTrack(localId, track) {
14024 this.assertNotClosed();
14025 this.assertSendDirection();
14026 if (track) {
14027 logger$2.debug('replaceTrack() [localId:%s, track.id:%s]', localId, track.id);
14028 }
14029 else {
14030 logger$2.debug('replaceTrack() [localId:%s, no track]', localId);
14031 }
14032 const transceiver = this._mapMidTransceiver.get(localId);
14033 if (!transceiver) {
14034 throw new Error('associated RTCRtpTransceiver not found');
14035 }
14036 await transceiver.sender.replaceTrack(track);
14037 }
14038 async setMaxSpatialLayer(localId, spatialLayer) {
14039 this.assertNotClosed();
14040 this.assertSendDirection();
14041 logger$2.debug('setMaxSpatialLayer() [localId:%s, spatialLayer:%s]', localId, spatialLayer);
14042 const transceiver = this._mapMidTransceiver.get(localId);
14043 if (!transceiver) {
14044 throw new Error('associated RTCRtpTransceiver not found');
14045 }
14046 const parameters = transceiver.sender.getParameters();
14047 parameters.encodings.forEach((encoding, idx) => {
14048 if (idx <= spatialLayer) {
14049 encoding.active = true;
14050 }
14051 else {
14052 encoding.active = false;
14053 }
14054 });
14055 await transceiver.sender.setParameters(parameters);
14056 this._remoteSdp.muxMediaSectionSimulcast(localId, parameters.encodings);
14057 const offer = await this._pc.createOffer();
14058 logger$2.debug('setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]', offer);
14059 await this._pc.setLocalDescription(offer);
14060 const answer = { type: 'answer', sdp: this._remoteSdp.getSdp() };
14061 logger$2.debug('setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]', answer);
14062 await this._pc.setRemoteDescription(answer);
14063 }
14064 async setRtpEncodingParameters(localId, params) {
14065 this.assertNotClosed();
14066 this.assertSendDirection();
14067 logger$2.debug('setRtpEncodingParameters() [localId:%s, params:%o]', localId, params);
14068 const transceiver = this._mapMidTransceiver.get(localId);
14069 if (!transceiver) {
14070 throw new Error('associated RTCRtpTransceiver not found');
14071 }
14072 const parameters = transceiver.sender.getParameters();
14073 parameters.encodings.forEach((encoding, idx) => {
14074 parameters.encodings[idx] = { ...encoding, ...params };
14075 });
14076 await transceiver.sender.setParameters(parameters);
14077 this._remoteSdp.muxMediaSectionSimulcast(localId, parameters.encodings);
14078 const offer = await this._pc.createOffer();
14079 logger$2.debug('setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]', offer);
14080 await this._pc.setLocalDescription(offer);
14081 const answer = { type: 'answer', sdp: this._remoteSdp.getSdp() };
14082 logger$2.debug('setRtpEncodingParameters() | calling pc.setRemoteDescription() [answer:%o]', answer);
14083 await this._pc.setRemoteDescription(answer);
14084 }
14085 async getSenderStats(localId) {
14086 this.assertNotClosed();
14087 this.assertSendDirection();
14088 const transceiver = this._mapMidTransceiver.get(localId);
14089 if (!transceiver) {
14090 throw new Error('associated RTCRtpTransceiver not found');
14091 }
14092 return transceiver.sender.getStats();
14093 }
14094 async sendDataChannel({ ordered, maxPacketLifeTime, maxRetransmits, label, protocol }) {
14095 this.assertNotClosed();
14096 this.assertSendDirection();
14097 const options = {
14098 negotiated: true,
14099 id: this._nextSendSctpStreamId,
14100 ordered,
14101 maxPacketLifeTime,
14102 maxRetransmits,
14103 protocol
14104 };
14105 logger$2.debug('sendDataChannel() [options:%o]', options);
14106 const dataChannel = this._pc.createDataChannel(label, options);
14107 // Increase next id.
14108 this._nextSendSctpStreamId =
14109 ++this._nextSendSctpStreamId % SCTP_NUM_STREAMS$1.MIS;
14110 // If this is the first DataChannel we need to create the SDP answer with
14111 // m=application section.
14112 if (!this._hasDataChannelMediaSection) {
14113 const offer = await this._pc.createOffer();
14114 const localSdpObject = sdpTransform$1.parse(offer.sdp);
14115 const offerMediaObject = localSdpObject.media
14116 .find((m) => m.type === 'application');
14117 if (!this._transportReady) {
14118 await this.setupTransport({
14119 localDtlsRole: this._forcedLocalDtlsRole ?? 'client',
14120 localSdpObject
14121 });
14122 }
14123 logger$2.debug('sendDataChannel() | calling pc.setLocalDescription() [offer:%o]', offer);
14124 await this._pc.setLocalDescription(offer);
14125 this._remoteSdp.sendSctpAssociation({ offerMediaObject });
14126 const answer = { type: 'answer', sdp: this._remoteSdp.getSdp() };
14127 logger$2.debug('sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]', answer);
14128 await this._pc.setRemoteDescription(answer);
14129 this._hasDataChannelMediaSection = true;
14130 }
14131 const sctpStreamParameters = {
14132 streamId: options.id,
14133 ordered: options.ordered,
14134 maxPacketLifeTime: options.maxPacketLifeTime,
14135 maxRetransmits: options.maxRetransmits
14136 };
14137 return { dataChannel, sctpStreamParameters };
14138 }
14139 async receive(optionsList) {
14140 this.assertNotClosed();
14141 this.assertRecvDirection();
14142 const results = [];
14143 const mapLocalId = new Map();
14144 for (const options of optionsList) {
14145 const { trackId, kind, rtpParameters, streamId } = options;
14146 logger$2.debug('receive() [trackId:%s, kind:%s]', trackId, kind);
14147 const localId = rtpParameters.mid || String(this._mapMidTransceiver.size);
14148 mapLocalId.set(trackId, localId);
14149 this._remoteSdp.receive({
14150 mid: localId,
14151 kind,
14152 offerRtpParameters: rtpParameters,
14153 streamId: streamId || rtpParameters.rtcp.cname,
14154 trackId
14155 });
14156 }
14157 const offer = { type: 'offer', sdp: this._remoteSdp.getSdp() };
14158 logger$2.debug('receive() | calling pc.setRemoteDescription() [offer:%o]', offer);
14159 await this._pc.setRemoteDescription(offer);
14160 let answer = await this._pc.createAnswer();
14161 const localSdpObject = sdpTransform$1.parse(answer.sdp);
14162 for (const options of optionsList) {
14163 const { trackId, rtpParameters } = options;
14164 const localId = mapLocalId.get(trackId);
14165 const answerMediaObject = localSdpObject.media
14166 .find((m) => String(m.mid) === localId);
14167 // May need to modify codec parameters in the answer based on codec
14168 // parameters in the offer.
14169 sdpCommonUtils$1.applyCodecParameters({
14170 offerRtpParameters: rtpParameters,
14171 answerMediaObject
14172 });
14173 }
14174 answer = { type: 'answer', sdp: sdpTransform$1.write(localSdpObject) };
14175 if (!this._transportReady) {
14176 await this.setupTransport({
14177 localDtlsRole: this._forcedLocalDtlsRole ?? 'client',
14178 localSdpObject
14179 });
14180 }
14181 logger$2.debug('receive() | calling pc.setLocalDescription() [answer:%o]', answer);
14182 await this._pc.setLocalDescription(answer);
14183 for (const options of optionsList) {
14184 const { trackId } = options;
14185 const localId = mapLocalId.get(trackId);
14186 const transceiver = this._pc.getTransceivers()
14187 .find((t) => t.mid === localId);
14188 if (!transceiver) {
14189 throw new Error('new RTCRtpTransceiver not found');
14190 }
14191 else {
14192 // Store in the map.
14193 this._mapMidTransceiver.set(localId, transceiver);
14194 results.push({
14195 localId,
14196 track: transceiver.receiver.track,
14197 rtpReceiver: transceiver.receiver
14198 });
14199 }
14200 }
14201 return results;
14202 }
14203 async stopReceiving(localIds) {
14204 this.assertRecvDirection();
14205 if (this._closed) {
14206 return;
14207 }
14208 for (const localId of localIds) {
14209 logger$2.debug('stopReceiving() [localId:%s]', localId);
14210 const transceiver = this._mapMidTransceiver.get(localId);
14211 if (!transceiver) {
14212 throw new Error('associated RTCRtpTransceiver not found');
14213 }
14214 this._remoteSdp.closeMediaSection(transceiver.mid);
14215 }
14216 const offer = { type: 'offer', sdp: this._remoteSdp.getSdp() };
14217 logger$2.debug('stopReceiving() | calling pc.setRemoteDescription() [offer:%o]', offer);
14218 await this._pc.setRemoteDescription(offer);
14219 const answer = await this._pc.createAnswer();
14220 logger$2.debug('stopReceiving() | calling pc.setLocalDescription() [answer:%o]', answer);
14221 await this._pc.setLocalDescription(answer);
14222 for (const localId of localIds) {
14223 this._mapMidTransceiver.delete(localId);
14224 }
14225 }
14226 async pauseReceiving(localIds) {
14227 this.assertNotClosed();
14228 this.assertRecvDirection();
14229 for (const localId of localIds) {
14230 logger$2.debug('pauseReceiving() [localId:%s]', localId);
14231 const transceiver = this._mapMidTransceiver.get(localId);
14232 if (!transceiver) {
14233 throw new Error('associated RTCRtpTransceiver not found');
14234 }
14235 transceiver.direction = 'inactive';
14236 this._remoteSdp.pauseMediaSection(localId);
14237 }
14238 const offer = { type: 'offer', sdp: this._remoteSdp.getSdp() };
14239 logger$2.debug('pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]', offer);
14240 await this._pc.setRemoteDescription(offer);
14241 const answer = await this._pc.createAnswer();
14242 logger$2.debug('pauseReceiving() | calling pc.setLocalDescription() [answer:%o]', answer);
14243 await this._pc.setLocalDescription(answer);
14244 }
14245 async resumeReceiving(localIds) {
14246 this.assertNotClosed();
14247 this.assertRecvDirection();
14248 for (const localId of localIds) {
14249 logger$2.debug('resumeReceiving() [localId:%s]', localId);
14250 const transceiver = this._mapMidTransceiver.get(localId);
14251 if (!transceiver) {
14252 throw new Error('associated RTCRtpTransceiver not found');
14253 }
14254 transceiver.direction = 'recvonly';
14255 this._remoteSdp.resumeReceivingMediaSection(localId);
14256 }
14257 const offer = { type: 'offer', sdp: this._remoteSdp.getSdp() };
14258 logger$2.debug('resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]', offer);
14259 await this._pc.setRemoteDescription(offer);
14260 const answer = await this._pc.createAnswer();
14261 logger$2.debug('resumeReceiving() | calling pc.setLocalDescription() [answer:%o]', answer);
14262 await this._pc.setLocalDescription(answer);
14263 }
14264 async getReceiverStats(localId) {
14265 this.assertNotClosed();
14266 this.assertRecvDirection();
14267 const transceiver = this._mapMidTransceiver.get(localId);
14268 if (!transceiver) {
14269 throw new Error('associated RTCRtpTransceiver not found');
14270 }
14271 return transceiver.receiver.getStats();
14272 }
14273 async receiveDataChannel({ sctpStreamParameters, label, protocol }) {
14274 this.assertNotClosed();
14275 this.assertRecvDirection();
14276 const { streamId, ordered, maxPacketLifeTime, maxRetransmits } = sctpStreamParameters;
14277 const options = {
14278 negotiated: true,
14279 id: streamId,
14280 ordered,
14281 maxPacketLifeTime,
14282 maxRetransmits,
14283 protocol
14284 };
14285 logger$2.debug('receiveDataChannel() [options:%o]', options);
14286 const dataChannel = this._pc.createDataChannel(label, options);
14287 // If this is the first DataChannel we need to create the SDP offer with
14288 // m=application section.
14289 if (!this._hasDataChannelMediaSection) {
14290 this._remoteSdp.receiveSctpAssociation();
14291 const offer = { type: 'offer', sdp: this._remoteSdp.getSdp() };
14292 logger$2.debug('receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]', offer);
14293 await this._pc.setRemoteDescription(offer);
14294 const answer = await this._pc.createAnswer();
14295 if (!this._transportReady) {
14296 const localSdpObject = sdpTransform$1.parse(answer.sdp);
14297 await this.setupTransport({
14298 localDtlsRole: this._forcedLocalDtlsRole ?? 'client',
14299 localSdpObject
14300 });
14301 }
14302 logger$2.debug('receiveDataChannel() | calling pc.setRemoteDescription() [answer:%o]', answer);
14303 await this._pc.setLocalDescription(answer);
14304 this._hasDataChannelMediaSection = true;
14305 }
14306 return { dataChannel };
14307 }
14308 async setupTransport({ localDtlsRole, localSdpObject }) {
14309 if (!localSdpObject) {
14310 localSdpObject = sdpTransform$1.parse(this._pc.localDescription.sdp);
14311 }
14312 // Get our local DTLS parameters.
14313 const dtlsParameters = sdpCommonUtils$1.extractDtlsParameters({ sdpObject: localSdpObject });
14314 // Set our DTLS role.
14315 dtlsParameters.role = localDtlsRole;
14316 // Update the remote DTLS role in the SDP.
14317 this._remoteSdp.updateDtlsRole(localDtlsRole === 'client' ? 'server' : 'client');
14318 // Need to tell the remote transport about our parameters.
14319 await new Promise((resolve, reject) => {
14320 this.safeEmit('@connect', { dtlsParameters }, resolve, reject);
14321 });
14322 this._transportReady = true;
14323 }
14324 assertNotClosed() {
14325 if (this._closed) {
14326 throw new errors_1$2.InvalidStateError('method called in a closed handler');
14327 }
14328 }
14329 assertSendDirection() {
14330 if (this._direction !== 'send') {
14331 throw new Error('method can just be called for handlers with "send" direction');
14332 }
14333 }
14334 assertRecvDirection() {
14335 if (this._direction !== 'recv') {
14336 throw new Error('method can just be called for handlers with "recv" direction');
14337 }
14338 }
14339 }
14340 ReactNativeUnifiedPlan$1.ReactNativeUnifiedPlan = ReactNativeUnifiedPlan;
14341
14342 var ReactNative$1 = {};
14343
14344 var __createBinding$1 = (commonjsGlobal && commonjsGlobal.__createBinding) || (Object.create ? (function(o, m, k, k2) {
14345 if (k2 === undefined) k2 = k;
14346 var desc = Object.getOwnPropertyDescriptor(m, k);
14347 if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
14348 desc = { enumerable: true, get: function() { return m[k]; } };
14349 }
14350 Object.defineProperty(o, k2, desc);
14351 }) : (function(o, m, k, k2) {
14352 if (k2 === undefined) k2 = k;
14353 o[k2] = m[k];
14354 }));
14355 var __setModuleDefault$1 = (commonjsGlobal && commonjsGlobal.__setModuleDefault) || (Object.create ? (function(o, v) {
14356 Object.defineProperty(o, "default", { enumerable: true, value: v });
14357 }) : function(o, v) {
14358 o["default"] = v;
14359 });
14360 var __importStar$1 = (commonjsGlobal && commonjsGlobal.__importStar) || function (mod) {
14361 if (mod && mod.__esModule) return mod;
14362 var result = {};
14363 if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding$1(result, mod, k);
14364 __setModuleDefault$1(result, mod);
14365 return result;
14366 };
14367 Object.defineProperty(ReactNative$1, "__esModule", { value: true });
14368 ReactNative$1.ReactNative = void 0;
14369 const sdpTransform = __importStar$1(lib);
14370 const Logger_1$1 = Logger$3;
14371 const errors_1$1 = errors;
14372 const utils$1 = __importStar$1(utils$h);
14373 const ortc$1 = __importStar$1(ortc$d);
14374 const sdpCommonUtils = __importStar$1(commonUtils);
14375 const sdpPlanBUtils = __importStar$1(planBUtils);
14376 const HandlerInterface_1 = HandlerInterface$1;
14377 const RemoteSdp_1 = RemoteSdp$1;
14378 const logger$1 = new Logger_1$1.Logger('ReactNative');
14379 const SCTP_NUM_STREAMS = { OS: 1024, MIS: 1024 };
14380 class ReactNative extends HandlerInterface_1.HandlerInterface {
14381 /**
14382 * Creates a factory function.
14383 */
14384 static createFactory() {
14385 return () => new ReactNative();
14386 }
14387 constructor() {
14388 super();
14389 // Local stream for sending.
14390 this._sendStream = new MediaStream();
14391 // Map of sending MediaStreamTracks indexed by localId.
14392 this._mapSendLocalIdTrack = new Map();
14393 // Next sending localId.
14394 this._nextSendLocalId = 0;
14395 // Map of MID, RTP parameters and RTCRtpReceiver indexed by local id.
14396 // Value is an Object with mid, rtpParameters and rtpReceiver.
14397 this._mapRecvLocalIdInfo = new Map();
14398 // Whether a DataChannel m=application section has been created.
14399 this._hasDataChannelMediaSection = false;
14400 // Sending DataChannel id value counter. Incremented for each new DataChannel.
14401 this._nextSendSctpStreamId = 0;
14402 // Got transport local and remote parameters.
14403 this._transportReady = false;
14404 }
14405 get name() {
14406 return 'ReactNative';
14407 }
14408 close() {
14409 logger$1.debug('close()');
14410 // Free/dispose native MediaStream but DO NOT free/dispose native
14411 // MediaStreamTracks (that is parent's business).
14412 // @ts-ignore (proprietary API in react-native-webrtc).
14413 this._sendStream.release(/* releaseTracks */ false);
14414 // Close RTCPeerConnection.
14415 if (this._pc) {
14416 try {
14417 this._pc.close();
14418 }
14419 catch (error) { }
14420 }
14421 this.emit('@close');
14422 }
14423 async getNativeRtpCapabilities() {
14424 logger$1.debug('getNativeRtpCapabilities()');
14425 const pc = new RTCPeerConnection({
14426 iceServers: [],
14427 iceTransportPolicy: 'all',
14428 bundlePolicy: 'max-bundle',
14429 rtcpMuxPolicy: 'require',
14430 sdpSemantics: 'plan-b'
14431 });
14432 try {
14433 const offer = await pc.createOffer({
14434 offerToReceiveAudio: true,
14435 offerToReceiveVideo: true
14436 });
14437 try {
14438 pc.close();
14439 }
14440 catch (error) { }
14441 const sdpObject = sdpTransform.parse(offer.sdp);
14442 const nativeRtpCapabilities = sdpCommonUtils.extractRtpCapabilities({ sdpObject });
14443 return nativeRtpCapabilities;
14444 }
14445 catch (error) {
14446 try {
14447 pc.close();
14448 }
14449 catch (error2) { }
14450 throw error;
14451 }
14452 }
14453 async getNativeSctpCapabilities() {
14454 logger$1.debug('getNativeSctpCapabilities()');
14455 return {
14456 numStreams: SCTP_NUM_STREAMS
14457 };
14458 }
14459 run({ direction, iceParameters, iceCandidates, dtlsParameters, sctpParameters, iceServers, iceTransportPolicy, additionalSettings, proprietaryConstraints, extendedRtpCapabilities }) {
14460 logger$1.debug('run()');
14461 this._direction = direction;
14462 this._remoteSdp = new RemoteSdp_1.RemoteSdp({
14463 iceParameters,
14464 iceCandidates,
14465 dtlsParameters,
14466 sctpParameters,
14467 planB: true
14468 });
14469 this._sendingRtpParametersByKind =
14470 {
14471 audio: ortc$1.getSendingRtpParameters('audio', extendedRtpCapabilities),
14472 video: ortc$1.getSendingRtpParameters('video', extendedRtpCapabilities)
14473 };
14474 this._sendingRemoteRtpParametersByKind =
14475 {
14476 audio: ortc$1.getSendingRemoteRtpParameters('audio', extendedRtpCapabilities),
14477 video: ortc$1.getSendingRemoteRtpParameters('video', extendedRtpCapabilities)
14478 };
14479 if (dtlsParameters.role && dtlsParameters.role !== 'auto') {
14480 this._forcedLocalDtlsRole = dtlsParameters.role === 'server'
14481 ? 'client'
14482 : 'server';
14483 }
14484 this._pc = new RTCPeerConnection({
14485 iceServers: iceServers || [],
14486 iceTransportPolicy: iceTransportPolicy || 'all',
14487 bundlePolicy: 'max-bundle',
14488 rtcpMuxPolicy: 'require',
14489 sdpSemantics: 'plan-b',
14490 ...additionalSettings
14491 }, proprietaryConstraints);
14492 this._pc.addEventListener('icegatheringstatechange', () => {
14493 this.emit('@icegatheringstatechange', this._pc.iceGatheringState);
14494 });
14495 if (this._pc.connectionState) {
14496 this._pc.addEventListener('connectionstatechange', () => {
14497 this.emit('@connectionstatechange', this._pc.connectionState);
14498 });
14499 }
14500 else {
14501 this._pc.addEventListener('iceconnectionstatechange', () => {
14502 logger$1.warn('run() | pc.connectionState not supported, using pc.iceConnectionState');
14503 switch (this._pc.iceConnectionState) {
14504 case 'checking':
14505 this.emit('@connectionstatechange', 'connecting');
14506 break;
14507 case 'connected':
14508 case 'completed':
14509 this.emit('@connectionstatechange', 'connected');
14510 break;
14511 case 'failed':
14512 this.emit('@connectionstatechange', 'failed');
14513 break;
14514 case 'disconnected':
14515 this.emit('@connectionstatechange', 'disconnected');
14516 break;
14517 case 'closed':
14518 this.emit('@connectionstatechange', 'closed');
14519 break;
14520 }
14521 });
14522 }
14523 }
14524 async updateIceServers(iceServers) {
14525 logger$1.debug('updateIceServers()');
14526 const configuration = this._pc.getConfiguration();
14527 configuration.iceServers = iceServers;
14528 this._pc.setConfiguration(configuration);
14529 }
14530 async restartIce(iceParameters) {
14531 logger$1.debug('restartIce()');
14532 // Provide the remote SDP handler with new remote ICE parameters.
14533 this._remoteSdp.updateIceParameters(iceParameters);
14534 if (!this._transportReady) {
14535 return;
14536 }
14537 if (this._direction === 'send') {
14538 const offer = await this._pc.createOffer({ iceRestart: true });
14539 logger$1.debug('restartIce() | calling pc.setLocalDescription() [offer:%o]', offer);
14540 await this._pc.setLocalDescription(offer);
14541 const answer = { type: 'answer', sdp: this._remoteSdp.getSdp() };
14542 logger$1.debug('restartIce() | calling pc.setRemoteDescription() [answer:%o]', answer);
14543 await this._pc.setRemoteDescription(answer);
14544 }
14545 else {
14546 const offer = { type: 'offer', sdp: this._remoteSdp.getSdp() };
14547 logger$1.debug('restartIce() | calling pc.setRemoteDescription() [offer:%o]', offer);
14548 await this._pc.setRemoteDescription(offer);
14549 const answer = await this._pc.createAnswer();
14550 logger$1.debug('restartIce() | calling pc.setLocalDescription() [answer:%o]', answer);
14551 await this._pc.setLocalDescription(answer);
14552 }
14553 }
14554 async getTransportStats() {
14555 return this._pc.getStats();
14556 }
14557 async send({ track, encodings, codecOptions, codec }) {
14558 this.assertSendDirection();
14559 logger$1.debug('send() [kind:%s, track.id:%s]', track.kind, track.id);
14560 if (codec) {
14561 logger$1.warn('send() | codec selection is not available in %s handler', this.name);
14562 }
14563 this._sendStream.addTrack(track);
14564 this._pc.addStream(this._sendStream);
14565 let offer = await this._pc.createOffer();
14566 let localSdpObject = sdpTransform.parse(offer.sdp);
14567 let offerMediaObject;
14568 const sendingRtpParameters = utils$1.clone(this._sendingRtpParametersByKind[track.kind]);
14569 sendingRtpParameters.codecs =
14570 ortc$1.reduceCodecs(sendingRtpParameters.codecs);
14571 const sendingRemoteRtpParameters = utils$1.clone(this._sendingRemoteRtpParametersByKind[track.kind]);
14572 sendingRemoteRtpParameters.codecs =
14573 ortc$1.reduceCodecs(sendingRemoteRtpParameters.codecs);
14574 if (!this._transportReady) {
14575 await this.setupTransport({
14576 localDtlsRole: this._forcedLocalDtlsRole ?? 'client',
14577 localSdpObject
14578 });
14579 }
14580 if (track.kind === 'video' && encodings && encodings.length > 1) {
14581 logger$1.debug('send() | enabling simulcast');
14582 localSdpObject = sdpTransform.parse(offer.sdp);
14583 offerMediaObject = localSdpObject.media
14584 .find((m) => m.type === 'video');
14585 sdpPlanBUtils.addLegacySimulcast({
14586 offerMediaObject,
14587 track,
14588 numStreams: encodings.length
14589 });
14590 offer = { type: 'offer', sdp: sdpTransform.write(localSdpObject) };
14591 }
14592 logger$1.debug('send() | calling pc.setLocalDescription() [offer:%o]', offer);
14593 await this._pc.setLocalDescription(offer);
14594 localSdpObject = sdpTransform.parse(this._pc.localDescription.sdp);
14595 offerMediaObject = localSdpObject.media
14596 .find((m) => m.type === track.kind);
14597 // Set RTCP CNAME.
14598 sendingRtpParameters.rtcp.cname =
14599 sdpCommonUtils.getCname({ offerMediaObject });
14600 // Set RTP encodings.
14601 sendingRtpParameters.encodings =
14602 sdpPlanBUtils.getRtpEncodings({ offerMediaObject, track });
14603 // Complete encodings with given values.
14604 if (encodings) {
14605 for (let idx = 0; idx < sendingRtpParameters.encodings.length; ++idx) {
14606 if (encodings[idx]) {
14607 Object.assign(sendingRtpParameters.encodings[idx], encodings[idx]);
14608 }
14609 }
14610 }
14611 // If VP8 or H264 and there is effective simulcast, add scalabilityMode to
14612 // each encoding.
14613 if (sendingRtpParameters.encodings.length > 1 &&
14614 (sendingRtpParameters.codecs[0].mimeType.toLowerCase() === 'video/vp8' ||
14615 sendingRtpParameters.codecs[0].mimeType.toLowerCase() === 'video/h264')) {
14616 for (const encoding of sendingRtpParameters.encodings) {
14617 encoding.scalabilityMode = 'L1T3';
14618 }
14619 }
14620 this._remoteSdp.send({
14621 offerMediaObject,
14622 offerRtpParameters: sendingRtpParameters,
14623 answerRtpParameters: sendingRemoteRtpParameters,
14624 codecOptions
14625 });
14626 const answer = { type: 'answer', sdp: this._remoteSdp.getSdp() };
14627 logger$1.debug('send() | calling pc.setRemoteDescription() [answer:%o]', answer);
14628 await this._pc.setRemoteDescription(answer);
14629 const localId = String(this._nextSendLocalId);
14630 this._nextSendLocalId++;
14631 // Insert into the map.
14632 this._mapSendLocalIdTrack.set(localId, track);
14633 return {
14634 localId: localId,
14635 rtpParameters: sendingRtpParameters
14636 };
14637 }
14638 async stopSending(localId) {
14639 this.assertSendDirection();
14640 logger$1.debug('stopSending() [localId:%s]', localId);
14641 const track = this._mapSendLocalIdTrack.get(localId);
14642 if (!track) {
14643 throw new Error('track not found');
14644 }
14645 this._mapSendLocalIdTrack.delete(localId);
14646 this._sendStream.removeTrack(track);
14647 this._pc.addStream(this._sendStream);
14648 const offer = await this._pc.createOffer();
14649 logger$1.debug('stopSending() | calling pc.setLocalDescription() [offer:%o]', offer);
14650 try {
14651 await this._pc.setLocalDescription(offer);
14652 }
14653 catch (error) {
14654 // NOTE: If there are no sending tracks, setLocalDescription() will fail with
14655 // "Failed to create channels". If so, ignore it.
14656 if (this._sendStream.getTracks().length === 0) {
14657 logger$1.warn('stopSending() | ignoring expected error due no sending tracks: %s', error.toString());
14658 return;
14659 }
14660 throw error;
14661 }
14662 if (this._pc.signalingState === 'stable') {
14663 return;
14664 }
14665 const answer = { type: 'answer', sdp: this._remoteSdp.getSdp() };
14666 logger$1.debug('stopSending() | calling pc.setRemoteDescription() [answer:%o]', answer);
14667 await this._pc.setRemoteDescription(answer);
14668 }
14669 // eslint-disable-next-line @typescript-eslint/no-unused-vars
14670 async pauseSending(localId) {
14671 // Unimplemented.
14672 }
14673 // eslint-disable-next-line @typescript-eslint/no-unused-vars
14674 async resumeSending(localId) {
14675 // Unimplemented.
14676 }
14677 async replaceTrack(
14678 // eslint-disable-next-line @typescript-eslint/no-unused-vars
14679 localId, track) {
14680 throw new errors_1$1.UnsupportedError('not implemented');
14681 }
14682 // eslint-disable-next-line @typescript-eslint/no-unused-vars
14683 async setMaxSpatialLayer(localId, spatialLayer) {
14684 throw new errors_1$1.UnsupportedError('not implemented');
14685 }
14686 // eslint-disable-next-line @typescript-eslint/no-unused-vars
14687 async setRtpEncodingParameters(localId, params) {
14688 throw new errors_1$1.UnsupportedError('not implemented');
14689 }
14690 // eslint-disable-next-line @typescript-eslint/no-unused-vars
14691 async getSenderStats(localId) {
14692 throw new errors_1$1.UnsupportedError('not implemented');
14693 }
14694 async sendDataChannel({ ordered, maxPacketLifeTime, maxRetransmits, label, protocol }) {
14695 this.assertSendDirection();
14696 const options = {
14697 negotiated: true,
14698 id: this._nextSendSctpStreamId,
14699 ordered,
14700 maxPacketLifeTime,
14701 maxRetransmitTime: maxPacketLifeTime,
14702 maxRetransmits,
14703 protocol
14704 };
14705 logger$1.debug('sendDataChannel() [options:%o]', options);
14706 const dataChannel = this._pc.createDataChannel(label, options);
14707 // Increase next id.
14708 this._nextSendSctpStreamId =
14709 ++this._nextSendSctpStreamId % SCTP_NUM_STREAMS.MIS;
14710 // If this is the first DataChannel we need to create the SDP answer with
14711 // m=application section.
14712 if (!this._hasDataChannelMediaSection) {
14713 const offer = await this._pc.createOffer();
14714 const localSdpObject = sdpTransform.parse(offer.sdp);
14715 const offerMediaObject = localSdpObject.media
14716 .find((m) => m.type === 'application');
14717 if (!this._transportReady) {
14718 await this.setupTransport({
14719 localDtlsRole: this._forcedLocalDtlsRole ?? 'client',
14720 localSdpObject
14721 });
14722 }
14723 logger$1.debug('sendDataChannel() | calling pc.setLocalDescription() [offer:%o]', offer);
14724 await this._pc.setLocalDescription(offer);
14725 this._remoteSdp.sendSctpAssociation({ offerMediaObject });
14726 const answer = { type: 'answer', sdp: this._remoteSdp.getSdp() };
14727 logger$1.debug('sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]', answer);
14728 await this._pc.setRemoteDescription(answer);
14729 this._hasDataChannelMediaSection = true;
14730 }
14731 const sctpStreamParameters = {
14732 streamId: options.id,
14733 ordered: options.ordered,
14734 maxPacketLifeTime: options.maxPacketLifeTime,
14735 maxRetransmits: options.maxRetransmits
14736 };
14737 return { dataChannel, sctpStreamParameters };
14738 }
14739 async receive(optionsList) {
14740 this.assertRecvDirection();
14741 const results = [];
14742 const mapStreamId = new Map();
14743 for (const options of optionsList) {
14744 const { trackId, kind, rtpParameters } = options;
14745 logger$1.debug('receive() [trackId:%s, kind:%s]', trackId, kind);
14746 const mid = kind;
14747 let streamId = options.streamId || rtpParameters.rtcp.cname;
14748 // NOTE: In React-Native we cannot reuse the same remote MediaStream for new
14749 // remote tracks. This is because react-native-webrtc does not react on new
14750 // tracks generated within already existing streams, so force the streamId
14751 // to be different. See:
14752 // https://github.com/react-native-webrtc/react-native-webrtc/issues/401
14753 logger$1.debug('receive() | forcing a random remote streamId to avoid well known bug in react-native-webrtc');
14754 streamId += `-hack-${utils$1.generateRandomNumber()}`;
14755 mapStreamId.set(trackId, streamId);
14756 this._remoteSdp.receive({
14757 mid,
14758 kind,
14759 offerRtpParameters: rtpParameters,
14760 streamId,
14761 trackId
14762 });
14763 }
14764 const offer = { type: 'offer', sdp: this._remoteSdp.getSdp() };
14765 logger$1.debug('receive() | calling pc.setRemoteDescription() [offer:%o]', offer);
14766 await this._pc.setRemoteDescription(offer);
14767 let answer = await this._pc.createAnswer();
14768 const localSdpObject = sdpTransform.parse(answer.sdp);
14769 for (const options of optionsList) {
14770 const { kind, rtpParameters } = options;
14771 const mid = kind;
14772 const answerMediaObject = localSdpObject.media
14773 .find((m) => String(m.mid) === mid);
14774 // May need to modify codec parameters in the answer based on codec
14775 // parameters in the offer.
14776 sdpCommonUtils.applyCodecParameters({
14777 offerRtpParameters: rtpParameters,
14778 answerMediaObject
14779 });
14780 }
14781 answer = { type: 'answer', sdp: sdpTransform.write(localSdpObject) };
14782 if (!this._transportReady) {
14783 await this.setupTransport({
14784 localDtlsRole: this._forcedLocalDtlsRole ?? 'client',
14785 localSdpObject
14786 });
14787 }
14788 logger$1.debug('receive() | calling pc.setLocalDescription() [answer:%o]', answer);
14789 await this._pc.setLocalDescription(answer);
14790 for (const options of optionsList) {
14791 const { kind, trackId, rtpParameters } = options;
14792 const localId = trackId;
14793 const mid = kind;
14794 const streamId = mapStreamId.get(trackId);
14795 const stream = this._pc.getRemoteStreams()
14796 .find((s) => s.id === streamId);
14797 const track = stream.getTrackById(localId);
14798 if (!track) {
14799 throw new Error('remote track not found');
14800 }
14801 // Insert into the map.
14802 this._mapRecvLocalIdInfo.set(localId, { mid, rtpParameters });
14803 results.push({ localId, track });
14804 }
14805 return results;
14806 }
14807 async stopReceiving(localIds) {
14808 this.assertRecvDirection();
14809 for (const localId of localIds) {
14810 logger$1.debug('stopReceiving() [localId:%s]', localId);
14811 const { mid, rtpParameters } = this._mapRecvLocalIdInfo.get(localId) || {};
14812 // Remove from the map.
14813 this._mapRecvLocalIdInfo.delete(localId);
14814 this._remoteSdp.planBStopReceiving({ mid: mid, offerRtpParameters: rtpParameters });
14815 }
14816 const offer = { type: 'offer', sdp: this._remoteSdp.getSdp() };
14817 logger$1.debug('stopReceiving() | calling pc.setRemoteDescription() [offer:%o]', offer);
14818 await this._pc.setRemoteDescription(offer);
14819 const answer = await this._pc.createAnswer();
14820 logger$1.debug('stopReceiving() | calling pc.setLocalDescription() [answer:%o]', answer);
14821 await this._pc.setLocalDescription(answer);
14822 }
14823 async pauseReceiving(
14824 // eslint-disable-next-line @typescript-eslint/no-unused-vars
14825 localIds) {
14826 // Unimplemented.
14827 }
14828 async resumeReceiving(
14829 // eslint-disable-next-line @typescript-eslint/no-unused-vars
14830 localIds) {
14831 // Unimplemented.
14832 }
14833 // eslint-disable-next-line @typescript-eslint/no-unused-vars
14834 async getReceiverStats(localId) {
14835 throw new errors_1$1.UnsupportedError('not implemented');
14836 }
14837 async receiveDataChannel({ sctpStreamParameters, label, protocol }) {
14838 this.assertRecvDirection();
14839 const { streamId, ordered, maxPacketLifeTime, maxRetransmits } = sctpStreamParameters;
14840 const options = {
14841 negotiated: true,
14842 id: streamId,
14843 ordered,
14844 maxPacketLifeTime,
14845 maxRetransmitTime: maxPacketLifeTime,
14846 maxRetransmits,
14847 protocol
14848 };
14849 logger$1.debug('receiveDataChannel() [options:%o]', options);
14850 const dataChannel = this._pc.createDataChannel(label, options);
14851 // If this is the first DataChannel we need to create the SDP offer with
14852 // m=application section.
14853 if (!this._hasDataChannelMediaSection) {
14854 this._remoteSdp.receiveSctpAssociation({ oldDataChannelSpec: true });
14855 const offer = { type: 'offer', sdp: this._remoteSdp.getSdp() };
14856 logger$1.debug('receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]', offer);
14857 await this._pc.setRemoteDescription(offer);
14858 const answer = await this._pc.createAnswer();
14859 if (!this._transportReady) {
14860 const localSdpObject = sdpTransform.parse(answer.sdp);
14861 await this.setupTransport({
14862 localDtlsRole: this._forcedLocalDtlsRole ?? 'client',
14863 localSdpObject
14864 });
14865 }
14866 logger$1.debug('receiveDataChannel() | calling pc.setRemoteDescription() [answer:%o]', answer);
14867 await this._pc.setLocalDescription(answer);
14868 this._hasDataChannelMediaSection = true;
14869 }
14870 return { dataChannel };
14871 }
14872 async setupTransport({ localDtlsRole, localSdpObject }) {
14873 if (!localSdpObject) {
14874 localSdpObject = sdpTransform.parse(this._pc.localDescription.sdp);
14875 }
14876 // Get our local DTLS parameters.
14877 const dtlsParameters = sdpCommonUtils.extractDtlsParameters({ sdpObject: localSdpObject });
14878 // Set our DTLS role.
14879 dtlsParameters.role = localDtlsRole;
14880 // Update the remote DTLS role in the SDP.
14881 this._remoteSdp.updateDtlsRole(localDtlsRole === 'client' ? 'server' : 'client');
14882 // Need to tell the remote transport about our parameters.
14883 await new Promise((resolve, reject) => {
14884 this.safeEmit('@connect', { dtlsParameters }, resolve, reject);
14885 });
14886 this._transportReady = true;
14887 }
14888 assertSendDirection() {
14889 if (this._direction !== 'send') {
14890 throw new Error('method can just be called for handlers with "send" direction');
14891 }
14892 }
14893 assertRecvDirection() {
14894 if (this._direction !== 'recv') {
14895 throw new Error('method can just be called for handlers with "recv" direction');
14896 }
14897 }
14898 }
14899 ReactNative$1.ReactNative = ReactNative;
14900
14901 var __createBinding = (commonjsGlobal && commonjsGlobal.__createBinding) || (Object.create ? (function(o, m, k, k2) {
14902 if (k2 === undefined) k2 = k;
14903 var desc = Object.getOwnPropertyDescriptor(m, k);
14904 if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
14905 desc = { enumerable: true, get: function() { return m[k]; } };
14906 }
14907 Object.defineProperty(o, k2, desc);
14908 }) : (function(o, m, k, k2) {
14909 if (k2 === undefined) k2 = k;
14910 o[k2] = m[k];
14911 }));
14912 var __setModuleDefault = (commonjsGlobal && commonjsGlobal.__setModuleDefault) || (Object.create ? (function(o, v) {
14913 Object.defineProperty(o, "default", { enumerable: true, value: v });
14914 }) : function(o, v) {
14915 o["default"] = v;
14916 });
14917 var __importStar = (commonjsGlobal && commonjsGlobal.__importStar) || function (mod) {
14918 if (mod && mod.__esModule) return mod;
14919 var result = {};
14920 if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
14921 __setModuleDefault(result, mod);
14922 return result;
14923 };
14924 Object.defineProperty(Device$1, "__esModule", { value: true });
14925 Device$1.Device = Device$1.detectDevice = void 0;
14926 const ua_parser_js_1 = uaParserExports;
14927 const Logger_1 = Logger$3;
14928 const EnhancedEventEmitter_1 = EnhancedEventEmitter$1;
14929 const errors_1 = errors;
14930 const utils = __importStar(utils$h);
14931 const ortc = __importStar(ortc$d);
14932 const Transport_1 = Transport$1;
14933 const Chrome111_1 = Chrome111$1;
14934 const Chrome74_1 = Chrome74$1;
14935 const Chrome70_1 = Chrome70$1;
14936 const Chrome67_1 = Chrome67$1;
14937 const Chrome55_1 = Chrome55$1;
14938 const Firefox60_1 = Firefox60$1;
14939 const Safari12_1 = Safari12$1;
14940 const Safari11_1 = Safari11$1;
14941 const Edge11_1 = Edge11$1;
14942 const ReactNativeUnifiedPlan_1 = ReactNativeUnifiedPlan$1;
14943 const ReactNative_1 = ReactNative$1;
14944 const logger = new Logger_1.Logger('Device');
14945 function detectDevice() {
14946 // React-Native.
14947 // NOTE: react-native-webrtc >= 1.75.0 is required.
14948 // NOTE: react-native-webrtc with Unified Plan requires version >= 106.0.0.
14949 if (typeof navigator === 'object' && navigator.product === 'ReactNative') {
14950 logger.debug('detectDevice() | React-Native detected');
14951 if (typeof RTCPeerConnection === 'undefined') {
14952 logger.warn('detectDevice() | unsupported react-native-webrtc without RTCPeerConnection, forgot to call registerGlobals()?');
14953 return undefined;
14954 }
14955 if (typeof RTCRtpTransceiver !== 'undefined') {
14956 logger.debug('detectDevice() | ReactNative UnifiedPlan handler chosen');
14957 return 'ReactNativeUnifiedPlan';
14958 }
14959 else {
14960 logger.debug('detectDevice() | ReactNative PlanB handler chosen');
14961 return 'ReactNative';
14962 }
14963 }
14964 // Browser.
14965 else if (typeof navigator === 'object' && typeof navigator.userAgent === 'string') {
14966 const ua = navigator.userAgent;
14967 const uaParser = new ua_parser_js_1.UAParser(ua);
14968 logger.debug('detectDevice() | browser detected [ua:%s, parsed:%o]', ua, uaParser.getResult());
14969 const browser = uaParser.getBrowser();
14970 const browserName = browser.name?.toLowerCase();
14971 const browserVersion = parseInt(browser.major ?? '0');
14972 const engine = uaParser.getEngine();
14973 const engineName = engine.name?.toLowerCase();
14974 const os = uaParser.getOS();
14975 const osName = os.name?.toLowerCase();
14976 const osVersion = parseFloat(os.version ?? '0');
14977 const device = uaParser.getDevice();
14978 const deviceModel = device.model?.toLowerCase();
14979 const isIOS = osName === 'ios' || deviceModel === 'ipad';
14980 const isChrome = browserName &&
14981 [
14982 'chrome',
14983 'chromium',
14984 'mobile chrome',
14985 'chrome webview',
14986 'chrome headless'
14987 ].includes(browserName);
14988 const isFirefox = browserName &&
14989 [
14990 'firefox',
14991 'mobile firefox',
14992 'mobile focus'
14993 ].includes(browserName);
14994 const isSafari = browserName &&
14995 [
14996 'safari',
14997 'mobile safari'
14998 ].includes(browserName);
14999 const isEdge = browserName && ['edge'].includes(browserName);
15000 // Chrome, Chromium, and Edge.
15001 if ((isChrome || isEdge) && !isIOS && browserVersion >= 111) {
15002 return 'Chrome111';
15003 }
15004 else if ((isChrome && !isIOS && browserVersion >= 74) ||
15005 (isEdge && !isIOS && browserVersion >= 88)) {
15006 return 'Chrome74';
15007 }
15008 else if (isChrome && !isIOS && browserVersion >= 70) {
15009 return 'Chrome70';
15010 }
15011 else if (isChrome && !isIOS && browserVersion >= 67) {
15012 return 'Chrome67';
15013 }
15014 else if (isChrome && !isIOS && browserVersion >= 55) {
15015 return 'Chrome55';
15016 }
15017 // Firefox.
15018 else if (isFirefox && !isIOS && browserVersion >= 60) {
15019 return 'Firefox60';
15020 }
15021 // Firefox on iOS (so Safari).
15022 else if (isFirefox && isIOS && osVersion >= 14.3) {
15023 return 'Safari12';
15024 }
15025 // Safari with Unified-Plan support enabled.
15026 else if (isSafari &&
15027 browserVersion >= 12 &&
15028 typeof RTCRtpTransceiver !== 'undefined' &&
15029 RTCRtpTransceiver.prototype.hasOwnProperty('currentDirection')) {
15030 return 'Safari12';
15031 }
15032 // Safari with Plab-B support.
15033 else if (isSafari && browserVersion >= 11) {
15034 return 'Safari11';
15035 }
15036 // Old Edge with ORTC support.
15037 else if (isEdge && !isIOS && browserVersion >= 11 && browserVersion <= 18) {
15038 return 'Edge11';
15039 }
15040 // Best effort for WebKit based browsers in iOS.
15041 else if (engineName === 'webkit' &&
15042 isIOS &&
15043 typeof RTCRtpTransceiver !== 'undefined' &&
15044 RTCRtpTransceiver.prototype.hasOwnProperty('currentDirection')) {
15045 return 'Safari12';
15046 }
15047 // Best effort for Chromium based browsers.
15048 else if (engineName === 'blink') {
15049 const match = ua.match(/(?:(?:Chrome|Chromium))[ /](\w+)/i);
15050 if (match) {
15051 const version = Number(match[1]);
15052 if (version >= 111) {
15053 return 'Chrome111';
15054 }
15055 else if (version >= 74) {
15056 return 'Chrome74';
15057 }
15058 else if (version >= 70) {
15059 return 'Chrome70';
15060 }
15061 else if (version >= 67) {
15062 return 'Chrome67';
15063 }
15064 else {
15065 return 'Chrome55';
15066 }
15067 }
15068 else {
15069 return 'Chrome111';
15070 }
15071 }
15072 // Unsupported browser.
15073 else {
15074 logger.warn('detectDevice() | browser not supported [name:%s, version:%s]', browserName, browserVersion);
15075 return undefined;
15076 }
15077 }
15078 // Unknown device.
15079 else {
15080 logger.warn('detectDevice() | unknown device');
15081 return undefined;
15082 }
15083 }
15084 Device$1.detectDevice = detectDevice;
15085 class Device {
15086 /**
15087 * Create a new Device to connect to mediasoup server.
15088 *
15089 * @throws {UnsupportedError} if device is not supported.
15090 */
15091 constructor({ handlerName, handlerFactory, Handler } = {}) {
15092 // Loaded flag.
15093 this._loaded = false;
15094 // Observer instance.
15095 this._observer = new EnhancedEventEmitter_1.EnhancedEventEmitter();
15096 logger.debug('constructor()');
15097 // Handle deprecated option.
15098 if (Handler) {
15099 logger.warn('constructor() | Handler option is DEPRECATED, use handlerName or handlerFactory instead');
15100 if (typeof Handler === 'string') {
15101 handlerName = Handler;
15102 }
15103 else {
15104 throw new TypeError('non string Handler option no longer supported, use handlerFactory instead');
15105 }
15106 }
15107 if (handlerName && handlerFactory) {
15108 throw new TypeError('just one of handlerName or handlerInterface can be given');
15109 }
15110 if (handlerFactory) {
15111 this._handlerFactory = handlerFactory;
15112 }
15113 else {
15114 if (handlerName) {
15115 logger.debug('constructor() | handler given: %s', handlerName);
15116 }
15117 else {
15118 handlerName = detectDevice();
15119 if (handlerName) {
15120 logger.debug('constructor() | detected handler: %s', handlerName);
15121 }
15122 else {
15123 throw new errors_1.UnsupportedError('device not supported');
15124 }
15125 }
15126 switch (handlerName) {
15127 case 'Chrome111':
15128 this._handlerFactory = Chrome111_1.Chrome111.createFactory();
15129 break;
15130 case 'Chrome74':
15131 this._handlerFactory = Chrome74_1.Chrome74.createFactory();
15132 break;
15133 case 'Chrome70':
15134 this._handlerFactory = Chrome70_1.Chrome70.createFactory();
15135 break;
15136 case 'Chrome67':
15137 this._handlerFactory = Chrome67_1.Chrome67.createFactory();
15138 break;
15139 case 'Chrome55':
15140 this._handlerFactory = Chrome55_1.Chrome55.createFactory();
15141 break;
15142 case 'Firefox60':
15143 this._handlerFactory = Firefox60_1.Firefox60.createFactory();
15144 break;
15145 case 'Safari12':
15146 this._handlerFactory = Safari12_1.Safari12.createFactory();
15147 break;
15148 case 'Safari11':
15149 this._handlerFactory = Safari11_1.Safari11.createFactory();
15150 break;
15151 case 'Edge11':
15152 this._handlerFactory = Edge11_1.Edge11.createFactory();
15153 break;
15154 case 'ReactNativeUnifiedPlan':
15155 this._handlerFactory = ReactNativeUnifiedPlan_1.ReactNativeUnifiedPlan.createFactory();
15156 break;
15157 case 'ReactNative':
15158 this._handlerFactory = ReactNative_1.ReactNative.createFactory();
15159 break;
15160 default:
15161 throw new TypeError(`unknown handlerName "${handlerName}"`);
15162 }
15163 }
15164 // Create a temporal handler to get its name.
15165 const handler = this._handlerFactory();
15166 this._handlerName = handler.name;
15167 handler.close();
15168 this._extendedRtpCapabilities = undefined;
15169 this._recvRtpCapabilities = undefined;
15170 this._canProduceByKind =
15171 {
15172 audio: false,
15173 video: false
15174 };
15175 this._sctpCapabilities = undefined;
15176 }
15177 /**
15178 * The RTC handler name.
15179 */
15180 get handlerName() {
15181 return this._handlerName;
15182 }
15183 /**
15184 * Whether the Device is loaded.
15185 */
15186 get loaded() {
15187 return this._loaded;
15188 }
15189 /**
15190 * RTP capabilities of the Device for receiving media.
15191 *
15192 * @throws {InvalidStateError} if not loaded.
15193 */
15194 get rtpCapabilities() {
15195 if (!this._loaded) {
15196 throw new errors_1.InvalidStateError('not loaded');
15197 }
15198 return this._recvRtpCapabilities;
15199 }
15200 /**
15201 * SCTP capabilities of the Device.
15202 *
15203 * @throws {InvalidStateError} if not loaded.
15204 */
15205 get sctpCapabilities() {
15206 if (!this._loaded) {
15207 throw new errors_1.InvalidStateError('not loaded');
15208 }
15209 return this._sctpCapabilities;
15210 }
15211 get observer() {
15212 return this._observer;
15213 }
15214 /**
15215 * Initialize the Device.
15216 */
15217 async load({ routerRtpCapabilities }) {
15218 logger.debug('load() [routerRtpCapabilities:%o]', routerRtpCapabilities);
15219 routerRtpCapabilities = utils.clone(routerRtpCapabilities);
15220 // Temporal handler to get its capabilities.
15221 let handler;
15222 try {
15223 if (this._loaded) {
15224 throw new errors_1.InvalidStateError('already loaded');
15225 }
15226 // This may throw.
15227 ortc.validateRtpCapabilities(routerRtpCapabilities);
15228 handler = this._handlerFactory();
15229 const nativeRtpCapabilities = await handler.getNativeRtpCapabilities();
15230 logger.debug('load() | got native RTP capabilities:%o', nativeRtpCapabilities);
15231 // This may throw.
15232 ortc.validateRtpCapabilities(nativeRtpCapabilities);
15233 // Get extended RTP capabilities.
15234 this._extendedRtpCapabilities = ortc.getExtendedRtpCapabilities(nativeRtpCapabilities, routerRtpCapabilities);
15235 logger.debug('load() | got extended RTP capabilities:%o', this._extendedRtpCapabilities);
15236 // Check whether we can produce audio/video.
15237 this._canProduceByKind.audio =
15238 ortc.canSend('audio', this._extendedRtpCapabilities);
15239 this._canProduceByKind.video =
15240 ortc.canSend('video', this._extendedRtpCapabilities);
15241 // Generate our receiving RTP capabilities for receiving media.
15242 this._recvRtpCapabilities =
15243 ortc.getRecvRtpCapabilities(this._extendedRtpCapabilities);
15244 // This may throw.
15245 ortc.validateRtpCapabilities(this._recvRtpCapabilities);
15246 logger.debug('load() | got receiving RTP capabilities:%o', this._recvRtpCapabilities);
15247 // Generate our SCTP capabilities.
15248 this._sctpCapabilities = await handler.getNativeSctpCapabilities();
15249 logger.debug('load() | got native SCTP capabilities:%o', this._sctpCapabilities);
15250 // This may throw.
15251 ortc.validateSctpCapabilities(this._sctpCapabilities);
15252 logger.debug('load() succeeded');
15253 this._loaded = true;
15254 handler.close();
15255 }
15256 catch (error) {
15257 if (handler) {
15258 handler.close();
15259 }
15260 throw error;
15261 }
15262 }
15263 /**
15264 * Whether we can produce audio/video.
15265 *
15266 * @throws {InvalidStateError} if not loaded.
15267 * @throws {TypeError} if wrong arguments.
15268 */
15269 canProduce(kind) {
15270 if (!this._loaded) {
15271 throw new errors_1.InvalidStateError('not loaded');
15272 }
15273 else if (kind !== 'audio' && kind !== 'video') {
15274 throw new TypeError(`invalid kind "${kind}"`);
15275 }
15276 return this._canProduceByKind[kind];
15277 }
15278 /**
15279 * Creates a Transport for sending media.
15280 *
15281 * @throws {InvalidStateError} if not loaded.
15282 * @throws {TypeError} if wrong arguments.
15283 */
15284 createSendTransport({ id, iceParameters, iceCandidates, dtlsParameters, sctpParameters, iceServers, iceTransportPolicy, additionalSettings, proprietaryConstraints, appData }) {
15285 logger.debug('createSendTransport()');
15286 return this.createTransport({
15287 direction: 'send',
15288 id: id,
15289 iceParameters: iceParameters,
15290 iceCandidates: iceCandidates,
15291 dtlsParameters: dtlsParameters,
15292 sctpParameters: sctpParameters,
15293 iceServers: iceServers,
15294 iceTransportPolicy: iceTransportPolicy,
15295 additionalSettings: additionalSettings,
15296 proprietaryConstraints: proprietaryConstraints,
15297 appData: appData
15298 });
15299 }
15300 /**
15301 * Creates a Transport for receiving media.
15302 *
15303 * @throws {InvalidStateError} if not loaded.
15304 * @throws {TypeError} if wrong arguments.
15305 */
15306 createRecvTransport({ id, iceParameters, iceCandidates, dtlsParameters, sctpParameters, iceServers, iceTransportPolicy, additionalSettings, proprietaryConstraints, appData }) {
15307 logger.debug('createRecvTransport()');
15308 return this.createTransport({
15309 direction: 'recv',
15310 id: id,
15311 iceParameters: iceParameters,
15312 iceCandidates: iceCandidates,
15313 dtlsParameters: dtlsParameters,
15314 sctpParameters: sctpParameters,
15315 iceServers: iceServers,
15316 iceTransportPolicy: iceTransportPolicy,
15317 additionalSettings: additionalSettings,
15318 proprietaryConstraints: proprietaryConstraints,
15319 appData: appData
15320 });
15321 }
15322 createTransport({ direction, id, iceParameters, iceCandidates, dtlsParameters, sctpParameters, iceServers, iceTransportPolicy, additionalSettings, proprietaryConstraints, appData }) {
15323 if (!this._loaded) {
15324 throw new errors_1.InvalidStateError('not loaded');
15325 }
15326 else if (typeof id !== 'string') {
15327 throw new TypeError('missing id');
15328 }
15329 else if (typeof iceParameters !== 'object') {
15330 throw new TypeError('missing iceParameters');
15331 }
15332 else if (!Array.isArray(iceCandidates)) {
15333 throw new TypeError('missing iceCandidates');
15334 }
15335 else if (typeof dtlsParameters !== 'object') {
15336 throw new TypeError('missing dtlsParameters');
15337 }
15338 else if (sctpParameters && typeof sctpParameters !== 'object') {
15339 throw new TypeError('wrong sctpParameters');
15340 }
15341 else if (appData && typeof appData !== 'object') {
15342 throw new TypeError('if given, appData must be an object');
15343 }
15344 // Create a new Transport.
15345 const transport = new Transport_1.Transport({
15346 direction,
15347 id,
15348 iceParameters,
15349 iceCandidates,
15350 dtlsParameters,
15351 sctpParameters,
15352 iceServers,
15353 iceTransportPolicy,
15354 additionalSettings,
15355 proprietaryConstraints,
15356 appData,
15357 handlerFactory: this._handlerFactory,
15358 extendedRtpCapabilities: this._extendedRtpCapabilities,
15359 canProduceByKind: this._canProduceByKind
15360 });
15361 // Emit observer event.
15362 this._observer.safeEmit('newtransport', transport);
15363 return transport;
15364 }
15365 }
15366 Device$1.Device = Device;
15367
15368 var types = {};
15369
15370 var RtpParameters = {};
15371
15372 /**
15373 * The RTP capabilities define what mediasoup or an endpoint can receive at
15374 * media level.
15375 */
15376 Object.defineProperty(RtpParameters, "__esModule", { value: true });
15377
15378 var SctpParameters = {};
15379
15380 Object.defineProperty(SctpParameters, "__esModule", { value: true });
15381
15382 (function (exports) {
15383 var __createBinding = (commonjsGlobal && commonjsGlobal.__createBinding) || (Object.create ? (function(o, m, k, k2) {
15384 if (k2 === undefined) k2 = k;
15385 var desc = Object.getOwnPropertyDescriptor(m, k);
15386 if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
15387 desc = { enumerable: true, get: function() { return m[k]; } };
15388 }
15389 Object.defineProperty(o, k2, desc);
15390 }) : (function(o, m, k, k2) {
15391 if (k2 === undefined) k2 = k;
15392 o[k2] = m[k];
15393 }));
15394 var __exportStar = (commonjsGlobal && commonjsGlobal.__exportStar) || function(m, exports) {
15395 for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15396 };
15397 Object.defineProperty(exports, "__esModule", { value: true });
15398 __exportStar(Device$1, exports);
15399 __exportStar(Transport$1, exports);
15400 __exportStar(Producer$1, exports);
15401 __exportStar(Consumer$1, exports);
15402 __exportStar(DataProducer$1, exports);
15403 __exportStar(DataConsumer$1, exports);
15404 __exportStar(RtpParameters, exports);
15405 __exportStar(SctpParameters, exports);
15406 __exportStar(HandlerInterface$1, exports);
15407 __exportStar(errors, exports);
15408 } (types));
15409
15410 (function (exports) {
15411 var __createBinding = (commonjsGlobal && commonjsGlobal.__createBinding) || (Object.create ? (function(o, m, k, k2) {
15412 if (k2 === undefined) k2 = k;
15413 var desc = Object.getOwnPropertyDescriptor(m, k);
15414 if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
15415 desc = { enumerable: true, get: function() { return m[k]; } };
15416 }
15417 Object.defineProperty(o, k2, desc);
15418 }) : (function(o, m, k, k2) {
15419 if (k2 === undefined) k2 = k;
15420 o[k2] = m[k];
15421 }));
15422 var __setModuleDefault = (commonjsGlobal && commonjsGlobal.__setModuleDefault) || (Object.create ? (function(o, v) {
15423 Object.defineProperty(o, "default", { enumerable: true, value: v });
15424 }) : function(o, v) {
15425 o["default"] = v;
15426 });
15427 var __importStar = (commonjsGlobal && commonjsGlobal.__importStar) || function (mod) {
15428 if (mod && mod.__esModule) return mod;
15429 var result = {};
15430 if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
15431 __setModuleDefault(result, mod);
15432 return result;
15433 };
15434 var __importDefault = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) {
15435 return (mod && mod.__esModule) ? mod : { "default": mod };
15436 };
15437 Object.defineProperty(exports, "__esModule", { value: true });
15438 exports.debug = exports.parseScalabilityMode = exports.detectDevice = exports.Device = exports.version = exports.types = void 0;
15439 const debug_1 = __importDefault(browserExports);
15440 exports.debug = debug_1.default;
15441 const Device_1 = Device$1;
15442 Object.defineProperty(exports, "Device", { enumerable: true, get: function () { return Device_1.Device; } });
15443 Object.defineProperty(exports, "detectDevice", { enumerable: true, get: function () { return Device_1.detectDevice; } });
15444 const types$1 = __importStar(types);
15445 exports.types = types$1;
15446 /**
15447 * Expose mediasoup-client version.
15448 */
15449 exports.version = '3.7.0';
15450 /**
15451 * Expose parseScalabilityMode() function.
15452 */
15453 var scalabilityModes_1 = scalabilityModes;
15454 Object.defineProperty(exports, "parseScalabilityMode", { enumerable: true, get: function () { return scalabilityModes_1.parse; } });
15455 } (lib$2));
15456
15457 /**
15458 * @typedef Payload
15459 * @property {Object} message
15460 * @property {string} [needResponse]
15461 * @property {string} [responseTo]
15462 */
15463
15464 /**
15465 * Bus class that implements a request/response pattern and a batching feature on top of a websocket.
15466 *
15467 * Compatible in both Node and Browser environment.
15468 */
15469 class Bus {
15470 /**
15471 * Used to know if the code runs on the client to avoid ID collisions as this class can is defined in both
15472 * the server(/node) and the client(/browser) environments (and therefore not share static properties).
15473 *
15474 * @type {"c"|"s"}
15475 */
15476 static _type =
15477 typeof window !== "undefined" && typeof window.document !== "undefined" ? "c" : "s";
15478 /** @type {number} */
15479 static _idCount = 0;
15480
15481 /** @type {Function} */
15482 onMessage;
15483 /** @type {Function} */
15484 onRequest;
15485 /** @type {number} */
15486 id = Bus._idCount++;
15487 /** @type {number} */
15488 _requestCount = 0;
15489 /** @type {WebSocket} */
15490 _websocket;
15491 /**
15492 * Whether the websocket is an EventEmitter (from `ws` node library), if false it is a EventTarget like the native browser ws.
15493 * @type {boolean}
15494 */
15495 _isWebsocketEmitter;
15496 /** @type {Map<string, {resolve: Function, reject: Function}>} */
15497 _pendingRequests = new Map();
15498 /** @type {Payload[]} */
15499 _messageQueue = [];
15500 /** @type {NodeJS.Timeout | string} */
15501 _batchTimeout;
15502 /** @type {number} */
15503 _batchDelay = 100;
15504
15505 /**
15506 * @param {import("ws").WebSocket} websocket
15507 * @param {Object} [options]
15508 * @param {number} [options.batchDelay] in milliseconds
15509 */
15510 constructor(websocket, { batchDelay = 200 } = {}) {
15511 this._batchDelay = batchDelay;
15512 this._websocket = websocket;
15513 this._isWebsocketEmitter = typeof websocket.on === "function"; // could use constructor name but can't use mocks during tests
15514 this._onMessage = this._onMessage.bind(this);
15515 this._onSocket("message", this._onMessage);
15516 this._onSocket("close", () => {
15517 this.close();
15518 });
15519 }
15520
15521 close() {
15522 clearTimeout(this._batchTimeout);
15523 this.onMessage = null;
15524 this.onRequest = null;
15525 this._sendPayload = () => {};
15526 for (const { reject, timeout } of this._pendingRequests.values()) {
15527 clearTimeout(timeout);
15528 reject(new Error("bus closed"));
15529 }
15530 this._offSocket("message", this._onMessage);
15531 }
15532
15533 /**
15534 * @param {Object} message
15535 * @param {Object} [options]
15536 * @param {number} [options.timeout] in milliseconds
15537 * @param {boolean} [options.batch]
15538 * @returns {Promise<Object>} response
15539 */
15540 request(message, { timeout = 5000, batch } = {}) {
15541 const requestId = this._getNextRequestId();
15542 return new Promise((resolve, reject) => {
15543 const timeoutId = setTimeout(() => {
15544 reject(new Error("bus request timed out"));
15545 this._pendingRequests.delete(requestId);
15546 }, timeout);
15547 this._pendingRequests.set(requestId, { resolve, reject, timeout: timeoutId });
15548 this._sendPayload(message, { needResponse: requestId, batch });
15549 });
15550 }
15551
15552 /**
15553 * @param message any JSON-serializable object
15554 * @param {Object} [options]
15555 * @param {boolean} [options.batch]
15556 */
15557 send(message, { batch } = {}) {
15558 this._sendPayload(message, { batch });
15559 }
15560
15561 /**
15562 * @param {string} event
15563 * @param {Function} func
15564 */
15565 _onSocket(event, func) {
15566 if (this._isWebsocketEmitter) {
15567 this._websocket.on(event, func);
15568 } else {
15569 this._websocket.addEventListener(event, func);
15570 }
15571 }
15572
15573 /**
15574 * @param {string} event
15575 * @param {Function} func
15576 */
15577 _offSocket(event, func) {
15578 if (this._isWebsocketEmitter) {
15579 this._websocket.off(event, func);
15580 } else {
15581 this._websocket.removeEventListener(event, func);
15582 }
15583 }
15584
15585 _getNextRequestId() {
15586 return `${Bus._type}_${this.id}_${this._requestCount++}`;
15587 }
15588
15589 /**
15590 * @param message any JSON-serializable object
15591 * @param {Object} [options]
15592 * @param {string} [options.needResponse] if set, the message is a `request` that expects a response with the same id.
15593 * @param {string} [options.responseTo] if set, the message is a response to a request of that id.
15594 * @param {boolean} [options.batch] true if batching the message
15595 */
15596 _sendPayload(message, { needResponse, responseTo, batch } = {}) {
15597 if (batch) {
15598 this._batch({ message, needResponse, responseTo });
15599 return;
15600 }
15601 this._websocket.send(JSON.stringify([{ message, needResponse, responseTo }]));
15602 }
15603
15604 /**
15605 * The delay for gathering the batch happens at the trailing end of the call, meaning that if there is no batch currently
15606 * gathering requests, the first request is sent immediately (to be lenient with infrequent messages), and new batch gathering
15607 * phase starts gathering the subsequent ones.
15608 *
15609 * @param {any} payload any JSON serializable
15610 */
15611 _batch(payload) {
15612 this._messageQueue.push(payload);
15613 if (this._batchTimeout) {
15614 // the messages will be flushed in currently gathering batch
15615 return;
15616 }
15617 this._flush();
15618 }
15619
15620 _flush() {
15621 if (this._messageQueue.length) {
15622 this._websocket.send(JSON.stringify(this._messageQueue));
15623 this._messageQueue = [];
15624 this._startGathering();
15625 }
15626 }
15627
15628 _startGathering() {
15629 this._batchTimeout = setTimeout(() => {
15630 this._flush();
15631 this._batchTimeout = undefined;
15632 }, this._batchDelay);
15633 }
15634
15635 /**
15636 * @param webSocketMessage the structure of the webSocketMessage varies depending on whether the websocket is an EventEmitter (node) or an EventTarget (browser)
15637 */
15638 _onMessage(webSocketMessage) {
15639 const normalizedMessage = this._isWebsocketEmitter
15640 ? webSocketMessage
15641 : webSocketMessage.data;
15642 /** @type {Payload[]} */
15643 const payloads = JSON.parse(normalizedMessage);
15644 for (const payload of payloads) {
15645 // not awaiting, handled in parallel
15646 this._handlePayload(payload);
15647 }
15648 }
15649
15650 /**
15651 * Handles incoming messages and dispatches them to the right handler based on whether they are requests, responses or plain messages.
15652 *
15653 * @param {Payload} payload
15654 */
15655 async _handlePayload({ message, needResponse, responseTo }) {
15656 if (responseTo) {
15657 const pendingRequest = this._pendingRequests.get(responseTo);
15658 clearTimeout(pendingRequest?.timeout);
15659 pendingRequest?.resolve(message);
15660 this._pendingRequests.delete(responseTo);
15661 } else if (needResponse) {
15662 const response = await this.onRequest?.(message);
15663 this._sendPayload(response, { responseTo: needResponse });
15664 } else {
15665 this.onMessage?.(message);
15666 }
15667 }
15668 }
15669
15670 // separate file to avoid circular dependencies or increasing bundle size (despite tree shaking)
15671 // it also allows documentation to be shared between client and server
15672
15673 const WS_CLOSE_CODE = {
15674 CLEAN: 1000,
15675 LEAVING: 1001,
15676 ERROR: 1011,
15677 // 4000-4999 range available for app specific use
15678 AUTHENTICATION_FAILED: 4106,
15679 TIMEOUT: 4107,
15680 KICKED: 4108,
15681 CHANNEL_FULL: 4109,
15682 };
15683
15684 const SERVER_REQUEST = {
15685 /** Requests the creation of a consumer that is used to forward a track to the client */
15686 INIT_CONSUMER: "INIT_CONSUMER",
15687 /** Requests the creation of upload and download transports */
15688 INIT_TRANSPORTS: "INIT_TRANSPORTS",
15689 /** Requests any response to keep the session alive */
15690 PING: "PING",
15691 };
15692
15693 const SERVER_MESSAGE = {
15694 /** Signals that the server wants to send a message to all the other members of that channel */
15695 BROADCAST: "BROADCAST",
15696 /** Signals the clients that one of the session in their channel has left. */
15697 SESSION_LEAVE: "SESSION_LEAVE",
15698 /** Signals the clients that the info (talking, mute,...) of one of the session in their channel has changed. */
15699 INFO_CHANGE: "S_INFO_CHANGE",
15700 };
15701
15702 const CLIENT_REQUEST = {
15703 /** Requests the server to connect the client-to-server transport, this occurs the first time a producer is added to this transport */
15704 CONNECT_CTS_TRANSPORT: "CONNECT_CTS_TRANSPORT",
15705 /** Requests the server to connect the server-to-client transport, this occurs the first time a consumer is added to this transport */
15706 CONNECT_STC_TRANSPORT: "CONNECT_STC_TRANSPORT",
15707 /** Requests the creation of a consumer that is used to upload a track to the server */
15708 INIT_PRODUCER: "INIT_PRODUCER",
15709 };
15710
15711 const CLIENT_MESSAGE = {
15712 /** Signals that the client wants to send a message to all the other members of that channel */
15713 BROADCAST: "BROADCAST",
15714 /** Signals that the client wants to change how it consumes a track (like pausing or ending the download) */
15715 CONSUMPTION_CHANGE: "CONSUMPTION_CHANGE",
15716 /** Signals that the info (talking, mute,...) of this client has changed. */
15717 INFO_CHANGE: "C_INFO_CHANGE",
15718 /** Signals that the client wants to change how it produces a track (like pausing or ending the upload) */
15719 PRODUCTION_CHANGE: "PRODUCTION_CHANGE",
15720 };
15721
15722 // eslint-disable-next-line node/no-unpublished-import
15723
15724 const INITIAL_RECONNECT_DELAY = 1_000; // the initial delay between reconnection attempts
15725 const MAXIMUM_RECONNECT_DELAY = 30_000; // the longest delay possible between reconnection attempts
15726 const MAX_ERRORS = 6; // how many errors should occur before trying a full restart of the connection
15727 const RECOVERY_DELAY = 1_000; // how much time after an error should pass before a soft recovery attempt (retry the operation and not the whole connection)
15728 const SUPPORTED_TYPES = new Set(["audio", "camera", "screen"]);
15729
15730 // https://mediasoup.org/documentation/v3/mediasoup-client/api/#ProducerOptions
15731 const DEFAULT_PRODUCER_OPTIONS = {
15732 stopTracks: false,
15733 disableTrackOnPause: false,
15734 zeroRtpOnPause: true,
15735 };
15736
15737 /**
15738 * @typedef {Object} Consumers
15739 * @property {import("mediasoup-client").types.Consumer | null} audio
15740 * @property {import("mediasoup-client").types.Consumer | null} camera
15741 * @property {import("mediasoup-client").types.Consumer | null} screen
15742 */
15743
15744 /**
15745 * @typedef {Object} Producers
15746 * @property {import("mediasoup-client").types.Producer | null} audio
15747 * @property {import("mediasoup-client").types.Producer | null} camera
15748 * @property {import("mediasoup-client").types.Producer | null} screen
15749 */
15750
15751 /**
15752 * @typedef {'audio' | 'camera' | 'screen' } streamType
15753 */
15754
15755 const SFU_CLIENT_STATE = Object.freeze({
15756 /**
15757 * The client is not connected to the server and does not want to do so. This state is intentional and
15758 * is only set at the creation of a sfuClient, or when the client calls `disconnect`.
15759 */
15760 DISCONNECTED: "disconnected",
15761 /**
15762 * The client is trying to connect to the server, it is not authenticated yet.
15763 */
15764 CONNECTING: "connecting",
15765 /**
15766 * The initial handshake with the server has been done and the client is authenticated, the bus is ready to be used.
15767 */
15768 AUTHENTICATED: "authenticated",
15769 /**
15770 * The client is ready to send and receive tracks.
15771 */
15772 CONNECTED: "connected",
15773 /**
15774 * This state is reached when the connection is lost and the client is trying to reconnect.
15775 */
15776 RECOVERING: "recovering",
15777 /**
15778 * This state is reached when the connection is stopped and there should be no automated attempt to reconnect.
15779 */
15780 CLOSED: "closed",
15781 });
15782
15783 const ACTIVE_STATES = new Set([
15784 SFU_CLIENT_STATE.CONNECTING,
15785 SFU_CLIENT_STATE.AUTHENTICATED,
15786 SFU_CLIENT_STATE.CONNECTED,
15787 ]);
15788
15789 /**
15790 * This class is run by the client and represents the server and abstracts the mediasoup API away.
15791 * It handles authentication, connection recovery and transport/consumers/producers maintenance.
15792 *
15793 * @fires SfuClient#stateChange
15794 * @fires SfuClient#update
15795 */
15796 class SfuClient extends EventTarget {
15797 /** @type {Error[]} */
15798 errors = [];
15799 /** @type {SFU_CLIENT_STATE[keyof SFU_CLIENT_STATE]} */
15800 _state = SFU_CLIENT_STATE.DISCONNECTED;
15801 /** @type {Bus | undefined} */
15802 _bus;
15803 /** @type {string} */
15804 _jsonWebToken;
15805 /** @type {import("mediasoup-client").types.Device} */
15806 _device;
15807 _recoverProducerTimeouts = {
15808 /** @type {number} */
15809 audio: undefined,
15810 /** @type {number} */
15811 camera: undefined,
15812 /** @type {number} */
15813 screen: undefined,
15814 };
15815 /** @type {import("mediasoup-client").types.Transport} Client-To-Server Transport */
15816 _ctsTransport;
15817 /** @type {import("mediasoup-client").types.Transport} Server-To-Client Transport */
15818 _stcTransport;
15819 /** @type {number} */
15820 _connectRetryDelay = INITIAL_RECONNECT_DELAY;
15821 /** @type {WebSocket} */
15822 _webSocket;
15823 /** @type {Map<number, Consumers>} */
15824 _consumers = new Map();
15825 /** @type {Producers} */
15826 _producers = {
15827 audio: null,
15828 camera: null,
15829 screen: null,
15830 };
15831 /** @type {Object<"audio" | "video", import("mediasoup-client").types.ProducerOptions>} */
15832 _producerOptionsByKind = {
15833 audio: DEFAULT_PRODUCER_OPTIONS,
15834 video: DEFAULT_PRODUCER_OPTIONS,
15835 };
15836 /** @type {Function[]} */
15837 _cleanups = [];
15838
15839 constructor() {
15840 super();
15841 this._handleMessage = this._handleMessage.bind(this);
15842 this._handleRequest = this._handleRequest.bind(this);
15843 this._handleConnectionEnd = this._handleConnectionEnd.bind(this);
15844 }
15845
15846 /**
15847 * @param {SFU_CLIENT_STATE[keyof SFU_CLIENT_STATE]} state
15848 * @fires SfuClient#stateChange
15849 */
15850 set state(state) {
15851 this._state = state;
15852 /**
15853 * @event SfuClient#stateChange
15854 * @type {Object}
15855 * @property {Object} detail
15856 * @property {string} detail.state
15857 */
15858 this.dispatchEvent(new CustomEvent("stateChange", { detail: { state } }));
15859 }
15860
15861 /**
15862 * @returns {SFU_CLIENT_STATE[keyof SFU_CLIENT_STATE]}
15863 */
15864 get state() {
15865 return this._state;
15866 }
15867
15868 /**
15869 * @param message any JSON serializable object
15870 */
15871 broadcast(message) {
15872 this._bus.send(
15873 {
15874 name: CLIENT_MESSAGE.BROADCAST,
15875 payload: message,
15876 },
15877 { batch: true }
15878 );
15879 }
15880
15881 /**
15882 * @param {string} url
15883 * @param {string} jsonWebToken
15884 * @param {Object} [options]
15885 * @param {string} [options.channelUUID]
15886 * @param {[]} [options.iceServers]
15887 */
15888 async connect(url, jsonWebToken, { channelUUID, iceServers } = {}) {
15889 // saving the options for so that the parameters are saved for reconnection attempts
15890 this._url = url.replace(/^http/, "ws"); // makes sure the url is a websocket url
15891 this._jsonWebToken = jsonWebToken;
15892 this._iceServers = iceServers;
15893 this._channelUUID = channelUUID;
15894 this._connectRetryDelay = INITIAL_RECONNECT_DELAY;
15895 this._device = this._createDevice();
15896 await this._connect();
15897 }
15898
15899 disconnect() {
15900 this._clear();
15901 this.state = SFU_CLIENT_STATE.DISCONNECTED;
15902 }
15903
15904 /**
15905 * @returns {Promise<{ uploadStats: RTCStatsReport, downloadStats: RTCStatsReport }>}
15906 */
15907 async getStats() {
15908 const stats = {};
15909 const [uploadStats, downloadStats] = await Promise.all([
15910 this._ctsTransport?.getStats(),
15911 this._stcTransport?.getStats(),
15912 ]);
15913 stats.uploadStats = uploadStats;
15914 stats.downloadStats = downloadStats;
15915 const proms = [];
15916 for (const [type, producer] of Object.entries(this._producers)) {
15917 if (producer) {
15918 proms.push(
15919 (async () => {
15920 stats[type] = await producer.getStats();
15921 })()
15922 );
15923 }
15924 }
15925 await Promise.all(proms);
15926 return stats;
15927 }
15928
15929 /**
15930 * Updates the server with the info of the session (isTalking, isCameraOn,...) so that it can broadcast it to the
15931 * other call participants.
15932 *
15933 * @param {import("#src/models/session.js").SessionInfo} info
15934 * @param {Object} [param0]
15935 * @param {boolean} [param0.needRefresh] true if the server should refresh the local info from all sessions of this channel
15936 */
15937 updateInfo(info, { needRefresh } = {}) {
15938 this._bus?.send(
15939 {
15940 name: CLIENT_MESSAGE.INFO_CHANGE,
15941 payload: { info, needRefresh },
15942 },
15943 { batch: true }
15944 );
15945 }
15946
15947 /**
15948 * Stop or resume the consumption of tracks from the other call participants.
15949 *
15950 * @param {number} sessionId
15951 * @param {Object<[streamType, boolean]>} states e.g: { audio: true, camera: false }
15952 */
15953 updateDownload(sessionId, states) {
15954 const consumers = this._consumers.get(sessionId);
15955 if (!consumers) {
15956 return;
15957 }
15958 let hasChanged = false;
15959 for (const [type, active] of Object.entries(states)) {
15960 if (!SUPPORTED_TYPES.has(type)) {
15961 continue;
15962 }
15963 const consumer = consumers[type];
15964 if (consumer) {
15965 if (active !== consumer.paused) {
15966 continue;
15967 }
15968 hasChanged = true;
15969 if (active) {
15970 consumer.resume();
15971 } else {
15972 consumer.pause();
15973 }
15974 }
15975 }
15976 if (!hasChanged) {
15977 return;
15978 }
15979 this._bus?.send(
15980 {
15981 name: CLIENT_MESSAGE.CONSUMPTION_CHANGE,
15982 payload: { sessionId, states },
15983 },
15984 { batch: true }
15985 );
15986 }
15987
15988 /**
15989 * @param {streamType} type
15990 * @param {MediaStreamTrack | null} track track to be sent to the other call participants,
15991 * not setting it will remove the track from the server
15992 */
15993 async updateUpload(type, track) {
15994 if (!SUPPORTED_TYPES.has(type)) {
15995 throw new Error(`Unsupported media type ${type}`);
15996 }
15997 clearTimeout(this._recoverProducerTimeouts[type]);
15998 const existingProducer = this._producers[type];
15999 if (existingProducer) {
16000 if (track) {
16001 await existingProducer.replaceTrack({ track });
16002 }
16003 this._bus.send(
16004 {
16005 name: CLIENT_MESSAGE.PRODUCTION_CHANGE,
16006 payload: { type, active: Boolean(track) },
16007 },
16008 { batch: true }
16009 );
16010 return;
16011 }
16012 if (!track) {
16013 return;
16014 }
16015 try {
16016 this._producers[type] = await this._ctsTransport.produce({
16017 ...this._producerOptionsByKind[track.kind],
16018 track,
16019 appData: { type },
16020 });
16021 } catch (error) {
16022 this.errors.push(error);
16023 // if we reach the max error count, we restart the whole connection from scratch
16024 if (this.errors.length > MAX_ERRORS) {
16025 // not awaited
16026 this._handleConnectionEnd();
16027 return;
16028 }
16029 // retry after some delay
16030 this._recoverProducerTimeouts[type] = setTimeout(async () => {
16031 await this.updateUpload(type, track);
16032 }, RECOVERY_DELAY);
16033 return;
16034 }
16035 this._onCleanup(() => {
16036 this._producers[type]?.close();
16037 this._producers[type] = null;
16038 clearTimeout(this._recoverProducerTimeouts[type]);
16039 });
16040 }
16041
16042 /**
16043 * To be overridden in tests.
16044 *
16045 * @returns {import("mediasoup-client").types.Device}
16046 */
16047 _createDevice() {
16048 return new lib$2.Device();
16049 }
16050
16051 /**
16052 * To be overridden in tests.
16053 *
16054 * @param {string} url
16055 * @returns {WebSocket}
16056 * @private
16057 */
16058 _createWebSocket(url) {
16059 return new WebSocket(url);
16060 }
16061
16062 /**
16063 * Opens the webSocket connection to the server and authenticates, handles reconnection attempts.
16064 */
16065 async _connect() {
16066 if (ACTIVE_STATES.has(this.state)) {
16067 return;
16068 }
16069 this._clear();
16070 this.state = SFU_CLIENT_STATE.CONNECTING;
16071 try {
16072 this._bus = await this._createBus();
16073 this.state = SFU_CLIENT_STATE.AUTHENTICATED;
16074 } catch {
16075 this._handleConnectionEnd();
16076 return;
16077 }
16078 this._bus.onMessage = this._handleMessage;
16079 this._bus.onRequest = this._handleRequest;
16080 }
16081
16082 /**
16083 * @param {string} [cause]
16084 * @private
16085 */
16086 _close(cause) {
16087 this._clear();
16088 const state = SFU_CLIENT_STATE.CLOSED;
16089 this._state = state;
16090 this.dispatchEvent(new CustomEvent("stateChange", { detail: { state, cause } }));
16091 }
16092
16093 /**
16094 * @returns {Promise<Bus>}
16095 */
16096 _createBus() {
16097 return new Promise((resolve, reject) => {
16098 let webSocket;
16099 try {
16100 webSocket = this._createWebSocket(this._url);
16101 } catch (error) {
16102 reject(error);
16103 return;
16104 }
16105 webSocket.addEventListener("close", this._handleConnectionEnd);
16106 webSocket.addEventListener("error", this._handleConnectionEnd);
16107 this._onCleanup(() => {
16108 webSocket.removeEventListener("close", this._handleConnectionEnd);
16109 webSocket.removeEventListener("error", this._handleConnectionEnd);
16110 if (webSocket.readyState < webSocket.CLOSING) {
16111 webSocket.close(WS_CLOSE_CODE.CLEAN);
16112 }
16113 });
16114 /**
16115 * Websocket handshake with the rtc server,
16116 * when opening the webSocket, the server expects the first message to contain the jwt.
16117 */
16118 webSocket.addEventListener(
16119 "open",
16120 () => {
16121 webSocket.send(
16122 JSON.stringify({ channelUUID: this._channelUUID, jwt: this._jsonWebToken })
16123 );
16124 },
16125 { once: true }
16126 );
16127 /**
16128 * Receiving a message means that the server has authenticated the client and is ready to receive messages.
16129 */
16130 webSocket.addEventListener(
16131 "message",
16132 () => {
16133 resolve(new Bus(webSocket));
16134 },
16135 { once: true }
16136 );
16137 });
16138 }
16139
16140 /**
16141 * @param {Function} callback
16142 */
16143 _onCleanup(callback) {
16144 this._cleanups.push(callback);
16145 }
16146
16147 _clear() {
16148 for (const cleanup of this._cleanups.splice(0)) {
16149 cleanup();
16150 }
16151 this.errors = [];
16152 for (const consumers of this._consumers.values()) {
16153 for (const consumer of Object.values(consumers)) {
16154 consumer?.close();
16155 }
16156 }
16157 this._consumers.clear();
16158 }
16159
16160 /**
16161 * @param {import("#src/models/session.js").SessionInfo.TransportConfig} ctsConfig
16162 */
16163 _makeCTSTransport(ctsConfig) {
16164 const transport = this._device.createSendTransport({
16165 ...ctsConfig,
16166 iceServers: this._iceServers,
16167 });
16168 transport.on("connect", async ({ dtlsParameters }, callback, errback) => {
16169 try {
16170 await this._bus.request({
16171 name: CLIENT_REQUEST.CONNECT_CTS_TRANSPORT,
16172 payload: { dtlsParameters },
16173 });
16174 callback();
16175 } catch (error) {
16176 errback(error);
16177 }
16178 });
16179 transport.on("produce", async ({ kind, rtpParameters, appData }, callback, errback) => {
16180 try {
16181 const result = await this._bus.request({
16182 name: CLIENT_REQUEST.INIT_PRODUCER,
16183 payload: { type: appData.type, kind, rtpParameters },
16184 });
16185 callback({ id: result.id });
16186 } catch (error) {
16187 errback(error);
16188 }
16189 });
16190 this._ctsTransport = transport;
16191 this._onCleanup(() => transport.close());
16192 }
16193
16194 /**
16195 * @param {import("#src/models/session.js").SessionInfo.TransportConfig} stcConfig
16196 */
16197 _makeSTCTransport(stcConfig) {
16198 const transport = this._device.createRecvTransport({
16199 ...stcConfig,
16200 iceServers: this._iceServers,
16201 });
16202 transport.on("connect", async ({ dtlsParameters }, callback, errback) => {
16203 try {
16204 await this._bus.request({
16205 name: CLIENT_REQUEST.CONNECT_STC_TRANSPORT,
16206 payload: { dtlsParameters },
16207 });
16208 callback();
16209 } catch (error) {
16210 errback(error);
16211 }
16212 });
16213 this._stcTransport = transport;
16214 this._onCleanup(() => transport.close());
16215 }
16216
16217 /**
16218 * @param {number} sessionId
16219 */
16220 _removeConsumers(sessionId) {
16221 const consumers = this._consumers.get(sessionId);
16222 if (!consumers) {
16223 return;
16224 }
16225 for (const consumer of Object.values(consumers)) {
16226 consumer?.close();
16227 }
16228 this._consumers.delete(sessionId);
16229 }
16230
16231 /**
16232 * dispatches an event, intended for the client
16233 *
16234 * @param { "disconnect" | "info_change" | "track" | "error" | "broadcast"} name
16235 * @param [payload]
16236 * @fires SfuClient#update
16237 */
16238 _updateClient(name, payload) {
16239 /**
16240 * @event SfuClient#update
16241 * @type {Object}
16242 * @property {Object} detail
16243 * @property {string} detail.name
16244 * @property {Object} detail.payload
16245 */
16246 this.dispatchEvent(new CustomEvent("update", { detail: { name, payload } }));
16247 }
16248
16249 /**
16250 * Handles cases where the connection to the server ends or in error and attempts to recover it if appropriate.
16251 *
16252 * @param {Event | CloseEvent} [event]
16253 */
16254 _handleConnectionEnd(event) {
16255 if (this.state === SFU_CLIENT_STATE.DISCONNECTED) {
16256 // state DISCONNECTED is intentional, so there is no reason to retry
16257 return;
16258 }
16259 switch (event?.code) {
16260 case WS_CLOSE_CODE.CHANNEL_FULL:
16261 this._close("full");
16262 return;
16263 case WS_CLOSE_CODE.AUTHENTICATION_FAILED:
16264 case WS_CLOSE_CODE.KICKED:
16265 this._close();
16266 return;
16267 }
16268 this.state = SFU_CLIENT_STATE.RECOVERING;
16269 // Retry connecting with an exponential backoff.
16270 this._connectRetryDelay =
16271 Math.min(this._connectRetryDelay * 1.5, MAXIMUM_RECONNECT_DELAY) + 1000 * Math.random();
16272 const timeout = setTimeout(this._connect.bind(this), this._connectRetryDelay);
16273 this._onCleanup(() => clearTimeout(timeout));
16274 }
16275
16276 /**
16277 * @param {Object} param0
16278 * @param {string} param0.name
16279 * @param {Object} param0.payload
16280 */
16281 async _handleMessage({ name, payload }) {
16282 switch (name) {
16283 case SERVER_MESSAGE.BROADCAST:
16284 this._updateClient("broadcast", payload);
16285 break;
16286 case SERVER_MESSAGE.SESSION_LEAVE:
16287 {
16288 const { sessionId } = payload;
16289 this._removeConsumers(sessionId);
16290 this._updateClient("disconnect", payload);
16291 }
16292 break;
16293 case SERVER_MESSAGE.INFO_CHANGE:
16294 this._updateClient("info_change", payload);
16295 break;
16296 }
16297 }
16298
16299 /**
16300 * @param {Object} param0
16301 * @param {string} param0.name
16302 * @param {Object} [param0.payload]
16303 * @returns {Promise<any>} response to the request, JSON-serializable
16304 */
16305 async _handleRequest({ name, payload }) {
16306 switch (name) {
16307 case SERVER_REQUEST.INIT_CONSUMER: {
16308 const { id, kind, producerId, rtpParameters, sessionId, type, active } = payload;
16309 let consumers;
16310 if (!this._consumers.has(sessionId)) {
16311 consumers = {
16312 audio: null,
16313 camera: null,
16314 screen: null,
16315 };
16316 this._consumers.set(sessionId, consumers);
16317 } else {
16318 consumers = this._consumers.get(sessionId);
16319 consumers[type]?.close();
16320 }
16321 const consumer = await this._stcTransport.consume({
16322 id,
16323 producerId,
16324 kind,
16325 rtpParameters,
16326 });
16327 if (!active) {
16328 consumer.pause();
16329 } else {
16330 consumer.resume();
16331 }
16332 this._updateClient("track", { type, sessionId, track: consumer.track, active });
16333 consumers[type] = consumer;
16334 return;
16335 }
16336 case SERVER_REQUEST.INIT_TRANSPORTS: {
16337 const { capabilities, stcConfig, ctsConfig, producerOptionsByKind } = payload;
16338 if (producerOptionsByKind) {
16339 this._producerOptionsByKind = producerOptionsByKind;
16340 }
16341 if (!this._device.loaded) {
16342 await this._device.load({ routerRtpCapabilities: capabilities });
16343 }
16344 this._makeSTCTransport(stcConfig);
16345 this._makeCTSTransport(ctsConfig);
16346 this.state = SFU_CLIENT_STATE.CONNECTED;
16347 return this._device.rtpCapabilities;
16348 }
16349 case SERVER_REQUEST.PING:
16350 return; // the server just needs a response, merely returning is enough
16351 }
16352 }
16353 }
16354
16355 export { SFU_CLIENT_STATE, SfuClient };
16356
16357
16358 export const __info__ = {
16359 date: '2024-08-26T05:07:14.489Z',
16360 hash: 'fcd3031',
16361 url: 'https://github.com/odoo/sfu',
16362 };