livekit-client 1.11.4 → 1.12.0
Sign up to get free protection for your applications and to get access to all the features.
- package/README.md +1 -3
- package/dist/livekit-client.e2ee.worker.js +2 -0
- package/dist/livekit-client.e2ee.worker.js.map +1 -0
- package/dist/livekit-client.e2ee.worker.mjs +1525 -0
- package/dist/livekit-client.e2ee.worker.mjs.map +1 -0
- package/dist/livekit-client.esm.mjs +4749 -4055
- package/dist/livekit-client.esm.mjs.map +1 -1
- package/dist/livekit-client.umd.js +1 -1
- package/dist/livekit-client.umd.js.map +1 -1
- package/dist/src/api/SignalClient.d.ts +4 -1
- package/dist/src/api/SignalClient.d.ts.map +1 -1
- package/dist/src/connectionHelper/checks/turn.d.ts.map +1 -1
- package/dist/src/connectionHelper/checks/websocket.d.ts.map +1 -1
- package/dist/src/e2ee/E2eeManager.d.ts +45 -0
- package/dist/src/e2ee/E2eeManager.d.ts.map +1 -0
- package/dist/src/e2ee/KeyProvider.d.ts +42 -0
- package/dist/src/e2ee/KeyProvider.d.ts.map +1 -0
- package/dist/src/e2ee/constants.d.ts +14 -0
- package/dist/src/e2ee/constants.d.ts.map +1 -0
- package/dist/src/e2ee/errors.d.ts +11 -0
- package/dist/src/e2ee/errors.d.ts.map +1 -0
- package/dist/src/e2ee/index.d.ts +4 -0
- package/dist/src/e2ee/index.d.ts.map +1 -0
- package/dist/src/e2ee/types.d.ts +129 -0
- package/dist/src/e2ee/types.d.ts.map +1 -0
- package/dist/src/e2ee/utils.d.ts +24 -0
- package/dist/src/e2ee/utils.d.ts.map +1 -0
- package/dist/src/e2ee/worker/FrameCryptor.d.ts +175 -0
- package/dist/src/e2ee/worker/FrameCryptor.d.ts.map +1 -0
- package/dist/src/e2ee/worker/ParticipantKeyHandler.d.ts +46 -0
- package/dist/src/e2ee/worker/ParticipantKeyHandler.d.ts.map +1 -0
- package/dist/src/e2ee/worker/e2ee.worker.d.ts +2 -0
- package/dist/src/e2ee/worker/e2ee.worker.d.ts.map +1 -0
- package/dist/src/index.d.ts +1 -0
- package/dist/src/index.d.ts.map +1 -1
- package/dist/src/logger.d.ts +4 -1
- package/dist/src/logger.d.ts.map +1 -1
- package/dist/src/options.d.ts +5 -0
- package/dist/src/options.d.ts.map +1 -1
- package/dist/src/proto/livekit_models.d.ts +2 -2
- package/dist/src/proto/livekit_models.d.ts.map +1 -1
- package/dist/src/room/PCTransport.d.ts +3 -1
- package/dist/src/room/PCTransport.d.ts.map +1 -1
- package/dist/src/room/RTCEngine.d.ts +17 -3
- package/dist/src/room/RTCEngine.d.ts.map +1 -1
- package/dist/src/room/Room.d.ts +10 -0
- package/dist/src/room/Room.d.ts.map +1 -1
- package/dist/src/room/events.d.ts +14 -2
- package/dist/src/room/events.d.ts.map +1 -1
- package/dist/src/room/participant/LocalParticipant.d.ts +7 -2
- package/dist/src/room/participant/LocalParticipant.d.ts.map +1 -1
- package/dist/src/room/participant/Participant.d.ts +1 -0
- package/dist/src/room/participant/Participant.d.ts.map +1 -1
- package/dist/src/room/track/LocalTrack.d.ts.map +1 -1
- package/dist/src/room/track/RemoteVideoTrack.d.ts.map +1 -1
- package/dist/src/room/track/TrackPublication.d.ts +3 -0
- package/dist/src/room/track/TrackPublication.d.ts.map +1 -1
- package/dist/src/room/track/options.d.ts +2 -2
- package/dist/src/room/track/options.d.ts.map +1 -1
- package/dist/src/room/track/utils.d.ts +9 -0
- package/dist/src/room/track/utils.d.ts.map +1 -1
- package/dist/src/room/utils.d.ts +2 -0
- package/dist/src/room/utils.d.ts.map +1 -1
- package/dist/src/test/MockMediaStreamTrack.d.ts.map +1 -1
- package/dist/ts4.2/src/api/SignalClient.d.ts +4 -1
- package/dist/ts4.2/src/e2ee/E2eeManager.d.ts +45 -0
- package/dist/ts4.2/src/e2ee/KeyProvider.d.ts +42 -0
- package/dist/ts4.2/src/e2ee/constants.d.ts +14 -0
- package/dist/ts4.2/src/e2ee/errors.d.ts +11 -0
- package/dist/ts4.2/src/e2ee/index.d.ts +4 -0
- package/dist/ts4.2/src/e2ee/types.d.ts +129 -0
- package/dist/ts4.2/src/e2ee/utils.d.ts +24 -0
- package/dist/ts4.2/src/e2ee/worker/FrameCryptor.d.ts +175 -0
- package/dist/ts4.2/src/e2ee/worker/ParticipantKeyHandler.d.ts +46 -0
- package/dist/ts4.2/src/e2ee/worker/e2ee.worker.d.ts +2 -0
- package/dist/ts4.2/src/index.d.ts +1 -0
- package/dist/ts4.2/src/logger.d.ts +4 -1
- package/dist/ts4.2/src/options.d.ts +5 -0
- package/dist/ts4.2/src/proto/livekit_models.d.ts +2 -2
- package/dist/ts4.2/src/room/PCTransport.d.ts +3 -1
- package/dist/ts4.2/src/room/RTCEngine.d.ts +17 -3
- package/dist/ts4.2/src/room/Room.d.ts +10 -0
- package/dist/ts4.2/src/room/events.d.ts +14 -2
- package/dist/ts4.2/src/room/participant/LocalParticipant.d.ts +7 -2
- package/dist/ts4.2/src/room/participant/Participant.d.ts +1 -0
- package/dist/ts4.2/src/room/track/TrackPublication.d.ts +3 -0
- package/dist/ts4.2/src/room/track/options.d.ts +6 -6
- package/dist/ts4.2/src/room/track/utils.d.ts +9 -0
- package/dist/ts4.2/src/room/utils.d.ts +2 -0
- package/package.json +17 -7
- package/src/api/SignalClient.ts +28 -9
- package/src/connectionHelper/checks/turn.ts +1 -0
- package/src/connectionHelper/checks/websocket.ts +1 -0
- package/src/e2ee/E2eeManager.ts +374 -0
- package/src/e2ee/KeyProvider.ts +77 -0
- package/src/e2ee/constants.ts +40 -0
- package/src/e2ee/errors.ts +16 -0
- package/src/e2ee/index.ts +3 -0
- package/src/e2ee/types.ts +160 -0
- package/src/e2ee/utils.ts +127 -0
- package/src/e2ee/worker/FrameCryptor.test.ts +21 -0
- package/src/e2ee/worker/FrameCryptor.ts +614 -0
- package/src/e2ee/worker/ParticipantKeyHandler.ts +129 -0
- package/src/e2ee/worker/e2ee.worker.ts +217 -0
- package/src/e2ee/worker/tsconfig.json +6 -0
- package/src/index.ts +1 -0
- package/src/logger.ts +10 -2
- package/src/options.ts +6 -0
- package/src/proto/livekit_models.ts +12 -12
- package/src/room/PCTransport.ts +39 -9
- package/src/room/RTCEngine.ts +127 -34
- package/src/room/Room.ts +77 -22
- package/src/room/defaults.ts +1 -1
- package/src/room/events.ts +14 -0
- package/src/room/participant/LocalParticipant.ts +52 -8
- package/src/room/participant/Participant.ts +4 -0
- package/src/room/track/LocalTrack.ts +5 -4
- package/src/room/track/RemoteVideoTrack.ts +2 -2
- package/src/room/track/TrackPublication.ts +9 -1
- package/src/room/track/options.ts +3 -2
- package/src/room/track/utils.ts +27 -0
- package/src/room/utils.ts +5 -0
- package/src/room/worker.d.ts +4 -0
- package/src/test/MockMediaStreamTrack.ts +1 -0
@@ -1,2 +1,2 @@
|
|
1
|
-
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).LivekitClient={})}(this,(function(e){"use strict";function t(e,t){return t.forEach((function(t){t&&"string"!=typeof t&&!Array.isArray(t)&&Object.keys(t).forEach((function(i){if("default"!==i&&!(i in e)){var n=Object.getOwnPropertyDescriptor(t,i);Object.defineProperty(e,i,n.get?n:{enumerable:!0,get:function(){return t[i]}})}}))})),Object.freeze(e)}var i="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function n(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var r={exports:{}};!function(e){var t,n;t=i,n=function(){var e=function(){},t="undefined",i=typeof window!==t&&typeof window.navigator!==t&&/Trident\/|MSIE /.test(window.navigator.userAgent),n=["trace","debug","info","warn","error"];function r(e,t){var i=e[t];if("function"==typeof i.bind)return i.bind(e);try{return Function.prototype.bind.call(i,e)}catch(t){return function(){return Function.prototype.apply.apply(i,[e,arguments])}}}function s(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function o(t,i){for(var r=0;r<n.length;r++){var s=n[r];this[s]=r<t?e:this.methodFactory(s,t,i)}this.log=this.debug}function a(e,i,n){return function(){typeof console!==t&&(o.call(this,i,n),this[e].apply(this,arguments))}}function c(n,o,c){return function(n){return"debug"===n&&(n="log"),typeof console!==t&&("trace"===n&&i?s:void 0!==console[n]?r(console,n):void 0!==console.log?r(console,"log"):e)}(n)||a.apply(this,arguments)}function d(e,i,r){var s,a=this;i=null==i?"WARN":i;var d="loglevel";function u(){var e;if(typeof window!==t&&d){try{e=window.localStorage[d]}catch(e){}if(typeof e===t)try{var i=window.document.cookie,n=i.indexOf(encodeURIComponent(d)+"=");-1!==n&&(e=/^([^;]+)/.exec(i.slice(n))[1])}catch(e){}return void 0===a.levels[e]&&(e=void 0),e}}"string"==typeof e?d+=":"+e:"symbol"==typeof e&&(d=void 0),a.name=e,a.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},a.methodFactory=r||c,a.getLevel=function(){return s},a.setLevel=function(i,r){if("string"==typeof i&&void 0!==a.levels[i.toUpperCase()]&&(i=a.levels[i.toUpperCase()]),!("number"==typeof i&&i>=0&&i<=a.levels.SILENT))throw"log.setLevel() called with invalid level: "+i;if(s=i,!1!==r&&function(e){var i=(n[e]||"silent").toUpperCase();if(typeof window!==t&&d){try{return void(window.localStorage[d]=i)}catch(e){}try{window.document.cookie=encodeURIComponent(d)+"="+i+";"}catch(e){}}}(i),o.call(a,i,e),typeof console===t&&i<a.levels.SILENT)return"No console available for logging"},a.setDefaultLevel=function(e){i=e,u()||a.setLevel(e,!1)},a.resetLevel=function(){a.setLevel(i,!1),function(){if(typeof window!==t&&d){try{return void window.localStorage.removeItem(d)}catch(e){}try{window.document.cookie=encodeURIComponent(d)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch(e){}}}()},a.enableAll=function(e){a.setLevel(a.levels.TRACE,e)},a.disableAll=function(e){a.setLevel(a.levels.SILENT,e)};var l=u();null==l&&(l=i),a.setLevel(l,!1)}var u=new d,l={};u.getLogger=function(e){if("symbol"!=typeof e&&"string"!=typeof e||""===e)throw new TypeError("You must supply a name when creating a logger.");var t=l[e];return t||(t=l[e]=new d(e,u.getLevel(),u.methodFactory)),t};var h=typeof window!==t?window.log:void 0;return u.noConflict=function(){return typeof window!==t&&window.log===u&&(window.log=h),u},u.getLoggers=function(){return l},u.default=u,u},e.exports?e.exports=n():t.log=n()}(r);var s,o=r.exports,a=n(o);e.LogLevel=void 0,(s=e.LogLevel||(e.LogLevel={}))[s.trace=0]="trace",s[s.debug=1]="debug",s[s.info=2]="info",s[s.warn=3]="warn",s[s.error=4]="error",s[s.silent=5]="silent";const c=o.getLogger("livekit");c.setDefaultLevel(e.LogLevel.info);var d=l,u=null;try{u=new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0,97,115,109,1,0,0,0,1,13,2,96,0,1,127,96,4,127,127,127,127,1,127,3,7,6,0,1,1,1,1,1,6,6,1,127,1,65,0,11,7,50,6,3,109,117,108,0,1,5,100,105,118,95,115,0,2,5,100,105,118,95,117,0,3,5,114,101,109,95,115,0,4,5,114,101,109,95,117,0,5,8,103,101,116,95,104,105,103,104,0,0,10,191,1,6,4,0,35,0,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,126,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,127,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,128,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,129,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,130,34,4,66,32,135,167,36,0,32,4,167,11])),{}).exports}catch(e){}function l(e,t,i){this.low=0|e,this.high=0|t,this.unsigned=!!i}function h(e){return!0===(e&&e.__isLong__)}l.prototype.__isLong__,Object.defineProperty(l.prototype,"__isLong__",{value:!0}),l.isLong=h;var p={},m={};function f(e,t){var i,n,r;return t?(r=0<=(e>>>=0)&&e<256)&&(n=m[e])?n:(i=g(e,(0|e)<0?-1:0,!0),r&&(m[e]=i),i):(r=-128<=(e|=0)&&e<128)&&(n=p[e])?n:(i=g(e,e<0?-1:0,!1),r&&(p[e]=i),i)}function v(e,t){if(isNaN(e))return t?w:P;if(t){if(e<0)return w;if(e>=C)return I}else{if(e<=-T)return A;if(e+1>=T)return D}return e<0?v(-e,t).neg():g(e%y|0,e/y|0,t)}function g(e,t,i){return new l(e,t,i)}l.fromInt=f,l.fromNumber=v,l.fromBits=g;var b=Math.pow;function k(e,t,i){if(0===e.length)throw Error("empty string");if("NaN"===e||"Infinity"===e||"+Infinity"===e||"-Infinity"===e)return P;if("number"==typeof t?(i=t,t=!1):t=!!t,(i=i||10)<2||36<i)throw RangeError("radix");var n;if((n=e.indexOf("-"))>0)throw Error("interior hyphen");if(0===n)return k(e.substring(1),t,i).neg();for(var r=v(b(i,8)),s=P,o=0;o<e.length;o+=8){var a=Math.min(8,e.length-o),c=parseInt(e.substring(o,o+a),i);if(a<8){var d=v(b(i,a));s=s.mul(d).add(v(c))}else s=(s=s.mul(r)).add(v(c))}return s.unsigned=t,s}function S(e,t){return"number"==typeof e?v(e,t):"string"==typeof e?k(e,t):g(e.low,e.high,"boolean"==typeof t?t:e.unsigned)}l.fromString=k,l.fromValue=S;var y=4294967296,C=y*y,T=C/2,E=f(1<<24),P=f(0);l.ZERO=P;var w=f(0,!0);l.UZERO=w;var R=f(1);l.ONE=R;var N=f(1,!0);l.UONE=N;var O=f(-1);l.NEG_ONE=O;var D=g(-1,2147483647,!1);l.MAX_VALUE=D;var I=g(-1,-1,!0);l.MAX_UNSIGNED_VALUE=I;var A=g(0,-2147483648,!1);l.MIN_VALUE=A;var U=l.prototype;U.toInt=function(){return this.unsigned?this.low>>>0:this.low},U.toNumber=function(){return this.unsigned?(this.high>>>0)*y+(this.low>>>0):this.high*y+(this.low>>>0)},U.toString=function(e){if((e=e||10)<2||36<e)throw RangeError("radix");if(this.isZero())return"0";if(this.isNegative()){if(this.eq(A)){var t=v(e),i=this.div(t),n=i.mul(t).sub(this);return i.toString(e)+n.toInt().toString(e)}return"-"+this.neg().toString(e)}for(var r=v(b(e,6),this.unsigned),s=this,o="";;){var a=s.div(r),c=(s.sub(a.mul(r)).toInt()>>>0).toString(e);if((s=a).isZero())return c+o;for(;c.length<6;)c="0"+c;o=""+c+o}},U.getHighBits=function(){return this.high},U.getHighBitsUnsigned=function(){return this.high>>>0},U.getLowBits=function(){return this.low},U.getLowBitsUnsigned=function(){return this.low>>>0},U.getNumBitsAbs=function(){if(this.isNegative())return this.eq(A)?64:this.neg().getNumBitsAbs();for(var e=0!=this.high?this.high:this.low,t=31;t>0&&0==(e&1<<t);t--);return 0!=this.high?t+33:t+1},U.isZero=function(){return 0===this.high&&0===this.low},U.eqz=U.isZero,U.isNegative=function(){return!this.unsigned&&this.high<0},U.isPositive=function(){return this.unsigned||this.high>=0},U.isOdd=function(){return 1==(1&this.low)},U.isEven=function(){return 0==(1&this.low)},U.equals=function(e){return h(e)||(e=S(e)),(this.unsigned===e.unsigned||this.high>>>31!=1||e.high>>>31!=1)&&(this.high===e.high&&this.low===e.low)},U.eq=U.equals,U.notEquals=function(e){return!this.eq(e)},U.neq=U.notEquals,U.ne=U.notEquals,U.lessThan=function(e){return this.comp(e)<0},U.lt=U.lessThan,U.lessThanOrEqual=function(e){return this.comp(e)<=0},U.lte=U.lessThanOrEqual,U.le=U.lessThanOrEqual,U.greaterThan=function(e){return this.comp(e)>0},U.gt=U.greaterThan,U.greaterThanOrEqual=function(e){return this.comp(e)>=0},U.gte=U.greaterThanOrEqual,U.ge=U.greaterThanOrEqual,U.compare=function(e){if(h(e)||(e=S(e)),this.eq(e))return 0;var t=this.isNegative(),i=e.isNegative();return t&&!i?-1:!t&&i?1:this.unsigned?e.high>>>0>this.high>>>0||e.high===this.high&&e.low>>>0>this.low>>>0?-1:1:this.sub(e).isNegative()?-1:1},U.comp=U.compare,U.negate=function(){return!this.unsigned&&this.eq(A)?A:this.not().add(R)},U.neg=U.negate,U.add=function(e){h(e)||(e=S(e));var t=this.high>>>16,i=65535&this.high,n=this.low>>>16,r=65535&this.low,s=e.high>>>16,o=65535&e.high,a=e.low>>>16,c=0,d=0,u=0,l=0;return u+=(l+=r+(65535&e.low))>>>16,d+=(u+=n+a)>>>16,c+=(d+=i+o)>>>16,c+=t+s,g((u&=65535)<<16|(l&=65535),(c&=65535)<<16|(d&=65535),this.unsigned)},U.subtract=function(e){return h(e)||(e=S(e)),this.add(e.neg())},U.sub=U.subtract,U.multiply=function(e){if(this.isZero())return P;if(h(e)||(e=S(e)),u)return g(u.mul(this.low,this.high,e.low,e.high),u.get_high(),this.unsigned);if(e.isZero())return P;if(this.eq(A))return e.isOdd()?A:P;if(e.eq(A))return this.isOdd()?A:P;if(this.isNegative())return e.isNegative()?this.neg().mul(e.neg()):this.neg().mul(e).neg();if(e.isNegative())return this.mul(e.neg()).neg();if(this.lt(E)&&e.lt(E))return v(this.toNumber()*e.toNumber(),this.unsigned);var t=this.high>>>16,i=65535&this.high,n=this.low>>>16,r=65535&this.low,s=e.high>>>16,o=65535&e.high,a=e.low>>>16,c=65535&e.low,d=0,l=0,p=0,m=0;return p+=(m+=r*c)>>>16,l+=(p+=n*c)>>>16,p&=65535,l+=(p+=r*a)>>>16,d+=(l+=i*c)>>>16,l&=65535,d+=(l+=n*a)>>>16,l&=65535,d+=(l+=r*o)>>>16,d+=t*c+i*a+n*o+r*s,g((p&=65535)<<16|(m&=65535),(d&=65535)<<16|(l&=65535),this.unsigned)},U.mul=U.multiply,U.divide=function(e){if(h(e)||(e=S(e)),e.isZero())throw Error("division by zero");var t,i,n;if(u)return this.unsigned||-2147483648!==this.high||-1!==e.low||-1!==e.high?g((this.unsigned?u.div_u:u.div_s)(this.low,this.high,e.low,e.high),u.get_high(),this.unsigned):this;if(this.isZero())return this.unsigned?w:P;if(this.unsigned){if(e.unsigned||(e=e.toUnsigned()),e.gt(this))return w;if(e.gt(this.shru(1)))return N;n=w}else{if(this.eq(A))return e.eq(R)||e.eq(O)?A:e.eq(A)?R:(t=this.shr(1).div(e).shl(1)).eq(P)?e.isNegative()?R:O:(i=this.sub(e.mul(t)),n=t.add(i.div(e)));if(e.eq(A))return this.unsigned?w:P;if(this.isNegative())return e.isNegative()?this.neg().div(e.neg()):this.neg().div(e).neg();if(e.isNegative())return this.div(e.neg()).neg();n=P}for(i=this;i.gte(e);){t=Math.max(1,Math.floor(i.toNumber()/e.toNumber()));for(var r=Math.ceil(Math.log(t)/Math.LN2),s=r<=48?1:b(2,r-48),o=v(t),a=o.mul(e);a.isNegative()||a.gt(i);)a=(o=v(t-=s,this.unsigned)).mul(e);o.isZero()&&(o=R),n=n.add(o),i=i.sub(a)}return n},U.div=U.divide,U.modulo=function(e){return h(e)||(e=S(e)),u?g((this.unsigned?u.rem_u:u.rem_s)(this.low,this.high,e.low,e.high),u.get_high(),this.unsigned):this.sub(this.div(e).mul(e))},U.mod=U.modulo,U.rem=U.modulo,U.not=function(){return g(~this.low,~this.high,this.unsigned)},U.and=function(e){return h(e)||(e=S(e)),g(this.low&e.low,this.high&e.high,this.unsigned)},U.or=function(e){return h(e)||(e=S(e)),g(this.low|e.low,this.high|e.high,this.unsigned)},U.xor=function(e){return h(e)||(e=S(e)),g(this.low^e.low,this.high^e.high,this.unsigned)},U.shiftLeft=function(e){return h(e)&&(e=e.toInt()),0==(e&=63)?this:e<32?g(this.low<<e,this.high<<e|this.low>>>32-e,this.unsigned):g(0,this.low<<e-32,this.unsigned)},U.shl=U.shiftLeft,U.shiftRight=function(e){return h(e)&&(e=e.toInt()),0==(e&=63)?this:e<32?g(this.low>>>e|this.high<<32-e,this.high>>e,this.unsigned):g(this.high>>e-32,this.high>=0?0:-1,this.unsigned)},U.shr=U.shiftRight,U.shiftRightUnsigned=function(e){if(h(e)&&(e=e.toInt()),0===(e&=63))return this;var t=this.high;return e<32?g(this.low>>>e|t<<32-e,t>>>e,this.unsigned):g(32===e?t:t>>>e-32,0,this.unsigned)},U.shru=U.shiftRightUnsigned,U.shr_u=U.shiftRightUnsigned,U.toSigned=function(){return this.unsigned?g(this.low,this.high,!1):this},U.toUnsigned=function(){return this.unsigned?this:g(this.low,this.high,!0)},U.toBytes=function(e){return e?this.toBytesLE():this.toBytesBE()},U.toBytesLE=function(){var e=this.high,t=this.low;return[255&t,t>>>8&255,t>>>16&255,t>>>24,255&e,e>>>8&255,e>>>16&255,e>>>24]},U.toBytesBE=function(){var e=this.high,t=this.low;return[e>>>24,e>>>16&255,e>>>8&255,255&e,t>>>24,t>>>16&255,t>>>8&255,255&t]},l.fromBytes=function(e,t,i){return i?l.fromBytesLE(e,t):l.fromBytesBE(e,t)},l.fromBytesLE=function(e,t){return new l(e[0]|e[1]<<8|e[2]<<16|e[3]<<24,e[4]|e[5]<<8|e[6]<<16|e[7]<<24,t)},l.fromBytesBE=function(e,t){return new l(e[4]<<24|e[5]<<16|e[6]<<8|e[7],e[0]<<24|e[1]<<16|e[2]<<8|e[3],t)};var M,L,_=n(d),x={},B={};var J,F,$,j,V,q,W,G={};var Q,H,K,Z,z,Y,X={};function ee(){return Y||(Y=1,function(e){var t=e;function n(e,t,i){for(var n=Object.keys(t),r=0;r<n.length;++r)void 0!==e[n[r]]&&i||(e[n[r]]=t[n[r]]);return e}function r(e){function t(e,i){if(!(this instanceof t))return new t(e,i);Object.defineProperty(this,"message",{get:function(){return e}}),Error.captureStackTrace?Error.captureStackTrace(this,t):Object.defineProperty(this,"stack",{value:(new Error).stack||""}),i&&n(this,i)}return t.prototype=Object.create(Error.prototype,{constructor:{value:t,writable:!0,enumerable:!1,configurable:!0},name:{get:function(){return e},set:void 0,enumerable:!1,configurable:!0},toString:{value:function(){return this.name+": "+this.message},writable:!0,enumerable:!1,configurable:!0}}),t}t.asPromise=(L||(L=1,M=function(e,t){for(var i=new Array(arguments.length-1),n=0,r=2,s=!0;r<arguments.length;)i[n++]=arguments[r++];return new Promise((function(r,o){i[n]=function(e){if(s)if(s=!1,e)o(e);else{for(var t=new Array(arguments.length-1),i=0;i<t.length;)t[i++]=arguments[i];r.apply(null,t)}};try{e.apply(t||null,i)}catch(e){s&&(s=!1,o(e))}}))}),M),t.base64=(J||(J=1,function(e){var t=e;t.length=function(e){var t=e.length;if(!t)return 0;for(var i=0;--t%4>1&&"="===e.charAt(t);)++i;return Math.ceil(3*e.length)/4-i};for(var i=new Array(64),n=new Array(123),r=0;r<64;)n[i[r]=r<26?r+65:r<52?r+71:r<62?r-4:r-59|43]=r++;t.encode=function(e,t,n){for(var r,s=null,o=[],a=0,c=0;t<n;){var d=e[t++];switch(c){case 0:o[a++]=i[d>>2],r=(3&d)<<4,c=1;break;case 1:o[a++]=i[r|d>>4],r=(15&d)<<2,c=2;break;case 2:o[a++]=i[r|d>>6],o[a++]=i[63&d],c=0}a>8191&&((s||(s=[])).push(String.fromCharCode.apply(String,o)),a=0)}return c&&(o[a++]=i[r],o[a++]=61,1===c&&(o[a++]=61)),s?(a&&s.push(String.fromCharCode.apply(String,o.slice(0,a))),s.join("")):String.fromCharCode.apply(String,o.slice(0,a))};var s="invalid encoding";t.decode=function(e,t,i){for(var r,o=i,a=0,c=0;c<e.length;){var d=e.charCodeAt(c++);if(61===d&&a>1)break;if(void 0===(d=n[d]))throw Error(s);switch(a){case 0:r=d,a=1;break;case 1:t[i++]=r<<2|(48&d)>>4,r=d,a=2;break;case 2:t[i++]=(15&r)<<4|(60&d)>>2,r=d,a=3;break;case 3:t[i++]=(3&r)<<6|d,a=0}}if(1===a)throw Error(s);return i-o},t.test=function(e){return/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(e)}}(G)),G),t.EventEmitter=function(){if($)return F;function e(){this._listeners={}}return $=1,F=e,e.prototype.on=function(e,t,i){return(this._listeners[e]||(this._listeners[e]=[])).push({fn:t,ctx:i||this}),this},e.prototype.off=function(e,t){if(void 0===e)this._listeners={};else if(void 0===t)this._listeners[e]=[];else for(var i=this._listeners[e],n=0;n<i.length;)i[n].fn===t?i.splice(n,1):++n;return this},e.prototype.emit=function(e){var t=this._listeners[e];if(t){for(var i=[],n=1;n<arguments.length;)i.push(arguments[n++]);for(n=0;n<t.length;)t[n].fn.apply(t[n++].ctx,i)}return this},F}(),t.float=function(){if(V)return j;function e(e){return"undefined"!=typeof Float32Array?function(){var t=new Float32Array([-0]),i=new Uint8Array(t.buffer),n=128===i[3];function r(e,n,r){t[0]=e,n[r]=i[0],n[r+1]=i[1],n[r+2]=i[2],n[r+3]=i[3]}function s(e,n,r){t[0]=e,n[r]=i[3],n[r+1]=i[2],n[r+2]=i[1],n[r+3]=i[0]}function o(e,n){return i[0]=e[n],i[1]=e[n+1],i[2]=e[n+2],i[3]=e[n+3],t[0]}function a(e,n){return i[3]=e[n],i[2]=e[n+1],i[1]=e[n+2],i[0]=e[n+3],t[0]}e.writeFloatLE=n?r:s,e.writeFloatBE=n?s:r,e.readFloatLE=n?o:a,e.readFloatBE=n?a:o}():function(){function s(e,t,i,n){var r=t<0?1:0;if(r&&(t=-t),0===t)e(1/t>0?0:2147483648,i,n);else if(isNaN(t))e(2143289344,i,n);else if(t>34028234663852886e22)e((r<<31|2139095040)>>>0,i,n);else if(t<11754943508222875e-54)e((r<<31|Math.round(t/1401298464324817e-60))>>>0,i,n);else{var s=Math.floor(Math.log(t)/Math.LN2);e((r<<31|s+127<<23|8388607&Math.round(t*Math.pow(2,-s)*8388608))>>>0,i,n)}}function o(e,t,i){var n=e(t,i),r=2*(n>>31)+1,s=n>>>23&255,o=8388607&n;return 255===s?o?NaN:r*(1/0):0===s?1401298464324817e-60*r*o:r*Math.pow(2,s-150)*(o+8388608)}e.writeFloatLE=s.bind(null,t),e.writeFloatBE=s.bind(null,i),e.readFloatLE=o.bind(null,n),e.readFloatBE=o.bind(null,r)}(),"undefined"!=typeof Float64Array?function(){var t=new Float64Array([-0]),i=new Uint8Array(t.buffer),n=128===i[7];function r(e,n,r){t[0]=e,n[r]=i[0],n[r+1]=i[1],n[r+2]=i[2],n[r+3]=i[3],n[r+4]=i[4],n[r+5]=i[5],n[r+6]=i[6],n[r+7]=i[7]}function s(e,n,r){t[0]=e,n[r]=i[7],n[r+1]=i[6],n[r+2]=i[5],n[r+3]=i[4],n[r+4]=i[3],n[r+5]=i[2],n[r+6]=i[1],n[r+7]=i[0]}function o(e,n){return i[0]=e[n],i[1]=e[n+1],i[2]=e[n+2],i[3]=e[n+3],i[4]=e[n+4],i[5]=e[n+5],i[6]=e[n+6],i[7]=e[n+7],t[0]}function a(e,n){return i[7]=e[n],i[6]=e[n+1],i[5]=e[n+2],i[4]=e[n+3],i[3]=e[n+4],i[2]=e[n+5],i[1]=e[n+6],i[0]=e[n+7],t[0]}e.writeDoubleLE=n?r:s,e.writeDoubleBE=n?s:r,e.readDoubleLE=n?o:a,e.readDoubleBE=n?a:o}():function(){function s(e,t,i,n,r,s){var o=n<0?1:0;if(o&&(n=-n),0===n)e(0,r,s+t),e(1/n>0?0:2147483648,r,s+i);else if(isNaN(n))e(0,r,s+t),e(2146959360,r,s+i);else if(n>17976931348623157e292)e(0,r,s+t),e((o<<31|2146435072)>>>0,r,s+i);else{var a;if(n<22250738585072014e-324)e((a=n/5e-324)>>>0,r,s+t),e((o<<31|a/4294967296)>>>0,r,s+i);else{var c=Math.floor(Math.log(n)/Math.LN2);1024===c&&(c=1023),e(4503599627370496*(a=n*Math.pow(2,-c))>>>0,r,s+t),e((o<<31|c+1023<<20|1048576*a&1048575)>>>0,r,s+i)}}}function o(e,t,i,n,r){var s=e(n,r+t),o=e(n,r+i),a=2*(o>>31)+1,c=o>>>20&2047,d=4294967296*(1048575&o)+s;return 2047===c?d?NaN:a*(1/0):0===c?5e-324*a*d:a*Math.pow(2,c-1075)*(d+4503599627370496)}e.writeDoubleLE=s.bind(null,t,0,4),e.writeDoubleBE=s.bind(null,i,4,0),e.readDoubleLE=o.bind(null,n,0,4),e.readDoubleBE=o.bind(null,r,4,0)}(),e}function t(e,t,i){t[i]=255&e,t[i+1]=e>>>8&255,t[i+2]=e>>>16&255,t[i+3]=e>>>24}function i(e,t,i){t[i]=e>>>24,t[i+1]=e>>>16&255,t[i+2]=e>>>8&255,t[i+3]=255&e}function n(e,t){return(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0}function r(e,t){return(e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3])>>>0}return V=1,j=e(e)}(),t.inquire=W?q:(W=1,q=function(e){return null}),t.utf8=(Q||(Q=1,function(e){var t=e;t.length=function(e){for(var t=0,i=0,n=0;n<e.length;++n)(i=e.charCodeAt(n))<128?t+=1:i<2048?t+=2:55296==(64512&i)&&56320==(64512&e.charCodeAt(n+1))?(++n,t+=4):t+=3;return t},t.read=function(e,t,i){if(i-t<1)return"";for(var n,r=null,s=[],o=0;t<i;)(n=e[t++])<128?s[o++]=n:n>191&&n<224?s[o++]=(31&n)<<6|63&e[t++]:n>239&&n<365?(n=((7&n)<<18|(63&e[t++])<<12|(63&e[t++])<<6|63&e[t++])-65536,s[o++]=55296+(n>>10),s[o++]=56320+(1023&n)):s[o++]=(15&n)<<12|(63&e[t++])<<6|63&e[t++],o>8191&&((r||(r=[])).push(String.fromCharCode.apply(String,s)),o=0);return r?(o&&r.push(String.fromCharCode.apply(String,s.slice(0,o))),r.join("")):String.fromCharCode.apply(String,s.slice(0,o))},t.write=function(e,t,i){for(var n,r,s=i,o=0;o<e.length;++o)(n=e.charCodeAt(o))<128?t[i++]=n:n<2048?(t[i++]=n>>6|192,t[i++]=63&n|128):55296==(64512&n)&&56320==(64512&(r=e.charCodeAt(o+1)))?(n=65536+((1023&n)<<10)+(1023&r),++o,t[i++]=n>>18|240,t[i++]=n>>12&63|128,t[i++]=n>>6&63|128,t[i++]=63&n|128):(t[i++]=n>>12|224,t[i++]=n>>6&63|128,t[i++]=63&n|128);return i-s}}(X)),X),t.pool=K?H:(K=1,H=function(e,t,i){var n=i||8192,r=n>>>1,s=null,o=n;return function(i){if(i<1||i>r)return e(i);o+i>n&&(s=e(n),o=0);var a=t.call(s,o,o+=i);return 7&o&&(o=1+(7|o)),a}}),t.LongBits=function(){if(z)return Z;z=1,Z=t;var e=ee();function t(e,t){this.lo=e>>>0,this.hi=t>>>0}var i=t.zero=new t(0,0);i.toNumber=function(){return 0},i.zzEncode=i.zzDecode=function(){return this},i.length=function(){return 1};var n=t.zeroHash="\0\0\0\0\0\0\0\0";t.fromNumber=function(e){if(0===e)return i;var n=e<0;n&&(e=-e);var r=e>>>0,s=(e-r)/4294967296>>>0;return n&&(s=~s>>>0,r=~r>>>0,++r>4294967295&&(r=0,++s>4294967295&&(s=0))),new t(r,s)},t.from=function(n){if("number"==typeof n)return t.fromNumber(n);if(e.isString(n)){if(!e.Long)return t.fromNumber(parseInt(n,10));n=e.Long.fromString(n)}return n.low||n.high?new t(n.low>>>0,n.high>>>0):i},t.prototype.toNumber=function(e){if(!e&&this.hi>>>31){var t=1+~this.lo>>>0,i=~this.hi>>>0;return t||(i=i+1>>>0),-(t+4294967296*i)}return this.lo+4294967296*this.hi},t.prototype.toLong=function(t){return e.Long?new e.Long(0|this.lo,0|this.hi,Boolean(t)):{low:0|this.lo,high:0|this.hi,unsigned:Boolean(t)}};var r=String.prototype.charCodeAt;return t.fromHash=function(e){return e===n?i:new t((r.call(e,0)|r.call(e,1)<<8|r.call(e,2)<<16|r.call(e,3)<<24)>>>0,(r.call(e,4)|r.call(e,5)<<8|r.call(e,6)<<16|r.call(e,7)<<24)>>>0)},t.prototype.toHash=function(){return String.fromCharCode(255&this.lo,this.lo>>>8&255,this.lo>>>16&255,this.lo>>>24,255&this.hi,this.hi>>>8&255,this.hi>>>16&255,this.hi>>>24)},t.prototype.zzEncode=function(){var e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this},t.prototype.zzDecode=function(){var e=-(1&this.lo);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this},t.prototype.length=function(){var e=this.lo,t=(this.lo>>>28|this.hi<<4)>>>0,i=this.hi>>>24;return 0===i?0===t?e<16384?e<128?1:2:e<2097152?3:4:t<16384?t<128?5:6:t<2097152?7:8:i<128?9:10},Z}(),t.isNode=Boolean(void 0!==i&&i&&i.process&&i.process.versions&&i.process.versions.node),t.global=t.isNode&&i||"undefined"!=typeof window&&window||"undefined"!=typeof self&&self||i,t.emptyArray=Object.freeze?Object.freeze([]):[],t.emptyObject=Object.freeze?Object.freeze({}):{},t.isInteger=Number.isInteger||function(e){return"number"==typeof e&&isFinite(e)&&Math.floor(e)===e},t.isString=function(e){return"string"==typeof e||e instanceof String},t.isObject=function(e){return e&&"object"==typeof e},t.isset=t.isSet=function(e,t){var i=e[t];return!(null==i||!e.hasOwnProperty(t))&&("object"!=typeof i||(Array.isArray(i)?i.length:Object.keys(i).length)>0)},t.Buffer=function(){try{var e=t.inquire("buffer").Buffer;return e.prototype.utf8Write?e:null}catch(e){return null}}(),t._Buffer_from=null,t._Buffer_allocUnsafe=null,t.newBuffer=function(e){return"number"==typeof e?t.Buffer?t._Buffer_allocUnsafe(e):new t.Array(e):t.Buffer?t._Buffer_from(e):"undefined"==typeof Uint8Array?e:new Uint8Array(e)},t.Array="undefined"!=typeof Uint8Array?Uint8Array:Array,t.Long=t.global.dcodeIO&&t.global.dcodeIO.Long||t.global.Long||t.inquire("long"),t.key2Re=/^true|false|0|1$/,t.key32Re=/^-?(?:0|[1-9][0-9]*)$/,t.key64Re=/^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/,t.longToHash=function(e){return e?t.LongBits.from(e).toHash():t.LongBits.zeroHash},t.longFromHash=function(e,i){var n=t.LongBits.fromHash(e);return t.Long?t.Long.fromBits(n.lo,n.hi,i):n.toNumber(Boolean(i))},t.merge=n,t.lcFirst=function(e){return e.charAt(0).toLowerCase()+e.substring(1)},t.newError=r,t.ProtocolError=r("ProtocolError"),t.oneOfGetter=function(e){for(var t={},i=0;i<e.length;++i)t[e[i]]=1;return function(){for(var e=Object.keys(this),i=e.length-1;i>-1;--i)if(1===t[e[i]]&&void 0!==this[e[i]]&&null!==this[e[i]])return e[i]}},t.oneOfSetter=function(e){return function(t){for(var i=0;i<e.length;++i)e[i]!==t&&delete this[e[i]]}},t.toJSONOptions={longs:String,enums:String,bytes:String,json:!0},t._configure=function(){var e=t.Buffer;e?(t._Buffer_from=e.from!==Uint8Array.from&&e.from||function(t,i){return new e(t,i)},t._Buffer_allocUnsafe=e.allocUnsafe||function(t){return new e(t)}):t._Buffer_from=t._Buffer_allocUnsafe=null}}(B)),B}var te,ie=ue,ne=ee(),re=ne.LongBits,se=ne.base64,oe=ne.utf8;function ae(e,t,i){this.fn=e,this.len=t,this.next=void 0,this.val=i}function ce(){}function de(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}function ue(){this.len=0,this.head=new ae(ce,0,0),this.tail=this.head,this.states=null}var le=function(){return ne.Buffer?function(){return(ue.create=function(){return new te})()}:function(){return new ue}};function he(e,t,i){t[i]=255&e}function pe(e,t){this.len=e,this.next=void 0,this.val=t}function me(e,t,i){for(;e.hi;)t[i++]=127&e.lo|128,e.lo=(e.lo>>>7|e.hi<<25)>>>0,e.hi>>>=7;for(;e.lo>127;)t[i++]=127&e.lo|128,e.lo=e.lo>>>7;t[i++]=e.lo}function fe(e,t,i){t[i]=255&e,t[i+1]=e>>>8&255,t[i+2]=e>>>16&255,t[i+3]=e>>>24}ue.create=le(),ue.alloc=function(e){return new ne.Array(e)},ne.Array!==Array&&(ue.alloc=ne.pool(ue.alloc,ne.Array.prototype.subarray)),ue.prototype._push=function(e,t,i){return this.tail=this.tail.next=new ae(e,t,i),this.len+=t,this},pe.prototype=Object.create(ae.prototype),pe.prototype.fn=function(e,t,i){for(;e>127;)t[i++]=127&e|128,e>>>=7;t[i]=e},ue.prototype.uint32=function(e){return this.len+=(this.tail=this.tail.next=new pe((e>>>=0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this},ue.prototype.int32=function(e){return e<0?this._push(me,10,re.fromNumber(e)):this.uint32(e)},ue.prototype.sint32=function(e){return this.uint32((e<<1^e>>31)>>>0)},ue.prototype.uint64=function(e){var t=re.from(e);return this._push(me,t.length(),t)},ue.prototype.int64=ue.prototype.uint64,ue.prototype.sint64=function(e){var t=re.from(e).zzEncode();return this._push(me,t.length(),t)},ue.prototype.bool=function(e){return this._push(he,1,e?1:0)},ue.prototype.fixed32=function(e){return this._push(fe,4,e>>>0)},ue.prototype.sfixed32=ue.prototype.fixed32,ue.prototype.fixed64=function(e){var t=re.from(e);return this._push(fe,4,t.lo)._push(fe,4,t.hi)},ue.prototype.sfixed64=ue.prototype.fixed64,ue.prototype.float=function(e){return this._push(ne.float.writeFloatLE,4,e)},ue.prototype.double=function(e){return this._push(ne.float.writeDoubleLE,8,e)};var ve=ne.Array.prototype.set?function(e,t,i){t.set(e,i)}:function(e,t,i){for(var n=0;n<e.length;++n)t[i+n]=e[n]};ue.prototype.bytes=function(e){var t=e.length>>>0;if(!t)return this._push(he,1,0);if(ne.isString(e)){var i=ue.alloc(t=se.length(e));se.decode(e,i,0),e=i}return this.uint32(t)._push(ve,t,e)},ue.prototype.string=function(e){var t=oe.length(e);return t?this.uint32(t)._push(oe.write,t,e):this._push(he,1,0)},ue.prototype.fork=function(){return this.states=new de(this),this.head=this.tail=new ae(ce,0,0),this.len=0,this},ue.prototype.reset=function(){return this.states?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new ae(ce,0,0),this.len=0),this},ue.prototype.ldelim=function(){var e=this.head,t=this.tail,i=this.len;return this.reset().uint32(i),i&&(this.tail.next=e.next,this.tail=t,this.len+=i),this},ue.prototype.finish=function(){for(var e=this.head.next,t=this.constructor.alloc(this.len),i=0;e;)e.fn(e.val,t,i),i+=e.len,e=e.next;return t},ue._configure=function(e){te=e,ue.create=le(),te._configure()};var ge=Se,be=ie;(Se.prototype=Object.create(be.prototype)).constructor=Se;var ke=ee();function Se(){be.call(this)}function ye(e,t,i){e.length<40?ke.utf8.write(e,t,i):t.utf8Write?t.utf8Write(e,i):t.write(e,i)}Se._configure=function(){Se.alloc=ke._Buffer_allocUnsafe,Se.writeBytesBuffer=ke.Buffer&&ke.Buffer.prototype instanceof Uint8Array&&"set"===ke.Buffer.prototype.set.name?function(e,t,i){t.set(e,i)}:function(e,t,i){if(e.copy)e.copy(t,i,0,e.length);else for(var n=0;n<e.length;)t[i++]=e[n++]}},Se.prototype.bytes=function(e){ke.isString(e)&&(e=ke._Buffer_from(e,"base64"));var t=e.length>>>0;return this.uint32(t),t&&this._push(Se.writeBytesBuffer,t,e),this},Se.prototype.string=function(e){var t=ke.Buffer.byteLength(e);return this.uint32(t),t&&this._push(ye,t,e),this},Se._configure();var Ce,Te=Ne,Ee=ee(),Pe=Ee.LongBits,we=Ee.utf8;function Re(e,t){return RangeError("index out of range: "+e.pos+" + "+(t||1)+" > "+e.len)}function Ne(e){this.buf=e,this.pos=0,this.len=e.length}var Oe,De="undefined"!=typeof Uint8Array?function(e){if(e instanceof Uint8Array||Array.isArray(e))return new Ne(e);throw Error("illegal buffer")}:function(e){if(Array.isArray(e))return new Ne(e);throw Error("illegal buffer")},Ie=function(){return Ee.Buffer?function(e){return(Ne.create=function(e){return Ee.Buffer.isBuffer(e)?new Ce(e):De(e)})(e)}:De};function Ae(){var e=new Pe(0,0),t=0;if(!(this.len-this.pos>4)){for(;t<3;++t){if(this.pos>=this.len)throw Re(this);if(e.lo=(e.lo|(127&this.buf[this.pos])<<7*t)>>>0,this.buf[this.pos++]<128)return e}return e.lo=(e.lo|(127&this.buf[this.pos++])<<7*t)>>>0,e}for(;t<4;++t)if(e.lo=(e.lo|(127&this.buf[this.pos])<<7*t)>>>0,this.buf[this.pos++]<128)return e;if(e.lo=(e.lo|(127&this.buf[this.pos])<<28)>>>0,e.hi=(e.hi|(127&this.buf[this.pos])>>4)>>>0,this.buf[this.pos++]<128)return e;if(t=0,this.len-this.pos>4){for(;t<5;++t)if(e.hi=(e.hi|(127&this.buf[this.pos])<<7*t+3)>>>0,this.buf[this.pos++]<128)return e}else for(;t<5;++t){if(this.pos>=this.len)throw Re(this);if(e.hi=(e.hi|(127&this.buf[this.pos])<<7*t+3)>>>0,this.buf[this.pos++]<128)return e}throw Error("invalid varint encoding")}function Ue(e,t){return(e[t-4]|e[t-3]<<8|e[t-2]<<16|e[t-1]<<24)>>>0}function Me(){if(this.pos+8>this.len)throw Re(this,8);return new Pe(Ue(this.buf,this.pos+=4),Ue(this.buf,this.pos+=4))}Ne.create=Ie(),Ne.prototype._slice=Ee.Array.prototype.subarray||Ee.Array.prototype.slice,Ne.prototype.uint32=(Oe=4294967295,function(){if(Oe=(127&this.buf[this.pos])>>>0,this.buf[this.pos++]<128)return Oe;if(Oe=(Oe|(127&this.buf[this.pos])<<7)>>>0,this.buf[this.pos++]<128)return Oe;if(Oe=(Oe|(127&this.buf[this.pos])<<14)>>>0,this.buf[this.pos++]<128)return Oe;if(Oe=(Oe|(127&this.buf[this.pos])<<21)>>>0,this.buf[this.pos++]<128)return Oe;if(Oe=(Oe|(15&this.buf[this.pos])<<28)>>>0,this.buf[this.pos++]<128)return Oe;if((this.pos+=5)>this.len)throw this.pos=this.len,Re(this,10);return Oe}),Ne.prototype.int32=function(){return 0|this.uint32()},Ne.prototype.sint32=function(){var e=this.uint32();return e>>>1^-(1&e)|0},Ne.prototype.bool=function(){return 0!==this.uint32()},Ne.prototype.fixed32=function(){if(this.pos+4>this.len)throw Re(this,4);return Ue(this.buf,this.pos+=4)},Ne.prototype.sfixed32=function(){if(this.pos+4>this.len)throw Re(this,4);return 0|Ue(this.buf,this.pos+=4)},Ne.prototype.float=function(){if(this.pos+4>this.len)throw Re(this,4);var e=Ee.float.readFloatLE(this.buf,this.pos);return this.pos+=4,e},Ne.prototype.double=function(){if(this.pos+8>this.len)throw Re(this,4);var e=Ee.float.readDoubleLE(this.buf,this.pos);return this.pos+=8,e},Ne.prototype.bytes=function(){var e=this.uint32(),t=this.pos,i=this.pos+e;if(i>this.len)throw Re(this,e);return this.pos+=e,Array.isArray(this.buf)?this.buf.slice(t,i):t===i?new this.buf.constructor(0):this._slice.call(this.buf,t,i)},Ne.prototype.string=function(){var e=this.bytes();return we.read(e,0,e.length)},Ne.prototype.skip=function(e){if("number"==typeof e){if(this.pos+e>this.len)throw Re(this,e);this.pos+=e}else do{if(this.pos>=this.len)throw Re(this)}while(128&this.buf[this.pos++]);return this},Ne.prototype.skipType=function(e){switch(e){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;4!=(e=7&this.uint32());)this.skipType(e);break;case 5:this.skip(4);break;default:throw Error("invalid wire type "+e+" at offset "+this.pos)}return this},Ne._configure=function(e){Ce=e,Ne.create=Ie(),Ce._configure();var t=Ee.Long?"toLong":"toNumber";Ee.merge(Ne.prototype,{int64:function(){return Ae.call(this)[t](!1)},uint64:function(){return Ae.call(this)[t](!0)},sint64:function(){return Ae.call(this).zzDecode()[t](!1)},fixed64:function(){return Me.call(this)[t](!0)},sfixed64:function(){return Me.call(this)[t](!1)}})};var Le=Be,_e=Te;(Be.prototype=Object.create(_e.prototype)).constructor=Be;var xe=ee();function Be(e){_e.call(this,e)}Be._configure=function(){xe.Buffer&&(Be.prototype._slice=xe.Buffer.prototype.slice)},Be.prototype.string=function(){var e=this.uint32();return this.buf.utf8Slice?this.buf.utf8Slice(this.pos,this.pos=Math.min(this.pos+e,this.len)):this.buf.toString("utf-8",this.pos,this.pos=Math.min(this.pos+e,this.len))},Be._configure();var Je={},Fe=je,$e=ee();function je(e,t,i){if("function"!=typeof e)throw TypeError("rpcImpl must be a function");$e.EventEmitter.call(this),this.rpcImpl=e,this.requestDelimited=Boolean(t),this.responseDelimited=Boolean(i)}(je.prototype=Object.create($e.EventEmitter.prototype)).constructor=je,je.prototype.rpcCall=function e(t,i,n,r,s){if(!r)throw TypeError("request must be specified");var o=this;if(!s)return $e.asPromise(e,o,t,i,n,r);if(o.rpcImpl)try{return o.rpcImpl(t,i[o.requestDelimited?"encodeDelimited":"encode"](r).finish(),(function(e,i){if(e)return o.emit("error",e,t),s(e);if(null!==i){if(!(i instanceof n))try{i=n[o.responseDelimited?"decodeDelimited":"decode"](i)}catch(e){return o.emit("error",e,t),s(e)}return o.emit("data",i,t),s(null,i)}o.end(!0)}))}catch(e){return o.emit("error",e,t),void setTimeout((function(){s(e)}),0)}else setTimeout((function(){s(Error("already ended"))}),0)},je.prototype.end=function(e){return this.rpcImpl&&(e||this.rpcImpl(null,null,null),this.rpcImpl=null,this.emit("end").off()),this},function(e){e.Service=Fe}(Je);var Ve={};!function(e){var t=e;function i(){t.util._configure(),t.Writer._configure(t.BufferWriter),t.Reader._configure(t.BufferReader)}t.build="minimal",t.Writer=ie,t.BufferWriter=ge,t.Reader=Te,t.BufferReader=Le,t.util=ee(),t.rpc=Je,t.roots=Ve,t.configure=i,i()}(x);var qe,We,Ge,Qe,He,Ke,Ze,ze,Ye,Xe,et,tt,it,nt,rt,st=n(x);function ot(e){switch(e){case 0:case"AUDIO":return Ge.AUDIO;case 1:case"VIDEO":return Ge.VIDEO;case 2:case"DATA":return Ge.DATA;default:return Ge.UNRECOGNIZED}}function at(e){switch(e){case Ge.AUDIO:return"AUDIO";case Ge.VIDEO:return"VIDEO";case Ge.DATA:return"DATA";case Ge.UNRECOGNIZED:default:return"UNRECOGNIZED"}}function ct(e){switch(e){case 0:case"UNKNOWN":return Qe.UNKNOWN;case 1:case"CAMERA":return Qe.CAMERA;case 2:case"MICROPHONE":return Qe.MICROPHONE;case 3:case"SCREEN_SHARE":return Qe.SCREEN_SHARE;case 4:case"SCREEN_SHARE_AUDIO":return Qe.SCREEN_SHARE_AUDIO;default:return Qe.UNRECOGNIZED}}function dt(e){switch(e){case Qe.UNKNOWN:return"UNKNOWN";case Qe.CAMERA:return"CAMERA";case Qe.MICROPHONE:return"MICROPHONE";case Qe.SCREEN_SHARE:return"SCREEN_SHARE";case Qe.SCREEN_SHARE_AUDIO:return"SCREEN_SHARE_AUDIO";case Qe.UNRECOGNIZED:default:return"UNRECOGNIZED"}}function ut(t){switch(t){case 0:case"LOW":return e.VideoQuality.LOW;case 1:case"MEDIUM":return e.VideoQuality.MEDIUM;case 2:case"HIGH":return e.VideoQuality.HIGH;case 3:case"OFF":return e.VideoQuality.OFF;default:return e.VideoQuality.UNRECOGNIZED}}function lt(t){switch(t){case e.VideoQuality.LOW:return"LOW";case e.VideoQuality.MEDIUM:return"MEDIUM";case e.VideoQuality.HIGH:return"HIGH";case e.VideoQuality.OFF:return"OFF";case e.VideoQuality.UNRECOGNIZED:default:return"UNRECOGNIZED"}}function ht(e){switch(e){case 0:case"POOR":return Ke.POOR;case 1:case"GOOD":return Ke.GOOD;case 2:case"EXCELLENT":return Ke.EXCELLENT;default:return Ke.UNRECOGNIZED}}function pt(e){switch(e){case 0:case"UNSET":return Ze.UNSET;case 1:case"DISABLED":return Ze.DISABLED;case 2:case"ENABLED":return Ze.ENABLED;default:return Ze.UNRECOGNIZED}}function mt(e){switch(e){case Ze.UNSET:return"UNSET";case Ze.DISABLED:return"DISABLED";case Ze.ENABLED:return"ENABLED";case Ze.UNRECOGNIZED:default:return"UNRECOGNIZED"}}function ft(t){switch(t){case 0:case"UNKNOWN_REASON":return e.DisconnectReason.UNKNOWN_REASON;case 1:case"CLIENT_INITIATED":return e.DisconnectReason.CLIENT_INITIATED;case 2:case"DUPLICATE_IDENTITY":return e.DisconnectReason.DUPLICATE_IDENTITY;case 3:case"SERVER_SHUTDOWN":return e.DisconnectReason.SERVER_SHUTDOWN;case 4:case"PARTICIPANT_REMOVED":return e.DisconnectReason.PARTICIPANT_REMOVED;case 5:case"ROOM_DELETED":return e.DisconnectReason.ROOM_DELETED;case 6:case"STATE_MISMATCH":return e.DisconnectReason.STATE_MISMATCH;case 7:case"JOIN_FAILURE":return e.DisconnectReason.JOIN_FAILURE;default:return e.DisconnectReason.UNRECOGNIZED}}function vt(e){switch(e){case 0:case"SE_UNKOWN":return Xe.SE_UNKOWN;case 1:case"SE_CODEC_UNSUPPORTED":return Xe.SE_CODEC_UNSUPPORTED;case 2:case"SE_TRACK_NOTFOUND":return Xe.SE_TRACK_NOTFOUND;default:return Xe.UNRECOGNIZED}}function gt(e){switch(e){case 0:case"JOINING":return et.JOINING;case 1:case"JOINED":return et.JOINED;case 2:case"ACTIVE":return et.ACTIVE;case 3:case"DISCONNECTED":return et.DISCONNECTED;default:return et.UNRECOGNIZED}}function bt(e){switch(e){case 0:case"NONE":return tt.NONE;case 1:case"GCM":return tt.GCM;case 2:case"CUSTOM":return tt.CUSTOM;default:return tt.UNRECOGNIZED}}function kt(e){switch(e){case tt.NONE:return"NONE";case tt.GCM:return"GCM";case tt.CUSTOM:return"CUSTOM";case tt.UNRECOGNIZED:default:return"UNRECOGNIZED"}}function St(t){switch(t){case 0:case"RELIABLE":return e.DataPacket_Kind.RELIABLE;case 1:case"LOSSY":return e.DataPacket_Kind.LOSSY;default:return e.DataPacket_Kind.UNRECOGNIZED}}function yt(e){switch(e){case 0:case"Standard":return nt.Standard;case 1:case"Cloud":return nt.Cloud;default:return nt.UNRECOGNIZED}}function Ct(e){switch(e){case 0:case"UNKNOWN":return rt.UNKNOWN;case 1:case"JS":return rt.JS;case 2:case"SWIFT":return rt.SWIFT;case 3:case"ANDROID":return rt.ANDROID;case 4:case"FLUTTER":return rt.FLUTTER;case 5:case"GO":return rt.GO;case 6:case"UNITY":return rt.UNITY;case 7:case"REACT_NATIVE":return rt.REACT_NATIVE;case 8:case"RUST":return rt.RUST;default:return rt.UNRECOGNIZED}}(()=>{if("undefined"!=typeof globalThis)return globalThis;if("undefined"!=typeof self)return self;if("undefined"!=typeof window)return window;if("undefined"!=typeof global)return global;throw"Unable to locate global object"})(),st.util.Long!==_&&(st.util.Long=_,st.configure()),function(e){e[e.DEFAULT_AC=0]="DEFAULT_AC",e[e.OPUS=1]="OPUS",e[e.AAC=2]="AAC",e[e.UNRECOGNIZED=-1]="UNRECOGNIZED"}(qe||(qe={})),function(e){e[e.DEFAULT_VC=0]="DEFAULT_VC",e[e.H264_BASELINE=1]="H264_BASELINE",e[e.H264_MAIN=2]="H264_MAIN",e[e.H264_HIGH=3]="H264_HIGH",e[e.VP8=4]="VP8",e[e.UNRECOGNIZED=-1]="UNRECOGNIZED"}(We||(We={})),function(e){e[e.AUDIO=0]="AUDIO",e[e.VIDEO=1]="VIDEO",e[e.DATA=2]="DATA",e[e.UNRECOGNIZED=-1]="UNRECOGNIZED"}(Ge||(Ge={})),function(e){e[e.UNKNOWN=0]="UNKNOWN",e[e.CAMERA=1]="CAMERA",e[e.MICROPHONE=2]="MICROPHONE",e[e.SCREEN_SHARE=3]="SCREEN_SHARE",e[e.SCREEN_SHARE_AUDIO=4]="SCREEN_SHARE_AUDIO",e[e.UNRECOGNIZED=-1]="UNRECOGNIZED"}(Qe||(Qe={})),e.VideoQuality=void 0,(He=e.VideoQuality||(e.VideoQuality={}))[He.LOW=0]="LOW",He[He.MEDIUM=1]="MEDIUM",He[He.HIGH=2]="HIGH",He[He.OFF=3]="OFF",He[He.UNRECOGNIZED=-1]="UNRECOGNIZED",function(e){e[e.POOR=0]="POOR",e[e.GOOD=1]="GOOD",e[e.EXCELLENT=2]="EXCELLENT",e[e.UNRECOGNIZED=-1]="UNRECOGNIZED"}(Ke||(Ke={})),function(e){e[e.UNSET=0]="UNSET",e[e.DISABLED=1]="DISABLED",e[e.ENABLED=2]="ENABLED",e[e.UNRECOGNIZED=-1]="UNRECOGNIZED"}(Ze||(Ze={})),e.DisconnectReason=void 0,(ze=e.DisconnectReason||(e.DisconnectReason={}))[ze.UNKNOWN_REASON=0]="UNKNOWN_REASON",ze[ze.CLIENT_INITIATED=1]="CLIENT_INITIATED",ze[ze.DUPLICATE_IDENTITY=2]="DUPLICATE_IDENTITY",ze[ze.SERVER_SHUTDOWN=3]="SERVER_SHUTDOWN",ze[ze.PARTICIPANT_REMOVED=4]="PARTICIPANT_REMOVED",ze[ze.ROOM_DELETED=5]="ROOM_DELETED",ze[ze.STATE_MISMATCH=6]="STATE_MISMATCH",ze[ze.JOIN_FAILURE=7]="JOIN_FAILURE",ze[ze.UNRECOGNIZED=-1]="UNRECOGNIZED",function(e){e[e.RR_UNKOWN=0]="RR_UNKOWN",e[e.RR_SIGNAL_DISCONNECTED=1]="RR_SIGNAL_DISCONNECTED",e[e.RR_PUBLISHER_FAILED=2]="RR_PUBLISHER_FAILED",e[e.RR_SUBSCRIBER_FAILED=3]="RR_SUBSCRIBER_FAILED",e[e.RR_SWITCH_CANDIDATE=4]="RR_SWITCH_CANDIDATE",e[e.UNRECOGNIZED=-1]="UNRECOGNIZED"}(Ye||(Ye={})),function(e){e[e.SE_UNKOWN=0]="SE_UNKOWN",e[e.SE_CODEC_UNSUPPORTED=1]="SE_CODEC_UNSUPPORTED",e[e.SE_TRACK_NOTFOUND=2]="SE_TRACK_NOTFOUND",e[e.UNRECOGNIZED=-1]="UNRECOGNIZED"}(Xe||(Xe={})),function(e){e[e.JOINING=0]="JOINING",e[e.JOINED=1]="JOINED",e[e.ACTIVE=2]="ACTIVE",e[e.DISCONNECTED=3]="DISCONNECTED",e[e.UNRECOGNIZED=-1]="UNRECOGNIZED"}(et||(et={})),function(e){e[e.NONE=0]="NONE",e[e.GCM=1]="GCM",e[e.CUSTOM=2]="CUSTOM",e[e.UNRECOGNIZED=-1]="UNRECOGNIZED"}(tt||(tt={})),e.DataPacket_Kind=void 0,(it=e.DataPacket_Kind||(e.DataPacket_Kind={}))[it.RELIABLE=0]="RELIABLE",it[it.LOSSY=1]="LOSSY",it[it.UNRECOGNIZED=-1]="UNRECOGNIZED",function(e){e[e.Standard=0]="Standard",e[e.Cloud=1]="Cloud",e[e.UNRECOGNIZED=-1]="UNRECOGNIZED"}(nt||(nt={})),function(e){e[e.UNKNOWN=0]="UNKNOWN",e[e.JS=1]="JS",e[e.SWIFT=2]="SWIFT",e[e.ANDROID=3]="ANDROID",e[e.FLUTTER=4]="FLUTTER",e[e.GO=5]="GO",e[e.UNITY=6]="UNITY",e[e.REACT_NATIVE=7]="REACT_NATIVE",e[e.RUST=8]="RUST",e[e.UNRECOGNIZED=-1]="UNRECOGNIZED"}(rt||(rt={}));const Tt={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:st.Writer.create();""!==e.sid&&t.uint32(10).string(e.sid),""!==e.name&&t.uint32(18).string(e.name),0!==e.emptyTimeout&&t.uint32(24).uint32(e.emptyTimeout),0!==e.maxParticipants&&t.uint32(32).uint32(e.maxParticipants),0!==e.creationTime&&t.uint32(40).int64(e.creationTime),""!==e.turnPassword&&t.uint32(50).string(e.turnPassword);for(const i of e.enabledCodecs)Et.encode(i,t.uint32(58).fork()).ldelim();return""!==e.metadata&&t.uint32(66).string(e.metadata),0!==e.numParticipants&&t.uint32(72).uint32(e.numParticipants),0!==e.numPublishers&&t.uint32(88).uint32(e.numPublishers),!0===e.activeRecording&&t.uint32(80).bool(e.activeRecording),t},decode(e,t){const i=e instanceof st.Reader?e:st.Reader.create(e);let n=void 0===t?i.len:i.pos+t;const r={sid:"",name:"",emptyTimeout:0,maxParticipants:0,creationTime:0,turnPassword:"",enabledCodecs:[],metadata:"",numParticipants:0,numPublishers:0,activeRecording:!1};for(;i.pos<n;){const e=i.uint32();switch(e>>>3){case 1:if(10!==e)break;r.sid=i.string();continue;case 2:if(18!==e)break;r.name=i.string();continue;case 3:if(24!==e)break;r.emptyTimeout=i.uint32();continue;case 4:if(32!==e)break;r.maxParticipants=i.uint32();continue;case 5:if(40!==e)break;r.creationTime=Vt(i.int64());continue;case 6:if(50!==e)break;r.turnPassword=i.string();continue;case 7:if(58!==e)break;r.enabledCodecs.push(Et.decode(i,i.uint32()));continue;case 8:if(66!==e)break;r.metadata=i.string();continue;case 9:if(72!==e)break;r.numParticipants=i.uint32();continue;case 11:if(88!==e)break;r.numPublishers=i.uint32();continue;case 10:if(80!==e)break;r.activeRecording=i.bool();continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return r},fromJSON:e=>({sid:qt(e.sid)?String(e.sid):"",name:qt(e.name)?String(e.name):"",emptyTimeout:qt(e.emptyTimeout)?Number(e.emptyTimeout):0,maxParticipants:qt(e.maxParticipants)?Number(e.maxParticipants):0,creationTime:qt(e.creationTime)?Number(e.creationTime):0,turnPassword:qt(e.turnPassword)?String(e.turnPassword):"",enabledCodecs:Array.isArray(null==e?void 0:e.enabledCodecs)?e.enabledCodecs.map((e=>Et.fromJSON(e))):[],metadata:qt(e.metadata)?String(e.metadata):"",numParticipants:qt(e.numParticipants)?Number(e.numParticipants):0,numPublishers:qt(e.numPublishers)?Number(e.numPublishers):0,activeRecording:!!qt(e.activeRecording)&&Boolean(e.activeRecording)}),toJSON(e){const t={};return void 0!==e.sid&&(t.sid=e.sid),void 0!==e.name&&(t.name=e.name),void 0!==e.emptyTimeout&&(t.emptyTimeout=Math.round(e.emptyTimeout)),void 0!==e.maxParticipants&&(t.maxParticipants=Math.round(e.maxParticipants)),void 0!==e.creationTime&&(t.creationTime=Math.round(e.creationTime)),void 0!==e.turnPassword&&(t.turnPassword=e.turnPassword),e.enabledCodecs?t.enabledCodecs=e.enabledCodecs.map((e=>e?Et.toJSON(e):void 0)):t.enabledCodecs=[],void 0!==e.metadata&&(t.metadata=e.metadata),void 0!==e.numParticipants&&(t.numParticipants=Math.round(e.numParticipants)),void 0!==e.numPublishers&&(t.numPublishers=Math.round(e.numPublishers)),void 0!==e.activeRecording&&(t.activeRecording=e.activeRecording),t},create:e=>Tt.fromPartial(null!=e?e:{}),fromPartial(e){var t,i,n,r,s,o,a,c,d,u,l;const h={sid:"",name:"",emptyTimeout:0,maxParticipants:0,creationTime:0,turnPassword:"",enabledCodecs:[],metadata:"",numParticipants:0,numPublishers:0,activeRecording:!1};return h.sid=null!==(t=e.sid)&&void 0!==t?t:"",h.name=null!==(i=e.name)&&void 0!==i?i:"",h.emptyTimeout=null!==(n=e.emptyTimeout)&&void 0!==n?n:0,h.maxParticipants=null!==(r=e.maxParticipants)&&void 0!==r?r:0,h.creationTime=null!==(s=e.creationTime)&&void 0!==s?s:0,h.turnPassword=null!==(o=e.turnPassword)&&void 0!==o?o:"",h.enabledCodecs=(null===(a=e.enabledCodecs)||void 0===a?void 0:a.map((e=>Et.fromPartial(e))))||[],h.metadata=null!==(c=e.metadata)&&void 0!==c?c:"",h.numParticipants=null!==(d=e.numParticipants)&&void 0!==d?d:0,h.numPublishers=null!==(u=e.numPublishers)&&void 0!==u?u:0,h.activeRecording=null!==(l=e.activeRecording)&&void 0!==l&&l,h}};const Et={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:st.Writer.create();return""!==e.mime&&t.uint32(10).string(e.mime),""!==e.fmtpLine&&t.uint32(18).string(e.fmtpLine),t},decode(e,t){const i=e instanceof st.Reader?e:st.Reader.create(e);let n=void 0===t?i.len:i.pos+t;const r={mime:"",fmtpLine:""};for(;i.pos<n;){const e=i.uint32();switch(e>>>3){case 1:if(10!==e)break;r.mime=i.string();continue;case 2:if(18!==e)break;r.fmtpLine=i.string();continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return r},fromJSON:e=>({mime:qt(e.mime)?String(e.mime):"",fmtpLine:qt(e.fmtpLine)?String(e.fmtpLine):""}),toJSON(e){const t={};return void 0!==e.mime&&(t.mime=e.mime),void 0!==e.fmtpLine&&(t.fmtpLine=e.fmtpLine),t},create:e=>Et.fromPartial(null!=e?e:{}),fromPartial(e){var t,i;const n={mime:"",fmtpLine:""};return n.mime=null!==(t=e.mime)&&void 0!==t?t:"",n.fmtpLine=null!==(i=e.fmtpLine)&&void 0!==i?i:"",n}};const Pt={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:st.Writer.create();!0===e.canSubscribe&&t.uint32(8).bool(e.canSubscribe),!0===e.canPublish&&t.uint32(16).bool(e.canPublish),!0===e.canPublishData&&t.uint32(24).bool(e.canPublishData),t.uint32(74).fork();for(const i of e.canPublishSources)t.int32(i);return t.ldelim(),!0===e.hidden&&t.uint32(56).bool(e.hidden),!0===e.recorder&&t.uint32(64).bool(e.recorder),!0===e.canUpdateMetadata&&t.uint32(80).bool(e.canUpdateMetadata),t},decode(e,t){const i=e instanceof st.Reader?e:st.Reader.create(e);let n=void 0===t?i.len:i.pos+t;const r={canSubscribe:!1,canPublish:!1,canPublishData:!1,canPublishSources:[],hidden:!1,recorder:!1,canUpdateMetadata:!1};for(;i.pos<n;){const e=i.uint32();switch(e>>>3){case 1:if(8!==e)break;r.canSubscribe=i.bool();continue;case 2:if(16!==e)break;r.canPublish=i.bool();continue;case 3:if(24!==e)break;r.canPublishData=i.bool();continue;case 9:if(72===e){r.canPublishSources.push(i.int32());continue}if(74===e){const e=i.uint32()+i.pos;for(;i.pos<e;)r.canPublishSources.push(i.int32());continue}break;case 7:if(56!==e)break;r.hidden=i.bool();continue;case 8:if(64!==e)break;r.recorder=i.bool();continue;case 10:if(80!==e)break;r.canUpdateMetadata=i.bool();continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return r},fromJSON:e=>({canSubscribe:!!qt(e.canSubscribe)&&Boolean(e.canSubscribe),canPublish:!!qt(e.canPublish)&&Boolean(e.canPublish),canPublishData:!!qt(e.canPublishData)&&Boolean(e.canPublishData),canPublishSources:Array.isArray(null==e?void 0:e.canPublishSources)?e.canPublishSources.map((e=>ct(e))):[],hidden:!!qt(e.hidden)&&Boolean(e.hidden),recorder:!!qt(e.recorder)&&Boolean(e.recorder),canUpdateMetadata:!!qt(e.canUpdateMetadata)&&Boolean(e.canUpdateMetadata)}),toJSON(e){const t={};return void 0!==e.canSubscribe&&(t.canSubscribe=e.canSubscribe),void 0!==e.canPublish&&(t.canPublish=e.canPublish),void 0!==e.canPublishData&&(t.canPublishData=e.canPublishData),e.canPublishSources?t.canPublishSources=e.canPublishSources.map((e=>dt(e))):t.canPublishSources=[],void 0!==e.hidden&&(t.hidden=e.hidden),void 0!==e.recorder&&(t.recorder=e.recorder),void 0!==e.canUpdateMetadata&&(t.canUpdateMetadata=e.canUpdateMetadata),t},create:e=>Pt.fromPartial(null!=e?e:{}),fromPartial(e){var t,i,n,r,s,o,a;const c={canSubscribe:!1,canPublish:!1,canPublishData:!1,canPublishSources:[],hidden:!1,recorder:!1,canUpdateMetadata:!1};return c.canSubscribe=null!==(t=e.canSubscribe)&&void 0!==t&&t,c.canPublish=null!==(i=e.canPublish)&&void 0!==i&&i,c.canPublishData=null!==(n=e.canPublishData)&&void 0!==n&&n,c.canPublishSources=(null===(r=e.canPublishSources)||void 0===r?void 0:r.map((e=>e)))||[],c.hidden=null!==(s=e.hidden)&&void 0!==s&&s,c.recorder=null!==(o=e.recorder)&&void 0!==o&&o,c.canUpdateMetadata=null!==(a=e.canUpdateMetadata)&&void 0!==a&&a,c}};const wt={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:st.Writer.create();""!==e.sid&&t.uint32(10).string(e.sid),""!==e.identity&&t.uint32(18).string(e.identity),0!==e.state&&t.uint32(24).int32(e.state);for(const i of e.tracks)Nt.encode(i,t.uint32(34).fork()).ldelim();return""!==e.metadata&&t.uint32(42).string(e.metadata),0!==e.joinedAt&&t.uint32(48).int64(e.joinedAt),""!==e.name&&t.uint32(74).string(e.name),0!==e.version&&t.uint32(80).uint32(e.version),void 0!==e.permission&&Pt.encode(e.permission,t.uint32(90).fork()).ldelim(),""!==e.region&&t.uint32(98).string(e.region),!0===e.isPublisher&&t.uint32(104).bool(e.isPublisher),t},decode(e,t){const i=e instanceof st.Reader?e:st.Reader.create(e);let n=void 0===t?i.len:i.pos+t;const r={sid:"",identity:"",state:0,tracks:[],metadata:"",joinedAt:0,name:"",version:0,permission:void 0,region:"",isPublisher:!1};for(;i.pos<n;){const e=i.uint32();switch(e>>>3){case 1:if(10!==e)break;r.sid=i.string();continue;case 2:if(18!==e)break;r.identity=i.string();continue;case 3:if(24!==e)break;r.state=i.int32();continue;case 4:if(34!==e)break;r.tracks.push(Nt.decode(i,i.uint32()));continue;case 5:if(42!==e)break;r.metadata=i.string();continue;case 6:if(48!==e)break;r.joinedAt=Vt(i.int64());continue;case 9:if(74!==e)break;r.name=i.string();continue;case 10:if(80!==e)break;r.version=i.uint32();continue;case 11:if(90!==e)break;r.permission=Pt.decode(i,i.uint32());continue;case 12:if(98!==e)break;r.region=i.string();continue;case 13:if(104!==e)break;r.isPublisher=i.bool();continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return r},fromJSON:e=>({sid:qt(e.sid)?String(e.sid):"",identity:qt(e.identity)?String(e.identity):"",state:qt(e.state)?gt(e.state):0,tracks:Array.isArray(null==e?void 0:e.tracks)?e.tracks.map((e=>Nt.fromJSON(e))):[],metadata:qt(e.metadata)?String(e.metadata):"",joinedAt:qt(e.joinedAt)?Number(e.joinedAt):0,name:qt(e.name)?String(e.name):"",version:qt(e.version)?Number(e.version):0,permission:qt(e.permission)?Pt.fromJSON(e.permission):void 0,region:qt(e.region)?String(e.region):"",isPublisher:!!qt(e.isPublisher)&&Boolean(e.isPublisher)}),toJSON(e){const t={};return void 0!==e.sid&&(t.sid=e.sid),void 0!==e.identity&&(t.identity=e.identity),void 0!==e.state&&(t.state=function(e){switch(e){case et.JOINING:return"JOINING";case et.JOINED:return"JOINED";case et.ACTIVE:return"ACTIVE";case et.DISCONNECTED:return"DISCONNECTED";case et.UNRECOGNIZED:default:return"UNRECOGNIZED"}}(e.state)),e.tracks?t.tracks=e.tracks.map((e=>e?Nt.toJSON(e):void 0)):t.tracks=[],void 0!==e.metadata&&(t.metadata=e.metadata),void 0!==e.joinedAt&&(t.joinedAt=Math.round(e.joinedAt)),void 0!==e.name&&(t.name=e.name),void 0!==e.version&&(t.version=Math.round(e.version)),void 0!==e.permission&&(t.permission=e.permission?Pt.toJSON(e.permission):void 0),void 0!==e.region&&(t.region=e.region),void 0!==e.isPublisher&&(t.isPublisher=e.isPublisher),t},create:e=>wt.fromPartial(null!=e?e:{}),fromPartial(e){var t,i,n,r,s,o,a,c,d,u;const l={sid:"",identity:"",state:0,tracks:[],metadata:"",joinedAt:0,name:"",version:0,permission:void 0,region:"",isPublisher:!1};return l.sid=null!==(t=e.sid)&&void 0!==t?t:"",l.identity=null!==(i=e.identity)&&void 0!==i?i:"",l.state=null!==(n=e.state)&&void 0!==n?n:0,l.tracks=(null===(r=e.tracks)||void 0===r?void 0:r.map((e=>Nt.fromPartial(e))))||[],l.metadata=null!==(s=e.metadata)&&void 0!==s?s:"",l.joinedAt=null!==(o=e.joinedAt)&&void 0!==o?o:0,l.name=null!==(a=e.name)&&void 0!==a?a:"",l.version=null!==(c=e.version)&&void 0!==c?c:0,l.permission=void 0!==e.permission&&null!==e.permission?Pt.fromPartial(e.permission):void 0,l.region=null!==(d=e.region)&&void 0!==d?d:"",l.isPublisher=null!==(u=e.isPublisher)&&void 0!==u&&u,l}};const Rt={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:st.Writer.create();""!==e.mimeType&&t.uint32(10).string(e.mimeType),""!==e.mid&&t.uint32(18).string(e.mid),""!==e.cid&&t.uint32(26).string(e.cid);for(const i of e.layers)Ot.encode(i,t.uint32(34).fork()).ldelim();return t},decode(e,t){const i=e instanceof st.Reader?e:st.Reader.create(e);let n=void 0===t?i.len:i.pos+t;const r={mimeType:"",mid:"",cid:"",layers:[]};for(;i.pos<n;){const e=i.uint32();switch(e>>>3){case 1:if(10!==e)break;r.mimeType=i.string();continue;case 2:if(18!==e)break;r.mid=i.string();continue;case 3:if(26!==e)break;r.cid=i.string();continue;case 4:if(34!==e)break;r.layers.push(Ot.decode(i,i.uint32()));continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return r},fromJSON:e=>({mimeType:qt(e.mimeType)?String(e.mimeType):"",mid:qt(e.mid)?String(e.mid):"",cid:qt(e.cid)?String(e.cid):"",layers:Array.isArray(null==e?void 0:e.layers)?e.layers.map((e=>Ot.fromJSON(e))):[]}),toJSON(e){const t={};return void 0!==e.mimeType&&(t.mimeType=e.mimeType),void 0!==e.mid&&(t.mid=e.mid),void 0!==e.cid&&(t.cid=e.cid),e.layers?t.layers=e.layers.map((e=>e?Ot.toJSON(e):void 0)):t.layers=[],t},create:e=>Rt.fromPartial(null!=e?e:{}),fromPartial(e){var t,i,n,r;const s={mimeType:"",mid:"",cid:"",layers:[]};return s.mimeType=null!==(t=e.mimeType)&&void 0!==t?t:"",s.mid=null!==(i=e.mid)&&void 0!==i?i:"",s.cid=null!==(n=e.cid)&&void 0!==n?n:"",s.layers=(null===(r=e.layers)||void 0===r?void 0:r.map((e=>Ot.fromPartial(e))))||[],s}};const Nt={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:st.Writer.create();""!==e.sid&&t.uint32(10).string(e.sid),0!==e.type&&t.uint32(16).int32(e.type),""!==e.name&&t.uint32(26).string(e.name),!0===e.muted&&t.uint32(32).bool(e.muted),0!==e.width&&t.uint32(40).uint32(e.width),0!==e.height&&t.uint32(48).uint32(e.height),!0===e.simulcast&&t.uint32(56).bool(e.simulcast),!0===e.disableDtx&&t.uint32(64).bool(e.disableDtx),0!==e.source&&t.uint32(72).int32(e.source);for(const i of e.layers)Ot.encode(i,t.uint32(82).fork()).ldelim();""!==e.mimeType&&t.uint32(90).string(e.mimeType),""!==e.mid&&t.uint32(98).string(e.mid);for(const i of e.codecs)Rt.encode(i,t.uint32(106).fork()).ldelim();return!0===e.stereo&&t.uint32(112).bool(e.stereo),!0===e.disableRed&&t.uint32(120).bool(e.disableRed),0!==e.encryption&&t.uint32(128).int32(e.encryption),t},decode(e,t){const i=e instanceof st.Reader?e:st.Reader.create(e);let n=void 0===t?i.len:i.pos+t;const r={sid:"",type:0,name:"",muted:!1,width:0,height:0,simulcast:!1,disableDtx:!1,source:0,layers:[],mimeType:"",mid:"",codecs:[],stereo:!1,disableRed:!1,encryption:0};for(;i.pos<n;){const e=i.uint32();switch(e>>>3){case 1:if(10!==e)break;r.sid=i.string();continue;case 2:if(16!==e)break;r.type=i.int32();continue;case 3:if(26!==e)break;r.name=i.string();continue;case 4:if(32!==e)break;r.muted=i.bool();continue;case 5:if(40!==e)break;r.width=i.uint32();continue;case 6:if(48!==e)break;r.height=i.uint32();continue;case 7:if(56!==e)break;r.simulcast=i.bool();continue;case 8:if(64!==e)break;r.disableDtx=i.bool();continue;case 9:if(72!==e)break;r.source=i.int32();continue;case 10:if(82!==e)break;r.layers.push(Ot.decode(i,i.uint32()));continue;case 11:if(90!==e)break;r.mimeType=i.string();continue;case 12:if(98!==e)break;r.mid=i.string();continue;case 13:if(106!==e)break;r.codecs.push(Rt.decode(i,i.uint32()));continue;case 14:if(112!==e)break;r.stereo=i.bool();continue;case 15:if(120!==e)break;r.disableRed=i.bool();continue;case 16:if(128!==e)break;r.encryption=i.int32();continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return r},fromJSON:e=>({sid:qt(e.sid)?String(e.sid):"",type:qt(e.type)?ot(e.type):0,name:qt(e.name)?String(e.name):"",muted:!!qt(e.muted)&&Boolean(e.muted),width:qt(e.width)?Number(e.width):0,height:qt(e.height)?Number(e.height):0,simulcast:!!qt(e.simulcast)&&Boolean(e.simulcast),disableDtx:!!qt(e.disableDtx)&&Boolean(e.disableDtx),source:qt(e.source)?ct(e.source):0,layers:Array.isArray(null==e?void 0:e.layers)?e.layers.map((e=>Ot.fromJSON(e))):[],mimeType:qt(e.mimeType)?String(e.mimeType):"",mid:qt(e.mid)?String(e.mid):"",codecs:Array.isArray(null==e?void 0:e.codecs)?e.codecs.map((e=>Rt.fromJSON(e))):[],stereo:!!qt(e.stereo)&&Boolean(e.stereo),disableRed:!!qt(e.disableRed)&&Boolean(e.disableRed),encryption:qt(e.encryption)?bt(e.encryption):0}),toJSON(e){const t={};return void 0!==e.sid&&(t.sid=e.sid),void 0!==e.type&&(t.type=at(e.type)),void 0!==e.name&&(t.name=e.name),void 0!==e.muted&&(t.muted=e.muted),void 0!==e.width&&(t.width=Math.round(e.width)),void 0!==e.height&&(t.height=Math.round(e.height)),void 0!==e.simulcast&&(t.simulcast=e.simulcast),void 0!==e.disableDtx&&(t.disableDtx=e.disableDtx),void 0!==e.source&&(t.source=dt(e.source)),e.layers?t.layers=e.layers.map((e=>e?Ot.toJSON(e):void 0)):t.layers=[],void 0!==e.mimeType&&(t.mimeType=e.mimeType),void 0!==e.mid&&(t.mid=e.mid),e.codecs?t.codecs=e.codecs.map((e=>e?Rt.toJSON(e):void 0)):t.codecs=[],void 0!==e.stereo&&(t.stereo=e.stereo),void 0!==e.disableRed&&(t.disableRed=e.disableRed),void 0!==e.encryption&&(t.encryption=kt(e.encryption)),t},create:e=>Nt.fromPartial(null!=e?e:{}),fromPartial(e){var t,i,n,r,s,o,a,c,d,u,l,h,p,m,f,v;const g={sid:"",type:0,name:"",muted:!1,width:0,height:0,simulcast:!1,disableDtx:!1,source:0,layers:[],mimeType:"",mid:"",codecs:[],stereo:!1,disableRed:!1,encryption:0};return g.sid=null!==(t=e.sid)&&void 0!==t?t:"",g.type=null!==(i=e.type)&&void 0!==i?i:0,g.name=null!==(n=e.name)&&void 0!==n?n:"",g.muted=null!==(r=e.muted)&&void 0!==r&&r,g.width=null!==(s=e.width)&&void 0!==s?s:0,g.height=null!==(o=e.height)&&void 0!==o?o:0,g.simulcast=null!==(a=e.simulcast)&&void 0!==a&&a,g.disableDtx=null!==(c=e.disableDtx)&&void 0!==c&&c,g.source=null!==(d=e.source)&&void 0!==d?d:0,g.layers=(null===(u=e.layers)||void 0===u?void 0:u.map((e=>Ot.fromPartial(e))))||[],g.mimeType=null!==(l=e.mimeType)&&void 0!==l?l:"",g.mid=null!==(h=e.mid)&&void 0!==h?h:"",g.codecs=(null===(p=e.codecs)||void 0===p?void 0:p.map((e=>Rt.fromPartial(e))))||[],g.stereo=null!==(m=e.stereo)&&void 0!==m&&m,g.disableRed=null!==(f=e.disableRed)&&void 0!==f&&f,g.encryption=null!==(v=e.encryption)&&void 0!==v?v:0,g}};const Ot={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:st.Writer.create();return 0!==e.quality&&t.uint32(8).int32(e.quality),0!==e.width&&t.uint32(16).uint32(e.width),0!==e.height&&t.uint32(24).uint32(e.height),0!==e.bitrate&&t.uint32(32).uint32(e.bitrate),0!==e.ssrc&&t.uint32(40).uint32(e.ssrc),t},decode(e,t){const i=e instanceof st.Reader?e:st.Reader.create(e);let n=void 0===t?i.len:i.pos+t;const r={quality:0,width:0,height:0,bitrate:0,ssrc:0};for(;i.pos<n;){const e=i.uint32();switch(e>>>3){case 1:if(8!==e)break;r.quality=i.int32();continue;case 2:if(16!==e)break;r.width=i.uint32();continue;case 3:if(24!==e)break;r.height=i.uint32();continue;case 4:if(32!==e)break;r.bitrate=i.uint32();continue;case 5:if(40!==e)break;r.ssrc=i.uint32();continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return r},fromJSON:e=>({quality:qt(e.quality)?ut(e.quality):0,width:qt(e.width)?Number(e.width):0,height:qt(e.height)?Number(e.height):0,bitrate:qt(e.bitrate)?Number(e.bitrate):0,ssrc:qt(e.ssrc)?Number(e.ssrc):0}),toJSON(e){const t={};return void 0!==e.quality&&(t.quality=lt(e.quality)),void 0!==e.width&&(t.width=Math.round(e.width)),void 0!==e.height&&(t.height=Math.round(e.height)),void 0!==e.bitrate&&(t.bitrate=Math.round(e.bitrate)),void 0!==e.ssrc&&(t.ssrc=Math.round(e.ssrc)),t},create:e=>Ot.fromPartial(null!=e?e:{}),fromPartial(e){var t,i,n,r,s;const o={quality:0,width:0,height:0,bitrate:0,ssrc:0};return o.quality=null!==(t=e.quality)&&void 0!==t?t:0,o.width=null!==(i=e.width)&&void 0!==i?i:0,o.height=null!==(n=e.height)&&void 0!==n?n:0,o.bitrate=null!==(r=e.bitrate)&&void 0!==r?r:0,o.ssrc=null!==(s=e.ssrc)&&void 0!==s?s:0,o}};const Dt={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:st.Writer.create();var i;switch(0!==e.kind&&t.uint32(8).int32(e.kind),null===(i=e.value)||void 0===i?void 0:i.$case){case"user":Mt.encode(e.value.user,t.uint32(18).fork()).ldelim();break;case"speaker":It.encode(e.value.speaker,t.uint32(26).fork()).ldelim()}return t},decode(e,t){const i=e instanceof st.Reader?e:st.Reader.create(e);let n=void 0===t?i.len:i.pos+t;const r={kind:0,value:void 0};for(;i.pos<n;){const e=i.uint32();switch(e>>>3){case 1:if(8!==e)break;r.kind=i.int32();continue;case 2:if(18!==e)break;r.value={$case:"user",user:Mt.decode(i,i.uint32())};continue;case 3:if(26!==e)break;r.value={$case:"speaker",speaker:It.decode(i,i.uint32())};continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return r},fromJSON:e=>({kind:qt(e.kind)?St(e.kind):0,value:qt(e.user)?{$case:"user",user:Mt.fromJSON(e.user)}:qt(e.speaker)?{$case:"speaker",speaker:It.fromJSON(e.speaker)}:void 0}),toJSON(t){var i,n,r,s,o,a;const c={};return void 0!==t.kind&&(c.kind=function(t){switch(t){case e.DataPacket_Kind.RELIABLE:return"RELIABLE";case e.DataPacket_Kind.LOSSY:return"LOSSY";case e.DataPacket_Kind.UNRECOGNIZED:default:return"UNRECOGNIZED"}}(t.kind)),"user"===(null===(i=t.value)||void 0===i?void 0:i.$case)&&(c.user=(null===(n=t.value)||void 0===n?void 0:n.user)?Mt.toJSON(null===(r=t.value)||void 0===r?void 0:r.user):void 0),"speaker"===(null===(s=t.value)||void 0===s?void 0:s.$case)&&(c.speaker=(null===(o=t.value)||void 0===o?void 0:o.speaker)?It.toJSON(null===(a=t.value)||void 0===a?void 0:a.speaker):void 0),c},create:e=>Dt.fromPartial(null!=e?e:{}),fromPartial(e){var t,i,n,r,s,o,a;const c={kind:0,value:void 0};return c.kind=null!==(t=e.kind)&&void 0!==t?t:0,"user"===(null===(i=e.value)||void 0===i?void 0:i.$case)&&void 0!==(null===(n=e.value)||void 0===n?void 0:n.user)&&null!==(null===(r=e.value)||void 0===r?void 0:r.user)&&(c.value={$case:"user",user:Mt.fromPartial(e.value.user)}),"speaker"===(null===(s=e.value)||void 0===s?void 0:s.$case)&&void 0!==(null===(o=e.value)||void 0===o?void 0:o.speaker)&&null!==(null===(a=e.value)||void 0===a?void 0:a.speaker)&&(c.value={$case:"speaker",speaker:It.fromPartial(e.value.speaker)}),c}};const It={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:st.Writer.create();for(const i of e.speakers)At.encode(i,t.uint32(10).fork()).ldelim();return t},decode(e,t){const i=e instanceof st.Reader?e:st.Reader.create(e);let n=void 0===t?i.len:i.pos+t;const r={speakers:[]};for(;i.pos<n;){const e=i.uint32();switch(e>>>3){case 1:if(10!==e)break;r.speakers.push(At.decode(i,i.uint32()));continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return r},fromJSON:e=>({speakers:Array.isArray(null==e?void 0:e.speakers)?e.speakers.map((e=>At.fromJSON(e))):[]}),toJSON(e){const t={};return e.speakers?t.speakers=e.speakers.map((e=>e?At.toJSON(e):void 0)):t.speakers=[],t},create:e=>It.fromPartial(null!=e?e:{}),fromPartial(e){var t;const i={speakers:[]};return i.speakers=(null===(t=e.speakers)||void 0===t?void 0:t.map((e=>At.fromPartial(e))))||[],i}};const At={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:st.Writer.create();return""!==e.sid&&t.uint32(10).string(e.sid),0!==e.level&&t.uint32(21).float(e.level),!0===e.active&&t.uint32(24).bool(e.active),t},decode(e,t){const i=e instanceof st.Reader?e:st.Reader.create(e);let n=void 0===t?i.len:i.pos+t;const r={sid:"",level:0,active:!1};for(;i.pos<n;){const e=i.uint32();switch(e>>>3){case 1:if(10!==e)break;r.sid=i.string();continue;case 2:if(21!==e)break;r.level=i.float();continue;case 3:if(24!==e)break;r.active=i.bool();continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return r},fromJSON:e=>({sid:qt(e.sid)?String(e.sid):"",level:qt(e.level)?Number(e.level):0,active:!!qt(e.active)&&Boolean(e.active)}),toJSON(e){const t={};return void 0!==e.sid&&(t.sid=e.sid),void 0!==e.level&&(t.level=e.level),void 0!==e.active&&(t.active=e.active),t},create:e=>At.fromPartial(null!=e?e:{}),fromPartial(e){var t,i,n;const r={sid:"",level:0,active:!1};return r.sid=null!==(t=e.sid)&&void 0!==t?t:"",r.level=null!==(i=e.level)&&void 0!==i?i:0,r.active=null!==(n=e.active)&&void 0!==n&&n,r}};function Ut(){return{participantSid:"",payload:new Uint8Array,destinationSids:[],topic:void 0}}const Mt={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:st.Writer.create();""!==e.participantSid&&t.uint32(10).string(e.participantSid),0!==e.payload.length&&t.uint32(18).bytes(e.payload);for(const i of e.destinationSids)t.uint32(26).string(i);return void 0!==e.topic&&t.uint32(34).string(e.topic),t},decode(e,t){const i=e instanceof st.Reader?e:st.Reader.create(e);let n=void 0===t?i.len:i.pos+t;const r=Ut();for(;i.pos<n;){const e=i.uint32();switch(e>>>3){case 1:if(10!==e)break;r.participantSid=i.string();continue;case 2:if(18!==e)break;r.payload=i.bytes();continue;case 3:if(26!==e)break;r.destinationSids.push(i.string());continue;case 4:if(34!==e)break;r.topic=i.string();continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return r},fromJSON:e=>({participantSid:qt(e.participantSid)?String(e.participantSid):"",payload:qt(e.payload)?jt(e.payload):new Uint8Array,destinationSids:Array.isArray(null==e?void 0:e.destinationSids)?e.destinationSids.map((e=>String(e))):[],topic:qt(e.topic)?String(e.topic):void 0}),toJSON(e){const t={};return void 0!==e.participantSid&&(t.participantSid=e.participantSid),void 0!==e.payload&&(t.payload=function(e){if($t.Buffer)return $t.Buffer.from(e).toString("base64");{const t=[];return e.forEach((e=>{t.push(String.fromCharCode(e))})),$t.btoa(t.join(""))}}(void 0!==e.payload?e.payload:new Uint8Array)),e.destinationSids?t.destinationSids=e.destinationSids.map((e=>e)):t.destinationSids=[],void 0!==e.topic&&(t.topic=e.topic),t},create:e=>Mt.fromPartial(null!=e?e:{}),fromPartial(e){var t,i,n,r;const s=Ut();return s.participantSid=null!==(t=e.participantSid)&&void 0!==t?t:"",s.payload=null!==(i=e.payload)&&void 0!==i?i:new Uint8Array,s.destinationSids=(null===(n=e.destinationSids)||void 0===n?void 0:n.map((e=>e)))||[],s.topic=null!==(r=e.topic)&&void 0!==r?r:void 0,s}};const Lt={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:st.Writer.create();""!==e.participantSid&&t.uint32(10).string(e.participantSid);for(const i of e.trackSids)t.uint32(18).string(i);return t},decode(e,t){const i=e instanceof st.Reader?e:st.Reader.create(e);let n=void 0===t?i.len:i.pos+t;const r={participantSid:"",trackSids:[]};for(;i.pos<n;){const e=i.uint32();switch(e>>>3){case 1:if(10!==e)break;r.participantSid=i.string();continue;case 2:if(18!==e)break;r.trackSids.push(i.string());continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return r},fromJSON:e=>({participantSid:qt(e.participantSid)?String(e.participantSid):"",trackSids:Array.isArray(null==e?void 0:e.trackSids)?e.trackSids.map((e=>String(e))):[]}),toJSON(e){const t={};return void 0!==e.participantSid&&(t.participantSid=e.participantSid),e.trackSids?t.trackSids=e.trackSids.map((e=>e)):t.trackSids=[],t},create:e=>Lt.fromPartial(null!=e?e:{}),fromPartial(e){var t,i;const n={participantSid:"",trackSids:[]};return n.participantSid=null!==(t=e.participantSid)&&void 0!==t?t:"",n.trackSids=(null===(i=e.trackSids)||void 0===i?void 0:i.map((e=>e)))||[],n}};const _t={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:st.Writer.create();return 0!==e.edition&&t.uint32(8).int32(e.edition),""!==e.version&&t.uint32(18).string(e.version),0!==e.protocol&&t.uint32(24).int32(e.protocol),""!==e.region&&t.uint32(34).string(e.region),""!==e.nodeId&&t.uint32(42).string(e.nodeId),""!==e.debugInfo&&t.uint32(50).string(e.debugInfo),t},decode(e,t){const i=e instanceof st.Reader?e:st.Reader.create(e);let n=void 0===t?i.len:i.pos+t;const r={edition:0,version:"",protocol:0,region:"",nodeId:"",debugInfo:""};for(;i.pos<n;){const e=i.uint32();switch(e>>>3){case 1:if(8!==e)break;r.edition=i.int32();continue;case 2:if(18!==e)break;r.version=i.string();continue;case 3:if(24!==e)break;r.protocol=i.int32();continue;case 4:if(34!==e)break;r.region=i.string();continue;case 5:if(42!==e)break;r.nodeId=i.string();continue;case 6:if(50!==e)break;r.debugInfo=i.string();continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return r},fromJSON:e=>({edition:qt(e.edition)?yt(e.edition):0,version:qt(e.version)?String(e.version):"",protocol:qt(e.protocol)?Number(e.protocol):0,region:qt(e.region)?String(e.region):"",nodeId:qt(e.nodeId)?String(e.nodeId):"",debugInfo:qt(e.debugInfo)?String(e.debugInfo):""}),toJSON(e){const t={};return void 0!==e.edition&&(t.edition=function(e){switch(e){case nt.Standard:return"Standard";case nt.Cloud:return"Cloud";case nt.UNRECOGNIZED:default:return"UNRECOGNIZED"}}(e.edition)),void 0!==e.version&&(t.version=e.version),void 0!==e.protocol&&(t.protocol=Math.round(e.protocol)),void 0!==e.region&&(t.region=e.region),void 0!==e.nodeId&&(t.nodeId=e.nodeId),void 0!==e.debugInfo&&(t.debugInfo=e.debugInfo),t},create:e=>_t.fromPartial(null!=e?e:{}),fromPartial(e){var t,i,n,r,s,o;const a={edition:0,version:"",protocol:0,region:"",nodeId:"",debugInfo:""};return a.edition=null!==(t=e.edition)&&void 0!==t?t:0,a.version=null!==(i=e.version)&&void 0!==i?i:"",a.protocol=null!==(n=e.protocol)&&void 0!==n?n:0,a.region=null!==(r=e.region)&&void 0!==r?r:"",a.nodeId=null!==(s=e.nodeId)&&void 0!==s?s:"",a.debugInfo=null!==(o=e.debugInfo)&&void 0!==o?o:"",a}};const xt={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:st.Writer.create();return 0!==e.sdk&&t.uint32(8).int32(e.sdk),""!==e.version&&t.uint32(18).string(e.version),0!==e.protocol&&t.uint32(24).int32(e.protocol),""!==e.os&&t.uint32(34).string(e.os),""!==e.osVersion&&t.uint32(42).string(e.osVersion),""!==e.deviceModel&&t.uint32(50).string(e.deviceModel),""!==e.browser&&t.uint32(58).string(e.browser),""!==e.browserVersion&&t.uint32(66).string(e.browserVersion),""!==e.address&&t.uint32(74).string(e.address),""!==e.network&&t.uint32(82).string(e.network),t},decode(e,t){const i=e instanceof st.Reader?e:st.Reader.create(e);let n=void 0===t?i.len:i.pos+t;const r={sdk:0,version:"",protocol:0,os:"",osVersion:"",deviceModel:"",browser:"",browserVersion:"",address:"",network:""};for(;i.pos<n;){const e=i.uint32();switch(e>>>3){case 1:if(8!==e)break;r.sdk=i.int32();continue;case 2:if(18!==e)break;r.version=i.string();continue;case 3:if(24!==e)break;r.protocol=i.int32();continue;case 4:if(34!==e)break;r.os=i.string();continue;case 5:if(42!==e)break;r.osVersion=i.string();continue;case 6:if(50!==e)break;r.deviceModel=i.string();continue;case 7:if(58!==e)break;r.browser=i.string();continue;case 8:if(66!==e)break;r.browserVersion=i.string();continue;case 9:if(74!==e)break;r.address=i.string();continue;case 10:if(82!==e)break;r.network=i.string();continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return r},fromJSON:e=>({sdk:qt(e.sdk)?Ct(e.sdk):0,version:qt(e.version)?String(e.version):"",protocol:qt(e.protocol)?Number(e.protocol):0,os:qt(e.os)?String(e.os):"",osVersion:qt(e.osVersion)?String(e.osVersion):"",deviceModel:qt(e.deviceModel)?String(e.deviceModel):"",browser:qt(e.browser)?String(e.browser):"",browserVersion:qt(e.browserVersion)?String(e.browserVersion):"",address:qt(e.address)?String(e.address):"",network:qt(e.network)?String(e.network):""}),toJSON(e){const t={};return void 0!==e.sdk&&(t.sdk=function(e){switch(e){case rt.UNKNOWN:return"UNKNOWN";case rt.JS:return"JS";case rt.SWIFT:return"SWIFT";case rt.ANDROID:return"ANDROID";case rt.FLUTTER:return"FLUTTER";case rt.GO:return"GO";case rt.UNITY:return"UNITY";case rt.REACT_NATIVE:return"REACT_NATIVE";case rt.RUST:return"RUST";case rt.UNRECOGNIZED:default:return"UNRECOGNIZED"}}(e.sdk)),void 0!==e.version&&(t.version=e.version),void 0!==e.protocol&&(t.protocol=Math.round(e.protocol)),void 0!==e.os&&(t.os=e.os),void 0!==e.osVersion&&(t.osVersion=e.osVersion),void 0!==e.deviceModel&&(t.deviceModel=e.deviceModel),void 0!==e.browser&&(t.browser=e.browser),void 0!==e.browserVersion&&(t.browserVersion=e.browserVersion),void 0!==e.address&&(t.address=e.address),void 0!==e.network&&(t.network=e.network),t},create:e=>xt.fromPartial(null!=e?e:{}),fromPartial(e){var t,i,n,r,s,o,a,c,d,u;const l={sdk:0,version:"",protocol:0,os:"",osVersion:"",deviceModel:"",browser:"",browserVersion:"",address:"",network:""};return l.sdk=null!==(t=e.sdk)&&void 0!==t?t:0,l.version=null!==(i=e.version)&&void 0!==i?i:"",l.protocol=null!==(n=e.protocol)&&void 0!==n?n:0,l.os=null!==(r=e.os)&&void 0!==r?r:"",l.osVersion=null!==(s=e.osVersion)&&void 0!==s?s:"",l.deviceModel=null!==(o=e.deviceModel)&&void 0!==o?o:"",l.browser=null!==(a=e.browser)&&void 0!==a?a:"",l.browserVersion=null!==(c=e.browserVersion)&&void 0!==c?c:"",l.address=null!==(d=e.address)&&void 0!==d?d:"",l.network=null!==(u=e.network)&&void 0!==u?u:"",l}};const Bt={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:st.Writer.create();return void 0!==e.video&&Jt.encode(e.video,t.uint32(10).fork()).ldelim(),void 0!==e.screen&&Jt.encode(e.screen,t.uint32(18).fork()).ldelim(),0!==e.resumeConnection&&t.uint32(24).int32(e.resumeConnection),void 0!==e.disabledCodecs&&Ft.encode(e.disabledCodecs,t.uint32(34).fork()).ldelim(),0!==e.forceRelay&&t.uint32(40).int32(e.forceRelay),t},decode(e,t){const i=e instanceof st.Reader?e:st.Reader.create(e);let n=void 0===t?i.len:i.pos+t;const r={video:void 0,screen:void 0,resumeConnection:0,disabledCodecs:void 0,forceRelay:0};for(;i.pos<n;){const e=i.uint32();switch(e>>>3){case 1:if(10!==e)break;r.video=Jt.decode(i,i.uint32());continue;case 2:if(18!==e)break;r.screen=Jt.decode(i,i.uint32());continue;case 3:if(24!==e)break;r.resumeConnection=i.int32();continue;case 4:if(34!==e)break;r.disabledCodecs=Ft.decode(i,i.uint32());continue;case 5:if(40!==e)break;r.forceRelay=i.int32();continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return r},fromJSON:e=>({video:qt(e.video)?Jt.fromJSON(e.video):void 0,screen:qt(e.screen)?Jt.fromJSON(e.screen):void 0,resumeConnection:qt(e.resumeConnection)?pt(e.resumeConnection):0,disabledCodecs:qt(e.disabledCodecs)?Ft.fromJSON(e.disabledCodecs):void 0,forceRelay:qt(e.forceRelay)?pt(e.forceRelay):0}),toJSON(e){const t={};return void 0!==e.video&&(t.video=e.video?Jt.toJSON(e.video):void 0),void 0!==e.screen&&(t.screen=e.screen?Jt.toJSON(e.screen):void 0),void 0!==e.resumeConnection&&(t.resumeConnection=mt(e.resumeConnection)),void 0!==e.disabledCodecs&&(t.disabledCodecs=e.disabledCodecs?Ft.toJSON(e.disabledCodecs):void 0),void 0!==e.forceRelay&&(t.forceRelay=mt(e.forceRelay)),t},create:e=>Bt.fromPartial(null!=e?e:{}),fromPartial(e){var t,i;const n={video:void 0,screen:void 0,resumeConnection:0,disabledCodecs:void 0,forceRelay:0};return n.video=void 0!==e.video&&null!==e.video?Jt.fromPartial(e.video):void 0,n.screen=void 0!==e.screen&&null!==e.screen?Jt.fromPartial(e.screen):void 0,n.resumeConnection=null!==(t=e.resumeConnection)&&void 0!==t?t:0,n.disabledCodecs=void 0!==e.disabledCodecs&&null!==e.disabledCodecs?Ft.fromPartial(e.disabledCodecs):void 0,n.forceRelay=null!==(i=e.forceRelay)&&void 0!==i?i:0,n}};const Jt={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:st.Writer.create();return 0!==e.hardwareEncoder&&t.uint32(8).int32(e.hardwareEncoder),t},decode(e,t){const i=e instanceof st.Reader?e:st.Reader.create(e);let n=void 0===t?i.len:i.pos+t;const r={hardwareEncoder:0};for(;i.pos<n;){const e=i.uint32();switch(e>>>3){case 1:if(8!==e)break;r.hardwareEncoder=i.int32();continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return r},fromJSON:e=>({hardwareEncoder:qt(e.hardwareEncoder)?pt(e.hardwareEncoder):0}),toJSON(e){const t={};return void 0!==e.hardwareEncoder&&(t.hardwareEncoder=mt(e.hardwareEncoder)),t},create:e=>Jt.fromPartial(null!=e?e:{}),fromPartial(e){var t;const i={hardwareEncoder:0};return i.hardwareEncoder=null!==(t=e.hardwareEncoder)&&void 0!==t?t:0,i}};const Ft={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:st.Writer.create();for(const i of e.codecs)Et.encode(i,t.uint32(10).fork()).ldelim();for(const i of e.publish)Et.encode(i,t.uint32(18).fork()).ldelim();return t},decode(e,t){const i=e instanceof st.Reader?e:st.Reader.create(e);let n=void 0===t?i.len:i.pos+t;const r={codecs:[],publish:[]};for(;i.pos<n;){const e=i.uint32();switch(e>>>3){case 1:if(10!==e)break;r.codecs.push(Et.decode(i,i.uint32()));continue;case 2:if(18!==e)break;r.publish.push(Et.decode(i,i.uint32()));continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return r},fromJSON:e=>({codecs:Array.isArray(null==e?void 0:e.codecs)?e.codecs.map((e=>Et.fromJSON(e))):[],publish:Array.isArray(null==e?void 0:e.publish)?e.publish.map((e=>Et.fromJSON(e))):[]}),toJSON(e){const t={};return e.codecs?t.codecs=e.codecs.map((e=>e?Et.toJSON(e):void 0)):t.codecs=[],e.publish?t.publish=e.publish.map((e=>e?Et.toJSON(e):void 0)):t.publish=[],t},create:e=>Ft.fromPartial(null!=e?e:{}),fromPartial(e){var t,i;const n={codecs:[],publish:[]};return n.codecs=(null===(t=e.codecs)||void 0===t?void 0:t.map((e=>Et.fromPartial(e))))||[],n.publish=(null===(i=e.publish)||void 0===i?void 0:i.map((e=>Et.fromPartial(e))))||[],n}};var $t=(()=>{if("undefined"!=typeof globalThis)return globalThis;if("undefined"!=typeof self)return self;if("undefined"!=typeof window)return window;if("undefined"!=typeof global)return global;throw"Unable to locate global object"})();function jt(e){if($t.Buffer)return Uint8Array.from($t.Buffer.from(e,"base64"));{const t=$t.atob(e),i=new Uint8Array(t.length);for(let e=0;e<t.length;++e)i[e]=t.charCodeAt(e);return i}}function Vt(e){if(e.gt(Number.MAX_SAFE_INTEGER))throw new $t.Error("Value is larger than Number.MAX_SAFE_INTEGER");return e.toNumber()}function qt(e){return null!=e}st.util.Long!==_&&(st.util.Long=_,st.configure());const Wt=7e3,Gt=[0,300,1200,2700,4800,Wt,Wt,Wt,Wt,Wt];class Qt{constructor(e){this._retryDelays=void 0!==e?[...e]:Gt}nextRetryDelayInMs(e){if(e.retryCount>=this._retryDelays.length)return null;const t=this._retryDelays[e.retryCount];return e.retryCount<=1?t:t+1e3*Math.random()}}function Ht(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{c(n.next(e))}catch(e){s(e)}}function a(e){try{c(n.throw(e))}catch(e){s(e)}}function c(e){e.done?r(e.value):function(e){return e instanceof i?e:new i((function(t){t(e)}))}(e.value).then(o,a)}c((n=n.apply(e,t||[])).next())}))}function Kt(e){var t="function"==typeof Symbol&&Symbol.iterator,i=t&&e[t],n=0;if(i)return i.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function Zt(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t,i=e[Symbol.asyncIterator];return i?i.call(e):(e=Kt(e),t={},n("next"),n("throw"),n("return"),t[Symbol.asyncIterator]=function(){return this},t);function n(i){t[i]=e[i]&&function(t){return new Promise((function(n,r){(function(e,t,i,n){Promise.resolve(n).then((function(t){e({value:t,done:i})}),t)})(n,r,(t=e[i](t)).done,t.value)}))}}}var zt={exports:{}};!function(e){var t=Object.prototype.hasOwnProperty,i="~";function n(){}function r(e,t,i){this.fn=e,this.context=t,this.once=i||!1}function s(e,t,n,s,o){if("function"!=typeof n)throw new TypeError("The listener must be a function");var a=new r(n,s||e,o),c=i?i+t:t;return e._events[c]?e._events[c].fn?e._events[c]=[e._events[c],a]:e._events[c].push(a):(e._events[c]=a,e._eventsCount++),e}function o(e,t){0==--e._eventsCount?e._events=new n:delete e._events[t]}function a(){this._events=new n,this._eventsCount=0}Object.create&&(n.prototype=Object.create(null),(new n).__proto__||(i=!1)),a.prototype.eventNames=function(){var e,n,r=[];if(0===this._eventsCount)return r;for(n in e=this._events)t.call(e,n)&&r.push(i?n.slice(1):n);return Object.getOwnPropertySymbols?r.concat(Object.getOwnPropertySymbols(e)):r},a.prototype.listeners=function(e){var t=i?i+e:e,n=this._events[t];if(!n)return[];if(n.fn)return[n.fn];for(var r=0,s=n.length,o=new Array(s);r<s;r++)o[r]=n[r].fn;return o},a.prototype.listenerCount=function(e){var t=i?i+e:e,n=this._events[t];return n?n.fn?1:n.length:0},a.prototype.emit=function(e,t,n,r,s,o){var a=i?i+e:e;if(!this._events[a])return!1;var c,d,u=this._events[a],l=arguments.length;if(u.fn){switch(u.once&&this.removeListener(e,u.fn,void 0,!0),l){case 1:return u.fn.call(u.context),!0;case 2:return u.fn.call(u.context,t),!0;case 3:return u.fn.call(u.context,t,n),!0;case 4:return u.fn.call(u.context,t,n,r),!0;case 5:return u.fn.call(u.context,t,n,r,s),!0;case 6:return u.fn.call(u.context,t,n,r,s,o),!0}for(d=1,c=new Array(l-1);d<l;d++)c[d-1]=arguments[d];u.fn.apply(u.context,c)}else{var h,p=u.length;for(d=0;d<p;d++)switch(u[d].once&&this.removeListener(e,u[d].fn,void 0,!0),l){case 1:u[d].fn.call(u[d].context);break;case 2:u[d].fn.call(u[d].context,t);break;case 3:u[d].fn.call(u[d].context,t,n);break;case 4:u[d].fn.call(u[d].context,t,n,r);break;default:if(!c)for(h=1,c=new Array(l-1);h<l;h++)c[h-1]=arguments[h];u[d].fn.apply(u[d].context,c)}}return!0},a.prototype.on=function(e,t,i){return s(this,e,t,i,!1)},a.prototype.once=function(e,t,i){return s(this,e,t,i,!0)},a.prototype.removeListener=function(e,t,n,r){var s=i?i+e:e;if(!this._events[s])return this;if(!t)return o(this,s),this;var a=this._events[s];if(a.fn)a.fn!==t||r&&!a.once||n&&a.context!==n||o(this,s);else{for(var c=0,d=[],u=a.length;c<u;c++)(a[c].fn!==t||r&&!a[c].once||n&&a[c].context!==n)&&d.push(a[c]);d.length?this._events[s]=1===d.length?d[0]:d:o(this,s)}return this},a.prototype.removeAllListeners=function(e){var t;return e?(t=i?i+e:e,this._events[t]&&o(this,t)):(this._events=new n,this._eventsCount=0),this},a.prototype.off=a.prototype.removeListener,a.prototype.addListener=a.prototype.on,a.prefixed=i,a.EventEmitter=a,e.exports=a}(zt);var Yt=n(zt.exports);let Xt=!0,ei=!0;function ti(e,t,i){const n=e.match(t);return n&&n.length>=i&&parseInt(n[i],10)}function ii(e,t,i){if(!e.RTCPeerConnection)return;const n=e.RTCPeerConnection.prototype,r=n.addEventListener;n.addEventListener=function(e,n){if(e!==t)return r.apply(this,arguments);const s=e=>{const t=i(e);t&&(n.handleEvent?n.handleEvent(t):n(t))};return this._eventMap=this._eventMap||{},this._eventMap[t]||(this._eventMap[t]=new Map),this._eventMap[t].set(n,s),r.apply(this,[e,s])};const s=n.removeEventListener;n.removeEventListener=function(e,i){if(e!==t||!this._eventMap||!this._eventMap[t])return s.apply(this,arguments);if(!this._eventMap[t].has(i))return s.apply(this,arguments);const n=this._eventMap[t].get(i);return this._eventMap[t].delete(i),0===this._eventMap[t].size&&delete this._eventMap[t],0===Object.keys(this._eventMap).length&&delete this._eventMap,s.apply(this,[e,n])},Object.defineProperty(n,"on"+t,{get(){return this["_on"+t]},set(e){this["_on"+t]&&(this.removeEventListener(t,this["_on"+t]),delete this["_on"+t]),e&&this.addEventListener(t,this["_on"+t]=e)},enumerable:!0,configurable:!0})}function ni(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(Xt=e,e?"adapter.js logging disabled":"adapter.js logging enabled")}function ri(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(ei=!e,"adapter.js deprecation warnings "+(e?"disabled":"enabled"))}function si(){if("object"==typeof window){if(Xt)return;"undefined"!=typeof console&&"function"==typeof console.log&&console.log.apply(console,arguments)}}function oi(e,t){ei&&console.warn(e+" is deprecated, please use "+t+" instead.")}function ai(e){return"[object Object]"===Object.prototype.toString.call(e)}function ci(e){return ai(e)?Object.keys(e).reduce((function(t,i){const n=ai(e[i]),r=n?ci(e[i]):e[i],s=n&&!Object.keys(r).length;return void 0===r||s?t:Object.assign(t,{[i]:r})}),{}):e}function di(e,t,i){t&&!i.has(t.id)&&(i.set(t.id,t),Object.keys(t).forEach((n=>{n.endsWith("Id")?di(e,e.get(t[n]),i):n.endsWith("Ids")&&t[n].forEach((t=>{di(e,e.get(t),i)}))})))}function ui(e,t,i){const n=i?"outbound-rtp":"inbound-rtp",r=new Map;if(null===t)return r;const s=[];return e.forEach((e=>{"track"===e.type&&e.trackIdentifier===t.id&&s.push(e)})),s.forEach((t=>{e.forEach((i=>{i.type===n&&i.trackId===t.id&&di(e,i,r)}))})),r}const li=si;function hi(e,t){const i=e&&e.navigator;if(!i.mediaDevices)return;const n=function(e){if("object"!=typeof e||e.mandatory||e.optional)return e;const t={};return Object.keys(e).forEach((i=>{if("require"===i||"advanced"===i||"mediaSource"===i)return;const n="object"==typeof e[i]?e[i]:{ideal:e[i]};void 0!==n.exact&&"number"==typeof n.exact&&(n.min=n.max=n.exact);const r=function(e,t){return e?e+t.charAt(0).toUpperCase()+t.slice(1):"deviceId"===t?"sourceId":t};if(void 0!==n.ideal){t.optional=t.optional||[];let e={};"number"==typeof n.ideal?(e[r("min",i)]=n.ideal,t.optional.push(e),e={},e[r("max",i)]=n.ideal,t.optional.push(e)):(e[r("",i)]=n.ideal,t.optional.push(e))}void 0!==n.exact&&"number"!=typeof n.exact?(t.mandatory=t.mandatory||{},t.mandatory[r("",i)]=n.exact):["min","max"].forEach((e=>{void 0!==n[e]&&(t.mandatory=t.mandatory||{},t.mandatory[r(e,i)]=n[e])}))})),e.advanced&&(t.optional=(t.optional||[]).concat(e.advanced)),t},r=function(e,r){if(t.version>=61)return r(e);if((e=JSON.parse(JSON.stringify(e)))&&"object"==typeof e.audio){const t=function(e,t,i){t in e&&!(i in e)&&(e[i]=e[t],delete e[t])};t((e=JSON.parse(JSON.stringify(e))).audio,"autoGainControl","googAutoGainControl"),t(e.audio,"noiseSuppression","googNoiseSuppression"),e.audio=n(e.audio)}if(e&&"object"==typeof e.video){let s=e.video.facingMode;s=s&&("object"==typeof s?s:{ideal:s});const o=t.version<66;if(s&&("user"===s.exact||"environment"===s.exact||"user"===s.ideal||"environment"===s.ideal)&&(!i.mediaDevices.getSupportedConstraints||!i.mediaDevices.getSupportedConstraints().facingMode||o)){let t;if(delete e.video.facingMode,"environment"===s.exact||"environment"===s.ideal?t=["back","rear"]:"user"!==s.exact&&"user"!==s.ideal||(t=["front"]),t)return i.mediaDevices.enumerateDevices().then((i=>{let o=(i=i.filter((e=>"videoinput"===e.kind))).find((e=>t.some((t=>e.label.toLowerCase().includes(t)))));return!o&&i.length&&t.includes("back")&&(o=i[i.length-1]),o&&(e.video.deviceId=s.exact?{exact:o.deviceId}:{ideal:o.deviceId}),e.video=n(e.video),li("chrome: "+JSON.stringify(e)),r(e)}))}e.video=n(e.video)}return li("chrome: "+JSON.stringify(e)),r(e)},s=function(e){return t.version>=64?e:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[e.name]||e.name,message:e.message,constraint:e.constraint||e.constraintName,toString(){return this.name+(this.message&&": ")+this.message}}};if(i.getUserMedia=function(e,t,n){r(e,(e=>{i.webkitGetUserMedia(e,t,(e=>{n&&n(s(e))}))}))}.bind(i),i.mediaDevices.getUserMedia){const e=i.mediaDevices.getUserMedia.bind(i.mediaDevices);i.mediaDevices.getUserMedia=function(t){return r(t,(t=>e(t).then((e=>{if(t.audio&&!e.getAudioTracks().length||t.video&&!e.getVideoTracks().length)throw e.getTracks().forEach((e=>{e.stop()})),new DOMException("","NotFoundError");return e}),(e=>Promise.reject(s(e))))))}}}function pi(e){e.MediaStream=e.MediaStream||e.webkitMediaStream}function mi(e){if("object"==typeof e&&e.RTCPeerConnection&&!("ontrack"in e.RTCPeerConnection.prototype)){Object.defineProperty(e.RTCPeerConnection.prototype,"ontrack",{get(){return this._ontrack},set(e){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=e)},enumerable:!0,configurable:!0});const t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=t=>{t.stream.addEventListener("addtrack",(i=>{let n;n=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find((e=>e.track&&e.track.id===i.track.id)):{track:i.track};const r=new Event("track");r.track=i.track,r.receiver=n,r.transceiver={receiver:n},r.streams=[t.stream],this.dispatchEvent(r)})),t.stream.getTracks().forEach((i=>{let n;n=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find((e=>e.track&&e.track.id===i.id)):{track:i};const r=new Event("track");r.track=i,r.receiver=n,r.transceiver={receiver:n},r.streams=[t.stream],this.dispatchEvent(r)}))},this.addEventListener("addstream",this._ontrackpoly)),t.apply(this,arguments)}}else ii(e,"track",(e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e)))}function fi(e){if("object"==typeof e&&e.RTCPeerConnection&&!("getSenders"in e.RTCPeerConnection.prototype)&&"createDTMFSender"in e.RTCPeerConnection.prototype){const t=function(e,t){return{track:t,get dtmf(){return void 0===this._dtmf&&("audio"===t.kind?this._dtmf=e.createDTMFSender(t):this._dtmf=null),this._dtmf},_pc:e}};if(!e.RTCPeerConnection.prototype.getSenders){e.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};const i=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,n){let r=i.apply(this,arguments);return r||(r=t(this,e),this._senders.push(r)),r};const n=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){n.apply(this,arguments);const t=this._senders.indexOf(e);-1!==t&&this._senders.splice(t,1)}}const i=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._senders=this._senders||[],i.apply(this,[e]),e.getTracks().forEach((e=>{this._senders.push(t(this,e))}))};const n=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){this._senders=this._senders||[],n.apply(this,[e]),e.getTracks().forEach((e=>{const t=this._senders.find((t=>t.track===e));t&&this._senders.splice(this._senders.indexOf(t),1)}))}}else if("object"==typeof e&&e.RTCPeerConnection&&"getSenders"in e.RTCPeerConnection.prototype&&"createDTMFSender"in e.RTCPeerConnection.prototype&&e.RTCRtpSender&&!("dtmf"in e.RTCRtpSender.prototype)){const t=e.RTCPeerConnection.prototype.getSenders;e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e},Object.defineProperty(e.RTCRtpSender.prototype,"dtmf",{get(){return void 0===this._dtmf&&("audio"===this.track.kind?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}}function vi(e){if(!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){const[e,i,n]=arguments;if(arguments.length>0&&"function"==typeof e)return t.apply(this,arguments);if(0===t.length&&(0===arguments.length||"function"!=typeof e))return t.apply(this,[]);const r=function(e){const t={};return e.result().forEach((e=>{const i={id:e.id,timestamp:e.timestamp,type:{localcandidate:"local-candidate",remotecandidate:"remote-candidate"}[e.type]||e.type};e.names().forEach((t=>{i[t]=e.stat(t)})),t[i.id]=i})),t},s=function(e){return new Map(Object.keys(e).map((t=>[t,e[t]])))};if(arguments.length>=2){const n=function(e){i(s(r(e)))};return t.apply(this,[n,e])}return new Promise(((e,i)=>{t.apply(this,[function(t){e(s(r(t)))},i])})).then(i,n)}}function gi(e){if(!("object"==typeof e&&e.RTCPeerConnection&&e.RTCRtpSender&&e.RTCRtpReceiver))return;if(!("getStats"in e.RTCRtpSender.prototype)){const t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e});const i=e.RTCPeerConnection.prototype.addTrack;i&&(e.RTCPeerConnection.prototype.addTrack=function(){const e=i.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){const e=this;return this._pc.getStats().then((t=>ui(t,e.track,!0)))}}if(!("getStats"in e.RTCRtpReceiver.prototype)){const t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e}),ii(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){const e=this;return this._pc.getStats().then((t=>ui(t,e.track,!1)))}}if(!("getStats"in e.RTCRtpSender.prototype)||!("getStats"in e.RTCRtpReceiver.prototype))return;const t=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof e.MediaStreamTrack){const e=arguments[0];let t,i,n;return this.getSenders().forEach((i=>{i.track===e&&(t?n=!0:t=i)})),this.getReceivers().forEach((t=>(t.track===e&&(i?n=!0:i=t),t.track===e))),n||t&&i?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):t?t.getStats():i?i.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return t.apply(this,arguments)}}function bi(e){e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map((e=>this._shimmedLocalStreams[e][0]))};const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,i){if(!i)return t.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};const n=t.apply(this,arguments);return this._shimmedLocalStreams[i.id]?-1===this._shimmedLocalStreams[i.id].indexOf(n)&&this._shimmedLocalStreams[i.id].push(n):this._shimmedLocalStreams[i.id]=[i,n],n};const i=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._shimmedLocalStreams=this._shimmedLocalStreams||{},e.getTracks().forEach((e=>{if(this.getSenders().find((t=>t.track===e)))throw new DOMException("Track already exists.","InvalidAccessError")}));const t=this.getSenders();i.apply(this,arguments);const n=this.getSenders().filter((e=>-1===t.indexOf(e)));this._shimmedLocalStreams[e.id]=[e].concat(n)};const n=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[e.id],n.apply(this,arguments)};const r=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},e&&Object.keys(this._shimmedLocalStreams).forEach((t=>{const i=this._shimmedLocalStreams[t].indexOf(e);-1!==i&&this._shimmedLocalStreams[t].splice(i,1),1===this._shimmedLocalStreams[t].length&&delete this._shimmedLocalStreams[t]})),r.apply(this,arguments)}}function ki(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return bi(e);const i=e.RTCPeerConnection.prototype.getLocalStreams;e.RTCPeerConnection.prototype.getLocalStreams=function(){const e=i.apply(this);return this._reverseStreams=this._reverseStreams||{},e.map((e=>this._reverseStreams[e.id]))};const n=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(t){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},t.getTracks().forEach((e=>{if(this.getSenders().find((t=>t.track===e)))throw new DOMException("Track already exists.","InvalidAccessError")})),!this._reverseStreams[t.id]){const i=new e.MediaStream(t.getTracks());this._streams[t.id]=i,this._reverseStreams[i.id]=t,t=i}n.apply(this,[t])};const r=e.RTCPeerConnection.prototype.removeStream;function s(e,t){let i=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((t=>{const n=e._reverseStreams[t],r=e._streams[n.id];i=i.replace(new RegExp(r.id,"g"),n.id)})),new RTCSessionDescription({type:t.type,sdp:i})}e.RTCPeerConnection.prototype.removeStream=function(e){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},r.apply(this,[this._streams[e.id]||e]),delete this._reverseStreams[this._streams[e.id]?this._streams[e.id].id:e.id],delete this._streams[e.id]},e.RTCPeerConnection.prototype.addTrack=function(t,i){if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");const n=[].slice.call(arguments,1);if(1!==n.length||!n[0].getTracks().find((e=>e===t)))throw new DOMException("The adapter.js addTrack polyfill only supports a single stream which is associated with the specified track.","NotSupportedError");if(this.getSenders().find((e=>e.track===t)))throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};const r=this._streams[i.id];if(r)r.addTrack(t),Promise.resolve().then((()=>{this.dispatchEvent(new Event("negotiationneeded"))}));else{const n=new e.MediaStream([t]);this._streams[i.id]=n,this._reverseStreams[n.id]=i,this.addStream(n)}return this.getSenders().find((e=>e.track===t))},["createOffer","createAnswer"].forEach((function(t){const i=e.RTCPeerConnection.prototype[t],n={[t](){const e=arguments;return arguments.length&&"function"==typeof arguments[0]?i.apply(this,[t=>{const i=s(this,t);e[0].apply(null,[i])},t=>{e[1]&&e[1].apply(null,t)},arguments[2]]):i.apply(this,arguments).then((e=>s(this,e)))}};e.RTCPeerConnection.prototype[t]=n[t]}));const o=e.RTCPeerConnection.prototype.setLocalDescription;e.RTCPeerConnection.prototype.setLocalDescription=function(){return arguments.length&&arguments[0].type?(arguments[0]=function(e,t){let i=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((t=>{const n=e._reverseStreams[t],r=e._streams[n.id];i=i.replace(new RegExp(n.id,"g"),r.id)})),new RTCSessionDescription({type:t.type,sdp:i})}(this,arguments[0]),o.apply(this,arguments)):o.apply(this,arguments)};const a=Object.getOwnPropertyDescriptor(e.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(e.RTCPeerConnection.prototype,"localDescription",{get(){const e=a.get.apply(this);return""===e.type?e:s(this,e)}}),e.RTCPeerConnection.prototype.removeTrack=function(e){if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!e._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(!(e._pc===this))throw new DOMException("Sender was not created by this connection.","InvalidAccessError");let t;this._streams=this._streams||{},Object.keys(this._streams).forEach((i=>{this._streams[i].getTracks().find((t=>e.track===t))&&(t=this._streams[i])})),t&&(1===t.getTracks().length?this.removeStream(this._reverseStreams[t.id]):t.removeTrack(e.track),this.dispatchEvent(new Event("negotiationneeded")))}}function Si(e,t){!e.RTCPeerConnection&&e.webkitRTCPeerConnection&&(e.RTCPeerConnection=e.webkitRTCPeerConnection),e.RTCPeerConnection&&t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach((function(t){const i=e.RTCPeerConnection.prototype[t],n={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),i.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=n[t]}))}function yi(e,t){ii(e,"negotiationneeded",(e=>{const i=e.target;if(!(t.version<72||i.getConfiguration&&"plan-b"===i.getConfiguration().sdpSemantics)||"stable"===i.signalingState)return e}))}var Ci=Object.freeze({__proto__:null,fixNegotiationNeeded:yi,shimAddTrackRemoveTrack:ki,shimAddTrackRemoveTrackWithNative:bi,shimGetDisplayMedia:function(e,t){e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||e.navigator.mediaDevices&&("function"==typeof t?e.navigator.mediaDevices.getDisplayMedia=function(i){return t(i).then((t=>{const n=i.video&&i.video.width,r=i.video&&i.video.height,s=i.video&&i.video.frameRate;return i.video={mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:t,maxFrameRate:s||3}},n&&(i.video.mandatory.maxWidth=n),r&&(i.video.mandatory.maxHeight=r),e.navigator.mediaDevices.getUserMedia(i)}))}:console.error("shimGetDisplayMedia: getSourceId argument is not a function"))},shimGetSendersWithDtmf:fi,shimGetStats:vi,shimGetUserMedia:hi,shimMediaStream:pi,shimOnTrack:mi,shimPeerConnection:Si,shimSenderReceiverGetStats:gi});function Ti(e,t){const i=e&&e.navigator,n=e&&e.MediaStreamTrack;if(i.getUserMedia=function(e,t,n){oi("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),i.mediaDevices.getUserMedia(e).then(t,n)},!(t.version>55&&"autoGainControl"in i.mediaDevices.getSupportedConstraints())){const e=function(e,t,i){t in e&&!(i in e)&&(e[i]=e[t],delete e[t])},t=i.mediaDevices.getUserMedia.bind(i.mediaDevices);if(i.mediaDevices.getUserMedia=function(i){return"object"==typeof i&&"object"==typeof i.audio&&(i=JSON.parse(JSON.stringify(i)),e(i.audio,"autoGainControl","mozAutoGainControl"),e(i.audio,"noiseSuppression","mozNoiseSuppression")),t(i)},n&&n.prototype.getSettings){const t=n.prototype.getSettings;n.prototype.getSettings=function(){const i=t.apply(this,arguments);return e(i,"mozAutoGainControl","autoGainControl"),e(i,"mozNoiseSuppression","noiseSuppression"),i}}if(n&&n.prototype.applyConstraints){const t=n.prototype.applyConstraints;n.prototype.applyConstraints=function(i){return"audio"===this.kind&&"object"==typeof i&&(i=JSON.parse(JSON.stringify(i)),e(i,"autoGainControl","mozAutoGainControl"),e(i,"noiseSuppression","mozNoiseSuppression")),t.apply(this,[i])}}}}function Ei(e){"object"==typeof e&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function Pi(e,t){if("object"!=typeof e||!e.RTCPeerConnection&&!e.mozRTCPeerConnection)return;!e.RTCPeerConnection&&e.mozRTCPeerConnection&&(e.RTCPeerConnection=e.mozRTCPeerConnection),t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach((function(t){const i=e.RTCPeerConnection.prototype[t],n={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),i.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=n[t]}));const i={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},n=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){const[e,r,s]=arguments;return n.apply(this,[e||null]).then((e=>{if(t.version<53&&!r)try{e.forEach((e=>{e.type=i[e.type]||e.type}))}catch(t){if("TypeError"!==t.name)throw t;e.forEach(((t,n)=>{e.set(n,Object.assign({},t,{type:i[t.type]||t.type}))}))}return e})).then(r,s)}}function wi(e){if("object"!=typeof e||!e.RTCPeerConnection||!e.RTCRtpSender)return;if(e.RTCRtpSender&&"getStats"in e.RTCRtpSender.prototype)return;const t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e});const i=e.RTCPeerConnection.prototype.addTrack;i&&(e.RTCPeerConnection.prototype.addTrack=function(){const e=i.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function Ri(e){if("object"!=typeof e||!e.RTCPeerConnection||!e.RTCRtpSender)return;if(e.RTCRtpSender&&"getStats"in e.RTCRtpReceiver.prototype)return;const t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e}),ii(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function Ni(e){e.RTCPeerConnection&&!("removeStream"in e.RTCPeerConnection.prototype)&&(e.RTCPeerConnection.prototype.removeStream=function(e){oi("removeStream","removeTrack"),this.getSenders().forEach((t=>{t.track&&e.getTracks().includes(t.track)&&this.removeTrack(t)}))})}function Oi(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)}function Di(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.addTransceiver;t&&(e.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let e=arguments[1]&&arguments[1].sendEncodings;void 0===e&&(e=[]),e=[...e];const i=e.length>0;i&&e.forEach((e=>{if("rid"in e){if(!/^[a-z0-9]{0,16}$/i.test(e.rid))throw new TypeError("Invalid RID value provided.")}if("scaleResolutionDownBy"in e&&!(parseFloat(e.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in e&&!(parseFloat(e.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")}));const n=t.apply(this,arguments);if(i){const{sender:t}=n,i=t.getParameters();(!("encodings"in i)||1===i.encodings.length&&0===Object.keys(i.encodings[0]).length)&&(i.encodings=e,t.sendEncodings=e,this.setParametersPromises.push(t.setParameters(i).then((()=>{delete t.sendEncodings})).catch((()=>{delete t.sendEncodings}))))}return n})}function Ii(e){if("object"!=typeof e||!e.RTCRtpSender)return;const t=e.RTCRtpSender.prototype.getParameters;t&&(e.RTCRtpSender.prototype.getParameters=function(){const e=t.apply(this,arguments);return"encodings"in e||(e.encodings=[].concat(this.sendEncodings||[{}])),e})}function Ai(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then((()=>t.apply(this,arguments))).finally((()=>{this.setParametersPromises=[]})):t.apply(this,arguments)}}function Ui(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.createAnswer;e.RTCPeerConnection.prototype.createAnswer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then((()=>t.apply(this,arguments))).finally((()=>{this.setParametersPromises=[]})):t.apply(this,arguments)}}var Mi=Object.freeze({__proto__:null,shimAddTransceiver:Di,shimCreateAnswer:Ui,shimCreateOffer:Ai,shimGetDisplayMedia:function(e,t){e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||e.navigator.mediaDevices&&(e.navigator.mediaDevices.getDisplayMedia=function(i){if(!i||!i.video){const e=new DOMException("getDisplayMedia without video constraints is undefined");return e.name="NotFoundError",e.code=8,Promise.reject(e)}return!0===i.video?i.video={mediaSource:t}:i.video.mediaSource=t,e.navigator.mediaDevices.getUserMedia(i)})},shimGetParameters:Ii,shimGetUserMedia:Ti,shimOnTrack:Ei,shimPeerConnection:Pi,shimRTCDataChannel:Oi,shimReceiverGetStats:Ri,shimRemoveStream:Ni,shimSenderGetStats:wi});function Li(e){if("object"==typeof e&&e.RTCPeerConnection){if("getLocalStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in e.RTCPeerConnection.prototype)){const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addStream=function(e){this._localStreams||(this._localStreams=[]),this._localStreams.includes(e)||this._localStreams.push(e),e.getAudioTracks().forEach((i=>t.call(this,i,e))),e.getVideoTracks().forEach((i=>t.call(this,i,e)))},e.RTCPeerConnection.prototype.addTrack=function(e){for(var i=arguments.length,n=new Array(i>1?i-1:0),r=1;r<i;r++)n[r-1]=arguments[r];return n&&n.forEach((e=>{this._localStreams?this._localStreams.includes(e)||this._localStreams.push(e):this._localStreams=[e]})),t.apply(this,arguments)}}"removeStream"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.removeStream=function(e){this._localStreams||(this._localStreams=[]);const t=this._localStreams.indexOf(e);if(-1===t)return;this._localStreams.splice(t,1);const i=e.getTracks();this.getSenders().forEach((e=>{i.includes(e.track)&&this.removeTrack(e)}))})}}function _i(e){if("object"==typeof e&&e.RTCPeerConnection&&("getRemoteStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!("onaddstream"in e.RTCPeerConnection.prototype))){Object.defineProperty(e.RTCPeerConnection.prototype,"onaddstream",{get(){return this._onaddstream},set(e){this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=e),this.addEventListener("track",this._onaddstreampoly=e=>{e.streams.forEach((e=>{if(this._remoteStreams||(this._remoteStreams=[]),this._remoteStreams.includes(e))return;this._remoteStreams.push(e);const t=new Event("addstream");t.stream=e,this.dispatchEvent(t)}))})}});const t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){const e=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(t){t.streams.forEach((t=>{if(e._remoteStreams||(e._remoteStreams=[]),e._remoteStreams.indexOf(t)>=0)return;e._remoteStreams.push(t);const i=new Event("addstream");i.stream=t,e.dispatchEvent(i)}))}),t.apply(e,arguments)}}}function xi(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype,i=t.createOffer,n=t.createAnswer,r=t.setLocalDescription,s=t.setRemoteDescription,o=t.addIceCandidate;t.createOffer=function(e,t){const n=arguments.length>=2?arguments[2]:arguments[0],r=i.apply(this,[n]);return t?(r.then(e,t),Promise.resolve()):r},t.createAnswer=function(e,t){const i=arguments.length>=2?arguments[2]:arguments[0],r=n.apply(this,[i]);return t?(r.then(e,t),Promise.resolve()):r};let a=function(e,t,i){const n=r.apply(this,[e]);return i?(n.then(t,i),Promise.resolve()):n};t.setLocalDescription=a,a=function(e,t,i){const n=s.apply(this,[e]);return i?(n.then(t,i),Promise.resolve()):n},t.setRemoteDescription=a,a=function(e,t,i){const n=o.apply(this,[e]);return i?(n.then(t,i),Promise.resolve()):n},t.addIceCandidate=a}function Bi(e){const t=e&&e.navigator;if(t.mediaDevices&&t.mediaDevices.getUserMedia){const e=t.mediaDevices,i=e.getUserMedia.bind(e);t.mediaDevices.getUserMedia=e=>i(Ji(e))}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=function(e,i,n){t.mediaDevices.getUserMedia(e).then(i,n)}.bind(t))}function Ji(e){return e&&void 0!==e.video?Object.assign({},e,{video:ci(e.video)}):e}function Fi(e){if(!e.RTCPeerConnection)return;const t=e.RTCPeerConnection;e.RTCPeerConnection=function(e,i){if(e&&e.iceServers){const t=[];for(let i=0;i<e.iceServers.length;i++){let n=e.iceServers[i];void 0===n.urls&&n.url?(oi("RTCIceServer.url","RTCIceServer.urls"),n=JSON.parse(JSON.stringify(n)),n.urls=n.url,delete n.url,t.push(n)):t.push(e.iceServers[i])}e.iceServers=t}return new t(e,i)},e.RTCPeerConnection.prototype=t.prototype,"generateCertificate"in t&&Object.defineProperty(e.RTCPeerConnection,"generateCertificate",{get:()=>t.generateCertificate})}function $i(e){"object"==typeof e&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function ji(e){const t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(e){if(e){void 0!==e.offerToReceiveAudio&&(e.offerToReceiveAudio=!!e.offerToReceiveAudio);const t=this.getTransceivers().find((e=>"audio"===e.receiver.track.kind));!1===e.offerToReceiveAudio&&t?"sendrecv"===t.direction?t.setDirection?t.setDirection("sendonly"):t.direction="sendonly":"recvonly"===t.direction&&(t.setDirection?t.setDirection("inactive"):t.direction="inactive"):!0!==e.offerToReceiveAudio||t||this.addTransceiver("audio",{direction:"recvonly"}),void 0!==e.offerToReceiveVideo&&(e.offerToReceiveVideo=!!e.offerToReceiveVideo);const i=this.getTransceivers().find((e=>"video"===e.receiver.track.kind));!1===e.offerToReceiveVideo&&i?"sendrecv"===i.direction?i.setDirection?i.setDirection("sendonly"):i.direction="sendonly":"recvonly"===i.direction&&(i.setDirection?i.setDirection("inactive"):i.direction="inactive"):!0!==e.offerToReceiveVideo||i||this.addTransceiver("video",{direction:"recvonly"})}return t.apply(this,arguments)}}function Vi(e){"object"!=typeof e||e.AudioContext||(e.AudioContext=e.webkitAudioContext)}var qi=Object.freeze({__proto__:null,shimAudioContext:Vi,shimCallbacksAPI:xi,shimConstraints:Ji,shimCreateOfferLegacy:ji,shimGetUserMedia:Bi,shimLocalStreamsAPI:Li,shimRTCIceServerUrls:Fi,shimRemoteStreamsAPI:_i,shimTrackEventTransceiver:$i}),Wi={exports:{}};!function(e){const t={generateIdentifier:function(){return Math.random().toString(36).substring(2,12)}};t.localCName=t.generateIdentifier(),t.splitLines=function(e){return e.trim().split("\n").map((e=>e.trim()))},t.splitSections=function(e){return e.split("\nm=").map(((e,t)=>(t>0?"m="+e:e).trim()+"\r\n"))},t.getDescription=function(e){const i=t.splitSections(e);return i&&i[0]},t.getMediaSections=function(e){const i=t.splitSections(e);return i.shift(),i},t.matchPrefix=function(e,i){return t.splitLines(e).filter((e=>0===e.indexOf(i)))},t.parseCandidate=function(e){let t;t=0===e.indexOf("a=candidate:")?e.substring(12).split(" "):e.substring(10).split(" ");const i={foundation:t[0],component:{1:"rtp",2:"rtcp"}[t[1]]||t[1],protocol:t[2].toLowerCase(),priority:parseInt(t[3],10),ip:t[4],address:t[4],port:parseInt(t[5],10),type:t[7]};for(let e=8;e<t.length;e+=2)switch(t[e]){case"raddr":i.relatedAddress=t[e+1];break;case"rport":i.relatedPort=parseInt(t[e+1],10);break;case"tcptype":i.tcpType=t[e+1];break;case"ufrag":i.ufrag=t[e+1],i.usernameFragment=t[e+1];break;default:void 0===i[t[e]]&&(i[t[e]]=t[e+1])}return i},t.writeCandidate=function(e){const t=[];t.push(e.foundation);const i=e.component;"rtp"===i?t.push(1):"rtcp"===i?t.push(2):t.push(i),t.push(e.protocol.toUpperCase()),t.push(e.priority),t.push(e.address||e.ip),t.push(e.port);const n=e.type;return t.push("typ"),t.push(n),"host"!==n&&e.relatedAddress&&e.relatedPort&&(t.push("raddr"),t.push(e.relatedAddress),t.push("rport"),t.push(e.relatedPort)),e.tcpType&&"tcp"===e.protocol.toLowerCase()&&(t.push("tcptype"),t.push(e.tcpType)),(e.usernameFragment||e.ufrag)&&(t.push("ufrag"),t.push(e.usernameFragment||e.ufrag)),"candidate:"+t.join(" ")},t.parseIceOptions=function(e){return e.substring(14).split(" ")},t.parseRtpMap=function(e){let t=e.substring(9).split(" ");const i={payloadType:parseInt(t.shift(),10)};return t=t[0].split("/"),i.name=t[0],i.clockRate=parseInt(t[1],10),i.channels=3===t.length?parseInt(t[2],10):1,i.numChannels=i.channels,i},t.writeRtpMap=function(e){let t=e.payloadType;void 0!==e.preferredPayloadType&&(t=e.preferredPayloadType);const i=e.channels||e.numChannels||1;return"a=rtpmap:"+t+" "+e.name+"/"+e.clockRate+(1!==i?"/"+i:"")+"\r\n"},t.parseExtmap=function(e){const t=e.substring(9).split(" ");return{id:parseInt(t[0],10),direction:t[0].indexOf("/")>0?t[0].split("/")[1]:"sendrecv",uri:t[1],attributes:t.slice(2).join(" ")}},t.writeExtmap=function(e){return"a=extmap:"+(e.id||e.preferredId)+(e.direction&&"sendrecv"!==e.direction?"/"+e.direction:"")+" "+e.uri+(e.attributes?" "+e.attributes:"")+"\r\n"},t.parseFmtp=function(e){const t={};let i;const n=e.substring(e.indexOf(" ")+1).split(";");for(let e=0;e<n.length;e++)i=n[e].trim().split("="),t[i[0].trim()]=i[1];return t},t.writeFmtp=function(e){let t="",i=e.payloadType;if(void 0!==e.preferredPayloadType&&(i=e.preferredPayloadType),e.parameters&&Object.keys(e.parameters).length){const n=[];Object.keys(e.parameters).forEach((t=>{void 0!==e.parameters[t]?n.push(t+"="+e.parameters[t]):n.push(t)})),t+="a=fmtp:"+i+" "+n.join(";")+"\r\n"}return t},t.parseRtcpFb=function(e){const t=e.substring(e.indexOf(" ")+1).split(" ");return{type:t.shift(),parameter:t.join(" ")}},t.writeRtcpFb=function(e){let t="",i=e.payloadType;return void 0!==e.preferredPayloadType&&(i=e.preferredPayloadType),e.rtcpFeedback&&e.rtcpFeedback.length&&e.rtcpFeedback.forEach((e=>{t+="a=rtcp-fb:"+i+" "+e.type+(e.parameter&&e.parameter.length?" "+e.parameter:"")+"\r\n"})),t},t.parseSsrcMedia=function(e){const t=e.indexOf(" "),i={ssrc:parseInt(e.substring(7,t),10)},n=e.indexOf(":",t);return n>-1?(i.attribute=e.substring(t+1,n),i.value=e.substring(n+1)):i.attribute=e.substring(t+1),i},t.parseSsrcGroup=function(e){const t=e.substring(13).split(" ");return{semantics:t.shift(),ssrcs:t.map((e=>parseInt(e,10)))}},t.getMid=function(e){const i=t.matchPrefix(e,"a=mid:")[0];if(i)return i.substring(6)},t.parseFingerprint=function(e){const t=e.substring(14).split(" ");return{algorithm:t[0].toLowerCase(),value:t[1].toUpperCase()}},t.getDtlsParameters=function(e,i){return{role:"auto",fingerprints:t.matchPrefix(e+i,"a=fingerprint:").map(t.parseFingerprint)}},t.writeDtlsParameters=function(e,t){let i="a=setup:"+t+"\r\n";return e.fingerprints.forEach((e=>{i+="a=fingerprint:"+e.algorithm+" "+e.value+"\r\n"})),i},t.parseCryptoLine=function(e){const t=e.substring(9).split(" ");return{tag:parseInt(t[0],10),cryptoSuite:t[1],keyParams:t[2],sessionParams:t.slice(3)}},t.writeCryptoLine=function(e){return"a=crypto:"+e.tag+" "+e.cryptoSuite+" "+("object"==typeof e.keyParams?t.writeCryptoKeyParams(e.keyParams):e.keyParams)+(e.sessionParams?" "+e.sessionParams.join(" "):"")+"\r\n"},t.parseCryptoKeyParams=function(e){if(0!==e.indexOf("inline:"))return null;const t=e.substring(7).split("|");return{keyMethod:"inline",keySalt:t[0],lifeTime:t[1],mkiValue:t[2]?t[2].split(":")[0]:void 0,mkiLength:t[2]?t[2].split(":")[1]:void 0}},t.writeCryptoKeyParams=function(e){return e.keyMethod+":"+e.keySalt+(e.lifeTime?"|"+e.lifeTime:"")+(e.mkiValue&&e.mkiLength?"|"+e.mkiValue+":"+e.mkiLength:"")},t.getCryptoParameters=function(e,i){return t.matchPrefix(e+i,"a=crypto:").map(t.parseCryptoLine)},t.getIceParameters=function(e,i){const n=t.matchPrefix(e+i,"a=ice-ufrag:")[0],r=t.matchPrefix(e+i,"a=ice-pwd:")[0];return n&&r?{usernameFragment:n.substring(12),password:r.substring(10)}:null},t.writeIceParameters=function(e){let t="a=ice-ufrag:"+e.usernameFragment+"\r\na=ice-pwd:"+e.password+"\r\n";return e.iceLite&&(t+="a=ice-lite\r\n"),t},t.parseRtpParameters=function(e){const i={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},n=t.splitLines(e)[0].split(" ");i.profile=n[2];for(let r=3;r<n.length;r++){const s=n[r],o=t.matchPrefix(e,"a=rtpmap:"+s+" ")[0];if(o){const n=t.parseRtpMap(o),r=t.matchPrefix(e,"a=fmtp:"+s+" ");switch(n.parameters=r.length?t.parseFmtp(r[0]):{},n.rtcpFeedback=t.matchPrefix(e,"a=rtcp-fb:"+s+" ").map(t.parseRtcpFb),i.codecs.push(n),n.name.toUpperCase()){case"RED":case"ULPFEC":i.fecMechanisms.push(n.name.toUpperCase())}}}t.matchPrefix(e,"a=extmap:").forEach((e=>{i.headerExtensions.push(t.parseExtmap(e))}));const r=t.matchPrefix(e,"a=rtcp-fb:* ").map(t.parseRtcpFb);return i.codecs.forEach((e=>{r.forEach((t=>{e.rtcpFeedback.find((e=>e.type===t.type&&e.parameter===t.parameter))||e.rtcpFeedback.push(t)}))})),i},t.writeRtpDescription=function(e,i){let n="";n+="m="+e+" ",n+=i.codecs.length>0?"9":"0",n+=" "+(i.profile||"UDP/TLS/RTP/SAVPF")+" ",n+=i.codecs.map((e=>void 0!==e.preferredPayloadType?e.preferredPayloadType:e.payloadType)).join(" ")+"\r\n",n+="c=IN IP4 0.0.0.0\r\n",n+="a=rtcp:9 IN IP4 0.0.0.0\r\n",i.codecs.forEach((e=>{n+=t.writeRtpMap(e),n+=t.writeFmtp(e),n+=t.writeRtcpFb(e)}));let r=0;return i.codecs.forEach((e=>{e.maxptime>r&&(r=e.maxptime)})),r>0&&(n+="a=maxptime:"+r+"\r\n"),i.headerExtensions&&i.headerExtensions.forEach((e=>{n+=t.writeExtmap(e)})),n},t.parseRtpEncodingParameters=function(e){const i=[],n=t.parseRtpParameters(e),r=-1!==n.fecMechanisms.indexOf("RED"),s=-1!==n.fecMechanisms.indexOf("ULPFEC"),o=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"cname"===e.attribute)),a=o.length>0&&o[0].ssrc;let c;const d=t.matchPrefix(e,"a=ssrc-group:FID").map((e=>e.substring(17).split(" ").map((e=>parseInt(e,10)))));d.length>0&&d[0].length>1&&d[0][0]===a&&(c=d[0][1]),n.codecs.forEach((e=>{if("RTX"===e.name.toUpperCase()&&e.parameters.apt){let t={ssrc:a,codecPayloadType:parseInt(e.parameters.apt,10)};a&&c&&(t.rtx={ssrc:c}),i.push(t),r&&(t=JSON.parse(JSON.stringify(t)),t.fec={ssrc:a,mechanism:s?"red+ulpfec":"red"},i.push(t))}})),0===i.length&&a&&i.push({ssrc:a});let u=t.matchPrefix(e,"b=");return u.length&&(u=0===u[0].indexOf("b=TIAS:")?parseInt(u[0].substring(7),10):0===u[0].indexOf("b=AS:")?1e3*parseInt(u[0].substring(5),10)*.95-16e3:void 0,i.forEach((e=>{e.maxBitrate=u}))),i},t.parseRtcpParameters=function(e){const i={},n=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"cname"===e.attribute))[0];n&&(i.cname=n.value,i.ssrc=n.ssrc);const r=t.matchPrefix(e,"a=rtcp-rsize");i.reducedSize=r.length>0,i.compound=0===r.length;const s=t.matchPrefix(e,"a=rtcp-mux");return i.mux=s.length>0,i},t.writeRtcpParameters=function(e){let t="";return e.reducedSize&&(t+="a=rtcp-rsize\r\n"),e.mux&&(t+="a=rtcp-mux\r\n"),void 0!==e.ssrc&&e.cname&&(t+="a=ssrc:"+e.ssrc+" cname:"+e.cname+"\r\n"),t},t.parseMsid=function(e){let i;const n=t.matchPrefix(e,"a=msid:");if(1===n.length)return i=n[0].substring(7).split(" "),{stream:i[0],track:i[1]};const r=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"msid"===e.attribute));return r.length>0?(i=r[0].value.split(" "),{stream:i[0],track:i[1]}):void 0},t.parseSctpDescription=function(e){const i=t.parseMLine(e),n=t.matchPrefix(e,"a=max-message-size:");let r;n.length>0&&(r=parseInt(n[0].substring(19),10)),isNaN(r)&&(r=65536);const s=t.matchPrefix(e,"a=sctp-port:");if(s.length>0)return{port:parseInt(s[0].substring(12),10),protocol:i.fmt,maxMessageSize:r};const o=t.matchPrefix(e,"a=sctpmap:");if(o.length>0){const e=o[0].substring(10).split(" ");return{port:parseInt(e[0],10),protocol:e[1],maxMessageSize:r}}},t.writeSctpDescription=function(e,t){let i=[];return i="DTLS/SCTP"!==e.protocol?["m="+e.kind+" 9 "+e.protocol+" "+t.protocol+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctp-port:"+t.port+"\r\n"]:["m="+e.kind+" 9 "+e.protocol+" "+t.port+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctpmap:"+t.port+" "+t.protocol+" 65535\r\n"],void 0!==t.maxMessageSize&&i.push("a=max-message-size:"+t.maxMessageSize+"\r\n"),i.join("")},t.generateSessionId=function(){return Math.random().toString().substr(2,22)},t.writeSessionBoilerplate=function(e,i,n){let r;const s=void 0!==i?i:2;r=e||t.generateSessionId();return"v=0\r\no="+(n||"thisisadapterortc")+" "+r+" "+s+" IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\n"},t.getDirection=function(e,i){const n=t.splitLines(e);for(let e=0;e<n.length;e++)switch(n[e]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return n[e].substring(2)}return i?t.getDirection(i):"sendrecv"},t.getKind=function(e){return t.splitLines(e)[0].split(" ")[0].substring(2)},t.isRejected=function(e){return"0"===e.split(" ",2)[1]},t.parseMLine=function(e){const i=t.splitLines(e)[0].substring(2).split(" ");return{kind:i[0],port:parseInt(i[1],10),protocol:i[2],fmt:i.slice(3).join(" ")}},t.parseOLine=function(e){const i=t.matchPrefix(e,"o=")[0].substring(2).split(" ");return{username:i[0],sessionId:i[1],sessionVersion:parseInt(i[2],10),netType:i[3],addressType:i[4],address:i[5]}},t.isValidSDP=function(e){if("string"!=typeof e||0===e.length)return!1;const i=t.splitLines(e);for(let e=0;e<i.length;e++)if(i[e].length<2||"="!==i[e].charAt(1))return!1;return!0},e.exports=t}(Wi);var Gi=Wi.exports,Qi=n(Gi),Hi=t({__proto__:null,default:Qi},[Gi]);function Ki(e){if(!e.RTCIceCandidate||e.RTCIceCandidate&&"foundation"in e.RTCIceCandidate.prototype)return;const t=e.RTCIceCandidate;e.RTCIceCandidate=function(e){if("object"==typeof e&&e.candidate&&0===e.candidate.indexOf("a=")&&((e=JSON.parse(JSON.stringify(e))).candidate=e.candidate.substring(2)),e.candidate&&e.candidate.length){const i=new t(e),n=Qi.parseCandidate(e.candidate);for(const e in n)e in i||Object.defineProperty(i,e,{value:n[e]});return i.toJSON=function(){return{candidate:i.candidate,sdpMid:i.sdpMid,sdpMLineIndex:i.sdpMLineIndex,usernameFragment:i.usernameFragment}},i}return new t(e)},e.RTCIceCandidate.prototype=t.prototype,ii(e,"icecandidate",(t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new e.RTCIceCandidate(t.candidate),writable:"false"}),t)))}function Zi(e){!e.RTCIceCandidate||e.RTCIceCandidate&&"relayProtocol"in e.RTCIceCandidate.prototype||ii(e,"icecandidate",(e=>{if(e.candidate){const t=Qi.parseCandidate(e.candidate.candidate);"relay"===t.type&&(e.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[t.priority>>24])}return e}))}function zi(e,t){if(!e.RTCPeerConnection)return;"sctp"in e.RTCPeerConnection.prototype||Object.defineProperty(e.RTCPeerConnection.prototype,"sctp",{get(){return void 0===this._sctp?null:this._sctp}});const i=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,"chrome"===t.browser&&t.version>=76){const{sdpSemantics:e}=this.getConfiguration();"plan-b"===e&&Object.defineProperty(this,"sctp",{get(){return void 0===this._sctp?null:this._sctp},enumerable:!0,configurable:!0})}if(function(e){if(!e||!e.sdp)return!1;const t=Qi.splitSections(e.sdp);return t.shift(),t.some((e=>{const t=Qi.parseMLine(e);return t&&"application"===t.kind&&-1!==t.protocol.indexOf("SCTP")}))}(arguments[0])){const e=function(e){const t=e.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(null===t||t.length<2)return-1;const i=parseInt(t[1],10);return i!=i?-1:i}(arguments[0]),i=function(e){let i=65536;return"firefox"===t.browser&&(i=t.version<57?-1===e?16384:2147483637:t.version<60?57===t.version?65535:65536:2147483637),i}(e),n=function(e,i){let n=65536;"firefox"===t.browser&&57===t.version&&(n=65535);const r=Qi.matchPrefix(e.sdp,"a=max-message-size:");return r.length>0?n=parseInt(r[0].substring(19),10):"firefox"===t.browser&&-1!==i&&(n=2147483637),n}(arguments[0],e);let r;r=0===i&&0===n?Number.POSITIVE_INFINITY:0===i||0===n?Math.max(i,n):Math.min(i,n);const s={};Object.defineProperty(s,"maxMessageSize",{get:()=>r}),this._sctp=s}return i.apply(this,arguments)}}function Yi(e){if(!e.RTCPeerConnection||!("createDataChannel"in e.RTCPeerConnection.prototype))return;function t(e,t){const i=e.send;e.send=function(){const n=arguments[0],r=n.length||n.size||n.byteLength;if("open"===e.readyState&&t.sctp&&r>t.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+t.sctp.maxMessageSize+" bytes)");return i.apply(e,arguments)}}const i=e.RTCPeerConnection.prototype.createDataChannel;e.RTCPeerConnection.prototype.createDataChannel=function(){const e=i.apply(this,arguments);return t(e,this),e},ii(e,"datachannel",(e=>(t(e.channel,e.target),e)))}function Xi(e){if(!e.RTCPeerConnection||"connectionState"in e.RTCPeerConnection.prototype)return;const t=e.RTCPeerConnection.prototype;Object.defineProperty(t,"connectionState",{get(){return{completed:"connected",checking:"connecting"}[this.iceConnectionState]||this.iceConnectionState},enumerable:!0,configurable:!0}),Object.defineProperty(t,"onconnectionstatechange",{get(){return this._onconnectionstatechange||null},set(e){this._onconnectionstatechange&&(this.removeEventListener("connectionstatechange",this._onconnectionstatechange),delete this._onconnectionstatechange),e&&this.addEventListener("connectionstatechange",this._onconnectionstatechange=e)},enumerable:!0,configurable:!0}),["setLocalDescription","setRemoteDescription"].forEach((e=>{const i=t[e];t[e]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=e=>{const t=e.target;if(t._lastConnectionState!==t.connectionState){t._lastConnectionState=t.connectionState;const i=new Event("connectionstatechange",e);t.dispatchEvent(i)}return e},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),i.apply(this,arguments)}}))}function en(e,t){if(!e.RTCPeerConnection)return;if("chrome"===t.browser&&t.version>=71)return;if("safari"===t.browser&&t.version>=605)return;const i=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(t){if(t&&t.sdp&&-1!==t.sdp.indexOf("\na=extmap-allow-mixed")){const i=t.sdp.split("\n").filter((e=>"a=extmap-allow-mixed"!==e.trim())).join("\n");e.RTCSessionDescription&&t instanceof e.RTCSessionDescription?arguments[0]=new e.RTCSessionDescription({type:t.type,sdp:i}):t.sdp=i}return i.apply(this,arguments)}}function tn(e,t){if(!e.RTCPeerConnection||!e.RTCPeerConnection.prototype)return;const i=e.RTCPeerConnection.prototype.addIceCandidate;i&&0!==i.length&&(e.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?("chrome"===t.browser&&t.version<78||"firefox"===t.browser&&t.version<68||"safari"===t.browser)&&arguments[0]&&""===arguments[0].candidate?Promise.resolve():i.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}function nn(e,t){if(!e.RTCPeerConnection||!e.RTCPeerConnection.prototype)return;const i=e.RTCPeerConnection.prototype.setLocalDescription;i&&0!==i.length&&(e.RTCPeerConnection.prototype.setLocalDescription=function(){let e=arguments[0]||{};if("object"!=typeof e||e.type&&e.sdp)return i.apply(this,arguments);if(e={type:e.type,sdp:e.sdp},!e.type)switch(this.signalingState){case"stable":case"have-local-offer":case"have-remote-pranswer":e.type="offer";break;default:e.type="answer"}if(e.sdp||"offer"!==e.type&&"answer"!==e.type)return i.apply(this,[e]);return("offer"===e.type?this.createOffer:this.createAnswer).apply(this).then((e=>i.apply(this,[e])))})}var rn,sn,on,an=Object.freeze({__proto__:null,removeExtmapAllowMixed:en,shimAddIceCandidateNullOrEmpty:tn,shimConnectionState:Xi,shimMaxMessageSize:zi,shimParameterlessSetLocalDescription:nn,shimRTCIceCandidate:Ki,shimRTCIceCandidateRelayProtocol:Zi,shimSendThrowTypeError:Yi});function cn(e){switch(e){case 0:case"PUBLISHER":return rn.PUBLISHER;case 1:case"SUBSCRIBER":return rn.SUBSCRIBER;default:return rn.UNRECOGNIZED}}function dn(e){switch(e){case rn.PUBLISHER:return"PUBLISHER";case rn.SUBSCRIBER:return"SUBSCRIBER";case rn.UNRECOGNIZED:default:return"UNRECOGNIZED"}}function un(e){switch(e){case 0:case"ACTIVE":return sn.ACTIVE;case 1:case"PAUSED":return sn.PAUSED;default:return sn.UNRECOGNIZED}}function ln(e){switch(e){case 0:case"UDP":return on.UDP;case 1:case"TCP":return on.TCP;case 2:case"TLS":return on.TLS;default:return on.UNRECOGNIZED}}!function(){let{window:e}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{shimChrome:!0,shimFirefox:!0,shimSafari:!0};const i=si,n=function(e){const t={browser:null,version:null};if(void 0===e||!e.navigator)return t.browser="Not a browser.",t;const{navigator:i}=e;if(i.mozGetUserMedia)t.browser="firefox",t.version=ti(i.userAgent,/Firefox\/(\d+)\./,1);else if(i.webkitGetUserMedia||!1===e.isSecureContext&&e.webkitRTCPeerConnection)t.browser="chrome",t.version=ti(i.userAgent,/Chrom(e|ium)\/(\d+)\./,2);else{if(!e.RTCPeerConnection||!i.userAgent.match(/AppleWebKit\/(\d+)\./))return t.browser="Not a supported browser.",t;t.browser="safari",t.version=ti(i.userAgent,/AppleWebKit\/(\d+)\./,1),t.supportsUnifiedPlan=e.RTCRtpTransceiver&&"currentDirection"in e.RTCRtpTransceiver.prototype}return t}(e),r={browserDetails:n,commonShim:an,extractVersion:ti,disableLog:ni,disableWarnings:ri,sdp:Hi};switch(n.browser){case"chrome":if(!Ci||!Si||!t.shimChrome)return i("Chrome shim is not included in this adapter release."),r;if(null===n.version)return i("Chrome shim can not determine version, not shimming."),r;i("adapter.js shimming chrome."),r.browserShim=Ci,tn(e,n),nn(e),hi(e,n),pi(e),Si(e,n),mi(e),ki(e,n),fi(e),vi(e),gi(e),yi(e,n),Ki(e),Zi(e),Xi(e),zi(e,n),Yi(e),en(e,n);break;case"firefox":if(!Mi||!Pi||!t.shimFirefox)return i("Firefox shim is not included in this adapter release."),r;i("adapter.js shimming firefox."),r.browserShim=Mi,tn(e,n),nn(e),Ti(e,n),Pi(e,n),Ei(e),Ni(e),wi(e),Ri(e),Oi(e),Di(e),Ii(e),Ai(e),Ui(e),Ki(e),Xi(e),zi(e,n),Yi(e);break;case"safari":if(!qi||!t.shimSafari)return i("Safari shim is not included in this adapter release."),r;i("adapter.js shimming safari."),r.browserShim=qi,tn(e,n),nn(e),Fi(e),ji(e),xi(e),Li(e),_i(e),$i(e),Bi(e),Vi(e),Ki(e),Zi(e),zi(e,n),Yi(e),en(e,n);break;default:i("Unsupported browser!")}}({window:"undefined"==typeof window?void 0:window}),function(e){e[e.PUBLISHER=0]="PUBLISHER",e[e.SUBSCRIBER=1]="SUBSCRIBER",e[e.UNRECOGNIZED=-1]="UNRECOGNIZED"}(rn||(rn={})),function(e){e[e.ACTIVE=0]="ACTIVE",e[e.PAUSED=1]="PAUSED",e[e.UNRECOGNIZED=-1]="UNRECOGNIZED"}(sn||(sn={})),function(e){e[e.UDP=0]="UDP",e[e.TCP=1]="TCP",e[e.TLS=2]="TLS",e[e.UNRECOGNIZED=-1]="UNRECOGNIZED"}(on||(on={}));const hn={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:st.Writer.create();var i;switch(null===(i=e.message)||void 0===i?void 0:i.$case){case"offer":Tn.encode(e.message.offer,t.uint32(10).fork()).ldelim();break;case"answer":Tn.encode(e.message.answer,t.uint32(18).fork()).ldelim();break;case"trickle":vn.encode(e.message.trickle,t.uint32(26).fork()).ldelim();break;case"addTrack":fn.encode(e.message.addTrack,t.uint32(34).fork()).ldelim();break;case"mute":gn.encode(e.message.mute,t.uint32(42).fork()).ldelim();break;case"subscription":Pn.encode(e.message.subscription,t.uint32(50).fork()).ldelim();break;case"trackSetting":wn.encode(e.message.trackSetting,t.uint32(58).fork()).ldelim();break;case"leave":Rn.encode(e.message.leave,t.uint32(66).fork()).ldelim();break;case"updateLayers":Nn.encode(e.message.updateLayers,t.uint32(82).fork()).ldelim();break;case"subscriptionPermission":$n.encode(e.message.subscriptionPermission,t.uint32(90).fork()).ldelim();break;case"syncState":Vn.encode(e.message.syncState,t.uint32(98).fork()).ldelim();break;case"simulate":Wn.encode(e.message.simulate,t.uint32(106).fork()).ldelim();break;case"ping":t.uint32(112).int64(e.message.ping);break;case"updateMetadata":On.encode(e.message.updateMetadata,t.uint32(122).fork()).ldelim();break;case"pingReq":Gn.encode(e.message.pingReq,t.uint32(130).fork()).ldelim()}return t},decode(e,t){const i=e instanceof st.Reader?e:st.Reader.create(e);let n=void 0===t?i.len:i.pos+t;const r={message:void 0};for(;i.pos<n;){const e=i.uint32();switch(e>>>3){case 1:if(10!==e)break;r.message={$case:"offer",offer:Tn.decode(i,i.uint32())};continue;case 2:if(18!==e)break;r.message={$case:"answer",answer:Tn.decode(i,i.uint32())};continue;case 3:if(26!==e)break;r.message={$case:"trickle",trickle:vn.decode(i,i.uint32())};continue;case 4:if(34!==e)break;r.message={$case:"addTrack",addTrack:fn.decode(i,i.uint32())};continue;case 5:if(42!==e)break;r.message={$case:"mute",mute:gn.decode(i,i.uint32())};continue;case 6:if(50!==e)break;r.message={$case:"subscription",subscription:Pn.decode(i,i.uint32())};continue;case 7:if(58!==e)break;r.message={$case:"trackSetting",trackSetting:wn.decode(i,i.uint32())};continue;case 8:if(66!==e)break;r.message={$case:"leave",leave:Rn.decode(i,i.uint32())};continue;case 10:if(82!==e)break;r.message={$case:"updateLayers",updateLayers:Nn.decode(i,i.uint32())};continue;case 11:if(90!==e)break;r.message={$case:"subscriptionPermission",subscriptionPermission:$n.decode(i,i.uint32())};continue;case 12:if(98!==e)break;r.message={$case:"syncState",syncState:Vn.decode(i,i.uint32())};continue;case 13:if(106!==e)break;r.message={$case:"simulate",simulate:Wn.decode(i,i.uint32())};continue;case 14:if(112!==e)break;r.message={$case:"ping",ping:Yn(i.int64())};continue;case 15:if(122!==e)break;r.message={$case:"updateMetadata",updateMetadata:On.decode(i,i.uint32())};continue;case 16:if(130!==e)break;r.message={$case:"pingReq",pingReq:Gn.decode(i,i.uint32())};continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return r},fromJSON:e=>({message:Xn(e.offer)?{$case:"offer",offer:Tn.fromJSON(e.offer)}:Xn(e.answer)?{$case:"answer",answer:Tn.fromJSON(e.answer)}:Xn(e.trickle)?{$case:"trickle",trickle:vn.fromJSON(e.trickle)}:Xn(e.addTrack)?{$case:"addTrack",addTrack:fn.fromJSON(e.addTrack)}:Xn(e.mute)?{$case:"mute",mute:gn.fromJSON(e.mute)}:Xn(e.subscription)?{$case:"subscription",subscription:Pn.fromJSON(e.subscription)}:Xn(e.trackSetting)?{$case:"trackSetting",trackSetting:wn.fromJSON(e.trackSetting)}:Xn(e.leave)?{$case:"leave",leave:Rn.fromJSON(e.leave)}:Xn(e.updateLayers)?{$case:"updateLayers",updateLayers:Nn.fromJSON(e.updateLayers)}:Xn(e.subscriptionPermission)?{$case:"subscriptionPermission",subscriptionPermission:$n.fromJSON(e.subscriptionPermission)}:Xn(e.syncState)?{$case:"syncState",syncState:Vn.fromJSON(e.syncState)}:Xn(e.simulate)?{$case:"simulate",simulate:Wn.fromJSON(e.simulate)}:Xn(e.ping)?{$case:"ping",ping:Number(e.ping)}:Xn(e.updateMetadata)?{$case:"updateMetadata",updateMetadata:On.fromJSON(e.updateMetadata)}:Xn(e.pingReq)?{$case:"pingReq",pingReq:Gn.fromJSON(e.pingReq)}:void 0}),toJSON(e){var t,i,n,r,s,o,a,c,d,u,l,h,p,m,f,v,g,b,k,S,y,C,T,E,P,w,R,N,O,D,I,A,U,M,L,_,x,B,J,F,$,j,V,q;const W={};return"offer"===(null===(t=e.message)||void 0===t?void 0:t.$case)&&(W.offer=(null===(i=e.message)||void 0===i?void 0:i.offer)?Tn.toJSON(null===(n=e.message)||void 0===n?void 0:n.offer):void 0),"answer"===(null===(r=e.message)||void 0===r?void 0:r.$case)&&(W.answer=(null===(s=e.message)||void 0===s?void 0:s.answer)?Tn.toJSON(null===(o=e.message)||void 0===o?void 0:o.answer):void 0),"trickle"===(null===(a=e.message)||void 0===a?void 0:a.$case)&&(W.trickle=(null===(c=e.message)||void 0===c?void 0:c.trickle)?vn.toJSON(null===(d=e.message)||void 0===d?void 0:d.trickle):void 0),"addTrack"===(null===(u=e.message)||void 0===u?void 0:u.$case)&&(W.addTrack=(null===(l=e.message)||void 0===l?void 0:l.addTrack)?fn.toJSON(null===(h=e.message)||void 0===h?void 0:h.addTrack):void 0),"mute"===(null===(p=e.message)||void 0===p?void 0:p.$case)&&(W.mute=(null===(m=e.message)||void 0===m?void 0:m.mute)?gn.toJSON(null===(f=e.message)||void 0===f?void 0:f.mute):void 0),"subscription"===(null===(v=e.message)||void 0===v?void 0:v.$case)&&(W.subscription=(null===(g=e.message)||void 0===g?void 0:g.subscription)?Pn.toJSON(null===(b=e.message)||void 0===b?void 0:b.subscription):void 0),"trackSetting"===(null===(k=e.message)||void 0===k?void 0:k.$case)&&(W.trackSetting=(null===(S=e.message)||void 0===S?void 0:S.trackSetting)?wn.toJSON(null===(y=e.message)||void 0===y?void 0:y.trackSetting):void 0),"leave"===(null===(C=e.message)||void 0===C?void 0:C.$case)&&(W.leave=(null===(T=e.message)||void 0===T?void 0:T.leave)?Rn.toJSON(null===(E=e.message)||void 0===E?void 0:E.leave):void 0),"updateLayers"===(null===(P=e.message)||void 0===P?void 0:P.$case)&&(W.updateLayers=(null===(w=e.message)||void 0===w?void 0:w.updateLayers)?Nn.toJSON(null===(R=e.message)||void 0===R?void 0:R.updateLayers):void 0),"subscriptionPermission"===(null===(N=e.message)||void 0===N?void 0:N.$case)&&(W.subscriptionPermission=(null===(O=e.message)||void 0===O?void 0:O.subscriptionPermission)?$n.toJSON(null===(D=e.message)||void 0===D?void 0:D.subscriptionPermission):void 0),"syncState"===(null===(I=e.message)||void 0===I?void 0:I.$case)&&(W.syncState=(null===(A=e.message)||void 0===A?void 0:A.syncState)?Vn.toJSON(null===(U=e.message)||void 0===U?void 0:U.syncState):void 0),"simulate"===(null===(M=e.message)||void 0===M?void 0:M.$case)&&(W.simulate=(null===(L=e.message)||void 0===L?void 0:L.simulate)?Wn.toJSON(null===(_=e.message)||void 0===_?void 0:_.simulate):void 0),"ping"===(null===(x=e.message)||void 0===x?void 0:x.$case)&&(W.ping=Math.round(null===(B=e.message)||void 0===B?void 0:B.ping)),"updateMetadata"===(null===(J=e.message)||void 0===J?void 0:J.$case)&&(W.updateMetadata=(null===(F=e.message)||void 0===F?void 0:F.updateMetadata)?On.toJSON(null===($=e.message)||void 0===$?void 0:$.updateMetadata):void 0),"pingReq"===(null===(j=e.message)||void 0===j?void 0:j.$case)&&(W.pingReq=(null===(V=e.message)||void 0===V?void 0:V.pingReq)?Gn.toJSON(null===(q=e.message)||void 0===q?void 0:q.pingReq):void 0),W},create:e=>hn.fromPartial(null!=e?e:{}),fromPartial(e){var t,i,n,r,s,o,a,c,d,u,l,h,p,m,f,v,g,b,k,S,y,C,T,E,P,w,R,N,O,D,I,A,U,M,L,_,x,B,J,F,$,j,V,q,W;const G={message:void 0};return"offer"===(null===(t=e.message)||void 0===t?void 0:t.$case)&&void 0!==(null===(i=e.message)||void 0===i?void 0:i.offer)&&null!==(null===(n=e.message)||void 0===n?void 0:n.offer)&&(G.message={$case:"offer",offer:Tn.fromPartial(e.message.offer)}),"answer"===(null===(r=e.message)||void 0===r?void 0:r.$case)&&void 0!==(null===(s=e.message)||void 0===s?void 0:s.answer)&&null!==(null===(o=e.message)||void 0===o?void 0:o.answer)&&(G.message={$case:"answer",answer:Tn.fromPartial(e.message.answer)}),"trickle"===(null===(a=e.message)||void 0===a?void 0:a.$case)&&void 0!==(null===(c=e.message)||void 0===c?void 0:c.trickle)&&null!==(null===(d=e.message)||void 0===d?void 0:d.trickle)&&(G.message={$case:"trickle",trickle:vn.fromPartial(e.message.trickle)}),"addTrack"===(null===(u=e.message)||void 0===u?void 0:u.$case)&&void 0!==(null===(l=e.message)||void 0===l?void 0:l.addTrack)&&null!==(null===(h=e.message)||void 0===h?void 0:h.addTrack)&&(G.message={$case:"addTrack",addTrack:fn.fromPartial(e.message.addTrack)}),"mute"===(null===(p=e.message)||void 0===p?void 0:p.$case)&&void 0!==(null===(m=e.message)||void 0===m?void 0:m.mute)&&null!==(null===(f=e.message)||void 0===f?void 0:f.mute)&&(G.message={$case:"mute",mute:gn.fromPartial(e.message.mute)}),"subscription"===(null===(v=e.message)||void 0===v?void 0:v.$case)&&void 0!==(null===(g=e.message)||void 0===g?void 0:g.subscription)&&null!==(null===(b=e.message)||void 0===b?void 0:b.subscription)&&(G.message={$case:"subscription",subscription:Pn.fromPartial(e.message.subscription)}),"trackSetting"===(null===(k=e.message)||void 0===k?void 0:k.$case)&&void 0!==(null===(S=e.message)||void 0===S?void 0:S.trackSetting)&&null!==(null===(y=e.message)||void 0===y?void 0:y.trackSetting)&&(G.message={$case:"trackSetting",trackSetting:wn.fromPartial(e.message.trackSetting)}),"leave"===(null===(C=e.message)||void 0===C?void 0:C.$case)&&void 0!==(null===(T=e.message)||void 0===T?void 0:T.leave)&&null!==(null===(E=e.message)||void 0===E?void 0:E.leave)&&(G.message={$case:"leave",leave:Rn.fromPartial(e.message.leave)}),"updateLayers"===(null===(P=e.message)||void 0===P?void 0:P.$case)&&void 0!==(null===(w=e.message)||void 0===w?void 0:w.updateLayers)&&null!==(null===(R=e.message)||void 0===R?void 0:R.updateLayers)&&(G.message={$case:"updateLayers",updateLayers:Nn.fromPartial(e.message.updateLayers)}),"subscriptionPermission"===(null===(N=e.message)||void 0===N?void 0:N.$case)&&void 0!==(null===(O=e.message)||void 0===O?void 0:O.subscriptionPermission)&&null!==(null===(D=e.message)||void 0===D?void 0:D.subscriptionPermission)&&(G.message={$case:"subscriptionPermission",subscriptionPermission:$n.fromPartial(e.message.subscriptionPermission)}),"syncState"===(null===(I=e.message)||void 0===I?void 0:I.$case)&&void 0!==(null===(A=e.message)||void 0===A?void 0:A.syncState)&&null!==(null===(U=e.message)||void 0===U?void 0:U.syncState)&&(G.message={$case:"syncState",syncState:Vn.fromPartial(e.message.syncState)}),"simulate"===(null===(M=e.message)||void 0===M?void 0:M.$case)&&void 0!==(null===(L=e.message)||void 0===L?void 0:L.simulate)&&null!==(null===(_=e.message)||void 0===_?void 0:_.simulate)&&(G.message={$case:"simulate",simulate:Wn.fromPartial(e.message.simulate)}),"ping"===(null===(x=e.message)||void 0===x?void 0:x.$case)&&void 0!==(null===(B=e.message)||void 0===B?void 0:B.ping)&&null!==(null===(J=e.message)||void 0===J?void 0:J.ping)&&(G.message={$case:"ping",ping:e.message.ping}),"updateMetadata"===(null===(F=e.message)||void 0===F?void 0:F.$case)&&void 0!==(null===($=e.message)||void 0===$?void 0:$.updateMetadata)&&null!==(null===(j=e.message)||void 0===j?void 0:j.updateMetadata)&&(G.message={$case:"updateMetadata",updateMetadata:On.fromPartial(e.message.updateMetadata)}),"pingReq"===(null===(V=e.message)||void 0===V?void 0:V.$case)&&void 0!==(null===(q=e.message)||void 0===q?void 0:q.pingReq)&&null!==(null===(W=e.message)||void 0===W?void 0:W.pingReq)&&(G.message={$case:"pingReq",pingReq:Gn.fromPartial(e.message.pingReq)}),G}};const pn={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:st.Writer.create();var i;switch(null===(i=e.message)||void 0===i?void 0:i.$case){case"join":kn.encode(e.message.join,t.uint32(10).fork()).ldelim();break;case"answer":Tn.encode(e.message.answer,t.uint32(18).fork()).ldelim();break;case"offer":Tn.encode(e.message.offer,t.uint32(26).fork()).ldelim();break;case"trickle":vn.encode(e.message.trickle,t.uint32(34).fork()).ldelim();break;case"update":En.encode(e.message.update,t.uint32(42).fork()).ldelim();break;case"trackPublished":yn.encode(e.message.trackPublished,t.uint32(50).fork()).ldelim();break;case"leave":Rn.encode(e.message.leave,t.uint32(66).fork()).ldelim();break;case"mute":gn.encode(e.message.mute,t.uint32(74).fork()).ldelim();break;case"speakersChanged":In.encode(e.message.speakersChanged,t.uint32(82).fork()).ldelim();break;case"roomUpdate":An.encode(e.message.roomUpdate,t.uint32(90).fork()).ldelim();break;case"connectionQuality":Mn.encode(e.message.connectionQuality,t.uint32(98).fork()).ldelim();break;case"streamStateUpdate":_n.encode(e.message.streamStateUpdate,t.uint32(106).fork()).ldelim();break;case"subscribedQualityUpdate":Jn.encode(e.message.subscribedQualityUpdate,t.uint32(114).fork()).ldelim();break;case"subscriptionPermissionUpdate":jn.encode(e.message.subscriptionPermissionUpdate,t.uint32(122).fork()).ldelim();break;case"refreshToken":t.uint32(130).string(e.message.refreshToken);break;case"trackUnpublished":Cn.encode(e.message.trackUnpublished,t.uint32(138).fork()).ldelim();break;case"pong":t.uint32(144).int64(e.message.pong);break;case"reconnect":Sn.encode(e.message.reconnect,t.uint32(154).fork()).ldelim();break;case"pongResp":Qn.encode(e.message.pongResp,t.uint32(162).fork()).ldelim();break;case"subscriptionResponse":Hn.encode(e.message.subscriptionResponse,t.uint32(170).fork()).ldelim()}return t},decode(e,t){const i=e instanceof st.Reader?e:st.Reader.create(e);let n=void 0===t?i.len:i.pos+t;const r={message:void 0};for(;i.pos<n;){const e=i.uint32();switch(e>>>3){case 1:if(10!==e)break;r.message={$case:"join",join:kn.decode(i,i.uint32())};continue;case 2:if(18!==e)break;r.message={$case:"answer",answer:Tn.decode(i,i.uint32())};continue;case 3:if(26!==e)break;r.message={$case:"offer",offer:Tn.decode(i,i.uint32())};continue;case 4:if(34!==e)break;r.message={$case:"trickle",trickle:vn.decode(i,i.uint32())};continue;case 5:if(42!==e)break;r.message={$case:"update",update:En.decode(i,i.uint32())};continue;case 6:if(50!==e)break;r.message={$case:"trackPublished",trackPublished:yn.decode(i,i.uint32())};continue;case 8:if(66!==e)break;r.message={$case:"leave",leave:Rn.decode(i,i.uint32())};continue;case 9:if(74!==e)break;r.message={$case:"mute",mute:gn.decode(i,i.uint32())};continue;case 10:if(82!==e)break;r.message={$case:"speakersChanged",speakersChanged:In.decode(i,i.uint32())};continue;case 11:if(90!==e)break;r.message={$case:"roomUpdate",roomUpdate:An.decode(i,i.uint32())};continue;case 12:if(98!==e)break;r.message={$case:"connectionQuality",connectionQuality:Mn.decode(i,i.uint32())};continue;case 13:if(106!==e)break;r.message={$case:"streamStateUpdate",streamStateUpdate:_n.decode(i,i.uint32())};continue;case 14:if(114!==e)break;r.message={$case:"subscribedQualityUpdate",subscribedQualityUpdate:Jn.decode(i,i.uint32())};continue;case 15:if(122!==e)break;r.message={$case:"subscriptionPermissionUpdate",subscriptionPermissionUpdate:jn.decode(i,i.uint32())};continue;case 16:if(130!==e)break;r.message={$case:"refreshToken",refreshToken:i.string()};continue;case 17:if(138!==e)break;r.message={$case:"trackUnpublished",trackUnpublished:Cn.decode(i,i.uint32())};continue;case 18:if(144!==e)break;r.message={$case:"pong",pong:Yn(i.int64())};continue;case 19:if(154!==e)break;r.message={$case:"reconnect",reconnect:Sn.decode(i,i.uint32())};continue;case 20:if(162!==e)break;r.message={$case:"pongResp",pongResp:Qn.decode(i,i.uint32())};continue;case 21:if(170!==e)break;r.message={$case:"subscriptionResponse",subscriptionResponse:Hn.decode(i,i.uint32())};continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return r},fromJSON:e=>({message:Xn(e.join)?{$case:"join",join:kn.fromJSON(e.join)}:Xn(e.answer)?{$case:"answer",answer:Tn.fromJSON(e.answer)}:Xn(e.offer)?{$case:"offer",offer:Tn.fromJSON(e.offer)}:Xn(e.trickle)?{$case:"trickle",trickle:vn.fromJSON(e.trickle)}:Xn(e.update)?{$case:"update",update:En.fromJSON(e.update)}:Xn(e.trackPublished)?{$case:"trackPublished",trackPublished:yn.fromJSON(e.trackPublished)}:Xn(e.leave)?{$case:"leave",leave:Rn.fromJSON(e.leave)}:Xn(e.mute)?{$case:"mute",mute:gn.fromJSON(e.mute)}:Xn(e.speakersChanged)?{$case:"speakersChanged",speakersChanged:In.fromJSON(e.speakersChanged)}:Xn(e.roomUpdate)?{$case:"roomUpdate",roomUpdate:An.fromJSON(e.roomUpdate)}:Xn(e.connectionQuality)?{$case:"connectionQuality",connectionQuality:Mn.fromJSON(e.connectionQuality)}:Xn(e.streamStateUpdate)?{$case:"streamStateUpdate",streamStateUpdate:_n.fromJSON(e.streamStateUpdate)}:Xn(e.subscribedQualityUpdate)?{$case:"subscribedQualityUpdate",subscribedQualityUpdate:Jn.fromJSON(e.subscribedQualityUpdate)}:Xn(e.subscriptionPermissionUpdate)?{$case:"subscriptionPermissionUpdate",subscriptionPermissionUpdate:jn.fromJSON(e.subscriptionPermissionUpdate)}:Xn(e.refreshToken)?{$case:"refreshToken",refreshToken:String(e.refreshToken)}:Xn(e.trackUnpublished)?{$case:"trackUnpublished",trackUnpublished:Cn.fromJSON(e.trackUnpublished)}:Xn(e.pong)?{$case:"pong",pong:Number(e.pong)}:Xn(e.reconnect)?{$case:"reconnect",reconnect:Sn.fromJSON(e.reconnect)}:Xn(e.pongResp)?{$case:"pongResp",pongResp:Qn.fromJSON(e.pongResp)}:Xn(e.subscriptionResponse)?{$case:"subscriptionResponse",subscriptionResponse:Hn.fromJSON(e.subscriptionResponse)}:void 0}),toJSON(e){var t,i,n,r,s,o,a,c,d,u,l,h,p,m,f,v,g,b,k,S,y,C,T,E,P,w,R,N,O,D,I,A,U,M,L,_,x,B,J,F,$,j,V,q,W,G,Q,H,K,Z,z,Y,X,ee,te,ie,ne,re;const se={};return"join"===(null===(t=e.message)||void 0===t?void 0:t.$case)&&(se.join=(null===(i=e.message)||void 0===i?void 0:i.join)?kn.toJSON(null===(n=e.message)||void 0===n?void 0:n.join):void 0),"answer"===(null===(r=e.message)||void 0===r?void 0:r.$case)&&(se.answer=(null===(s=e.message)||void 0===s?void 0:s.answer)?Tn.toJSON(null===(o=e.message)||void 0===o?void 0:o.answer):void 0),"offer"===(null===(a=e.message)||void 0===a?void 0:a.$case)&&(se.offer=(null===(c=e.message)||void 0===c?void 0:c.offer)?Tn.toJSON(null===(d=e.message)||void 0===d?void 0:d.offer):void 0),"trickle"===(null===(u=e.message)||void 0===u?void 0:u.$case)&&(se.trickle=(null===(l=e.message)||void 0===l?void 0:l.trickle)?vn.toJSON(null===(h=e.message)||void 0===h?void 0:h.trickle):void 0),"update"===(null===(p=e.message)||void 0===p?void 0:p.$case)&&(se.update=(null===(m=e.message)||void 0===m?void 0:m.update)?En.toJSON(null===(f=e.message)||void 0===f?void 0:f.update):void 0),"trackPublished"===(null===(v=e.message)||void 0===v?void 0:v.$case)&&(se.trackPublished=(null===(g=e.message)||void 0===g?void 0:g.trackPublished)?yn.toJSON(null===(b=e.message)||void 0===b?void 0:b.trackPublished):void 0),"leave"===(null===(k=e.message)||void 0===k?void 0:k.$case)&&(se.leave=(null===(S=e.message)||void 0===S?void 0:S.leave)?Rn.toJSON(null===(y=e.message)||void 0===y?void 0:y.leave):void 0),"mute"===(null===(C=e.message)||void 0===C?void 0:C.$case)&&(se.mute=(null===(T=e.message)||void 0===T?void 0:T.mute)?gn.toJSON(null===(E=e.message)||void 0===E?void 0:E.mute):void 0),"speakersChanged"===(null===(P=e.message)||void 0===P?void 0:P.$case)&&(se.speakersChanged=(null===(w=e.message)||void 0===w?void 0:w.speakersChanged)?In.toJSON(null===(R=e.message)||void 0===R?void 0:R.speakersChanged):void 0),"roomUpdate"===(null===(N=e.message)||void 0===N?void 0:N.$case)&&(se.roomUpdate=(null===(O=e.message)||void 0===O?void 0:O.roomUpdate)?An.toJSON(null===(D=e.message)||void 0===D?void 0:D.roomUpdate):void 0),"connectionQuality"===(null===(I=e.message)||void 0===I?void 0:I.$case)&&(se.connectionQuality=(null===(A=e.message)||void 0===A?void 0:A.connectionQuality)?Mn.toJSON(null===(U=e.message)||void 0===U?void 0:U.connectionQuality):void 0),"streamStateUpdate"===(null===(M=e.message)||void 0===M?void 0:M.$case)&&(se.streamStateUpdate=(null===(L=e.message)||void 0===L?void 0:L.streamStateUpdate)?_n.toJSON(null===(_=e.message)||void 0===_?void 0:_.streamStateUpdate):void 0),"subscribedQualityUpdate"===(null===(x=e.message)||void 0===x?void 0:x.$case)&&(se.subscribedQualityUpdate=(null===(B=e.message)||void 0===B?void 0:B.subscribedQualityUpdate)?Jn.toJSON(null===(J=e.message)||void 0===J?void 0:J.subscribedQualityUpdate):void 0),"subscriptionPermissionUpdate"===(null===(F=e.message)||void 0===F?void 0:F.$case)&&(se.subscriptionPermissionUpdate=(null===($=e.message)||void 0===$?void 0:$.subscriptionPermissionUpdate)?jn.toJSON(null===(j=e.message)||void 0===j?void 0:j.subscriptionPermissionUpdate):void 0),"refreshToken"===(null===(V=e.message)||void 0===V?void 0:V.$case)&&(se.refreshToken=null===(q=e.message)||void 0===q?void 0:q.refreshToken),"trackUnpublished"===(null===(W=e.message)||void 0===W?void 0:W.$case)&&(se.trackUnpublished=(null===(G=e.message)||void 0===G?void 0:G.trackUnpublished)?Cn.toJSON(null===(Q=e.message)||void 0===Q?void 0:Q.trackUnpublished):void 0),"pong"===(null===(H=e.message)||void 0===H?void 0:H.$case)&&(se.pong=Math.round(null===(K=e.message)||void 0===K?void 0:K.pong)),"reconnect"===(null===(Z=e.message)||void 0===Z?void 0:Z.$case)&&(se.reconnect=(null===(z=e.message)||void 0===z?void 0:z.reconnect)?Sn.toJSON(null===(Y=e.message)||void 0===Y?void 0:Y.reconnect):void 0),"pongResp"===(null===(X=e.message)||void 0===X?void 0:X.$case)&&(se.pongResp=(null===(ee=e.message)||void 0===ee?void 0:ee.pongResp)?Qn.toJSON(null===(te=e.message)||void 0===te?void 0:te.pongResp):void 0),"subscriptionResponse"===(null===(ie=e.message)||void 0===ie?void 0:ie.$case)&&(se.subscriptionResponse=(null===(ne=e.message)||void 0===ne?void 0:ne.subscriptionResponse)?Hn.toJSON(null===(re=e.message)||void 0===re?void 0:re.subscriptionResponse):void 0),se},create:e=>pn.fromPartial(null!=e?e:{}),fromPartial(e){var t,i,n,r,s,o,a,c,d,u,l,h,p,m,f,v,g,b,k,S,y,C,T,E,P,w,R,N,O,D,I,A,U,M,L,_,x,B,J,F,$,j,V,q,W,G,Q,H,K,Z,z,Y,X,ee,te,ie,ne,re,se,oe;const ae={message:void 0};return"join"===(null===(t=e.message)||void 0===t?void 0:t.$case)&&void 0!==(null===(i=e.message)||void 0===i?void 0:i.join)&&null!==(null===(n=e.message)||void 0===n?void 0:n.join)&&(ae.message={$case:"join",join:kn.fromPartial(e.message.join)}),"answer"===(null===(r=e.message)||void 0===r?void 0:r.$case)&&void 0!==(null===(s=e.message)||void 0===s?void 0:s.answer)&&null!==(null===(o=e.message)||void 0===o?void 0:o.answer)&&(ae.message={$case:"answer",answer:Tn.fromPartial(e.message.answer)}),"offer"===(null===(a=e.message)||void 0===a?void 0:a.$case)&&void 0!==(null===(c=e.message)||void 0===c?void 0:c.offer)&&null!==(null===(d=e.message)||void 0===d?void 0:d.offer)&&(ae.message={$case:"offer",offer:Tn.fromPartial(e.message.offer)}),"trickle"===(null===(u=e.message)||void 0===u?void 0:u.$case)&&void 0!==(null===(l=e.message)||void 0===l?void 0:l.trickle)&&null!==(null===(h=e.message)||void 0===h?void 0:h.trickle)&&(ae.message={$case:"trickle",trickle:vn.fromPartial(e.message.trickle)}),"update"===(null===(p=e.message)||void 0===p?void 0:p.$case)&&void 0!==(null===(m=e.message)||void 0===m?void 0:m.update)&&null!==(null===(f=e.message)||void 0===f?void 0:f.update)&&(ae.message={$case:"update",update:En.fromPartial(e.message.update)}),"trackPublished"===(null===(v=e.message)||void 0===v?void 0:v.$case)&&void 0!==(null===(g=e.message)||void 0===g?void 0:g.trackPublished)&&null!==(null===(b=e.message)||void 0===b?void 0:b.trackPublished)&&(ae.message={$case:"trackPublished",trackPublished:yn.fromPartial(e.message.trackPublished)}),"leave"===(null===(k=e.message)||void 0===k?void 0:k.$case)&&void 0!==(null===(S=e.message)||void 0===S?void 0:S.leave)&&null!==(null===(y=e.message)||void 0===y?void 0:y.leave)&&(ae.message={$case:"leave",leave:Rn.fromPartial(e.message.leave)}),"mute"===(null===(C=e.message)||void 0===C?void 0:C.$case)&&void 0!==(null===(T=e.message)||void 0===T?void 0:T.mute)&&null!==(null===(E=e.message)||void 0===E?void 0:E.mute)&&(ae.message={$case:"mute",mute:gn.fromPartial(e.message.mute)}),"speakersChanged"===(null===(P=e.message)||void 0===P?void 0:P.$case)&&void 0!==(null===(w=e.message)||void 0===w?void 0:w.speakersChanged)&&null!==(null===(R=e.message)||void 0===R?void 0:R.speakersChanged)&&(ae.message={$case:"speakersChanged",speakersChanged:In.fromPartial(e.message.speakersChanged)}),"roomUpdate"===(null===(N=e.message)||void 0===N?void 0:N.$case)&&void 0!==(null===(O=e.message)||void 0===O?void 0:O.roomUpdate)&&null!==(null===(D=e.message)||void 0===D?void 0:D.roomUpdate)&&(ae.message={$case:"roomUpdate",roomUpdate:An.fromPartial(e.message.roomUpdate)}),"connectionQuality"===(null===(I=e.message)||void 0===I?void 0:I.$case)&&void 0!==(null===(A=e.message)||void 0===A?void 0:A.connectionQuality)&&null!==(null===(U=e.message)||void 0===U?void 0:U.connectionQuality)&&(ae.message={$case:"connectionQuality",connectionQuality:Mn.fromPartial(e.message.connectionQuality)}),"streamStateUpdate"===(null===(M=e.message)||void 0===M?void 0:M.$case)&&void 0!==(null===(L=e.message)||void 0===L?void 0:L.streamStateUpdate)&&null!==(null===(_=e.message)||void 0===_?void 0:_.streamStateUpdate)&&(ae.message={$case:"streamStateUpdate",streamStateUpdate:_n.fromPartial(e.message.streamStateUpdate)}),"subscribedQualityUpdate"===(null===(x=e.message)||void 0===x?void 0:x.$case)&&void 0!==(null===(B=e.message)||void 0===B?void 0:B.subscribedQualityUpdate)&&null!==(null===(J=e.message)||void 0===J?void 0:J.subscribedQualityUpdate)&&(ae.message={$case:"subscribedQualityUpdate",subscribedQualityUpdate:Jn.fromPartial(e.message.subscribedQualityUpdate)}),"subscriptionPermissionUpdate"===(null===(F=e.message)||void 0===F?void 0:F.$case)&&void 0!==(null===($=e.message)||void 0===$?void 0:$.subscriptionPermissionUpdate)&&null!==(null===(j=e.message)||void 0===j?void 0:j.subscriptionPermissionUpdate)&&(ae.message={$case:"subscriptionPermissionUpdate",subscriptionPermissionUpdate:jn.fromPartial(e.message.subscriptionPermissionUpdate)}),"refreshToken"===(null===(V=e.message)||void 0===V?void 0:V.$case)&&void 0!==(null===(q=e.message)||void 0===q?void 0:q.refreshToken)&&null!==(null===(W=e.message)||void 0===W?void 0:W.refreshToken)&&(ae.message={$case:"refreshToken",refreshToken:e.message.refreshToken}),"trackUnpublished"===(null===(G=e.message)||void 0===G?void 0:G.$case)&&void 0!==(null===(Q=e.message)||void 0===Q?void 0:Q.trackUnpublished)&&null!==(null===(H=e.message)||void 0===H?void 0:H.trackUnpublished)&&(ae.message={$case:"trackUnpublished",trackUnpublished:Cn.fromPartial(e.message.trackUnpublished)}),"pong"===(null===(K=e.message)||void 0===K?void 0:K.$case)&&void 0!==(null===(Z=e.message)||void 0===Z?void 0:Z.pong)&&null!==(null===(z=e.message)||void 0===z?void 0:z.pong)&&(ae.message={$case:"pong",pong:e.message.pong}),"reconnect"===(null===(Y=e.message)||void 0===Y?void 0:Y.$case)&&void 0!==(null===(X=e.message)||void 0===X?void 0:X.reconnect)&&null!==(null===(ee=e.message)||void 0===ee?void 0:ee.reconnect)&&(ae.message={$case:"reconnect",reconnect:Sn.fromPartial(e.message.reconnect)}),"pongResp"===(null===(te=e.message)||void 0===te?void 0:te.$case)&&void 0!==(null===(ie=e.message)||void 0===ie?void 0:ie.pongResp)&&null!==(null===(ne=e.message)||void 0===ne?void 0:ne.pongResp)&&(ae.message={$case:"pongResp",pongResp:Qn.fromPartial(e.message.pongResp)}),"subscriptionResponse"===(null===(re=e.message)||void 0===re?void 0:re.$case)&&void 0!==(null===(se=e.message)||void 0===se?void 0:se.subscriptionResponse)&&null!==(null===(oe=e.message)||void 0===oe?void 0:oe.subscriptionResponse)&&(ae.message={$case:"subscriptionResponse",subscriptionResponse:Hn.fromPartial(e.message.subscriptionResponse)}),ae}};const mn={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:st.Writer.create();return""!==e.codec&&t.uint32(10).string(e.codec),""!==e.cid&&t.uint32(18).string(e.cid),!0===e.enableSimulcastLayers&&t.uint32(24).bool(e.enableSimulcastLayers),t},decode(e,t){const i=e instanceof st.Reader?e:st.Reader.create(e);let n=void 0===t?i.len:i.pos+t;const r={codec:"",cid:"",enableSimulcastLayers:!1};for(;i.pos<n;){const e=i.uint32();switch(e>>>3){case 1:if(10!==e)break;r.codec=i.string();continue;case 2:if(18!==e)break;r.cid=i.string();continue;case 3:if(24!==e)break;r.enableSimulcastLayers=i.bool();continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return r},fromJSON:e=>({codec:Xn(e.codec)?String(e.codec):"",cid:Xn(e.cid)?String(e.cid):"",enableSimulcastLayers:!!Xn(e.enableSimulcastLayers)&&Boolean(e.enableSimulcastLayers)}),toJSON(e){const t={};return void 0!==e.codec&&(t.codec=e.codec),void 0!==e.cid&&(t.cid=e.cid),void 0!==e.enableSimulcastLayers&&(t.enableSimulcastLayers=e.enableSimulcastLayers),t},create:e=>mn.fromPartial(null!=e?e:{}),fromPartial(e){var t,i,n;const r={codec:"",cid:"",enableSimulcastLayers:!1};return r.codec=null!==(t=e.codec)&&void 0!==t?t:"",r.cid=null!==(i=e.cid)&&void 0!==i?i:"",r.enableSimulcastLayers=null!==(n=e.enableSimulcastLayers)&&void 0!==n&&n,r}};const fn={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:st.Writer.create();""!==e.cid&&t.uint32(10).string(e.cid),""!==e.name&&t.uint32(18).string(e.name),0!==e.type&&t.uint32(24).int32(e.type),0!==e.width&&t.uint32(32).uint32(e.width),0!==e.height&&t.uint32(40).uint32(e.height),!0===e.muted&&t.uint32(48).bool(e.muted),!0===e.disableDtx&&t.uint32(56).bool(e.disableDtx),0!==e.source&&t.uint32(64).int32(e.source);for(const i of e.layers)Ot.encode(i,t.uint32(74).fork()).ldelim();for(const i of e.simulcastCodecs)mn.encode(i,t.uint32(82).fork()).ldelim();return""!==e.sid&&t.uint32(90).string(e.sid),!0===e.stereo&&t.uint32(96).bool(e.stereo),!0===e.disableRed&&t.uint32(104).bool(e.disableRed),0!==e.encryption&&t.uint32(112).int32(e.encryption),t},decode(e,t){const i=e instanceof st.Reader?e:st.Reader.create(e);let n=void 0===t?i.len:i.pos+t;const r={cid:"",name:"",type:0,width:0,height:0,muted:!1,disableDtx:!1,source:0,layers:[],simulcastCodecs:[],sid:"",stereo:!1,disableRed:!1,encryption:0};for(;i.pos<n;){const e=i.uint32();switch(e>>>3){case 1:if(10!==e)break;r.cid=i.string();continue;case 2:if(18!==e)break;r.name=i.string();continue;case 3:if(24!==e)break;r.type=i.int32();continue;case 4:if(32!==e)break;r.width=i.uint32();continue;case 5:if(40!==e)break;r.height=i.uint32();continue;case 6:if(48!==e)break;r.muted=i.bool();continue;case 7:if(56!==e)break;r.disableDtx=i.bool();continue;case 8:if(64!==e)break;r.source=i.int32();continue;case 9:if(74!==e)break;r.layers.push(Ot.decode(i,i.uint32()));continue;case 10:if(82!==e)break;r.simulcastCodecs.push(mn.decode(i,i.uint32()));continue;case 11:if(90!==e)break;r.sid=i.string();continue;case 12:if(96!==e)break;r.stereo=i.bool();continue;case 13:if(104!==e)break;r.disableRed=i.bool();continue;case 14:if(112!==e)break;r.encryption=i.int32();continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return r},fromJSON:e=>({cid:Xn(e.cid)?String(e.cid):"",name:Xn(e.name)?String(e.name):"",type:Xn(e.type)?ot(e.type):0,width:Xn(e.width)?Number(e.width):0,height:Xn(e.height)?Number(e.height):0,muted:!!Xn(e.muted)&&Boolean(e.muted),disableDtx:!!Xn(e.disableDtx)&&Boolean(e.disableDtx),source:Xn(e.source)?ct(e.source):0,layers:Array.isArray(null==e?void 0:e.layers)?e.layers.map((e=>Ot.fromJSON(e))):[],simulcastCodecs:Array.isArray(null==e?void 0:e.simulcastCodecs)?e.simulcastCodecs.map((e=>mn.fromJSON(e))):[],sid:Xn(e.sid)?String(e.sid):"",stereo:!!Xn(e.stereo)&&Boolean(e.stereo),disableRed:!!Xn(e.disableRed)&&Boolean(e.disableRed),encryption:Xn(e.encryption)?bt(e.encryption):0}),toJSON(e){const t={};return void 0!==e.cid&&(t.cid=e.cid),void 0!==e.name&&(t.name=e.name),void 0!==e.type&&(t.type=at(e.type)),void 0!==e.width&&(t.width=Math.round(e.width)),void 0!==e.height&&(t.height=Math.round(e.height)),void 0!==e.muted&&(t.muted=e.muted),void 0!==e.disableDtx&&(t.disableDtx=e.disableDtx),void 0!==e.source&&(t.source=dt(e.source)),e.layers?t.layers=e.layers.map((e=>e?Ot.toJSON(e):void 0)):t.layers=[],e.simulcastCodecs?t.simulcastCodecs=e.simulcastCodecs.map((e=>e?mn.toJSON(e):void 0)):t.simulcastCodecs=[],void 0!==e.sid&&(t.sid=e.sid),void 0!==e.stereo&&(t.stereo=e.stereo),void 0!==e.disableRed&&(t.disableRed=e.disableRed),void 0!==e.encryption&&(t.encryption=kt(e.encryption)),t},create:e=>fn.fromPartial(null!=e?e:{}),fromPartial(e){var t,i,n,r,s,o,a,c,d,u,l,h,p,m;const f={cid:"",name:"",type:0,width:0,height:0,muted:!1,disableDtx:!1,source:0,layers:[],simulcastCodecs:[],sid:"",stereo:!1,disableRed:!1,encryption:0};return f.cid=null!==(t=e.cid)&&void 0!==t?t:"",f.name=null!==(i=e.name)&&void 0!==i?i:"",f.type=null!==(n=e.type)&&void 0!==n?n:0,f.width=null!==(r=e.width)&&void 0!==r?r:0,f.height=null!==(s=e.height)&&void 0!==s?s:0,f.muted=null!==(o=e.muted)&&void 0!==o&&o,f.disableDtx=null!==(a=e.disableDtx)&&void 0!==a&&a,f.source=null!==(c=e.source)&&void 0!==c?c:0,f.layers=(null===(d=e.layers)||void 0===d?void 0:d.map((e=>Ot.fromPartial(e))))||[],f.simulcastCodecs=(null===(u=e.simulcastCodecs)||void 0===u?void 0:u.map((e=>mn.fromPartial(e))))||[],f.sid=null!==(l=e.sid)&&void 0!==l?l:"",f.stereo=null!==(h=e.stereo)&&void 0!==h&&h,f.disableRed=null!==(p=e.disableRed)&&void 0!==p&&p,f.encryption=null!==(m=e.encryption)&&void 0!==m?m:0,f}};const vn={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:st.Writer.create();return""!==e.candidateInit&&t.uint32(10).string(e.candidateInit),0!==e.target&&t.uint32(16).int32(e.target),t},decode(e,t){const i=e instanceof st.Reader?e:st.Reader.create(e);let n=void 0===t?i.len:i.pos+t;const r={candidateInit:"",target:0};for(;i.pos<n;){const e=i.uint32();switch(e>>>3){case 1:if(10!==e)break;r.candidateInit=i.string();continue;case 2:if(16!==e)break;r.target=i.int32();continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return r},fromJSON:e=>({candidateInit:Xn(e.candidateInit)?String(e.candidateInit):"",target:Xn(e.target)?cn(e.target):0}),toJSON(e){const t={};return void 0!==e.candidateInit&&(t.candidateInit=e.candidateInit),void 0!==e.target&&(t.target=dn(e.target)),t},create:e=>vn.fromPartial(null!=e?e:{}),fromPartial(e){var t,i;const n={candidateInit:"",target:0};return n.candidateInit=null!==(t=e.candidateInit)&&void 0!==t?t:"",n.target=null!==(i=e.target)&&void 0!==i?i:0,n}};const gn={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:st.Writer.create();return""!==e.sid&&t.uint32(10).string(e.sid),!0===e.muted&&t.uint32(16).bool(e.muted),t},decode(e,t){const i=e instanceof st.Reader?e:st.Reader.create(e);let n=void 0===t?i.len:i.pos+t;const r={sid:"",muted:!1};for(;i.pos<n;){const e=i.uint32();switch(e>>>3){case 1:if(10!==e)break;r.sid=i.string();continue;case 2:if(16!==e)break;r.muted=i.bool();continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return r},fromJSON:e=>({sid:Xn(e.sid)?String(e.sid):"",muted:!!Xn(e.muted)&&Boolean(e.muted)}),toJSON(e){const t={};return void 0!==e.sid&&(t.sid=e.sid),void 0!==e.muted&&(t.muted=e.muted),t},create:e=>gn.fromPartial(null!=e?e:{}),fromPartial(e){var t,i;const n={sid:"",muted:!1};return n.sid=null!==(t=e.sid)&&void 0!==t?t:"",n.muted=null!==(i=e.muted)&&void 0!==i&&i,n}};function bn(){return{room:void 0,participant:void 0,otherParticipants:[],serverVersion:"",iceServers:[],subscriberPrimary:!1,alternativeUrl:"",clientConfiguration:void 0,serverRegion:"",pingTimeout:0,pingInterval:0,serverInfo:void 0,sifTrailer:new Uint8Array}}const kn={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:st.Writer.create();void 0!==e.room&&Tt.encode(e.room,t.uint32(10).fork()).ldelim(),void 0!==e.participant&&wt.encode(e.participant,t.uint32(18).fork()).ldelim();for(const i of e.otherParticipants)wt.encode(i,t.uint32(26).fork()).ldelim();""!==e.serverVersion&&t.uint32(34).string(e.serverVersion);for(const i of e.iceServers)Dn.encode(i,t.uint32(42).fork()).ldelim();return!0===e.subscriberPrimary&&t.uint32(48).bool(e.subscriberPrimary),""!==e.alternativeUrl&&t.uint32(58).string(e.alternativeUrl),void 0!==e.clientConfiguration&&Bt.encode(e.clientConfiguration,t.uint32(66).fork()).ldelim(),""!==e.serverRegion&&t.uint32(74).string(e.serverRegion),0!==e.pingTimeout&&t.uint32(80).int32(e.pingTimeout),0!==e.pingInterval&&t.uint32(88).int32(e.pingInterval),void 0!==e.serverInfo&&_t.encode(e.serverInfo,t.uint32(98).fork()).ldelim(),0!==e.sifTrailer.length&&t.uint32(106).bytes(e.sifTrailer),t},decode(e,t){const i=e instanceof st.Reader?e:st.Reader.create(e);let n=void 0===t?i.len:i.pos+t;const r=bn();for(;i.pos<n;){const e=i.uint32();switch(e>>>3){case 1:if(10!==e)break;r.room=Tt.decode(i,i.uint32());continue;case 2:if(18!==e)break;r.participant=wt.decode(i,i.uint32());continue;case 3:if(26!==e)break;r.otherParticipants.push(wt.decode(i,i.uint32()));continue;case 4:if(34!==e)break;r.serverVersion=i.string();continue;case 5:if(42!==e)break;r.iceServers.push(Dn.decode(i,i.uint32()));continue;case 6:if(48!==e)break;r.subscriberPrimary=i.bool();continue;case 7:if(58!==e)break;r.alternativeUrl=i.string();continue;case 8:if(66!==e)break;r.clientConfiguration=Bt.decode(i,i.uint32());continue;case 9:if(74!==e)break;r.serverRegion=i.string();continue;case 10:if(80!==e)break;r.pingTimeout=i.int32();continue;case 11:if(88!==e)break;r.pingInterval=i.int32();continue;case 12:if(98!==e)break;r.serverInfo=_t.decode(i,i.uint32());continue;case 13:if(106!==e)break;r.sifTrailer=i.bytes();continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return r},fromJSON:e=>({room:Xn(e.room)?Tt.fromJSON(e.room):void 0,participant:Xn(e.participant)?wt.fromJSON(e.participant):void 0,otherParticipants:Array.isArray(null==e?void 0:e.otherParticipants)?e.otherParticipants.map((e=>wt.fromJSON(e))):[],serverVersion:Xn(e.serverVersion)?String(e.serverVersion):"",iceServers:Array.isArray(null==e?void 0:e.iceServers)?e.iceServers.map((e=>Dn.fromJSON(e))):[],subscriberPrimary:!!Xn(e.subscriberPrimary)&&Boolean(e.subscriberPrimary),alternativeUrl:Xn(e.alternativeUrl)?String(e.alternativeUrl):"",clientConfiguration:Xn(e.clientConfiguration)?Bt.fromJSON(e.clientConfiguration):void 0,serverRegion:Xn(e.serverRegion)?String(e.serverRegion):"",pingTimeout:Xn(e.pingTimeout)?Number(e.pingTimeout):0,pingInterval:Xn(e.pingInterval)?Number(e.pingInterval):0,serverInfo:Xn(e.serverInfo)?_t.fromJSON(e.serverInfo):void 0,sifTrailer:Xn(e.sifTrailer)?zn(e.sifTrailer):new Uint8Array}),toJSON(e){const t={};return void 0!==e.room&&(t.room=e.room?Tt.toJSON(e.room):void 0),void 0!==e.participant&&(t.participant=e.participant?wt.toJSON(e.participant):void 0),e.otherParticipants?t.otherParticipants=e.otherParticipants.map((e=>e?wt.toJSON(e):void 0)):t.otherParticipants=[],void 0!==e.serverVersion&&(t.serverVersion=e.serverVersion),e.iceServers?t.iceServers=e.iceServers.map((e=>e?Dn.toJSON(e):void 0)):t.iceServers=[],void 0!==e.subscriberPrimary&&(t.subscriberPrimary=e.subscriberPrimary),void 0!==e.alternativeUrl&&(t.alternativeUrl=e.alternativeUrl),void 0!==e.clientConfiguration&&(t.clientConfiguration=e.clientConfiguration?Bt.toJSON(e.clientConfiguration):void 0),void 0!==e.serverRegion&&(t.serverRegion=e.serverRegion),void 0!==e.pingTimeout&&(t.pingTimeout=Math.round(e.pingTimeout)),void 0!==e.pingInterval&&(t.pingInterval=Math.round(e.pingInterval)),void 0!==e.serverInfo&&(t.serverInfo=e.serverInfo?_t.toJSON(e.serverInfo):void 0),void 0!==e.sifTrailer&&(t.sifTrailer=function(e){if(Zn.Buffer)return Zn.Buffer.from(e).toString("base64");{const t=[];return e.forEach((e=>{t.push(String.fromCharCode(e))})),Zn.btoa(t.join(""))}}(void 0!==e.sifTrailer?e.sifTrailer:new Uint8Array)),t},create:e=>kn.fromPartial(null!=e?e:{}),fromPartial(e){var t,i,n,r,s,o,a,c,d;const u=bn();return u.room=void 0!==e.room&&null!==e.room?Tt.fromPartial(e.room):void 0,u.participant=void 0!==e.participant&&null!==e.participant?wt.fromPartial(e.participant):void 0,u.otherParticipants=(null===(t=e.otherParticipants)||void 0===t?void 0:t.map((e=>wt.fromPartial(e))))||[],u.serverVersion=null!==(i=e.serverVersion)&&void 0!==i?i:"",u.iceServers=(null===(n=e.iceServers)||void 0===n?void 0:n.map((e=>Dn.fromPartial(e))))||[],u.subscriberPrimary=null!==(r=e.subscriberPrimary)&&void 0!==r&&r,u.alternativeUrl=null!==(s=e.alternativeUrl)&&void 0!==s?s:"",u.clientConfiguration=void 0!==e.clientConfiguration&&null!==e.clientConfiguration?Bt.fromPartial(e.clientConfiguration):void 0,u.serverRegion=null!==(o=e.serverRegion)&&void 0!==o?o:"",u.pingTimeout=null!==(a=e.pingTimeout)&&void 0!==a?a:0,u.pingInterval=null!==(c=e.pingInterval)&&void 0!==c?c:0,u.serverInfo=void 0!==e.serverInfo&&null!==e.serverInfo?_t.fromPartial(e.serverInfo):void 0,u.sifTrailer=null!==(d=e.sifTrailer)&&void 0!==d?d:new Uint8Array,u}};const Sn={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:st.Writer.create();for(const i of e.iceServers)Dn.encode(i,t.uint32(10).fork()).ldelim();return void 0!==e.clientConfiguration&&Bt.encode(e.clientConfiguration,t.uint32(18).fork()).ldelim(),t},decode(e,t){const i=e instanceof st.Reader?e:st.Reader.create(e);let n=void 0===t?i.len:i.pos+t;const r={iceServers:[],clientConfiguration:void 0};for(;i.pos<n;){const e=i.uint32();switch(e>>>3){case 1:if(10!==e)break;r.iceServers.push(Dn.decode(i,i.uint32()));continue;case 2:if(18!==e)break;r.clientConfiguration=Bt.decode(i,i.uint32());continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return r},fromJSON:e=>({iceServers:Array.isArray(null==e?void 0:e.iceServers)?e.iceServers.map((e=>Dn.fromJSON(e))):[],clientConfiguration:Xn(e.clientConfiguration)?Bt.fromJSON(e.clientConfiguration):void 0}),toJSON(e){const t={};return e.iceServers?t.iceServers=e.iceServers.map((e=>e?Dn.toJSON(e):void 0)):t.iceServers=[],void 0!==e.clientConfiguration&&(t.clientConfiguration=e.clientConfiguration?Bt.toJSON(e.clientConfiguration):void 0),t},create:e=>Sn.fromPartial(null!=e?e:{}),fromPartial(e){var t;const i={iceServers:[],clientConfiguration:void 0};return i.iceServers=(null===(t=e.iceServers)||void 0===t?void 0:t.map((e=>Dn.fromPartial(e))))||[],i.clientConfiguration=void 0!==e.clientConfiguration&&null!==e.clientConfiguration?Bt.fromPartial(e.clientConfiguration):void 0,i}};const yn={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:st.Writer.create();return""!==e.cid&&t.uint32(10).string(e.cid),void 0!==e.track&&Nt.encode(e.track,t.uint32(18).fork()).ldelim(),t},decode(e,t){const i=e instanceof st.Reader?e:st.Reader.create(e);let n=void 0===t?i.len:i.pos+t;const r={cid:"",track:void 0};for(;i.pos<n;){const e=i.uint32();switch(e>>>3){case 1:if(10!==e)break;r.cid=i.string();continue;case 2:if(18!==e)break;r.track=Nt.decode(i,i.uint32());continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return r},fromJSON:e=>({cid:Xn(e.cid)?String(e.cid):"",track:Xn(e.track)?Nt.fromJSON(e.track):void 0}),toJSON(e){const t={};return void 0!==e.cid&&(t.cid=e.cid),void 0!==e.track&&(t.track=e.track?Nt.toJSON(e.track):void 0),t},create:e=>yn.fromPartial(null!=e?e:{}),fromPartial(e){var t;const i={cid:"",track:void 0};return i.cid=null!==(t=e.cid)&&void 0!==t?t:"",i.track=void 0!==e.track&&null!==e.track?Nt.fromPartial(e.track):void 0,i}};const Cn={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:st.Writer.create();return""!==e.trackSid&&t.uint32(10).string(e.trackSid),t},decode(e,t){const i=e instanceof st.Reader?e:st.Reader.create(e);let n=void 0===t?i.len:i.pos+t;const r={trackSid:""};for(;i.pos<n;){const e=i.uint32();switch(e>>>3){case 1:if(10!==e)break;r.trackSid=i.string();continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return r},fromJSON:e=>({trackSid:Xn(e.trackSid)?String(e.trackSid):""}),toJSON(e){const t={};return void 0!==e.trackSid&&(t.trackSid=e.trackSid),t},create:e=>Cn.fromPartial(null!=e?e:{}),fromPartial(e){var t;const i={trackSid:""};return i.trackSid=null!==(t=e.trackSid)&&void 0!==t?t:"",i}};const Tn={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:st.Writer.create();return""!==e.type&&t.uint32(10).string(e.type),""!==e.sdp&&t.uint32(18).string(e.sdp),t},decode(e,t){const i=e instanceof st.Reader?e:st.Reader.create(e);let n=void 0===t?i.len:i.pos+t;const r={type:"",sdp:""};for(;i.pos<n;){const e=i.uint32();switch(e>>>3){case 1:if(10!==e)break;r.type=i.string();continue;case 2:if(18!==e)break;r.sdp=i.string();continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return r},fromJSON:e=>({type:Xn(e.type)?String(e.type):"",sdp:Xn(e.sdp)?String(e.sdp):""}),toJSON(e){const t={};return void 0!==e.type&&(t.type=e.type),void 0!==e.sdp&&(t.sdp=e.sdp),t},create:e=>Tn.fromPartial(null!=e?e:{}),fromPartial(e){var t,i;const n={type:"",sdp:""};return n.type=null!==(t=e.type)&&void 0!==t?t:"",n.sdp=null!==(i=e.sdp)&&void 0!==i?i:"",n}};const En={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:st.Writer.create();for(const i of e.participants)wt.encode(i,t.uint32(10).fork()).ldelim();return t},decode(e,t){const i=e instanceof st.Reader?e:st.Reader.create(e);let n=void 0===t?i.len:i.pos+t;const r={participants:[]};for(;i.pos<n;){const e=i.uint32();switch(e>>>3){case 1:if(10!==e)break;r.participants.push(wt.decode(i,i.uint32()));continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return r},fromJSON:e=>({participants:Array.isArray(null==e?void 0:e.participants)?e.participants.map((e=>wt.fromJSON(e))):[]}),toJSON(e){const t={};return e.participants?t.participants=e.participants.map((e=>e?wt.toJSON(e):void 0)):t.participants=[],t},create:e=>En.fromPartial(null!=e?e:{}),fromPartial(e){var t;const i={participants:[]};return i.participants=(null===(t=e.participants)||void 0===t?void 0:t.map((e=>wt.fromPartial(e))))||[],i}};const Pn={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:st.Writer.create();for(const i of e.trackSids)t.uint32(10).string(i);!0===e.subscribe&&t.uint32(16).bool(e.subscribe);for(const i of e.participantTracks)Lt.encode(i,t.uint32(26).fork()).ldelim();return t},decode(e,t){const i=e instanceof st.Reader?e:st.Reader.create(e);let n=void 0===t?i.len:i.pos+t;const r={trackSids:[],subscribe:!1,participantTracks:[]};for(;i.pos<n;){const e=i.uint32();switch(e>>>3){case 1:if(10!==e)break;r.trackSids.push(i.string());continue;case 2:if(16!==e)break;r.subscribe=i.bool();continue;case 3:if(26!==e)break;r.participantTracks.push(Lt.decode(i,i.uint32()));continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return r},fromJSON:e=>({trackSids:Array.isArray(null==e?void 0:e.trackSids)?e.trackSids.map((e=>String(e))):[],subscribe:!!Xn(e.subscribe)&&Boolean(e.subscribe),participantTracks:Array.isArray(null==e?void 0:e.participantTracks)?e.participantTracks.map((e=>Lt.fromJSON(e))):[]}),toJSON(e){const t={};return e.trackSids?t.trackSids=e.trackSids.map((e=>e)):t.trackSids=[],void 0!==e.subscribe&&(t.subscribe=e.subscribe),e.participantTracks?t.participantTracks=e.participantTracks.map((e=>e?Lt.toJSON(e):void 0)):t.participantTracks=[],t},create:e=>Pn.fromPartial(null!=e?e:{}),fromPartial(e){var t,i,n;const r={trackSids:[],subscribe:!1,participantTracks:[]};return r.trackSids=(null===(t=e.trackSids)||void 0===t?void 0:t.map((e=>e)))||[],r.subscribe=null!==(i=e.subscribe)&&void 0!==i&&i,r.participantTracks=(null===(n=e.participantTracks)||void 0===n?void 0:n.map((e=>Lt.fromPartial(e))))||[],r}};const wn={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:st.Writer.create();for(const i of e.trackSids)t.uint32(10).string(i);return!0===e.disabled&&t.uint32(24).bool(e.disabled),0!==e.quality&&t.uint32(32).int32(e.quality),0!==e.width&&t.uint32(40).uint32(e.width),0!==e.height&&t.uint32(48).uint32(e.height),0!==e.fps&&t.uint32(56).uint32(e.fps),0!==e.priority&&t.uint32(64).uint32(e.priority),t},decode(e,t){const i=e instanceof st.Reader?e:st.Reader.create(e);let n=void 0===t?i.len:i.pos+t;const r={trackSids:[],disabled:!1,quality:0,width:0,height:0,fps:0,priority:0};for(;i.pos<n;){const e=i.uint32();switch(e>>>3){case 1:if(10!==e)break;r.trackSids.push(i.string());continue;case 3:if(24!==e)break;r.disabled=i.bool();continue;case 4:if(32!==e)break;r.quality=i.int32();continue;case 5:if(40!==e)break;r.width=i.uint32();continue;case 6:if(48!==e)break;r.height=i.uint32();continue;case 7:if(56!==e)break;r.fps=i.uint32();continue;case 8:if(64!==e)break;r.priority=i.uint32();continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return r},fromJSON:e=>({trackSids:Array.isArray(null==e?void 0:e.trackSids)?e.trackSids.map((e=>String(e))):[],disabled:!!Xn(e.disabled)&&Boolean(e.disabled),quality:Xn(e.quality)?ut(e.quality):0,width:Xn(e.width)?Number(e.width):0,height:Xn(e.height)?Number(e.height):0,fps:Xn(e.fps)?Number(e.fps):0,priority:Xn(e.priority)?Number(e.priority):0}),toJSON(e){const t={};return e.trackSids?t.trackSids=e.trackSids.map((e=>e)):t.trackSids=[],void 0!==e.disabled&&(t.disabled=e.disabled),void 0!==e.quality&&(t.quality=lt(e.quality)),void 0!==e.width&&(t.width=Math.round(e.width)),void 0!==e.height&&(t.height=Math.round(e.height)),void 0!==e.fps&&(t.fps=Math.round(e.fps)),void 0!==e.priority&&(t.priority=Math.round(e.priority)),t},create:e=>wn.fromPartial(null!=e?e:{}),fromPartial(e){var t,i,n,r,s,o,a;const c={trackSids:[],disabled:!1,quality:0,width:0,height:0,fps:0,priority:0};return c.trackSids=(null===(t=e.trackSids)||void 0===t?void 0:t.map((e=>e)))||[],c.disabled=null!==(i=e.disabled)&&void 0!==i&&i,c.quality=null!==(n=e.quality)&&void 0!==n?n:0,c.width=null!==(r=e.width)&&void 0!==r?r:0,c.height=null!==(s=e.height)&&void 0!==s?s:0,c.fps=null!==(o=e.fps)&&void 0!==o?o:0,c.priority=null!==(a=e.priority)&&void 0!==a?a:0,c}};const Rn={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:st.Writer.create();return!0===e.canReconnect&&t.uint32(8).bool(e.canReconnect),0!==e.reason&&t.uint32(16).int32(e.reason),t},decode(e,t){const i=e instanceof st.Reader?e:st.Reader.create(e);let n=void 0===t?i.len:i.pos+t;const r={canReconnect:!1,reason:0};for(;i.pos<n;){const e=i.uint32();switch(e>>>3){case 1:if(8!==e)break;r.canReconnect=i.bool();continue;case 2:if(16!==e)break;r.reason=i.int32();continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return r},fromJSON:e=>({canReconnect:!!Xn(e.canReconnect)&&Boolean(e.canReconnect),reason:Xn(e.reason)?ft(e.reason):0}),toJSON(t){const i={};return void 0!==t.canReconnect&&(i.canReconnect=t.canReconnect),void 0!==t.reason&&(i.reason=function(t){switch(t){case e.DisconnectReason.UNKNOWN_REASON:return"UNKNOWN_REASON";case e.DisconnectReason.CLIENT_INITIATED:return"CLIENT_INITIATED";case e.DisconnectReason.DUPLICATE_IDENTITY:return"DUPLICATE_IDENTITY";case e.DisconnectReason.SERVER_SHUTDOWN:return"SERVER_SHUTDOWN";case e.DisconnectReason.PARTICIPANT_REMOVED:return"PARTICIPANT_REMOVED";case e.DisconnectReason.ROOM_DELETED:return"ROOM_DELETED";case e.DisconnectReason.STATE_MISMATCH:return"STATE_MISMATCH";case e.DisconnectReason.JOIN_FAILURE:return"JOIN_FAILURE";case e.DisconnectReason.UNRECOGNIZED:default:return"UNRECOGNIZED"}}(t.reason)),i},create:e=>Rn.fromPartial(null!=e?e:{}),fromPartial(e){var t,i;const n={canReconnect:!1,reason:0};return n.canReconnect=null!==(t=e.canReconnect)&&void 0!==t&&t,n.reason=null!==(i=e.reason)&&void 0!==i?i:0,n}};const Nn={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:st.Writer.create();""!==e.trackSid&&t.uint32(10).string(e.trackSid);for(const i of e.layers)Ot.encode(i,t.uint32(18).fork()).ldelim();return t},decode(e,t){const i=e instanceof st.Reader?e:st.Reader.create(e);let n=void 0===t?i.len:i.pos+t;const r={trackSid:"",layers:[]};for(;i.pos<n;){const e=i.uint32();switch(e>>>3){case 1:if(10!==e)break;r.trackSid=i.string();continue;case 2:if(18!==e)break;r.layers.push(Ot.decode(i,i.uint32()));continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return r},fromJSON:e=>({trackSid:Xn(e.trackSid)?String(e.trackSid):"",layers:Array.isArray(null==e?void 0:e.layers)?e.layers.map((e=>Ot.fromJSON(e))):[]}),toJSON(e){const t={};return void 0!==e.trackSid&&(t.trackSid=e.trackSid),e.layers?t.layers=e.layers.map((e=>e?Ot.toJSON(e):void 0)):t.layers=[],t},create:e=>Nn.fromPartial(null!=e?e:{}),fromPartial(e){var t,i;const n={trackSid:"",layers:[]};return n.trackSid=null!==(t=e.trackSid)&&void 0!==t?t:"",n.layers=(null===(i=e.layers)||void 0===i?void 0:i.map((e=>Ot.fromPartial(e))))||[],n}};const On={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:st.Writer.create();return""!==e.metadata&&t.uint32(10).string(e.metadata),""!==e.name&&t.uint32(18).string(e.name),t},decode(e,t){const i=e instanceof st.Reader?e:st.Reader.create(e);let n=void 0===t?i.len:i.pos+t;const r={metadata:"",name:""};for(;i.pos<n;){const e=i.uint32();switch(e>>>3){case 1:if(10!==e)break;r.metadata=i.string();continue;case 2:if(18!==e)break;r.name=i.string();continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return r},fromJSON:e=>({metadata:Xn(e.metadata)?String(e.metadata):"",name:Xn(e.name)?String(e.name):""}),toJSON(e){const t={};return void 0!==e.metadata&&(t.metadata=e.metadata),void 0!==e.name&&(t.name=e.name),t},create:e=>On.fromPartial(null!=e?e:{}),fromPartial(e){var t,i;const n={metadata:"",name:""};return n.metadata=null!==(t=e.metadata)&&void 0!==t?t:"",n.name=null!==(i=e.name)&&void 0!==i?i:"",n}};const Dn={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:st.Writer.create();for(const i of e.urls)t.uint32(10).string(i);return""!==e.username&&t.uint32(18).string(e.username),""!==e.credential&&t.uint32(26).string(e.credential),t},decode(e,t){const i=e instanceof st.Reader?e:st.Reader.create(e);let n=void 0===t?i.len:i.pos+t;const r={urls:[],username:"",credential:""};for(;i.pos<n;){const e=i.uint32();switch(e>>>3){case 1:if(10!==e)break;r.urls.push(i.string());continue;case 2:if(18!==e)break;r.username=i.string();continue;case 3:if(26!==e)break;r.credential=i.string();continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return r},fromJSON:e=>({urls:Array.isArray(null==e?void 0:e.urls)?e.urls.map((e=>String(e))):[],username:Xn(e.username)?String(e.username):"",credential:Xn(e.credential)?String(e.credential):""}),toJSON(e){const t={};return e.urls?t.urls=e.urls.map((e=>e)):t.urls=[],void 0!==e.username&&(t.username=e.username),void 0!==e.credential&&(t.credential=e.credential),t},create:e=>Dn.fromPartial(null!=e?e:{}),fromPartial(e){var t,i,n;const r={urls:[],username:"",credential:""};return r.urls=(null===(t=e.urls)||void 0===t?void 0:t.map((e=>e)))||[],r.username=null!==(i=e.username)&&void 0!==i?i:"",r.credential=null!==(n=e.credential)&&void 0!==n?n:"",r}};const In={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:st.Writer.create();for(const i of e.speakers)At.encode(i,t.uint32(10).fork()).ldelim();return t},decode(e,t){const i=e instanceof st.Reader?e:st.Reader.create(e);let n=void 0===t?i.len:i.pos+t;const r={speakers:[]};for(;i.pos<n;){const e=i.uint32();switch(e>>>3){case 1:if(10!==e)break;r.speakers.push(At.decode(i,i.uint32()));continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return r},fromJSON:e=>({speakers:Array.isArray(null==e?void 0:e.speakers)?e.speakers.map((e=>At.fromJSON(e))):[]}),toJSON(e){const t={};return e.speakers?t.speakers=e.speakers.map((e=>e?At.toJSON(e):void 0)):t.speakers=[],t},create:e=>In.fromPartial(null!=e?e:{}),fromPartial(e){var t;const i={speakers:[]};return i.speakers=(null===(t=e.speakers)||void 0===t?void 0:t.map((e=>At.fromPartial(e))))||[],i}};const An={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:st.Writer.create();return void 0!==e.room&&Tt.encode(e.room,t.uint32(10).fork()).ldelim(),t},decode(e,t){const i=e instanceof st.Reader?e:st.Reader.create(e);let n=void 0===t?i.len:i.pos+t;const r={room:void 0};for(;i.pos<n;){const e=i.uint32();switch(e>>>3){case 1:if(10!==e)break;r.room=Tt.decode(i,i.uint32());continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return r},fromJSON:e=>({room:Xn(e.room)?Tt.fromJSON(e.room):void 0}),toJSON(e){const t={};return void 0!==e.room&&(t.room=e.room?Tt.toJSON(e.room):void 0),t},create:e=>An.fromPartial(null!=e?e:{}),fromPartial(e){const t={room:void 0};return t.room=void 0!==e.room&&null!==e.room?Tt.fromPartial(e.room):void 0,t}};const Un={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:st.Writer.create();return""!==e.participantSid&&t.uint32(10).string(e.participantSid),0!==e.quality&&t.uint32(16).int32(e.quality),0!==e.score&&t.uint32(29).float(e.score),t},decode(e,t){const i=e instanceof st.Reader?e:st.Reader.create(e);let n=void 0===t?i.len:i.pos+t;const r={participantSid:"",quality:0,score:0};for(;i.pos<n;){const e=i.uint32();switch(e>>>3){case 1:if(10!==e)break;r.participantSid=i.string();continue;case 2:if(16!==e)break;r.quality=i.int32();continue;case 3:if(29!==e)break;r.score=i.float();continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return r},fromJSON:e=>({participantSid:Xn(e.participantSid)?String(e.participantSid):"",quality:Xn(e.quality)?ht(e.quality):0,score:Xn(e.score)?Number(e.score):0}),toJSON(e){const t={};return void 0!==e.participantSid&&(t.participantSid=e.participantSid),void 0!==e.quality&&(t.quality=function(e){switch(e){case Ke.POOR:return"POOR";case Ke.GOOD:return"GOOD";case Ke.EXCELLENT:return"EXCELLENT";case Ke.UNRECOGNIZED:default:return"UNRECOGNIZED"}}(e.quality)),void 0!==e.score&&(t.score=e.score),t},create:e=>Un.fromPartial(null!=e?e:{}),fromPartial(e){var t,i,n;const r={participantSid:"",quality:0,score:0};return r.participantSid=null!==(t=e.participantSid)&&void 0!==t?t:"",r.quality=null!==(i=e.quality)&&void 0!==i?i:0,r.score=null!==(n=e.score)&&void 0!==n?n:0,r}};const Mn={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:st.Writer.create();for(const i of e.updates)Un.encode(i,t.uint32(10).fork()).ldelim();return t},decode(e,t){const i=e instanceof st.Reader?e:st.Reader.create(e);let n=void 0===t?i.len:i.pos+t;const r={updates:[]};for(;i.pos<n;){const e=i.uint32();switch(e>>>3){case 1:if(10!==e)break;r.updates.push(Un.decode(i,i.uint32()));continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return r},fromJSON:e=>({updates:Array.isArray(null==e?void 0:e.updates)?e.updates.map((e=>Un.fromJSON(e))):[]}),toJSON(e){const t={};return e.updates?t.updates=e.updates.map((e=>e?Un.toJSON(e):void 0)):t.updates=[],t},create:e=>Mn.fromPartial(null!=e?e:{}),fromPartial(e){var t;const i={updates:[]};return i.updates=(null===(t=e.updates)||void 0===t?void 0:t.map((e=>Un.fromPartial(e))))||[],i}};const Ln={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:st.Writer.create();return""!==e.participantSid&&t.uint32(10).string(e.participantSid),""!==e.trackSid&&t.uint32(18).string(e.trackSid),0!==e.state&&t.uint32(24).int32(e.state),t},decode(e,t){const i=e instanceof st.Reader?e:st.Reader.create(e);let n=void 0===t?i.len:i.pos+t;const r={participantSid:"",trackSid:"",state:0};for(;i.pos<n;){const e=i.uint32();switch(e>>>3){case 1:if(10!==e)break;r.participantSid=i.string();continue;case 2:if(18!==e)break;r.trackSid=i.string();continue;case 3:if(24!==e)break;r.state=i.int32();continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return r},fromJSON:e=>({participantSid:Xn(e.participantSid)?String(e.participantSid):"",trackSid:Xn(e.trackSid)?String(e.trackSid):"",state:Xn(e.state)?un(e.state):0}),toJSON(e){const t={};return void 0!==e.participantSid&&(t.participantSid=e.participantSid),void 0!==e.trackSid&&(t.trackSid=e.trackSid),void 0!==e.state&&(t.state=function(e){switch(e){case sn.ACTIVE:return"ACTIVE";case sn.PAUSED:return"PAUSED";case sn.UNRECOGNIZED:default:return"UNRECOGNIZED"}}(e.state)),t},create:e=>Ln.fromPartial(null!=e?e:{}),fromPartial(e){var t,i,n;const r={participantSid:"",trackSid:"",state:0};return r.participantSid=null!==(t=e.participantSid)&&void 0!==t?t:"",r.trackSid=null!==(i=e.trackSid)&&void 0!==i?i:"",r.state=null!==(n=e.state)&&void 0!==n?n:0,r}};const _n={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:st.Writer.create();for(const i of e.streamStates)Ln.encode(i,t.uint32(10).fork()).ldelim();return t},decode(e,t){const i=e instanceof st.Reader?e:st.Reader.create(e);let n=void 0===t?i.len:i.pos+t;const r={streamStates:[]};for(;i.pos<n;){const e=i.uint32();switch(e>>>3){case 1:if(10!==e)break;r.streamStates.push(Ln.decode(i,i.uint32()));continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return r},fromJSON:e=>({streamStates:Array.isArray(null==e?void 0:e.streamStates)?e.streamStates.map((e=>Ln.fromJSON(e))):[]}),toJSON(e){const t={};return e.streamStates?t.streamStates=e.streamStates.map((e=>e?Ln.toJSON(e):void 0)):t.streamStates=[],t},create:e=>_n.fromPartial(null!=e?e:{}),fromPartial(e){var t;const i={streamStates:[]};return i.streamStates=(null===(t=e.streamStates)||void 0===t?void 0:t.map((e=>Ln.fromPartial(e))))||[],i}};const xn={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:st.Writer.create();return 0!==e.quality&&t.uint32(8).int32(e.quality),!0===e.enabled&&t.uint32(16).bool(e.enabled),t},decode(e,t){const i=e instanceof st.Reader?e:st.Reader.create(e);let n=void 0===t?i.len:i.pos+t;const r={quality:0,enabled:!1};for(;i.pos<n;){const e=i.uint32();switch(e>>>3){case 1:if(8!==e)break;r.quality=i.int32();continue;case 2:if(16!==e)break;r.enabled=i.bool();continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return r},fromJSON:e=>({quality:Xn(e.quality)?ut(e.quality):0,enabled:!!Xn(e.enabled)&&Boolean(e.enabled)}),toJSON(e){const t={};return void 0!==e.quality&&(t.quality=lt(e.quality)),void 0!==e.enabled&&(t.enabled=e.enabled),t},create:e=>xn.fromPartial(null!=e?e:{}),fromPartial(e){var t,i;const n={quality:0,enabled:!1};return n.quality=null!==(t=e.quality)&&void 0!==t?t:0,n.enabled=null!==(i=e.enabled)&&void 0!==i&&i,n}};const Bn={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:st.Writer.create();""!==e.codec&&t.uint32(10).string(e.codec);for(const i of e.qualities)xn.encode(i,t.uint32(18).fork()).ldelim();return t},decode(e,t){const i=e instanceof st.Reader?e:st.Reader.create(e);let n=void 0===t?i.len:i.pos+t;const r={codec:"",qualities:[]};for(;i.pos<n;){const e=i.uint32();switch(e>>>3){case 1:if(10!==e)break;r.codec=i.string();continue;case 2:if(18!==e)break;r.qualities.push(xn.decode(i,i.uint32()));continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return r},fromJSON:e=>({codec:Xn(e.codec)?String(e.codec):"",qualities:Array.isArray(null==e?void 0:e.qualities)?e.qualities.map((e=>xn.fromJSON(e))):[]}),toJSON(e){const t={};return void 0!==e.codec&&(t.codec=e.codec),e.qualities?t.qualities=e.qualities.map((e=>e?xn.toJSON(e):void 0)):t.qualities=[],t},create:e=>Bn.fromPartial(null!=e?e:{}),fromPartial(e){var t,i;const n={codec:"",qualities:[]};return n.codec=null!==(t=e.codec)&&void 0!==t?t:"",n.qualities=(null===(i=e.qualities)||void 0===i?void 0:i.map((e=>xn.fromPartial(e))))||[],n}};const Jn={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:st.Writer.create();""!==e.trackSid&&t.uint32(10).string(e.trackSid);for(const i of e.subscribedQualities)xn.encode(i,t.uint32(18).fork()).ldelim();for(const i of e.subscribedCodecs)Bn.encode(i,t.uint32(26).fork()).ldelim();return t},decode(e,t){const i=e instanceof st.Reader?e:st.Reader.create(e);let n=void 0===t?i.len:i.pos+t;const r={trackSid:"",subscribedQualities:[],subscribedCodecs:[]};for(;i.pos<n;){const e=i.uint32();switch(e>>>3){case 1:if(10!==e)break;r.trackSid=i.string();continue;case 2:if(18!==e)break;r.subscribedQualities.push(xn.decode(i,i.uint32()));continue;case 3:if(26!==e)break;r.subscribedCodecs.push(Bn.decode(i,i.uint32()));continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return r},fromJSON:e=>({trackSid:Xn(e.trackSid)?String(e.trackSid):"",subscribedQualities:Array.isArray(null==e?void 0:e.subscribedQualities)?e.subscribedQualities.map((e=>xn.fromJSON(e))):[],subscribedCodecs:Array.isArray(null==e?void 0:e.subscribedCodecs)?e.subscribedCodecs.map((e=>Bn.fromJSON(e))):[]}),toJSON(e){const t={};return void 0!==e.trackSid&&(t.trackSid=e.trackSid),e.subscribedQualities?t.subscribedQualities=e.subscribedQualities.map((e=>e?xn.toJSON(e):void 0)):t.subscribedQualities=[],e.subscribedCodecs?t.subscribedCodecs=e.subscribedCodecs.map((e=>e?Bn.toJSON(e):void 0)):t.subscribedCodecs=[],t},create:e=>Jn.fromPartial(null!=e?e:{}),fromPartial(e){var t,i,n;const r={trackSid:"",subscribedQualities:[],subscribedCodecs:[]};return r.trackSid=null!==(t=e.trackSid)&&void 0!==t?t:"",r.subscribedQualities=(null===(i=e.subscribedQualities)||void 0===i?void 0:i.map((e=>xn.fromPartial(e))))||[],r.subscribedCodecs=(null===(n=e.subscribedCodecs)||void 0===n?void 0:n.map((e=>Bn.fromPartial(e))))||[],r}};const Fn={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:st.Writer.create();""!==e.participantSid&&t.uint32(10).string(e.participantSid),!0===e.allTracks&&t.uint32(16).bool(e.allTracks);for(const i of e.trackSids)t.uint32(26).string(i);return""!==e.participantIdentity&&t.uint32(34).string(e.participantIdentity),t},decode(e,t){const i=e instanceof st.Reader?e:st.Reader.create(e);let n=void 0===t?i.len:i.pos+t;const r={participantSid:"",allTracks:!1,trackSids:[],participantIdentity:""};for(;i.pos<n;){const e=i.uint32();switch(e>>>3){case 1:if(10!==e)break;r.participantSid=i.string();continue;case 2:if(16!==e)break;r.allTracks=i.bool();continue;case 3:if(26!==e)break;r.trackSids.push(i.string());continue;case 4:if(34!==e)break;r.participantIdentity=i.string();continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return r},fromJSON:e=>({participantSid:Xn(e.participantSid)?String(e.participantSid):"",allTracks:!!Xn(e.allTracks)&&Boolean(e.allTracks),trackSids:Array.isArray(null==e?void 0:e.trackSids)?e.trackSids.map((e=>String(e))):[],participantIdentity:Xn(e.participantIdentity)?String(e.participantIdentity):""}),toJSON(e){const t={};return void 0!==e.participantSid&&(t.participantSid=e.participantSid),void 0!==e.allTracks&&(t.allTracks=e.allTracks),e.trackSids?t.trackSids=e.trackSids.map((e=>e)):t.trackSids=[],void 0!==e.participantIdentity&&(t.participantIdentity=e.participantIdentity),t},create:e=>Fn.fromPartial(null!=e?e:{}),fromPartial(e){var t,i,n,r;const s={participantSid:"",allTracks:!1,trackSids:[],participantIdentity:""};return s.participantSid=null!==(t=e.participantSid)&&void 0!==t?t:"",s.allTracks=null!==(i=e.allTracks)&&void 0!==i&&i,s.trackSids=(null===(n=e.trackSids)||void 0===n?void 0:n.map((e=>e)))||[],s.participantIdentity=null!==(r=e.participantIdentity)&&void 0!==r?r:"",s}};const $n={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:st.Writer.create();!0===e.allParticipants&&t.uint32(8).bool(e.allParticipants);for(const i of e.trackPermissions)Fn.encode(i,t.uint32(18).fork()).ldelim();return t},decode(e,t){const i=e instanceof st.Reader?e:st.Reader.create(e);let n=void 0===t?i.len:i.pos+t;const r={allParticipants:!1,trackPermissions:[]};for(;i.pos<n;){const e=i.uint32();switch(e>>>3){case 1:if(8!==e)break;r.allParticipants=i.bool();continue;case 2:if(18!==e)break;r.trackPermissions.push(Fn.decode(i,i.uint32()));continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return r},fromJSON:e=>({allParticipants:!!Xn(e.allParticipants)&&Boolean(e.allParticipants),trackPermissions:Array.isArray(null==e?void 0:e.trackPermissions)?e.trackPermissions.map((e=>Fn.fromJSON(e))):[]}),toJSON(e){const t={};return void 0!==e.allParticipants&&(t.allParticipants=e.allParticipants),e.trackPermissions?t.trackPermissions=e.trackPermissions.map((e=>e?Fn.toJSON(e):void 0)):t.trackPermissions=[],t},create:e=>$n.fromPartial(null!=e?e:{}),fromPartial(e){var t,i;const n={allParticipants:!1,trackPermissions:[]};return n.allParticipants=null!==(t=e.allParticipants)&&void 0!==t&&t,n.trackPermissions=(null===(i=e.trackPermissions)||void 0===i?void 0:i.map((e=>Fn.fromPartial(e))))||[],n}};const jn={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:st.Writer.create();return""!==e.participantSid&&t.uint32(10).string(e.participantSid),""!==e.trackSid&&t.uint32(18).string(e.trackSid),!0===e.allowed&&t.uint32(24).bool(e.allowed),t},decode(e,t){const i=e instanceof st.Reader?e:st.Reader.create(e);let n=void 0===t?i.len:i.pos+t;const r={participantSid:"",trackSid:"",allowed:!1};for(;i.pos<n;){const e=i.uint32();switch(e>>>3){case 1:if(10!==e)break;r.participantSid=i.string();continue;case 2:if(18!==e)break;r.trackSid=i.string();continue;case 3:if(24!==e)break;r.allowed=i.bool();continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return r},fromJSON:e=>({participantSid:Xn(e.participantSid)?String(e.participantSid):"",trackSid:Xn(e.trackSid)?String(e.trackSid):"",allowed:!!Xn(e.allowed)&&Boolean(e.allowed)}),toJSON(e){const t={};return void 0!==e.participantSid&&(t.participantSid=e.participantSid),void 0!==e.trackSid&&(t.trackSid=e.trackSid),void 0!==e.allowed&&(t.allowed=e.allowed),t},create:e=>jn.fromPartial(null!=e?e:{}),fromPartial(e){var t,i,n;const r={participantSid:"",trackSid:"",allowed:!1};return r.participantSid=null!==(t=e.participantSid)&&void 0!==t?t:"",r.trackSid=null!==(i=e.trackSid)&&void 0!==i?i:"",r.allowed=null!==(n=e.allowed)&&void 0!==n&&n,r}};const Vn={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:st.Writer.create();void 0!==e.answer&&Tn.encode(e.answer,t.uint32(10).fork()).ldelim(),void 0!==e.subscription&&Pn.encode(e.subscription,t.uint32(18).fork()).ldelim();for(const i of e.publishTracks)yn.encode(i,t.uint32(26).fork()).ldelim();for(const i of e.dataChannels)qn.encode(i,t.uint32(34).fork()).ldelim();return void 0!==e.offer&&Tn.encode(e.offer,t.uint32(42).fork()).ldelim(),t},decode(e,t){const i=e instanceof st.Reader?e:st.Reader.create(e);let n=void 0===t?i.len:i.pos+t;const r={answer:void 0,subscription:void 0,publishTracks:[],dataChannels:[],offer:void 0};for(;i.pos<n;){const e=i.uint32();switch(e>>>3){case 1:if(10!==e)break;r.answer=Tn.decode(i,i.uint32());continue;case 2:if(18!==e)break;r.subscription=Pn.decode(i,i.uint32());continue;case 3:if(26!==e)break;r.publishTracks.push(yn.decode(i,i.uint32()));continue;case 4:if(34!==e)break;r.dataChannels.push(qn.decode(i,i.uint32()));continue;case 5:if(42!==e)break;r.offer=Tn.decode(i,i.uint32());continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return r},fromJSON:e=>({answer:Xn(e.answer)?Tn.fromJSON(e.answer):void 0,subscription:Xn(e.subscription)?Pn.fromJSON(e.subscription):void 0,publishTracks:Array.isArray(null==e?void 0:e.publishTracks)?e.publishTracks.map((e=>yn.fromJSON(e))):[],dataChannels:Array.isArray(null==e?void 0:e.dataChannels)?e.dataChannels.map((e=>qn.fromJSON(e))):[],offer:Xn(e.offer)?Tn.fromJSON(e.offer):void 0}),toJSON(e){const t={};return void 0!==e.answer&&(t.answer=e.answer?Tn.toJSON(e.answer):void 0),void 0!==e.subscription&&(t.subscription=e.subscription?Pn.toJSON(e.subscription):void 0),e.publishTracks?t.publishTracks=e.publishTracks.map((e=>e?yn.toJSON(e):void 0)):t.publishTracks=[],e.dataChannels?t.dataChannels=e.dataChannels.map((e=>e?qn.toJSON(e):void 0)):t.dataChannels=[],void 0!==e.offer&&(t.offer=e.offer?Tn.toJSON(e.offer):void 0),t},create:e=>Vn.fromPartial(null!=e?e:{}),fromPartial(e){var t,i;const n={answer:void 0,subscription:void 0,publishTracks:[],dataChannels:[],offer:void 0};return n.answer=void 0!==e.answer&&null!==e.answer?Tn.fromPartial(e.answer):void 0,n.subscription=void 0!==e.subscription&&null!==e.subscription?Pn.fromPartial(e.subscription):void 0,n.publishTracks=(null===(t=e.publishTracks)||void 0===t?void 0:t.map((e=>yn.fromPartial(e))))||[],n.dataChannels=(null===(i=e.dataChannels)||void 0===i?void 0:i.map((e=>qn.fromPartial(e))))||[],n.offer=void 0!==e.offer&&null!==e.offer?Tn.fromPartial(e.offer):void 0,n}};const qn={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:st.Writer.create();return""!==e.label&&t.uint32(10).string(e.label),0!==e.id&&t.uint32(16).uint32(e.id),0!==e.target&&t.uint32(24).int32(e.target),t},decode(e,t){const i=e instanceof st.Reader?e:st.Reader.create(e);let n=void 0===t?i.len:i.pos+t;const r={label:"",id:0,target:0};for(;i.pos<n;){const e=i.uint32();switch(e>>>3){case 1:if(10!==e)break;r.label=i.string();continue;case 2:if(16!==e)break;r.id=i.uint32();continue;case 3:if(24!==e)break;r.target=i.int32();continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return r},fromJSON:e=>({label:Xn(e.label)?String(e.label):"",id:Xn(e.id)?Number(e.id):0,target:Xn(e.target)?cn(e.target):0}),toJSON(e){const t={};return void 0!==e.label&&(t.label=e.label),void 0!==e.id&&(t.id=Math.round(e.id)),void 0!==e.target&&(t.target=dn(e.target)),t},create:e=>qn.fromPartial(null!=e?e:{}),fromPartial(e){var t,i,n;const r={label:"",id:0,target:0};return r.label=null!==(t=e.label)&&void 0!==t?t:"",r.id=null!==(i=e.id)&&void 0!==i?i:0,r.target=null!==(n=e.target)&&void 0!==n?n:0,r}};const Wn={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:st.Writer.create();var i;switch(null===(i=e.scenario)||void 0===i?void 0:i.$case){case"speakerUpdate":t.uint32(8).int32(e.scenario.speakerUpdate);break;case"nodeFailure":t.uint32(16).bool(e.scenario.nodeFailure);break;case"migration":t.uint32(24).bool(e.scenario.migration);break;case"serverLeave":t.uint32(32).bool(e.scenario.serverLeave);break;case"switchCandidateProtocol":t.uint32(40).int32(e.scenario.switchCandidateProtocol);break;case"subscriberBandwidth":t.uint32(48).int64(e.scenario.subscriberBandwidth)}return t},decode(e,t){const i=e instanceof st.Reader?e:st.Reader.create(e);let n=void 0===t?i.len:i.pos+t;const r={scenario:void 0};for(;i.pos<n;){const e=i.uint32();switch(e>>>3){case 1:if(8!==e)break;r.scenario={$case:"speakerUpdate",speakerUpdate:i.int32()};continue;case 2:if(16!==e)break;r.scenario={$case:"nodeFailure",nodeFailure:i.bool()};continue;case 3:if(24!==e)break;r.scenario={$case:"migration",migration:i.bool()};continue;case 4:if(32!==e)break;r.scenario={$case:"serverLeave",serverLeave:i.bool()};continue;case 5:if(40!==e)break;r.scenario={$case:"switchCandidateProtocol",switchCandidateProtocol:i.int32()};continue;case 6:if(48!==e)break;r.scenario={$case:"subscriberBandwidth",subscriberBandwidth:Yn(i.int64())};continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return r},fromJSON:e=>({scenario:Xn(e.speakerUpdate)?{$case:"speakerUpdate",speakerUpdate:Number(e.speakerUpdate)}:Xn(e.nodeFailure)?{$case:"nodeFailure",nodeFailure:Boolean(e.nodeFailure)}:Xn(e.migration)?{$case:"migration",migration:Boolean(e.migration)}:Xn(e.serverLeave)?{$case:"serverLeave",serverLeave:Boolean(e.serverLeave)}:Xn(e.switchCandidateProtocol)?{$case:"switchCandidateProtocol",switchCandidateProtocol:ln(e.switchCandidateProtocol)}:Xn(e.subscriberBandwidth)?{$case:"subscriberBandwidth",subscriberBandwidth:Number(e.subscriberBandwidth)}:void 0}),toJSON(e){var t,i,n,r,s,o,a,c,d,u,l,h,p;const m={};return"speakerUpdate"===(null===(t=e.scenario)||void 0===t?void 0:t.$case)&&(m.speakerUpdate=Math.round(null===(i=e.scenario)||void 0===i?void 0:i.speakerUpdate)),"nodeFailure"===(null===(n=e.scenario)||void 0===n?void 0:n.$case)&&(m.nodeFailure=null===(r=e.scenario)||void 0===r?void 0:r.nodeFailure),"migration"===(null===(s=e.scenario)||void 0===s?void 0:s.$case)&&(m.migration=null===(o=e.scenario)||void 0===o?void 0:o.migration),"serverLeave"===(null===(a=e.scenario)||void 0===a?void 0:a.$case)&&(m.serverLeave=null===(c=e.scenario)||void 0===c?void 0:c.serverLeave),"switchCandidateProtocol"===(null===(d=e.scenario)||void 0===d?void 0:d.$case)&&(m.switchCandidateProtocol=void 0!==(null===(u=e.scenario)||void 0===u?void 0:u.switchCandidateProtocol)?function(e){switch(e){case on.UDP:return"UDP";case on.TCP:return"TCP";case on.TLS:return"TLS";case on.UNRECOGNIZED:default:return"UNRECOGNIZED"}}(null===(l=e.scenario)||void 0===l?void 0:l.switchCandidateProtocol):void 0),"subscriberBandwidth"===(null===(h=e.scenario)||void 0===h?void 0:h.$case)&&(m.subscriberBandwidth=Math.round(null===(p=e.scenario)||void 0===p?void 0:p.subscriberBandwidth)),m},create:e=>Wn.fromPartial(null!=e?e:{}),fromPartial(e){var t,i,n,r,s,o,a,c,d,u,l,h,p,m,f,v,g,b;const k={scenario:void 0};return"speakerUpdate"===(null===(t=e.scenario)||void 0===t?void 0:t.$case)&&void 0!==(null===(i=e.scenario)||void 0===i?void 0:i.speakerUpdate)&&null!==(null===(n=e.scenario)||void 0===n?void 0:n.speakerUpdate)&&(k.scenario={$case:"speakerUpdate",speakerUpdate:e.scenario.speakerUpdate}),"nodeFailure"===(null===(r=e.scenario)||void 0===r?void 0:r.$case)&&void 0!==(null===(s=e.scenario)||void 0===s?void 0:s.nodeFailure)&&null!==(null===(o=e.scenario)||void 0===o?void 0:o.nodeFailure)&&(k.scenario={$case:"nodeFailure",nodeFailure:e.scenario.nodeFailure}),"migration"===(null===(a=e.scenario)||void 0===a?void 0:a.$case)&&void 0!==(null===(c=e.scenario)||void 0===c?void 0:c.migration)&&null!==(null===(d=e.scenario)||void 0===d?void 0:d.migration)&&(k.scenario={$case:"migration",migration:e.scenario.migration}),"serverLeave"===(null===(u=e.scenario)||void 0===u?void 0:u.$case)&&void 0!==(null===(l=e.scenario)||void 0===l?void 0:l.serverLeave)&&null!==(null===(h=e.scenario)||void 0===h?void 0:h.serverLeave)&&(k.scenario={$case:"serverLeave",serverLeave:e.scenario.serverLeave}),"switchCandidateProtocol"===(null===(p=e.scenario)||void 0===p?void 0:p.$case)&&void 0!==(null===(m=e.scenario)||void 0===m?void 0:m.switchCandidateProtocol)&&null!==(null===(f=e.scenario)||void 0===f?void 0:f.switchCandidateProtocol)&&(k.scenario={$case:"switchCandidateProtocol",switchCandidateProtocol:e.scenario.switchCandidateProtocol}),"subscriberBandwidth"===(null===(v=e.scenario)||void 0===v?void 0:v.$case)&&void 0!==(null===(g=e.scenario)||void 0===g?void 0:g.subscriberBandwidth)&&null!==(null===(b=e.scenario)||void 0===b?void 0:b.subscriberBandwidth)&&(k.scenario={$case:"subscriberBandwidth",subscriberBandwidth:e.scenario.subscriberBandwidth}),k}};const Gn={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:st.Writer.create();return 0!==e.timestamp&&t.uint32(8).int64(e.timestamp),0!==e.rtt&&t.uint32(16).int64(e.rtt),t},decode(e,t){const i=e instanceof st.Reader?e:st.Reader.create(e);let n=void 0===t?i.len:i.pos+t;const r={timestamp:0,rtt:0};for(;i.pos<n;){const e=i.uint32();switch(e>>>3){case 1:if(8!==e)break;r.timestamp=Yn(i.int64());continue;case 2:if(16!==e)break;r.rtt=Yn(i.int64());continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return r},fromJSON:e=>({timestamp:Xn(e.timestamp)?Number(e.timestamp):0,rtt:Xn(e.rtt)?Number(e.rtt):0}),toJSON(e){const t={};return void 0!==e.timestamp&&(t.timestamp=Math.round(e.timestamp)),void 0!==e.rtt&&(t.rtt=Math.round(e.rtt)),t},create:e=>Gn.fromPartial(null!=e?e:{}),fromPartial(e){var t,i;const n={timestamp:0,rtt:0};return n.timestamp=null!==(t=e.timestamp)&&void 0!==t?t:0,n.rtt=null!==(i=e.rtt)&&void 0!==i?i:0,n}};const Qn={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:st.Writer.create();return 0!==e.lastPingTimestamp&&t.uint32(8).int64(e.lastPingTimestamp),0!==e.timestamp&&t.uint32(16).int64(e.timestamp),t},decode(e,t){const i=e instanceof st.Reader?e:st.Reader.create(e);let n=void 0===t?i.len:i.pos+t;const r={lastPingTimestamp:0,timestamp:0};for(;i.pos<n;){const e=i.uint32();switch(e>>>3){case 1:if(8!==e)break;r.lastPingTimestamp=Yn(i.int64());continue;case 2:if(16!==e)break;r.timestamp=Yn(i.int64());continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return r},fromJSON:e=>({lastPingTimestamp:Xn(e.lastPingTimestamp)?Number(e.lastPingTimestamp):0,timestamp:Xn(e.timestamp)?Number(e.timestamp):0}),toJSON(e){const t={};return void 0!==e.lastPingTimestamp&&(t.lastPingTimestamp=Math.round(e.lastPingTimestamp)),void 0!==e.timestamp&&(t.timestamp=Math.round(e.timestamp)),t},create:e=>Qn.fromPartial(null!=e?e:{}),fromPartial(e){var t,i;const n={lastPingTimestamp:0,timestamp:0};return n.lastPingTimestamp=null!==(t=e.lastPingTimestamp)&&void 0!==t?t:0,n.timestamp=null!==(i=e.timestamp)&&void 0!==i?i:0,n}};const Hn={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:st.Writer.create();return""!==e.trackSid&&t.uint32(10).string(e.trackSid),0!==e.err&&t.uint32(16).int32(e.err),t},decode(e,t){const i=e instanceof st.Reader?e:st.Reader.create(e);let n=void 0===t?i.len:i.pos+t;const r={trackSid:"",err:0};for(;i.pos<n;){const e=i.uint32();switch(e>>>3){case 1:if(10!==e)break;r.trackSid=i.string();continue;case 2:if(16!==e)break;r.err=i.int32();continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return r},fromJSON:e=>({trackSid:Xn(e.trackSid)?String(e.trackSid):"",err:Xn(e.err)?vt(e.err):0}),toJSON(e){const t={};return void 0!==e.trackSid&&(t.trackSid=e.trackSid),void 0!==e.err&&(t.err=function(e){switch(e){case Xe.SE_UNKOWN:return"SE_UNKOWN";case Xe.SE_CODEC_UNSUPPORTED:return"SE_CODEC_UNSUPPORTED";case Xe.SE_TRACK_NOTFOUND:return"SE_TRACK_NOTFOUND";case Xe.UNRECOGNIZED:default:return"UNRECOGNIZED"}}(e.err)),t},create:e=>Hn.fromPartial(null!=e?e:{}),fromPartial(e){var t,i;const n={trackSid:"",err:0};return n.trackSid=null!==(t=e.trackSid)&&void 0!==t?t:"",n.err=null!==(i=e.err)&&void 0!==i?i:0,n}};var Kn,Zn=(()=>{if("undefined"!=typeof globalThis)return globalThis;if("undefined"!=typeof self)return self;if("undefined"!=typeof window)return window;if("undefined"!=typeof global)return global;throw"Unable to locate global object"})();function zn(e){if(Zn.Buffer)return Uint8Array.from(Zn.Buffer.from(e,"base64"));{const t=Zn.atob(e),i=new Uint8Array(t.length);for(let e=0;e<t.length;++e)i[e]=t.charCodeAt(e);return i}}function Yn(e){if(e.gt(Number.MAX_SAFE_INTEGER))throw new Zn.Error("Value is larger than Number.MAX_SAFE_INTEGER");return e.toNumber()}function Xn(e){return null!=e}st.util.Long!==_&&(st.util.Long=_,st.configure());class er extends Error{constructor(e,t){super(t||"an error has occured"),this.code=e}}class tr extends er{constructor(e,t,i){super(1,e),this.status=i,this.reason=t}}class ir extends er{constructor(e){super(21,null!=e?e:"device is unsupported")}}class nr extends er{constructor(e){super(20,null!=e?e:"track is invalid")}}class rr extends er{constructor(e){super(10,null!=e?e:"unsupported server")}}class sr extends er{constructor(e){super(12,null!=e?e:"unexpected connection state")}}class or extends er{constructor(e){super(13,null!=e?e:"unable to negotiate")}}e.MediaDeviceFailure=void 0,(Kn=e.MediaDeviceFailure||(e.MediaDeviceFailure={})).PermissionDenied="PermissionDenied",Kn.NotFound="NotFound",Kn.DeviceInUse="DeviceInUse",Kn.Other="Other",function(e){e.getFailure=function(t){if(t&&"name"in t)return"NotFoundError"===t.name||"DevicesNotFoundError"===t.name?e.NotFound:"NotAllowedError"===t.name||"PermissionDeniedError"===t.name?e.PermissionDenied:"NotReadableError"===t.name||"TrackStartError"===t.name?e.DeviceInUse:e.Other}}(e.MediaDeviceFailure||(e.MediaDeviceFailure={}));class ar{}ar.setTimeout=function(){return setTimeout(...arguments)},ar.setInterval=function(){return setInterval(...arguments)},ar.clearTimeout=function(){return clearTimeout(...arguments)},ar.clearInterval=function(){return clearInterval(...arguments)};const cr=/version\/(\d+(\.?_?\d+)+)/i;let dr;function ur(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(void 0===e&&"undefined"==typeof navigator)return;const i=(null!=e?e:navigator.userAgent).toLowerCase();if(void 0===dr||t){const e=lr.find((e=>{let{test:t}=e;return t.test(i)}));dr=null==e?void 0:e.describe(i)}return dr}const lr=[{test:/firefox|iceweasel|fxios/i,describe:e=>({name:"Firefox",version:hr(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,e)})},{test:/chrom|crios|crmo/i,describe:e=>({name:"Chrome",version:hr(/(?:chrome|chromium|crios|crmo)\/(\d+(\.?_?\d+)+)/i,e)})},{test:/safari|applewebkit/i,describe:e=>({name:"Safari",version:hr(cr,e)})}];function hr(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1;const n=t.match(e);return n&&n.length>=i&&n[i]||""}const pr="1.11.4";function mr(e,t,i){const n=Object.assign({},e);return!0===n.audio&&(n.audio={}),!0===n.video&&(n.video={}),n.audio&&fr(n.audio,t),n.video&&fr(n.video,i),n}function fr(e,t){return Object.keys(t).forEach((i=>{void 0===e[i]&&(e[i]=t[i])})),e}function vr(e){const t={};if(e.video)if("object"==typeof e.video){const i={},n=i,r=e.video;Object.keys(r).forEach((e=>{if("resolution"===e)fr(n,r.resolution);else n[e]=r[e]})),t.video=i}else t.video=e.video;else t.video=!1;return e.audio?"object"==typeof e.audio?t.audio=e.audio:t.audio=!0:t.audio=!1,t}function gr(){const e="undefined"!=typeof window&&(window.AudioContext||window.webkitAudioContext);if(e)return new e({latencyHint:"interactive"})}const br="https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension";function kr(e){return Ht(this,void 0,void 0,(function*(){return new Promise((t=>setTimeout(t,e)))}))}function Sr(){return"addTransceiver"in RTCPeerConnection.prototype}function yr(){return"addTrack"in RTCPeerConnection.prototype}function Cr(){if(!("getCapabilities"in RTCRtpSender))return!1;const e=RTCRtpSender.getCapabilities("video");let t=!1;if(e)for(const i of e.codecs)if("video/AV1"===i.mimeType){t=!0;break}return t}function Tr(){if(!("getCapabilities"in RTCRtpSender))return!1;const e=RTCRtpSender.getCapabilities("video");let t=!1;if(e)for(const i of e.codecs)if("video/VP9"===i.mimeType){t=!0;break}return t}function Er(e){return"av1"===e||"vp9"===e}function Pr(e){return!!document&&(e||(e=document.createElement("audio")),"setSinkId"in e)}const wr={Chrome:"100",Safari:"15",Firefox:"100"};function Rr(){var e;return"Firefox"===(null===(e=ur())||void 0===e?void 0:e.name)}function Nr(){var e;return"Safari"===(null===(e=ur())||void 0===e?void 0:e.name)}function Or(){return!!Dr()&&/Tablet|iPad|Mobile|Android|BlackBerry/.test(navigator.userAgent)}function Dr(){return"undefined"!=typeof document}function Ir(){return"ReactNative"==navigator.product}function Ar(e){return e.hostname.endsWith(".livekit.cloud")}function Ur(){if(global&&global.LiveKitReactNativeGlobal)return global.LiveKitReactNativeGlobal}function Mr(){if(!Ir())return;let e=Ur();return e?e.platform:void 0}function Lr(){if(Dr())return window.devicePixelRatio;if(Ir()){let e=Ur();if(e)return e.devicePixelRatio}return 1}function _r(e,t){const i=e.split("."),n=t.split("."),r=Math.min(i.length,n.length);for(let e=0;e<r;++e){const t=parseInt(i[e],10),s=parseInt(n[e],10);if(t>s)return 1;if(t<s)return-1;if(e===r-1&&t===s)return 0}return""===e&&""!==t?-1:""===t?1:i.length==n.length?0:i.length<n.length?-1:1}function xr(e){for(const t of e)t.target.handleResize(t)}function Br(e){for(const t of e)t.target.handleVisibilityChanged(t)}let Jr=null;const Fr=()=>(Jr||(Jr=new ResizeObserver(xr)),Jr);let $r=null;const jr=()=>($r||($r=new IntersectionObserver(Br,{root:null,rootMargin:"0px"})),$r);let Vr,qr;function Wr(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:16,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:16,i=arguments.length>2&&void 0!==arguments[2]&&arguments[2],n=arguments.length>3&&void 0!==arguments[3]&&arguments[3];const r=document.createElement("canvas");r.width=e,r.height=t;const s=r.getContext("2d");null==s||s.fillRect(0,0,r.width,r.height),n&&s&&(s.beginPath(),s.arc(e/2,t/2,50,0,2*Math.PI,!0),s.closePath(),s.fillStyle="grey",s.fill());const o=r.captureStream(),[a]=o.getTracks();if(!a)throw Error("Could not get empty media stream video track");return a.enabled=i,a}function Gr(){if(!qr){const e=new AudioContext,t=e.createOscillator(),i=e.createGain();i.gain.setValueAtTime(0,0);const n=e.createMediaStreamDestination();if(t.connect(i),i.connect(n),t.start(),[qr]=n.stream.getAudioTracks(),!qr)throw Error("Could not get empty media stream audio track");qr.enabled=!1}return qr.clone()}class Qr{constructor(e,t){this.onFinally=t,this.promise=new Promise(((t,i)=>Ht(this,void 0,void 0,(function*(){this.resolve=t,this.reject=i,e&&(yield e(t,i))})))).finally((()=>{var e;return null===(e=this.onFinally)||void 0===e?void 0:e.call(this)}))}}class Hr{constructor(){this._locking=Promise.resolve(),this._locks=0}isLocked(){return this._locks>0}lock(){let e;this._locks+=1;const t=new Promise((t=>e=()=>{this._locks-=1,t()})),i=this._locking.then((()=>e));return this._locking=this._locking.then((()=>t)),i}}function Kr(e){if("string"==typeof e)return e;if(Array.isArray(e))return e[0];if(e.exact)return Array.isArray(e.exact)?e.exact[0]:e.exact;if(e.ideal)return Array.isArray(e.ideal)?e.ideal[0]:e.ideal;throw Error("could not unwrap constraint")}var Zr;!function(e){e[e.WAITING=0]="WAITING",e[e.RUNNING=1]="RUNNING",e[e.COMPLETED=2]="COMPLETED"}(Zr||(Zr={}));class zr{constructor(){this.pendingTasks=new Map,this.taskMutex=new Hr,this.nextTaskIndex=0}run(e){return Ht(this,void 0,void 0,(function*(){const t={id:this.nextTaskIndex++,enqueuedAt:Date.now(),status:Zr.WAITING};this.pendingTasks.set(t.id,t);const i=yield this.taskMutex.lock();try{return t.executedAt=Date.now(),t.status=Zr.RUNNING,yield e()}finally{t.status=Zr.COMPLETED,this.pendingTasks.delete(t.id),i()}}))}flush(){return Ht(this,void 0,void 0,(function*(){return this.run((()=>Ht(this,void 0,void 0,(function*(){}))))}))}snapshot(){return Array.from(this.pendingTasks.values())}}const Yr=["syncState","trickle","offer","answer","simulate","leave"];class Xr{constructor(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];this.rtt=0,this.isConnected=!1,this.isReconnecting=!1,this.useJSON=e,this.requestQueue=new zr,this.queuedRequests=[],this.closingLock=new Hr}join(e,t,i,n){return Ht(this,void 0,void 0,(function*(){this.isConnected=!1,this.options=i;return yield this.connect(e,t,i,n)}))}reconnect(e,t,i,n){return Ht(this,void 0,void 0,(function*(){if(!this.options)return void c.warn("attempted to reconnect without signal options being set, ignoring");this.isReconnecting=!0,this.clearPingInterval();return yield this.connect(e,t,Object.assign(Object.assign({},this.options),{reconnect:!0,sid:i,reconnectReason:n}))}))}connect(e,t,i,n){this.connectOptions=i,e.startsWith("http")&&(e=e.replace("http","ws")),e=e.replace(/\/$/,""),e+="/rtc";const r=function(e,t,i){var n;const r=new URLSearchParams;r.set("access_token",e),i.reconnect&&(r.set("reconnect","1"),i.sid&&r.set("sid",i.sid));r.set("auto_subscribe",i.autoSubscribe?"1":"0"),r.set("sdk",Ir()?"reactnative":"js"),r.set("version",t.version),r.set("protocol",t.protocol.toString()),t.deviceModel&&r.set("device_model",t.deviceModel);t.os&&r.set("os",t.os);t.osVersion&&r.set("os_version",t.osVersion);t.browser&&r.set("browser",t.browser);t.browserVersion&&r.set("browser_version",t.browserVersion);void 0!==i.publishOnly&&r.set("publish",i.publishOnly);i.adaptiveStream&&r.set("adaptive_stream","1");i.reconnectReason&&r.set("reconnect_reason",i.reconnectReason.toString());(null===(n=navigator.connection)||void 0===n?void 0:n.type)&&r.set("network",navigator.connection.type);return"?".concat(r.toString())}(t,function(){var e;const t=xt.fromPartial({sdk:rt.JS,protocol:9,version:pr});return Ir()&&(t.os=null!==(e=Mr())&&void 0!==e?e:""),t}(),i);return new Promise(((t,s)=>Ht(this,void 0,void 0,(function*(){const o=()=>Ht(this,void 0,void 0,(function*(){this.close(),s(new tr("room connection has been cancelled (signal)"))}));(null==n?void 0:n.aborted)&&o(),null==n||n.addEventListener("abort",o),c.debug("connecting to ".concat(e+r)),this.ws&&(yield this.close()),this.ws=new WebSocket(e+r),this.ws.binaryType="arraybuffer",this.ws.onerror=t=>Ht(this,void 0,void 0,(function*(){if(this.isConnected)this.handleWSError(t);else try{const t=yield fetch("http".concat(e.substring(2),"/validate").concat(r));if(t.status.toFixed(0).startsWith("4")){const e=yield t.text();s(new tr(e,0,t.status))}else s(new tr("Internal error",2,t.status))}catch(e){s(new tr("server was not reachable",1))}})),this.ws.onmessage=e=>Ht(this,void 0,void 0,(function*(){var r,a,d,u;let l;if("string"==typeof e.data){const t=JSON.parse(e.data);l=pn.fromJSON(t)}else{if(!(e.data instanceof ArrayBuffer))return void c.error("could not decode websocket message: ".concat(typeof e.data));l=pn.decode(new Uint8Array(e.data))}if(!this.isConnected){let e=!1;if("join"===(null===(r=l.message)||void 0===r?void 0:r.$case)?(this.isConnected=!0,null==n||n.removeEventListener("abort",o),this.pingTimeoutDuration=l.message.join.pingTimeout,this.pingIntervalDuration=l.message.join.pingInterval,this.pingTimeoutDuration&&this.pingTimeoutDuration>0&&(c.debug("ping config",{timeout:this.pingTimeoutDuration,interval:this.pingIntervalDuration}),this.startPingInterval()),t(l.message.join)):i.reconnect?(this.isConnected=!0,null==n||n.removeEventListener("abort",o),this.startPingInterval(),"reconnect"===(null===(a=l.message)||void 0===a?void 0:a.$case)?t(null===(d=l.message)||void 0===d?void 0:d.reconnect):(t(),e=!0)):i.reconnect||s(new tr("did not receive join response, got ".concat(null===(u=l.message)||void 0===u?void 0:u.$case," instead"))),!e)return}this.signalLatency&&(yield kr(this.signalLatency)),this.handleSignalResponse(l)})),this.ws.onclose=e=>{c.warn("websocket closed",{ev:e}),this.handleOnClose(e.reason)}}))))}close(){return Ht(this,void 0,void 0,(function*(){const e=yield this.closingLock.lock();try{if(this.isConnected=!1,this.ws){this.ws.onclose=null,this.ws.onmessage=null,this.ws.onopen=null;const e=new Promise((e=>{this.ws?this.ws.onclose=e:e(!0)}));this.ws.readyState<this.ws.CLOSING&&(this.ws.close(),yield Promise.race([e,kr(250)])),this.ws=void 0,this.clearPingInterval()}}finally{e()}}))}sendOffer(e){c.debug("sending offer",e),this.sendRequest({$case:"offer",offer:ts(e)})}sendAnswer(e){return c.debug("sending answer"),this.sendRequest({$case:"answer",answer:ts(e)})}sendIceCandidate(e,t){return c.trace("sending ice candidate",e),this.sendRequest({$case:"trickle",trickle:{candidateInit:JSON.stringify(e),target:t}})}sendMuteTrack(e,t){return this.sendRequest({$case:"mute",mute:{sid:e,muted:t}})}sendAddTrack(e){return this.sendRequest({$case:"addTrack",addTrack:fn.fromPartial(e)})}sendUpdateLocalMetadata(e,t){return this.sendRequest({$case:"updateMetadata",updateMetadata:{metadata:e,name:t}})}sendUpdateTrackSettings(e){this.sendRequest({$case:"trackSetting",trackSetting:e})}sendUpdateSubscription(e){return this.sendRequest({$case:"subscription",subscription:e})}sendSyncState(e){return this.sendRequest({$case:"syncState",syncState:e})}sendUpdateVideoLayers(e,t){return this.sendRequest({$case:"updateLayers",updateLayers:{trackSid:e,layers:t}})}sendUpdateSubscriptionPermissions(e,t){return this.sendRequest({$case:"subscriptionPermission",subscriptionPermission:{allParticipants:e,trackPermissions:t}})}sendSimulateScenario(e){return this.sendRequest({$case:"simulate",simulate:e})}sendPing(){return Promise.all([this.sendRequest({$case:"ping",ping:Date.now()}),this.sendRequest({$case:"pingReq",pingReq:{timestamp:Date.now(),rtt:this.rtt}})])}sendLeave(){return this.sendRequest({$case:"leave",leave:{canReconnect:!1,reason:e.DisconnectReason.CLIENT_INITIATED}})}sendRequest(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return Ht(this,void 0,void 0,(function*(){const i=!t&&!function(e){const t=Yr.indexOf(e.$case)>=0;return c.trace("request allowed to bypass queue:",{canPass:t,req:e}),t}(e);if(i&&this.isReconnecting)return void this.queuedRequests.push((()=>Ht(this,void 0,void 0,(function*(){yield this.sendRequest(e,!0)}))));if(t||(yield this.requestQueue.flush()),this.signalLatency&&(yield kr(this.signalLatency)),!this.ws||this.ws.readyState!==this.ws.OPEN)return void c.error("cannot send signal request before connected, type: ".concat(null==e?void 0:e.$case));const n={message:e};try{this.useJSON?this.ws.send(JSON.stringify(hn.toJSON(n))):this.ws.send(hn.encode(n).finish())}catch(e){c.error("error sending signal message",{error:e})}}))}handleSignalResponse(e){var t,i;const n=e.message;if(null!=n)if("answer"===n.$case){const e=es(n.answer);this.onAnswer&&this.onAnswer(e)}else if("offer"===n.$case){const e=es(n.offer);this.onOffer&&this.onOffer(e)}else if("trickle"===n.$case){const e=JSON.parse(n.trickle.candidateInit);this.onTrickle&&this.onTrickle(e,n.trickle.target)}else"update"===n.$case?this.onParticipantUpdate&&this.onParticipantUpdate(null!==(t=n.update.participants)&&void 0!==t?t:[]):"trackPublished"===n.$case?this.onLocalTrackPublished&&this.onLocalTrackPublished(n.trackPublished):"speakersChanged"===n.$case?this.onSpeakersChanged&&this.onSpeakersChanged(null!==(i=n.speakersChanged.speakers)&&void 0!==i?i:[]):"leave"===n.$case?this.onLeave&&this.onLeave(n.leave):"mute"===n.$case?this.onRemoteMuteChanged&&this.onRemoteMuteChanged(n.mute.sid,n.mute.muted):"roomUpdate"===n.$case?this.onRoomUpdate&&n.roomUpdate.room&&this.onRoomUpdate(n.roomUpdate.room):"connectionQuality"===n.$case?this.onConnectionQuality&&this.onConnectionQuality(n.connectionQuality):"streamStateUpdate"===n.$case?this.onStreamStateUpdate&&this.onStreamStateUpdate(n.streamStateUpdate):"subscribedQualityUpdate"===n.$case?this.onSubscribedQualityUpdate&&this.onSubscribedQualityUpdate(n.subscribedQualityUpdate):"subscriptionPermissionUpdate"===n.$case?this.onSubscriptionPermissionUpdate&&this.onSubscriptionPermissionUpdate(n.subscriptionPermissionUpdate):"refreshToken"===n.$case?this.onTokenRefresh&&this.onTokenRefresh(n.refreshToken):"trackUnpublished"===n.$case?this.onLocalTrackUnpublished&&this.onLocalTrackUnpublished(n.trackUnpublished):"subscriptionResponse"===n.$case?this.onSubscriptionError&&this.onSubscriptionError(n.subscriptionResponse):"pong"===n.$case?this.resetPingTimeout():"pongResp"===n.$case?(this.rtt=Date.now()-n.pongResp.lastPingTimestamp,this.resetPingTimeout()):c.debug("unsupported message",n);else c.debug("received unsupported message")}setReconnected(){for(;this.queuedRequests.length>0;){const e=this.queuedRequests.shift();e&&this.requestQueue.run(e)}this.isReconnecting=!1}handleOnClose(e){return Ht(this,void 0,void 0,(function*(){this.isConnected&&(yield this.close(),c.debug("websocket connection closed: ".concat(e)),this.onClose&&this.onClose(e))}))}handleWSError(e){c.error("websocket error",e)}resetPingTimeout(){this.clearPingTimeout(),this.pingTimeoutDuration?this.pingTimeout=ar.setTimeout((()=>{c.warn("ping timeout triggered. last pong received at: ".concat(new Date(Date.now()-1e3*this.pingTimeoutDuration).toUTCString())),this.handleOnClose("ping timeout")}),1e3*this.pingTimeoutDuration):c.warn("ping timeout duration not set")}clearPingTimeout(){this.pingTimeout&&ar.clearTimeout(this.pingTimeout)}startPingInterval(){this.clearPingInterval(),this.resetPingTimeout(),this.pingIntervalDuration?(c.debug("start ping interval"),this.pingInterval=ar.setInterval((()=>{this.sendPing()}),1e3*this.pingIntervalDuration)):c.warn("ping interval duration not set")}clearPingInterval(){c.debug("clearing ping interval"),this.clearPingTimeout(),this.pingInterval&&ar.clearInterval(this.pingInterval)}}function es(e){const t={type:"offer",sdp:e.sdp};switch(e.type){case"answer":case"offer":case"pranswer":case"rollback":t.type=e.type}return t}function ts(e){return{sdp:e.sdp,type:e.type}}const is="default";class ns{static getInstance(){return void 0===this.instance&&(this.instance=new ns),this.instance}getDevices(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];var i;return Ht(this,void 0,void 0,(function*(){if((null===(i=ns.userMediaPromiseMap)||void 0===i?void 0:i.size)>0){c.debug("awaiting getUserMedia promise");try{e?yield ns.userMediaPromiseMap.get(e):yield Promise.all(ns.userMediaPromiseMap.values())}catch(e){c.warn("error waiting for media permissons")}}let n=yield navigator.mediaDevices.enumerateDevices();if(t&&e&&(!ns.userMediaPromiseMap.get(e)||!Nr())){if(0===n.length||n.some((t=>{const i=""===t.label,n=!e||t.kind===e;return i&&n}))){const t={video:"audioinput"!==e&&"audiooutput"!==e,audio:"videoinput"!==e},i=yield navigator.mediaDevices.getUserMedia(t);n=yield navigator.mediaDevices.enumerateDevices(),i.getTracks().forEach((e=>{e.stop()}))}}return e&&(n=n.filter((t=>t.kind===e))),n}))}normalizeDeviceId(e,t,i){return Ht(this,void 0,void 0,(function*(){if(t!==is)return t;const n=(yield this.getDevices(e)).find((e=>e.groupId===i&&e.deviceId!==is));return null==n?void 0:n.deviceId}))}}ns.mediaDeviceKinds=["audioinput","audiooutput","videoinput"],ns.userMediaPromiseMap=new Map;var rs={},ss={exports:{}},os=ss.exports={v:[{name:"version",reg:/^(\d*)$/}],o:[{name:"origin",reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:["username","sessionId","sessionVersion","netType","ipVer","address"],format:"%s %s %d %s IP%d %s"}],s:[{name:"name"}],i:[{name:"description"}],u:[{name:"uri"}],e:[{name:"email"}],p:[{name:"phone"}],z:[{name:"timezones"}],r:[{name:"repeats"}],t:[{name:"timing",reg:/^(\d*) (\d*)/,names:["start","stop"],format:"%d %d"}],c:[{name:"connection",reg:/^IN IP(\d) (\S*)/,names:["version","ip"],format:"IN IP%d %s"}],b:[{push:"bandwidth",reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:["type","limit"],format:"%s:%s"}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:["type","port","protocol","payloads"],format:"%s %d %s %s"}],a:[{push:"rtp",reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:["payload","codec","rate","encoding"],format:function(e){return e.encoding?"rtpmap:%d %s/%s/%s":e.rate?"rtpmap:%d %s/%s":"rtpmap:%d %s"}},{push:"fmtp",reg:/^fmtp:(\d*) ([\S| ]*)/,names:["payload","config"],format:"fmtp:%d %s"},{name:"control",reg:/^control:(.*)/,format:"control:%s"},{name:"rtcp",reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:["port","netType","ipVer","address"],format:function(e){return null!=e.address?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%s trr-int %d"},{push:"rtcpFb",reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:["payload","type","subtype"],format:function(e){return null!=e.subtype?"rtcp-fb:%s %s %s":"rtcp-fb:%s %s"}},{push:"ext",reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:["value","direction","encrypt-uri","uri","config"],format:function(e){return"extmap:%d"+(e.direction?"/%s":"%v")+(e["encrypt-uri"]?" %s":"%v")+" %s"+(e.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(e){return null!=e.sessionConfig?"crypto:%d %s %s %s":"crypto:%d %s %s"}},{name:"setup",reg:/^setup:(\w*)/,format:"setup:%s"},{name:"connectionType",reg:/^connection:(new|existing)/,format:"connection:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{name:"msid",reg:/^msid:(.*)/,format:"msid:%s"},{name:"ptime",reg:/^ptime:(\d*(?:\.\d*)*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\d*(?:\.\d*)*)/,format:"maxptime:%d"},{name:"direction",reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:"icelite",reg:/^(ice-lite)/},{name:"iceUfrag",reg:/^ice-ufrag:(\S*)/,format:"ice-ufrag:%s"},{name:"icePwd",reg:/^ice-pwd:(\S*)/,format:"ice-pwd:%s"},{name:"fingerprint",reg:/^fingerprint:(\S*) (\S*)/,names:["type","hash"],format:"fingerprint:%s %s"},{push:"candidates",reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation","network-id","network-cost"],format:function(e){var t="candidate:%s %d %s %d %s %d typ %s";return t+=null!=e.raddr?" raddr %s rport %d":"%v%v",t+=null!=e.tcptype?" tcptype %s":"%v",null!=e.generation&&(t+=" generation %d"),t+=null!=e["network-id"]?" network-id %d":"%v",t+=null!=e["network-cost"]?" network-cost %d":"%v"}},{name:"endOfCandidates",reg:/^(end-of-candidates)/},{name:"remoteCandidates",reg:/^remote-candidates:(.*)/,format:"remote-candidates:%s"},{name:"iceOptions",reg:/^ice-options:(\S*)/,format:"ice-options:%s"},{push:"ssrcs",reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:["id","attribute","value"],format:function(e){var t="ssrc:%d";return null!=e.attribute&&(t+=" %s",null!=e.value&&(t+=":%s")),t}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","maxMessageSize"],format:function(e){return null!=e.maxMessageSize?"sctpmap:%s %s %s":"sctpmap:%s %s"}},{name:"xGoogleFlag",reg:/^x-google-flag:([^\s]*)/,format:"x-google-flag:%s"},{push:"rids",reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:["id","direction","params"],format:function(e){return e.params?"rid:%s %s %s":"rid:%s %s"}},{push:"imageattrs",reg:new RegExp("^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?"),names:["pt","dir1","attrs1","dir2","attrs2"],format:function(e){return"imageattr:%s %s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast",reg:new RegExp("^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$"),names:["dir1","list1","dir2","list2"],format:function(e){return"simulcast:%s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast_03",reg:/^simulcast:[\s\t]+([\S+\s\t]+)$/,names:["value"],format:"simulcast: %s"},{name:"framerate",reg:/^framerate:(\d+(?:$|\.\d+))/,format:"framerate:%s"},{name:"sourceFilter",reg:/^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,names:["filterMode","netType","addressTypes","destAddress","srcList"],format:"source-filter: %s %s %s %s %s"},{name:"bundleOnly",reg:/^(bundle-only)/},{name:"label",reg:/^label:(.+)/,format:"label:%s"},{name:"sctpPort",reg:/^sctp-port:(\d+)$/,format:"sctp-port:%s"},{name:"maxMessageSize",reg:/^max-message-size:(\d+)$/,format:"max-message-size:%s"},{push:"tsRefClocks",reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:["clksrc","clksrcExt"],format:function(e){return"ts-refclk:%s"+(null!=e.clksrcExt?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(e){var t="mediaclk:";return t+=null!=e.id?"id=%s %s":"%v%s",t+=null!=e.mediaClockValue?"=%s":"",t+=null!=e.rateNumerator?" rate=%s":"",t+=null!=e.rateDenominator?"/%s":""}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{push:"invalid",names:["value"]}]};Object.keys(os).forEach((function(e){os[e].forEach((function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")}))}));var as=ss.exports;!function(e){var t=function(e){return String(Number(e))===e?Number(e):e},i=function(e,i,n){var r=e.name&&e.names;e.push&&!i[e.push]?i[e.push]=[]:r&&!i[e.name]&&(i[e.name]={});var s=e.push?{}:r?i[e.name]:i;!function(e,i,n,r){if(r&&!n)i[r]=t(e[1]);else for(var s=0;s<n.length;s+=1)null!=e[s+1]&&(i[n[s]]=t(e[s+1]))}(n.match(e.reg),s,e.names,e.name),e.push&&i[e.push].push(s)},n=as,r=RegExp.prototype.test.bind(/^([a-z])=(.*)/);e.parse=function(e){var t={},s=[],o=t;return e.split(/(\r\n|\r|\n)/).filter(r).forEach((function(e){var t=e[0],r=e.slice(2);"m"===t&&(s.push({rtp:[],fmtp:[]}),o=s[s.length-1]);for(var a=0;a<(n[t]||[]).length;a+=1){var c=n[t][a];if(c.reg.test(r))return i(c,o,r)}})),t.media=s,t};var s=function(e,i){var n=i.split(/=(.+)/,2);return 2===n.length?e[n[0]]=t(n[1]):1===n.length&&i.length>1&&(e[n[0]]=void 0),e};e.parseParams=function(e){return e.split(/;\s?/).reduce(s,{})},e.parseFmtpConfig=e.parseParams,e.parsePayloads=function(e){return e.toString().split(" ").map(Number)},e.parseRemoteCandidates=function(e){for(var i=[],n=e.split(" ").map(t),r=0;r<n.length;r+=3)i.push({component:n[r],ip:n[r+1],port:n[r+2]});return i},e.parseImageAttributes=function(e){return e.split(" ").map((function(e){return e.substring(1,e.length-1).split(",").reduce(s,{})}))},e.parseSimulcastStreamList=function(e){return e.split(";").map((function(e){return e.split(",").map((function(e){var i,n=!1;return"~"!==e[0]?i=t(e):(i=t(e.substring(1,e.length)),n=!0),{scid:i,paused:n}}))}))}}(rs);var cs=as,ds=/%[sdv%]/g,us=function(e){var t=1,i=arguments,n=i.length;return e.replace(ds,(function(e){if(t>=n)return e;var r=i[t];switch(t+=1,e){case"%%":return"%";case"%s":return String(r);case"%d":return Number(r);case"%v":return""}}))},ls=function(e,t,i){var n=[e+"="+(t.format instanceof Function?t.format(t.push?i:i[t.name]):t.format)];if(t.names)for(var r=0;r<t.names.length;r+=1){var s=t.names[r];t.name?n.push(i[t.name][s]):n.push(i[t.names[r]])}else n.push(i[t.name]);return us.apply(null,n)},hs=["v","o","s","i","u","e","p","c","b","t","r","z","a"],ps=["i","c","b","a"],ms=rs,fs=function(e,t){t=t||{},null==e.version&&(e.version=0),null==e.name&&(e.name=" "),e.media.forEach((function(e){null==e.payloads&&(e.payloads="")}));var i=t.outerOrder||hs,n=t.innerOrder||ps,r=[];return i.forEach((function(t){cs[t].forEach((function(i){i.name in e&&null!=e[i.name]?r.push(ls(t,i,e)):i.push in e&&null!=e[i.push]&&e[i.push].forEach((function(e){r.push(ls(t,i,e))}))}))})),e.media.forEach((function(e){r.push(ls("m",cs.m[0],e)),n.forEach((function(t){cs[t].forEach((function(i){i.name in e&&null!=e[i.name]?r.push(ls(t,i,e)):i.push in e&&null!=e[i.push]&&e[i.push].forEach((function(e){r.push(ls(t,i,e))}))}))}))})),r.join("\r\n")+"\r\n"},vs=fs,gs=ms.parse;function bs(e,t,i){var n,r,s;void 0===t&&(t=50),void 0===i&&(i={});var o=null!=(n=i.isImmediate)&&n,a=null!=(r=i.callback)&&r,c=i.maxWait,d=Date.now(),u=[];function l(){if(void 0!==c){var e=Date.now()-d;if(e+t>=c)return c-e}return t}var h=function(){var t=[].slice.call(arguments),i=this;return new Promise((function(n,r){var c=o&&void 0===s;if(void 0!==s&&clearTimeout(s),s=setTimeout((function(){if(s=void 0,d=Date.now(),!o){var n=e.apply(i,t);a&&a(n),u.forEach((function(e){return(0,e.resolve)(n)})),u=[]}}),l()),c){var h=e.apply(i,t);return a&&a(h),n(h)}u.push({resolve:n,reject:r})}))};return h.cancel=function(e){void 0!==s&&clearTimeout(s),u.forEach((function(t){return(0,t.reject)(e)})),u=[]},h}const ks="negotiationStarted",Ss="negotiationComplete";class ys extends Yt{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};var i;super(),this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate=!1,this.trackBitrates=[],this.remoteStereoMids=[],this.remoteNackMids=[],this.negotiate=bs((e=>{this.emit(ks);try{this.createAndSendOffer()}catch(t){if(!e)throw t;e(t)}}),100),this.pc="Chrome"===(null===(i=ur())||void 0===i?void 0:i.name)?new RTCPeerConnection(e,t):new RTCPeerConnection(e)}get isICEConnected(){return"connected"===this.pc.iceConnectionState||"completed"===this.pc.iceConnectionState}addIceCandidate(e){return Ht(this,void 0,void 0,(function*(){if(this.pc.remoteDescription&&!this.restartingIce)return this.pc.addIceCandidate(e);this.pendingCandidates.push(e)}))}setRemoteDescription(e){var t;return Ht(this,void 0,void 0,(function*(){let i;if("offer"===e.type){let{stereoMids:t,nackMids:i}=function(e){var t;const i=[],n=[],r=gs(null!==(t=e.sdp)&&void 0!==t?t:"");let s=0;return r.media.forEach((e=>{var t;"audio"===e.type&&(e.rtp.some((e=>"opus"===e.codec&&(s=e.payload,!0))),(null===(t=e.rtcpFb)||void 0===t?void 0:t.some((e=>e.payload===s&&"nack"===e.type)))&&n.push(e.mid),e.fmtp.some((t=>t.payload===s&&(t.config.includes("sprop-stereo=1")&&i.push(e.mid),!0))))})),{stereoMids:i,nackMids:n}}(e);this.remoteStereoMids=t,this.remoteNackMids=i}else if("answer"===e.type){const n=gs(null!==(t=e.sdp)&&void 0!==t?t:"");n.media.forEach((e=>{"audio"===e.type&&this.trackBitrates.some((t=>{if(!t.transceiver||e.mid!=t.transceiver.mid)return!1;let i=0;if(e.rtp.some((e=>e.codec.toUpperCase()===t.codec.toUpperCase()&&(i=e.payload,!0))),0===i)return!0;let n=!1;for(const r of e.fmtp)if(r.payload===i){r.config=r.config.split(";").filter((e=>!e.includes("maxaveragebitrate"))).join(";"),t.maxbr>0&&(r.config+=";maxaveragebitrate=".concat(1e3*t.maxbr)),n=!0;break}return n||t.maxbr>0&&e.fmtp.push({payload:i,config:"maxaveragebitrate=".concat(1e3*t.maxbr)}),!0}))})),i=vs(n)}yield this.setMungedSDP(e,i,!0),this.pendingCandidates.forEach((e=>{this.pc.addIceCandidate(e)})),this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate?(this.renegotiate=!1,this.createAndSendOffer()):"answer"===e.type&&this.emit(Ss)}))}createAndSendOffer(e){var t;return Ht(this,void 0,void 0,(function*(){if(void 0===this.onOffer)return;if((null==e?void 0:e.iceRestart)&&(c.debug("restarting ICE"),this.restartingIce=!0),"have-local-offer"===this.pc.signalingState){const t=this.pc.remoteDescription;if(!(null==e?void 0:e.iceRestart)||!t)return void(this.renegotiate=!0);yield this.pc.setRemoteDescription(t)}else if("closed"===this.pc.signalingState)return void c.warn("could not createOffer with closed peer connection");c.debug("starting to negotiate");const i=yield this.pc.createOffer(e),n=gs(null!==(t=i.sdp)&&void 0!==t?t:"");n.media.forEach((e=>{"audio"===e.type?Cs(e,[],[]):"video"===e.type&&(!function(e){var t,i,n,r;const s=null===(i=null===(t=e.rtp[0])||void 0===t?void 0:t.codec)||void 0===i?void 0:i.toLowerCase();if(!Er(s))return;let o=0;const a=null===(n=e.ext)||void 0===n?void 0:n.some((e=>e.uri===br||(e.value>o&&(o=e.value),!1)));a||null===(r=e.ext)||void 0===r||r.push({value:o+1,uri:br})}(e),this.trackBitrates.some((t=>{if(!e.msid||!t.cid||!e.msid.includes(t.cid))return!1;let i=0;if(e.rtp.some((e=>e.codec.toUpperCase()===t.codec.toUpperCase()&&(i=e.payload,!0))),0===i)return!0;let n=!1;for(const r of e.fmtp)if(r.payload===i){r.config.includes("x-google-start-bitrate")||(r.config+=";x-google-start-bitrate=".concat(.7*t.maxbr)),r.config.includes("x-google-max-bitrate")||(r.config+=";x-google-max-bitrate=".concat(t.maxbr)),n=!0;break}return n||e.fmtp.push({payload:i,config:"x-google-start-bitrate=".concat(.7*t.maxbr,";x-google-max-bitrate=").concat(t.maxbr)}),!0})))})),yield this.setMungedSDP(i,vs(n)),this.onOffer(i)}))}createAndSetAnswer(){var e;return Ht(this,void 0,void 0,(function*(){const t=yield this.pc.createAnswer(),i=gs(null!==(e=t.sdp)&&void 0!==e?e:"");return i.media.forEach((e=>{"audio"===e.type&&Cs(e,this.remoteStereoMids,this.remoteNackMids)})),yield this.setMungedSDP(t,vs(i)),t}))}setTrackCodecBitrate(e){this.trackBitrates.push(e)}close(){this.pc.onconnectionstatechange=null,this.pc.oniceconnectionstatechange=null,this.pc.close()}setMungedSDP(e,t,i){return Ht(this,void 0,void 0,(function*(){if(t){const n=e.sdp;e.sdp=t;try{return c.debug("setting munged ".concat(i?"remote":"local"," description")),void(i?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e))}catch(t){c.warn("not able to set ".concat(e.type,", falling back to unmodified sdp"),{error:t}),e.sdp=n}}try{i?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e)}catch(e){let t="unknown error";throw e instanceof Error?t=e.message:"string"==typeof e&&(t=e),new or(t)}}))}}function Cs(e,t,i){let n=0;e.rtp.some((e=>"opus"===e.codec&&(n=e.payload,!0))),n>0&&(e.rtcpFb||(e.rtcpFb=[]),i.includes(e.mid)&&!e.rtcpFb.some((e=>e.payload===n&&"nack"===e.type))&&e.rtcpFb.push({payload:n,type:"nack"}),t.includes(e.mid)&&e.fmtp.some((e=>e.payload===n&&(e.config.includes("stereo=1")||(e.config+=";stereo=1"),!0))))}class Ts{constructor(e,t){this.lastUpdateAt=0,this.settingsCacheTime=3e3,this.attemptedRegions=[],this.serverUrl=new URL(e),this.token=t}isCloud(){return Ar(this.serverUrl)}getNextBestRegionUrl(e){return Ht(this,void 0,void 0,(function*(){if(!this.isCloud())throw Error("region availability is only supported for LiveKit Cloud domains");(!this.regionSettings||Date.now()-this.lastUpdateAt>this.settingsCacheTime)&&(this.regionSettings=yield this.fetchRegionSettings(e));const t=this.regionSettings.regions.filter((e=>!this.attemptedRegions.find((t=>t.url===e.url))));if(t.length>0){const e=t[0];return this.attemptedRegions.push(e),c.debug("next region: ".concat(e.region)),e.url}return null}))}resetAttempts(){this.attemptedRegions=[]}fetchRegionSettings(e){return Ht(this,void 0,void 0,(function*(){const t=yield fetch("".concat((i=this.serverUrl,"".concat(i.protocol.replace("ws","http"),"//").concat(i.host,"/settings")),"/regions"),{headers:{authorization:"Bearer ".concat(this.token)},signal:e});var i;if(t.ok){const e=yield t.json();return this.lastUpdateAt=Date.now(),e}throw new tr("Could not fetch region settings: ".concat(t.statusText),401===t.status?0:void 0,t.status)}))}}class Es{constructor(e,t,i,n,r){this.width=e,this.height=t,this.encoding={maxBitrate:i,maxFramerate:n,priority:r}}get resolution(){return{width:this.width,height:this.height,frameRate:this.encoding.maxFramerate,aspectRatio:this.width/this.height}}}const Ps=["vp8","h264"];function ws(e){return!!Ps.find((t=>t===e))}function Rs(e,t){return(null==e?void 0:e.toLowerCase().replace(/audio\/|video\//y,""))===(null==t?void 0:t.toLowerCase().replace(/audio\/|video\//y,""))}var Ns;e.AudioPresets=void 0,(Ns=e.AudioPresets||(e.AudioPresets={})).telephone={maxBitrate:12e3},Ns.speech={maxBitrate:2e4},Ns.music={maxBitrate:32e3},Ns.musicStereo={maxBitrate:48e3},Ns.musicHighQuality={maxBitrate:64e3},Ns.musicHighQualityStereo={maxBitrate:96e3};const Os={h90:new Es(160,90,6e4,15),h180:new Es(320,180,12e4,15),h216:new Es(384,216,18e4,15),h360:new Es(640,360,3e5,20),h540:new Es(960,540,6e5,25),h720:new Es(1280,720,17e5,30),h1080:new Es(1920,1080,3e6,30),h1440:new Es(2560,1440,5e6,30),h2160:new Es(3840,2160,8e6,30)},Ds={h120:new Es(160,120,8e4,15),h180:new Es(240,180,1e5,15),h240:new Es(320,240,15e4,15),h360:new Es(480,360,225e3,20),h480:new Es(640,480,3e5,20),h540:new Es(720,540,45e4,25),h720:new Es(960,720,15e5,30),h1080:new Es(1440,1080,25e5,30),h1440:new Es(1920,1440,35e5,30)},Is={h360fps3:new Es(640,360,2e5,3,"medium"),h720fps5:new Es(1280,720,4e5,5,"medium"),h720fps15:new Es(1280,720,1e6,15,"medium"),h1080fps15:new Es(1920,1080,15e5,15,"medium"),h1080fps30:new Es(1920,1080,3e6,30,"medium")},As={audioBitrate:e.AudioPresets.music.maxBitrate,audioPreset:e.AudioPresets.music,dtx:!0,red:!0,forceStereo:!1,simulcast:!0,screenShareEncoding:Is.h1080fps15.encoding,stopMicTrackOnMute:!1,videoCodec:"vp8",backupCodec:{codec:"vp8",encoding:Os.h540.encoding}},Us={autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0},Ms={resolution:Os.h720.resolution},Ls={adaptiveStream:!1,dynacast:!1,stopLocalTrackOnUnpublish:!0,reconnectPolicy:new Qt,disconnectOnPageLeave:!0,expWebAudioMix:!1},_s={autoSubscribe:!0,maxRetries:1,peerConnectionTimeout:15e3};var xs,Bs,Js,Fs;e.RoomEvent=void 0,(xs=e.RoomEvent||(e.RoomEvent={})).Connected="connected",xs.Reconnecting="reconnecting",xs.Reconnected="reconnected",xs.Disconnected="disconnected",xs.ConnectionStateChanged="connectionStateChanged",xs.StateChanged="connectionStateChanged",xs.MediaDevicesChanged="mediaDevicesChanged",xs.ParticipantConnected="participantConnected",xs.ParticipantDisconnected="participantDisconnected",xs.TrackPublished="trackPublished",xs.TrackSubscribed="trackSubscribed",xs.TrackSubscriptionFailed="trackSubscriptionFailed",xs.TrackUnpublished="trackUnpublished",xs.TrackUnsubscribed="trackUnsubscribed",xs.TrackMuted="trackMuted",xs.TrackUnmuted="trackUnmuted",xs.LocalTrackPublished="localTrackPublished",xs.LocalTrackUnpublished="localTrackUnpublished",xs.LocalAudioSilenceDetected="localAudioSilenceDetected",xs.ActiveSpeakersChanged="activeSpeakersChanged",xs.ParticipantMetadataChanged="participantMetadataChanged",xs.ParticipantNameChanged="participantNameChanged",xs.RoomMetadataChanged="roomMetadataChanged",xs.DataReceived="dataReceived",xs.ConnectionQualityChanged="connectionQualityChanged",xs.TrackStreamStateChanged="trackStreamStateChanged",xs.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",xs.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",xs.AudioPlaybackStatusChanged="audioPlaybackChanged",xs.MediaDevicesError="mediaDevicesError",xs.ParticipantPermissionsChanged="participantPermissionsChanged",xs.SignalConnected="signalConnected",xs.RecordingStatusChanged="recordingStatusChanged",xs.DCBufferStatusChanged="dcBufferStatusChanged",xs.ActiveDeviceChanged="activeDeviceChanged",e.ParticipantEvent=void 0,(Bs=e.ParticipantEvent||(e.ParticipantEvent={})).TrackPublished="trackPublished",Bs.TrackSubscribed="trackSubscribed",Bs.TrackSubscriptionFailed="trackSubscriptionFailed",Bs.TrackUnpublished="trackUnpublished",Bs.TrackUnsubscribed="trackUnsubscribed",Bs.TrackMuted="trackMuted",Bs.TrackUnmuted="trackUnmuted",Bs.LocalTrackPublished="localTrackPublished",Bs.LocalTrackUnpublished="localTrackUnpublished",Bs.ParticipantMetadataChanged="participantMetadataChanged",Bs.ParticipantNameChanged="participantNameChanged",Bs.DataReceived="dataReceived",Bs.IsSpeakingChanged="isSpeakingChanged",Bs.ConnectionQualityChanged="connectionQualityChanged",Bs.TrackStreamStateChanged="trackStreamStateChanged",Bs.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",Bs.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",Bs.MediaDevicesError="mediaDevicesError",Bs.ParticipantPermissionsChanged="participantPermissionsChanged",e.EngineEvent=void 0,(Js=e.EngineEvent||(e.EngineEvent={})).TransportsCreated="transportsCreated",Js.Connected="connected",Js.Disconnected="disconnected",Js.Resuming="resuming",Js.Resumed="resumed",Js.Restarting="restarting",Js.Restarted="restarted",Js.SignalResumed="signalResumed",Js.SignalRestarted="signalRestarted",Js.Closing="closing",Js.MediaTrackAdded="mediaTrackAdded",Js.ActiveSpeakersUpdate="activeSpeakersUpdate",Js.DataPacketReceived="dataPacketReceived",Js.DCBufferStatusChanged="dcBufferStatusChanged",e.TrackEvent=void 0,(Fs=e.TrackEvent||(e.TrackEvent={})).Message="message",Fs.Muted="muted",Fs.Unmuted="unmuted",Fs.Restarted="restarted",Fs.Ended="ended",Fs.Subscribed="subscribed",Fs.Unsubscribed="unsubscribed",Fs.UpdateSettings="updateSettings",Fs.UpdateSubscription="updateSubscription",Fs.AudioPlaybackStarted="audioPlaybackStarted",Fs.AudioPlaybackFailed="audioPlaybackFailed",Fs.AudioSilenceDetected="audioSilenceDetected",Fs.VisibilityChanged="visibilityChanged",Fs.VideoDimensionsChanged="videoDimensionsChanged",Fs.ElementAttached="elementAttached",Fs.ElementDetached="elementDetached",Fs.UpstreamPaused="upstreamPaused",Fs.UpstreamResumed="upstreamResumed",Fs.SubscriptionPermissionChanged="subscriptionPermissionChanged",Fs.SubscriptionStatusChanged="subscriptionStatusChanged",Fs.SubscriptionFailed="subscriptionFailed";const $s=[];class js extends Yt{constructor(e,t){super(),this.attachedElements=[],this.isMuted=!1,this.streamState=js.StreamState.Active,this.isInBackground=!1,this._currentBitrate=0,this.appVisibilityChangedListener=()=>{this.backgroundTimeout&&clearTimeout(this.backgroundTimeout),"hidden"===document.visibilityState?this.backgroundTimeout=setTimeout((()=>this.handleAppVisibilityChanged()),5e3):this.handleAppVisibilityChanged()},this.kind=t,this._mediaStreamTrack=e,this._mediaStreamID=e.id,this.source=js.Source.Unknown}get currentBitrate(){return this._currentBitrate}get mediaStreamTrack(){return this._mediaStreamTrack}get mediaStreamID(){return this._mediaStreamID}attach(t){let i="audio";this.kind===js.Kind.Video&&(i="video"),0===this.attachedElements.length&&js.Kind.Video&&this.addAppVisibilityListener(),t||("audio"===i&&($s.forEach((e=>{null!==e.parentElement||t||(t=e)})),t&&$s.splice($s.indexOf(t),1)),t||(t=document.createElement(i))),this.attachedElements.includes(t)||this.attachedElements.push(t),Vs(this.mediaStreamTrack,t);const n=t.srcObject.getTracks();return n.some((e=>"audio"===e.kind))&&t.play().then((()=>{this.emit(e.TrackEvent.AudioPlaybackStarted)})).catch((i=>{"NotAllowedError"===i.name?this.emit(e.TrackEvent.AudioPlaybackFailed,i):c.warn("could not playback audio",i),t&&n.some((e=>"video"===e.kind))&&"NotAllowedError"===i.name&&(t.muted=!0,t.play().catch((()=>{})))})),this.emit(e.TrackEvent.ElementAttached,t),t}detach(t){try{if(t){qs(this.mediaStreamTrack,t);const i=this.attachedElements.indexOf(t);return i>=0&&(this.attachedElements.splice(i,1),this.recycleElement(t),this.emit(e.TrackEvent.ElementDetached,t)),t}const i=[];return this.attachedElements.forEach((t=>{qs(this.mediaStreamTrack,t),i.push(t),this.recycleElement(t),this.emit(e.TrackEvent.ElementDetached,t)})),this.attachedElements=[],i}finally{0===this.attachedElements.length&&this.removeAppVisibilityListener()}}stop(){this.stopMonitor(),this._mediaStreamTrack.stop()}enable(){this._mediaStreamTrack.enabled=!0}disable(){this._mediaStreamTrack.enabled=!1}stopMonitor(){this.monitorInterval&&clearInterval(this.monitorInterval)}recycleElement(e){if(e instanceof HTMLAudioElement){let t=!0;e.pause(),$s.forEach((e=>{e.parentElement||(t=!1)})),t&&$s.push(e)}}handleAppVisibilityChanged(){return Ht(this,void 0,void 0,(function*(){this.isInBackground="hidden"===document.visibilityState}))}addAppVisibilityListener(){Dr()?(this.isInBackground="hidden"===document.visibilityState,document.addEventListener("visibilitychange",this.appVisibilityChangedListener)):this.isInBackground=!1}removeAppVisibilityListener(){Dr()&&document.removeEventListener("visibilitychange",this.appVisibilityChangedListener)}}function Vs(e,t){let i,n;i=t.srcObject instanceof MediaStream?t.srcObject:new MediaStream,n="audio"===e.kind?i.getAudioTracks():i.getVideoTracks(),n.includes(e)||(n.forEach((e=>{i.removeTrack(e)})),i.addTrack(e)),t.autoplay=!0,t.muted=0===i.getAudioTracks().length,t instanceof HTMLVideoElement&&(t.playsInline=!0),t.srcObject!==i&&(t.srcObject=i,(Nr()||Rr())&&t instanceof HTMLVideoElement&&setTimeout((()=>{t.srcObject=i,t.play().catch((()=>{}))}),0))}function qs(e,t){if(t.srcObject instanceof MediaStream){const i=t.srcObject;i.removeTrack(e),i.getTracks().length>0?t.srcObject=i:t.srcObject=null}}!function(e){let t,i,n;!function(e){e.Audio="audio",e.Video="video",e.Unknown="unknown"}(t=e.Kind||(e.Kind={})),function(e){e.Camera="camera",e.Microphone="microphone",e.ScreenShare="screen_share",e.ScreenShareAudio="screen_share_audio",e.Unknown="unknown"}(i=e.Source||(e.Source={})),function(e){e.Active="active",e.Paused="paused",e.Unknown="unknown"}(n=e.StreamState||(e.StreamState={})),e.kindToProto=function(e){switch(e){case t.Audio:return Ge.AUDIO;case t.Video:return Ge.VIDEO;default:return Ge.UNRECOGNIZED}},e.kindFromProto=function(e){switch(e){case Ge.AUDIO:return t.Audio;case Ge.VIDEO:return t.Video;default:return t.Unknown}},e.sourceToProto=function(e){switch(e){case i.Camera:return Qe.CAMERA;case i.Microphone:return Qe.MICROPHONE;case i.ScreenShare:return Qe.SCREEN_SHARE;case i.ScreenShareAudio:return Qe.SCREEN_SHARE_AUDIO;default:return Qe.UNRECOGNIZED}},e.sourceFromProto=function(e){switch(e){case Qe.CAMERA:return i.Camera;case Qe.MICROPHONE:return i.Microphone;case Qe.SCREEN_SHARE:return i.ScreenShare;case Qe.SCREEN_SHARE_AUDIO:return i.ScreenShareAudio;default:return i.Unknown}},e.streamStateFromProto=function(e){switch(e){case sn.ACTIVE:return n.Active;case sn.PAUSED:return n.Paused;default:return n.Unknown}}}(js||(js={}));const Ws="_lossy",Gs="_reliable",Qs="leave-reconnect";var Hs;!function(e){e[e.New=0]="New",e[e.Connected=1]="Connected",e[e.Disconnected=2]="Disconnected",e[e.Reconnecting=3]="Reconnecting",e[e.Closed=4]="Closed"}(Hs||(Hs={}));class Ks extends Yt{get isClosed(){return this._isClosed}constructor(t){super(),this.options=t,this.rtcConfig={},this.peerConnectionTimeout=_s.peerConnectionTimeout,this.fullReconnectOnNext=!1,this.subscriberPrimary=!1,this.pcState=Hs.New,this._isClosed=!0,this.pendingTrackResolvers={},this.hasPublished=!1,this.reconnectAttempts=0,this.reconnectStart=0,this.attemptingReconnect=!1,this.joinAttempts=0,this.maxJoinAttempts=1,this.shouldFailNext=!1,this.handleDataChannel=e=>{let{channel:t}=e;return Ht(this,void 0,void 0,(function*(){if(t){if(t.label===Gs)this.reliableDCSub=t;else{if(t.label!==Ws)return;this.lossyDCSub=t}c.debug("on data channel ".concat(t.id,", ").concat(t.label)),t.onmessage=this.handleDataMessage}}))},this.handleDataMessage=t=>Ht(this,void 0,void 0,(function*(){var i,n;const r=yield this.dataProcessLock.lock();try{let r;if(t.data instanceof ArrayBuffer)r=t.data;else{if(!(t.data instanceof Blob))return void c.error("unsupported data type",t.data);r=yield t.data.arrayBuffer()}const s=Dt.decode(new Uint8Array(r));"speaker"===(null===(i=s.value)||void 0===i?void 0:i.$case)?this.emit(e.EngineEvent.ActiveSpeakersUpdate,s.value.speaker.speakers):"user"===(null===(n=s.value)||void 0===n?void 0:n.$case)&&this.emit(e.EngineEvent.DataPacketReceived,s.value.user,s.kind)}finally{r()}})),this.handleDataError=e=>{const t=0===e.currentTarget.maxRetransmits?"lossy":"reliable";if(e instanceof ErrorEvent){const{error:i}=e.error;c.error("DataChannel error on ".concat(t,": ").concat(e.message),i)}else c.error("Unknown DataChannel Error on ".concat(t),e)},this.handleBufferedAmountLow=t=>{const i=0===t.currentTarget.maxRetransmits?e.DataPacket_Kind.LOSSY:e.DataPacket_Kind.RELIABLE;this.updateAndEmitDCBufferStatus(i)},this.handleDisconnect=(t,i)=>{if(this._isClosed)return;c.warn("".concat(t," disconnected")),0===this.reconnectAttempts&&(this.reconnectStart=Date.now());const n=t=>{c.warn("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(t,"ms. giving up")),this.emit(e.EngineEvent.Disconnected),this.close()},r=Date.now()-this.reconnectStart;let s=this.getNextRetryDelay({elapsedMs:r,retryCount:this.reconnectAttempts});null!==s?(t===Qs&&(s=0),c.debug("reconnecting in ".concat(s,"ms")),this.clearReconnectTimeout(),this.url&&this.token&&Ar(new URL(this.url))&&(this.regionUrlProvider=new Ts(this.url,this.token)),this.reconnectTimeout=ar.setTimeout((()=>this.attemptReconnect(i)),s)):n(r)},this.waitForRestarted=()=>new Promise(((t,i)=>{this.pcState===Hs.Connected&&t();const n=()=>{this.off(e.EngineEvent.Disconnected,r),t()},r=()=>{this.off(e.EngineEvent.Restarted,n),i()};this.once(e.EngineEvent.Restarted,n),this.once(e.EngineEvent.Disconnected,r),this.once(e.EngineEvent.Closing,r)})),this.updateAndEmitDCBufferStatus=t=>{const i=this.isBufferStatusLow(t);void 0!==i&&i!==this.dcBufferStatus.get(t)&&(this.dcBufferStatus.set(t,i),this.emit(e.EngineEvent.DCBufferStatusChanged,i,t))},this.isBufferStatusLow=e=>{const t=this.dataChannelForKind(e);if(t)return t.bufferedAmount<=t.bufferedAmountLowThreshold},this.handleBrowserOnLine=()=>{this.client.isReconnecting&&(this.clearReconnectTimeout(),this.attemptReconnect(Ye.RR_SIGNAL_DISCONNECTED))},this.client=new Xr,this.client.signalLatency=this.options.expSignalLatency,this.reconnectPolicy=this.options.reconnectPolicy,this.registerOnLineListener(),this.closingLock=new Hr,this.dataProcessLock=new Hr,this.dcBufferStatus=new Map([[e.DataPacket_Kind.LOSSY,!0],[e.DataPacket_Kind.RELIABLE,!0]])}join(e,t,i,n){return Ht(this,void 0,void 0,(function*(){this.url=e,this.token=t,this.signalOpts=i;try{this.joinAttempts+=1;const r=yield this.client.join(e,t,i,n);return this._isClosed=!1,this.latestJoinResponse=r,this.subscriberPrimary=r.subscriberPrimary,this.publisher||this.configure(r),this.subscriberPrimary||this.negotiate(),this.clientConfiguration=r.clientConfiguration,r}catch(r){if(r instanceof tr&&1===r.reason&&(c.warn("Couldn't connect to server, attempt ".concat(this.joinAttempts," of ").concat(this.maxJoinAttempts)),this.joinAttempts<this.maxJoinAttempts))return this.join(e,t,i,n);throw r}}))}close(){return Ht(this,void 0,void 0,(function*(){const t=yield this.closingLock.lock();if(this.isClosed)t();else try{this._isClosed=!0,this.emit(e.EngineEvent.Closing),this.removeAllListeners(),this.deregisterOnLineListener(),this.clearPendingReconnect(),this.publisher&&"closed"!==this.publisher.pc.signalingState&&(this.publisher.pc.getSenders().forEach((e=>{var t,i;try{(null===(t=this.publisher)||void 0===t?void 0:t.pc.removeTrack)&&(null===(i=this.publisher)||void 0===i||i.pc.removeTrack(e))}catch(e){c.warn("could not removeTrack",{error:e})}})),this.publisher.close(),this.publisher=void 0),this.subscriber&&(this.subscriber.close(),this.subscriber=void 0),yield this.client.close()}finally{t()}}))}addTrack(e){if(this.pendingTrackResolvers[e.cid])throw new nr("a track with the same ID has already been published");return new Promise(((t,i)=>{const n=setTimeout((()=>{delete this.pendingTrackResolvers[e.cid],i(new tr("publication of local track timed out, no response from server"))}),1e4);this.pendingTrackResolvers[e.cid]={resolve:e=>{clearTimeout(n),t(e)},reject:()=>{clearTimeout(n),i(new Error("Cancelled publication by calling unpublish"))}},this.client.sendAddTrack(e)}))}removeTrack(e){var t;if(e.track&&this.pendingTrackResolvers[e.track.id]){const{reject:t}=this.pendingTrackResolvers[e.track.id];t&&t(),delete this.pendingTrackResolvers[e.track.id]}try{return null===(t=this.publisher)||void 0===t||t.pc.removeTrack(e),!0}catch(e){c.warn("failed to remove track",{error:e,method:"removeTrack"})}return!1}updateMuteStatus(e,t){this.client.sendMuteTrack(e,t)}get dataSubscriberReadyState(){var e;return null===(e=this.reliableDCSub)||void 0===e?void 0:e.readyState}getConnectedServerAddress(){return Ht(this,void 0,void 0,(function*(){if(void 0!==this.primaryPC)return function(e){var t;return Ht(this,void 0,void 0,(function*(){let i="";const n=new Map,r=new Map;if((yield e.getStats()).forEach((e=>{switch(e.type){case"transport":i=e.selectedCandidatePairId;break;case"candidate-pair":""===i&&e.selected&&(i=e.id),n.set(e.id,e);break;case"remote-candidate":r.set(e.id,"".concat(e.address,":").concat(e.port))}})),""===i)return;const s=null===(t=n.get(i))||void 0===t?void 0:t.remoteCandidateId;return void 0!==s?r.get(s):void 0}))}(this.primaryPC)}))}configure(t){var i;if(this.publisher||this.subscriber)return;this.participantSid=null===(i=t.participant)||void 0===i?void 0:i.sid;const n=this.makeRTCConfiguration(t);this.publisher=new ys(n,{optional:[{googDscp:!0}]}),this.subscriber=new ys(n),this.emit(e.EngineEvent.TransportsCreated,this.publisher,this.subscriber),this.publisher.pc.onicecandidate=e=>{e.candidate&&(c.trace("adding ICE candidate for peer",e.candidate),this.client.sendIceCandidate(e.candidate,rn.PUBLISHER))},this.subscriber.pc.onicecandidate=e=>{e.candidate&&this.client.sendIceCandidate(e.candidate,rn.SUBSCRIBER)},this.publisher.onOffer=e=>{this.client.sendOffer(e)};let r=this.publisher.pc,s=this.subscriber.pc,o=t.subscriberPrimary;o&&(r=this.subscriber.pc,s=this.publisher.pc,this.subscriber.pc.ondatachannel=this.handleDataChannel),this.primaryPC=r,r.onconnectionstatechange=()=>Ht(this,void 0,void 0,(function*(){if(c.debug("primary PC state changed ".concat(r.connectionState)),"connected"===r.connectionState){const i=this.pcState===Hs.New;this.pcState=Hs.Connected,i&&this.emit(e.EngineEvent.Connected,t)}else"failed"===r.connectionState&&this.pcState===Hs.Connected&&(this.pcState=Hs.Disconnected,this.handleDisconnect("primary peerconnection",o?Ye.RR_SUBSCRIBER_FAILED:Ye.RR_PUBLISHER_FAILED))})),s.onconnectionstatechange=()=>Ht(this,void 0,void 0,(function*(){c.debug("secondary PC state changed ".concat(s.connectionState)),"failed"===s.connectionState&&this.handleDisconnect("secondary peerconnection",o?Ye.RR_PUBLISHER_FAILED:Ye.RR_SUBSCRIBER_FAILED)})),this.subscriber.pc.ontrack=t=>{this.emit(e.EngineEvent.MediaTrackAdded,t.track,t.streams[0],t.receiver)},this.createDataChannels(),this.client.onAnswer=e=>Ht(this,void 0,void 0,(function*(){this.publisher&&(c.debug("received server answer",{RTCSdpType:e.type,signalingState:this.publisher.pc.signalingState}),yield this.publisher.setRemoteDescription(e))})),this.client.onTrickle=(e,t)=>{this.publisher&&this.subscriber&&(c.trace("got ICE candidate from peer",{candidate:e,target:t}),t===rn.PUBLISHER?this.publisher.addIceCandidate(e):this.subscriber.addIceCandidate(e))},this.client.onOffer=e=>Ht(this,void 0,void 0,(function*(){if(!this.subscriber)return;c.debug("received server offer",{RTCSdpType:e.type,signalingState:this.subscriber.pc.signalingState}),yield this.subscriber.setRemoteDescription(e);const t=yield this.subscriber.createAndSetAnswer();this.client.sendAnswer(t)})),this.client.onLocalTrackPublished=e=>{c.debug("received trackPublishedResponse",e);const{resolve:t}=this.pendingTrackResolvers[e.cid];t?(delete this.pendingTrackResolvers[e.cid],t(e.track)):c.error("missing track resolver for ".concat(e.cid))},this.client.onTokenRefresh=e=>{this.token=e},this.client.onClose=()=>{this.handleDisconnect("signal",Ye.RR_SIGNAL_DISCONNECTED)},this.client.onLeave=t=>{(null==t?void 0:t.canReconnect)?(this.fullReconnectOnNext=!0,this.primaryPC=void 0,this.handleDisconnect(Qs)):(this.emit(e.EngineEvent.Disconnected,null==t?void 0:t.reason),this.close()),c.trace("leave request",{leave:t})}}makeRTCConfiguration(e){const t=Object.assign({},this.rtcConfig);if(e.iceServers&&!t.iceServers){const i=[];e.iceServers.forEach((e=>{const t={urls:e.urls};e.username&&(t.username=e.username),e.credential&&(t.credential=e.credential),i.push(t)})),t.iceServers=i}return e.clientConfiguration&&e.clientConfiguration.forceRelay===Ze.ENABLED&&(t.iceTransportPolicy="relay"),t.sdpSemantics="unified-plan",t.continualGatheringPolicy="gather_continually",t}createDataChannels(){this.publisher&&(this.lossyDC&&(this.lossyDC.onmessage=null,this.lossyDC.onerror=null),this.reliableDC&&(this.reliableDC.onmessage=null,this.reliableDC.onerror=null),this.lossyDC=this.publisher.pc.createDataChannel(Ws,{ordered:!0,maxRetransmits:0}),this.reliableDC=this.publisher.pc.createDataChannel(Gs,{ordered:!0}),this.lossyDC.onmessage=this.handleDataMessage,this.reliableDC.onmessage=this.handleDataMessage,this.lossyDC.onerror=this.handleDataError,this.reliableDC.onerror=this.handleDataError,this.lossyDC.bufferedAmountLowThreshold=65535,this.reliableDC.bufferedAmountLowThreshold=65535,this.lossyDC.onbufferedamountlow=this.handleBufferedAmountLow,this.reliableDC.onbufferedamountlow=this.handleBufferedAmountLow)}setPreferredCodec(e,t,i){if(!("getCapabilities"in RTCRtpSender))return;const n=RTCRtpSender.getCapabilities(t);if(!n)return;c.debug("get capabilities",n);const r=[],s=[],o=[];n.codecs.forEach((e=>{const t=e.mimeType.toLowerCase();if("audio/opus"===t)return void r.push(e);t==="video/".concat(i)?"h264"!==i||e.sdpFmtpLine&&e.sdpFmtpLine.includes("profile-level-id=42e01f")?r.push(e):s.push(e):o.push(e)})),function(e){if(!Dr())return!1;if(!("setCodecPreferences"in e))return!1;const t=ur();if(!(null==t?void 0:t.name)||!t.version)return!1;const i=wr[t.name];return!!i&&_r(t.version,i)>=0}(e)&&e.setCodecPreferences(r.concat(s,o))}createSender(e,t,i){return Ht(this,void 0,void 0,(function*(){if(Sr())return this.createTransceiverRTCRtpSender(e,t,i);if(yr())return c.debug("using add-track fallback"),this.createRTCRtpSender(e.mediaStreamTrack);throw new sr("Required webRTC APIs not supported on this device")}))}createSimulcastSender(e,t,i,n){return Ht(this,void 0,void 0,(function*(){if(Sr())return this.createSimulcastTransceiverSender(e,t,i,n);if(yr())return c.debug("using add-track fallback"),this.createRTCRtpSender(e.mediaStreamTrack);throw new sr("Cannot stream on this device")}))}createTransceiverRTCRtpSender(e,t,i){return Ht(this,void 0,void 0,(function*(){if(!this.publisher)throw new sr("publisher is closed");const n={direction:"sendonly"};i&&(n.sendEncodings=i);const r=yield this.publisher.pc.addTransceiver(e.mediaStreamTrack,n);return e.kind===js.Kind.Video&&t.videoCodec&&(this.setPreferredCodec(r,e.kind,t.videoCodec),e.codec=t.videoCodec),r.sender}))}createSimulcastTransceiverSender(e,t,i,n){return Ht(this,void 0,void 0,(function*(){if(!this.publisher)throw new sr("publisher is closed");const r={direction:"sendonly"};n&&(r.sendEncodings=n);const s=yield this.publisher.pc.addTransceiver(t.mediaStreamTrack,r);if(i.videoCodec)return this.setPreferredCodec(s,e.kind,i.videoCodec),e.setSimulcastTrackSender(i.videoCodec,s.sender),s.sender}))}createRTCRtpSender(e){return Ht(this,void 0,void 0,(function*(){if(!this.publisher)throw new sr("publisher is closed");return this.publisher.pc.addTrack(e)}))}attemptReconnect(t){var i,n,r;return Ht(this,void 0,void 0,(function*(){if(!this._isClosed&&!this.attemptingReconnect){(null===(i=this.clientConfiguration)||void 0===i?void 0:i.resumeConnection)!==Ze.DISABLED&&"closed"!==(null!==(r=null===(n=this.primaryPC)||void 0===n?void 0:n.signalingState)&&void 0!==r?r:"closed")||(this.fullReconnectOnNext=!0);try{this.attemptingReconnect=!0,this.fullReconnectOnNext?yield this.restartConnection():yield this.resumeConnection(t),this.clearPendingReconnect(),this.fullReconnectOnNext=!1}catch(t){this.reconnectAttempts+=1;let i=!0;t instanceof sr?(c.debug("received unrecoverable error",{error:t}),i=!1):t instanceof Zs||(this.fullReconnectOnNext=!0),i?this.handleDisconnect("reconnect",Ye.RR_UNKOWN):(c.info("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(Date.now()-this.reconnectStart,"ms. giving up")),this.emit(e.EngineEvent.Disconnected),yield this.close())}finally{this.attemptingReconnect=!1}}}))}getNextRetryDelay(e){try{return this.reconnectPolicy.nextRetryDelayInMs(e)}catch(e){c.warn("encountered error in reconnect policy",{error:e})}return null}restartConnection(t){var i,n,r,s,o;return Ht(this,void 0,void 0,(function*(){try{if(!this.url||!this.token)throw new sr("could not reconnect, url or token not saved");let s;c.info("reconnecting, attempt: ".concat(this.reconnectAttempts)),this.emit(e.EngineEvent.Restarting),this.client.isConnected&&(yield this.client.sendLeave()),yield this.client.close(),this.primaryPC=void 0,null===(i=this.publisher)||void 0===i||i.close(),this.publisher=void 0,null===(n=this.subscriber)||void 0===n||n.close(),this.subscriber=void 0;try{if(!this.signalOpts)throw c.warn("attempted connection restart, without signal options present"),new Zs;s=yield this.join(null!=t?t:this.url,this.token,this.signalOpts)}catch(e){if(e instanceof tr&&0===e.reason)throw new sr("could not reconnect, token might be expired");throw new Zs}if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");this.client.setReconnected(),this.emit(e.EngineEvent.SignalRestarted,s),yield this.waitForPCReconnected(),null===(r=this.regionUrlProvider)||void 0===r||r.resetAttempts(),this.emit(e.EngineEvent.Restarted)}catch(e){const t=yield null===(s=this.regionUrlProvider)||void 0===s?void 0:s.getNextBestRegionUrl();if(t)return void(yield this.restartConnection(t));throw null===(o=this.regionUrlProvider)||void 0===o||o.resetAttempts(),e}}))}resumeConnection(t){var i;return Ht(this,void 0,void 0,(function*(){if(!this.url||!this.token)throw new sr("could not reconnect, url or token not saved");if(!this.publisher||!this.subscriber)throw new sr("publisher and subscriber connections unset");c.info("resuming signal connection, attempt ".concat(this.reconnectAttempts)),this.emit(e.EngineEvent.Resuming);try{const e=yield this.client.reconnect(this.url,this.token,this.participantSid,t);if(e){const t=this.makeRTCConfiguration(e);this.publisher.pc.setConfiguration(t),this.subscriber.pc.setConfiguration(t)}}catch(e){let t="";if(e instanceof Error&&(t=e.message),e instanceof tr&&0===e.reason)throw new sr("could not reconnect, token might be expired");throw new Zs(t)}if(this.emit(e.EngineEvent.SignalResumed),this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");this.subscriber.restartingIce=!0,this.hasPublished&&(yield this.publisher.createAndSendOffer({iceRestart:!0})),yield this.waitForPCReconnected(),this.client.setReconnected(),"open"===(null===(i=this.reliableDC)||void 0===i?void 0:i.readyState)&&null===this.reliableDC.id&&this.createDataChannels(),this.emit(e.EngineEvent.Resumed)}))}waitForPCInitialConnection(t,i){return Ht(this,void 0,void 0,(function*(){if(this.pcState!==Hs.Connected){if(this.pcState!==Hs.New)throw new sr("Expected peer connection to be new on initial connection");return new Promise(((n,r)=>{const s=()=>{c.warn("closing engine"),ar.clearTimeout(a),r(new tr("room connection has been cancelled",3))};(null==i?void 0:i.signal.aborted)&&s(),null==i||i.signal.addEventListener("abort",s);const o=()=>{ar.clearTimeout(a),null==i||i.signal.removeEventListener("abort",s),n()},a=ar.setTimeout((()=>{this.off(e.EngineEvent.Connected,o),r(new tr("could not establish pc connection"))}),null!=t?t:this.peerConnectionTimeout);this.once(e.EngineEvent.Connected,o)}))}}))}waitForPCReconnected(){var e;return Ht(this,void 0,void 0,(function*(){const t=Date.now();let i=t;for(this.pcState=Hs.Reconnecting,c.debug("waiting for peer connection to reconnect");i-t<this.peerConnectionTimeout&&void 0!==this.primaryPC;){if(i-t>2e3&&"connected"===(null===(e=this.primaryPC)||void 0===e?void 0:e.connectionState)&&(this.pcState=Hs.Connected),this.pcState===Hs.Connected)return;yield kr(100),i=Date.now()}throw new tr("could not establish PC connection")}))}sendDataPacket(e,t){return Ht(this,void 0,void 0,(function*(){const i=Dt.encode(e).finish();yield this.ensurePublisherConnected(t);const n=this.dataChannelForKind(t);n&&n.send(i),this.updateAndEmitDCBufferStatus(t)}))}ensureDataTransportConnected(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.subscriberPrimary;var i,n,r;return Ht(this,void 0,void 0,(function*(){const s=t?this.subscriber:this.publisher,o=t?"Subscriber":"Publisher";if(!s)throw new tr("".concat(o," connection not set"));t||(null===(i=this.publisher)||void 0===i?void 0:i.isICEConnected)||"checking"===(null===(n=this.publisher)||void 0===n?void 0:n.pc.iceConnectionState)||this.negotiate();const a=this.dataChannelForKind(e,t);if("open"===(null==a?void 0:a.readyState))return;const c=(new Date).getTime()+this.peerConnectionTimeout;for(;(new Date).getTime()<c;){if(s.isICEConnected&&"open"===(null===(r=this.dataChannelForKind(e,t))||void 0===r?void 0:r.readyState))return;yield kr(50)}throw new tr("could not establish ".concat(o," connection, state: ").concat(s.pc.iceConnectionState))}))}ensurePublisherConnected(e){return Ht(this,void 0,void 0,(function*(){yield this.ensureDataTransportConnected(e,!1)}))}verifyTransport(){if(!this.primaryPC)return!1;if("closed"===this.primaryPC.connectionState||"failed"===this.primaryPC.connectionState)return!1;if(this.hasPublished&&this.subscriberPrimary){if(!this.publisher)return!1;if("closed"===this.publisher.pc.connectionState||"failed"===this.publisher.pc.connectionState)return!1}return!(!this.client.ws||this.client.ws.readyState===WebSocket.CLOSED)}negotiate(){return new Promise(((t,i)=>{if(!this.publisher)return void i(new or("publisher is not defined"));this.hasPublished=!0;const n=()=>{c.warn("engine disconnected while negotiation was ongoing"),s(),t()};this.on(e.EngineEvent.Closing,n);const r=setTimeout((()=>{i("negotiation timed out"),this.handleDisconnect("negotiation",Ye.RR_SIGNAL_DISCONNECTED)}),this.peerConnectionTimeout),s=()=>{clearTimeout(r),this.off(e.EngineEvent.Closing,n)};this.publisher.once(ks,(()=>{var e;null===(e=this.publisher)||void 0===e||e.once(Ss,(()=>{s(),t()}))})),this.publisher.negotiate((e=>{s(),i(e),e instanceof or&&(this.fullReconnectOnNext=!0),this.handleDisconnect("negotiation",Ye.RR_UNKOWN)}))}))}dataChannelForKind(t,i){if(i){if(t===e.DataPacket_Kind.LOSSY)return this.lossyDCSub;if(t===e.DataPacket_Kind.RELIABLE)return this.reliableDCSub}else{if(t===e.DataPacket_Kind.LOSSY)return this.lossyDC;if(t===e.DataPacket_Kind.RELIABLE)return this.reliableDC}}failNext(){this.shouldFailNext=!0}clearReconnectTimeout(){this.reconnectTimeout&&ar.clearTimeout(this.reconnectTimeout)}clearPendingReconnect(){this.clearReconnectTimeout(),this.reconnectAttempts=0}registerOnLineListener(){Dr()&&window.addEventListener("online",this.handleBrowserOnLine)}deregisterOnLineListener(){Dr()&&window.removeEventListener("online",this.handleBrowserOnLine)}}class Zs extends Error{}const zs=2e3;function Ys(e,t){if(!t)return 0;let i,n;return"bytesReceived"in e?(i=e.bytesReceived,n=t.bytesReceived):"bytesSent"in e&&(i=e.bytesSent,n=t.bytesSent),void 0===i||void 0===n||void 0===e.timestamp||void 0===t.timestamp?0:8*(i-n)*1e3/(e.timestamp-t.timestamp)}class Xs extends js{get constraints(){return this._constraints}constructor(t,i,n){let r=arguments.length>3&&void 0!==arguments[3]&&arguments[3];super(t,i),this._isUpstreamPaused=!1,this.handleEnded=()=>{this.isInBackground&&(this.reacquireTrack=!0),this._mediaStreamTrack.removeEventListener("mute",this.pauseUpstream),this._mediaStreamTrack.removeEventListener("unmute",this.resumeUpstream),this.emit(e.TrackEvent.Ended,this)},this.pauseUpstream=()=>Ht(this,void 0,void 0,(function*(){const t=yield this.pauseUpstreamLock.lock();try{if(!0===this._isUpstreamPaused)return;if(!this.sender)return void c.warn("unable to pause upstream for an unpublished track");this._isUpstreamPaused=!0,this.emit(e.TrackEvent.UpstreamPaused,this);const t=ur();if("Safari"===(null==t?void 0:t.name)&&_r(t.version,"12.0")<0)throw new ir("pauseUpstream is not supported on Safari < 12.");yield this.sender.replaceTrack(null)}finally{t()}})),this.resumeUpstream=()=>Ht(this,void 0,void 0,(function*(){const t=yield this.pauseUpstreamLock.lock();try{if(!1===this._isUpstreamPaused)return;if(!this.sender)return void c.warn("unable to resume upstream for an unpublished track");this._isUpstreamPaused=!1,this.emit(e.TrackEvent.UpstreamResumed,this),yield this.sender.replaceTrack(this._mediaStreamTrack)}finally{t()}})),this.reacquireTrack=!1,this.providedByUser=r,this.muteLock=new Hr,this.pauseUpstreamLock=new Hr,this.processorLock=new Hr,this._constraints=t.getConstraints(),this.setMediaStreamTrack(t),n&&(this._constraints=n)}get id(){return this._mediaStreamTrack.id}get dimensions(){if(this.kind!==js.Kind.Video)return;const{width:e,height:t}=this._mediaStreamTrack.getSettings();return e&&t?{width:e,height:t}:void 0}get isUpstreamPaused(){return this._isUpstreamPaused}get isUserProvided(){return this.providedByUser}get mediaStreamTrack(){var e,t;return null!==(t=null===(e=this.processor)||void 0===e?void 0:e.processedTrack)&&void 0!==t?t:this._mediaStreamTrack}setMediaStreamTrack(e){return Ht(this,void 0,void 0,(function*(){e!==this._mediaStreamTrack&&(this._mediaStreamTrack&&(this.attachedElements.forEach((e=>{qs(this._mediaStreamTrack,e)})),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.removeEventListener("mute",this.pauseUpstream),this._mediaStreamTrack.removeEventListener("unmute",this.resumeUpstream),this.providedByUser||this._mediaStreamTrack.stop()),this.mediaStream=new MediaStream([e]),e&&(e.addEventListener("ended",this.handleEnded),e.addEventListener("mute",this.pauseUpstream),e.addEventListener("unmute",this.resumeUpstream),this._constraints=e.getConstraints()),this.sender&&(yield this.sender.replaceTrack(e)),this._mediaStreamTrack=e,e&&(this._mediaStreamTrack.enabled=!this.isMuted,yield this.resumeUpstream(),this.attachedElements.forEach((t=>{Vs(e,t)}))))}))}waitForDimensions(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1e3;return Ht(this,void 0,void 0,(function*(){if(this.kind===js.Kind.Audio)throw new Error("cannot get dimensions for audio tracks");const t=Date.now();for(;Date.now()-t<e;){const e=this.dimensions;if(e)return e;yield kr(50)}throw new nr("unable to get track dimensions after timeout")}))}getDeviceId(){return Ht(this,void 0,void 0,(function*(){if(this.source===js.Source.ScreenShare)return;const{deviceId:e,groupId:t}=this._mediaStreamTrack.getSettings(),i=this.kind===js.Kind.Audio?"audioinput":"videoinput";return ns.getInstance().normalizeDeviceId(i,e,t)}))}mute(){return Ht(this,void 0,void 0,(function*(){return this.setTrackMuted(!0),this}))}unmute(){return Ht(this,void 0,void 0,(function*(){return this.setTrackMuted(!1),this}))}replaceTrack(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return Ht(this,void 0,void 0,(function*(){if(!this.sender)throw new nr("unable to replace an unpublished track");return c.debug("replace MediaStreamTrack"),yield this.setMediaStreamTrack(e),this.providedByUser=t,this.processor&&(yield this.stopProcessor()),this}))}restart(t){return Ht(this,void 0,void 0,(function*(){t||(t=this._constraints),c.debug("restarting track with constraints",t);const i={audio:!1,video:!1};this.kind===js.Kind.Video?i.video=t:i.audio=t,this.attachedElements.forEach((e=>{qs(this.mediaStreamTrack,e)})),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.stop();const n=(yield navigator.mediaDevices.getUserMedia(i)).getTracks()[0];if(n.addEventListener("ended",this.handleEnded),c.debug("re-acquired MediaStreamTrack"),yield this.setMediaStreamTrack(n),this._constraints=t,this.processor){const e=this.processor;yield this.setProcessor(e)}else this.attachedElements.forEach((e=>{Vs(this._mediaStreamTrack,e)}));return this.emit(e.TrackEvent.Restarted,this),this}))}setTrackMuted(t){c.debug("setting ".concat(this.kind," track ").concat(t?"muted":"unmuted")),this.isMuted===t&&this._mediaStreamTrack.enabled!==t||(this.isMuted=t,this._mediaStreamTrack.enabled=!t,this.emit(t?e.TrackEvent.Muted:e.TrackEvent.Unmuted,this))}get needsReAcquisition(){return"live"!==this._mediaStreamTrack.readyState||this._mediaStreamTrack.muted||!this._mediaStreamTrack.enabled||this.reacquireTrack}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return Ht(this,void 0,void 0,(function*(){yield e.handleAppVisibilityChanged.call(this),Or()&&(c.debug("visibility changed, is in Background: ".concat(this.isInBackground)),this.isInBackground||!this.needsReAcquisition||this.isUserProvided||this.isMuted||(c.debug("track needs to be reaquired, restarting ".concat(this.source)),yield this.restart(),this.reacquireTrack=!1))}))}stop(){var e;super.stop(),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.removeEventListener("mute",this.pauseUpstream),this._mediaStreamTrack.removeEventListener("unmute",this.resumeUpstream),null===(e=this.processor)||void 0===e||e.destroy(),this.processor=void 0}setProcessor(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];var i,n;return Ht(this,void 0,void 0,(function*(){const r=yield this.processorLock.lock();try{if(c.debug("setting up processor"),this.processor&&(yield this.stopProcessor()),"unknown"===this.kind)throw TypeError("cannot set processor on track of unknown kind");this.processorElement=null!==(i=this.processorElement)&&void 0!==i?i:document.createElement(this.kind),this.processorElement.muted=!0,Vs(this._mediaStreamTrack,this.processorElement),this.processorElement.play().catch((e=>c.error("failed to play processor element",{error:e})));const r={kind:this.kind,track:this._mediaStreamTrack,element:this.processorElement};if(yield e.init(r),this.processor=e,this.processor.processedTrack){for(const e of this.attachedElements)e!==this.processorElement&&t&&(qs(this._mediaStreamTrack,e),Vs(this.processor.processedTrack,e));yield null===(n=this.sender)||void 0===n?void 0:n.replaceTrack(this.processor.processedTrack)}}finally{r()}}))}getProcessor(){return this.processor}stopProcessor(){var e,t;return Ht(this,void 0,void 0,(function*(){this.processor&&(c.debug("stopping processor"),null===(e=this.processor.processedTrack)||void 0===e||e.stop(),yield this.processor.destroy(),this.processor=void 0,null===(t=this.processorElement)||void 0===t||t.remove(),this.processorElement=void 0,yield this.restart())}))}}class eo extends Xs{constructor(e,t){let i=!(arguments.length>2&&void 0!==arguments[2])||arguments[2];super(e,js.Kind.Audio,t,i),this.stopOnMute=!1,this.monitorSender=()=>Ht(this,void 0,void 0,(function*(){if(!this.sender)return void(this._currentBitrate=0);let e;try{e=yield this.getSenderStats()}catch(e){return void c.error("could not get audio sender stats",{error:e})}e&&this.prevStats&&(this._currentBitrate=Ys(e,this.prevStats)),this.prevStats=e})),this.checkForSilence()}setDeviceId(e){return Ht(this,void 0,void 0,(function*(){return this._constraints.deviceId===e||(this._constraints.deviceId=e,this.isMuted||(yield this.restartTrack()),this.isMuted||Kr(e)===this.mediaStreamTrack.getSettings().deviceId)}))}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return Ht(this,void 0,void 0,(function*(){const t=yield this.muteLock.lock();try{return this.source===js.Source.Microphone&&this.stopOnMute&&!this.isUserProvided&&(c.debug("stopping mic track"),this._mediaStreamTrack.stop()),yield e.mute.call(this),this}finally{t()}}))}unmute(){const e=Object.create(null,{unmute:{get:()=>super.unmute}});return Ht(this,void 0,void 0,(function*(){const t=yield this.muteLock.lock();try{const t=this._constraints.deviceId&&this._mediaStreamTrack.getSettings().deviceId!==Kr(this._constraints.deviceId);return this.source!==js.Source.Microphone||!this.stopOnMute&&"ended"!==this._mediaStreamTrack.readyState&&!t||this.isUserProvided||(c.debug("reacquiring mic track"),yield this.restartTrack()),yield e.unmute.call(this),this}finally{t()}}))}restartTrack(e){return Ht(this,void 0,void 0,(function*(){let t;if(e){const i=vr({audio:e});"boolean"!=typeof i.audio&&(t=i.audio)}yield this.restart(t)}))}restart(e){const t=Object.create(null,{restart:{get:()=>super.restart}});return Ht(this,void 0,void 0,(function*(){const i=yield t.restart.call(this,e);return this.checkForSilence(),i}))}startMonitor(){Dr()&&(this.monitorInterval||(this.monitorInterval=setInterval((()=>{this.monitorSender()}),zs)))}getSenderStats(){var e;return Ht(this,void 0,void 0,(function*(){if(!(null===(e=this.sender)||void 0===e?void 0:e.getStats))return;let t;return(yield this.sender.getStats()).forEach((e=>{"outbound-rtp"===e.type&&(t={type:"audio",streamId:e.id,packetsSent:e.packetsSent,packetsLost:e.packetsLost,bytesSent:e.bytesSent,timestamp:e.timestamp,roundTripTime:e.roundTripTime,jitter:e.jitter})})),t}))}checkForSilence(){return Ht(this,void 0,void 0,(function*(){const t=yield function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:200;return Ht(this,void 0,void 0,(function*(){const i=gr();if(i){const n=i.createAnalyser();n.fftSize=2048;const r=n.frequencyBinCount,s=new Uint8Array(r);i.createMediaStreamSource(new MediaStream([e.mediaStreamTrack])).connect(n),yield kr(t),n.getByteTimeDomainData(s);const o=s.some((e=>128!==e&&0!==e));return i.close(),!o}return!1}))}(this);return t&&(this.isMuted||c.warn("silence detected on local audio track"),this.emit(e.TrackEvent.AudioSilenceDetected)),t}))}}function to(e,t){switch(e.kind){case"audio":return new eo(e,t,!1);case"video":return new vo(e,t,!1);default:throw new nr("unsupported track type: ".concat(e.kind))}}const io=Object.values(Os),no=Object.values(Ds),ro=Object.values(Is),so=[Os.h180,Os.h360],oo=[Ds.h180,Ds.h360],ao=e=>[{scaleResolutionDownBy:2,fps:3}].map((t=>{var i;return new Es(Math.floor(e.width/t.scaleResolutionDownBy),Math.floor(e.height/t.scaleResolutionDownBy),Math.max(15e4,Math.floor(e.encoding.maxBitrate/(Math.pow(t.scaleResolutionDownBy,2)*((null!==(i=e.encoding.maxFramerate)&&void 0!==i?i:30)/t.fps)))),t.fps,e.encoding.priority)})),co=["q","h","f"];function uo(e,t,i,n){var r,s;let o=null==n?void 0:n.videoEncoding;e&&(o=null==n?void 0:n.screenShareEncoding);const a=null==n?void 0:n.simulcast,d=null==n?void 0:n.scalabilityMode,u=null==n?void 0:n.videoCodec;if(!o&&!a&&!d||!t||!i)return[{}];o||(o=function(e,t,i,n){const r=function(e,t,i){if(e)return ro;const n=t>i?t/i:i/t;if(Math.abs(n-16/9)<Math.abs(n-4/3))return io;return no}(e,t,i);let{encoding:s}=r[0];const o=Math.max(t,i);for(let e=0;e<r.length;e+=1){const t=r[e];if(s=t.encoding,t.width>=o)break}if(n)switch(n){case"av1":s=Object.assign({},s),s.maxBitrate=.7*s.maxBitrate;break;case"vp9":s=Object.assign({},s),s.maxBitrate=.85*s.maxBitrate}return s}(e,t,i,u),c.debug("using video encoding",o));const l=new Es(t,i,o.maxBitrate,o.maxFramerate,o.priority);if(d&&Er(u)){c.debug("using svc with scalabilityMode ".concat(d));const e=new fo(d),t=[];if(e.spatial>3)throw new Error("unsupported scalabilityMode: ".concat(d));for(let i=0;i<e.spatial;i+=1)t.push({rid:co[2-i],maxBitrate:o.maxBitrate/Math.pow(3,i),maxFramerate:l.encoding.maxFramerate});return t[0].scalabilityMode=d,c.debug("encodings",t),t}if(!a)return[o];let h,p=[];if(p=e?null!==(r=mo(null==n?void 0:n.screenShareSimulcastLayers))&&void 0!==r?r:ho(e,l):null!==(s=mo(null==n?void 0:n.videoSimulcastLayers))&&void 0!==s?s:ho(e,l),p.length>0){const e=p[0];p.length>1&&([,h]=p);const n=Math.max(t,i);if(n>=960&&h)return po(t,i,[e,h,l]);if(n>=480)return po(t,i,[e,l])}return po(t,i,[l])}function lo(e,t,i){var n,r,s,o;if(!i.backupCodec||i.backupCodec.codec===i.videoCodec)return;t!==i.backupCodec.codec&&c.warn("requested a different codec than specified as backup",{serverRequested:t,backup:i.backupCodec.codec}),i.videoCodec=t,i.videoEncoding=i.backupCodec.encoding;const a=e.mediaStreamTrack.getSettings(),d=null!==(n=a.width)&&void 0!==n?n:null===(r=e.dimensions)||void 0===r?void 0:r.width,u=null!==(s=a.height)&&void 0!==s?s:null===(o=e.dimensions)||void 0===o?void 0:o.height;return uo(e.source===js.Source.ScreenShare,d,u,i)}function ho(e,t){if(e)return ao(t);const{width:i,height:n}=t,r=i>n?i/n:n/i;return Math.abs(r-16/9)<Math.abs(r-4/3)?so:oo}function po(e,t,i){const n=[];if(i.forEach(((i,r)=>{if(r>=co.length)return;const s=Math.min(e,t),o={rid:co[r],scaleResolutionDownBy:Math.max(1,s/Math.min(i.width,i.height)),maxBitrate:i.encoding.maxBitrate};i.encoding.maxFramerate&&(o.maxFramerate=i.encoding.maxFramerate);const a=Rr()||0===r;i.encoding.priority&&a&&(o.priority=i.encoding.priority,o.networkPriority=i.encoding.priority),n.push(o)})),Ir()&&"ios"===Mr()){let e;n.forEach((t=>{e?t.maxFramerate&&t.maxFramerate>e&&(e=t.maxFramerate):e=t.maxFramerate}));let t=!0;n.forEach((i=>{var n;i.maxFramerate!=e&&(t&&(t=!1,c.info("Simulcast on iOS React-Native requires all encodings to share the same framerate.")),c.info('Setting framerate of encoding "'.concat(null!==(n=i.rid)&&void 0!==n?n:"",'" to ').concat(e)),i.maxFramerate=e)}))}return n}function mo(e){if(e)return e.sort(((e,t)=>{const{encoding:i}=e,{encoding:n}=t;return i.maxBitrate>n.maxBitrate?1:i.maxBitrate<n.maxBitrate?-1:i.maxBitrate===n.maxBitrate&&i.maxFramerate&&n.maxFramerate?i.maxFramerate>n.maxFramerate?1:-1:0}))}class fo{constructor(e){const t=e.match(/^L(\d)T(\d)(h|_KEY|_KEY_SHIFT){0,1}$/);if(!t)throw new Error("invalid scalability mode");if(this.spatial=parseInt(t[1]),this.temporal=parseInt(t[2]),t.length>3)switch(t[3]){case"h":case"_KEY":case"_KEY_SHIFT":this.suffix=t[3]}}toString(){var e;return"L".concat(this.spatial,"T").concat(this.temporal).concat(null!==(e=this.suffix)&&void 0!==e?e:"")}}class vo extends Xs{constructor(e,t){let i=!(arguments.length>2&&void 0!==arguments[2])||arguments[2];super(e,js.Kind.Video,t,i),this.simulcastCodecs=new Map,this.monitorSender=()=>Ht(this,void 0,void 0,(function*(){if(!this.sender)return void(this._currentBitrate=0);let e;try{e=yield this.getSenderStats()}catch(e){return void c.error("could not get audio sender stats",{error:e})}const t=new Map(e.map((e=>[e.rid,e])));if(this.prevStats){let e=0;t.forEach(((t,i)=>{var n;const r=null===(n=this.prevStats)||void 0===n?void 0:n.get(i);e+=Ys(t,r)})),this._currentBitrate=e}this.prevStats=t})),this.senderLock=new Hr}get isSimulcast(){return!!(this.sender&&this.sender.getParameters().encodings.length>1)}startMonitor(e){var t;if(this.signalClient=e,!Dr())return;const i=null===(t=this.sender)||void 0===t?void 0:t.getParameters();i&&(this.encodings=i.encodings),this.monitorInterval||(this.monitorInterval=setInterval((()=>{this.monitorSender()}),zs))}stop(){this._mediaStreamTrack.getConstraints(),this.simulcastCodecs.forEach((e=>{e.mediaStreamTrack.stop()})),super.stop()}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return Ht(this,void 0,void 0,(function*(){const t=yield this.muteLock.lock();try{return this.source!==js.Source.Camera||this.isUserProvided||(c.debug("stopping camera track"),this._mediaStreamTrack.stop()),yield e.mute.call(this),this}finally{t()}}))}unmute(){const e=Object.create(null,{unmute:{get:()=>super.unmute}});return Ht(this,void 0,void 0,(function*(){const t=yield this.muteLock.lock();try{return this.source!==js.Source.Camera||this.isUserProvided||(c.debug("reacquiring camera track"),yield this.restartTrack()),yield e.unmute.call(this),this}finally{t()}}))}getSenderStats(){var e;return Ht(this,void 0,void 0,(function*(){if(!(null===(e=this.sender)||void 0===e?void 0:e.getStats))return[];const t=[],i=yield this.sender.getStats();return i.forEach((e=>{var n;if("outbound-rtp"===e.type){const r={type:"video",streamId:e.id,frameHeight:e.frameHeight,frameWidth:e.frameWidth,firCount:e.firCount,pliCount:e.pliCount,nackCount:e.nackCount,packetsSent:e.packetsSent,bytesSent:e.bytesSent,framesSent:e.framesSent,timestamp:e.timestamp,rid:null!==(n=e.rid)&&void 0!==n?n:e.id,retransmittedPacketsSent:e.retransmittedPacketsSent,qualityLimitationReason:e.qualityLimitationReason,qualityLimitationResolutionChanges:e.qualityLimitationResolutionChanges},s=i.get(e.remoteId);s&&(r.jitter=s.jitter,r.packetsLost=s.packetsLost,r.roundTripTime=s.roundTripTime),t.push(r)}})),t}))}setPublishingQuality(t){const i=[];for(let n=e.VideoQuality.LOW;n<=e.VideoQuality.HIGH;n+=1)i.push({quality:n,enabled:n<=t});c.debug("setting publishing quality. max quality ".concat(t)),this.setPublishingLayers(i)}setDeviceId(e){return Ht(this,void 0,void 0,(function*(){return this._constraints.deviceId===e&&this._mediaStreamTrack.getSettings().deviceId===Kr(e)||(this._constraints.deviceId=e,this.isMuted||(yield this.restartTrack()),this.isMuted||Kr(e)===this._mediaStreamTrack.getSettings().deviceId)}))}restartTrack(e){return Ht(this,void 0,void 0,(function*(){let t;if(e){const i=vr({video:e});"boolean"!=typeof i.video&&(t=i.video)}yield this.restart(t)}))}addSimulcastTrack(e,t){if(this.simulcastCodecs.has(e))throw new Error("".concat(e," already added"));const i={codec:e,mediaStreamTrack:this.mediaStreamTrack.clone(),sender:void 0,encodings:t};return this.simulcastCodecs.set(e,i),i}setSimulcastTrackSender(e,t){const i=this.simulcastCodecs.get(e);i&&(i.sender=t,setTimeout((()=>{this.subscribedCodecs&&this.setPublishingCodecs(this.subscribedCodecs)}),5e3))}setPublishingCodecs(e){var t,i,n,r,s,o,a;return Ht(this,void 0,void 0,(function*(){if(c.debug("setting publishing codecs",{codecs:e,currentCodec:this.codec}),!this.codec&&e.length>0)return yield this.setPublishingLayers(e[0].qualities),[];this.subscribedCodecs=e;const d=[];try{for(t=!0,i=Zt(e);n=yield i.next(),!(r=n.done);t=!0){a=n.value,t=!1;const e=a;if(this.codec&&this.codec!==e.codec){const t=this.simulcastCodecs.get(e.codec);if(c.debug("try setPublishingCodec for ".concat(e.codec),t),t&&t.sender)t.encodings&&(c.debug("try setPublishingLayersForSender ".concat(e.codec)),yield go(t.sender,t.encodings,e.qualities,this.senderLock));else for(const t of e.qualities)if(t.enabled){d.push(e.codec);break}}else yield this.setPublishingLayers(e.qualities)}}catch(e){s={error:e}}finally{try{t||r||!(o=i.return)||(yield o.call(i))}finally{if(s)throw s.error}}return d}))}setPublishingLayers(e){return Ht(this,void 0,void 0,(function*(){c.debug("setting publishing layers",e),this.sender&&this.encodings&&(yield go(this.sender,this.encodings,e,this.senderLock))}))}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return Ht(this,void 0,void 0,(function*(){yield e.handleAppVisibilityChanged.call(this),Or()&&this.isInBackground&&this.source===js.Source.Camera&&(this._mediaStreamTrack.enabled=!1)}))}}function go(e,t,i,n){return Ht(this,void 0,void 0,(function*(){const r=yield n.lock();c.debug("setPublishingLayersForSender",{sender:e,qualities:i,senderEncodings:t});try{const n=e.getParameters(),{encodings:r}=n;if(!r)return;if(r.length!==t.length)return void c.warn("cannot set publishing layers, encodings mismatch");let s=!1;!1&&r[0].scalabilityMode||r.forEach(((e,n)=>{var r;let o=null!==(r=e.rid)&&void 0!==r?r:"";""===o&&(o="q");const a=bo(o),d=i.find((e=>e.quality===a));d&&e.active!==d.enabled&&(s=!0,e.active=d.enabled,c.debug("setting layer ".concat(d.quality," to ").concat(e.active?"enabled":"disabled")),Rr()&&(d.enabled?(e.scaleResolutionDownBy=t[n].scaleResolutionDownBy,e.maxBitrate=t[n].maxBitrate,e.maxFrameRate=t[n].maxFrameRate):(e.scaleResolutionDownBy=4,e.maxBitrate=10,e.maxFrameRate=2)))})),s&&(n.encodings=r,c.debug("setting encodings",n.encodings),yield e.setParameters(n))}finally{r()}}))}function bo(t){switch(t){case"f":return e.VideoQuality.HIGH;case"h":return e.VideoQuality.MEDIUM;case"q":return e.VideoQuality.LOW;default:return e.VideoQuality.UNRECOGNIZED}}function ko(t,i,n,r){if(!n)return[{quality:e.VideoQuality.HIGH,width:t,height:i,bitrate:0,ssrc:0}];if(r){const r=new fo(n[0].scalabilityMode),s=[];for(let o=0;o<r.spatial;o+=1)s.push({quality:e.VideoQuality.HIGH-o,width:t/Math.pow(2,o),height:i/Math.pow(2,o),bitrate:n[0].maxBitrate?n[0].maxBitrate/Math.pow(3,o):0,ssrc:0});return s}return n.map((r=>{var s,o,a;const c=null!==(s=r.scaleResolutionDownBy)&&void 0!==s?s:1;let d=bo(null!==(o=r.rid)&&void 0!==o?o:"");return d===e.VideoQuality.UNRECOGNIZED&&1===n.length&&(d=e.VideoQuality.HIGH),{quality:d,width:t/c,height:i/c,bitrate:null!==(a=r.maxBitrate)&&void 0!==a?a:0,ssrc:0}}))}class So extends js{constructor(e,t,i,n){super(e,i),this.sid=t,this.receiver=n}setMuted(t){this.isMuted!==t&&(this.isMuted=t,this._mediaStreamTrack.enabled=!t,this.emit(t?e.TrackEvent.Muted:e.TrackEvent.Unmuted,this))}setMediaStream(t){this.mediaStream=t,t.onremovetrack=()=>{this.receiver=void 0,this._currentBitrate=0,this.emit(e.TrackEvent.Ended,this)}}start(){this.startMonitor(),super.enable()}stop(){this.stopMonitor(),super.disable()}startMonitor(){this.monitorInterval||(this.monitorInterval=setInterval((()=>this.monitorReceiver()),zs))}}class yo extends So{constructor(e,t,i,n,r){super(e,t,js.Kind.Audio,i),this.monitorReceiver=()=>Ht(this,void 0,void 0,(function*(){if(!this.receiver)return void(this._currentBitrate=0);const e=yield this.getReceiverStats();e&&this.prevStats&&this.receiver&&(this._currentBitrate=Ys(e,this.prevStats)),this.prevStats=e})),this.audioContext=n,this.webAudioPluginNodes=[],r&&(this.sinkId=r.deviceId)}setVolume(e){var t;for(const i of this.attachedElements)this.audioContext?null===(t=this.gainNode)||void 0===t||t.gain.setTargetAtTime(e,0,.1):i.volume=e;this.elementVolume=e}getVolume(){if(this.elementVolume)return this.elementVolume;let e=0;return this.attachedElements.forEach((t=>{t.volume>e&&(e=t.volume)})),e}setSinkId(e){return Ht(this,void 0,void 0,(function*(){this.sinkId=e,yield Promise.all(this.attachedElements.map((t=>{if(Pr(t))return t.setSinkId(e)})))}))}attach(e){const t=0===this.attachedElements.length;return e?super.attach(e):e=super.attach(),this.elementVolume&&(e.volume=this.elementVolume),this.sinkId&&Pr(e)&&e.setSinkId(this.sinkId),this.audioContext&&t&&(c.debug("using audio context mapping"),this.connectWebAudio(this.audioContext,e),e.volume=0,e.muted=!0),e}detach(e){let t;return e?(t=super.detach(e),this.audioContext&&(this.attachedElements.length>0?this.connectWebAudio(this.audioContext,this.attachedElements[0]):this.disconnectWebAudio())):(t=super.detach(),this.disconnectWebAudio()),t}setAudioContext(e){this.audioContext=e,e&&this.attachedElements.length>0?this.connectWebAudio(e,this.attachedElements[0]):e||this.disconnectWebAudio()}setWebAudioPlugins(e){this.webAudioPluginNodes=e,this.attachedElements.length>0&&this.audioContext&&this.connectWebAudio(this.audioContext,this.attachedElements[0])}connectWebAudio(t,i){this.disconnectWebAudio(),this.sourceNode=t.createMediaStreamSource(i.srcObject);let n=this.sourceNode;this.webAudioPluginNodes.forEach((e=>{n.connect(e),n=e})),this.gainNode=t.createGain(),n.connect(this.gainNode),this.gainNode.connect(t.destination),this.elementVolume&&this.gainNode.gain.setTargetAtTime(this.elementVolume,0,.1),"running"!==t.state&&t.resume().then((()=>{"running"!==t.state&&this.emit(e.TrackEvent.AudioPlaybackFailed,new Error("Audio Context couldn't be started automatically"))})).catch((t=>{this.emit(e.TrackEvent.AudioPlaybackFailed,t)}))}disconnectWebAudio(){var e,t;null===(e=this.gainNode)||void 0===e||e.disconnect(),null===(t=this.sourceNode)||void 0===t||t.disconnect(),this.gainNode=void 0,this.sourceNode=void 0}getReceiverStats(){return Ht(this,void 0,void 0,(function*(){if(!this.receiver||!this.receiver.getStats)return;let e;return(yield this.receiver.getStats()).forEach((t=>{"inbound-rtp"===t.type&&(e={type:"audio",timestamp:t.timestamp,jitter:t.jitter,bytesReceived:t.bytesReceived,concealedSamples:t.concealedSamples,concealmentEvents:t.concealmentEvents,silentConcealedSamples:t.silentConcealedSamples,silentConcealmentEvents:t.silentConcealmentEvents,totalAudioEnergy:t.totalAudioEnergy,totalSamplesDuration:t.totalSamplesDuration})})),e}))}}class Co extends So{constructor(e,t,i,n){super(e,t,js.Kind.Video,i),this.elementInfos=[],this.monitorReceiver=()=>Ht(this,void 0,void 0,(function*(){if(!this.receiver)return void(this._currentBitrate=0);const e=yield this.getReceiverStats();e&&this.prevStats&&this.receiver&&(this._currentBitrate=Ys(e,this.prevStats)),this.prevStats=e})),this.debouncedHandleResize=bs((()=>{this.updateDimensions()}),100),this.adaptiveStreamSettings=n}get isAdaptiveStream(){return void 0!==this.adaptiveStreamSettings}get mediaStreamTrack(){return this._mediaStreamTrack}setMuted(e){super.setMuted(e),this.attachedElements.forEach((t=>{e?qs(this._mediaStreamTrack,t):Vs(this._mediaStreamTrack,t)}))}attach(e){if(e?super.attach(e):e=super.attach(),this.adaptiveStreamSettings&&void 0===this.elementInfos.find((t=>t.element===e))){const t=new To(e);this.observeElementInfo(t)}return e}observeElementInfo(e){this.adaptiveStreamSettings&&void 0===this.elementInfos.find((t=>t===e))?(e.handleResize=()=>{this.debouncedHandleResize()},e.handleVisibilityChanged=()=>{this.updateVisibility()},this.elementInfos.push(e),e.observe(),this.debouncedHandleResize(),this.updateVisibility()):c.warn("visibility resize observer not triggered")}stopObservingElementInfo(e){if(!this.isAdaptiveStream)return void c.warn("stopObservingElementInfo ignored");const t=this.elementInfos.filter((t=>t===e));for(const e of t)e.stopObserving();this.elementInfos=this.elementInfos.filter((t=>t!==e)),this.updateVisibility()}detach(e){let t=[];if(e)return this.stopObservingElement(e),super.detach(e);t=super.detach();for(const e of t)this.stopObservingElement(e);return t}getDecoderImplementation(){var e;return null===(e=this.prevStats)||void 0===e?void 0:e.decoderImplementation}getReceiverStats(){return Ht(this,void 0,void 0,(function*(){if(!this.receiver||!this.receiver.getStats)return;let e;return(yield this.receiver.getStats()).forEach((t=>{"inbound-rtp"===t.type&&(e={type:"video",framesDecoded:t.framesDecoded,framesDropped:t.framesDropped,framesReceived:t.framesReceived,packetsReceived:t.packetsReceived,packetsLost:t.packetsLost,frameWidth:t.frameWidth,frameHeight:t.frameHeight,pliCount:t.pliCount,firCount:t.firCount,nackCount:t.nackCount,jitter:t.jitter,timestamp:t.timestamp,bytesReceived:t.bytesReceived,decoderImplementation:t.decoderImplementation})})),e}))}stopObservingElement(e){const t=this.elementInfos.filter((t=>t.element===e));for(const e of t)e.stopObserving();this.elementInfos=this.elementInfos.filter((t=>t.element!==e))}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return Ht(this,void 0,void 0,(function*(){yield e.handleAppVisibilityChanged.call(this),this.isAdaptiveStream&&this.updateVisibility()}))}updateVisibility(){var t,i;const n=this.elementInfos.reduce(((e,t)=>Math.max(e,t.visibilityChangedAt||0)),0),r=!(null!==(i=null===(t=this.adaptiveStreamSettings)||void 0===t?void 0:t.pauseVideoInBackground)&&void 0!==i&&!i)&&this.isInBackground,s=this.elementInfos.some((e=>e.pictureInPicture)),o=this.elementInfos.some((e=>e.visible))&&!r||s;this.lastVisible!==o&&(!o&&Date.now()-n<100?ar.setTimeout((()=>{this.updateVisibility()}),100):(this.lastVisible=o,this.emit(e.TrackEvent.VisibilityChanged,o,this)))}updateDimensions(){var t,i;let n=0,r=0;const s=this.getPixelDensity();for(const e of this.elementInfos){const t=e.width()*s,i=e.height()*s;t+i>n+r&&(n=t,r=i)}(null===(t=this.lastDimensions)||void 0===t?void 0:t.width)===n&&(null===(i=this.lastDimensions)||void 0===i?void 0:i.height)===r||(this.lastDimensions={width:n,height:r},this.emit(e.TrackEvent.VideoDimensionsChanged,this.lastDimensions,this))}getPixelDensity(){var e;const t=null===(e=this.adaptiveStreamSettings)||void 0===e?void 0:e.pixelDensity;if("screen"===t)return Lr();if(!t){return Lr()>2?2:1}return t}}class To{get visible(){return this.isPiP||this.isIntersecting}get pictureInPicture(){return this.isPiP}constructor(e,t){this.onVisibilityChanged=e=>{var t;const{target:i,isIntersecting:n}=e;i===this.element&&(this.isIntersecting=n,this.visibilityChangedAt=Date.now(),null===(t=this.handleVisibilityChanged)||void 0===t||t.call(this))},this.onEnterPiP=()=>{var e;this.isPiP=!0,null===(e=this.handleVisibilityChanged)||void 0===e||e.call(this)},this.onLeavePiP=()=>{var e;this.isPiP=!1,null===(e=this.handleVisibilityChanged)||void 0===e||e.call(this)},this.element=e,this.isIntersecting=null!=t?t:Eo(e),this.isPiP=Dr()&&document.pictureInPictureElement===e,this.visibilityChangedAt=0}width(){return this.element.clientWidth}height(){return this.element.clientHeight}observe(){this.isIntersecting=Eo(this.element),this.isPiP=document.pictureInPictureElement===this.element,this.element.handleResize=()=>{var e;null===(e=this.handleResize)||void 0===e||e.call(this)},this.element.handleVisibilityChanged=this.onVisibilityChanged,jr().observe(this.element),Fr().observe(this.element),this.element.addEventListener("enterpictureinpicture",this.onEnterPiP),this.element.addEventListener("leavepictureinpicture",this.onLeavePiP)}stopObserving(){var e,t;null===(e=jr())||void 0===e||e.unobserve(this.element),null===(t=Fr())||void 0===t||t.unobserve(this.element),this.element.removeEventListener("enterpictureinpicture",this.onEnterPiP),this.element.removeEventListener("leavepictureinpicture",this.onLeavePiP)}}function Eo(e){let t=e.offsetTop,i=e.offsetLeft;const n=e.offsetWidth,r=e.offsetHeight,{hidden:s}=e,{opacity:o,display:a}=getComputedStyle(e);for(;e.offsetParent;)t+=(e=e.offsetParent).offsetTop,i+=e.offsetLeft;return t<window.pageYOffset+window.innerHeight&&i<window.pageXOffset+window.innerWidth&&t+r>window.pageYOffset&&i+n>window.pageXOffset&&!s&&(""===o||parseFloat(o)>0)&&"none"!==a}class Po extends Yt{constructor(t,i,n){super(),this.metadataMuted=!1,this.handleMuted=()=>{this.emit(e.TrackEvent.Muted)},this.handleUnmuted=()=>{this.emit(e.TrackEvent.Unmuted)},this.kind=t,this.trackSid=i,this.trackName=n,this.source=js.Source.Unknown}setTrack(t){this.track&&(this.track.off(e.TrackEvent.Muted,this.handleMuted),this.track.off(e.TrackEvent.Unmuted,this.handleUnmuted)),this.track=t,t&&(t.on(e.TrackEvent.Muted,this.handleMuted),t.on(e.TrackEvent.Unmuted,this.handleUnmuted))}get isMuted(){return this.metadataMuted}get isEnabled(){return!0}get isSubscribed(){return void 0!==this.track}get audioTrack(){if(this.track instanceof eo||this.track instanceof yo)return this.track}get videoTrack(){if(this.track instanceof vo||this.track instanceof Co)return this.track}updateInfo(e){this.trackSid=e.sid,this.trackName=e.name,this.source=js.sourceFromProto(e.source),this.mimeType=e.mimeType,this.kind===js.Kind.Video&&e.width>0&&(this.dimensions={width:e.width,height:e.height},this.simulcasted=e.simulcast),this.trackInfo=e,c.trace("update publication info",{info:e})}}!function(e){var t,i;(t=e.SubscriptionStatus||(e.SubscriptionStatus={})).Desired="desired",t.Subscribed="subscribed",t.Unsubscribed="unsubscribed",(i=e.PermissionStatus||(e.PermissionStatus={})).Allowed="allowed",i.NotAllowed="not_allowed"}(Po||(Po={}));class wo extends Po{get isUpstreamPaused(){var e;return null===(e=this.track)||void 0===e?void 0:e.isUpstreamPaused}constructor(t,i,n){super(t,i.sid,i.name),this.track=void 0,this.handleTrackEnded=()=>{this.emit(e.TrackEvent.Ended)},this.updateInfo(i),this.setTrack(n)}setTrack(t){this.track&&this.track.off(e.TrackEvent.Ended,this.handleTrackEnded),super.setTrack(t),t&&t.on(e.TrackEvent.Ended,this.handleTrackEnded)}get isMuted(){return this.track?this.track.isMuted:super.isMuted}get audioTrack(){return super.audioTrack}get videoTrack(){return super.videoTrack}mute(){var e;return Ht(this,void 0,void 0,(function*(){return null===(e=this.track)||void 0===e?void 0:e.mute()}))}unmute(){var e;return Ht(this,void 0,void 0,(function*(){return null===(e=this.track)||void 0===e?void 0:e.unmute()}))}pauseUpstream(){var e;return Ht(this,void 0,void 0,(function*(){yield null===(e=this.track)||void 0===e?void 0:e.pauseUpstream()}))}resumeUpstream(){var e;return Ht(this,void 0,void 0,(function*(){yield null===(e=this.track)||void 0===e?void 0:e.resumeUpstream()}))}}e.ConnectionQuality=void 0,function(e){e.Excellent="excellent",e.Good="good",e.Poor="poor",e.Unknown="unknown"}(e.ConnectionQuality||(e.ConnectionQuality={}));class Ro extends Yt{constructor(t,i,n,r){super(),this.audioLevel=0,this.isSpeaking=!1,this._connectionQuality=e.ConnectionQuality.Unknown,this.sid=t,this.identity=i,this.name=n,this.metadata=r,this.audioTracks=new Map,this.videoTracks=new Map,this.tracks=new Map}getTracks(){return Array.from(this.tracks.values())}getTrack(e){for(const[,t]of this.tracks)if(t.source===e)return t}getTrackByName(e){for(const[,t]of this.tracks)if(t.trackName===e)return t}get connectionQuality(){return this._connectionQuality}get isCameraEnabled(){var e;const t=this.getTrack(js.Source.Camera);return!(null===(e=null==t?void 0:t.isMuted)||void 0===e||e)}get isMicrophoneEnabled(){var e;const t=this.getTrack(js.Source.Microphone);return!(null===(e=null==t?void 0:t.isMuted)||void 0===e||e)}get isScreenShareEnabled(){return!!this.getTrack(js.Source.ScreenShare)}get isLocal(){return!1}get joinedAt(){return this.participantInfo?new Date(1e3*this.participantInfo.joinedAt):new Date}updateInfo(e){return!(this.participantInfo&&this.participantInfo.sid===e.sid&&this.participantInfo.version>e.version)&&(this.identity=e.identity,this.sid=e.sid,this.setName(e.name),this.setMetadata(e.metadata),e.permission&&this.setPermissions(e.permission),this.participantInfo=e,c.trace("update participant info",{info:e}),!0)}setMetadata(t){const i=this.metadata!==t,n=this.metadata;this.metadata=t,i&&this.emit(e.ParticipantEvent.ParticipantMetadataChanged,n)}setName(t){const i=this.name!==t;this.name=t,i&&this.emit(e.ParticipantEvent.ParticipantNameChanged,t)}setPermissions(t){var i,n,r,s,o;const a=this.permissions,c=t.canPublish!==(null===(i=this.permissions)||void 0===i?void 0:i.canPublish)||t.canSubscribe!==(null===(n=this.permissions)||void 0===n?void 0:n.canSubscribe)||t.canPublishData!==(null===(r=this.permissions)||void 0===r?void 0:r.canPublishData)||t.hidden!==(null===(s=this.permissions)||void 0===s?void 0:s.hidden)||t.recorder!==(null===(o=this.permissions)||void 0===o?void 0:o.recorder)||t.canPublishSources.length!==this.permissions.canPublishSources.length||t.canPublishSources.some(((e,t)=>{var i;return e!==(null===(i=this.permissions)||void 0===i?void 0:i.canPublishSources[t])}));return this.permissions=t,c&&this.emit(e.ParticipantEvent.ParticipantPermissionsChanged,a),c}setIsSpeaking(t){t!==this.isSpeaking&&(this.isSpeaking=t,t&&(this.lastSpokeAt=new Date),this.emit(e.ParticipantEvent.IsSpeakingChanged,t))}setConnectionQuality(t){const i=this._connectionQuality;this._connectionQuality=function(t){switch(t){case Ke.EXCELLENT:return e.ConnectionQuality.Excellent;case Ke.GOOD:return e.ConnectionQuality.Good;case Ke.POOR:return e.ConnectionQuality.Poor;default:return e.ConnectionQuality.Unknown}}(t),i!==this._connectionQuality&&this.emit(e.ParticipantEvent.ConnectionQualityChanged,this._connectionQuality)}addTrackPublication(t){t.on(e.TrackEvent.Muted,(()=>{this.emit(e.ParticipantEvent.TrackMuted,t)})),t.on(e.TrackEvent.Unmuted,(()=>{this.emit(e.ParticipantEvent.TrackUnmuted,t)}));const i=t;switch(i.track&&(i.track.sid=t.trackSid),this.tracks.set(t.trackSid,t),t.kind){case js.Kind.Audio:this.audioTracks.set(t.trackSid,t);break;case js.Kind.Video:this.videoTracks.set(t.trackSid,t)}}}class No extends Po{constructor(t,i,n){super(t,i.sid,i.name),this.track=void 0,this.allowed=!0,this.disabled=!1,this.currentVideoQuality=e.VideoQuality.HIGH,this.handleEnded=t=>{this.setTrack(void 0),this.emit(e.TrackEvent.Ended,t)},this.handleVisibilityChange=e=>{c.debug("adaptivestream video visibility ".concat(this.trackSid,", visible=").concat(e),{trackSid:this.trackSid}),this.disabled=!e,this.emitTrackUpdate()},this.handleVideoDimensionsChange=e=>{c.debug("adaptivestream video dimensions ".concat(e.width,"x").concat(e.height),{trackSid:this.trackSid}),this.videoDimensions=e,this.emitTrackUpdate()},this.subscribed=n,this.updateInfo(i)}setSubscribed(t){const i=this.subscriptionStatus,n=this.permissionStatus;this.subscribed=t,t&&(this.allowed=!0);const r={trackSids:[this.trackSid],subscribe:this.subscribed,participantTracks:[{participantSid:"",trackSids:[this.trackSid]}]};this.emit(e.TrackEvent.UpdateSubscription,r),this.emitSubscriptionUpdateIfChanged(i),this.emitPermissionUpdateIfChanged(n)}get subscriptionStatus(){return!1===this.subscribed?Po.SubscriptionStatus.Unsubscribed:super.isSubscribed?Po.SubscriptionStatus.Subscribed:Po.SubscriptionStatus.Desired}get permissionStatus(){return this.allowed?Po.PermissionStatus.Allowed:Po.PermissionStatus.NotAllowed}get isSubscribed(){return!1!==this.subscribed&&super.isSubscribed}get isDesired(){return!1!==this.subscribed}get isEnabled(){return!this.disabled}setEnabled(e){this.isManualOperationAllowed()&&this.disabled!==!e&&(this.disabled=!e,this.emitTrackUpdate())}setVideoQuality(e){this.isManualOperationAllowed()&&this.currentVideoQuality!==e&&(this.currentVideoQuality=e,this.videoDimensions=void 0,this.emitTrackUpdate())}setVideoDimensions(e){var t,i;this.isManualOperationAllowed()&&((null===(t=this.videoDimensions)||void 0===t?void 0:t.width)===e.width&&(null===(i=this.videoDimensions)||void 0===i?void 0:i.height)===e.height||(this.track instanceof Co&&(this.videoDimensions=e),this.currentVideoQuality=void 0,this.emitTrackUpdate()))}setVideoFPS(e){this.isManualOperationAllowed()&&this.track instanceof Co&&this.fps!==e&&(this.fps=e,this.emitTrackUpdate())}get videoQuality(){return this.currentVideoQuality}setTrack(t){const i=this.subscriptionStatus,n=this.permissionStatus,r=this.track;r!==t&&(r&&(r.off(e.TrackEvent.VideoDimensionsChanged,this.handleVideoDimensionsChange),r.off(e.TrackEvent.VisibilityChanged,this.handleVisibilityChange),r.off(e.TrackEvent.Ended,this.handleEnded),r.detach(),r.stopMonitor(),this.emit(e.TrackEvent.Unsubscribed,r)),super.setTrack(t),t&&(t.sid=this.trackSid,t.on(e.TrackEvent.VideoDimensionsChanged,this.handleVideoDimensionsChange),t.on(e.TrackEvent.VisibilityChanged,this.handleVisibilityChange),t.on(e.TrackEvent.Ended,this.handleEnded),this.emit(e.TrackEvent.Subscribed,t)),this.emitPermissionUpdateIfChanged(n),this.emitSubscriptionUpdateIfChanged(i))}setAllowed(e){const t=this.subscriptionStatus,i=this.permissionStatus;this.allowed=e,this.emitPermissionUpdateIfChanged(i),this.emitSubscriptionUpdateIfChanged(t)}setSubscriptionError(t){this.emit(e.TrackEvent.SubscriptionFailed,t)}updateInfo(t){super.updateInfo(t);const i=this.metadataMuted;this.metadataMuted=t.muted,this.track?this.track.setMuted(t.muted):i!==t.muted&&this.emit(t.muted?e.TrackEvent.Muted:e.TrackEvent.Unmuted)}emitSubscriptionUpdateIfChanged(t){const i=this.subscriptionStatus;t!==i&&this.emit(e.TrackEvent.SubscriptionStatusChanged,i,t)}emitPermissionUpdateIfChanged(t){this.permissionStatus!==t&&this.emit(e.TrackEvent.SubscriptionPermissionChanged,this.permissionStatus,t)}isManualOperationAllowed(){return this.kind===js.Kind.Video&&this.isAdaptiveStream?(c.warn("adaptive stream is enabled, cannot change video track settings",{trackSid:this.trackSid}),!1):!!this.isDesired||(c.warn("cannot update track settings when not subscribed",{trackSid:this.trackSid}),!1)}get isAdaptiveStream(){return this.track instanceof Co&&this.track.isAdaptiveStream}emitTrackUpdate(){const t=wn.fromPartial({trackSids:[this.trackSid],disabled:this.disabled,fps:this.fps});this.videoDimensions?(t.width=this.videoDimensions.width,t.height=this.videoDimensions.height):void 0!==this.currentVideoQuality?t.quality=this.currentVideoQuality:t.quality=e.VideoQuality.HIGH,this.emit(e.TrackEvent.UpdateSettings,t)}}class Oo extends Ro{static fromParticipantInfo(e,t){return new Oo(e,t.sid,t.identity,t.name,t.metadata)}constructor(e,t,i,n,r){super(t,i||"",n,r),this.signalClient=e,this.tracks=new Map,this.audioTracks=new Map,this.videoTracks=new Map}addTrackPublication(t){super.addTrackPublication(t),t.on(e.TrackEvent.UpdateSettings,(e=>{c.debug("send update settings",e),this.signalClient.sendUpdateTrackSettings(e)})),t.on(e.TrackEvent.UpdateSubscription,(e=>{e.participantTracks.forEach((e=>{e.participantSid=this.sid})),this.signalClient.sendUpdateSubscription(e)})),t.on(e.TrackEvent.SubscriptionPermissionChanged,(i=>{this.emit(e.ParticipantEvent.TrackSubscriptionPermissionChanged,t,i)})),t.on(e.TrackEvent.SubscriptionStatusChanged,(i=>{this.emit(e.ParticipantEvent.TrackSubscriptionStatusChanged,t,i)})),t.on(e.TrackEvent.Subscribed,(i=>{this.emit(e.ParticipantEvent.TrackSubscribed,i,t)})),t.on(e.TrackEvent.Unsubscribed,(i=>{this.emit(e.ParticipantEvent.TrackUnsubscribed,i,t)})),t.on(e.TrackEvent.SubscriptionFailed,(i=>{this.emit(e.ParticipantEvent.TrackSubscriptionFailed,t.trackSid,i)}))}getTrack(e){const t=super.getTrack(e);if(t)return t}getTrackByName(e){const t=super.getTrackByName(e);if(t)return t}setVolume(e){this.volume=e;const t=this.getTrack(js.Source.Microphone);t&&t.track&&t.track.setVolume(e)}getVolume(){const e=this.getTrack(js.Source.Microphone);return e&&e.track?e.track.getVolume():this.volume}addSubscribedMediaTrack(t,i,n,r,s,o){let a=this.getTrackPublication(i);if(a||i.startsWith("TR")||this.tracks.forEach((e=>{a||t.kind!==e.kind.toString()||(a=e)})),!a)return 0===o?(c.error("could not find published track",{participant:this.sid,trackSid:i}),void this.emit(e.ParticipantEvent.TrackSubscriptionFailed,i)):(void 0===o&&(o=20),void setTimeout((()=>{this.addSubscribedMediaTrack(t,i,n,r,s,o-1)}),150));if("ended"===t.readyState)return c.error("unable to subscribe because MediaStreamTrack is ended. Do not call MediaStreamTrack.stop()",{participant:this.sid,trackSid:i}),void this.emit(e.ParticipantEvent.TrackSubscriptionFailed,i);let d;return d="video"===t.kind?new Co(t,i,r,s):new yo(t,i,r,this.audioContext,this.audioOutput),d.source=a.source,d.isMuted=a.isMuted,d.setMediaStream(n),d.start(),a.setTrack(d),void 0!==this.volume&&d instanceof yo&&d.source===js.Source.Microphone&&d.setVolume(this.volume),a}get hasMetadata(){return!!this.participantInfo}getTrackPublication(e){return this.tracks.get(e)}updateInfo(t){if(!super.updateInfo(t))return!1;const i=new Map,n=new Map;return t.tracks.forEach((e=>{var r;let s=this.getTrackPublication(e.sid);if(s)s.updateInfo(e);else{const i=js.kindFromProto(e.type);if(!i)return;s=new No(i,e,null===(r=this.signalClient.connectOptions)||void 0===r?void 0:r.autoSubscribe),s.updateInfo(e),n.set(e.sid,s);const o=Array.from(this.tracks.values()).find((e=>e.source===(null==s?void 0:s.source)));o&&s.source!==js.Source.Unknown&&c.debug("received a second track publication for ".concat(this.identity," with the same source: ").concat(s.source),{oldTrack:o,newTrack:s,participant:this,participantInfo:t}),this.addTrackPublication(s)}i.set(e.sid,s)})),this.tracks.forEach((e=>{i.has(e.trackSid)||(c.trace("detected removed track on remote participant, unpublishing",{publication:e,participantSid:this.sid}),this.unpublishTrack(e.trackSid,!0))})),n.forEach((t=>{this.emit(e.ParticipantEvent.TrackPublished,t)})),!0}unpublishTrack(t,i){const n=this.tracks.get(t);if(!n)return;const{track:r}=n;switch(r&&(r.stop(),n.setTrack(void 0)),this.tracks.delete(t),n.kind){case js.Kind.Audio:this.audioTracks.delete(t);break;case js.Kind.Video:this.videoTracks.delete(t)}i&&this.emit(e.ParticipantEvent.TrackUnpublished,n)}setAudioContext(e){this.audioContext=e,this.audioTracks.forEach((t=>t.track instanceof yo&&t.track.setAudioContext(e)))}setAudioOutput(e){return Ht(this,void 0,void 0,(function*(){this.audioOutput=e;const t=[];this.audioTracks.forEach((i=>{var n;i.track instanceof yo&&t.push(i.track.setSinkId(null!==(n=e.deviceId)&&void 0!==n?n:"default"))})),yield Promise.all(t)}))}emit(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),n=1;n<t;n++)i[n-1]=arguments[n];return c.trace("participant event",{participant:this.sid,event:e,args:i}),super.emit(e,...i)}}class Do extends Ro{constructor(e,t,i,n){super(e,t),this.pendingPublishing=new Set,this.pendingPublishPromises=new Map,this.participantTrackPermissions=[],this.allParticipantsAllowedToSubscribe=!0,this.handleReconnecting=()=>{this.reconnectFuture||(this.reconnectFuture=new Qr)},this.handleReconnected=()=>{var e,t;null===(t=null===(e=this.reconnectFuture)||void 0===e?void 0:e.resolve)||void 0===t||t.call(e),this.reconnectFuture=void 0,this.updateTrackSubscriptionPermissions()},this.handleDisconnected=()=>{var e,t;this.reconnectFuture&&(this.reconnectFuture.promise.catch((e=>c.warn(e))),null===(t=null===(e=this.reconnectFuture)||void 0===e?void 0:e.reject)||void 0===t||t.call(e,"Got disconnected during reconnection attempt"),this.reconnectFuture=void 0)},this.updateTrackSubscriptionPermissions=()=>{c.debug("updating track subscription permissions",{allParticipantsAllowed:this.allParticipantsAllowedToSubscribe,participantTrackPermissions:this.participantTrackPermissions}),this.engine.client.sendUpdateSubscriptionPermissions(this.allParticipantsAllowedToSubscribe,this.participantTrackPermissions.map((e=>function(e){var t,i,n;if(!e.participantSid&&!e.participantIdentity)throw new Error("Invalid track permission, must provide at least one of participantIdentity and participantSid");return{participantIdentity:null!==(t=e.participantIdentity)&&void 0!==t?t:"",participantSid:null!==(i=e.participantSid)&&void 0!==i?i:"",allTracks:null!==(n=e.allowAll)&&void 0!==n&&n,trackSids:e.allowedTrackSids||[]}}(e))))},this.onTrackUnmuted=e=>{this.onTrackMuted(e,e.isUpstreamPaused)},this.onTrackMuted=(e,t)=>{void 0===t&&(t=!0),e.sid?this.engine.updateMuteStatus(e.sid,t):c.error("could not update mute status for unpublished track",e)},this.onTrackUpstreamPaused=e=>{c.debug("upstream paused"),this.onTrackMuted(e,!0)},this.onTrackUpstreamResumed=e=>{c.debug("upstream resumed"),this.onTrackMuted(e,e.isMuted)},this.handleSubscribedQualityUpdate=e=>Ht(this,void 0,void 0,(function*(){var t,i,n,r,s,o;if(!(null===(s=this.roomOptions)||void 0===s?void 0:s.dynacast))return;const a=this.videoTracks.get(e.trackSid);if(a)if(e.subscribedCodecs.length>0){if(!a.videoTrack)return;const s=yield a.videoTrack.setPublishingCodecs(e.subscribedCodecs);try{for(var d,u=!0,l=Zt(s);!(t=(d=yield l.next()).done);u=!0){r=d.value,u=!1;const e=r;ws(e)&&(c.debug("publish ".concat(e," for ").concat(a.videoTrack.sid)),yield this.publishAdditionalCodecForTrack(a.videoTrack,e,a.options))}}catch(e){i={error:e}}finally{try{u||t||!(n=l.return)||(yield n.call(l))}finally{if(i)throw i.error}}}else e.subscribedQualities.length>0&&(yield null===(o=a.videoTrack)||void 0===o?void 0:o.setPublishingLayers(e.subscribedQualities));else c.warn("received subscribed quality update for unknown track",{method:"handleSubscribedQualityUpdate",sid:e.trackSid})})),this.handleLocalTrackUnpublished=e=>{const t=this.tracks.get(e.trackSid);t?this.unpublishTrack(t.track):c.warn("received unpublished event for unknown track",{method:"handleLocalTrackUnpublished",trackSid:e.trackSid})},this.handleTrackEnded=e=>Ht(this,void 0,void 0,(function*(){if(e.source===js.Source.ScreenShare||e.source===js.Source.ScreenShareAudio)c.debug("unpublishing local track due to TrackEnded",{track:e.sid}),this.unpublishTrack(e);else if(e.isUserProvided)yield e.mute();else if(e instanceof eo||e instanceof vo)try{if(Dr())try{const t=yield null===navigator||void 0===navigator?void 0:navigator.permissions.query({name:e.source===js.Source.Camera?"camera":"microphone"});if(t&&"denied"===t.state)throw c.warn("user has revoked access to ".concat(e.source)),t.onchange=()=>{"denied"!==t.state&&(e.isMuted||e.restartTrack(),t.onchange=null)},new Error("GetUserMedia Permission denied")}catch(e){}e.isMuted||(c.debug("track ended, attempting to use a different device"),yield e.restartTrack())}catch(t){c.warn("could not restart track, muting instead"),yield e.mute()}})),this.audioTracks=new Map,this.videoTracks=new Map,this.tracks=new Map,this.engine=i,this.roomOptions=n,this.setupEngine(i),this.activeDeviceMap=new Map}get lastCameraError(){return this.cameraError}get lastMicrophoneError(){return this.microphoneError}getTrack(e){const t=super.getTrack(e);if(t)return t}getTrackByName(e){const t=super.getTrackByName(e);if(t)return t}setupEngine(t){this.engine=t,this.engine.client.onRemoteMuteChanged=(e,t)=>{const i=this.tracks.get(e);i&&i.track&&(t?i.mute():i.unmute())},this.engine.client.onSubscribedQualityUpdate=this.handleSubscribedQualityUpdate,this.engine.client.onLocalTrackUnpublished=this.handleLocalTrackUnpublished,this.engine.on(e.EngineEvent.Connected,this.handleReconnected).on(e.EngineEvent.Restarted,this.handleReconnected).on(e.EngineEvent.Resumed,this.handleReconnected).on(e.EngineEvent.Restarting,this.handleReconnecting).on(e.EngineEvent.Resuming,this.handleReconnecting).on(e.EngineEvent.Disconnected,this.handleDisconnected)}setMetadata(e){var t;super.setMetadata(e),this.engine.client.sendUpdateLocalMetadata(e,null!==(t=this.name)&&void 0!==t?t:"")}setName(e){var t;super.setName(e),this.engine.client.sendUpdateLocalMetadata(null!==(t=this.metadata)&&void 0!==t?t:"",e)}setCameraEnabled(e,t,i){return this.setTrackEnabled(js.Source.Camera,e,t,i)}setMicrophoneEnabled(e,t,i){return this.setTrackEnabled(js.Source.Microphone,e,t,i)}setScreenShareEnabled(e,t,i){return this.setTrackEnabled(js.Source.ScreenShare,e,t,i)}setTrackEnabled(t,i,n,r){var s,o;return Ht(this,void 0,void 0,(function*(){c.debug("setTrackEnabled",{source:t,enabled:i});let a=this.getTrack(t);if(i)if(a)yield a.unmute();else{let i;if(this.pendingPublishing.has(t))return void c.info("skipping duplicate published source",{source:t});this.pendingPublishing.add(t);try{switch(t){case js.Source.Camera:i=yield this.createTracks({video:null===(s=n)||void 0===s||s});break;case js.Source.Microphone:i=yield this.createTracks({audio:null===(o=n)||void 0===o||o});break;case js.Source.ScreenShare:i=yield this.createScreenTracks(Object.assign({},n));break;default:throw new nr(t)}const e=[];for(const t of i)c.info("publishing track",{localTrack:t}),e.push(this.publishTrack(t,r));const d=yield Promise.all(e);[a]=d}catch(t){throw t instanceof Error&&!(t instanceof nr)&&this.emit(e.ParticipantEvent.MediaDevicesError,t),t}finally{this.pendingPublishing.delete(t)}}else if(a&&a.track)if(t===js.Source.ScreenShare){a=yield this.unpublishTrack(a.track);const e=this.getTrack(js.Source.ScreenShareAudio);e&&e.track&&this.unpublishTrack(e.track)}else yield a.mute();return a}))}enableCameraAndMicrophone(){return Ht(this,void 0,void 0,(function*(){if(!this.pendingPublishing.has(js.Source.Camera)&&!this.pendingPublishing.has(js.Source.Microphone)){this.pendingPublishing.add(js.Source.Camera),this.pendingPublishing.add(js.Source.Microphone);try{const e=yield this.createTracks({audio:!0,video:!0});yield Promise.all(e.map((e=>this.publishTrack(e))))}finally{this.pendingPublishing.delete(js.Source.Camera),this.pendingPublishing.delete(js.Source.Microphone)}}}))}createTracks(e){var t,i;return Ht(this,void 0,void 0,(function*(){const n=vr(mr(e,null===(t=this.roomOptions)||void 0===t?void 0:t.audioCaptureDefaults,null===(i=this.roomOptions)||void 0===i?void 0:i.videoCaptureDefaults));let r;try{r=yield navigator.mediaDevices.getUserMedia(n)}catch(e){throw e instanceof Error&&(n.audio&&(this.microphoneError=e),n.video&&(this.cameraError=e)),e}return n.audio&&(this.microphoneError=void 0),n.video&&(this.cameraError=void 0),r.getTracks().map((t=>{const i="audio"===t.kind;let s;i?e.audio:e.video;const o=i?n.audio:n.video;"boolean"!=typeof o&&(s=o);const a=to(t,s);return a.kind===js.Kind.Video?a.source=js.Source.Camera:a.kind===js.Kind.Audio&&(a.source=js.Source.Microphone),a.mediaStream=r,a}))}))}createScreenTracks(e){var t;return Ht(this,void 0,void 0,(function*(){void 0===e&&(e={}),void 0===e.resolution&&(e.resolution=Is.h1080fps15.resolution);let i=!0;if(e.resolution&&(i=Nr()?{width:{max:e.resolution.width},height:{max:e.resolution.height},frameRate:e.resolution.frameRate}:{width:{ideal:e.resolution.width},height:{ideal:e.resolution.height},frameRate:e.resolution.frameRate}),void 0===navigator.mediaDevices.getDisplayMedia)throw new ir("getDisplayMedia not supported");const n=yield navigator.mediaDevices.getDisplayMedia({audio:null!==(t=e.audio)&&void 0!==t&&t,video:i,controller:e.controller,selfBrowserSurface:e.selfBrowserSurface,surfaceSwitching:e.surfaceSwitching,systemAudio:e.systemAudio}),r=n.getVideoTracks();if(0===r.length)throw new nr("no video track found");const s=new vo(r[0],void 0,!1);s.source=js.Source.ScreenShare;const o=[s];if(n.getAudioTracks().length>0){const e=new eo(n.getAudioTracks()[0],void 0,!1);e.source=js.Source.ScreenShareAudio,o.push(e)}return o}))}publishTrack(e,t){var i,n,r,s;return Ht(this,void 0,void 0,(function*(){let o,a;if(yield null===(i=this.reconnectFuture)||void 0===i?void 0:i.promise,e instanceof Xs&&this.pendingPublishPromises.has(e)&&(yield this.pendingPublishPromises.get(e)),e instanceof MediaStreamTrack)o=e.getConstraints();else{let t;switch(o=e.constraints,e.source){case js.Source.Microphone:t="audioinput";break;case js.Source.Camera:t="videoinput"}t&&this.activeDeviceMap.has(t)&&(o=Object.assign(Object.assign({},o),{deviceId:this.activeDeviceMap.get(t)}))}if(e instanceof MediaStreamTrack)switch(e.kind){case"audio":e=new eo(e,o,!0);break;case"video":e=new vo(e,o,!0);break;default:throw new nr("unsupported MediaStreamTrack kind ".concat(e.kind))}if(this.tracks.forEach((t=>{t.track&&t.track===e&&(a=t)})),a)return c.warn("track has already been published, skipping"),a;const d="channelCount"in e.mediaStreamTrack.getSettings()&&2===e.mediaStreamTrack.getSettings().channelCount||2===e.mediaStreamTrack.getConstraints().channelCount,u=null!==(n=null==t?void 0:t.forceStereo)&&void 0!==n?n:d;u&&(t||(t={}),void 0===t.dtx&&c.info("Opus DTX will be disabled for stereo tracks by default. Enable them explicitly to make it work."),void 0===t.red&&c.info("Opus RED will be disabled for stereo tracks by default. Enable them explicitly to make it work."),null!==(r=t.dtx)&&void 0!==r||(t.dtx=!1),null!==(s=t.red)&&void 0!==s||(t.red=!1));const l=Object.assign(Object.assign({},this.roomOptions.publishDefaults),t);l.source&&(e.source=l.source);const h=this.publish(e,l,t,u);this.pendingPublishPromises.set(e,h);try{return yield h}catch(e){throw e}finally{this.pendingPublishPromises.delete(e)}}))}publish(t,i,n,r){var s,o,a,d,u,l,h,p,m,f,v,g,b,k;return Ht(this,void 0,void 0,(function*(){const S=Array.from(this.tracks.values()).find((e=>t instanceof Xs&&e.source===t.source));if(S&&t.source!==js.Source.Unknown)try{throw Error("publishing a second track with the same source: ".concat(t.source))}catch(e){e instanceof Error&&c.warn(e.message,{oldTrack:S,newTrack:t,trace:e.stack})}i.stopMicTrackOnMute&&t instanceof eo&&(t.stopOnMute=!0),t.source===js.Source.ScreenShare&&Rr()&&(i.simulcast=!1),"av1"!==i.videoCodec||Cr()||(i.videoCodec=void 0),"vp9"!==i.videoCodec||Tr()||(i.videoCodec=void 0),t.on(e.TrackEvent.Muted,this.onTrackMuted),t.on(e.TrackEvent.Unmuted,this.onTrackUnmuted),t.on(e.TrackEvent.Ended,this.handleTrackEnded),t.on(e.TrackEvent.UpstreamPaused,this.onTrackUpstreamPaused),t.on(e.TrackEvent.UpstreamResumed,this.onTrackUpstreamResumed);const y=fn.fromPartial({cid:t.mediaStreamTrack.id,name:null==n?void 0:n.name,type:js.kindToProto(t.kind),muted:t.isMuted,source:js.sourceToProto(t.source),disableDtx:!(null===(s=i.dtx)||void 0===s||s),stereo:r,disableRed:!(null===(o=i.red)||void 0===o||o)});let C,T;if(t.kind===js.Kind.Video){let e={width:0,height:0};try{e=yield t.waitForDimensions()}catch(t){const i=null!==(d=null===(a=this.roomOptions.videoCaptureDefaults)||void 0===a?void 0:a.resolution)&&void 0!==d?d:Os.h720.resolution;e={width:i.width,height:i.height},c.error("could not determine track dimensions, using defaults",e)}if(y.width=e.width,y.height=e.height,t instanceof vo)if(Er(i.videoCodec)&&(i.scalabilityMode=null!==(u=i.scalabilityMode)&&void 0!==u?u:"L3T3_KEY"),i.videoCodec&&i.backupCodec&&i.videoCodec!==i.backupCodec.codec){const e=Object.assign({},i);e.simulcast=!0,T=lo(t,i.backupCodec.codec,e),y.simulcastCodecs=[{codec:i.videoCodec,cid:t.mediaStreamTrack.id,enableSimulcastLayers:!0},{codec:i.backupCodec.codec,cid:"",enableSimulcastLayers:!0}]}else i.videoCodec&&(y.simulcastCodecs=[{codec:i.videoCodec,cid:t.mediaStreamTrack.id,enableSimulcastLayers:null!==(l=i.simulcast)&&void 0!==l&&l}]);C=uo(t.source===js.Source.ScreenShare,e.width,e.height,i),y.layers=ko(y.width,y.height,C,Er(i.videoCodec))}else t.kind===js.Kind.Audio&&(C=[{maxBitrate:null!==(p=null===(h=i.audioPreset)||void 0===h?void 0:h.maxBitrate)&&void 0!==p?p:i.audioBitrate,priority:null!==(f=null===(m=i.audioPreset)||void 0===m?void 0:m.priority)&&void 0!==f?f:"high",networkPriority:null!==(g=null===(v=i.audioPreset)||void 0===v?void 0:v.priority)&&void 0!==g?g:"high"}]);if(!this.engine||this.engine.isClosed)throw new sr("cannot publish track when not connected");const E=yield this.engine.addTrack(y);let P=!1,w=!1;if(E.codecs.forEach((e=>{Rs(e.mimeType,i.videoCodec)?P=!0:i.backupCodec&&Rs(e.mimeType,i.backupCodec.codec)&&(w=!0)})),y.simulcastCodecs.length>0){if(!P&&!w)throw Error("cannot publish track, codec not supported by server");if(!P&&i.backupCodec){const e=i.backupCodec;i=Object.assign({},i),c.debug("primary codec ".concat(i.videoCodec," not supported, fallback to ").concat(e.codec)),i.videoCodec=e.codec,i.videoEncoding=e.encoding,C=T}}const R=new wo(t.kind,E,t);if(R.options=i,t.sid=E.sid,!this.engine.publisher)throw new sr("publisher is closed");if(c.debug("publishing ".concat(t.kind," with encodings"),{encodings:C,trackInfo:E}),t.sender=yield this.engine.createSender(t,i,C),C)if(Rr()&&t.kind===js.Kind.Audio){let e;for(const i of this.engine.publisher.pc.getTransceivers())if(i.sender===t.sender){e=i;break}e&&this.engine.publisher.setTrackCodecBitrate({transceiver:e,codec:"opus",maxbr:(null===(b=C[0])||void 0===b?void 0:b.maxBitrate)?C[0].maxBitrate/1e3:0})}else t.codec&&Er(t.codec)&&(null===(k=C[0])||void 0===k?void 0:k.maxBitrate)&&this.engine.publisher.setTrackCodecBitrate({cid:y.cid,codec:t.codec,maxbr:C[0].maxBitrate/1e3});return this.engine.negotiate(),t instanceof vo?t.startMonitor(this.engine.client):t instanceof eo&&t.startMonitor(),this.addTrackPublication(R),this.emit(e.ParticipantEvent.LocalTrackPublished,R),R}))}get isLocal(){return!0}publishAdditionalCodecForTrack(e,t,i){var n;return Ht(this,void 0,void 0,(function*(){let r;if(this.tracks.forEach((t=>{t.track&&t.track===e&&(r=t)})),!r)throw new nr("track is not published");if(!(e instanceof vo))throw new nr("track is not a video track");const s=Object.assign(Object.assign({},null===(n=this.roomOptions)||void 0===n?void 0:n.publishDefaults),i),o=lo(e,t,s);if(!o)return void c.info("backup codec has been disabled, ignoring request to add additional codec for track");const a=e.addSimulcastTrack(t,o),d=fn.fromPartial({cid:a.mediaStreamTrack.id,type:js.kindToProto(e.kind),muted:e.isMuted,source:js.sourceToProto(e.source),sid:e.sid,simulcastCodecs:[{codec:s.videoCodec,cid:a.mediaStreamTrack.id,enableSimulcastLayers:s.simulcast}]});if(d.layers=ko(d.width,d.height,o),!this.engine||this.engine.isClosed)throw new sr("cannot publish track when not connected");const u=yield this.engine.addTrack(d);yield this.engine.createSimulcastSender(e,a,s,o),this.engine.negotiate(),c.debug("published ".concat(t," for track ").concat(e.sid),{encodings:o,trackInfo:u})}))}unpublishTrack(t,i){var n,r;return Ht(this,void 0,void 0,(function*(){const s=this.getPublicationForTrack(t);if(c.debug("unpublishing track",{track:t,method:"unpublishTrack"}),!s||!s.track)return void c.warn("track was not unpublished because no publication was found",{track:t,method:"unpublishTrack"});(t=s.track).off(e.TrackEvent.Muted,this.onTrackMuted),t.off(e.TrackEvent.Unmuted,this.onTrackUnmuted),t.off(e.TrackEvent.Ended,this.handleTrackEnded),t.off(e.TrackEvent.UpstreamPaused,this.onTrackUpstreamPaused),t.off(e.TrackEvent.UpstreamResumed,this.onTrackUpstreamResumed),void 0===i&&(i=null===(r=null===(n=this.roomOptions)||void 0===n?void 0:n.stopLocalTrackOnUnpublish)||void 0===r||r),i&&t.stop();let o=!1;const a=t.sender;if(t.sender=void 0,this.engine.publisher&&"closed"!==this.engine.publisher.pc.connectionState&&a)try{for(const e of this.engine.publisher.pc.getTransceivers())e.sender===a&&(e.direction="inactive",o=!0);if(this.engine.removeTrack(a)&&(o=!0),t instanceof vo){for(const[,e]of t.simulcastCodecs)e.sender&&(this.engine.removeTrack(e.sender)&&(o=!0),e.sender=void 0);t.simulcastCodecs.clear()}}catch(e){c.warn("failed to unpublish track",{error:e,method:"unpublishTrack"})}switch(this.tracks.delete(s.trackSid),s.kind){case js.Kind.Audio:this.audioTracks.delete(s.trackSid);break;case js.Kind.Video:this.videoTracks.delete(s.trackSid)}return this.emit(e.ParticipantEvent.LocalTrackUnpublished,s),s.setTrack(void 0),o&&(yield this.engine.negotiate()),s}))}unpublishTracks(e){return Ht(this,void 0,void 0,(function*(){return(yield Promise.all(e.map((e=>this.unpublishTrack(e))))).filter((e=>e instanceof wo))}))}republishAllTracks(e){return Ht(this,void 0,void 0,(function*(){const t=[];this.tracks.forEach((i=>{i.track&&(e&&(i.options=Object.assign(Object.assign({},i.options),e)),t.push(i))})),yield Promise.all(t.map((e=>Ht(this,void 0,void 0,(function*(){const t=e.track;yield this.unpublishTrack(t,!1),yield this.publishTrack(t,e.options)})))))}))}publishData(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return Ht(this,void 0,void 0,(function*(){const n=Array.isArray(i)?i:null==i?void 0:i.destination,r=[],s=Array.isArray(i)?void 0:i.topic;void 0!==n&&n.forEach((e=>{e instanceof Oo?r.push(e.sid):r.push(e)}));const o={kind:t,value:{$case:"user",user:{participantSid:this.sid,payload:e,destinationSids:r,topic:s}}};yield this.engine.sendDataPacket(o,t)}))}setTrackSubscriptionPermissions(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[];this.participantTrackPermissions=t,this.allParticipantsAllowedToSubscribe=e,this.engine.client.isConnected&&this.updateTrackSubscriptionPermissions()}updateInfo(e){return e.sid===this.sid&&(!!super.updateInfo(e)&&(e.tracks.forEach((e=>{var t,i;const n=this.tracks.get(e.sid);if(n){const r=n.isMuted||null!==(i=null===(t=n.track)||void 0===t?void 0:t.isUpstreamPaused)&&void 0!==i&&i;r!==e.muted&&(c.debug("updating server mute state after reconcile",{sid:e.sid,muted:r}),this.engine.client.sendMuteTrack(e.sid,r))}})),!0))}getPublicationForTrack(e){let t;return this.tracks.forEach((i=>{const n=i.track;n&&(e instanceof MediaStreamTrack?(n instanceof eo||n instanceof vo)&&n.mediaStreamTrack===e&&(t=i):e===n&&(t=i))})),t}publishedTracksInfo(){const e=[];return this.tracks.forEach((t=>{void 0!==t.track&&e.push({cid:t.track.mediaStreamID,track:t.trackInfo})})),e}dataChannelsInfo(){const t=[],i=(e,i)=>{void 0!==(null==e?void 0:e.id)&&null!==e.id&&t.push({label:e.label,id:e.id,target:i})};return i(this.engine.dataChannelForKind(e.DataPacket_Kind.LOSSY),rn.PUBLISHER),i(this.engine.dataChannelForKind(e.DataPacket_Kind.RELIABLE),rn.PUBLISHER),i(this.engine.dataChannelForKind(e.DataPacket_Kind.LOSSY,!0),rn.SUBSCRIBER),i(this.engine.dataChannelForKind(e.DataPacket_Kind.RELIABLE,!0),rn.SUBSCRIBER),t}}var Io;e.ConnectionState=void 0,(Io=e.ConnectionState||(e.ConnectionState={})).Disconnected="disconnected",Io.Connecting="connecting",Io.Connected="connected",Io.Reconnecting="reconnecting";const Ao=e.ConnectionState;class Uo extends Yt{constructor(t){var i,n;super(),i=this,this.state=e.ConnectionState.Disconnected,this.activeSpeakers=[],this.audioEnabled=!0,this.connect=(t,i,n)=>Ht(this,void 0,void 0,(function*(){const r=yield this.disconnectLock.lock();if(this.state===e.ConnectionState.Connected)return c.info("already connected to room ".concat(this.name)),r(),Promise.resolve();if(this.connectFuture)return r(),this.connectFuture.promise;this.setAndEmitConnectionState(e.ConnectionState.Connecting);const s=new Ts(t,i),o=(e,a,d)=>Ht(this,void 0,void 0,(function*(){var u;this.abortController&&this.abortController.abort(),this.abortController=new AbortController,null==r||r();try{yield this.attemptConnection(null!=d?d:t,i,n,this.abortController),this.abortController=void 0,e()}catch(i){if(Ar(new URL(t))&&i instanceof tr&&3!==i.reason){let t=null;try{t=yield s.getNextBestRegionUrl(null===(u=this.abortController)||void 0===u?void 0:u.signal)}catch(e){if(e instanceof tr&&(401===e.status||3===e.reason))return void a(e)}t?(c.debug("initial connection failed, retrying with another region"),yield o(e,a,t)):a(i)}else a(i)}}));return this.connectFuture=new Qr(o,(()=>{this.clearConnectionFutures()})),this.connectFuture.promise})),this.connectSignal=(e,t,i,n,r,s)=>Ht(this,void 0,void 0,(function*(){const o=yield i.join(e,t,{autoSubscribe:n.autoSubscribe,publishOnly:n.publishOnly,adaptiveStream:"object"==typeof r.adaptiveStream||r.adaptiveStream,maxRetries:n.maxRetries},s.signal);let a=o.serverInfo;if(a||(a={version:o.serverVersion,region:o.serverRegion}),c.debug("connected to Livekit Server ".concat(Object.entries(a).map((e=>{let[t,i]=e;return"".concat(t,": ").concat(i)})).join(", "))),!o.serverVersion)throw new rr("unknown server version");return"0.15.1"===o.serverVersion&&this.options.dynacast&&(c.debug("disabling dynacast due to server version"),r.dynacast=!1),o})),this.applyJoinResponse=e=>{const t=e.participant;this.localParticipant.sid=t.sid,this.localParticipant.identity=t.identity,this.handleParticipantUpdates([t,...e.otherParticipants]),e.room&&this.handleRoomUpdate(e.room)},this.attemptConnection=(t,i,n,r)=>Ht(this,void 0,void 0,(function*(){var s;this.state===e.ConnectionState.Reconnecting?(c.info("Reconnection attempt replaced by new connection attempt"),this.recreateEngine()):this.maybeCreateEngine(),this.acquireAudioContext(),this.connOptions=Object.assign(Object.assign({},_s),n),this.connOptions.rtcConfig&&(this.engine.rtcConfig=this.connOptions.rtcConfig),this.connOptions.peerConnectionTimeout&&(this.engine.peerConnectionTimeout=this.connOptions.peerConnectionTimeout);try{const n=yield this.connectSignal(t,i,this.engine,this.connOptions,this.options,r);this.applyJoinResponse(n),this.setupLocalParticipantEvents(),this.emit(e.RoomEvent.SignalConnected)}catch(e){this.recreateEngine(),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish);const t=new tr("could not establish signal connection");throw e instanceof Error&&(t.message="".concat(t.message,": ").concat(e.message)),e instanceof tr&&(t.reason=e.reason,t.status=e.status),c.debug("error trying to establish signal connection",{error:e}),t}if(r.signal.aborted)throw this.recreateEngine(),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),new tr("Connection attempt aborted");try{yield this.engine.waitForPCInitialConnection(this.connOptions.peerConnectionTimeout,r)}catch(e){throw this.recreateEngine(),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),e}Dr()&&this.options.disconnectOnPageLeave&&(window.addEventListener("pagehide",this.onPageLeave),window.addEventListener("beforeunload",this.onPageLeave)),Dr()&&(document.addEventListener("freeze",this.onPageLeave),null===(s=navigator.mediaDevices)||void 0===s||s.addEventListener("devicechange",this.handleDeviceChange)),this.setAndEmitConnectionState(e.ConnectionState.Connected),this.emit(e.RoomEvent.Connected),this.registerConnectionReconcile()})),this.disconnect=function(){let t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return Ht(i,void 0,void 0,(function*(){var i,n,r,s;const o=yield this.disconnectLock.lock();try{if(this.state===e.ConnectionState.Disconnected)return void c.debug("already disconnected");c.info("disconnect from room",{identity:this.localParticipant.identity}),this.state!==e.ConnectionState.Connecting&&this.state!==e.ConnectionState.Reconnecting||(c.warn("abort connection attempt"),null===(i=this.abortController)||void 0===i||i.abort(),null===(r=null===(n=this.connectFuture)||void 0===n?void 0:n.reject)||void 0===r||r.call(n,new tr("Client initiated disconnect")),this.connectFuture=void 0),(null===(s=this.engine)||void 0===s?void 0:s.client.isConnected)&&(yield this.engine.client.sendLeave()),this.engine&&(yield this.engine.close()),this.handleDisconnect(t,e.DisconnectReason.CLIENT_INITIATED),this.engine=void 0}finally{o()}}))},this.onPageLeave=()=>Ht(this,void 0,void 0,(function*(){yield this.disconnect()})),this.handleRestarting=()=>{this.clearConnectionReconcile();for(const e of this.participants.values())this.handleParticipantDisconnected(e.sid,e);this.setAndEmitConnectionState(e.ConnectionState.Reconnecting)&&this.emit(e.RoomEvent.Reconnecting)},this.handleSignalRestarted=t=>Ht(this,void 0,void 0,(function*(){c.debug("signal reconnected to server",{region:t.serverRegion}),this.cachedParticipantSids=[],this.applyJoinResponse(t);try{const e=[];this.localParticipant.tracks.forEach((t=>{t.track&&e.push(t)})),yield Promise.all(e.map((e=>Ht(this,void 0,void 0,(function*(){const t=e.track;this.localParticipant.unpublishTrack(t,!1),t.isMuted||((t instanceof eo||t instanceof vo)&&!t.isUserProvided&&(c.debug("restarting existing track",{track:e.trackSid}),yield t.restartTrack()),c.debug("publishing new track",{track:e.trackSid}),yield this.localParticipant.publishTrack(t,e.options))})))))}catch(e){c.error("error trying to re-publish tracks after reconnection",{error:e})}try{yield this.engine.waitForRestarted(),c.debug("fully reconnected to server",{region:t.serverRegion})}catch(e){return}this.setAndEmitConnectionState(e.ConnectionState.Connected),this.emit(e.RoomEvent.Reconnected),this.registerConnectionReconcile(),this.participants.forEach((t=>{this.emit(e.RoomEvent.ParticipantConnected,t)}))})),this.handleParticipantUpdates=e=>{e.forEach((e=>{if(e.identity===this.localParticipant.identity)return void this.localParticipant.updateInfo(e);const t=this.identityToSid.get(e.identity);t&&t!==e.sid&&this.handleParticipantDisconnected(t,this.participants.get(t));let i=this.participants.get(e.sid);const n=!i;e.state===et.DISCONNECTED?this.handleParticipantDisconnected(e.sid,i):(i=this.getOrCreateParticipant(e.sid,e),n||i.updateInfo(e))}))},this.handleActiveSpeakersUpdate=t=>{const i=[],n={};t.forEach((e=>{if(n[e.sid]=!0,e.sid===this.localParticipant.sid)this.localParticipant.audioLevel=e.level,this.localParticipant.setIsSpeaking(!0),i.push(this.localParticipant);else{const t=this.participants.get(e.sid);t&&(t.audioLevel=e.level,t.setIsSpeaking(!0),i.push(t))}})),n[this.localParticipant.sid]||(this.localParticipant.audioLevel=0,this.localParticipant.setIsSpeaking(!1)),this.participants.forEach((e=>{n[e.sid]||(e.audioLevel=0,e.setIsSpeaking(!1))})),this.activeSpeakers=i,this.emitWhenConnected(e.RoomEvent.ActiveSpeakersChanged,i)},this.handleSpeakersChanged=t=>{const i=new Map;this.activeSpeakers.forEach((e=>{i.set(e.sid,e)})),t.forEach((e=>{let t=this.participants.get(e.sid);e.sid===this.localParticipant.sid&&(t=this.localParticipant),t&&(t.audioLevel=e.level,t.setIsSpeaking(e.active),e.active?i.set(e.sid,t):i.delete(e.sid))}));const n=Array.from(i.values());n.sort(((e,t)=>t.audioLevel-e.audioLevel)),this.activeSpeakers=n,this.emitWhenConnected(e.RoomEvent.ActiveSpeakersChanged,n)},this.handleStreamStateUpdate=t=>{t.streamStates.forEach((t=>{const i=this.participants.get(t.participantSid);if(!i)return;const n=i.getTrackPublication(t.trackSid);n&&n.track&&(n.track.streamState=js.streamStateFromProto(t.state),i.emit(e.ParticipantEvent.TrackStreamStateChanged,n,n.track.streamState),this.emitWhenConnected(e.RoomEvent.TrackStreamStateChanged,n,n.track.streamState,i))}))},this.handleSubscriptionPermissionUpdate=e=>{const t=this.participants.get(e.participantSid);if(!t)return;const i=t.getTrackPublication(e.trackSid);i&&i.setAllowed(e.allowed)},this.handleSubscriptionError=e=>{const t=Array.from(this.participants.values()).find((t=>t.tracks.has(e.trackSid)));if(!t)return;const i=t.getTrackPublication(e.trackSid);i&&i.setSubscriptionError(e.err)},this.handleDataPacket=(t,i)=>{const n=this.participants.get(t.participantSid);this.emit(e.RoomEvent.DataReceived,t.payload,n,i,t.topic),null==n||n.emit(e.ParticipantEvent.DataReceived,t.payload,i)},this.handleAudioPlaybackStarted=()=>{this.canPlaybackAudio||(this.audioEnabled=!0,this.emit(e.RoomEvent.AudioPlaybackStatusChanged,!0))},this.handleAudioPlaybackFailed=t=>{c.warn("could not playback audio",t),this.canPlaybackAudio&&(this.audioEnabled=!1,this.emit(e.RoomEvent.AudioPlaybackStatusChanged,!1))},this.handleDeviceChange=()=>Ht(this,void 0,void 0,(function*(){this.emit(e.RoomEvent.MediaDevicesChanged)})),this.handleRoomUpdate=t=>{const i=this.roomInfo;this.roomInfo=t,i&&i.metadata!==t.metadata&&this.emitWhenConnected(e.RoomEvent.RoomMetadataChanged,t.metadata),(null==i?void 0:i.activeRecording)!==t.activeRecording&&this.emitWhenConnected(e.RoomEvent.RecordingStatusChanged,t.activeRecording)},this.handleConnectionQualityUpdate=e=>{e.updates.forEach((e=>{if(e.participantSid===this.localParticipant.sid)return void this.localParticipant.setConnectionQuality(e.quality);const t=this.participants.get(e.participantSid);t&&t.setConnectionQuality(e.quality)}))},this.onLocalParticipantMetadataChanged=t=>{this.emit(e.RoomEvent.ParticipantMetadataChanged,t,this.localParticipant)},this.onLocalParticipantNameChanged=t=>{this.emit(e.RoomEvent.ParticipantNameChanged,t,this.localParticipant)},this.onLocalTrackMuted=t=>{this.emit(e.RoomEvent.TrackMuted,t,this.localParticipant)},this.onLocalTrackUnmuted=t=>{this.emit(e.RoomEvent.TrackUnmuted,t,this.localParticipant)},this.onLocalTrackPublished=t=>Ht(this,void 0,void 0,(function*(){if(this.emit(e.RoomEvent.LocalTrackPublished,t,this.localParticipant),t.track instanceof eo){(yield t.track.checkForSilence())&&this.emit(e.RoomEvent.LocalAudioSilenceDetected,t)}})),this.onLocalTrackUnpublished=t=>{this.emit(e.RoomEvent.LocalTrackUnpublished,t,this.localParticipant)},this.onLocalConnectionQualityChanged=t=>{this.emit(e.RoomEvent.ConnectionQualityChanged,t,this.localParticipant)},this.onMediaDevicesError=t=>{this.emit(e.RoomEvent.MediaDevicesError,t)},this.onLocalParticipantPermissionsChanged=t=>{this.emit(e.RoomEvent.ParticipantPermissionsChanged,t,this.localParticipant)},this.participants=new Map,this.cachedParticipantSids=[],this.identityToSid=new Map,this.options=Object.assign(Object.assign({},Ls),t),this.options.audioCaptureDefaults=Object.assign(Object.assign({},Us),null==t?void 0:t.audioCaptureDefaults),this.options.videoCaptureDefaults=Object.assign(Object.assign({},Ms),null==t?void 0:t.videoCaptureDefaults),this.options.publishDefaults=Object.assign(Object.assign({},As),null==t?void 0:t.publishDefaults),this.maybeCreateEngine(),this.disconnectLock=new Hr,this.localParticipant=new Do("","",this.engine,this.options),this.options.videoCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("videoinput",Kr(this.options.videoCaptureDefaults.deviceId)),this.options.audioCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("audioinput",Kr(this.options.audioCaptureDefaults.deviceId)),(null===(n=this.options.audioOutput)||void 0===n?void 0:n.deviceId)&&this.switchActiveDevice("audiooutput",Kr(this.options.audioOutput.deviceId))}get isRecording(){var e,t;return null!==(t=null===(e=this.roomInfo)||void 0===e?void 0:e.activeRecording)&&void 0!==t&&t}get sid(){var e,t;return null!==(t=null===(e=this.roomInfo)||void 0===e?void 0:e.sid)&&void 0!==t?t:""}get name(){var e,t;return null!==(t=null===(e=this.roomInfo)||void 0===e?void 0:e.name)&&void 0!==t?t:""}get metadata(){var e;return null===(e=this.roomInfo)||void 0===e?void 0:e.metadata}get numParticipants(){var e,t;return null!==(t=null===(e=this.roomInfo)||void 0===e?void 0:e.numParticipants)&&void 0!==t?t:0}get numPublishers(){var e,t;return null!==(t=null===(e=this.roomInfo)||void 0===e?void 0:e.numPublishers)&&void 0!==t?t:0}maybeCreateEngine(){this.engine&&!this.engine.isClosed||(this.engine=new Ks(this.options),this.engine.client.onParticipantUpdate=this.handleParticipantUpdates,this.engine.client.onRoomUpdate=this.handleRoomUpdate,this.engine.client.onSpeakersChanged=this.handleSpeakersChanged,this.engine.client.onStreamStateUpdate=this.handleStreamStateUpdate,this.engine.client.onSubscriptionPermissionUpdate=this.handleSubscriptionPermissionUpdate,this.engine.client.onConnectionQuality=this.handleConnectionQualityUpdate,this.engine.client.onSubscriptionError=this.handleSubscriptionError,this.engine.on(e.EngineEvent.MediaTrackAdded,((e,t,i)=>{this.onTrackAdded(e,t,i)})).on(e.EngineEvent.Disconnected,(e=>{this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e)})).on(e.EngineEvent.ActiveSpeakersUpdate,this.handleActiveSpeakersUpdate).on(e.EngineEvent.DataPacketReceived,this.handleDataPacket).on(e.EngineEvent.Resuming,(()=>{this.clearConnectionReconcile(),this.setAndEmitConnectionState(e.ConnectionState.Reconnecting)&&this.emit(e.RoomEvent.Reconnecting),this.cachedParticipantSids=Array.from(this.participants.keys())})).on(e.EngineEvent.Resumed,(()=>{this.setAndEmitConnectionState(e.ConnectionState.Connected),this.emit(e.RoomEvent.Reconnected),this.registerConnectionReconcile(),this.updateSubscriptions();Array.from(this.participants.values()).filter((e=>!this.cachedParticipantSids.includes(e.sid))).forEach((t=>this.emit(e.RoomEvent.ParticipantConnected,t))),this.cachedParticipantSids=[]})).on(e.EngineEvent.SignalResumed,(()=>{this.state===e.ConnectionState.Reconnecting&&this.sendSyncState()})).on(e.EngineEvent.Restarting,this.handleRestarting).on(e.EngineEvent.SignalRestarted,this.handleSignalRestarted).on(e.EngineEvent.DCBufferStatusChanged,((t,i)=>{this.emit(e.RoomEvent.DCBufferStatusChanged,t,i)})),this.localParticipant&&this.localParticipant.setupEngine(this.engine))}static getLocalDevices(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return ns.getInstance().getDevices(e,t)}prepareConnection(e){return Ht(this,void 0,void 0,(function*(){yield fetch("http".concat(e.substring(2)),{method:"HEAD"})}))}getParticipantByIdentity(e){if(this.localParticipant.identity===e)return this.localParticipant;const t=this.identityToSid.get(e);return t?this.participants.get(t):void 0}clearConnectionFutures(){this.connectFuture=void 0}simulateScenario(t){return Ht(this,void 0,void 0,(function*(){let i,n=()=>{};switch(t){case"signal-reconnect":yield this.engine.client.close(),this.engine.client.onClose&&this.engine.client.onClose("simulate disconnect");break;case"speaker":i=Wn.fromPartial({scenario:{$case:"speakerUpdate",speakerUpdate:3}});break;case"node-failure":i=Wn.fromPartial({scenario:{$case:"nodeFailure",nodeFailure:!0}});break;case"server-leave":i=Wn.fromPartial({scenario:{$case:"serverLeave",serverLeave:!0}});break;case"migration":i=Wn.fromPartial({scenario:{$case:"migration",migration:!0}});break;case"resume-reconnect":this.engine.failNext(),yield this.engine.client.close(),this.engine.client.onClose&&this.engine.client.onClose("simulate resume-reconnect");break;case"full-reconnect":this.engine.fullReconnectOnNext=!0,yield this.engine.client.close(),this.engine.client.onClose&&this.engine.client.onClose("simulate full-reconnect");break;case"force-tcp":case"force-tls":i=Wn.fromPartial({scenario:{$case:"switchCandidateProtocol",switchCandidateProtocol:"force-tls"===t?2:1}}),n=()=>Ht(this,void 0,void 0,(function*(){const t=this.engine.client.onLeave;t&&t({reason:e.DisconnectReason.CLIENT_INITIATED,canReconnect:!0})}))}i&&(this.engine.client.sendSimulateScenario(i),n())}))}startAudio(){return Ht(this,void 0,void 0,(function*(){yield this.acquireAudioContext();const e=[];if(Nr()){const t="livekit-dummy-audio-el";let i=document.getElementById(t);if(!i){i=document.createElement("audio"),i.autoplay=!0,i.hidden=!0;const e=Gr();e.enabled=!0,i.srcObject=new MediaStream([e]),document.body.append(i)}e.push(i)}this.participants.forEach((t=>{t.audioTracks.forEach((t=>{t.track&&t.track.attachedElements.forEach((t=>{e.push(t)}))}))}));try{yield Promise.all(e.map((e=>(e.muted=!1,e.play())))),this.handleAudioPlaybackStarted()}catch(e){throw this.handleAudioPlaybackFailed(e),e}}))}get canPlaybackAudio(){return this.audioEnabled}getActiveAudioOutputDevice(){var e,t;return null!==(t=null===(e=this.options.audioOutput)||void 0===e?void 0:e.deviceId)&&void 0!==t?t:""}getActiveDevice(e){return this.localParticipant.activeDeviceMap.get(e)}switchActiveDevice(t,i){let n=arguments.length>2&&void 0!==arguments[2]&&arguments[2];var r,s,o;return Ht(this,void 0,void 0,(function*(){let a=!1,c=!0;const d=n?{exact:i}:i;if("audioinput"===t){const e=this.options.audioCaptureDefaults.deviceId;this.options.audioCaptureDefaults.deviceId=d,a=e!==d;const t=Array.from(this.localParticipant.audioTracks.values()).filter((e=>e.source===js.Source.Microphone));try{c=(yield Promise.all(t.map((e=>{var t;return null===(t=e.audioTrack)||void 0===t?void 0:t.setDeviceId(d)})))).every((e=>!0===e))}catch(t){throw this.options.audioCaptureDefaults.deviceId=e,t}}else if("videoinput"===t){const e=this.options.videoCaptureDefaults.deviceId;this.options.videoCaptureDefaults.deviceId=d,a=e!==d;const t=Array.from(this.localParticipant.videoTracks.values()).filter((e=>e.source===js.Source.Camera));try{c=(yield Promise.all(t.map((e=>{var t;return null===(t=e.videoTrack)||void 0===t?void 0:t.setDeviceId(d)})))).every((e=>!0===e))}catch(t){throw this.options.videoCaptureDefaults.deviceId=e,t}}else if("audiooutput"===t){if(!Pr()&&!this.options.expWebAudioMix||this.audioContext&&!("setSinkId"in this.audioContext))throw new Error("cannot switch audio output, setSinkId not supported");null!==(r=(o=this.options).audioOutput)&&void 0!==r||(o.audioOutput={});const e=this.options.audioOutput.deviceId;this.options.audioOutput.deviceId=i,a=e!==d;try{this.options.expWebAudioMix?null===(s=this.audioContext)||void 0===s||s.setSinkId(i):yield Promise.all(Array.from(this.participants.values()).map((e=>e.setAudioOutput({deviceId:i}))))}catch(t){throw this.options.audioOutput.deviceId=e,t}}return a&&c&&(this.localParticipant.activeDeviceMap.set(t,i),this.emit(e.RoomEvent.ActiveDeviceChanged,t,i)),c}))}setupLocalParticipantEvents(){this.localParticipant.on(e.ParticipantEvent.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).on(e.ParticipantEvent.ParticipantNameChanged,this.onLocalParticipantNameChanged).on(e.ParticipantEvent.TrackMuted,this.onLocalTrackMuted).on(e.ParticipantEvent.TrackUnmuted,this.onLocalTrackUnmuted).on(e.ParticipantEvent.LocalTrackPublished,this.onLocalTrackPublished).on(e.ParticipantEvent.LocalTrackUnpublished,this.onLocalTrackUnpublished).on(e.ParticipantEvent.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).on(e.ParticipantEvent.MediaDevicesError,this.onMediaDevicesError).on(e.ParticipantEvent.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged)}recreateEngine(){var e;null===(e=this.engine)||void 0===e||e.close(),this.engine=void 0,this.participants.clear(),this.maybeCreateEngine()}onTrackAdded(t,i,n){if(this.state===e.ConnectionState.Connecting||this.state===e.ConnectionState.Reconnecting){const r=()=>{this.onTrackAdded(t,i,n),s()},s=()=>{this.off(e.RoomEvent.Reconnected,r),this.off(e.RoomEvent.Connected,r),this.off(e.RoomEvent.Disconnected,s)};return this.once(e.RoomEvent.Reconnected,r),this.once(e.RoomEvent.Connected,r),void this.once(e.RoomEvent.Disconnected,s)}if(this.state===e.ConnectionState.Disconnected)return void c.warn("skipping incoming track after Room disconnected");const r=function(e){const t=e.split("|");return t.length>1?[t[0],e.substr(t[0].length+1)]:[e,""]}(i.id),s=r[0];let o=r[1];if(o&&""!==o||(o=t.id),s===this.localParticipant.sid)return void c.warn("tried to create RemoteParticipant for local participant");const a=this.getOrCreateParticipant(s);let d;this.options.adaptiveStream&&(d="object"==typeof this.options.adaptiveStream?this.options.adaptiveStream:{}),a.addSubscribedMediaTrack(t,o,i,n,d)}handleDisconnect(){let t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0],i=arguments.length>1?arguments[1]:void 0;var n;if(this.clearConnectionReconcile(),this.state!==e.ConnectionState.Disconnected)try{this.participants.forEach((e=>{e.tracks.forEach((t=>{e.unpublishTrack(t.trackSid)}))})),this.localParticipant.tracks.forEach((e=>{var i,n;e.track&&this.localParticipant.unpublishTrack(e.track,t),t&&(null===(i=e.track)||void 0===i||i.detach(),null===(n=e.track)||void 0===n||n.stop())})),this.localParticipant.off(e.ParticipantEvent.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).off(e.ParticipantEvent.ParticipantNameChanged,this.onLocalParticipantNameChanged).off(e.ParticipantEvent.TrackMuted,this.onLocalTrackMuted).off(e.ParticipantEvent.TrackUnmuted,this.onLocalTrackUnmuted).off(e.ParticipantEvent.LocalTrackPublished,this.onLocalTrackPublished).off(e.ParticipantEvent.LocalTrackUnpublished,this.onLocalTrackUnpublished).off(e.ParticipantEvent.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).off(e.ParticipantEvent.MediaDevicesError,this.onMediaDevicesError).off(e.ParticipantEvent.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged),this.localParticipant.tracks.clear(),this.localParticipant.videoTracks.clear(),this.localParticipant.audioTracks.clear(),this.participants.clear(),this.activeSpeakers=[],this.audioContext&&"boolean"==typeof this.options.expWebAudioMix&&(this.audioContext.close(),this.audioContext=void 0),Dr()&&(window.removeEventListener("beforeunload",this.onPageLeave),window.removeEventListener("pagehide",this.onPageLeave),window.removeEventListener("freeze",this.onPageLeave),null===(n=navigator.mediaDevices)||void 0===n||n.removeEventListener("devicechange",this.handleDeviceChange))}finally{this.setAndEmitConnectionState(e.ConnectionState.Disconnected),this.emit(e.RoomEvent.Disconnected,i)}}handleParticipantDisconnected(t,i){this.participants.delete(t),i&&(this.identityToSid.delete(i.identity),i.tracks.forEach((e=>{i.unpublishTrack(e.trackSid,!0)})),this.emit(e.RoomEvent.ParticipantDisconnected,i))}acquireAudioContext(){var t,i;return Ht(this,void 0,void 0,(function*(){"boolean"!=typeof this.options.expWebAudioMix&&this.options.expWebAudioMix.audioContext?(this.audioContext=this.options.expWebAudioMix.audioContext,yield this.audioContext.resume()):this.audioContext=null!==(t=gr())&&void 0!==t?t:void 0,this.options.expWebAudioMix&&this.participants.forEach((e=>e.setAudioContext(this.audioContext)));const n="running"===(null===(i=this.audioContext)||void 0===i?void 0:i.state);n!==this.canPlaybackAudio&&(this.audioEnabled=n,this.emit(e.RoomEvent.AudioPlaybackStatusChanged,n))}))}createParticipant(e,t){let i;return i=t?Oo.fromParticipantInfo(this.engine.client,t):new Oo(this.engine.client,e,"",void 0,void 0),this.options.expWebAudioMix&&i.setAudioContext(this.audioContext),i}getOrCreateParticipant(t,i){if(this.participants.has(t))return this.participants.get(t);const n=this.createParticipant(t,i);return this.participants.set(t,n),i&&(this.identityToSid.set(i.identity,i.sid),this.emitWhenConnected(e.RoomEvent.ParticipantConnected,n)),n.on(e.ParticipantEvent.TrackPublished,(t=>{this.emitWhenConnected(e.RoomEvent.TrackPublished,t,n)})).on(e.ParticipantEvent.TrackSubscribed,((t,i)=>{t.kind===js.Kind.Audio&&(t.on(e.TrackEvent.AudioPlaybackStarted,this.handleAudioPlaybackStarted),t.on(e.TrackEvent.AudioPlaybackFailed,this.handleAudioPlaybackFailed)),this.emit(e.RoomEvent.TrackSubscribed,t,i,n)})).on(e.ParticipantEvent.TrackUnpublished,(t=>{this.emit(e.RoomEvent.TrackUnpublished,t,n)})).on(e.ParticipantEvent.TrackUnsubscribed,((t,i)=>{this.emit(e.RoomEvent.TrackUnsubscribed,t,i,n)})).on(e.ParticipantEvent.TrackSubscriptionFailed,(t=>{this.emit(e.RoomEvent.TrackSubscriptionFailed,t,n)})).on(e.ParticipantEvent.TrackMuted,(t=>{this.emitWhenConnected(e.RoomEvent.TrackMuted,t,n)})).on(e.ParticipantEvent.TrackUnmuted,(t=>{this.emitWhenConnected(e.RoomEvent.TrackUnmuted,t,n)})).on(e.ParticipantEvent.ParticipantMetadataChanged,(t=>{this.emitWhenConnected(e.RoomEvent.ParticipantMetadataChanged,t,n)})).on(e.ParticipantEvent.ParticipantNameChanged,(t=>{this.emitWhenConnected(e.RoomEvent.ParticipantNameChanged,t,n)})).on(e.ParticipantEvent.ConnectionQualityChanged,(t=>{this.emitWhenConnected(e.RoomEvent.ConnectionQualityChanged,t,n)})).on(e.ParticipantEvent.ParticipantPermissionsChanged,(t=>{this.emitWhenConnected(e.RoomEvent.ParticipantPermissionsChanged,t,n)})).on(e.ParticipantEvent.TrackSubscriptionStatusChanged,((t,i)=>{this.emitWhenConnected(e.RoomEvent.TrackSubscriptionStatusChanged,t,i,n)})).on(e.ParticipantEvent.TrackSubscriptionFailed,((t,i)=>{this.emit(e.RoomEvent.TrackSubscriptionFailed,t,n,i)})).on(e.ParticipantEvent.TrackSubscriptionPermissionChanged,((t,i)=>{this.emitWhenConnected(e.RoomEvent.TrackSubscriptionPermissionChanged,t,i,n)})),i&&n.updateInfo(i),n}sendSyncState(){var e,t;if(void 0===this.engine.subscriber||null===this.engine.subscriber.pc.localDescription)return;const i=this.engine.subscriber.pc.localDescription,n=this.engine.subscriber.pc.remoteDescription,r=null===(t=null===(e=this.connOptions)||void 0===e?void 0:e.autoSubscribe)||void 0===t||t,s=new Array;this.participants.forEach((e=>{e.tracks.forEach((e=>{e.isDesired!==r&&s.push(e.trackSid)}))})),this.engine.client.sendSyncState({answer:ts({sdp:i.sdp,type:i.type}),offer:n?ts({sdp:n.sdp,type:n.type}):void 0,subscription:{trackSids:s,subscribe:!r,participantTracks:[]},publishTracks:this.localParticipant.publishedTracksInfo(),dataChannels:this.localParticipant.dataChannelsInfo()})}updateSubscriptions(){for(const e of this.participants.values())for(const t of e.videoTracks.values())t.isSubscribed&&t instanceof No&&t.emitTrackUpdate()}registerConnectionReconcile(){this.clearConnectionReconcile();let t=0;this.connectionReconcileInterval=ar.setInterval((()=>{this.engine&&!this.engine.isClosed&&this.engine.verifyTransport()?t=0:(t++,c.warn("detected connection state mismatch",{numFailures:t}),t>=3&&(this.recreateEngine(),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e.DisconnectReason.STATE_MISMATCH)))}),2e3)}clearConnectionReconcile(){this.connectionReconcileInterval&&ar.clearInterval(this.connectionReconcileInterval)}setAndEmitConnectionState(t){return t!==this.state&&(this.state=t,this.emit(e.RoomEvent.ConnectionStateChanged,this.state),!0)}emitWhenConnected(t){if(this.state===e.ConnectionState.Connected){for(var i=arguments.length,n=new Array(i>1?i-1:0),r=1;r<i;r++)n[r-1]=arguments[r];return this.emit(t,...n)}return!1}simulateParticipants(t){var i,n;return Ht(this,void 0,void 0,(function*(){const r=Object.assign({audio:!0,video:!0,useRealTracks:!1},t.publish),s=Object.assign({count:9,audio:!1,video:!0,aspectRatios:[1.66,1.7,1.3]},t.participants);if(this.handleDisconnect(),this.roomInfo={sid:"RM_SIMULATED",name:"simulated-room",emptyTimeout:0,maxParticipants:0,creationTime:(new Date).getTime(),metadata:"",numParticipants:1,numPublishers:1,turnPassword:"",enabledCodecs:[],activeRecording:!1},this.localParticipant.updateInfo(wt.fromPartial({identity:"simulated-local",name:"local-name"})),this.setupLocalParticipantEvents(),this.emit(e.RoomEvent.SignalConnected),this.emit(e.RoomEvent.Connected),this.setAndEmitConnectionState(e.ConnectionState.Connected),r.video){const t=new wo(js.Kind.Video,Nt.fromPartial({source:Qe.CAMERA,sid:Math.floor(1e4*Math.random()).toString(),type:Ge.AUDIO,name:"video-dummy"}),new vo(r.useRealTracks?(yield navigator.mediaDevices.getUserMedia({video:!0})).getVideoTracks()[0]:Wr(null!==(i=160*s.aspectRatios[0])&&void 0!==i?i:1,160,!0,!0)));this.localParticipant.addTrackPublication(t),this.localParticipant.emit(e.ParticipantEvent.LocalTrackPublished,t)}if(r.audio){const t=new wo(js.Kind.Audio,Nt.fromPartial({source:Qe.MICROPHONE,sid:Math.floor(1e4*Math.random()).toString(),type:Ge.AUDIO}),new eo(r.useRealTracks?(yield navigator.mediaDevices.getUserMedia({audio:!0})).getAudioTracks()[0]:Gr()));this.localParticipant.addTrackPublication(t),this.localParticipant.emit(e.ParticipantEvent.LocalTrackPublished,t)}for(let e=0;e<s.count-1;e+=1){let t=wt.fromPartial({sid:Math.floor(1e4*Math.random()).toString(),identity:"simulated-".concat(e),state:et.ACTIVE,tracks:[],joinedAt:Date.now()});const i=this.getOrCreateParticipant(t.identity,t);if(s.video){const r=Wr(null!==(n=160*s.aspectRatios[e%s.aspectRatios.length])&&void 0!==n?n:1,160,!1,!0),o=Nt.fromPartial({source:Qe.CAMERA,sid:Math.floor(1e4*Math.random()).toString(),type:Ge.AUDIO});i.addSubscribedMediaTrack(r,o.sid,new MediaStream([r])),t.tracks=[...t.tracks,o]}if(s.audio){const e=Gr(),n=Nt.fromPartial({source:Qe.MICROPHONE,sid:Math.floor(1e4*Math.random()).toString(),type:Ge.AUDIO});i.addSubscribedMediaTrack(e,n.sid,new MediaStream([e])),t.tracks=[...t.tracks,n]}i.updateInfo(t)}}))}emit(t){for(var i=arguments.length,n=new Array(i>1?i-1:0),r=1;r<i;r++)n[r-1]=arguments[r];return t!==e.RoomEvent.ActiveSpeakersChanged&&c.debug("room event ".concat(t),{event:t,args:n}),super.emit(t,...n)}}var Mo;!function(e){e[e.IDLE=0]="IDLE",e[e.RUNNING=1]="RUNNING",e[e.SKIPPED=2]="SKIPPED",e[e.SUCCESS=3]="SUCCESS",e[e.FAILED=4]="FAILED"}(Mo||(Mo={}));class Lo extends Yt{constructor(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};super(),this.status=Mo.IDLE,this.logs=[],this.errorsAsWarnings=!1,this.url=e,this.token=t,this.name=this.constructor.name,this.room=new Uo(i.roomOptions),this.connectOptions=i.connectOptions,i.errorsAsWarnings&&(this.errorsAsWarnings=i.errorsAsWarnings)}run(e){return Ht(this,void 0,void 0,(function*(){if(this.status!==Mo.IDLE)throw Error("check is running already");this.setStatus(Mo.RUNNING),this.appendMessage("".concat(this.name," started."));try{yield this.perform()}catch(e){e instanceof Error&&(this.errorsAsWarnings?this.appendWarning(e.message):this.appendError(e.message))}return yield this.disconnect(),yield new Promise((e=>setTimeout(e,500))),this.status!==Mo.SKIPPED&&this.setStatus(this.isSuccess()?Mo.SUCCESS:Mo.FAILED),e&&e(),this.getInfo()}))}isSuccess(){return!this.logs.some((e=>"error"===e.level))}connect(){return Ht(this,void 0,void 0,(function*(){return this.room.state===e.ConnectionState.Connected||(yield this.room.connect(this.url,this.token)),this.room}))}disconnect(){return Ht(this,void 0,void 0,(function*(){this.room&&this.room.state!==e.ConnectionState.Disconnected&&(yield this.room.disconnect(),yield new Promise((e=>setTimeout(e,500))))}))}skip(){this.setStatus(Mo.SKIPPED)}appendMessage(e){this.logs.push({level:"info",message:e}),this.emit("update",this.getInfo())}appendWarning(e){this.logs.push({level:"warning",message:e}),this.emit("update",this.getInfo())}appendError(e){this.logs.push({level:"error",message:e}),this.emit("update",this.getInfo())}setStatus(e){this.status=e,this.emit("update",this.getInfo())}get engine(){var e;return null===(e=this.room)||void 0===e?void 0:e.engine}getInfo(){return{logs:this.logs,name:this.name,status:this.status,description:this.description}}}function _o(e){var t,i;return Ht(this,void 0,void 0,(function*(){null!=e||(e={}),null!==(t=e.audio)&&void 0!==t||(e.audio=!0),null!==(i=e.video)&&void 0!==i||(e.video=!0);const n=vr(mr(e,Us,Ms)),r=navigator.mediaDevices.getUserMedia(n);e.audio&&(ns.userMediaPromiseMap.set("audioinput",r),r.catch((()=>ns.userMediaPromiseMap.delete("audioinput")))),e.video&&(ns.userMediaPromiseMap.set("videoinput",r),r.catch((()=>ns.userMediaPromiseMap.delete("videoinput"))));const s=yield r;return s.getTracks().map((t=>{const i="audio"===t.kind;let r;i?e.audio:e.video;const o=i?n.audio:n.video;"boolean"!=typeof o&&(r=o);const a=to(t,r);return a.kind===js.Kind.Video?a.source=js.Source.Camera:a.kind===js.Kind.Audio&&(a.source=js.Source.Microphone),a.mediaStream=s,a}))}))}function xo(e){return Ht(this,void 0,void 0,(function*(){return(yield _o({audio:!1,video:e}))[0]}))}function Bo(e){return Ht(this,void 0,void 0,(function*(){return(yield _o({audio:e,video:!1}))[0]}))}class Jo extends Lo{get description(){return"Can publish audio"}perform(){var e;return Ht(this,void 0,void 0,(function*(){const t=yield this.connect(),i=yield Bo();t.localParticipant.publishTrack(i),yield new Promise((e=>setTimeout(e,3e3)));const n=yield null===(e=i.sender)||void 0===e?void 0:e.getStats();if(!n)throw new Error("Could not get RTCStats");let r=0;if(n.forEach((e=>{"outbound-rtp"===e.type&&"audio"===e.mediaType&&(r=e.packetsSent)})),0===r)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(r," audio packets"))}))}}class Fo extends Lo{get description(){return"Can publish video"}perform(){var e;return Ht(this,void 0,void 0,(function*(){const t=yield this.connect(),i=yield xo();t.localParticipant.publishTrack(i),yield new Promise((e=>setTimeout(e,3e3)));const n=yield null===(e=i.sender)||void 0===e?void 0:e.getStats();if(!n)throw new Error("Could not get RTCStats");let r=0;if(n.forEach((e=>{"outbound-rtp"===e.type&&"video"===e.mediaType&&(r=e.packetsSent)})),0===r)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(r," video packets"))}))}}class $o extends Lo{get description(){return"Resuming connection after interruption"}perform(){var t;return Ht(this,void 0,void 0,(function*(){const i=yield this.connect();let n,r=!1,s=!1;const o=new Promise((e=>{setTimeout(e,5e3),n=e}));i.on(e.RoomEvent.Reconnecting,(()=>{r=!0})).on(e.RoomEvent.Reconnected,(()=>{s=!0,n(!0)})),null===(t=i.engine.client.ws)||void 0===t||t.close();const a=i.engine.client.onClose;if(a&&a(""),yield o,!r)throw new Error("Did not attempt to reconnect");if(!s||i.state!==e.ConnectionState.Connected)throw this.appendWarning("reconnection is only possible in Redis-based configurations"),new Error("Not able to reconnect")}))}}class jo extends Lo{get description(){return"Can connect via TURN"}perform(){var e,t;return Ht(this,void 0,void 0,(function*(){const i=new Xr,n=yield i.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0});let r=!1,s=!1,o=!1;for(let e of n.iceServers)for(let t of e.urls)t.startsWith("turn:")?(s=!0,o=!0):t.startsWith("turns:")&&(s=!0,o=!0,r=!0),t.startsWith("stun:")&&(o=!0);o?s&&!r&&this.appendWarning("TURN is configured server side, but TURN/TLS is unavailable."):this.appendWarning("No STUN servers configured on server side."),yield i.close(),(null===(t=null===(e=this.connectOptions)||void 0===e?void 0:e.rtcConfig)||void 0===t?void 0:t.iceServers)||s?yield this.room.connect(this.url,this.token,{rtcConfig:{iceTransportPolicy:"relay"}}):(this.appendWarning("No TURN servers configured."),this.skip(),yield new Promise((e=>setTimeout(e,0))))}))}}class Vo extends Lo{get description(){return"Establishing WebRTC connection"}perform(){return Ht(this,void 0,void 0,(function*(){try{console.log("initiating room connection"),this.room=yield this.connect(),console.log("now the room is connected")}catch(e){throw this.appendWarning("ports need to be open on firewall in order to connect."),e}}))}}class qo extends Lo{get description(){return"Connecting to signal connection via WebSocket"}perform(){return Ht(this,void 0,void 0,(function*(){(this.url.startsWith("ws:")||this.url.startsWith("http:"))&&this.appendWarning("Server is insecure, clients may block connections to it");let e=new Xr;const t=yield e.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0});this.appendMessage("Connected to server, version ".concat(t.serverVersion,".")),yield e.close()}))}}const Wo=new Map([["obs virtual camera",{facingMode:"environment",confidence:"medium"}]]),Go=new Map([["iphone",{facingMode:"environment",confidence:"medium"}],["ipad",{facingMode:"environment",confidence:"medium"}]]);function Qo(e){var t;const i=e.trim().toLowerCase();if(""!==i)return Wo.has(i)?Wo.get(i):null===(t=Array.from(Go.entries()).find((e=>{let[t]=e;return i.includes(t)})))||void 0===t?void 0:t[1]}e.ConnectionCheck=class extends Yt{constructor(e,t){super(),this.checkResults=new Map,this.url=e,this.token=t}getNextCheckId(){const e=this.checkResults.size;return this.checkResults.set(e,{logs:[],status:Mo.IDLE,name:"",description:""}),e}updateCheck(e,t){this.checkResults.set(e,t),this.emit("checkUpdate",e,t)}isSuccess(){return Array.from(this.checkResults.values()).every((e=>e.status!==Mo.FAILED))}getResults(){return Array.from(this.checkResults.values())}createAndRunCheck(e){return Ht(this,void 0,void 0,(function*(){const t=this.getNextCheckId(),i=new e(this.url,this.token),n=e=>{this.updateCheck(t,e)};i.on("update",n);const r=yield i.run();return i.off("update",n),r}))}checkWebsocket(){return Ht(this,void 0,void 0,(function*(){return this.createAndRunCheck(qo)}))}checkWebRTC(){return Ht(this,void 0,void 0,(function*(){return this.createAndRunCheck(Vo)}))}checkTURN(){return Ht(this,void 0,void 0,(function*(){return this.createAndRunCheck(jo)}))}checkReconnect(){return Ht(this,void 0,void 0,(function*(){return this.createAndRunCheck($o)}))}checkPublishAudio(){return Ht(this,void 0,void 0,(function*(){return this.createAndRunCheck(Jo)}))}checkPublishVideo(){return Ht(this,void 0,void 0,(function*(){return this.createAndRunCheck(Fo)}))}},e.ConnectionError=tr,e.CriticalTimers=ar,e.DefaultReconnectPolicy=Qt,e.DeviceUnsupportedError=ir,e.LivekitError=er,e.LocalAudioTrack=eo,e.LocalParticipant=Do,e.LocalTrack=Xs,e.LocalTrackPublication=wo,e.LocalVideoTrack=vo,e.NegotiationError=or,e.Participant=Ro,e.PublishDataError=class extends er{constructor(e){super(13,null!=e?e:"unable to publish data")}},e.RemoteAudioTrack=yo,e.RemoteParticipant=Oo,e.RemoteTrack=So,e.RemoteTrackPublication=No,e.RemoteVideoTrack=Co,e.Room=Uo,e.RoomState=Ao,e.ScreenSharePresets=Is,e.Track=js,e.TrackInvalidError=nr,e.TrackPublication=Po,e.UnexpectedConnectionState=sr,e.UnsupportedServer=rr,e.VideoPreset=Es,e.VideoPresets=Os,e.VideoPresets43=Ds,e.attachToElement=Vs,e.createAudioAnalyser=function(e,t){const i=Object.assign({cloneTrack:!1,fftSize:2048,smoothingTimeConstant:.8,minDecibels:-100,maxDecibels:-80},t),n=gr();if(!n)throw new Error("Audio Context not supported on this browser");const r=i.cloneTrack?e.mediaStreamTrack.clone():e.mediaStreamTrack,s=n.createMediaStreamSource(new MediaStream([r])),o=n.createAnalyser();o.minDecibels=i.minDecibels,o.maxDecibels=i.maxDecibels,o.fftSize=i.fftSize,o.smoothingTimeConstant=i.smoothingTimeConstant,s.connect(o);const a=new Uint8Array(o.frequencyBinCount);return{calculateVolume:()=>{o.getByteFrequencyData(a);let e=0;for(const t of a)e+=Math.pow(t/255,2);return Math.sqrt(e/a.length)},analyser:o,cleanup:()=>{n.close(),i.cloneTrack&&r.stop()}}},e.createLocalAudioTrack=Bo,e.createLocalScreenTracks=function(e){var t;return Ht(this,void 0,void 0,(function*(){void 0===e&&(e={}),void 0===e.resolution&&(e.resolution=Os.h1080.resolution);let i=!0;if(e.resolution&&(i={width:e.resolution.width,height:e.resolution.height}),void 0===navigator.mediaDevices.getDisplayMedia)throw new ir("getDisplayMedia not supported");const n=yield navigator.mediaDevices.getDisplayMedia({audio:null!==(t=e.audio)&&void 0!==t&&t,video:i}),r=n.getVideoTracks();if(0===r.length)throw new nr("no video track found");const s=new vo(r[0],void 0,!1);s.source=js.Source.ScreenShare;const o=[s];if(n.getAudioTracks().length>0){const e=new eo(n.getAudioTracks()[0],void 0,!1);e.source=js.Source.ScreenShareAudio,o.push(e)}return o}))},e.createLocalTracks=_o,e.createLocalVideoTrack=xo,e.detachTrack=qs,e.facingModeFromDeviceLabel=Qo,e.facingModeFromLocalTrack=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};var i;const n=e instanceof Xs?e.mediaStreamTrack:e,r=n.getSettings();let s={facingMode:null!==(i=t.defaultFacingMode)&&void 0!==i?i:"user",confidence:"low"};if("facingMode"in r){const e=r.facingMode;a.debug("rawFacingMode",{rawFacingMode:e}),e&&"string"==typeof e&&function(e){const t=["user","environment","left","right"];return void 0===e||t.includes(e)}(e)&&(s={facingMode:e,confidence:"high"})}if(["low","medium"].includes(s.confidence)){a.debug("Try to get facing mode from device label: (".concat(n.label,")"));const e=Qo(n.label);void 0!==e&&(s=e)}return s},e.getEmptyAudioStreamTrack=Gr,e.getEmptyVideoStreamTrack=function(){return Vr||(Vr=Wr()),Vr.clone()},e.isBackupCodec=ws,e.isBrowserSupported=function(){return Sr()||yr()},e.isCodecEqual=Rs,e.protocolVersion=9,e.setLogExtension=function(t){const i=c.methodFactory;c.methodFactory=(n,r,s)=>{const o=i(n,r,s),a=e.LogLevel[n],c=a>=r&&a<e.LogLevel.silent;return(e,i)=>{i?o(e,i):o(e),c&&t(a,e,i)}},c.setLevel(c.getLevel())},e.setLogLevel=function(e){c.setLevel(e)},e.supportsAV1=Cr,e.supportsAdaptiveStream=function(){return void 0!==typeof ResizeObserver&&void 0!==typeof IntersectionObserver},e.supportsDynacast=function(){return Sr()},e.supportsVP9=Tr,e.version=pr}));
|
1
|
+
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).LivekitClient={})}(this,(function(e){"use strict";function t(e,t){return t.forEach((function(t){t&&"string"!=typeof t&&!Array.isArray(t)&&Object.keys(t).forEach((function(i){if("default"!==i&&!(i in e)){var n=Object.getOwnPropertyDescriptor(t,i);Object.defineProperty(e,i,n.get?n:{enumerable:!0,get:function(){return t[i]}})}}))})),Object.freeze(e)}var i="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function n(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var r={exports:{}};!function(e){var t,n;t=i,n=function(){var e=function(){},t="undefined",i=typeof window!==t&&typeof window.navigator!==t&&/Trident\/|MSIE /.test(window.navigator.userAgent),n=["trace","debug","info","warn","error"];function r(e,t){var i=e[t];if("function"==typeof i.bind)return i.bind(e);try{return Function.prototype.bind.call(i,e)}catch(t){return function(){return Function.prototype.apply.apply(i,[e,arguments])}}}function s(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function o(t,i){for(var r=0;r<n.length;r++){var s=n[r];this[s]=r<t?e:this.methodFactory(s,t,i)}this.log=this.debug}function a(e,i,n){return function(){typeof console!==t&&(o.call(this,i,n),this[e].apply(this,arguments))}}function c(n,o,c){return function(n){return"debug"===n&&(n="log"),typeof console!==t&&("trace"===n&&i?s:void 0!==console[n]?r(console,n):void 0!==console.log?r(console,"log"):e)}(n)||a.apply(this,arguments)}function d(e,i,r){var s,a=this;i=null==i?"WARN":i;var d="loglevel";function u(){var e;if(typeof window!==t&&d){try{e=window.localStorage[d]}catch(e){}if(typeof e===t)try{var i=window.document.cookie,n=i.indexOf(encodeURIComponent(d)+"=");-1!==n&&(e=/^([^;]+)/.exec(i.slice(n))[1])}catch(e){}return void 0===a.levels[e]&&(e=void 0),e}}"string"==typeof e?d+=":"+e:"symbol"==typeof e&&(d=void 0),a.name=e,a.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},a.methodFactory=r||c,a.getLevel=function(){return s},a.setLevel=function(i,r){if("string"==typeof i&&void 0!==a.levels[i.toUpperCase()]&&(i=a.levels[i.toUpperCase()]),!("number"==typeof i&&i>=0&&i<=a.levels.SILENT))throw"log.setLevel() called with invalid level: "+i;if(s=i,!1!==r&&function(e){var i=(n[e]||"silent").toUpperCase();if(typeof window!==t&&d){try{return void(window.localStorage[d]=i)}catch(e){}try{window.document.cookie=encodeURIComponent(d)+"="+i+";"}catch(e){}}}(i),o.call(a,i,e),typeof console===t&&i<a.levels.SILENT)return"No console available for logging"},a.setDefaultLevel=function(e){i=e,u()||a.setLevel(e,!1)},a.resetLevel=function(){a.setLevel(i,!1),function(){if(typeof window!==t&&d){try{return void window.localStorage.removeItem(d)}catch(e){}try{window.document.cookie=encodeURIComponent(d)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch(e){}}}()},a.enableAll=function(e){a.setLevel(a.levels.TRACE,e)},a.disableAll=function(e){a.setLevel(a.levels.SILENT,e)};var l=u();null==l&&(l=i),a.setLevel(l,!1)}var u=new d,l={};u.getLogger=function(e){if("symbol"!=typeof e&&"string"!=typeof e||""===e)throw new TypeError("You must supply a name when creating a logger.");var t=l[e];return t||(t=l[e]=new d(e,u.getLevel(),u.methodFactory)),t};var h=typeof window!==t?window.log:void 0;return u.noConflict=function(){return typeof window!==t&&window.log===u&&(window.log=h),u},u.getLoggers=function(){return l},u.default=u,u},e.exports?e.exports=n():t.log=n()}(r);var s,o=r.exports,a=n(o);e.LogLevel=void 0,(s=e.LogLevel||(e.LogLevel={}))[s.trace=0]="trace",s[s.debug=1]="debug",s[s.info=2]="info",s[s.warn=3]="warn",s[s.error=4]="error",s[s.silent=5]="silent";const c=o.getLogger("livekit");c.setDefaultLevel(e.LogLevel.info),o.getLogger("lk-e2ee");var d=l,u=null;try{u=new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0,97,115,109,1,0,0,0,1,13,2,96,0,1,127,96,4,127,127,127,127,1,127,3,7,6,0,1,1,1,1,1,6,6,1,127,1,65,0,11,7,50,6,3,109,117,108,0,1,5,100,105,118,95,115,0,2,5,100,105,118,95,117,0,3,5,114,101,109,95,115,0,4,5,114,101,109,95,117,0,5,8,103,101,116,95,104,105,103,104,0,0,10,191,1,6,4,0,35,0,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,126,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,127,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,128,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,129,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,130,34,4,66,32,135,167,36,0,32,4,167,11])),{}).exports}catch(e){}function l(e,t,i){this.low=0|e,this.high=0|t,this.unsigned=!!i}function h(e){return!0===(e&&e.__isLong__)}l.prototype.__isLong__,Object.defineProperty(l.prototype,"__isLong__",{value:!0}),l.isLong=h;var p={},m={};function f(e,t){var i,n,r;return t?(r=0<=(e>>>=0)&&e<256)&&(n=m[e])?n:(i=g(e,(0|e)<0?-1:0,!0),r&&(m[e]=i),i):(r=-128<=(e|=0)&&e<128)&&(n=p[e])?n:(i=g(e,e<0?-1:0,!1),r&&(p[e]=i),i)}function v(e,t){if(isNaN(e))return t?w:P;if(t){if(e<0)return w;if(e>=C)return D}else{if(e<=-E)return A;if(e+1>=E)return I}return e<0?v(-e,t).neg():g(e%S|0,e/S|0,t)}function g(e,t,i){return new l(e,t,i)}l.fromInt=f,l.fromNumber=v,l.fromBits=g;var b=Math.pow;function k(e,t,i){if(0===e.length)throw Error("empty string");if("NaN"===e||"Infinity"===e||"+Infinity"===e||"-Infinity"===e)return P;if("number"==typeof t?(i=t,t=!1):t=!!t,(i=i||10)<2||36<i)throw RangeError("radix");var n;if((n=e.indexOf("-"))>0)throw Error("interior hyphen");if(0===n)return k(e.substring(1),t,i).neg();for(var r=v(b(i,8)),s=P,o=0;o<e.length;o+=8){var a=Math.min(8,e.length-o),c=parseInt(e.substring(o,o+a),i);if(a<8){var d=v(b(i,a));s=s.mul(d).add(v(c))}else s=(s=s.mul(r)).add(v(c))}return s.unsigned=t,s}function y(e,t){return"number"==typeof e?v(e,t):"string"==typeof e?k(e,t):g(e.low,e.high,"boolean"==typeof t?t:e.unsigned)}l.fromString=k,l.fromValue=y;var S=4294967296,C=S*S,E=C/2,T=f(1<<24),P=f(0);l.ZERO=P;var w=f(0,!0);l.UZERO=w;var R=f(1);l.ONE=R;var N=f(1,!0);l.UONE=N;var O=f(-1);l.NEG_ONE=O;var I=g(-1,2147483647,!1);l.MAX_VALUE=I;var D=g(-1,-1,!0);l.MAX_UNSIGNED_VALUE=D;var A=g(0,-2147483648,!1);l.MIN_VALUE=A;var U=l.prototype;U.toInt=function(){return this.unsigned?this.low>>>0:this.low},U.toNumber=function(){return this.unsigned?(this.high>>>0)*S+(this.low>>>0):this.high*S+(this.low>>>0)},U.toString=function(e){if((e=e||10)<2||36<e)throw RangeError("radix");if(this.isZero())return"0";if(this.isNegative()){if(this.eq(A)){var t=v(e),i=this.div(t),n=i.mul(t).sub(this);return i.toString(e)+n.toInt().toString(e)}return"-"+this.neg().toString(e)}for(var r=v(b(e,6),this.unsigned),s=this,o="";;){var a=s.div(r),c=(s.sub(a.mul(r)).toInt()>>>0).toString(e);if((s=a).isZero())return c+o;for(;c.length<6;)c="0"+c;o=""+c+o}},U.getHighBits=function(){return this.high},U.getHighBitsUnsigned=function(){return this.high>>>0},U.getLowBits=function(){return this.low},U.getLowBitsUnsigned=function(){return this.low>>>0},U.getNumBitsAbs=function(){if(this.isNegative())return this.eq(A)?64:this.neg().getNumBitsAbs();for(var e=0!=this.high?this.high:this.low,t=31;t>0&&0==(e&1<<t);t--);return 0!=this.high?t+33:t+1},U.isZero=function(){return 0===this.high&&0===this.low},U.eqz=U.isZero,U.isNegative=function(){return!this.unsigned&&this.high<0},U.isPositive=function(){return this.unsigned||this.high>=0},U.isOdd=function(){return 1==(1&this.low)},U.isEven=function(){return 0==(1&this.low)},U.equals=function(e){return h(e)||(e=y(e)),(this.unsigned===e.unsigned||this.high>>>31!=1||e.high>>>31!=1)&&(this.high===e.high&&this.low===e.low)},U.eq=U.equals,U.notEquals=function(e){return!this.eq(e)},U.neq=U.notEquals,U.ne=U.notEquals,U.lessThan=function(e){return this.comp(e)<0},U.lt=U.lessThan,U.lessThanOrEqual=function(e){return this.comp(e)<=0},U.lte=U.lessThanOrEqual,U.le=U.lessThanOrEqual,U.greaterThan=function(e){return this.comp(e)>0},U.gt=U.greaterThan,U.greaterThanOrEqual=function(e){return this.comp(e)>=0},U.gte=U.greaterThanOrEqual,U.ge=U.greaterThanOrEqual,U.compare=function(e){if(h(e)||(e=y(e)),this.eq(e))return 0;var t=this.isNegative(),i=e.isNegative();return t&&!i?-1:!t&&i?1:this.unsigned?e.high>>>0>this.high>>>0||e.high===this.high&&e.low>>>0>this.low>>>0?-1:1:this.sub(e).isNegative()?-1:1},U.comp=U.compare,U.negate=function(){return!this.unsigned&&this.eq(A)?A:this.not().add(R)},U.neg=U.negate,U.add=function(e){h(e)||(e=y(e));var t=this.high>>>16,i=65535&this.high,n=this.low>>>16,r=65535&this.low,s=e.high>>>16,o=65535&e.high,a=e.low>>>16,c=0,d=0,u=0,l=0;return u+=(l+=r+(65535&e.low))>>>16,d+=(u+=n+a)>>>16,c+=(d+=i+o)>>>16,c+=t+s,g((u&=65535)<<16|(l&=65535),(c&=65535)<<16|(d&=65535),this.unsigned)},U.subtract=function(e){return h(e)||(e=y(e)),this.add(e.neg())},U.sub=U.subtract,U.multiply=function(e){if(this.isZero())return P;if(h(e)||(e=y(e)),u)return g(u.mul(this.low,this.high,e.low,e.high),u.get_high(),this.unsigned);if(e.isZero())return P;if(this.eq(A))return e.isOdd()?A:P;if(e.eq(A))return this.isOdd()?A:P;if(this.isNegative())return e.isNegative()?this.neg().mul(e.neg()):this.neg().mul(e).neg();if(e.isNegative())return this.mul(e.neg()).neg();if(this.lt(T)&&e.lt(T))return v(this.toNumber()*e.toNumber(),this.unsigned);var t=this.high>>>16,i=65535&this.high,n=this.low>>>16,r=65535&this.low,s=e.high>>>16,o=65535&e.high,a=e.low>>>16,c=65535&e.low,d=0,l=0,p=0,m=0;return p+=(m+=r*c)>>>16,l+=(p+=n*c)>>>16,p&=65535,l+=(p+=r*a)>>>16,d+=(l+=i*c)>>>16,l&=65535,d+=(l+=n*a)>>>16,l&=65535,d+=(l+=r*o)>>>16,d+=t*c+i*a+n*o+r*s,g((p&=65535)<<16|(m&=65535),(d&=65535)<<16|(l&=65535),this.unsigned)},U.mul=U.multiply,U.divide=function(e){if(h(e)||(e=y(e)),e.isZero())throw Error("division by zero");var t,i,n;if(u)return this.unsigned||-2147483648!==this.high||-1!==e.low||-1!==e.high?g((this.unsigned?u.div_u:u.div_s)(this.low,this.high,e.low,e.high),u.get_high(),this.unsigned):this;if(this.isZero())return this.unsigned?w:P;if(this.unsigned){if(e.unsigned||(e=e.toUnsigned()),e.gt(this))return w;if(e.gt(this.shru(1)))return N;n=w}else{if(this.eq(A))return e.eq(R)||e.eq(O)?A:e.eq(A)?R:(t=this.shr(1).div(e).shl(1)).eq(P)?e.isNegative()?R:O:(i=this.sub(e.mul(t)),n=t.add(i.div(e)));if(e.eq(A))return this.unsigned?w:P;if(this.isNegative())return e.isNegative()?this.neg().div(e.neg()):this.neg().div(e).neg();if(e.isNegative())return this.div(e.neg()).neg();n=P}for(i=this;i.gte(e);){t=Math.max(1,Math.floor(i.toNumber()/e.toNumber()));for(var r=Math.ceil(Math.log(t)/Math.LN2),s=r<=48?1:b(2,r-48),o=v(t),a=o.mul(e);a.isNegative()||a.gt(i);)a=(o=v(t-=s,this.unsigned)).mul(e);o.isZero()&&(o=R),n=n.add(o),i=i.sub(a)}return n},U.div=U.divide,U.modulo=function(e){return h(e)||(e=y(e)),u?g((this.unsigned?u.rem_u:u.rem_s)(this.low,this.high,e.low,e.high),u.get_high(),this.unsigned):this.sub(this.div(e).mul(e))},U.mod=U.modulo,U.rem=U.modulo,U.not=function(){return g(~this.low,~this.high,this.unsigned)},U.and=function(e){return h(e)||(e=y(e)),g(this.low&e.low,this.high&e.high,this.unsigned)},U.or=function(e){return h(e)||(e=y(e)),g(this.low|e.low,this.high|e.high,this.unsigned)},U.xor=function(e){return h(e)||(e=y(e)),g(this.low^e.low,this.high^e.high,this.unsigned)},U.shiftLeft=function(e){return h(e)&&(e=e.toInt()),0==(e&=63)?this:e<32?g(this.low<<e,this.high<<e|this.low>>>32-e,this.unsigned):g(0,this.low<<e-32,this.unsigned)},U.shl=U.shiftLeft,U.shiftRight=function(e){return h(e)&&(e=e.toInt()),0==(e&=63)?this:e<32?g(this.low>>>e|this.high<<32-e,this.high>>e,this.unsigned):g(this.high>>e-32,this.high>=0?0:-1,this.unsigned)},U.shr=U.shiftRight,U.shiftRightUnsigned=function(e){if(h(e)&&(e=e.toInt()),0===(e&=63))return this;var t=this.high;return e<32?g(this.low>>>e|t<<32-e,t>>>e,this.unsigned):g(32===e?t:t>>>e-32,0,this.unsigned)},U.shru=U.shiftRightUnsigned,U.shr_u=U.shiftRightUnsigned,U.toSigned=function(){return this.unsigned?g(this.low,this.high,!1):this},U.toUnsigned=function(){return this.unsigned?this:g(this.low,this.high,!0)},U.toBytes=function(e){return e?this.toBytesLE():this.toBytesBE()},U.toBytesLE=function(){var e=this.high,t=this.low;return[255&t,t>>>8&255,t>>>16&255,t>>>24,255&e,e>>>8&255,e>>>16&255,e>>>24]},U.toBytesBE=function(){var e=this.high,t=this.low;return[e>>>24,e>>>16&255,e>>>8&255,255&e,t>>>24,t>>>16&255,t>>>8&255,255&t]},l.fromBytes=function(e,t,i){return i?l.fromBytesLE(e,t):l.fromBytesBE(e,t)},l.fromBytesLE=function(e,t){return new l(e[0]|e[1]<<8|e[2]<<16|e[3]<<24,e[4]|e[5]<<8|e[6]<<16|e[7]<<24,t)},l.fromBytesBE=function(e,t){return new l(e[4]<<24|e[5]<<16|e[6]<<8|e[7],e[0]<<24|e[1]<<16|e[2]<<8|e[3],t)};var M,L,_=n(d),x={},B={};var J,F,$,V,j,q,W,G={};var K,Q,H,Z,z,Y,X={};function ee(){return Y||(Y=1,function(e){var t=e;function n(e,t,i){for(var n=Object.keys(t),r=0;r<n.length;++r)void 0!==e[n[r]]&&i||(e[n[r]]=t[n[r]]);return e}function r(e){function t(e,i){if(!(this instanceof t))return new t(e,i);Object.defineProperty(this,"message",{get:function(){return e}}),Error.captureStackTrace?Error.captureStackTrace(this,t):Object.defineProperty(this,"stack",{value:(new Error).stack||""}),i&&n(this,i)}return t.prototype=Object.create(Error.prototype,{constructor:{value:t,writable:!0,enumerable:!1,configurable:!0},name:{get:function(){return e},set:void 0,enumerable:!1,configurable:!0},toString:{value:function(){return this.name+": "+this.message},writable:!0,enumerable:!1,configurable:!0}}),t}t.asPromise=(L||(L=1,M=function(e,t){for(var i=new Array(arguments.length-1),n=0,r=2,s=!0;r<arguments.length;)i[n++]=arguments[r++];return new Promise((function(r,o){i[n]=function(e){if(s)if(s=!1,e)o(e);else{for(var t=new Array(arguments.length-1),i=0;i<t.length;)t[i++]=arguments[i];r.apply(null,t)}};try{e.apply(t||null,i)}catch(e){s&&(s=!1,o(e))}}))}),M),t.base64=(J||(J=1,function(e){var t=e;t.length=function(e){var t=e.length;if(!t)return 0;for(var i=0;--t%4>1&&"="===e.charAt(t);)++i;return Math.ceil(3*e.length)/4-i};for(var i=new Array(64),n=new Array(123),r=0;r<64;)n[i[r]=r<26?r+65:r<52?r+71:r<62?r-4:r-59|43]=r++;t.encode=function(e,t,n){for(var r,s=null,o=[],a=0,c=0;t<n;){var d=e[t++];switch(c){case 0:o[a++]=i[d>>2],r=(3&d)<<4,c=1;break;case 1:o[a++]=i[r|d>>4],r=(15&d)<<2,c=2;break;case 2:o[a++]=i[r|d>>6],o[a++]=i[63&d],c=0}a>8191&&((s||(s=[])).push(String.fromCharCode.apply(String,o)),a=0)}return c&&(o[a++]=i[r],o[a++]=61,1===c&&(o[a++]=61)),s?(a&&s.push(String.fromCharCode.apply(String,o.slice(0,a))),s.join("")):String.fromCharCode.apply(String,o.slice(0,a))};var s="invalid encoding";t.decode=function(e,t,i){for(var r,o=i,a=0,c=0;c<e.length;){var d=e.charCodeAt(c++);if(61===d&&a>1)break;if(void 0===(d=n[d]))throw Error(s);switch(a){case 0:r=d,a=1;break;case 1:t[i++]=r<<2|(48&d)>>4,r=d,a=2;break;case 2:t[i++]=(15&r)<<4|(60&d)>>2,r=d,a=3;break;case 3:t[i++]=(3&r)<<6|d,a=0}}if(1===a)throw Error(s);return i-o},t.test=function(e){return/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(e)}}(G)),G),t.EventEmitter=function(){if($)return F;function e(){this._listeners={}}return $=1,F=e,e.prototype.on=function(e,t,i){return(this._listeners[e]||(this._listeners[e]=[])).push({fn:t,ctx:i||this}),this},e.prototype.off=function(e,t){if(void 0===e)this._listeners={};else if(void 0===t)this._listeners[e]=[];else for(var i=this._listeners[e],n=0;n<i.length;)i[n].fn===t?i.splice(n,1):++n;return this},e.prototype.emit=function(e){var t=this._listeners[e];if(t){for(var i=[],n=1;n<arguments.length;)i.push(arguments[n++]);for(n=0;n<t.length;)t[n].fn.apply(t[n++].ctx,i)}return this},F}(),t.float=function(){if(j)return V;function e(e){return"undefined"!=typeof Float32Array?function(){var t=new Float32Array([-0]),i=new Uint8Array(t.buffer),n=128===i[3];function r(e,n,r){t[0]=e,n[r]=i[0],n[r+1]=i[1],n[r+2]=i[2],n[r+3]=i[3]}function s(e,n,r){t[0]=e,n[r]=i[3],n[r+1]=i[2],n[r+2]=i[1],n[r+3]=i[0]}function o(e,n){return i[0]=e[n],i[1]=e[n+1],i[2]=e[n+2],i[3]=e[n+3],t[0]}function a(e,n){return i[3]=e[n],i[2]=e[n+1],i[1]=e[n+2],i[0]=e[n+3],t[0]}e.writeFloatLE=n?r:s,e.writeFloatBE=n?s:r,e.readFloatLE=n?o:a,e.readFloatBE=n?a:o}():function(){function s(e,t,i,n){var r=t<0?1:0;if(r&&(t=-t),0===t)e(1/t>0?0:2147483648,i,n);else if(isNaN(t))e(2143289344,i,n);else if(t>34028234663852886e22)e((r<<31|2139095040)>>>0,i,n);else if(t<11754943508222875e-54)e((r<<31|Math.round(t/1401298464324817e-60))>>>0,i,n);else{var s=Math.floor(Math.log(t)/Math.LN2);e((r<<31|s+127<<23|8388607&Math.round(t*Math.pow(2,-s)*8388608))>>>0,i,n)}}function o(e,t,i){var n=e(t,i),r=2*(n>>31)+1,s=n>>>23&255,o=8388607&n;return 255===s?o?NaN:r*(1/0):0===s?1401298464324817e-60*r*o:r*Math.pow(2,s-150)*(o+8388608)}e.writeFloatLE=s.bind(null,t),e.writeFloatBE=s.bind(null,i),e.readFloatLE=o.bind(null,n),e.readFloatBE=o.bind(null,r)}(),"undefined"!=typeof Float64Array?function(){var t=new Float64Array([-0]),i=new Uint8Array(t.buffer),n=128===i[7];function r(e,n,r){t[0]=e,n[r]=i[0],n[r+1]=i[1],n[r+2]=i[2],n[r+3]=i[3],n[r+4]=i[4],n[r+5]=i[5],n[r+6]=i[6],n[r+7]=i[7]}function s(e,n,r){t[0]=e,n[r]=i[7],n[r+1]=i[6],n[r+2]=i[5],n[r+3]=i[4],n[r+4]=i[3],n[r+5]=i[2],n[r+6]=i[1],n[r+7]=i[0]}function o(e,n){return i[0]=e[n],i[1]=e[n+1],i[2]=e[n+2],i[3]=e[n+3],i[4]=e[n+4],i[5]=e[n+5],i[6]=e[n+6],i[7]=e[n+7],t[0]}function a(e,n){return i[7]=e[n],i[6]=e[n+1],i[5]=e[n+2],i[4]=e[n+3],i[3]=e[n+4],i[2]=e[n+5],i[1]=e[n+6],i[0]=e[n+7],t[0]}e.writeDoubleLE=n?r:s,e.writeDoubleBE=n?s:r,e.readDoubleLE=n?o:a,e.readDoubleBE=n?a:o}():function(){function s(e,t,i,n,r,s){var o=n<0?1:0;if(o&&(n=-n),0===n)e(0,r,s+t),e(1/n>0?0:2147483648,r,s+i);else if(isNaN(n))e(0,r,s+t),e(2146959360,r,s+i);else if(n>17976931348623157e292)e(0,r,s+t),e((o<<31|2146435072)>>>0,r,s+i);else{var a;if(n<22250738585072014e-324)e((a=n/5e-324)>>>0,r,s+t),e((o<<31|a/4294967296)>>>0,r,s+i);else{var c=Math.floor(Math.log(n)/Math.LN2);1024===c&&(c=1023),e(4503599627370496*(a=n*Math.pow(2,-c))>>>0,r,s+t),e((o<<31|c+1023<<20|1048576*a&1048575)>>>0,r,s+i)}}}function o(e,t,i,n,r){var s=e(n,r+t),o=e(n,r+i),a=2*(o>>31)+1,c=o>>>20&2047,d=4294967296*(1048575&o)+s;return 2047===c?d?NaN:a*(1/0):0===c?5e-324*a*d:a*Math.pow(2,c-1075)*(d+4503599627370496)}e.writeDoubleLE=s.bind(null,t,0,4),e.writeDoubleBE=s.bind(null,i,4,0),e.readDoubleLE=o.bind(null,n,0,4),e.readDoubleBE=o.bind(null,r,4,0)}(),e}function t(e,t,i){t[i]=255&e,t[i+1]=e>>>8&255,t[i+2]=e>>>16&255,t[i+3]=e>>>24}function i(e,t,i){t[i]=e>>>24,t[i+1]=e>>>16&255,t[i+2]=e>>>8&255,t[i+3]=255&e}function n(e,t){return(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0}function r(e,t){return(e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3])>>>0}return j=1,V=e(e)}(),t.inquire=W?q:(W=1,q=function(e){return null}),t.utf8=(K||(K=1,function(e){var t=e;t.length=function(e){for(var t=0,i=0,n=0;n<e.length;++n)(i=e.charCodeAt(n))<128?t+=1:i<2048?t+=2:55296==(64512&i)&&56320==(64512&e.charCodeAt(n+1))?(++n,t+=4):t+=3;return t},t.read=function(e,t,i){if(i-t<1)return"";for(var n,r=null,s=[],o=0;t<i;)(n=e[t++])<128?s[o++]=n:n>191&&n<224?s[o++]=(31&n)<<6|63&e[t++]:n>239&&n<365?(n=((7&n)<<18|(63&e[t++])<<12|(63&e[t++])<<6|63&e[t++])-65536,s[o++]=55296+(n>>10),s[o++]=56320+(1023&n)):s[o++]=(15&n)<<12|(63&e[t++])<<6|63&e[t++],o>8191&&((r||(r=[])).push(String.fromCharCode.apply(String,s)),o=0);return r?(o&&r.push(String.fromCharCode.apply(String,s.slice(0,o))),r.join("")):String.fromCharCode.apply(String,s.slice(0,o))},t.write=function(e,t,i){for(var n,r,s=i,o=0;o<e.length;++o)(n=e.charCodeAt(o))<128?t[i++]=n:n<2048?(t[i++]=n>>6|192,t[i++]=63&n|128):55296==(64512&n)&&56320==(64512&(r=e.charCodeAt(o+1)))?(n=65536+((1023&n)<<10)+(1023&r),++o,t[i++]=n>>18|240,t[i++]=n>>12&63|128,t[i++]=n>>6&63|128,t[i++]=63&n|128):(t[i++]=n>>12|224,t[i++]=n>>6&63|128,t[i++]=63&n|128);return i-s}}(X)),X),t.pool=H?Q:(H=1,Q=function(e,t,i){var n=i||8192,r=n>>>1,s=null,o=n;return function(i){if(i<1||i>r)return e(i);o+i>n&&(s=e(n),o=0);var a=t.call(s,o,o+=i);return 7&o&&(o=1+(7|o)),a}}),t.LongBits=function(){if(z)return Z;z=1,Z=t;var e=ee();function t(e,t){this.lo=e>>>0,this.hi=t>>>0}var i=t.zero=new t(0,0);i.toNumber=function(){return 0},i.zzEncode=i.zzDecode=function(){return this},i.length=function(){return 1};var n=t.zeroHash="\0\0\0\0\0\0\0\0";t.fromNumber=function(e){if(0===e)return i;var n=e<0;n&&(e=-e);var r=e>>>0,s=(e-r)/4294967296>>>0;return n&&(s=~s>>>0,r=~r>>>0,++r>4294967295&&(r=0,++s>4294967295&&(s=0))),new t(r,s)},t.from=function(n){if("number"==typeof n)return t.fromNumber(n);if(e.isString(n)){if(!e.Long)return t.fromNumber(parseInt(n,10));n=e.Long.fromString(n)}return n.low||n.high?new t(n.low>>>0,n.high>>>0):i},t.prototype.toNumber=function(e){if(!e&&this.hi>>>31){var t=1+~this.lo>>>0,i=~this.hi>>>0;return t||(i=i+1>>>0),-(t+4294967296*i)}return this.lo+4294967296*this.hi},t.prototype.toLong=function(t){return e.Long?new e.Long(0|this.lo,0|this.hi,Boolean(t)):{low:0|this.lo,high:0|this.hi,unsigned:Boolean(t)}};var r=String.prototype.charCodeAt;return t.fromHash=function(e){return e===n?i:new t((r.call(e,0)|r.call(e,1)<<8|r.call(e,2)<<16|r.call(e,3)<<24)>>>0,(r.call(e,4)|r.call(e,5)<<8|r.call(e,6)<<16|r.call(e,7)<<24)>>>0)},t.prototype.toHash=function(){return String.fromCharCode(255&this.lo,this.lo>>>8&255,this.lo>>>16&255,this.lo>>>24,255&this.hi,this.hi>>>8&255,this.hi>>>16&255,this.hi>>>24)},t.prototype.zzEncode=function(){var e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this},t.prototype.zzDecode=function(){var e=-(1&this.lo);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this},t.prototype.length=function(){var e=this.lo,t=(this.lo>>>28|this.hi<<4)>>>0,i=this.hi>>>24;return 0===i?0===t?e<16384?e<128?1:2:e<2097152?3:4:t<16384?t<128?5:6:t<2097152?7:8:i<128?9:10},Z}(),t.isNode=Boolean(void 0!==i&&i&&i.process&&i.process.versions&&i.process.versions.node),t.global=t.isNode&&i||"undefined"!=typeof window&&window||"undefined"!=typeof self&&self||i,t.emptyArray=Object.freeze?Object.freeze([]):[],t.emptyObject=Object.freeze?Object.freeze({}):{},t.isInteger=Number.isInteger||function(e){return"number"==typeof e&&isFinite(e)&&Math.floor(e)===e},t.isString=function(e){return"string"==typeof e||e instanceof String},t.isObject=function(e){return e&&"object"==typeof e},t.isset=t.isSet=function(e,t){var i=e[t];return!(null==i||!e.hasOwnProperty(t))&&("object"!=typeof i||(Array.isArray(i)?i.length:Object.keys(i).length)>0)},t.Buffer=function(){try{var e=t.inquire("buffer").Buffer;return e.prototype.utf8Write?e:null}catch(e){return null}}(),t._Buffer_from=null,t._Buffer_allocUnsafe=null,t.newBuffer=function(e){return"number"==typeof e?t.Buffer?t._Buffer_allocUnsafe(e):new t.Array(e):t.Buffer?t._Buffer_from(e):"undefined"==typeof Uint8Array?e:new Uint8Array(e)},t.Array="undefined"!=typeof Uint8Array?Uint8Array:Array,t.Long=t.global.dcodeIO&&t.global.dcodeIO.Long||t.global.Long||t.inquire("long"),t.key2Re=/^true|false|0|1$/,t.key32Re=/^-?(?:0|[1-9][0-9]*)$/,t.key64Re=/^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/,t.longToHash=function(e){return e?t.LongBits.from(e).toHash():t.LongBits.zeroHash},t.longFromHash=function(e,i){var n=t.LongBits.fromHash(e);return t.Long?t.Long.fromBits(n.lo,n.hi,i):n.toNumber(Boolean(i))},t.merge=n,t.lcFirst=function(e){return e.charAt(0).toLowerCase()+e.substring(1)},t.newError=r,t.ProtocolError=r("ProtocolError"),t.oneOfGetter=function(e){for(var t={},i=0;i<e.length;++i)t[e[i]]=1;return function(){for(var e=Object.keys(this),i=e.length-1;i>-1;--i)if(1===t[e[i]]&&void 0!==this[e[i]]&&null!==this[e[i]])return e[i]}},t.oneOfSetter=function(e){return function(t){for(var i=0;i<e.length;++i)e[i]!==t&&delete this[e[i]]}},t.toJSONOptions={longs:String,enums:String,bytes:String,json:!0},t._configure=function(){var e=t.Buffer;e?(t._Buffer_from=e.from!==Uint8Array.from&&e.from||function(t,i){return new e(t,i)},t._Buffer_allocUnsafe=e.allocUnsafe||function(t){return new e(t)}):t._Buffer_from=t._Buffer_allocUnsafe=null}}(B)),B}var te,ie=ue,ne=ee(),re=ne.LongBits,se=ne.base64,oe=ne.utf8;function ae(e,t,i){this.fn=e,this.len=t,this.next=void 0,this.val=i}function ce(){}function de(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}function ue(){this.len=0,this.head=new ae(ce,0,0),this.tail=this.head,this.states=null}var le=function(){return ne.Buffer?function(){return(ue.create=function(){return new te})()}:function(){return new ue}};function he(e,t,i){t[i]=255&e}function pe(e,t){this.len=e,this.next=void 0,this.val=t}function me(e,t,i){for(;e.hi;)t[i++]=127&e.lo|128,e.lo=(e.lo>>>7|e.hi<<25)>>>0,e.hi>>>=7;for(;e.lo>127;)t[i++]=127&e.lo|128,e.lo=e.lo>>>7;t[i++]=e.lo}function fe(e,t,i){t[i]=255&e,t[i+1]=e>>>8&255,t[i+2]=e>>>16&255,t[i+3]=e>>>24}ue.create=le(),ue.alloc=function(e){return new ne.Array(e)},ne.Array!==Array&&(ue.alloc=ne.pool(ue.alloc,ne.Array.prototype.subarray)),ue.prototype._push=function(e,t,i){return this.tail=this.tail.next=new ae(e,t,i),this.len+=t,this},pe.prototype=Object.create(ae.prototype),pe.prototype.fn=function(e,t,i){for(;e>127;)t[i++]=127&e|128,e>>>=7;t[i]=e},ue.prototype.uint32=function(e){return this.len+=(this.tail=this.tail.next=new pe((e>>>=0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this},ue.prototype.int32=function(e){return e<0?this._push(me,10,re.fromNumber(e)):this.uint32(e)},ue.prototype.sint32=function(e){return this.uint32((e<<1^e>>31)>>>0)},ue.prototype.uint64=function(e){var t=re.from(e);return this._push(me,t.length(),t)},ue.prototype.int64=ue.prototype.uint64,ue.prototype.sint64=function(e){var t=re.from(e).zzEncode();return this._push(me,t.length(),t)},ue.prototype.bool=function(e){return this._push(he,1,e?1:0)},ue.prototype.fixed32=function(e){return this._push(fe,4,e>>>0)},ue.prototype.sfixed32=ue.prototype.fixed32,ue.prototype.fixed64=function(e){var t=re.from(e);return this._push(fe,4,t.lo)._push(fe,4,t.hi)},ue.prototype.sfixed64=ue.prototype.fixed64,ue.prototype.float=function(e){return this._push(ne.float.writeFloatLE,4,e)},ue.prototype.double=function(e){return this._push(ne.float.writeDoubleLE,8,e)};var ve=ne.Array.prototype.set?function(e,t,i){t.set(e,i)}:function(e,t,i){for(var n=0;n<e.length;++n)t[i+n]=e[n]};ue.prototype.bytes=function(e){var t=e.length>>>0;if(!t)return this._push(he,1,0);if(ne.isString(e)){var i=ue.alloc(t=se.length(e));se.decode(e,i,0),e=i}return this.uint32(t)._push(ve,t,e)},ue.prototype.string=function(e){var t=oe.length(e);return t?this.uint32(t)._push(oe.write,t,e):this._push(he,1,0)},ue.prototype.fork=function(){return this.states=new de(this),this.head=this.tail=new ae(ce,0,0),this.len=0,this},ue.prototype.reset=function(){return this.states?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new ae(ce,0,0),this.len=0),this},ue.prototype.ldelim=function(){var e=this.head,t=this.tail,i=this.len;return this.reset().uint32(i),i&&(this.tail.next=e.next,this.tail=t,this.len+=i),this},ue.prototype.finish=function(){for(var e=this.head.next,t=this.constructor.alloc(this.len),i=0;e;)e.fn(e.val,t,i),i+=e.len,e=e.next;return t},ue._configure=function(e){te=e,ue.create=le(),te._configure()};var ge=ye,be=ie;(ye.prototype=Object.create(be.prototype)).constructor=ye;var ke=ee();function ye(){be.call(this)}function Se(e,t,i){e.length<40?ke.utf8.write(e,t,i):t.utf8Write?t.utf8Write(e,i):t.write(e,i)}ye._configure=function(){ye.alloc=ke._Buffer_allocUnsafe,ye.writeBytesBuffer=ke.Buffer&&ke.Buffer.prototype instanceof Uint8Array&&"set"===ke.Buffer.prototype.set.name?function(e,t,i){t.set(e,i)}:function(e,t,i){if(e.copy)e.copy(t,i,0,e.length);else for(var n=0;n<e.length;)t[i++]=e[n++]}},ye.prototype.bytes=function(e){ke.isString(e)&&(e=ke._Buffer_from(e,"base64"));var t=e.length>>>0;return this.uint32(t),t&&this._push(ye.writeBytesBuffer,t,e),this},ye.prototype.string=function(e){var t=ke.Buffer.byteLength(e);return this.uint32(t),t&&this._push(Se,t,e),this},ye._configure();var Ce,Ee=Ne,Te=ee(),Pe=Te.LongBits,we=Te.utf8;function Re(e,t){return RangeError("index out of range: "+e.pos+" + "+(t||1)+" > "+e.len)}function Ne(e){this.buf=e,this.pos=0,this.len=e.length}var Oe,Ie="undefined"!=typeof Uint8Array?function(e){if(e instanceof Uint8Array||Array.isArray(e))return new Ne(e);throw Error("illegal buffer")}:function(e){if(Array.isArray(e))return new Ne(e);throw Error("illegal buffer")},De=function(){return Te.Buffer?function(e){return(Ne.create=function(e){return Te.Buffer.isBuffer(e)?new Ce(e):Ie(e)})(e)}:Ie};function Ae(){var e=new Pe(0,0),t=0;if(!(this.len-this.pos>4)){for(;t<3;++t){if(this.pos>=this.len)throw Re(this);if(e.lo=(e.lo|(127&this.buf[this.pos])<<7*t)>>>0,this.buf[this.pos++]<128)return e}return e.lo=(e.lo|(127&this.buf[this.pos++])<<7*t)>>>0,e}for(;t<4;++t)if(e.lo=(e.lo|(127&this.buf[this.pos])<<7*t)>>>0,this.buf[this.pos++]<128)return e;if(e.lo=(e.lo|(127&this.buf[this.pos])<<28)>>>0,e.hi=(e.hi|(127&this.buf[this.pos])>>4)>>>0,this.buf[this.pos++]<128)return e;if(t=0,this.len-this.pos>4){for(;t<5;++t)if(e.hi=(e.hi|(127&this.buf[this.pos])<<7*t+3)>>>0,this.buf[this.pos++]<128)return e}else for(;t<5;++t){if(this.pos>=this.len)throw Re(this);if(e.hi=(e.hi|(127&this.buf[this.pos])<<7*t+3)>>>0,this.buf[this.pos++]<128)return e}throw Error("invalid varint encoding")}function Ue(e,t){return(e[t-4]|e[t-3]<<8|e[t-2]<<16|e[t-1]<<24)>>>0}function Me(){if(this.pos+8>this.len)throw Re(this,8);return new Pe(Ue(this.buf,this.pos+=4),Ue(this.buf,this.pos+=4))}Ne.create=De(),Ne.prototype._slice=Te.Array.prototype.subarray||Te.Array.prototype.slice,Ne.prototype.uint32=(Oe=4294967295,function(){if(Oe=(127&this.buf[this.pos])>>>0,this.buf[this.pos++]<128)return Oe;if(Oe=(Oe|(127&this.buf[this.pos])<<7)>>>0,this.buf[this.pos++]<128)return Oe;if(Oe=(Oe|(127&this.buf[this.pos])<<14)>>>0,this.buf[this.pos++]<128)return Oe;if(Oe=(Oe|(127&this.buf[this.pos])<<21)>>>0,this.buf[this.pos++]<128)return Oe;if(Oe=(Oe|(15&this.buf[this.pos])<<28)>>>0,this.buf[this.pos++]<128)return Oe;if((this.pos+=5)>this.len)throw this.pos=this.len,Re(this,10);return Oe}),Ne.prototype.int32=function(){return 0|this.uint32()},Ne.prototype.sint32=function(){var e=this.uint32();return e>>>1^-(1&e)|0},Ne.prototype.bool=function(){return 0!==this.uint32()},Ne.prototype.fixed32=function(){if(this.pos+4>this.len)throw Re(this,4);return Ue(this.buf,this.pos+=4)},Ne.prototype.sfixed32=function(){if(this.pos+4>this.len)throw Re(this,4);return 0|Ue(this.buf,this.pos+=4)},Ne.prototype.float=function(){if(this.pos+4>this.len)throw Re(this,4);var e=Te.float.readFloatLE(this.buf,this.pos);return this.pos+=4,e},Ne.prototype.double=function(){if(this.pos+8>this.len)throw Re(this,4);var e=Te.float.readDoubleLE(this.buf,this.pos);return this.pos+=8,e},Ne.prototype.bytes=function(){var e=this.uint32(),t=this.pos,i=this.pos+e;if(i>this.len)throw Re(this,e);return this.pos+=e,Array.isArray(this.buf)?this.buf.slice(t,i):t===i?new this.buf.constructor(0):this._slice.call(this.buf,t,i)},Ne.prototype.string=function(){var e=this.bytes();return we.read(e,0,e.length)},Ne.prototype.skip=function(e){if("number"==typeof e){if(this.pos+e>this.len)throw Re(this,e);this.pos+=e}else do{if(this.pos>=this.len)throw Re(this)}while(128&this.buf[this.pos++]);return this},Ne.prototype.skipType=function(e){switch(e){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;4!=(e=7&this.uint32());)this.skipType(e);break;case 5:this.skip(4);break;default:throw Error("invalid wire type "+e+" at offset "+this.pos)}return this},Ne._configure=function(e){Ce=e,Ne.create=De(),Ce._configure();var t=Te.Long?"toLong":"toNumber";Te.merge(Ne.prototype,{int64:function(){return Ae.call(this)[t](!1)},uint64:function(){return Ae.call(this)[t](!0)},sint64:function(){return Ae.call(this).zzDecode()[t](!1)},fixed64:function(){return Me.call(this)[t](!0)},sfixed64:function(){return Me.call(this)[t](!1)}})};var Le=Be,_e=Ee;(Be.prototype=Object.create(_e.prototype)).constructor=Be;var xe=ee();function Be(e){_e.call(this,e)}Be._configure=function(){xe.Buffer&&(Be.prototype._slice=xe.Buffer.prototype.slice)},Be.prototype.string=function(){var e=this.uint32();return this.buf.utf8Slice?this.buf.utf8Slice(this.pos,this.pos=Math.min(this.pos+e,this.len)):this.buf.toString("utf-8",this.pos,this.pos=Math.min(this.pos+e,this.len))},Be._configure();var Je={},Fe=Ve,$e=ee();function Ve(e,t,i){if("function"!=typeof e)throw TypeError("rpcImpl must be a function");$e.EventEmitter.call(this),this.rpcImpl=e,this.requestDelimited=Boolean(t),this.responseDelimited=Boolean(i)}(Ve.prototype=Object.create($e.EventEmitter.prototype)).constructor=Ve,Ve.prototype.rpcCall=function e(t,i,n,r,s){if(!r)throw TypeError("request must be specified");var o=this;if(!s)return $e.asPromise(e,o,t,i,n,r);if(o.rpcImpl)try{return o.rpcImpl(t,i[o.requestDelimited?"encodeDelimited":"encode"](r).finish(),(function(e,i){if(e)return o.emit("error",e,t),s(e);if(null!==i){if(!(i instanceof n))try{i=n[o.responseDelimited?"decodeDelimited":"decode"](i)}catch(e){return o.emit("error",e,t),s(e)}return o.emit("data",i,t),s(null,i)}o.end(!0)}))}catch(e){return o.emit("error",e,t),void setTimeout((function(){s(e)}),0)}else setTimeout((function(){s(Error("already ended"))}),0)},Ve.prototype.end=function(e){return this.rpcImpl&&(e||this.rpcImpl(null,null,null),this.rpcImpl=null,this.emit("end").off()),this},function(e){e.Service=Fe}(Je);var je={};!function(e){var t=e;function i(){t.util._configure(),t.Writer._configure(t.BufferWriter),t.Reader._configure(t.BufferReader)}t.build="minimal",t.Writer=ie,t.BufferWriter=ge,t.Reader=Ee,t.BufferReader=Le,t.util=ee(),t.rpc=Je,t.roots=je,t.configure=i,i()}(x);var qe,We,Ge,Ke,Qe,He,Ze,ze,Ye,Xe,et,tt,it,nt,rt,st=n(x);function ot(e){switch(e){case 0:case"AUDIO":return Ge.AUDIO;case 1:case"VIDEO":return Ge.VIDEO;case 2:case"DATA":return Ge.DATA;default:return Ge.UNRECOGNIZED}}function at(e){switch(e){case Ge.AUDIO:return"AUDIO";case Ge.VIDEO:return"VIDEO";case Ge.DATA:return"DATA";case Ge.UNRECOGNIZED:default:return"UNRECOGNIZED"}}function ct(e){switch(e){case 0:case"UNKNOWN":return Ke.UNKNOWN;case 1:case"CAMERA":return Ke.CAMERA;case 2:case"MICROPHONE":return Ke.MICROPHONE;case 3:case"SCREEN_SHARE":return Ke.SCREEN_SHARE;case 4:case"SCREEN_SHARE_AUDIO":return Ke.SCREEN_SHARE_AUDIO;default:return Ke.UNRECOGNIZED}}function dt(e){switch(e){case Ke.UNKNOWN:return"UNKNOWN";case Ke.CAMERA:return"CAMERA";case Ke.MICROPHONE:return"MICROPHONE";case Ke.SCREEN_SHARE:return"SCREEN_SHARE";case Ke.SCREEN_SHARE_AUDIO:return"SCREEN_SHARE_AUDIO";case Ke.UNRECOGNIZED:default:return"UNRECOGNIZED"}}function ut(t){switch(t){case 0:case"LOW":return e.VideoQuality.LOW;case 1:case"MEDIUM":return e.VideoQuality.MEDIUM;case 2:case"HIGH":return e.VideoQuality.HIGH;case 3:case"OFF":return e.VideoQuality.OFF;default:return e.VideoQuality.UNRECOGNIZED}}function lt(t){switch(t){case e.VideoQuality.LOW:return"LOW";case e.VideoQuality.MEDIUM:return"MEDIUM";case e.VideoQuality.HIGH:return"HIGH";case e.VideoQuality.OFF:return"OFF";case e.VideoQuality.UNRECOGNIZED:default:return"UNRECOGNIZED"}}function ht(e){switch(e){case 0:case"POOR":return He.POOR;case 1:case"GOOD":return He.GOOD;case 2:case"EXCELLENT":return He.EXCELLENT;default:return He.UNRECOGNIZED}}function pt(e){switch(e){case 0:case"UNSET":return Ze.UNSET;case 1:case"DISABLED":return Ze.DISABLED;case 2:case"ENABLED":return Ze.ENABLED;default:return Ze.UNRECOGNIZED}}function mt(e){switch(e){case Ze.UNSET:return"UNSET";case Ze.DISABLED:return"DISABLED";case Ze.ENABLED:return"ENABLED";case Ze.UNRECOGNIZED:default:return"UNRECOGNIZED"}}function ft(t){switch(t){case 0:case"UNKNOWN_REASON":return e.DisconnectReason.UNKNOWN_REASON;case 1:case"CLIENT_INITIATED":return e.DisconnectReason.CLIENT_INITIATED;case 2:case"DUPLICATE_IDENTITY":return e.DisconnectReason.DUPLICATE_IDENTITY;case 3:case"SERVER_SHUTDOWN":return e.DisconnectReason.SERVER_SHUTDOWN;case 4:case"PARTICIPANT_REMOVED":return e.DisconnectReason.PARTICIPANT_REMOVED;case 5:case"ROOM_DELETED":return e.DisconnectReason.ROOM_DELETED;case 6:case"STATE_MISMATCH":return e.DisconnectReason.STATE_MISMATCH;case 7:case"JOIN_FAILURE":return e.DisconnectReason.JOIN_FAILURE;default:return e.DisconnectReason.UNRECOGNIZED}}function vt(e){switch(e){case 0:case"SE_UNKNOWN":return Xe.SE_UNKNOWN;case 1:case"SE_CODEC_UNSUPPORTED":return Xe.SE_CODEC_UNSUPPORTED;case 2:case"SE_TRACK_NOTFOUND":return Xe.SE_TRACK_NOTFOUND;default:return Xe.UNRECOGNIZED}}function gt(e){switch(e){case 0:case"JOINING":return et.JOINING;case 1:case"JOINED":return et.JOINED;case 2:case"ACTIVE":return et.ACTIVE;case 3:case"DISCONNECTED":return et.DISCONNECTED;default:return et.UNRECOGNIZED}}function bt(e){switch(e){case 0:case"NONE":return tt.NONE;case 1:case"GCM":return tt.GCM;case 2:case"CUSTOM":return tt.CUSTOM;default:return tt.UNRECOGNIZED}}function kt(e){switch(e){case tt.NONE:return"NONE";case tt.GCM:return"GCM";case tt.CUSTOM:return"CUSTOM";case tt.UNRECOGNIZED:default:return"UNRECOGNIZED"}}function yt(t){switch(t){case 0:case"RELIABLE":return e.DataPacket_Kind.RELIABLE;case 1:case"LOSSY":return e.DataPacket_Kind.LOSSY;default:return e.DataPacket_Kind.UNRECOGNIZED}}function St(e){switch(e){case 0:case"Standard":return nt.Standard;case 1:case"Cloud":return nt.Cloud;default:return nt.UNRECOGNIZED}}function Ct(e){switch(e){case 0:case"UNKNOWN":return rt.UNKNOWN;case 1:case"JS":return rt.JS;case 2:case"SWIFT":return rt.SWIFT;case 3:case"ANDROID":return rt.ANDROID;case 4:case"FLUTTER":return rt.FLUTTER;case 5:case"GO":return rt.GO;case 6:case"UNITY":return rt.UNITY;case 7:case"REACT_NATIVE":return rt.REACT_NATIVE;case 8:case"RUST":return rt.RUST;default:return rt.UNRECOGNIZED}}(()=>{if("undefined"!=typeof globalThis)return globalThis;if("undefined"!=typeof self)return self;if("undefined"!=typeof window)return window;if("undefined"!=typeof global)return global;throw"Unable to locate global object"})(),st.util.Long!==_&&(st.util.Long=_,st.configure()),function(e){e[e.DEFAULT_AC=0]="DEFAULT_AC",e[e.OPUS=1]="OPUS",e[e.AAC=2]="AAC",e[e.UNRECOGNIZED=-1]="UNRECOGNIZED"}(qe||(qe={})),function(e){e[e.DEFAULT_VC=0]="DEFAULT_VC",e[e.H264_BASELINE=1]="H264_BASELINE",e[e.H264_MAIN=2]="H264_MAIN",e[e.H264_HIGH=3]="H264_HIGH",e[e.VP8=4]="VP8",e[e.UNRECOGNIZED=-1]="UNRECOGNIZED"}(We||(We={})),function(e){e[e.AUDIO=0]="AUDIO",e[e.VIDEO=1]="VIDEO",e[e.DATA=2]="DATA",e[e.UNRECOGNIZED=-1]="UNRECOGNIZED"}(Ge||(Ge={})),function(e){e[e.UNKNOWN=0]="UNKNOWN",e[e.CAMERA=1]="CAMERA",e[e.MICROPHONE=2]="MICROPHONE",e[e.SCREEN_SHARE=3]="SCREEN_SHARE",e[e.SCREEN_SHARE_AUDIO=4]="SCREEN_SHARE_AUDIO",e[e.UNRECOGNIZED=-1]="UNRECOGNIZED"}(Ke||(Ke={})),e.VideoQuality=void 0,(Qe=e.VideoQuality||(e.VideoQuality={}))[Qe.LOW=0]="LOW",Qe[Qe.MEDIUM=1]="MEDIUM",Qe[Qe.HIGH=2]="HIGH",Qe[Qe.OFF=3]="OFF",Qe[Qe.UNRECOGNIZED=-1]="UNRECOGNIZED",function(e){e[e.POOR=0]="POOR",e[e.GOOD=1]="GOOD",e[e.EXCELLENT=2]="EXCELLENT",e[e.UNRECOGNIZED=-1]="UNRECOGNIZED"}(He||(He={})),function(e){e[e.UNSET=0]="UNSET",e[e.DISABLED=1]="DISABLED",e[e.ENABLED=2]="ENABLED",e[e.UNRECOGNIZED=-1]="UNRECOGNIZED"}(Ze||(Ze={})),e.DisconnectReason=void 0,(ze=e.DisconnectReason||(e.DisconnectReason={}))[ze.UNKNOWN_REASON=0]="UNKNOWN_REASON",ze[ze.CLIENT_INITIATED=1]="CLIENT_INITIATED",ze[ze.DUPLICATE_IDENTITY=2]="DUPLICATE_IDENTITY",ze[ze.SERVER_SHUTDOWN=3]="SERVER_SHUTDOWN",ze[ze.PARTICIPANT_REMOVED=4]="PARTICIPANT_REMOVED",ze[ze.ROOM_DELETED=5]="ROOM_DELETED",ze[ze.STATE_MISMATCH=6]="STATE_MISMATCH",ze[ze.JOIN_FAILURE=7]="JOIN_FAILURE",ze[ze.UNRECOGNIZED=-1]="UNRECOGNIZED",function(e){e[e.RR_UNKNOWN=0]="RR_UNKNOWN",e[e.RR_SIGNAL_DISCONNECTED=1]="RR_SIGNAL_DISCONNECTED",e[e.RR_PUBLISHER_FAILED=2]="RR_PUBLISHER_FAILED",e[e.RR_SUBSCRIBER_FAILED=3]="RR_SUBSCRIBER_FAILED",e[e.RR_SWITCH_CANDIDATE=4]="RR_SWITCH_CANDIDATE",e[e.UNRECOGNIZED=-1]="UNRECOGNIZED"}(Ye||(Ye={})),function(e){e[e.SE_UNKNOWN=0]="SE_UNKNOWN",e[e.SE_CODEC_UNSUPPORTED=1]="SE_CODEC_UNSUPPORTED",e[e.SE_TRACK_NOTFOUND=2]="SE_TRACK_NOTFOUND",e[e.UNRECOGNIZED=-1]="UNRECOGNIZED"}(Xe||(Xe={})),function(e){e[e.JOINING=0]="JOINING",e[e.JOINED=1]="JOINED",e[e.ACTIVE=2]="ACTIVE",e[e.DISCONNECTED=3]="DISCONNECTED",e[e.UNRECOGNIZED=-1]="UNRECOGNIZED"}(et||(et={})),function(e){e[e.NONE=0]="NONE",e[e.GCM=1]="GCM",e[e.CUSTOM=2]="CUSTOM",e[e.UNRECOGNIZED=-1]="UNRECOGNIZED"}(tt||(tt={})),e.DataPacket_Kind=void 0,(it=e.DataPacket_Kind||(e.DataPacket_Kind={}))[it.RELIABLE=0]="RELIABLE",it[it.LOSSY=1]="LOSSY",it[it.UNRECOGNIZED=-1]="UNRECOGNIZED",function(e){e[e.Standard=0]="Standard",e[e.Cloud=1]="Cloud",e[e.UNRECOGNIZED=-1]="UNRECOGNIZED"}(nt||(nt={})),function(e){e[e.UNKNOWN=0]="UNKNOWN",e[e.JS=1]="JS",e[e.SWIFT=2]="SWIFT",e[e.ANDROID=3]="ANDROID",e[e.FLUTTER=4]="FLUTTER",e[e.GO=5]="GO",e[e.UNITY=6]="UNITY",e[e.REACT_NATIVE=7]="REACT_NATIVE",e[e.RUST=8]="RUST",e[e.UNRECOGNIZED=-1]="UNRECOGNIZED"}(rt||(rt={}));const Et={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:st.Writer.create();""!==e.sid&&t.uint32(10).string(e.sid),""!==e.name&&t.uint32(18).string(e.name),0!==e.emptyTimeout&&t.uint32(24).uint32(e.emptyTimeout),0!==e.maxParticipants&&t.uint32(32).uint32(e.maxParticipants),0!==e.creationTime&&t.uint32(40).int64(e.creationTime),""!==e.turnPassword&&t.uint32(50).string(e.turnPassword);for(const i of e.enabledCodecs)Tt.encode(i,t.uint32(58).fork()).ldelim();return""!==e.metadata&&t.uint32(66).string(e.metadata),0!==e.numParticipants&&t.uint32(72).uint32(e.numParticipants),0!==e.numPublishers&&t.uint32(88).uint32(e.numPublishers),!0===e.activeRecording&&t.uint32(80).bool(e.activeRecording),t},decode(e,t){const i=e instanceof st.Reader?e:st.Reader.create(e);let n=void 0===t?i.len:i.pos+t;const r={sid:"",name:"",emptyTimeout:0,maxParticipants:0,creationTime:0,turnPassword:"",enabledCodecs:[],metadata:"",numParticipants:0,numPublishers:0,activeRecording:!1};for(;i.pos<n;){const e=i.uint32();switch(e>>>3){case 1:if(10!==e)break;r.sid=i.string();continue;case 2:if(18!==e)break;r.name=i.string();continue;case 3:if(24!==e)break;r.emptyTimeout=i.uint32();continue;case 4:if(32!==e)break;r.maxParticipants=i.uint32();continue;case 5:if(40!==e)break;r.creationTime=jt(i.int64());continue;case 6:if(50!==e)break;r.turnPassword=i.string();continue;case 7:if(58!==e)break;r.enabledCodecs.push(Tt.decode(i,i.uint32()));continue;case 8:if(66!==e)break;r.metadata=i.string();continue;case 9:if(72!==e)break;r.numParticipants=i.uint32();continue;case 11:if(88!==e)break;r.numPublishers=i.uint32();continue;case 10:if(80!==e)break;r.activeRecording=i.bool();continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return r},fromJSON:e=>({sid:qt(e.sid)?String(e.sid):"",name:qt(e.name)?String(e.name):"",emptyTimeout:qt(e.emptyTimeout)?Number(e.emptyTimeout):0,maxParticipants:qt(e.maxParticipants)?Number(e.maxParticipants):0,creationTime:qt(e.creationTime)?Number(e.creationTime):0,turnPassword:qt(e.turnPassword)?String(e.turnPassword):"",enabledCodecs:Array.isArray(null==e?void 0:e.enabledCodecs)?e.enabledCodecs.map((e=>Tt.fromJSON(e))):[],metadata:qt(e.metadata)?String(e.metadata):"",numParticipants:qt(e.numParticipants)?Number(e.numParticipants):0,numPublishers:qt(e.numPublishers)?Number(e.numPublishers):0,activeRecording:!!qt(e.activeRecording)&&Boolean(e.activeRecording)}),toJSON(e){const t={};return void 0!==e.sid&&(t.sid=e.sid),void 0!==e.name&&(t.name=e.name),void 0!==e.emptyTimeout&&(t.emptyTimeout=Math.round(e.emptyTimeout)),void 0!==e.maxParticipants&&(t.maxParticipants=Math.round(e.maxParticipants)),void 0!==e.creationTime&&(t.creationTime=Math.round(e.creationTime)),void 0!==e.turnPassword&&(t.turnPassword=e.turnPassword),e.enabledCodecs?t.enabledCodecs=e.enabledCodecs.map((e=>e?Tt.toJSON(e):void 0)):t.enabledCodecs=[],void 0!==e.metadata&&(t.metadata=e.metadata),void 0!==e.numParticipants&&(t.numParticipants=Math.round(e.numParticipants)),void 0!==e.numPublishers&&(t.numPublishers=Math.round(e.numPublishers)),void 0!==e.activeRecording&&(t.activeRecording=e.activeRecording),t},create:e=>Et.fromPartial(null!=e?e:{}),fromPartial(e){var t,i,n,r,s,o,a,c,d,u,l;const h={sid:"",name:"",emptyTimeout:0,maxParticipants:0,creationTime:0,turnPassword:"",enabledCodecs:[],metadata:"",numParticipants:0,numPublishers:0,activeRecording:!1};return h.sid=null!==(t=e.sid)&&void 0!==t?t:"",h.name=null!==(i=e.name)&&void 0!==i?i:"",h.emptyTimeout=null!==(n=e.emptyTimeout)&&void 0!==n?n:0,h.maxParticipants=null!==(r=e.maxParticipants)&&void 0!==r?r:0,h.creationTime=null!==(s=e.creationTime)&&void 0!==s?s:0,h.turnPassword=null!==(o=e.turnPassword)&&void 0!==o?o:"",h.enabledCodecs=(null===(a=e.enabledCodecs)||void 0===a?void 0:a.map((e=>Tt.fromPartial(e))))||[],h.metadata=null!==(c=e.metadata)&&void 0!==c?c:"",h.numParticipants=null!==(d=e.numParticipants)&&void 0!==d?d:0,h.numPublishers=null!==(u=e.numPublishers)&&void 0!==u?u:0,h.activeRecording=null!==(l=e.activeRecording)&&void 0!==l&&l,h}};const Tt={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:st.Writer.create();return""!==e.mime&&t.uint32(10).string(e.mime),""!==e.fmtpLine&&t.uint32(18).string(e.fmtpLine),t},decode(e,t){const i=e instanceof st.Reader?e:st.Reader.create(e);let n=void 0===t?i.len:i.pos+t;const r={mime:"",fmtpLine:""};for(;i.pos<n;){const e=i.uint32();switch(e>>>3){case 1:if(10!==e)break;r.mime=i.string();continue;case 2:if(18!==e)break;r.fmtpLine=i.string();continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return r},fromJSON:e=>({mime:qt(e.mime)?String(e.mime):"",fmtpLine:qt(e.fmtpLine)?String(e.fmtpLine):""}),toJSON(e){const t={};return void 0!==e.mime&&(t.mime=e.mime),void 0!==e.fmtpLine&&(t.fmtpLine=e.fmtpLine),t},create:e=>Tt.fromPartial(null!=e?e:{}),fromPartial(e){var t,i;const n={mime:"",fmtpLine:""};return n.mime=null!==(t=e.mime)&&void 0!==t?t:"",n.fmtpLine=null!==(i=e.fmtpLine)&&void 0!==i?i:"",n}};const Pt={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:st.Writer.create();!0===e.canSubscribe&&t.uint32(8).bool(e.canSubscribe),!0===e.canPublish&&t.uint32(16).bool(e.canPublish),!0===e.canPublishData&&t.uint32(24).bool(e.canPublishData),t.uint32(74).fork();for(const i of e.canPublishSources)t.int32(i);return t.ldelim(),!0===e.hidden&&t.uint32(56).bool(e.hidden),!0===e.recorder&&t.uint32(64).bool(e.recorder),!0===e.canUpdateMetadata&&t.uint32(80).bool(e.canUpdateMetadata),t},decode(e,t){const i=e instanceof st.Reader?e:st.Reader.create(e);let n=void 0===t?i.len:i.pos+t;const r={canSubscribe:!1,canPublish:!1,canPublishData:!1,canPublishSources:[],hidden:!1,recorder:!1,canUpdateMetadata:!1};for(;i.pos<n;){const e=i.uint32();switch(e>>>3){case 1:if(8!==e)break;r.canSubscribe=i.bool();continue;case 2:if(16!==e)break;r.canPublish=i.bool();continue;case 3:if(24!==e)break;r.canPublishData=i.bool();continue;case 9:if(72===e){r.canPublishSources.push(i.int32());continue}if(74===e){const e=i.uint32()+i.pos;for(;i.pos<e;)r.canPublishSources.push(i.int32());continue}break;case 7:if(56!==e)break;r.hidden=i.bool();continue;case 8:if(64!==e)break;r.recorder=i.bool();continue;case 10:if(80!==e)break;r.canUpdateMetadata=i.bool();continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return r},fromJSON:e=>({canSubscribe:!!qt(e.canSubscribe)&&Boolean(e.canSubscribe),canPublish:!!qt(e.canPublish)&&Boolean(e.canPublish),canPublishData:!!qt(e.canPublishData)&&Boolean(e.canPublishData),canPublishSources:Array.isArray(null==e?void 0:e.canPublishSources)?e.canPublishSources.map((e=>ct(e))):[],hidden:!!qt(e.hidden)&&Boolean(e.hidden),recorder:!!qt(e.recorder)&&Boolean(e.recorder),canUpdateMetadata:!!qt(e.canUpdateMetadata)&&Boolean(e.canUpdateMetadata)}),toJSON(e){const t={};return void 0!==e.canSubscribe&&(t.canSubscribe=e.canSubscribe),void 0!==e.canPublish&&(t.canPublish=e.canPublish),void 0!==e.canPublishData&&(t.canPublishData=e.canPublishData),e.canPublishSources?t.canPublishSources=e.canPublishSources.map((e=>dt(e))):t.canPublishSources=[],void 0!==e.hidden&&(t.hidden=e.hidden),void 0!==e.recorder&&(t.recorder=e.recorder),void 0!==e.canUpdateMetadata&&(t.canUpdateMetadata=e.canUpdateMetadata),t},create:e=>Pt.fromPartial(null!=e?e:{}),fromPartial(e){var t,i,n,r,s,o,a;const c={canSubscribe:!1,canPublish:!1,canPublishData:!1,canPublishSources:[],hidden:!1,recorder:!1,canUpdateMetadata:!1};return c.canSubscribe=null!==(t=e.canSubscribe)&&void 0!==t&&t,c.canPublish=null!==(i=e.canPublish)&&void 0!==i&&i,c.canPublishData=null!==(n=e.canPublishData)&&void 0!==n&&n,c.canPublishSources=(null===(r=e.canPublishSources)||void 0===r?void 0:r.map((e=>e)))||[],c.hidden=null!==(s=e.hidden)&&void 0!==s&&s,c.recorder=null!==(o=e.recorder)&&void 0!==o&&o,c.canUpdateMetadata=null!==(a=e.canUpdateMetadata)&&void 0!==a&&a,c}};const wt={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:st.Writer.create();""!==e.sid&&t.uint32(10).string(e.sid),""!==e.identity&&t.uint32(18).string(e.identity),0!==e.state&&t.uint32(24).int32(e.state);for(const i of e.tracks)Nt.encode(i,t.uint32(34).fork()).ldelim();return""!==e.metadata&&t.uint32(42).string(e.metadata),0!==e.joinedAt&&t.uint32(48).int64(e.joinedAt),""!==e.name&&t.uint32(74).string(e.name),0!==e.version&&t.uint32(80).uint32(e.version),void 0!==e.permission&&Pt.encode(e.permission,t.uint32(90).fork()).ldelim(),""!==e.region&&t.uint32(98).string(e.region),!0===e.isPublisher&&t.uint32(104).bool(e.isPublisher),t},decode(e,t){const i=e instanceof st.Reader?e:st.Reader.create(e);let n=void 0===t?i.len:i.pos+t;const r={sid:"",identity:"",state:0,tracks:[],metadata:"",joinedAt:0,name:"",version:0,permission:void 0,region:"",isPublisher:!1};for(;i.pos<n;){const e=i.uint32();switch(e>>>3){case 1:if(10!==e)break;r.sid=i.string();continue;case 2:if(18!==e)break;r.identity=i.string();continue;case 3:if(24!==e)break;r.state=i.int32();continue;case 4:if(34!==e)break;r.tracks.push(Nt.decode(i,i.uint32()));continue;case 5:if(42!==e)break;r.metadata=i.string();continue;case 6:if(48!==e)break;r.joinedAt=jt(i.int64());continue;case 9:if(74!==e)break;r.name=i.string();continue;case 10:if(80!==e)break;r.version=i.uint32();continue;case 11:if(90!==e)break;r.permission=Pt.decode(i,i.uint32());continue;case 12:if(98!==e)break;r.region=i.string();continue;case 13:if(104!==e)break;r.isPublisher=i.bool();continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return r},fromJSON:e=>({sid:qt(e.sid)?String(e.sid):"",identity:qt(e.identity)?String(e.identity):"",state:qt(e.state)?gt(e.state):0,tracks:Array.isArray(null==e?void 0:e.tracks)?e.tracks.map((e=>Nt.fromJSON(e))):[],metadata:qt(e.metadata)?String(e.metadata):"",joinedAt:qt(e.joinedAt)?Number(e.joinedAt):0,name:qt(e.name)?String(e.name):"",version:qt(e.version)?Number(e.version):0,permission:qt(e.permission)?Pt.fromJSON(e.permission):void 0,region:qt(e.region)?String(e.region):"",isPublisher:!!qt(e.isPublisher)&&Boolean(e.isPublisher)}),toJSON(e){const t={};return void 0!==e.sid&&(t.sid=e.sid),void 0!==e.identity&&(t.identity=e.identity),void 0!==e.state&&(t.state=function(e){switch(e){case et.JOINING:return"JOINING";case et.JOINED:return"JOINED";case et.ACTIVE:return"ACTIVE";case et.DISCONNECTED:return"DISCONNECTED";case et.UNRECOGNIZED:default:return"UNRECOGNIZED"}}(e.state)),e.tracks?t.tracks=e.tracks.map((e=>e?Nt.toJSON(e):void 0)):t.tracks=[],void 0!==e.metadata&&(t.metadata=e.metadata),void 0!==e.joinedAt&&(t.joinedAt=Math.round(e.joinedAt)),void 0!==e.name&&(t.name=e.name),void 0!==e.version&&(t.version=Math.round(e.version)),void 0!==e.permission&&(t.permission=e.permission?Pt.toJSON(e.permission):void 0),void 0!==e.region&&(t.region=e.region),void 0!==e.isPublisher&&(t.isPublisher=e.isPublisher),t},create:e=>wt.fromPartial(null!=e?e:{}),fromPartial(e){var t,i,n,r,s,o,a,c,d,u;const l={sid:"",identity:"",state:0,tracks:[],metadata:"",joinedAt:0,name:"",version:0,permission:void 0,region:"",isPublisher:!1};return l.sid=null!==(t=e.sid)&&void 0!==t?t:"",l.identity=null!==(i=e.identity)&&void 0!==i?i:"",l.state=null!==(n=e.state)&&void 0!==n?n:0,l.tracks=(null===(r=e.tracks)||void 0===r?void 0:r.map((e=>Nt.fromPartial(e))))||[],l.metadata=null!==(s=e.metadata)&&void 0!==s?s:"",l.joinedAt=null!==(o=e.joinedAt)&&void 0!==o?o:0,l.name=null!==(a=e.name)&&void 0!==a?a:"",l.version=null!==(c=e.version)&&void 0!==c?c:0,l.permission=void 0!==e.permission&&null!==e.permission?Pt.fromPartial(e.permission):void 0,l.region=null!==(d=e.region)&&void 0!==d?d:"",l.isPublisher=null!==(u=e.isPublisher)&&void 0!==u&&u,l}};const Rt={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:st.Writer.create();""!==e.mimeType&&t.uint32(10).string(e.mimeType),""!==e.mid&&t.uint32(18).string(e.mid),""!==e.cid&&t.uint32(26).string(e.cid);for(const i of e.layers)Ot.encode(i,t.uint32(34).fork()).ldelim();return t},decode(e,t){const i=e instanceof st.Reader?e:st.Reader.create(e);let n=void 0===t?i.len:i.pos+t;const r={mimeType:"",mid:"",cid:"",layers:[]};for(;i.pos<n;){const e=i.uint32();switch(e>>>3){case 1:if(10!==e)break;r.mimeType=i.string();continue;case 2:if(18!==e)break;r.mid=i.string();continue;case 3:if(26!==e)break;r.cid=i.string();continue;case 4:if(34!==e)break;r.layers.push(Ot.decode(i,i.uint32()));continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return r},fromJSON:e=>({mimeType:qt(e.mimeType)?String(e.mimeType):"",mid:qt(e.mid)?String(e.mid):"",cid:qt(e.cid)?String(e.cid):"",layers:Array.isArray(null==e?void 0:e.layers)?e.layers.map((e=>Ot.fromJSON(e))):[]}),toJSON(e){const t={};return void 0!==e.mimeType&&(t.mimeType=e.mimeType),void 0!==e.mid&&(t.mid=e.mid),void 0!==e.cid&&(t.cid=e.cid),e.layers?t.layers=e.layers.map((e=>e?Ot.toJSON(e):void 0)):t.layers=[],t},create:e=>Rt.fromPartial(null!=e?e:{}),fromPartial(e){var t,i,n,r;const s={mimeType:"",mid:"",cid:"",layers:[]};return s.mimeType=null!==(t=e.mimeType)&&void 0!==t?t:"",s.mid=null!==(i=e.mid)&&void 0!==i?i:"",s.cid=null!==(n=e.cid)&&void 0!==n?n:"",s.layers=(null===(r=e.layers)||void 0===r?void 0:r.map((e=>Ot.fromPartial(e))))||[],s}};const Nt={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:st.Writer.create();""!==e.sid&&t.uint32(10).string(e.sid),0!==e.type&&t.uint32(16).int32(e.type),""!==e.name&&t.uint32(26).string(e.name),!0===e.muted&&t.uint32(32).bool(e.muted),0!==e.width&&t.uint32(40).uint32(e.width),0!==e.height&&t.uint32(48).uint32(e.height),!0===e.simulcast&&t.uint32(56).bool(e.simulcast),!0===e.disableDtx&&t.uint32(64).bool(e.disableDtx),0!==e.source&&t.uint32(72).int32(e.source);for(const i of e.layers)Ot.encode(i,t.uint32(82).fork()).ldelim();""!==e.mimeType&&t.uint32(90).string(e.mimeType),""!==e.mid&&t.uint32(98).string(e.mid);for(const i of e.codecs)Rt.encode(i,t.uint32(106).fork()).ldelim();return!0===e.stereo&&t.uint32(112).bool(e.stereo),!0===e.disableRed&&t.uint32(120).bool(e.disableRed),0!==e.encryption&&t.uint32(128).int32(e.encryption),t},decode(e,t){const i=e instanceof st.Reader?e:st.Reader.create(e);let n=void 0===t?i.len:i.pos+t;const r={sid:"",type:0,name:"",muted:!1,width:0,height:0,simulcast:!1,disableDtx:!1,source:0,layers:[],mimeType:"",mid:"",codecs:[],stereo:!1,disableRed:!1,encryption:0};for(;i.pos<n;){const e=i.uint32();switch(e>>>3){case 1:if(10!==e)break;r.sid=i.string();continue;case 2:if(16!==e)break;r.type=i.int32();continue;case 3:if(26!==e)break;r.name=i.string();continue;case 4:if(32!==e)break;r.muted=i.bool();continue;case 5:if(40!==e)break;r.width=i.uint32();continue;case 6:if(48!==e)break;r.height=i.uint32();continue;case 7:if(56!==e)break;r.simulcast=i.bool();continue;case 8:if(64!==e)break;r.disableDtx=i.bool();continue;case 9:if(72!==e)break;r.source=i.int32();continue;case 10:if(82!==e)break;r.layers.push(Ot.decode(i,i.uint32()));continue;case 11:if(90!==e)break;r.mimeType=i.string();continue;case 12:if(98!==e)break;r.mid=i.string();continue;case 13:if(106!==e)break;r.codecs.push(Rt.decode(i,i.uint32()));continue;case 14:if(112!==e)break;r.stereo=i.bool();continue;case 15:if(120!==e)break;r.disableRed=i.bool();continue;case 16:if(128!==e)break;r.encryption=i.int32();continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return r},fromJSON:e=>({sid:qt(e.sid)?String(e.sid):"",type:qt(e.type)?ot(e.type):0,name:qt(e.name)?String(e.name):"",muted:!!qt(e.muted)&&Boolean(e.muted),width:qt(e.width)?Number(e.width):0,height:qt(e.height)?Number(e.height):0,simulcast:!!qt(e.simulcast)&&Boolean(e.simulcast),disableDtx:!!qt(e.disableDtx)&&Boolean(e.disableDtx),source:qt(e.source)?ct(e.source):0,layers:Array.isArray(null==e?void 0:e.layers)?e.layers.map((e=>Ot.fromJSON(e))):[],mimeType:qt(e.mimeType)?String(e.mimeType):"",mid:qt(e.mid)?String(e.mid):"",codecs:Array.isArray(null==e?void 0:e.codecs)?e.codecs.map((e=>Rt.fromJSON(e))):[],stereo:!!qt(e.stereo)&&Boolean(e.stereo),disableRed:!!qt(e.disableRed)&&Boolean(e.disableRed),encryption:qt(e.encryption)?bt(e.encryption):0}),toJSON(e){const t={};return void 0!==e.sid&&(t.sid=e.sid),void 0!==e.type&&(t.type=at(e.type)),void 0!==e.name&&(t.name=e.name),void 0!==e.muted&&(t.muted=e.muted),void 0!==e.width&&(t.width=Math.round(e.width)),void 0!==e.height&&(t.height=Math.round(e.height)),void 0!==e.simulcast&&(t.simulcast=e.simulcast),void 0!==e.disableDtx&&(t.disableDtx=e.disableDtx),void 0!==e.source&&(t.source=dt(e.source)),e.layers?t.layers=e.layers.map((e=>e?Ot.toJSON(e):void 0)):t.layers=[],void 0!==e.mimeType&&(t.mimeType=e.mimeType),void 0!==e.mid&&(t.mid=e.mid),e.codecs?t.codecs=e.codecs.map((e=>e?Rt.toJSON(e):void 0)):t.codecs=[],void 0!==e.stereo&&(t.stereo=e.stereo),void 0!==e.disableRed&&(t.disableRed=e.disableRed),void 0!==e.encryption&&(t.encryption=kt(e.encryption)),t},create:e=>Nt.fromPartial(null!=e?e:{}),fromPartial(e){var t,i,n,r,s,o,a,c,d,u,l,h,p,m,f,v;const g={sid:"",type:0,name:"",muted:!1,width:0,height:0,simulcast:!1,disableDtx:!1,source:0,layers:[],mimeType:"",mid:"",codecs:[],stereo:!1,disableRed:!1,encryption:0};return g.sid=null!==(t=e.sid)&&void 0!==t?t:"",g.type=null!==(i=e.type)&&void 0!==i?i:0,g.name=null!==(n=e.name)&&void 0!==n?n:"",g.muted=null!==(r=e.muted)&&void 0!==r&&r,g.width=null!==(s=e.width)&&void 0!==s?s:0,g.height=null!==(o=e.height)&&void 0!==o?o:0,g.simulcast=null!==(a=e.simulcast)&&void 0!==a&&a,g.disableDtx=null!==(c=e.disableDtx)&&void 0!==c&&c,g.source=null!==(d=e.source)&&void 0!==d?d:0,g.layers=(null===(u=e.layers)||void 0===u?void 0:u.map((e=>Ot.fromPartial(e))))||[],g.mimeType=null!==(l=e.mimeType)&&void 0!==l?l:"",g.mid=null!==(h=e.mid)&&void 0!==h?h:"",g.codecs=(null===(p=e.codecs)||void 0===p?void 0:p.map((e=>Rt.fromPartial(e))))||[],g.stereo=null!==(m=e.stereo)&&void 0!==m&&m,g.disableRed=null!==(f=e.disableRed)&&void 0!==f&&f,g.encryption=null!==(v=e.encryption)&&void 0!==v?v:0,g}};const Ot={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:st.Writer.create();return 0!==e.quality&&t.uint32(8).int32(e.quality),0!==e.width&&t.uint32(16).uint32(e.width),0!==e.height&&t.uint32(24).uint32(e.height),0!==e.bitrate&&t.uint32(32).uint32(e.bitrate),0!==e.ssrc&&t.uint32(40).uint32(e.ssrc),t},decode(e,t){const i=e instanceof st.Reader?e:st.Reader.create(e);let n=void 0===t?i.len:i.pos+t;const r={quality:0,width:0,height:0,bitrate:0,ssrc:0};for(;i.pos<n;){const e=i.uint32();switch(e>>>3){case 1:if(8!==e)break;r.quality=i.int32();continue;case 2:if(16!==e)break;r.width=i.uint32();continue;case 3:if(24!==e)break;r.height=i.uint32();continue;case 4:if(32!==e)break;r.bitrate=i.uint32();continue;case 5:if(40!==e)break;r.ssrc=i.uint32();continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return r},fromJSON:e=>({quality:qt(e.quality)?ut(e.quality):0,width:qt(e.width)?Number(e.width):0,height:qt(e.height)?Number(e.height):0,bitrate:qt(e.bitrate)?Number(e.bitrate):0,ssrc:qt(e.ssrc)?Number(e.ssrc):0}),toJSON(e){const t={};return void 0!==e.quality&&(t.quality=lt(e.quality)),void 0!==e.width&&(t.width=Math.round(e.width)),void 0!==e.height&&(t.height=Math.round(e.height)),void 0!==e.bitrate&&(t.bitrate=Math.round(e.bitrate)),void 0!==e.ssrc&&(t.ssrc=Math.round(e.ssrc)),t},create:e=>Ot.fromPartial(null!=e?e:{}),fromPartial(e){var t,i,n,r,s;const o={quality:0,width:0,height:0,bitrate:0,ssrc:0};return o.quality=null!==(t=e.quality)&&void 0!==t?t:0,o.width=null!==(i=e.width)&&void 0!==i?i:0,o.height=null!==(n=e.height)&&void 0!==n?n:0,o.bitrate=null!==(r=e.bitrate)&&void 0!==r?r:0,o.ssrc=null!==(s=e.ssrc)&&void 0!==s?s:0,o}};const It={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:st.Writer.create();var i;switch(0!==e.kind&&t.uint32(8).int32(e.kind),null===(i=e.value)||void 0===i?void 0:i.$case){case"user":Mt.encode(e.value.user,t.uint32(18).fork()).ldelim();break;case"speaker":Dt.encode(e.value.speaker,t.uint32(26).fork()).ldelim()}return t},decode(e,t){const i=e instanceof st.Reader?e:st.Reader.create(e);let n=void 0===t?i.len:i.pos+t;const r={kind:0,value:void 0};for(;i.pos<n;){const e=i.uint32();switch(e>>>3){case 1:if(8!==e)break;r.kind=i.int32();continue;case 2:if(18!==e)break;r.value={$case:"user",user:Mt.decode(i,i.uint32())};continue;case 3:if(26!==e)break;r.value={$case:"speaker",speaker:Dt.decode(i,i.uint32())};continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return r},fromJSON:e=>({kind:qt(e.kind)?yt(e.kind):0,value:qt(e.user)?{$case:"user",user:Mt.fromJSON(e.user)}:qt(e.speaker)?{$case:"speaker",speaker:Dt.fromJSON(e.speaker)}:void 0}),toJSON(t){var i,n,r,s,o,a;const c={};return void 0!==t.kind&&(c.kind=function(t){switch(t){case e.DataPacket_Kind.RELIABLE:return"RELIABLE";case e.DataPacket_Kind.LOSSY:return"LOSSY";case e.DataPacket_Kind.UNRECOGNIZED:default:return"UNRECOGNIZED"}}(t.kind)),"user"===(null===(i=t.value)||void 0===i?void 0:i.$case)&&(c.user=(null===(n=t.value)||void 0===n?void 0:n.user)?Mt.toJSON(null===(r=t.value)||void 0===r?void 0:r.user):void 0),"speaker"===(null===(s=t.value)||void 0===s?void 0:s.$case)&&(c.speaker=(null===(o=t.value)||void 0===o?void 0:o.speaker)?Dt.toJSON(null===(a=t.value)||void 0===a?void 0:a.speaker):void 0),c},create:e=>It.fromPartial(null!=e?e:{}),fromPartial(e){var t,i,n,r,s,o,a;const c={kind:0,value:void 0};return c.kind=null!==(t=e.kind)&&void 0!==t?t:0,"user"===(null===(i=e.value)||void 0===i?void 0:i.$case)&&void 0!==(null===(n=e.value)||void 0===n?void 0:n.user)&&null!==(null===(r=e.value)||void 0===r?void 0:r.user)&&(c.value={$case:"user",user:Mt.fromPartial(e.value.user)}),"speaker"===(null===(s=e.value)||void 0===s?void 0:s.$case)&&void 0!==(null===(o=e.value)||void 0===o?void 0:o.speaker)&&null!==(null===(a=e.value)||void 0===a?void 0:a.speaker)&&(c.value={$case:"speaker",speaker:Dt.fromPartial(e.value.speaker)}),c}};const Dt={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:st.Writer.create();for(const i of e.speakers)At.encode(i,t.uint32(10).fork()).ldelim();return t},decode(e,t){const i=e instanceof st.Reader?e:st.Reader.create(e);let n=void 0===t?i.len:i.pos+t;const r={speakers:[]};for(;i.pos<n;){const e=i.uint32();switch(e>>>3){case 1:if(10!==e)break;r.speakers.push(At.decode(i,i.uint32()));continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return r},fromJSON:e=>({speakers:Array.isArray(null==e?void 0:e.speakers)?e.speakers.map((e=>At.fromJSON(e))):[]}),toJSON(e){const t={};return e.speakers?t.speakers=e.speakers.map((e=>e?At.toJSON(e):void 0)):t.speakers=[],t},create:e=>Dt.fromPartial(null!=e?e:{}),fromPartial(e){var t;const i={speakers:[]};return i.speakers=(null===(t=e.speakers)||void 0===t?void 0:t.map((e=>At.fromPartial(e))))||[],i}};const At={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:st.Writer.create();return""!==e.sid&&t.uint32(10).string(e.sid),0!==e.level&&t.uint32(21).float(e.level),!0===e.active&&t.uint32(24).bool(e.active),t},decode(e,t){const i=e instanceof st.Reader?e:st.Reader.create(e);let n=void 0===t?i.len:i.pos+t;const r={sid:"",level:0,active:!1};for(;i.pos<n;){const e=i.uint32();switch(e>>>3){case 1:if(10!==e)break;r.sid=i.string();continue;case 2:if(21!==e)break;r.level=i.float();continue;case 3:if(24!==e)break;r.active=i.bool();continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return r},fromJSON:e=>({sid:qt(e.sid)?String(e.sid):"",level:qt(e.level)?Number(e.level):0,active:!!qt(e.active)&&Boolean(e.active)}),toJSON(e){const t={};return void 0!==e.sid&&(t.sid=e.sid),void 0!==e.level&&(t.level=e.level),void 0!==e.active&&(t.active=e.active),t},create:e=>At.fromPartial(null!=e?e:{}),fromPartial(e){var t,i,n;const r={sid:"",level:0,active:!1};return r.sid=null!==(t=e.sid)&&void 0!==t?t:"",r.level=null!==(i=e.level)&&void 0!==i?i:0,r.active=null!==(n=e.active)&&void 0!==n&&n,r}};function Ut(){return{participantSid:"",payload:new Uint8Array,destinationSids:[],topic:void 0}}const Mt={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:st.Writer.create();""!==e.participantSid&&t.uint32(10).string(e.participantSid),0!==e.payload.length&&t.uint32(18).bytes(e.payload);for(const i of e.destinationSids)t.uint32(26).string(i);return void 0!==e.topic&&t.uint32(34).string(e.topic),t},decode(e,t){const i=e instanceof st.Reader?e:st.Reader.create(e);let n=void 0===t?i.len:i.pos+t;const r=Ut();for(;i.pos<n;){const e=i.uint32();switch(e>>>3){case 1:if(10!==e)break;r.participantSid=i.string();continue;case 2:if(18!==e)break;r.payload=i.bytes();continue;case 3:if(26!==e)break;r.destinationSids.push(i.string());continue;case 4:if(34!==e)break;r.topic=i.string();continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return r},fromJSON:e=>({participantSid:qt(e.participantSid)?String(e.participantSid):"",payload:qt(e.payload)?Vt(e.payload):new Uint8Array,destinationSids:Array.isArray(null==e?void 0:e.destinationSids)?e.destinationSids.map((e=>String(e))):[],topic:qt(e.topic)?String(e.topic):void 0}),toJSON(e){const t={};return void 0!==e.participantSid&&(t.participantSid=e.participantSid),void 0!==e.payload&&(t.payload=function(e){if($t.Buffer)return $t.Buffer.from(e).toString("base64");{const t=[];return e.forEach((e=>{t.push(String.fromCharCode(e))})),$t.btoa(t.join(""))}}(void 0!==e.payload?e.payload:new Uint8Array)),e.destinationSids?t.destinationSids=e.destinationSids.map((e=>e)):t.destinationSids=[],void 0!==e.topic&&(t.topic=e.topic),t},create:e=>Mt.fromPartial(null!=e?e:{}),fromPartial(e){var t,i,n,r;const s=Ut();return s.participantSid=null!==(t=e.participantSid)&&void 0!==t?t:"",s.payload=null!==(i=e.payload)&&void 0!==i?i:new Uint8Array,s.destinationSids=(null===(n=e.destinationSids)||void 0===n?void 0:n.map((e=>e)))||[],s.topic=null!==(r=e.topic)&&void 0!==r?r:void 0,s}};const Lt={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:st.Writer.create();""!==e.participantSid&&t.uint32(10).string(e.participantSid);for(const i of e.trackSids)t.uint32(18).string(i);return t},decode(e,t){const i=e instanceof st.Reader?e:st.Reader.create(e);let n=void 0===t?i.len:i.pos+t;const r={participantSid:"",trackSids:[]};for(;i.pos<n;){const e=i.uint32();switch(e>>>3){case 1:if(10!==e)break;r.participantSid=i.string();continue;case 2:if(18!==e)break;r.trackSids.push(i.string());continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return r},fromJSON:e=>({participantSid:qt(e.participantSid)?String(e.participantSid):"",trackSids:Array.isArray(null==e?void 0:e.trackSids)?e.trackSids.map((e=>String(e))):[]}),toJSON(e){const t={};return void 0!==e.participantSid&&(t.participantSid=e.participantSid),e.trackSids?t.trackSids=e.trackSids.map((e=>e)):t.trackSids=[],t},create:e=>Lt.fromPartial(null!=e?e:{}),fromPartial(e){var t,i;const n={participantSid:"",trackSids:[]};return n.participantSid=null!==(t=e.participantSid)&&void 0!==t?t:"",n.trackSids=(null===(i=e.trackSids)||void 0===i?void 0:i.map((e=>e)))||[],n}};const _t={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:st.Writer.create();return 0!==e.edition&&t.uint32(8).int32(e.edition),""!==e.version&&t.uint32(18).string(e.version),0!==e.protocol&&t.uint32(24).int32(e.protocol),""!==e.region&&t.uint32(34).string(e.region),""!==e.nodeId&&t.uint32(42).string(e.nodeId),""!==e.debugInfo&&t.uint32(50).string(e.debugInfo),t},decode(e,t){const i=e instanceof st.Reader?e:st.Reader.create(e);let n=void 0===t?i.len:i.pos+t;const r={edition:0,version:"",protocol:0,region:"",nodeId:"",debugInfo:""};for(;i.pos<n;){const e=i.uint32();switch(e>>>3){case 1:if(8!==e)break;r.edition=i.int32();continue;case 2:if(18!==e)break;r.version=i.string();continue;case 3:if(24!==e)break;r.protocol=i.int32();continue;case 4:if(34!==e)break;r.region=i.string();continue;case 5:if(42!==e)break;r.nodeId=i.string();continue;case 6:if(50!==e)break;r.debugInfo=i.string();continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return r},fromJSON:e=>({edition:qt(e.edition)?St(e.edition):0,version:qt(e.version)?String(e.version):"",protocol:qt(e.protocol)?Number(e.protocol):0,region:qt(e.region)?String(e.region):"",nodeId:qt(e.nodeId)?String(e.nodeId):"",debugInfo:qt(e.debugInfo)?String(e.debugInfo):""}),toJSON(e){const t={};return void 0!==e.edition&&(t.edition=function(e){switch(e){case nt.Standard:return"Standard";case nt.Cloud:return"Cloud";case nt.UNRECOGNIZED:default:return"UNRECOGNIZED"}}(e.edition)),void 0!==e.version&&(t.version=e.version),void 0!==e.protocol&&(t.protocol=Math.round(e.protocol)),void 0!==e.region&&(t.region=e.region),void 0!==e.nodeId&&(t.nodeId=e.nodeId),void 0!==e.debugInfo&&(t.debugInfo=e.debugInfo),t},create:e=>_t.fromPartial(null!=e?e:{}),fromPartial(e){var t,i,n,r,s,o;const a={edition:0,version:"",protocol:0,region:"",nodeId:"",debugInfo:""};return a.edition=null!==(t=e.edition)&&void 0!==t?t:0,a.version=null!==(i=e.version)&&void 0!==i?i:"",a.protocol=null!==(n=e.protocol)&&void 0!==n?n:0,a.region=null!==(r=e.region)&&void 0!==r?r:"",a.nodeId=null!==(s=e.nodeId)&&void 0!==s?s:"",a.debugInfo=null!==(o=e.debugInfo)&&void 0!==o?o:"",a}};const xt={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:st.Writer.create();return 0!==e.sdk&&t.uint32(8).int32(e.sdk),""!==e.version&&t.uint32(18).string(e.version),0!==e.protocol&&t.uint32(24).int32(e.protocol),""!==e.os&&t.uint32(34).string(e.os),""!==e.osVersion&&t.uint32(42).string(e.osVersion),""!==e.deviceModel&&t.uint32(50).string(e.deviceModel),""!==e.browser&&t.uint32(58).string(e.browser),""!==e.browserVersion&&t.uint32(66).string(e.browserVersion),""!==e.address&&t.uint32(74).string(e.address),""!==e.network&&t.uint32(82).string(e.network),t},decode(e,t){const i=e instanceof st.Reader?e:st.Reader.create(e);let n=void 0===t?i.len:i.pos+t;const r={sdk:0,version:"",protocol:0,os:"",osVersion:"",deviceModel:"",browser:"",browserVersion:"",address:"",network:""};for(;i.pos<n;){const e=i.uint32();switch(e>>>3){case 1:if(8!==e)break;r.sdk=i.int32();continue;case 2:if(18!==e)break;r.version=i.string();continue;case 3:if(24!==e)break;r.protocol=i.int32();continue;case 4:if(34!==e)break;r.os=i.string();continue;case 5:if(42!==e)break;r.osVersion=i.string();continue;case 6:if(50!==e)break;r.deviceModel=i.string();continue;case 7:if(58!==e)break;r.browser=i.string();continue;case 8:if(66!==e)break;r.browserVersion=i.string();continue;case 9:if(74!==e)break;r.address=i.string();continue;case 10:if(82!==e)break;r.network=i.string();continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return r},fromJSON:e=>({sdk:qt(e.sdk)?Ct(e.sdk):0,version:qt(e.version)?String(e.version):"",protocol:qt(e.protocol)?Number(e.protocol):0,os:qt(e.os)?String(e.os):"",osVersion:qt(e.osVersion)?String(e.osVersion):"",deviceModel:qt(e.deviceModel)?String(e.deviceModel):"",browser:qt(e.browser)?String(e.browser):"",browserVersion:qt(e.browserVersion)?String(e.browserVersion):"",address:qt(e.address)?String(e.address):"",network:qt(e.network)?String(e.network):""}),toJSON(e){const t={};return void 0!==e.sdk&&(t.sdk=function(e){switch(e){case rt.UNKNOWN:return"UNKNOWN";case rt.JS:return"JS";case rt.SWIFT:return"SWIFT";case rt.ANDROID:return"ANDROID";case rt.FLUTTER:return"FLUTTER";case rt.GO:return"GO";case rt.UNITY:return"UNITY";case rt.REACT_NATIVE:return"REACT_NATIVE";case rt.RUST:return"RUST";case rt.UNRECOGNIZED:default:return"UNRECOGNIZED"}}(e.sdk)),void 0!==e.version&&(t.version=e.version),void 0!==e.protocol&&(t.protocol=Math.round(e.protocol)),void 0!==e.os&&(t.os=e.os),void 0!==e.osVersion&&(t.osVersion=e.osVersion),void 0!==e.deviceModel&&(t.deviceModel=e.deviceModel),void 0!==e.browser&&(t.browser=e.browser),void 0!==e.browserVersion&&(t.browserVersion=e.browserVersion),void 0!==e.address&&(t.address=e.address),void 0!==e.network&&(t.network=e.network),t},create:e=>xt.fromPartial(null!=e?e:{}),fromPartial(e){var t,i,n,r,s,o,a,c,d,u;const l={sdk:0,version:"",protocol:0,os:"",osVersion:"",deviceModel:"",browser:"",browserVersion:"",address:"",network:""};return l.sdk=null!==(t=e.sdk)&&void 0!==t?t:0,l.version=null!==(i=e.version)&&void 0!==i?i:"",l.protocol=null!==(n=e.protocol)&&void 0!==n?n:0,l.os=null!==(r=e.os)&&void 0!==r?r:"",l.osVersion=null!==(s=e.osVersion)&&void 0!==s?s:"",l.deviceModel=null!==(o=e.deviceModel)&&void 0!==o?o:"",l.browser=null!==(a=e.browser)&&void 0!==a?a:"",l.browserVersion=null!==(c=e.browserVersion)&&void 0!==c?c:"",l.address=null!==(d=e.address)&&void 0!==d?d:"",l.network=null!==(u=e.network)&&void 0!==u?u:"",l}};const Bt={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:st.Writer.create();return void 0!==e.video&&Jt.encode(e.video,t.uint32(10).fork()).ldelim(),void 0!==e.screen&&Jt.encode(e.screen,t.uint32(18).fork()).ldelim(),0!==e.resumeConnection&&t.uint32(24).int32(e.resumeConnection),void 0!==e.disabledCodecs&&Ft.encode(e.disabledCodecs,t.uint32(34).fork()).ldelim(),0!==e.forceRelay&&t.uint32(40).int32(e.forceRelay),t},decode(e,t){const i=e instanceof st.Reader?e:st.Reader.create(e);let n=void 0===t?i.len:i.pos+t;const r={video:void 0,screen:void 0,resumeConnection:0,disabledCodecs:void 0,forceRelay:0};for(;i.pos<n;){const e=i.uint32();switch(e>>>3){case 1:if(10!==e)break;r.video=Jt.decode(i,i.uint32());continue;case 2:if(18!==e)break;r.screen=Jt.decode(i,i.uint32());continue;case 3:if(24!==e)break;r.resumeConnection=i.int32();continue;case 4:if(34!==e)break;r.disabledCodecs=Ft.decode(i,i.uint32());continue;case 5:if(40!==e)break;r.forceRelay=i.int32();continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return r},fromJSON:e=>({video:qt(e.video)?Jt.fromJSON(e.video):void 0,screen:qt(e.screen)?Jt.fromJSON(e.screen):void 0,resumeConnection:qt(e.resumeConnection)?pt(e.resumeConnection):0,disabledCodecs:qt(e.disabledCodecs)?Ft.fromJSON(e.disabledCodecs):void 0,forceRelay:qt(e.forceRelay)?pt(e.forceRelay):0}),toJSON(e){const t={};return void 0!==e.video&&(t.video=e.video?Jt.toJSON(e.video):void 0),void 0!==e.screen&&(t.screen=e.screen?Jt.toJSON(e.screen):void 0),void 0!==e.resumeConnection&&(t.resumeConnection=mt(e.resumeConnection)),void 0!==e.disabledCodecs&&(t.disabledCodecs=e.disabledCodecs?Ft.toJSON(e.disabledCodecs):void 0),void 0!==e.forceRelay&&(t.forceRelay=mt(e.forceRelay)),t},create:e=>Bt.fromPartial(null!=e?e:{}),fromPartial(e){var t,i;const n={video:void 0,screen:void 0,resumeConnection:0,disabledCodecs:void 0,forceRelay:0};return n.video=void 0!==e.video&&null!==e.video?Jt.fromPartial(e.video):void 0,n.screen=void 0!==e.screen&&null!==e.screen?Jt.fromPartial(e.screen):void 0,n.resumeConnection=null!==(t=e.resumeConnection)&&void 0!==t?t:0,n.disabledCodecs=void 0!==e.disabledCodecs&&null!==e.disabledCodecs?Ft.fromPartial(e.disabledCodecs):void 0,n.forceRelay=null!==(i=e.forceRelay)&&void 0!==i?i:0,n}};const Jt={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:st.Writer.create();return 0!==e.hardwareEncoder&&t.uint32(8).int32(e.hardwareEncoder),t},decode(e,t){const i=e instanceof st.Reader?e:st.Reader.create(e);let n=void 0===t?i.len:i.pos+t;const r={hardwareEncoder:0};for(;i.pos<n;){const e=i.uint32();switch(e>>>3){case 1:if(8!==e)break;r.hardwareEncoder=i.int32();continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return r},fromJSON:e=>({hardwareEncoder:qt(e.hardwareEncoder)?pt(e.hardwareEncoder):0}),toJSON(e){const t={};return void 0!==e.hardwareEncoder&&(t.hardwareEncoder=mt(e.hardwareEncoder)),t},create:e=>Jt.fromPartial(null!=e?e:{}),fromPartial(e){var t;const i={hardwareEncoder:0};return i.hardwareEncoder=null!==(t=e.hardwareEncoder)&&void 0!==t?t:0,i}};const Ft={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:st.Writer.create();for(const i of e.codecs)Tt.encode(i,t.uint32(10).fork()).ldelim();for(const i of e.publish)Tt.encode(i,t.uint32(18).fork()).ldelim();return t},decode(e,t){const i=e instanceof st.Reader?e:st.Reader.create(e);let n=void 0===t?i.len:i.pos+t;const r={codecs:[],publish:[]};for(;i.pos<n;){const e=i.uint32();switch(e>>>3){case 1:if(10!==e)break;r.codecs.push(Tt.decode(i,i.uint32()));continue;case 2:if(18!==e)break;r.publish.push(Tt.decode(i,i.uint32()));continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return r},fromJSON:e=>({codecs:Array.isArray(null==e?void 0:e.codecs)?e.codecs.map((e=>Tt.fromJSON(e))):[],publish:Array.isArray(null==e?void 0:e.publish)?e.publish.map((e=>Tt.fromJSON(e))):[]}),toJSON(e){const t={};return e.codecs?t.codecs=e.codecs.map((e=>e?Tt.toJSON(e):void 0)):t.codecs=[],e.publish?t.publish=e.publish.map((e=>e?Tt.toJSON(e):void 0)):t.publish=[],t},create:e=>Ft.fromPartial(null!=e?e:{}),fromPartial(e){var t,i;const n={codecs:[],publish:[]};return n.codecs=(null===(t=e.codecs)||void 0===t?void 0:t.map((e=>Tt.fromPartial(e))))||[],n.publish=(null===(i=e.publish)||void 0===i?void 0:i.map((e=>Tt.fromPartial(e))))||[],n}};var $t=(()=>{if("undefined"!=typeof globalThis)return globalThis;if("undefined"!=typeof self)return self;if("undefined"!=typeof window)return window;if("undefined"!=typeof global)return global;throw"Unable to locate global object"})();function Vt(e){if($t.Buffer)return Uint8Array.from($t.Buffer.from(e,"base64"));{const t=$t.atob(e),i=new Uint8Array(t.length);for(let e=0;e<t.length;++e)i[e]=t.charCodeAt(e);return i}}function jt(e){if(e.gt(Number.MAX_SAFE_INTEGER))throw new $t.Error("Value is larger than Number.MAX_SAFE_INTEGER");return e.toNumber()}function qt(e){return null!=e}st.util.Long!==_&&(st.util.Long=_,st.configure());const Wt=7e3,Gt=[0,300,1200,2700,4800,Wt,Wt,Wt,Wt,Wt];class Kt{constructor(e){this._retryDelays=void 0!==e?[...e]:Gt}nextRetryDelayInMs(e){if(e.retryCount>=this._retryDelays.length)return null;const t=this._retryDelays[e.retryCount];return e.retryCount<=1?t:t+1e3*Math.random()}}function Qt(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{c(n.next(e))}catch(e){s(e)}}function a(e){try{c(n.throw(e))}catch(e){s(e)}}function c(e){e.done?r(e.value):function(e){return e instanceof i?e:new i((function(t){t(e)}))}(e.value).then(o,a)}c((n=n.apply(e,t||[])).next())}))}function Ht(e){var t="function"==typeof Symbol&&Symbol.iterator,i=t&&e[t],n=0;if(i)return i.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function Zt(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t,i=e[Symbol.asyncIterator];return i?i.call(e):(e=Ht(e),t={},n("next"),n("throw"),n("return"),t[Symbol.asyncIterator]=function(){return this},t);function n(i){t[i]=e[i]&&function(t){return new Promise((function(n,r){(function(e,t,i,n){Promise.resolve(n).then((function(t){e({value:t,done:i})}),t)})(n,r,(t=e[i](t)).done,t.value)}))}}}var zt={exports:{}};!function(e){var t=Object.prototype.hasOwnProperty,i="~";function n(){}function r(e,t,i){this.fn=e,this.context=t,this.once=i||!1}function s(e,t,n,s,o){if("function"!=typeof n)throw new TypeError("The listener must be a function");var a=new r(n,s||e,o),c=i?i+t:t;return e._events[c]?e._events[c].fn?e._events[c]=[e._events[c],a]:e._events[c].push(a):(e._events[c]=a,e._eventsCount++),e}function o(e,t){0==--e._eventsCount?e._events=new n:delete e._events[t]}function a(){this._events=new n,this._eventsCount=0}Object.create&&(n.prototype=Object.create(null),(new n).__proto__||(i=!1)),a.prototype.eventNames=function(){var e,n,r=[];if(0===this._eventsCount)return r;for(n in e=this._events)t.call(e,n)&&r.push(i?n.slice(1):n);return Object.getOwnPropertySymbols?r.concat(Object.getOwnPropertySymbols(e)):r},a.prototype.listeners=function(e){var t=i?i+e:e,n=this._events[t];if(!n)return[];if(n.fn)return[n.fn];for(var r=0,s=n.length,o=new Array(s);r<s;r++)o[r]=n[r].fn;return o},a.prototype.listenerCount=function(e){var t=i?i+e:e,n=this._events[t];return n?n.fn?1:n.length:0},a.prototype.emit=function(e,t,n,r,s,o){var a=i?i+e:e;if(!this._events[a])return!1;var c,d,u=this._events[a],l=arguments.length;if(u.fn){switch(u.once&&this.removeListener(e,u.fn,void 0,!0),l){case 1:return u.fn.call(u.context),!0;case 2:return u.fn.call(u.context,t),!0;case 3:return u.fn.call(u.context,t,n),!0;case 4:return u.fn.call(u.context,t,n,r),!0;case 5:return u.fn.call(u.context,t,n,r,s),!0;case 6:return u.fn.call(u.context,t,n,r,s,o),!0}for(d=1,c=new Array(l-1);d<l;d++)c[d-1]=arguments[d];u.fn.apply(u.context,c)}else{var h,p=u.length;for(d=0;d<p;d++)switch(u[d].once&&this.removeListener(e,u[d].fn,void 0,!0),l){case 1:u[d].fn.call(u[d].context);break;case 2:u[d].fn.call(u[d].context,t);break;case 3:u[d].fn.call(u[d].context,t,n);break;case 4:u[d].fn.call(u[d].context,t,n,r);break;default:if(!c)for(h=1,c=new Array(l-1);h<l;h++)c[h-1]=arguments[h];u[d].fn.apply(u[d].context,c)}}return!0},a.prototype.on=function(e,t,i){return s(this,e,t,i,!1)},a.prototype.once=function(e,t,i){return s(this,e,t,i,!0)},a.prototype.removeListener=function(e,t,n,r){var s=i?i+e:e;if(!this._events[s])return this;if(!t)return o(this,s),this;var a=this._events[s];if(a.fn)a.fn!==t||r&&!a.once||n&&a.context!==n||o(this,s);else{for(var c=0,d=[],u=a.length;c<u;c++)(a[c].fn!==t||r&&!a[c].once||n&&a[c].context!==n)&&d.push(a[c]);d.length?this._events[s]=1===d.length?d[0]:d:o(this,s)}return this},a.prototype.removeAllListeners=function(e){var t;return e?(t=i?i+e:e,this._events[t]&&o(this,t)):(this._events=new n,this._eventsCount=0),this},a.prototype.off=a.prototype.removeListener,a.prototype.addListener=a.prototype.on,a.prefixed=i,a.EventEmitter=a,e.exports=a}(zt);var Yt=n(zt.exports);let Xt=!0,ei=!0;function ti(e,t,i){const n=e.match(t);return n&&n.length>=i&&parseInt(n[i],10)}function ii(e,t,i){if(!e.RTCPeerConnection)return;const n=e.RTCPeerConnection.prototype,r=n.addEventListener;n.addEventListener=function(e,n){if(e!==t)return r.apply(this,arguments);const s=e=>{const t=i(e);t&&(n.handleEvent?n.handleEvent(t):n(t))};return this._eventMap=this._eventMap||{},this._eventMap[t]||(this._eventMap[t]=new Map),this._eventMap[t].set(n,s),r.apply(this,[e,s])};const s=n.removeEventListener;n.removeEventListener=function(e,i){if(e!==t||!this._eventMap||!this._eventMap[t])return s.apply(this,arguments);if(!this._eventMap[t].has(i))return s.apply(this,arguments);const n=this._eventMap[t].get(i);return this._eventMap[t].delete(i),0===this._eventMap[t].size&&delete this._eventMap[t],0===Object.keys(this._eventMap).length&&delete this._eventMap,s.apply(this,[e,n])},Object.defineProperty(n,"on"+t,{get(){return this["_on"+t]},set(e){this["_on"+t]&&(this.removeEventListener(t,this["_on"+t]),delete this["_on"+t]),e&&this.addEventListener(t,this["_on"+t]=e)},enumerable:!0,configurable:!0})}function ni(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(Xt=e,e?"adapter.js logging disabled":"adapter.js logging enabled")}function ri(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(ei=!e,"adapter.js deprecation warnings "+(e?"disabled":"enabled"))}function si(){if("object"==typeof window){if(Xt)return;"undefined"!=typeof console&&"function"==typeof console.log&&console.log.apply(console,arguments)}}function oi(e,t){ei&&console.warn(e+" is deprecated, please use "+t+" instead.")}function ai(e){return"[object Object]"===Object.prototype.toString.call(e)}function ci(e){return ai(e)?Object.keys(e).reduce((function(t,i){const n=ai(e[i]),r=n?ci(e[i]):e[i],s=n&&!Object.keys(r).length;return void 0===r||s?t:Object.assign(t,{[i]:r})}),{}):e}function di(e,t,i){t&&!i.has(t.id)&&(i.set(t.id,t),Object.keys(t).forEach((n=>{n.endsWith("Id")?di(e,e.get(t[n]),i):n.endsWith("Ids")&&t[n].forEach((t=>{di(e,e.get(t),i)}))})))}function ui(e,t,i){const n=i?"outbound-rtp":"inbound-rtp",r=new Map;if(null===t)return r;const s=[];return e.forEach((e=>{"track"===e.type&&e.trackIdentifier===t.id&&s.push(e)})),s.forEach((t=>{e.forEach((i=>{i.type===n&&i.trackId===t.id&&di(e,i,r)}))})),r}const li=si;function hi(e,t){const i=e&&e.navigator;if(!i.mediaDevices)return;const n=function(e){if("object"!=typeof e||e.mandatory||e.optional)return e;const t={};return Object.keys(e).forEach((i=>{if("require"===i||"advanced"===i||"mediaSource"===i)return;const n="object"==typeof e[i]?e[i]:{ideal:e[i]};void 0!==n.exact&&"number"==typeof n.exact&&(n.min=n.max=n.exact);const r=function(e,t){return e?e+t.charAt(0).toUpperCase()+t.slice(1):"deviceId"===t?"sourceId":t};if(void 0!==n.ideal){t.optional=t.optional||[];let e={};"number"==typeof n.ideal?(e[r("min",i)]=n.ideal,t.optional.push(e),e={},e[r("max",i)]=n.ideal,t.optional.push(e)):(e[r("",i)]=n.ideal,t.optional.push(e))}void 0!==n.exact&&"number"!=typeof n.exact?(t.mandatory=t.mandatory||{},t.mandatory[r("",i)]=n.exact):["min","max"].forEach((e=>{void 0!==n[e]&&(t.mandatory=t.mandatory||{},t.mandatory[r(e,i)]=n[e])}))})),e.advanced&&(t.optional=(t.optional||[]).concat(e.advanced)),t},r=function(e,r){if(t.version>=61)return r(e);if((e=JSON.parse(JSON.stringify(e)))&&"object"==typeof e.audio){const t=function(e,t,i){t in e&&!(i in e)&&(e[i]=e[t],delete e[t])};t((e=JSON.parse(JSON.stringify(e))).audio,"autoGainControl","googAutoGainControl"),t(e.audio,"noiseSuppression","googNoiseSuppression"),e.audio=n(e.audio)}if(e&&"object"==typeof e.video){let s=e.video.facingMode;s=s&&("object"==typeof s?s:{ideal:s});const o=t.version<66;if(s&&("user"===s.exact||"environment"===s.exact||"user"===s.ideal||"environment"===s.ideal)&&(!i.mediaDevices.getSupportedConstraints||!i.mediaDevices.getSupportedConstraints().facingMode||o)){let t;if(delete e.video.facingMode,"environment"===s.exact||"environment"===s.ideal?t=["back","rear"]:"user"!==s.exact&&"user"!==s.ideal||(t=["front"]),t)return i.mediaDevices.enumerateDevices().then((i=>{let o=(i=i.filter((e=>"videoinput"===e.kind))).find((e=>t.some((t=>e.label.toLowerCase().includes(t)))));return!o&&i.length&&t.includes("back")&&(o=i[i.length-1]),o&&(e.video.deviceId=s.exact?{exact:o.deviceId}:{ideal:o.deviceId}),e.video=n(e.video),li("chrome: "+JSON.stringify(e)),r(e)}))}e.video=n(e.video)}return li("chrome: "+JSON.stringify(e)),r(e)},s=function(e){return t.version>=64?e:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[e.name]||e.name,message:e.message,constraint:e.constraint||e.constraintName,toString(){return this.name+(this.message&&": ")+this.message}}};if(i.getUserMedia=function(e,t,n){r(e,(e=>{i.webkitGetUserMedia(e,t,(e=>{n&&n(s(e))}))}))}.bind(i),i.mediaDevices.getUserMedia){const e=i.mediaDevices.getUserMedia.bind(i.mediaDevices);i.mediaDevices.getUserMedia=function(t){return r(t,(t=>e(t).then((e=>{if(t.audio&&!e.getAudioTracks().length||t.video&&!e.getVideoTracks().length)throw e.getTracks().forEach((e=>{e.stop()})),new DOMException("","NotFoundError");return e}),(e=>Promise.reject(s(e))))))}}}function pi(e){e.MediaStream=e.MediaStream||e.webkitMediaStream}function mi(e){if("object"==typeof e&&e.RTCPeerConnection&&!("ontrack"in e.RTCPeerConnection.prototype)){Object.defineProperty(e.RTCPeerConnection.prototype,"ontrack",{get(){return this._ontrack},set(e){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=e)},enumerable:!0,configurable:!0});const t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=t=>{t.stream.addEventListener("addtrack",(i=>{let n;n=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find((e=>e.track&&e.track.id===i.track.id)):{track:i.track};const r=new Event("track");r.track=i.track,r.receiver=n,r.transceiver={receiver:n},r.streams=[t.stream],this.dispatchEvent(r)})),t.stream.getTracks().forEach((i=>{let n;n=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find((e=>e.track&&e.track.id===i.id)):{track:i};const r=new Event("track");r.track=i,r.receiver=n,r.transceiver={receiver:n},r.streams=[t.stream],this.dispatchEvent(r)}))},this.addEventListener("addstream",this._ontrackpoly)),t.apply(this,arguments)}}else ii(e,"track",(e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e)))}function fi(e){if("object"==typeof e&&e.RTCPeerConnection&&!("getSenders"in e.RTCPeerConnection.prototype)&&"createDTMFSender"in e.RTCPeerConnection.prototype){const t=function(e,t){return{track:t,get dtmf(){return void 0===this._dtmf&&("audio"===t.kind?this._dtmf=e.createDTMFSender(t):this._dtmf=null),this._dtmf},_pc:e}};if(!e.RTCPeerConnection.prototype.getSenders){e.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};const i=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,n){let r=i.apply(this,arguments);return r||(r=t(this,e),this._senders.push(r)),r};const n=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){n.apply(this,arguments);const t=this._senders.indexOf(e);-1!==t&&this._senders.splice(t,1)}}const i=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._senders=this._senders||[],i.apply(this,[e]),e.getTracks().forEach((e=>{this._senders.push(t(this,e))}))};const n=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){this._senders=this._senders||[],n.apply(this,[e]),e.getTracks().forEach((e=>{const t=this._senders.find((t=>t.track===e));t&&this._senders.splice(this._senders.indexOf(t),1)}))}}else if("object"==typeof e&&e.RTCPeerConnection&&"getSenders"in e.RTCPeerConnection.prototype&&"createDTMFSender"in e.RTCPeerConnection.prototype&&e.RTCRtpSender&&!("dtmf"in e.RTCRtpSender.prototype)){const t=e.RTCPeerConnection.prototype.getSenders;e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e},Object.defineProperty(e.RTCRtpSender.prototype,"dtmf",{get(){return void 0===this._dtmf&&("audio"===this.track.kind?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}}function vi(e){if(!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){const[e,i,n]=arguments;if(arguments.length>0&&"function"==typeof e)return t.apply(this,arguments);if(0===t.length&&(0===arguments.length||"function"!=typeof e))return t.apply(this,[]);const r=function(e){const t={};return e.result().forEach((e=>{const i={id:e.id,timestamp:e.timestamp,type:{localcandidate:"local-candidate",remotecandidate:"remote-candidate"}[e.type]||e.type};e.names().forEach((t=>{i[t]=e.stat(t)})),t[i.id]=i})),t},s=function(e){return new Map(Object.keys(e).map((t=>[t,e[t]])))};if(arguments.length>=2){const n=function(e){i(s(r(e)))};return t.apply(this,[n,e])}return new Promise(((e,i)=>{t.apply(this,[function(t){e(s(r(t)))},i])})).then(i,n)}}function gi(e){if(!("object"==typeof e&&e.RTCPeerConnection&&e.RTCRtpSender&&e.RTCRtpReceiver))return;if(!("getStats"in e.RTCRtpSender.prototype)){const t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e});const i=e.RTCPeerConnection.prototype.addTrack;i&&(e.RTCPeerConnection.prototype.addTrack=function(){const e=i.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){const e=this;return this._pc.getStats().then((t=>ui(t,e.track,!0)))}}if(!("getStats"in e.RTCRtpReceiver.prototype)){const t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e}),ii(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){const e=this;return this._pc.getStats().then((t=>ui(t,e.track,!1)))}}if(!("getStats"in e.RTCRtpSender.prototype)||!("getStats"in e.RTCRtpReceiver.prototype))return;const t=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof e.MediaStreamTrack){const e=arguments[0];let t,i,n;return this.getSenders().forEach((i=>{i.track===e&&(t?n=!0:t=i)})),this.getReceivers().forEach((t=>(t.track===e&&(i?n=!0:i=t),t.track===e))),n||t&&i?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):t?t.getStats():i?i.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return t.apply(this,arguments)}}function bi(e){e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map((e=>this._shimmedLocalStreams[e][0]))};const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,i){if(!i)return t.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};const n=t.apply(this,arguments);return this._shimmedLocalStreams[i.id]?-1===this._shimmedLocalStreams[i.id].indexOf(n)&&this._shimmedLocalStreams[i.id].push(n):this._shimmedLocalStreams[i.id]=[i,n],n};const i=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._shimmedLocalStreams=this._shimmedLocalStreams||{},e.getTracks().forEach((e=>{if(this.getSenders().find((t=>t.track===e)))throw new DOMException("Track already exists.","InvalidAccessError")}));const t=this.getSenders();i.apply(this,arguments);const n=this.getSenders().filter((e=>-1===t.indexOf(e)));this._shimmedLocalStreams[e.id]=[e].concat(n)};const n=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[e.id],n.apply(this,arguments)};const r=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},e&&Object.keys(this._shimmedLocalStreams).forEach((t=>{const i=this._shimmedLocalStreams[t].indexOf(e);-1!==i&&this._shimmedLocalStreams[t].splice(i,1),1===this._shimmedLocalStreams[t].length&&delete this._shimmedLocalStreams[t]})),r.apply(this,arguments)}}function ki(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return bi(e);const i=e.RTCPeerConnection.prototype.getLocalStreams;e.RTCPeerConnection.prototype.getLocalStreams=function(){const e=i.apply(this);return this._reverseStreams=this._reverseStreams||{},e.map((e=>this._reverseStreams[e.id]))};const n=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(t){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},t.getTracks().forEach((e=>{if(this.getSenders().find((t=>t.track===e)))throw new DOMException("Track already exists.","InvalidAccessError")})),!this._reverseStreams[t.id]){const i=new e.MediaStream(t.getTracks());this._streams[t.id]=i,this._reverseStreams[i.id]=t,t=i}n.apply(this,[t])};const r=e.RTCPeerConnection.prototype.removeStream;function s(e,t){let i=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((t=>{const n=e._reverseStreams[t],r=e._streams[n.id];i=i.replace(new RegExp(r.id,"g"),n.id)})),new RTCSessionDescription({type:t.type,sdp:i})}e.RTCPeerConnection.prototype.removeStream=function(e){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},r.apply(this,[this._streams[e.id]||e]),delete this._reverseStreams[this._streams[e.id]?this._streams[e.id].id:e.id],delete this._streams[e.id]},e.RTCPeerConnection.prototype.addTrack=function(t,i){if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");const n=[].slice.call(arguments,1);if(1!==n.length||!n[0].getTracks().find((e=>e===t)))throw new DOMException("The adapter.js addTrack polyfill only supports a single stream which is associated with the specified track.","NotSupportedError");if(this.getSenders().find((e=>e.track===t)))throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};const r=this._streams[i.id];if(r)r.addTrack(t),Promise.resolve().then((()=>{this.dispatchEvent(new Event("negotiationneeded"))}));else{const n=new e.MediaStream([t]);this._streams[i.id]=n,this._reverseStreams[n.id]=i,this.addStream(n)}return this.getSenders().find((e=>e.track===t))},["createOffer","createAnswer"].forEach((function(t){const i=e.RTCPeerConnection.prototype[t],n={[t](){const e=arguments;return arguments.length&&"function"==typeof arguments[0]?i.apply(this,[t=>{const i=s(this,t);e[0].apply(null,[i])},t=>{e[1]&&e[1].apply(null,t)},arguments[2]]):i.apply(this,arguments).then((e=>s(this,e)))}};e.RTCPeerConnection.prototype[t]=n[t]}));const o=e.RTCPeerConnection.prototype.setLocalDescription;e.RTCPeerConnection.prototype.setLocalDescription=function(){return arguments.length&&arguments[0].type?(arguments[0]=function(e,t){let i=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((t=>{const n=e._reverseStreams[t],r=e._streams[n.id];i=i.replace(new RegExp(n.id,"g"),r.id)})),new RTCSessionDescription({type:t.type,sdp:i})}(this,arguments[0]),o.apply(this,arguments)):o.apply(this,arguments)};const a=Object.getOwnPropertyDescriptor(e.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(e.RTCPeerConnection.prototype,"localDescription",{get(){const e=a.get.apply(this);return""===e.type?e:s(this,e)}}),e.RTCPeerConnection.prototype.removeTrack=function(e){if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!e._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(!(e._pc===this))throw new DOMException("Sender was not created by this connection.","InvalidAccessError");let t;this._streams=this._streams||{},Object.keys(this._streams).forEach((i=>{this._streams[i].getTracks().find((t=>e.track===t))&&(t=this._streams[i])})),t&&(1===t.getTracks().length?this.removeStream(this._reverseStreams[t.id]):t.removeTrack(e.track),this.dispatchEvent(new Event("negotiationneeded")))}}function yi(e,t){!e.RTCPeerConnection&&e.webkitRTCPeerConnection&&(e.RTCPeerConnection=e.webkitRTCPeerConnection),e.RTCPeerConnection&&t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach((function(t){const i=e.RTCPeerConnection.prototype[t],n={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),i.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=n[t]}))}function Si(e,t){ii(e,"negotiationneeded",(e=>{const i=e.target;if(!(t.version<72||i.getConfiguration&&"plan-b"===i.getConfiguration().sdpSemantics)||"stable"===i.signalingState)return e}))}var Ci=Object.freeze({__proto__:null,fixNegotiationNeeded:Si,shimAddTrackRemoveTrack:ki,shimAddTrackRemoveTrackWithNative:bi,shimGetDisplayMedia:function(e,t){e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||e.navigator.mediaDevices&&("function"==typeof t?e.navigator.mediaDevices.getDisplayMedia=function(i){return t(i).then((t=>{const n=i.video&&i.video.width,r=i.video&&i.video.height,s=i.video&&i.video.frameRate;return i.video={mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:t,maxFrameRate:s||3}},n&&(i.video.mandatory.maxWidth=n),r&&(i.video.mandatory.maxHeight=r),e.navigator.mediaDevices.getUserMedia(i)}))}:console.error("shimGetDisplayMedia: getSourceId argument is not a function"))},shimGetSendersWithDtmf:fi,shimGetStats:vi,shimGetUserMedia:hi,shimMediaStream:pi,shimOnTrack:mi,shimPeerConnection:yi,shimSenderReceiverGetStats:gi});function Ei(e,t){const i=e&&e.navigator,n=e&&e.MediaStreamTrack;if(i.getUserMedia=function(e,t,n){oi("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),i.mediaDevices.getUserMedia(e).then(t,n)},!(t.version>55&&"autoGainControl"in i.mediaDevices.getSupportedConstraints())){const e=function(e,t,i){t in e&&!(i in e)&&(e[i]=e[t],delete e[t])},t=i.mediaDevices.getUserMedia.bind(i.mediaDevices);if(i.mediaDevices.getUserMedia=function(i){return"object"==typeof i&&"object"==typeof i.audio&&(i=JSON.parse(JSON.stringify(i)),e(i.audio,"autoGainControl","mozAutoGainControl"),e(i.audio,"noiseSuppression","mozNoiseSuppression")),t(i)},n&&n.prototype.getSettings){const t=n.prototype.getSettings;n.prototype.getSettings=function(){const i=t.apply(this,arguments);return e(i,"mozAutoGainControl","autoGainControl"),e(i,"mozNoiseSuppression","noiseSuppression"),i}}if(n&&n.prototype.applyConstraints){const t=n.prototype.applyConstraints;n.prototype.applyConstraints=function(i){return"audio"===this.kind&&"object"==typeof i&&(i=JSON.parse(JSON.stringify(i)),e(i,"autoGainControl","mozAutoGainControl"),e(i,"noiseSuppression","mozNoiseSuppression")),t.apply(this,[i])}}}}function Ti(e){"object"==typeof e&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function Pi(e,t){if("object"!=typeof e||!e.RTCPeerConnection&&!e.mozRTCPeerConnection)return;!e.RTCPeerConnection&&e.mozRTCPeerConnection&&(e.RTCPeerConnection=e.mozRTCPeerConnection),t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach((function(t){const i=e.RTCPeerConnection.prototype[t],n={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),i.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=n[t]}));const i={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},n=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){const[e,r,s]=arguments;return n.apply(this,[e||null]).then((e=>{if(t.version<53&&!r)try{e.forEach((e=>{e.type=i[e.type]||e.type}))}catch(t){if("TypeError"!==t.name)throw t;e.forEach(((t,n)=>{e.set(n,Object.assign({},t,{type:i[t.type]||t.type}))}))}return e})).then(r,s)}}function wi(e){if("object"!=typeof e||!e.RTCPeerConnection||!e.RTCRtpSender)return;if(e.RTCRtpSender&&"getStats"in e.RTCRtpSender.prototype)return;const t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e});const i=e.RTCPeerConnection.prototype.addTrack;i&&(e.RTCPeerConnection.prototype.addTrack=function(){const e=i.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function Ri(e){if("object"!=typeof e||!e.RTCPeerConnection||!e.RTCRtpSender)return;if(e.RTCRtpSender&&"getStats"in e.RTCRtpReceiver.prototype)return;const t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e}),ii(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function Ni(e){e.RTCPeerConnection&&!("removeStream"in e.RTCPeerConnection.prototype)&&(e.RTCPeerConnection.prototype.removeStream=function(e){oi("removeStream","removeTrack"),this.getSenders().forEach((t=>{t.track&&e.getTracks().includes(t.track)&&this.removeTrack(t)}))})}function Oi(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)}function Ii(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.addTransceiver;t&&(e.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let e=arguments[1]&&arguments[1].sendEncodings;void 0===e&&(e=[]),e=[...e];const i=e.length>0;i&&e.forEach((e=>{if("rid"in e){if(!/^[a-z0-9]{0,16}$/i.test(e.rid))throw new TypeError("Invalid RID value provided.")}if("scaleResolutionDownBy"in e&&!(parseFloat(e.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in e&&!(parseFloat(e.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")}));const n=t.apply(this,arguments);if(i){const{sender:t}=n,i=t.getParameters();(!("encodings"in i)||1===i.encodings.length&&0===Object.keys(i.encodings[0]).length)&&(i.encodings=e,t.sendEncodings=e,this.setParametersPromises.push(t.setParameters(i).then((()=>{delete t.sendEncodings})).catch((()=>{delete t.sendEncodings}))))}return n})}function Di(e){if("object"!=typeof e||!e.RTCRtpSender)return;const t=e.RTCRtpSender.prototype.getParameters;t&&(e.RTCRtpSender.prototype.getParameters=function(){const e=t.apply(this,arguments);return"encodings"in e||(e.encodings=[].concat(this.sendEncodings||[{}])),e})}function Ai(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then((()=>t.apply(this,arguments))).finally((()=>{this.setParametersPromises=[]})):t.apply(this,arguments)}}function Ui(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.createAnswer;e.RTCPeerConnection.prototype.createAnswer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then((()=>t.apply(this,arguments))).finally((()=>{this.setParametersPromises=[]})):t.apply(this,arguments)}}var Mi=Object.freeze({__proto__:null,shimAddTransceiver:Ii,shimCreateAnswer:Ui,shimCreateOffer:Ai,shimGetDisplayMedia:function(e,t){e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||e.navigator.mediaDevices&&(e.navigator.mediaDevices.getDisplayMedia=function(i){if(!i||!i.video){const e=new DOMException("getDisplayMedia without video constraints is undefined");return e.name="NotFoundError",e.code=8,Promise.reject(e)}return!0===i.video?i.video={mediaSource:t}:i.video.mediaSource=t,e.navigator.mediaDevices.getUserMedia(i)})},shimGetParameters:Di,shimGetUserMedia:Ei,shimOnTrack:Ti,shimPeerConnection:Pi,shimRTCDataChannel:Oi,shimReceiverGetStats:Ri,shimRemoveStream:Ni,shimSenderGetStats:wi});function Li(e){if("object"==typeof e&&e.RTCPeerConnection){if("getLocalStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in e.RTCPeerConnection.prototype)){const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addStream=function(e){this._localStreams||(this._localStreams=[]),this._localStreams.includes(e)||this._localStreams.push(e),e.getAudioTracks().forEach((i=>t.call(this,i,e))),e.getVideoTracks().forEach((i=>t.call(this,i,e)))},e.RTCPeerConnection.prototype.addTrack=function(e){for(var i=arguments.length,n=new Array(i>1?i-1:0),r=1;r<i;r++)n[r-1]=arguments[r];return n&&n.forEach((e=>{this._localStreams?this._localStreams.includes(e)||this._localStreams.push(e):this._localStreams=[e]})),t.apply(this,arguments)}}"removeStream"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.removeStream=function(e){this._localStreams||(this._localStreams=[]);const t=this._localStreams.indexOf(e);if(-1===t)return;this._localStreams.splice(t,1);const i=e.getTracks();this.getSenders().forEach((e=>{i.includes(e.track)&&this.removeTrack(e)}))})}}function _i(e){if("object"==typeof e&&e.RTCPeerConnection&&("getRemoteStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!("onaddstream"in e.RTCPeerConnection.prototype))){Object.defineProperty(e.RTCPeerConnection.prototype,"onaddstream",{get(){return this._onaddstream},set(e){this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=e),this.addEventListener("track",this._onaddstreampoly=e=>{e.streams.forEach((e=>{if(this._remoteStreams||(this._remoteStreams=[]),this._remoteStreams.includes(e))return;this._remoteStreams.push(e);const t=new Event("addstream");t.stream=e,this.dispatchEvent(t)}))})}});const t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){const e=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(t){t.streams.forEach((t=>{if(e._remoteStreams||(e._remoteStreams=[]),e._remoteStreams.indexOf(t)>=0)return;e._remoteStreams.push(t);const i=new Event("addstream");i.stream=t,e.dispatchEvent(i)}))}),t.apply(e,arguments)}}}function xi(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype,i=t.createOffer,n=t.createAnswer,r=t.setLocalDescription,s=t.setRemoteDescription,o=t.addIceCandidate;t.createOffer=function(e,t){const n=arguments.length>=2?arguments[2]:arguments[0],r=i.apply(this,[n]);return t?(r.then(e,t),Promise.resolve()):r},t.createAnswer=function(e,t){const i=arguments.length>=2?arguments[2]:arguments[0],r=n.apply(this,[i]);return t?(r.then(e,t),Promise.resolve()):r};let a=function(e,t,i){const n=r.apply(this,[e]);return i?(n.then(t,i),Promise.resolve()):n};t.setLocalDescription=a,a=function(e,t,i){const n=s.apply(this,[e]);return i?(n.then(t,i),Promise.resolve()):n},t.setRemoteDescription=a,a=function(e,t,i){const n=o.apply(this,[e]);return i?(n.then(t,i),Promise.resolve()):n},t.addIceCandidate=a}function Bi(e){const t=e&&e.navigator;if(t.mediaDevices&&t.mediaDevices.getUserMedia){const e=t.mediaDevices,i=e.getUserMedia.bind(e);t.mediaDevices.getUserMedia=e=>i(Ji(e))}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=function(e,i,n){t.mediaDevices.getUserMedia(e).then(i,n)}.bind(t))}function Ji(e){return e&&void 0!==e.video?Object.assign({},e,{video:ci(e.video)}):e}function Fi(e){if(!e.RTCPeerConnection)return;const t=e.RTCPeerConnection;e.RTCPeerConnection=function(e,i){if(e&&e.iceServers){const t=[];for(let i=0;i<e.iceServers.length;i++){let n=e.iceServers[i];void 0===n.urls&&n.url?(oi("RTCIceServer.url","RTCIceServer.urls"),n=JSON.parse(JSON.stringify(n)),n.urls=n.url,delete n.url,t.push(n)):t.push(e.iceServers[i])}e.iceServers=t}return new t(e,i)},e.RTCPeerConnection.prototype=t.prototype,"generateCertificate"in t&&Object.defineProperty(e.RTCPeerConnection,"generateCertificate",{get:()=>t.generateCertificate})}function $i(e){"object"==typeof e&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function Vi(e){const t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(e){if(e){void 0!==e.offerToReceiveAudio&&(e.offerToReceiveAudio=!!e.offerToReceiveAudio);const t=this.getTransceivers().find((e=>"audio"===e.receiver.track.kind));!1===e.offerToReceiveAudio&&t?"sendrecv"===t.direction?t.setDirection?t.setDirection("sendonly"):t.direction="sendonly":"recvonly"===t.direction&&(t.setDirection?t.setDirection("inactive"):t.direction="inactive"):!0!==e.offerToReceiveAudio||t||this.addTransceiver("audio",{direction:"recvonly"}),void 0!==e.offerToReceiveVideo&&(e.offerToReceiveVideo=!!e.offerToReceiveVideo);const i=this.getTransceivers().find((e=>"video"===e.receiver.track.kind));!1===e.offerToReceiveVideo&&i?"sendrecv"===i.direction?i.setDirection?i.setDirection("sendonly"):i.direction="sendonly":"recvonly"===i.direction&&(i.setDirection?i.setDirection("inactive"):i.direction="inactive"):!0!==e.offerToReceiveVideo||i||this.addTransceiver("video",{direction:"recvonly"})}return t.apply(this,arguments)}}function ji(e){"object"!=typeof e||e.AudioContext||(e.AudioContext=e.webkitAudioContext)}var qi=Object.freeze({__proto__:null,shimAudioContext:ji,shimCallbacksAPI:xi,shimConstraints:Ji,shimCreateOfferLegacy:Vi,shimGetUserMedia:Bi,shimLocalStreamsAPI:Li,shimRTCIceServerUrls:Fi,shimRemoteStreamsAPI:_i,shimTrackEventTransceiver:$i}),Wi={exports:{}};!function(e){const t={generateIdentifier:function(){return Math.random().toString(36).substring(2,12)}};t.localCName=t.generateIdentifier(),t.splitLines=function(e){return e.trim().split("\n").map((e=>e.trim()))},t.splitSections=function(e){return e.split("\nm=").map(((e,t)=>(t>0?"m="+e:e).trim()+"\r\n"))},t.getDescription=function(e){const i=t.splitSections(e);return i&&i[0]},t.getMediaSections=function(e){const i=t.splitSections(e);return i.shift(),i},t.matchPrefix=function(e,i){return t.splitLines(e).filter((e=>0===e.indexOf(i)))},t.parseCandidate=function(e){let t;t=0===e.indexOf("a=candidate:")?e.substring(12).split(" "):e.substring(10).split(" ");const i={foundation:t[0],component:{1:"rtp",2:"rtcp"}[t[1]]||t[1],protocol:t[2].toLowerCase(),priority:parseInt(t[3],10),ip:t[4],address:t[4],port:parseInt(t[5],10),type:t[7]};for(let e=8;e<t.length;e+=2)switch(t[e]){case"raddr":i.relatedAddress=t[e+1];break;case"rport":i.relatedPort=parseInt(t[e+1],10);break;case"tcptype":i.tcpType=t[e+1];break;case"ufrag":i.ufrag=t[e+1],i.usernameFragment=t[e+1];break;default:void 0===i[t[e]]&&(i[t[e]]=t[e+1])}return i},t.writeCandidate=function(e){const t=[];t.push(e.foundation);const i=e.component;"rtp"===i?t.push(1):"rtcp"===i?t.push(2):t.push(i),t.push(e.protocol.toUpperCase()),t.push(e.priority),t.push(e.address||e.ip),t.push(e.port);const n=e.type;return t.push("typ"),t.push(n),"host"!==n&&e.relatedAddress&&e.relatedPort&&(t.push("raddr"),t.push(e.relatedAddress),t.push("rport"),t.push(e.relatedPort)),e.tcpType&&"tcp"===e.protocol.toLowerCase()&&(t.push("tcptype"),t.push(e.tcpType)),(e.usernameFragment||e.ufrag)&&(t.push("ufrag"),t.push(e.usernameFragment||e.ufrag)),"candidate:"+t.join(" ")},t.parseIceOptions=function(e){return e.substring(14).split(" ")},t.parseRtpMap=function(e){let t=e.substring(9).split(" ");const i={payloadType:parseInt(t.shift(),10)};return t=t[0].split("/"),i.name=t[0],i.clockRate=parseInt(t[1],10),i.channels=3===t.length?parseInt(t[2],10):1,i.numChannels=i.channels,i},t.writeRtpMap=function(e){let t=e.payloadType;void 0!==e.preferredPayloadType&&(t=e.preferredPayloadType);const i=e.channels||e.numChannels||1;return"a=rtpmap:"+t+" "+e.name+"/"+e.clockRate+(1!==i?"/"+i:"")+"\r\n"},t.parseExtmap=function(e){const t=e.substring(9).split(" ");return{id:parseInt(t[0],10),direction:t[0].indexOf("/")>0?t[0].split("/")[1]:"sendrecv",uri:t[1],attributes:t.slice(2).join(" ")}},t.writeExtmap=function(e){return"a=extmap:"+(e.id||e.preferredId)+(e.direction&&"sendrecv"!==e.direction?"/"+e.direction:"")+" "+e.uri+(e.attributes?" "+e.attributes:"")+"\r\n"},t.parseFmtp=function(e){const t={};let i;const n=e.substring(e.indexOf(" ")+1).split(";");for(let e=0;e<n.length;e++)i=n[e].trim().split("="),t[i[0].trim()]=i[1];return t},t.writeFmtp=function(e){let t="",i=e.payloadType;if(void 0!==e.preferredPayloadType&&(i=e.preferredPayloadType),e.parameters&&Object.keys(e.parameters).length){const n=[];Object.keys(e.parameters).forEach((t=>{void 0!==e.parameters[t]?n.push(t+"="+e.parameters[t]):n.push(t)})),t+="a=fmtp:"+i+" "+n.join(";")+"\r\n"}return t},t.parseRtcpFb=function(e){const t=e.substring(e.indexOf(" ")+1).split(" ");return{type:t.shift(),parameter:t.join(" ")}},t.writeRtcpFb=function(e){let t="",i=e.payloadType;return void 0!==e.preferredPayloadType&&(i=e.preferredPayloadType),e.rtcpFeedback&&e.rtcpFeedback.length&&e.rtcpFeedback.forEach((e=>{t+="a=rtcp-fb:"+i+" "+e.type+(e.parameter&&e.parameter.length?" "+e.parameter:"")+"\r\n"})),t},t.parseSsrcMedia=function(e){const t=e.indexOf(" "),i={ssrc:parseInt(e.substring(7,t),10)},n=e.indexOf(":",t);return n>-1?(i.attribute=e.substring(t+1,n),i.value=e.substring(n+1)):i.attribute=e.substring(t+1),i},t.parseSsrcGroup=function(e){const t=e.substring(13).split(" ");return{semantics:t.shift(),ssrcs:t.map((e=>parseInt(e,10)))}},t.getMid=function(e){const i=t.matchPrefix(e,"a=mid:")[0];if(i)return i.substring(6)},t.parseFingerprint=function(e){const t=e.substring(14).split(" ");return{algorithm:t[0].toLowerCase(),value:t[1].toUpperCase()}},t.getDtlsParameters=function(e,i){return{role:"auto",fingerprints:t.matchPrefix(e+i,"a=fingerprint:").map(t.parseFingerprint)}},t.writeDtlsParameters=function(e,t){let i="a=setup:"+t+"\r\n";return e.fingerprints.forEach((e=>{i+="a=fingerprint:"+e.algorithm+" "+e.value+"\r\n"})),i},t.parseCryptoLine=function(e){const t=e.substring(9).split(" ");return{tag:parseInt(t[0],10),cryptoSuite:t[1],keyParams:t[2],sessionParams:t.slice(3)}},t.writeCryptoLine=function(e){return"a=crypto:"+e.tag+" "+e.cryptoSuite+" "+("object"==typeof e.keyParams?t.writeCryptoKeyParams(e.keyParams):e.keyParams)+(e.sessionParams?" "+e.sessionParams.join(" "):"")+"\r\n"},t.parseCryptoKeyParams=function(e){if(0!==e.indexOf("inline:"))return null;const t=e.substring(7).split("|");return{keyMethod:"inline",keySalt:t[0],lifeTime:t[1],mkiValue:t[2]?t[2].split(":")[0]:void 0,mkiLength:t[2]?t[2].split(":")[1]:void 0}},t.writeCryptoKeyParams=function(e){return e.keyMethod+":"+e.keySalt+(e.lifeTime?"|"+e.lifeTime:"")+(e.mkiValue&&e.mkiLength?"|"+e.mkiValue+":"+e.mkiLength:"")},t.getCryptoParameters=function(e,i){return t.matchPrefix(e+i,"a=crypto:").map(t.parseCryptoLine)},t.getIceParameters=function(e,i){const n=t.matchPrefix(e+i,"a=ice-ufrag:")[0],r=t.matchPrefix(e+i,"a=ice-pwd:")[0];return n&&r?{usernameFragment:n.substring(12),password:r.substring(10)}:null},t.writeIceParameters=function(e){let t="a=ice-ufrag:"+e.usernameFragment+"\r\na=ice-pwd:"+e.password+"\r\n";return e.iceLite&&(t+="a=ice-lite\r\n"),t},t.parseRtpParameters=function(e){const i={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},n=t.splitLines(e)[0].split(" ");i.profile=n[2];for(let r=3;r<n.length;r++){const s=n[r],o=t.matchPrefix(e,"a=rtpmap:"+s+" ")[0];if(o){const n=t.parseRtpMap(o),r=t.matchPrefix(e,"a=fmtp:"+s+" ");switch(n.parameters=r.length?t.parseFmtp(r[0]):{},n.rtcpFeedback=t.matchPrefix(e,"a=rtcp-fb:"+s+" ").map(t.parseRtcpFb),i.codecs.push(n),n.name.toUpperCase()){case"RED":case"ULPFEC":i.fecMechanisms.push(n.name.toUpperCase())}}}t.matchPrefix(e,"a=extmap:").forEach((e=>{i.headerExtensions.push(t.parseExtmap(e))}));const r=t.matchPrefix(e,"a=rtcp-fb:* ").map(t.parseRtcpFb);return i.codecs.forEach((e=>{r.forEach((t=>{e.rtcpFeedback.find((e=>e.type===t.type&&e.parameter===t.parameter))||e.rtcpFeedback.push(t)}))})),i},t.writeRtpDescription=function(e,i){let n="";n+="m="+e+" ",n+=i.codecs.length>0?"9":"0",n+=" "+(i.profile||"UDP/TLS/RTP/SAVPF")+" ",n+=i.codecs.map((e=>void 0!==e.preferredPayloadType?e.preferredPayloadType:e.payloadType)).join(" ")+"\r\n",n+="c=IN IP4 0.0.0.0\r\n",n+="a=rtcp:9 IN IP4 0.0.0.0\r\n",i.codecs.forEach((e=>{n+=t.writeRtpMap(e),n+=t.writeFmtp(e),n+=t.writeRtcpFb(e)}));let r=0;return i.codecs.forEach((e=>{e.maxptime>r&&(r=e.maxptime)})),r>0&&(n+="a=maxptime:"+r+"\r\n"),i.headerExtensions&&i.headerExtensions.forEach((e=>{n+=t.writeExtmap(e)})),n},t.parseRtpEncodingParameters=function(e){const i=[],n=t.parseRtpParameters(e),r=-1!==n.fecMechanisms.indexOf("RED"),s=-1!==n.fecMechanisms.indexOf("ULPFEC"),o=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"cname"===e.attribute)),a=o.length>0&&o[0].ssrc;let c;const d=t.matchPrefix(e,"a=ssrc-group:FID").map((e=>e.substring(17).split(" ").map((e=>parseInt(e,10)))));d.length>0&&d[0].length>1&&d[0][0]===a&&(c=d[0][1]),n.codecs.forEach((e=>{if("RTX"===e.name.toUpperCase()&&e.parameters.apt){let t={ssrc:a,codecPayloadType:parseInt(e.parameters.apt,10)};a&&c&&(t.rtx={ssrc:c}),i.push(t),r&&(t=JSON.parse(JSON.stringify(t)),t.fec={ssrc:a,mechanism:s?"red+ulpfec":"red"},i.push(t))}})),0===i.length&&a&&i.push({ssrc:a});let u=t.matchPrefix(e,"b=");return u.length&&(u=0===u[0].indexOf("b=TIAS:")?parseInt(u[0].substring(7),10):0===u[0].indexOf("b=AS:")?1e3*parseInt(u[0].substring(5),10)*.95-16e3:void 0,i.forEach((e=>{e.maxBitrate=u}))),i},t.parseRtcpParameters=function(e){const i={},n=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"cname"===e.attribute))[0];n&&(i.cname=n.value,i.ssrc=n.ssrc);const r=t.matchPrefix(e,"a=rtcp-rsize");i.reducedSize=r.length>0,i.compound=0===r.length;const s=t.matchPrefix(e,"a=rtcp-mux");return i.mux=s.length>0,i},t.writeRtcpParameters=function(e){let t="";return e.reducedSize&&(t+="a=rtcp-rsize\r\n"),e.mux&&(t+="a=rtcp-mux\r\n"),void 0!==e.ssrc&&e.cname&&(t+="a=ssrc:"+e.ssrc+" cname:"+e.cname+"\r\n"),t},t.parseMsid=function(e){let i;const n=t.matchPrefix(e,"a=msid:");if(1===n.length)return i=n[0].substring(7).split(" "),{stream:i[0],track:i[1]};const r=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"msid"===e.attribute));return r.length>0?(i=r[0].value.split(" "),{stream:i[0],track:i[1]}):void 0},t.parseSctpDescription=function(e){const i=t.parseMLine(e),n=t.matchPrefix(e,"a=max-message-size:");let r;n.length>0&&(r=parseInt(n[0].substring(19),10)),isNaN(r)&&(r=65536);const s=t.matchPrefix(e,"a=sctp-port:");if(s.length>0)return{port:parseInt(s[0].substring(12),10),protocol:i.fmt,maxMessageSize:r};const o=t.matchPrefix(e,"a=sctpmap:");if(o.length>0){const e=o[0].substring(10).split(" ");return{port:parseInt(e[0],10),protocol:e[1],maxMessageSize:r}}},t.writeSctpDescription=function(e,t){let i=[];return i="DTLS/SCTP"!==e.protocol?["m="+e.kind+" 9 "+e.protocol+" "+t.protocol+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctp-port:"+t.port+"\r\n"]:["m="+e.kind+" 9 "+e.protocol+" "+t.port+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctpmap:"+t.port+" "+t.protocol+" 65535\r\n"],void 0!==t.maxMessageSize&&i.push("a=max-message-size:"+t.maxMessageSize+"\r\n"),i.join("")},t.generateSessionId=function(){return Math.random().toString().substr(2,22)},t.writeSessionBoilerplate=function(e,i,n){let r;const s=void 0!==i?i:2;r=e||t.generateSessionId();return"v=0\r\no="+(n||"thisisadapterortc")+" "+r+" "+s+" IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\n"},t.getDirection=function(e,i){const n=t.splitLines(e);for(let e=0;e<n.length;e++)switch(n[e]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return n[e].substring(2)}return i?t.getDirection(i):"sendrecv"},t.getKind=function(e){return t.splitLines(e)[0].split(" ")[0].substring(2)},t.isRejected=function(e){return"0"===e.split(" ",2)[1]},t.parseMLine=function(e){const i=t.splitLines(e)[0].substring(2).split(" ");return{kind:i[0],port:parseInt(i[1],10),protocol:i[2],fmt:i.slice(3).join(" ")}},t.parseOLine=function(e){const i=t.matchPrefix(e,"o=")[0].substring(2).split(" ");return{username:i[0],sessionId:i[1],sessionVersion:parseInt(i[2],10),netType:i[3],addressType:i[4],address:i[5]}},t.isValidSDP=function(e){if("string"!=typeof e||0===e.length)return!1;const i=t.splitLines(e);for(let e=0;e<i.length;e++)if(i[e].length<2||"="!==i[e].charAt(1))return!1;return!0},e.exports=t}(Wi);var Gi=Wi.exports,Ki=n(Gi),Qi=t({__proto__:null,default:Ki},[Gi]);function Hi(e){if(!e.RTCIceCandidate||e.RTCIceCandidate&&"foundation"in e.RTCIceCandidate.prototype)return;const t=e.RTCIceCandidate;e.RTCIceCandidate=function(e){if("object"==typeof e&&e.candidate&&0===e.candidate.indexOf("a=")&&((e=JSON.parse(JSON.stringify(e))).candidate=e.candidate.substring(2)),e.candidate&&e.candidate.length){const i=new t(e),n=Ki.parseCandidate(e.candidate);for(const e in n)e in i||Object.defineProperty(i,e,{value:n[e]});return i.toJSON=function(){return{candidate:i.candidate,sdpMid:i.sdpMid,sdpMLineIndex:i.sdpMLineIndex,usernameFragment:i.usernameFragment}},i}return new t(e)},e.RTCIceCandidate.prototype=t.prototype,ii(e,"icecandidate",(t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new e.RTCIceCandidate(t.candidate),writable:"false"}),t)))}function Zi(e){!e.RTCIceCandidate||e.RTCIceCandidate&&"relayProtocol"in e.RTCIceCandidate.prototype||ii(e,"icecandidate",(e=>{if(e.candidate){const t=Ki.parseCandidate(e.candidate.candidate);"relay"===t.type&&(e.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[t.priority>>24])}return e}))}function zi(e,t){if(!e.RTCPeerConnection)return;"sctp"in e.RTCPeerConnection.prototype||Object.defineProperty(e.RTCPeerConnection.prototype,"sctp",{get(){return void 0===this._sctp?null:this._sctp}});const i=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,"chrome"===t.browser&&t.version>=76){const{sdpSemantics:e}=this.getConfiguration();"plan-b"===e&&Object.defineProperty(this,"sctp",{get(){return void 0===this._sctp?null:this._sctp},enumerable:!0,configurable:!0})}if(function(e){if(!e||!e.sdp)return!1;const t=Ki.splitSections(e.sdp);return t.shift(),t.some((e=>{const t=Ki.parseMLine(e);return t&&"application"===t.kind&&-1!==t.protocol.indexOf("SCTP")}))}(arguments[0])){const e=function(e){const t=e.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(null===t||t.length<2)return-1;const i=parseInt(t[1],10);return i!=i?-1:i}(arguments[0]),i=function(e){let i=65536;return"firefox"===t.browser&&(i=t.version<57?-1===e?16384:2147483637:t.version<60?57===t.version?65535:65536:2147483637),i}(e),n=function(e,i){let n=65536;"firefox"===t.browser&&57===t.version&&(n=65535);const r=Ki.matchPrefix(e.sdp,"a=max-message-size:");return r.length>0?n=parseInt(r[0].substring(19),10):"firefox"===t.browser&&-1!==i&&(n=2147483637),n}(arguments[0],e);let r;r=0===i&&0===n?Number.POSITIVE_INFINITY:0===i||0===n?Math.max(i,n):Math.min(i,n);const s={};Object.defineProperty(s,"maxMessageSize",{get:()=>r}),this._sctp=s}return i.apply(this,arguments)}}function Yi(e){if(!e.RTCPeerConnection||!("createDataChannel"in e.RTCPeerConnection.prototype))return;function t(e,t){const i=e.send;e.send=function(){const n=arguments[0],r=n.length||n.size||n.byteLength;if("open"===e.readyState&&t.sctp&&r>t.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+t.sctp.maxMessageSize+" bytes)");return i.apply(e,arguments)}}const i=e.RTCPeerConnection.prototype.createDataChannel;e.RTCPeerConnection.prototype.createDataChannel=function(){const e=i.apply(this,arguments);return t(e,this),e},ii(e,"datachannel",(e=>(t(e.channel,e.target),e)))}function Xi(e){if(!e.RTCPeerConnection||"connectionState"in e.RTCPeerConnection.prototype)return;const t=e.RTCPeerConnection.prototype;Object.defineProperty(t,"connectionState",{get(){return{completed:"connected",checking:"connecting"}[this.iceConnectionState]||this.iceConnectionState},enumerable:!0,configurable:!0}),Object.defineProperty(t,"onconnectionstatechange",{get(){return this._onconnectionstatechange||null},set(e){this._onconnectionstatechange&&(this.removeEventListener("connectionstatechange",this._onconnectionstatechange),delete this._onconnectionstatechange),e&&this.addEventListener("connectionstatechange",this._onconnectionstatechange=e)},enumerable:!0,configurable:!0}),["setLocalDescription","setRemoteDescription"].forEach((e=>{const i=t[e];t[e]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=e=>{const t=e.target;if(t._lastConnectionState!==t.connectionState){t._lastConnectionState=t.connectionState;const i=new Event("connectionstatechange",e);t.dispatchEvent(i)}return e},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),i.apply(this,arguments)}}))}function en(e,t){if(!e.RTCPeerConnection)return;if("chrome"===t.browser&&t.version>=71)return;if("safari"===t.browser&&t.version>=605)return;const i=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(t){if(t&&t.sdp&&-1!==t.sdp.indexOf("\na=extmap-allow-mixed")){const i=t.sdp.split("\n").filter((e=>"a=extmap-allow-mixed"!==e.trim())).join("\n");e.RTCSessionDescription&&t instanceof e.RTCSessionDescription?arguments[0]=new e.RTCSessionDescription({type:t.type,sdp:i}):t.sdp=i}return i.apply(this,arguments)}}function tn(e,t){if(!e.RTCPeerConnection||!e.RTCPeerConnection.prototype)return;const i=e.RTCPeerConnection.prototype.addIceCandidate;i&&0!==i.length&&(e.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?("chrome"===t.browser&&t.version<78||"firefox"===t.browser&&t.version<68||"safari"===t.browser)&&arguments[0]&&""===arguments[0].candidate?Promise.resolve():i.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}function nn(e,t){if(!e.RTCPeerConnection||!e.RTCPeerConnection.prototype)return;const i=e.RTCPeerConnection.prototype.setLocalDescription;i&&0!==i.length&&(e.RTCPeerConnection.prototype.setLocalDescription=function(){let e=arguments[0]||{};if("object"!=typeof e||e.type&&e.sdp)return i.apply(this,arguments);if(e={type:e.type,sdp:e.sdp},!e.type)switch(this.signalingState){case"stable":case"have-local-offer":case"have-remote-pranswer":e.type="offer";break;default:e.type="answer"}if(e.sdp||"offer"!==e.type&&"answer"!==e.type)return i.apply(this,[e]);return("offer"===e.type?this.createOffer:this.createAnswer).apply(this).then((e=>i.apply(this,[e])))})}var rn,sn,on,an=Object.freeze({__proto__:null,removeExtmapAllowMixed:en,shimAddIceCandidateNullOrEmpty:tn,shimConnectionState:Xi,shimMaxMessageSize:zi,shimParameterlessSetLocalDescription:nn,shimRTCIceCandidate:Hi,shimRTCIceCandidateRelayProtocol:Zi,shimSendThrowTypeError:Yi});function cn(e){switch(e){case 0:case"PUBLISHER":return rn.PUBLISHER;case 1:case"SUBSCRIBER":return rn.SUBSCRIBER;default:return rn.UNRECOGNIZED}}function dn(e){switch(e){case rn.PUBLISHER:return"PUBLISHER";case rn.SUBSCRIBER:return"SUBSCRIBER";case rn.UNRECOGNIZED:default:return"UNRECOGNIZED"}}function un(e){switch(e){case 0:case"ACTIVE":return sn.ACTIVE;case 1:case"PAUSED":return sn.PAUSED;default:return sn.UNRECOGNIZED}}function ln(e){switch(e){case 0:case"UDP":return on.UDP;case 1:case"TCP":return on.TCP;case 2:case"TLS":return on.TLS;default:return on.UNRECOGNIZED}}!function(){let{window:e}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{shimChrome:!0,shimFirefox:!0,shimSafari:!0};const i=si,n=function(e){const t={browser:null,version:null};if(void 0===e||!e.navigator)return t.browser="Not a browser.",t;const{navigator:i}=e;if(i.mozGetUserMedia)t.browser="firefox",t.version=ti(i.userAgent,/Firefox\/(\d+)\./,1);else if(i.webkitGetUserMedia||!1===e.isSecureContext&&e.webkitRTCPeerConnection)t.browser="chrome",t.version=ti(i.userAgent,/Chrom(e|ium)\/(\d+)\./,2);else{if(!e.RTCPeerConnection||!i.userAgent.match(/AppleWebKit\/(\d+)\./))return t.browser="Not a supported browser.",t;t.browser="safari",t.version=ti(i.userAgent,/AppleWebKit\/(\d+)\./,1),t.supportsUnifiedPlan=e.RTCRtpTransceiver&&"currentDirection"in e.RTCRtpTransceiver.prototype}return t}(e),r={browserDetails:n,commonShim:an,extractVersion:ti,disableLog:ni,disableWarnings:ri,sdp:Qi};switch(n.browser){case"chrome":if(!Ci||!yi||!t.shimChrome)return i("Chrome shim is not included in this adapter release."),r;if(null===n.version)return i("Chrome shim can not determine version, not shimming."),r;i("adapter.js shimming chrome."),r.browserShim=Ci,tn(e,n),nn(e),hi(e,n),pi(e),yi(e,n),mi(e),ki(e,n),fi(e),vi(e),gi(e),Si(e,n),Hi(e),Zi(e),Xi(e),zi(e,n),Yi(e),en(e,n);break;case"firefox":if(!Mi||!Pi||!t.shimFirefox)return i("Firefox shim is not included in this adapter release."),r;i("adapter.js shimming firefox."),r.browserShim=Mi,tn(e,n),nn(e),Ei(e,n),Pi(e,n),Ti(e),Ni(e),wi(e),Ri(e),Oi(e),Ii(e),Di(e),Ai(e),Ui(e),Hi(e),Xi(e),zi(e,n),Yi(e);break;case"safari":if(!qi||!t.shimSafari)return i("Safari shim is not included in this adapter release."),r;i("adapter.js shimming safari."),r.browserShim=qi,tn(e,n),nn(e),Fi(e),Vi(e),xi(e),Li(e),_i(e),$i(e),Bi(e),ji(e),Hi(e),Zi(e),zi(e,n),Yi(e),en(e,n);break;default:i("Unsupported browser!")}}({window:"undefined"==typeof window?void 0:window}),function(e){e[e.PUBLISHER=0]="PUBLISHER",e[e.SUBSCRIBER=1]="SUBSCRIBER",e[e.UNRECOGNIZED=-1]="UNRECOGNIZED"}(rn||(rn={})),function(e){e[e.ACTIVE=0]="ACTIVE",e[e.PAUSED=1]="PAUSED",e[e.UNRECOGNIZED=-1]="UNRECOGNIZED"}(sn||(sn={})),function(e){e[e.UDP=0]="UDP",e[e.TCP=1]="TCP",e[e.TLS=2]="TLS",e[e.UNRECOGNIZED=-1]="UNRECOGNIZED"}(on||(on={}));const hn={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:st.Writer.create();var i;switch(null===(i=e.message)||void 0===i?void 0:i.$case){case"offer":En.encode(e.message.offer,t.uint32(10).fork()).ldelim();break;case"answer":En.encode(e.message.answer,t.uint32(18).fork()).ldelim();break;case"trickle":vn.encode(e.message.trickle,t.uint32(26).fork()).ldelim();break;case"addTrack":fn.encode(e.message.addTrack,t.uint32(34).fork()).ldelim();break;case"mute":gn.encode(e.message.mute,t.uint32(42).fork()).ldelim();break;case"subscription":Pn.encode(e.message.subscription,t.uint32(50).fork()).ldelim();break;case"trackSetting":wn.encode(e.message.trackSetting,t.uint32(58).fork()).ldelim();break;case"leave":Rn.encode(e.message.leave,t.uint32(66).fork()).ldelim();break;case"updateLayers":Nn.encode(e.message.updateLayers,t.uint32(82).fork()).ldelim();break;case"subscriptionPermission":$n.encode(e.message.subscriptionPermission,t.uint32(90).fork()).ldelim();break;case"syncState":jn.encode(e.message.syncState,t.uint32(98).fork()).ldelim();break;case"simulate":Wn.encode(e.message.simulate,t.uint32(106).fork()).ldelim();break;case"ping":t.uint32(112).int64(e.message.ping);break;case"updateMetadata":On.encode(e.message.updateMetadata,t.uint32(122).fork()).ldelim();break;case"pingReq":Gn.encode(e.message.pingReq,t.uint32(130).fork()).ldelim()}return t},decode(e,t){const i=e instanceof st.Reader?e:st.Reader.create(e);let n=void 0===t?i.len:i.pos+t;const r={message:void 0};for(;i.pos<n;){const e=i.uint32();switch(e>>>3){case 1:if(10!==e)break;r.message={$case:"offer",offer:En.decode(i,i.uint32())};continue;case 2:if(18!==e)break;r.message={$case:"answer",answer:En.decode(i,i.uint32())};continue;case 3:if(26!==e)break;r.message={$case:"trickle",trickle:vn.decode(i,i.uint32())};continue;case 4:if(34!==e)break;r.message={$case:"addTrack",addTrack:fn.decode(i,i.uint32())};continue;case 5:if(42!==e)break;r.message={$case:"mute",mute:gn.decode(i,i.uint32())};continue;case 6:if(50!==e)break;r.message={$case:"subscription",subscription:Pn.decode(i,i.uint32())};continue;case 7:if(58!==e)break;r.message={$case:"trackSetting",trackSetting:wn.decode(i,i.uint32())};continue;case 8:if(66!==e)break;r.message={$case:"leave",leave:Rn.decode(i,i.uint32())};continue;case 10:if(82!==e)break;r.message={$case:"updateLayers",updateLayers:Nn.decode(i,i.uint32())};continue;case 11:if(90!==e)break;r.message={$case:"subscriptionPermission",subscriptionPermission:$n.decode(i,i.uint32())};continue;case 12:if(98!==e)break;r.message={$case:"syncState",syncState:jn.decode(i,i.uint32())};continue;case 13:if(106!==e)break;r.message={$case:"simulate",simulate:Wn.decode(i,i.uint32())};continue;case 14:if(112!==e)break;r.message={$case:"ping",ping:Yn(i.int64())};continue;case 15:if(122!==e)break;r.message={$case:"updateMetadata",updateMetadata:On.decode(i,i.uint32())};continue;case 16:if(130!==e)break;r.message={$case:"pingReq",pingReq:Gn.decode(i,i.uint32())};continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return r},fromJSON:e=>({message:Xn(e.offer)?{$case:"offer",offer:En.fromJSON(e.offer)}:Xn(e.answer)?{$case:"answer",answer:En.fromJSON(e.answer)}:Xn(e.trickle)?{$case:"trickle",trickle:vn.fromJSON(e.trickle)}:Xn(e.addTrack)?{$case:"addTrack",addTrack:fn.fromJSON(e.addTrack)}:Xn(e.mute)?{$case:"mute",mute:gn.fromJSON(e.mute)}:Xn(e.subscription)?{$case:"subscription",subscription:Pn.fromJSON(e.subscription)}:Xn(e.trackSetting)?{$case:"trackSetting",trackSetting:wn.fromJSON(e.trackSetting)}:Xn(e.leave)?{$case:"leave",leave:Rn.fromJSON(e.leave)}:Xn(e.updateLayers)?{$case:"updateLayers",updateLayers:Nn.fromJSON(e.updateLayers)}:Xn(e.subscriptionPermission)?{$case:"subscriptionPermission",subscriptionPermission:$n.fromJSON(e.subscriptionPermission)}:Xn(e.syncState)?{$case:"syncState",syncState:jn.fromJSON(e.syncState)}:Xn(e.simulate)?{$case:"simulate",simulate:Wn.fromJSON(e.simulate)}:Xn(e.ping)?{$case:"ping",ping:Number(e.ping)}:Xn(e.updateMetadata)?{$case:"updateMetadata",updateMetadata:On.fromJSON(e.updateMetadata)}:Xn(e.pingReq)?{$case:"pingReq",pingReq:Gn.fromJSON(e.pingReq)}:void 0}),toJSON(e){var t,i,n,r,s,o,a,c,d,u,l,h,p,m,f,v,g,b,k,y,S,C,E,T,P,w,R,N,O,I,D,A,U,M,L,_,x,B,J,F,$,V,j,q;const W={};return"offer"===(null===(t=e.message)||void 0===t?void 0:t.$case)&&(W.offer=(null===(i=e.message)||void 0===i?void 0:i.offer)?En.toJSON(null===(n=e.message)||void 0===n?void 0:n.offer):void 0),"answer"===(null===(r=e.message)||void 0===r?void 0:r.$case)&&(W.answer=(null===(s=e.message)||void 0===s?void 0:s.answer)?En.toJSON(null===(o=e.message)||void 0===o?void 0:o.answer):void 0),"trickle"===(null===(a=e.message)||void 0===a?void 0:a.$case)&&(W.trickle=(null===(c=e.message)||void 0===c?void 0:c.trickle)?vn.toJSON(null===(d=e.message)||void 0===d?void 0:d.trickle):void 0),"addTrack"===(null===(u=e.message)||void 0===u?void 0:u.$case)&&(W.addTrack=(null===(l=e.message)||void 0===l?void 0:l.addTrack)?fn.toJSON(null===(h=e.message)||void 0===h?void 0:h.addTrack):void 0),"mute"===(null===(p=e.message)||void 0===p?void 0:p.$case)&&(W.mute=(null===(m=e.message)||void 0===m?void 0:m.mute)?gn.toJSON(null===(f=e.message)||void 0===f?void 0:f.mute):void 0),"subscription"===(null===(v=e.message)||void 0===v?void 0:v.$case)&&(W.subscription=(null===(g=e.message)||void 0===g?void 0:g.subscription)?Pn.toJSON(null===(b=e.message)||void 0===b?void 0:b.subscription):void 0),"trackSetting"===(null===(k=e.message)||void 0===k?void 0:k.$case)&&(W.trackSetting=(null===(y=e.message)||void 0===y?void 0:y.trackSetting)?wn.toJSON(null===(S=e.message)||void 0===S?void 0:S.trackSetting):void 0),"leave"===(null===(C=e.message)||void 0===C?void 0:C.$case)&&(W.leave=(null===(E=e.message)||void 0===E?void 0:E.leave)?Rn.toJSON(null===(T=e.message)||void 0===T?void 0:T.leave):void 0),"updateLayers"===(null===(P=e.message)||void 0===P?void 0:P.$case)&&(W.updateLayers=(null===(w=e.message)||void 0===w?void 0:w.updateLayers)?Nn.toJSON(null===(R=e.message)||void 0===R?void 0:R.updateLayers):void 0),"subscriptionPermission"===(null===(N=e.message)||void 0===N?void 0:N.$case)&&(W.subscriptionPermission=(null===(O=e.message)||void 0===O?void 0:O.subscriptionPermission)?$n.toJSON(null===(I=e.message)||void 0===I?void 0:I.subscriptionPermission):void 0),"syncState"===(null===(D=e.message)||void 0===D?void 0:D.$case)&&(W.syncState=(null===(A=e.message)||void 0===A?void 0:A.syncState)?jn.toJSON(null===(U=e.message)||void 0===U?void 0:U.syncState):void 0),"simulate"===(null===(M=e.message)||void 0===M?void 0:M.$case)&&(W.simulate=(null===(L=e.message)||void 0===L?void 0:L.simulate)?Wn.toJSON(null===(_=e.message)||void 0===_?void 0:_.simulate):void 0),"ping"===(null===(x=e.message)||void 0===x?void 0:x.$case)&&(W.ping=Math.round(null===(B=e.message)||void 0===B?void 0:B.ping)),"updateMetadata"===(null===(J=e.message)||void 0===J?void 0:J.$case)&&(W.updateMetadata=(null===(F=e.message)||void 0===F?void 0:F.updateMetadata)?On.toJSON(null===($=e.message)||void 0===$?void 0:$.updateMetadata):void 0),"pingReq"===(null===(V=e.message)||void 0===V?void 0:V.$case)&&(W.pingReq=(null===(j=e.message)||void 0===j?void 0:j.pingReq)?Gn.toJSON(null===(q=e.message)||void 0===q?void 0:q.pingReq):void 0),W},create:e=>hn.fromPartial(null!=e?e:{}),fromPartial(e){var t,i,n,r,s,o,a,c,d,u,l,h,p,m,f,v,g,b,k,y,S,C,E,T,P,w,R,N,O,I,D,A,U,M,L,_,x,B,J,F,$,V,j,q,W;const G={message:void 0};return"offer"===(null===(t=e.message)||void 0===t?void 0:t.$case)&&void 0!==(null===(i=e.message)||void 0===i?void 0:i.offer)&&null!==(null===(n=e.message)||void 0===n?void 0:n.offer)&&(G.message={$case:"offer",offer:En.fromPartial(e.message.offer)}),"answer"===(null===(r=e.message)||void 0===r?void 0:r.$case)&&void 0!==(null===(s=e.message)||void 0===s?void 0:s.answer)&&null!==(null===(o=e.message)||void 0===o?void 0:o.answer)&&(G.message={$case:"answer",answer:En.fromPartial(e.message.answer)}),"trickle"===(null===(a=e.message)||void 0===a?void 0:a.$case)&&void 0!==(null===(c=e.message)||void 0===c?void 0:c.trickle)&&null!==(null===(d=e.message)||void 0===d?void 0:d.trickle)&&(G.message={$case:"trickle",trickle:vn.fromPartial(e.message.trickle)}),"addTrack"===(null===(u=e.message)||void 0===u?void 0:u.$case)&&void 0!==(null===(l=e.message)||void 0===l?void 0:l.addTrack)&&null!==(null===(h=e.message)||void 0===h?void 0:h.addTrack)&&(G.message={$case:"addTrack",addTrack:fn.fromPartial(e.message.addTrack)}),"mute"===(null===(p=e.message)||void 0===p?void 0:p.$case)&&void 0!==(null===(m=e.message)||void 0===m?void 0:m.mute)&&null!==(null===(f=e.message)||void 0===f?void 0:f.mute)&&(G.message={$case:"mute",mute:gn.fromPartial(e.message.mute)}),"subscription"===(null===(v=e.message)||void 0===v?void 0:v.$case)&&void 0!==(null===(g=e.message)||void 0===g?void 0:g.subscription)&&null!==(null===(b=e.message)||void 0===b?void 0:b.subscription)&&(G.message={$case:"subscription",subscription:Pn.fromPartial(e.message.subscription)}),"trackSetting"===(null===(k=e.message)||void 0===k?void 0:k.$case)&&void 0!==(null===(y=e.message)||void 0===y?void 0:y.trackSetting)&&null!==(null===(S=e.message)||void 0===S?void 0:S.trackSetting)&&(G.message={$case:"trackSetting",trackSetting:wn.fromPartial(e.message.trackSetting)}),"leave"===(null===(C=e.message)||void 0===C?void 0:C.$case)&&void 0!==(null===(E=e.message)||void 0===E?void 0:E.leave)&&null!==(null===(T=e.message)||void 0===T?void 0:T.leave)&&(G.message={$case:"leave",leave:Rn.fromPartial(e.message.leave)}),"updateLayers"===(null===(P=e.message)||void 0===P?void 0:P.$case)&&void 0!==(null===(w=e.message)||void 0===w?void 0:w.updateLayers)&&null!==(null===(R=e.message)||void 0===R?void 0:R.updateLayers)&&(G.message={$case:"updateLayers",updateLayers:Nn.fromPartial(e.message.updateLayers)}),"subscriptionPermission"===(null===(N=e.message)||void 0===N?void 0:N.$case)&&void 0!==(null===(O=e.message)||void 0===O?void 0:O.subscriptionPermission)&&null!==(null===(I=e.message)||void 0===I?void 0:I.subscriptionPermission)&&(G.message={$case:"subscriptionPermission",subscriptionPermission:$n.fromPartial(e.message.subscriptionPermission)}),"syncState"===(null===(D=e.message)||void 0===D?void 0:D.$case)&&void 0!==(null===(A=e.message)||void 0===A?void 0:A.syncState)&&null!==(null===(U=e.message)||void 0===U?void 0:U.syncState)&&(G.message={$case:"syncState",syncState:jn.fromPartial(e.message.syncState)}),"simulate"===(null===(M=e.message)||void 0===M?void 0:M.$case)&&void 0!==(null===(L=e.message)||void 0===L?void 0:L.simulate)&&null!==(null===(_=e.message)||void 0===_?void 0:_.simulate)&&(G.message={$case:"simulate",simulate:Wn.fromPartial(e.message.simulate)}),"ping"===(null===(x=e.message)||void 0===x?void 0:x.$case)&&void 0!==(null===(B=e.message)||void 0===B?void 0:B.ping)&&null!==(null===(J=e.message)||void 0===J?void 0:J.ping)&&(G.message={$case:"ping",ping:e.message.ping}),"updateMetadata"===(null===(F=e.message)||void 0===F?void 0:F.$case)&&void 0!==(null===($=e.message)||void 0===$?void 0:$.updateMetadata)&&null!==(null===(V=e.message)||void 0===V?void 0:V.updateMetadata)&&(G.message={$case:"updateMetadata",updateMetadata:On.fromPartial(e.message.updateMetadata)}),"pingReq"===(null===(j=e.message)||void 0===j?void 0:j.$case)&&void 0!==(null===(q=e.message)||void 0===q?void 0:q.pingReq)&&null!==(null===(W=e.message)||void 0===W?void 0:W.pingReq)&&(G.message={$case:"pingReq",pingReq:Gn.fromPartial(e.message.pingReq)}),G}};const pn={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:st.Writer.create();var i;switch(null===(i=e.message)||void 0===i?void 0:i.$case){case"join":kn.encode(e.message.join,t.uint32(10).fork()).ldelim();break;case"answer":En.encode(e.message.answer,t.uint32(18).fork()).ldelim();break;case"offer":En.encode(e.message.offer,t.uint32(26).fork()).ldelim();break;case"trickle":vn.encode(e.message.trickle,t.uint32(34).fork()).ldelim();break;case"update":Tn.encode(e.message.update,t.uint32(42).fork()).ldelim();break;case"trackPublished":Sn.encode(e.message.trackPublished,t.uint32(50).fork()).ldelim();break;case"leave":Rn.encode(e.message.leave,t.uint32(66).fork()).ldelim();break;case"mute":gn.encode(e.message.mute,t.uint32(74).fork()).ldelim();break;case"speakersChanged":Dn.encode(e.message.speakersChanged,t.uint32(82).fork()).ldelim();break;case"roomUpdate":An.encode(e.message.roomUpdate,t.uint32(90).fork()).ldelim();break;case"connectionQuality":Mn.encode(e.message.connectionQuality,t.uint32(98).fork()).ldelim();break;case"streamStateUpdate":_n.encode(e.message.streamStateUpdate,t.uint32(106).fork()).ldelim();break;case"subscribedQualityUpdate":Jn.encode(e.message.subscribedQualityUpdate,t.uint32(114).fork()).ldelim();break;case"subscriptionPermissionUpdate":Vn.encode(e.message.subscriptionPermissionUpdate,t.uint32(122).fork()).ldelim();break;case"refreshToken":t.uint32(130).string(e.message.refreshToken);break;case"trackUnpublished":Cn.encode(e.message.trackUnpublished,t.uint32(138).fork()).ldelim();break;case"pong":t.uint32(144).int64(e.message.pong);break;case"reconnect":yn.encode(e.message.reconnect,t.uint32(154).fork()).ldelim();break;case"pongResp":Kn.encode(e.message.pongResp,t.uint32(162).fork()).ldelim();break;case"subscriptionResponse":Qn.encode(e.message.subscriptionResponse,t.uint32(170).fork()).ldelim()}return t},decode(e,t){const i=e instanceof st.Reader?e:st.Reader.create(e);let n=void 0===t?i.len:i.pos+t;const r={message:void 0};for(;i.pos<n;){const e=i.uint32();switch(e>>>3){case 1:if(10!==e)break;r.message={$case:"join",join:kn.decode(i,i.uint32())};continue;case 2:if(18!==e)break;r.message={$case:"answer",answer:En.decode(i,i.uint32())};continue;case 3:if(26!==e)break;r.message={$case:"offer",offer:En.decode(i,i.uint32())};continue;case 4:if(34!==e)break;r.message={$case:"trickle",trickle:vn.decode(i,i.uint32())};continue;case 5:if(42!==e)break;r.message={$case:"update",update:Tn.decode(i,i.uint32())};continue;case 6:if(50!==e)break;r.message={$case:"trackPublished",trackPublished:Sn.decode(i,i.uint32())};continue;case 8:if(66!==e)break;r.message={$case:"leave",leave:Rn.decode(i,i.uint32())};continue;case 9:if(74!==e)break;r.message={$case:"mute",mute:gn.decode(i,i.uint32())};continue;case 10:if(82!==e)break;r.message={$case:"speakersChanged",speakersChanged:Dn.decode(i,i.uint32())};continue;case 11:if(90!==e)break;r.message={$case:"roomUpdate",roomUpdate:An.decode(i,i.uint32())};continue;case 12:if(98!==e)break;r.message={$case:"connectionQuality",connectionQuality:Mn.decode(i,i.uint32())};continue;case 13:if(106!==e)break;r.message={$case:"streamStateUpdate",streamStateUpdate:_n.decode(i,i.uint32())};continue;case 14:if(114!==e)break;r.message={$case:"subscribedQualityUpdate",subscribedQualityUpdate:Jn.decode(i,i.uint32())};continue;case 15:if(122!==e)break;r.message={$case:"subscriptionPermissionUpdate",subscriptionPermissionUpdate:Vn.decode(i,i.uint32())};continue;case 16:if(130!==e)break;r.message={$case:"refreshToken",refreshToken:i.string()};continue;case 17:if(138!==e)break;r.message={$case:"trackUnpublished",trackUnpublished:Cn.decode(i,i.uint32())};continue;case 18:if(144!==e)break;r.message={$case:"pong",pong:Yn(i.int64())};continue;case 19:if(154!==e)break;r.message={$case:"reconnect",reconnect:yn.decode(i,i.uint32())};continue;case 20:if(162!==e)break;r.message={$case:"pongResp",pongResp:Kn.decode(i,i.uint32())};continue;case 21:if(170!==e)break;r.message={$case:"subscriptionResponse",subscriptionResponse:Qn.decode(i,i.uint32())};continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return r},fromJSON:e=>({message:Xn(e.join)?{$case:"join",join:kn.fromJSON(e.join)}:Xn(e.answer)?{$case:"answer",answer:En.fromJSON(e.answer)}:Xn(e.offer)?{$case:"offer",offer:En.fromJSON(e.offer)}:Xn(e.trickle)?{$case:"trickle",trickle:vn.fromJSON(e.trickle)}:Xn(e.update)?{$case:"update",update:Tn.fromJSON(e.update)}:Xn(e.trackPublished)?{$case:"trackPublished",trackPublished:Sn.fromJSON(e.trackPublished)}:Xn(e.leave)?{$case:"leave",leave:Rn.fromJSON(e.leave)}:Xn(e.mute)?{$case:"mute",mute:gn.fromJSON(e.mute)}:Xn(e.speakersChanged)?{$case:"speakersChanged",speakersChanged:Dn.fromJSON(e.speakersChanged)}:Xn(e.roomUpdate)?{$case:"roomUpdate",roomUpdate:An.fromJSON(e.roomUpdate)}:Xn(e.connectionQuality)?{$case:"connectionQuality",connectionQuality:Mn.fromJSON(e.connectionQuality)}:Xn(e.streamStateUpdate)?{$case:"streamStateUpdate",streamStateUpdate:_n.fromJSON(e.streamStateUpdate)}:Xn(e.subscribedQualityUpdate)?{$case:"subscribedQualityUpdate",subscribedQualityUpdate:Jn.fromJSON(e.subscribedQualityUpdate)}:Xn(e.subscriptionPermissionUpdate)?{$case:"subscriptionPermissionUpdate",subscriptionPermissionUpdate:Vn.fromJSON(e.subscriptionPermissionUpdate)}:Xn(e.refreshToken)?{$case:"refreshToken",refreshToken:String(e.refreshToken)}:Xn(e.trackUnpublished)?{$case:"trackUnpublished",trackUnpublished:Cn.fromJSON(e.trackUnpublished)}:Xn(e.pong)?{$case:"pong",pong:Number(e.pong)}:Xn(e.reconnect)?{$case:"reconnect",reconnect:yn.fromJSON(e.reconnect)}:Xn(e.pongResp)?{$case:"pongResp",pongResp:Kn.fromJSON(e.pongResp)}:Xn(e.subscriptionResponse)?{$case:"subscriptionResponse",subscriptionResponse:Qn.fromJSON(e.subscriptionResponse)}:void 0}),toJSON(e){var t,i,n,r,s,o,a,c,d,u,l,h,p,m,f,v,g,b,k,y,S,C,E,T,P,w,R,N,O,I,D,A,U,M,L,_,x,B,J,F,$,V,j,q,W,G,K,Q,H,Z,z,Y,X,ee,te,ie,ne,re;const se={};return"join"===(null===(t=e.message)||void 0===t?void 0:t.$case)&&(se.join=(null===(i=e.message)||void 0===i?void 0:i.join)?kn.toJSON(null===(n=e.message)||void 0===n?void 0:n.join):void 0),"answer"===(null===(r=e.message)||void 0===r?void 0:r.$case)&&(se.answer=(null===(s=e.message)||void 0===s?void 0:s.answer)?En.toJSON(null===(o=e.message)||void 0===o?void 0:o.answer):void 0),"offer"===(null===(a=e.message)||void 0===a?void 0:a.$case)&&(se.offer=(null===(c=e.message)||void 0===c?void 0:c.offer)?En.toJSON(null===(d=e.message)||void 0===d?void 0:d.offer):void 0),"trickle"===(null===(u=e.message)||void 0===u?void 0:u.$case)&&(se.trickle=(null===(l=e.message)||void 0===l?void 0:l.trickle)?vn.toJSON(null===(h=e.message)||void 0===h?void 0:h.trickle):void 0),"update"===(null===(p=e.message)||void 0===p?void 0:p.$case)&&(se.update=(null===(m=e.message)||void 0===m?void 0:m.update)?Tn.toJSON(null===(f=e.message)||void 0===f?void 0:f.update):void 0),"trackPublished"===(null===(v=e.message)||void 0===v?void 0:v.$case)&&(se.trackPublished=(null===(g=e.message)||void 0===g?void 0:g.trackPublished)?Sn.toJSON(null===(b=e.message)||void 0===b?void 0:b.trackPublished):void 0),"leave"===(null===(k=e.message)||void 0===k?void 0:k.$case)&&(se.leave=(null===(y=e.message)||void 0===y?void 0:y.leave)?Rn.toJSON(null===(S=e.message)||void 0===S?void 0:S.leave):void 0),"mute"===(null===(C=e.message)||void 0===C?void 0:C.$case)&&(se.mute=(null===(E=e.message)||void 0===E?void 0:E.mute)?gn.toJSON(null===(T=e.message)||void 0===T?void 0:T.mute):void 0),"speakersChanged"===(null===(P=e.message)||void 0===P?void 0:P.$case)&&(se.speakersChanged=(null===(w=e.message)||void 0===w?void 0:w.speakersChanged)?Dn.toJSON(null===(R=e.message)||void 0===R?void 0:R.speakersChanged):void 0),"roomUpdate"===(null===(N=e.message)||void 0===N?void 0:N.$case)&&(se.roomUpdate=(null===(O=e.message)||void 0===O?void 0:O.roomUpdate)?An.toJSON(null===(I=e.message)||void 0===I?void 0:I.roomUpdate):void 0),"connectionQuality"===(null===(D=e.message)||void 0===D?void 0:D.$case)&&(se.connectionQuality=(null===(A=e.message)||void 0===A?void 0:A.connectionQuality)?Mn.toJSON(null===(U=e.message)||void 0===U?void 0:U.connectionQuality):void 0),"streamStateUpdate"===(null===(M=e.message)||void 0===M?void 0:M.$case)&&(se.streamStateUpdate=(null===(L=e.message)||void 0===L?void 0:L.streamStateUpdate)?_n.toJSON(null===(_=e.message)||void 0===_?void 0:_.streamStateUpdate):void 0),"subscribedQualityUpdate"===(null===(x=e.message)||void 0===x?void 0:x.$case)&&(se.subscribedQualityUpdate=(null===(B=e.message)||void 0===B?void 0:B.subscribedQualityUpdate)?Jn.toJSON(null===(J=e.message)||void 0===J?void 0:J.subscribedQualityUpdate):void 0),"subscriptionPermissionUpdate"===(null===(F=e.message)||void 0===F?void 0:F.$case)&&(se.subscriptionPermissionUpdate=(null===($=e.message)||void 0===$?void 0:$.subscriptionPermissionUpdate)?Vn.toJSON(null===(V=e.message)||void 0===V?void 0:V.subscriptionPermissionUpdate):void 0),"refreshToken"===(null===(j=e.message)||void 0===j?void 0:j.$case)&&(se.refreshToken=null===(q=e.message)||void 0===q?void 0:q.refreshToken),"trackUnpublished"===(null===(W=e.message)||void 0===W?void 0:W.$case)&&(se.trackUnpublished=(null===(G=e.message)||void 0===G?void 0:G.trackUnpublished)?Cn.toJSON(null===(K=e.message)||void 0===K?void 0:K.trackUnpublished):void 0),"pong"===(null===(Q=e.message)||void 0===Q?void 0:Q.$case)&&(se.pong=Math.round(null===(H=e.message)||void 0===H?void 0:H.pong)),"reconnect"===(null===(Z=e.message)||void 0===Z?void 0:Z.$case)&&(se.reconnect=(null===(z=e.message)||void 0===z?void 0:z.reconnect)?yn.toJSON(null===(Y=e.message)||void 0===Y?void 0:Y.reconnect):void 0),"pongResp"===(null===(X=e.message)||void 0===X?void 0:X.$case)&&(se.pongResp=(null===(ee=e.message)||void 0===ee?void 0:ee.pongResp)?Kn.toJSON(null===(te=e.message)||void 0===te?void 0:te.pongResp):void 0),"subscriptionResponse"===(null===(ie=e.message)||void 0===ie?void 0:ie.$case)&&(se.subscriptionResponse=(null===(ne=e.message)||void 0===ne?void 0:ne.subscriptionResponse)?Qn.toJSON(null===(re=e.message)||void 0===re?void 0:re.subscriptionResponse):void 0),se},create:e=>pn.fromPartial(null!=e?e:{}),fromPartial(e){var t,i,n,r,s,o,a,c,d,u,l,h,p,m,f,v,g,b,k,y,S,C,E,T,P,w,R,N,O,I,D,A,U,M,L,_,x,B,J,F,$,V,j,q,W,G,K,Q,H,Z,z,Y,X,ee,te,ie,ne,re,se,oe;const ae={message:void 0};return"join"===(null===(t=e.message)||void 0===t?void 0:t.$case)&&void 0!==(null===(i=e.message)||void 0===i?void 0:i.join)&&null!==(null===(n=e.message)||void 0===n?void 0:n.join)&&(ae.message={$case:"join",join:kn.fromPartial(e.message.join)}),"answer"===(null===(r=e.message)||void 0===r?void 0:r.$case)&&void 0!==(null===(s=e.message)||void 0===s?void 0:s.answer)&&null!==(null===(o=e.message)||void 0===o?void 0:o.answer)&&(ae.message={$case:"answer",answer:En.fromPartial(e.message.answer)}),"offer"===(null===(a=e.message)||void 0===a?void 0:a.$case)&&void 0!==(null===(c=e.message)||void 0===c?void 0:c.offer)&&null!==(null===(d=e.message)||void 0===d?void 0:d.offer)&&(ae.message={$case:"offer",offer:En.fromPartial(e.message.offer)}),"trickle"===(null===(u=e.message)||void 0===u?void 0:u.$case)&&void 0!==(null===(l=e.message)||void 0===l?void 0:l.trickle)&&null!==(null===(h=e.message)||void 0===h?void 0:h.trickle)&&(ae.message={$case:"trickle",trickle:vn.fromPartial(e.message.trickle)}),"update"===(null===(p=e.message)||void 0===p?void 0:p.$case)&&void 0!==(null===(m=e.message)||void 0===m?void 0:m.update)&&null!==(null===(f=e.message)||void 0===f?void 0:f.update)&&(ae.message={$case:"update",update:Tn.fromPartial(e.message.update)}),"trackPublished"===(null===(v=e.message)||void 0===v?void 0:v.$case)&&void 0!==(null===(g=e.message)||void 0===g?void 0:g.trackPublished)&&null!==(null===(b=e.message)||void 0===b?void 0:b.trackPublished)&&(ae.message={$case:"trackPublished",trackPublished:Sn.fromPartial(e.message.trackPublished)}),"leave"===(null===(k=e.message)||void 0===k?void 0:k.$case)&&void 0!==(null===(y=e.message)||void 0===y?void 0:y.leave)&&null!==(null===(S=e.message)||void 0===S?void 0:S.leave)&&(ae.message={$case:"leave",leave:Rn.fromPartial(e.message.leave)}),"mute"===(null===(C=e.message)||void 0===C?void 0:C.$case)&&void 0!==(null===(E=e.message)||void 0===E?void 0:E.mute)&&null!==(null===(T=e.message)||void 0===T?void 0:T.mute)&&(ae.message={$case:"mute",mute:gn.fromPartial(e.message.mute)}),"speakersChanged"===(null===(P=e.message)||void 0===P?void 0:P.$case)&&void 0!==(null===(w=e.message)||void 0===w?void 0:w.speakersChanged)&&null!==(null===(R=e.message)||void 0===R?void 0:R.speakersChanged)&&(ae.message={$case:"speakersChanged",speakersChanged:Dn.fromPartial(e.message.speakersChanged)}),"roomUpdate"===(null===(N=e.message)||void 0===N?void 0:N.$case)&&void 0!==(null===(O=e.message)||void 0===O?void 0:O.roomUpdate)&&null!==(null===(I=e.message)||void 0===I?void 0:I.roomUpdate)&&(ae.message={$case:"roomUpdate",roomUpdate:An.fromPartial(e.message.roomUpdate)}),"connectionQuality"===(null===(D=e.message)||void 0===D?void 0:D.$case)&&void 0!==(null===(A=e.message)||void 0===A?void 0:A.connectionQuality)&&null!==(null===(U=e.message)||void 0===U?void 0:U.connectionQuality)&&(ae.message={$case:"connectionQuality",connectionQuality:Mn.fromPartial(e.message.connectionQuality)}),"streamStateUpdate"===(null===(M=e.message)||void 0===M?void 0:M.$case)&&void 0!==(null===(L=e.message)||void 0===L?void 0:L.streamStateUpdate)&&null!==(null===(_=e.message)||void 0===_?void 0:_.streamStateUpdate)&&(ae.message={$case:"streamStateUpdate",streamStateUpdate:_n.fromPartial(e.message.streamStateUpdate)}),"subscribedQualityUpdate"===(null===(x=e.message)||void 0===x?void 0:x.$case)&&void 0!==(null===(B=e.message)||void 0===B?void 0:B.subscribedQualityUpdate)&&null!==(null===(J=e.message)||void 0===J?void 0:J.subscribedQualityUpdate)&&(ae.message={$case:"subscribedQualityUpdate",subscribedQualityUpdate:Jn.fromPartial(e.message.subscribedQualityUpdate)}),"subscriptionPermissionUpdate"===(null===(F=e.message)||void 0===F?void 0:F.$case)&&void 0!==(null===($=e.message)||void 0===$?void 0:$.subscriptionPermissionUpdate)&&null!==(null===(V=e.message)||void 0===V?void 0:V.subscriptionPermissionUpdate)&&(ae.message={$case:"subscriptionPermissionUpdate",subscriptionPermissionUpdate:Vn.fromPartial(e.message.subscriptionPermissionUpdate)}),"refreshToken"===(null===(j=e.message)||void 0===j?void 0:j.$case)&&void 0!==(null===(q=e.message)||void 0===q?void 0:q.refreshToken)&&null!==(null===(W=e.message)||void 0===W?void 0:W.refreshToken)&&(ae.message={$case:"refreshToken",refreshToken:e.message.refreshToken}),"trackUnpublished"===(null===(G=e.message)||void 0===G?void 0:G.$case)&&void 0!==(null===(K=e.message)||void 0===K?void 0:K.trackUnpublished)&&null!==(null===(Q=e.message)||void 0===Q?void 0:Q.trackUnpublished)&&(ae.message={$case:"trackUnpublished",trackUnpublished:Cn.fromPartial(e.message.trackUnpublished)}),"pong"===(null===(H=e.message)||void 0===H?void 0:H.$case)&&void 0!==(null===(Z=e.message)||void 0===Z?void 0:Z.pong)&&null!==(null===(z=e.message)||void 0===z?void 0:z.pong)&&(ae.message={$case:"pong",pong:e.message.pong}),"reconnect"===(null===(Y=e.message)||void 0===Y?void 0:Y.$case)&&void 0!==(null===(X=e.message)||void 0===X?void 0:X.reconnect)&&null!==(null===(ee=e.message)||void 0===ee?void 0:ee.reconnect)&&(ae.message={$case:"reconnect",reconnect:yn.fromPartial(e.message.reconnect)}),"pongResp"===(null===(te=e.message)||void 0===te?void 0:te.$case)&&void 0!==(null===(ie=e.message)||void 0===ie?void 0:ie.pongResp)&&null!==(null===(ne=e.message)||void 0===ne?void 0:ne.pongResp)&&(ae.message={$case:"pongResp",pongResp:Kn.fromPartial(e.message.pongResp)}),"subscriptionResponse"===(null===(re=e.message)||void 0===re?void 0:re.$case)&&void 0!==(null===(se=e.message)||void 0===se?void 0:se.subscriptionResponse)&&null!==(null===(oe=e.message)||void 0===oe?void 0:oe.subscriptionResponse)&&(ae.message={$case:"subscriptionResponse",subscriptionResponse:Qn.fromPartial(e.message.subscriptionResponse)}),ae}};const mn={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:st.Writer.create();return""!==e.codec&&t.uint32(10).string(e.codec),""!==e.cid&&t.uint32(18).string(e.cid),!0===e.enableSimulcastLayers&&t.uint32(24).bool(e.enableSimulcastLayers),t},decode(e,t){const i=e instanceof st.Reader?e:st.Reader.create(e);let n=void 0===t?i.len:i.pos+t;const r={codec:"",cid:"",enableSimulcastLayers:!1};for(;i.pos<n;){const e=i.uint32();switch(e>>>3){case 1:if(10!==e)break;r.codec=i.string();continue;case 2:if(18!==e)break;r.cid=i.string();continue;case 3:if(24!==e)break;r.enableSimulcastLayers=i.bool();continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return r},fromJSON:e=>({codec:Xn(e.codec)?String(e.codec):"",cid:Xn(e.cid)?String(e.cid):"",enableSimulcastLayers:!!Xn(e.enableSimulcastLayers)&&Boolean(e.enableSimulcastLayers)}),toJSON(e){const t={};return void 0!==e.codec&&(t.codec=e.codec),void 0!==e.cid&&(t.cid=e.cid),void 0!==e.enableSimulcastLayers&&(t.enableSimulcastLayers=e.enableSimulcastLayers),t},create:e=>mn.fromPartial(null!=e?e:{}),fromPartial(e){var t,i,n;const r={codec:"",cid:"",enableSimulcastLayers:!1};return r.codec=null!==(t=e.codec)&&void 0!==t?t:"",r.cid=null!==(i=e.cid)&&void 0!==i?i:"",r.enableSimulcastLayers=null!==(n=e.enableSimulcastLayers)&&void 0!==n&&n,r}};const fn={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:st.Writer.create();""!==e.cid&&t.uint32(10).string(e.cid),""!==e.name&&t.uint32(18).string(e.name),0!==e.type&&t.uint32(24).int32(e.type),0!==e.width&&t.uint32(32).uint32(e.width),0!==e.height&&t.uint32(40).uint32(e.height),!0===e.muted&&t.uint32(48).bool(e.muted),!0===e.disableDtx&&t.uint32(56).bool(e.disableDtx),0!==e.source&&t.uint32(64).int32(e.source);for(const i of e.layers)Ot.encode(i,t.uint32(74).fork()).ldelim();for(const i of e.simulcastCodecs)mn.encode(i,t.uint32(82).fork()).ldelim();return""!==e.sid&&t.uint32(90).string(e.sid),!0===e.stereo&&t.uint32(96).bool(e.stereo),!0===e.disableRed&&t.uint32(104).bool(e.disableRed),0!==e.encryption&&t.uint32(112).int32(e.encryption),t},decode(e,t){const i=e instanceof st.Reader?e:st.Reader.create(e);let n=void 0===t?i.len:i.pos+t;const r={cid:"",name:"",type:0,width:0,height:0,muted:!1,disableDtx:!1,source:0,layers:[],simulcastCodecs:[],sid:"",stereo:!1,disableRed:!1,encryption:0};for(;i.pos<n;){const e=i.uint32();switch(e>>>3){case 1:if(10!==e)break;r.cid=i.string();continue;case 2:if(18!==e)break;r.name=i.string();continue;case 3:if(24!==e)break;r.type=i.int32();continue;case 4:if(32!==e)break;r.width=i.uint32();continue;case 5:if(40!==e)break;r.height=i.uint32();continue;case 6:if(48!==e)break;r.muted=i.bool();continue;case 7:if(56!==e)break;r.disableDtx=i.bool();continue;case 8:if(64!==e)break;r.source=i.int32();continue;case 9:if(74!==e)break;r.layers.push(Ot.decode(i,i.uint32()));continue;case 10:if(82!==e)break;r.simulcastCodecs.push(mn.decode(i,i.uint32()));continue;case 11:if(90!==e)break;r.sid=i.string();continue;case 12:if(96!==e)break;r.stereo=i.bool();continue;case 13:if(104!==e)break;r.disableRed=i.bool();continue;case 14:if(112!==e)break;r.encryption=i.int32();continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return r},fromJSON:e=>({cid:Xn(e.cid)?String(e.cid):"",name:Xn(e.name)?String(e.name):"",type:Xn(e.type)?ot(e.type):0,width:Xn(e.width)?Number(e.width):0,height:Xn(e.height)?Number(e.height):0,muted:!!Xn(e.muted)&&Boolean(e.muted),disableDtx:!!Xn(e.disableDtx)&&Boolean(e.disableDtx),source:Xn(e.source)?ct(e.source):0,layers:Array.isArray(null==e?void 0:e.layers)?e.layers.map((e=>Ot.fromJSON(e))):[],simulcastCodecs:Array.isArray(null==e?void 0:e.simulcastCodecs)?e.simulcastCodecs.map((e=>mn.fromJSON(e))):[],sid:Xn(e.sid)?String(e.sid):"",stereo:!!Xn(e.stereo)&&Boolean(e.stereo),disableRed:!!Xn(e.disableRed)&&Boolean(e.disableRed),encryption:Xn(e.encryption)?bt(e.encryption):0}),toJSON(e){const t={};return void 0!==e.cid&&(t.cid=e.cid),void 0!==e.name&&(t.name=e.name),void 0!==e.type&&(t.type=at(e.type)),void 0!==e.width&&(t.width=Math.round(e.width)),void 0!==e.height&&(t.height=Math.round(e.height)),void 0!==e.muted&&(t.muted=e.muted),void 0!==e.disableDtx&&(t.disableDtx=e.disableDtx),void 0!==e.source&&(t.source=dt(e.source)),e.layers?t.layers=e.layers.map((e=>e?Ot.toJSON(e):void 0)):t.layers=[],e.simulcastCodecs?t.simulcastCodecs=e.simulcastCodecs.map((e=>e?mn.toJSON(e):void 0)):t.simulcastCodecs=[],void 0!==e.sid&&(t.sid=e.sid),void 0!==e.stereo&&(t.stereo=e.stereo),void 0!==e.disableRed&&(t.disableRed=e.disableRed),void 0!==e.encryption&&(t.encryption=kt(e.encryption)),t},create:e=>fn.fromPartial(null!=e?e:{}),fromPartial(e){var t,i,n,r,s,o,a,c,d,u,l,h,p,m;const f={cid:"",name:"",type:0,width:0,height:0,muted:!1,disableDtx:!1,source:0,layers:[],simulcastCodecs:[],sid:"",stereo:!1,disableRed:!1,encryption:0};return f.cid=null!==(t=e.cid)&&void 0!==t?t:"",f.name=null!==(i=e.name)&&void 0!==i?i:"",f.type=null!==(n=e.type)&&void 0!==n?n:0,f.width=null!==(r=e.width)&&void 0!==r?r:0,f.height=null!==(s=e.height)&&void 0!==s?s:0,f.muted=null!==(o=e.muted)&&void 0!==o&&o,f.disableDtx=null!==(a=e.disableDtx)&&void 0!==a&&a,f.source=null!==(c=e.source)&&void 0!==c?c:0,f.layers=(null===(d=e.layers)||void 0===d?void 0:d.map((e=>Ot.fromPartial(e))))||[],f.simulcastCodecs=(null===(u=e.simulcastCodecs)||void 0===u?void 0:u.map((e=>mn.fromPartial(e))))||[],f.sid=null!==(l=e.sid)&&void 0!==l?l:"",f.stereo=null!==(h=e.stereo)&&void 0!==h&&h,f.disableRed=null!==(p=e.disableRed)&&void 0!==p&&p,f.encryption=null!==(m=e.encryption)&&void 0!==m?m:0,f}};const vn={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:st.Writer.create();return""!==e.candidateInit&&t.uint32(10).string(e.candidateInit),0!==e.target&&t.uint32(16).int32(e.target),t},decode(e,t){const i=e instanceof st.Reader?e:st.Reader.create(e);let n=void 0===t?i.len:i.pos+t;const r={candidateInit:"",target:0};for(;i.pos<n;){const e=i.uint32();switch(e>>>3){case 1:if(10!==e)break;r.candidateInit=i.string();continue;case 2:if(16!==e)break;r.target=i.int32();continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return r},fromJSON:e=>({candidateInit:Xn(e.candidateInit)?String(e.candidateInit):"",target:Xn(e.target)?cn(e.target):0}),toJSON(e){const t={};return void 0!==e.candidateInit&&(t.candidateInit=e.candidateInit),void 0!==e.target&&(t.target=dn(e.target)),t},create:e=>vn.fromPartial(null!=e?e:{}),fromPartial(e){var t,i;const n={candidateInit:"",target:0};return n.candidateInit=null!==(t=e.candidateInit)&&void 0!==t?t:"",n.target=null!==(i=e.target)&&void 0!==i?i:0,n}};const gn={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:st.Writer.create();return""!==e.sid&&t.uint32(10).string(e.sid),!0===e.muted&&t.uint32(16).bool(e.muted),t},decode(e,t){const i=e instanceof st.Reader?e:st.Reader.create(e);let n=void 0===t?i.len:i.pos+t;const r={sid:"",muted:!1};for(;i.pos<n;){const e=i.uint32();switch(e>>>3){case 1:if(10!==e)break;r.sid=i.string();continue;case 2:if(16!==e)break;r.muted=i.bool();continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return r},fromJSON:e=>({sid:Xn(e.sid)?String(e.sid):"",muted:!!Xn(e.muted)&&Boolean(e.muted)}),toJSON(e){const t={};return void 0!==e.sid&&(t.sid=e.sid),void 0!==e.muted&&(t.muted=e.muted),t},create:e=>gn.fromPartial(null!=e?e:{}),fromPartial(e){var t,i;const n={sid:"",muted:!1};return n.sid=null!==(t=e.sid)&&void 0!==t?t:"",n.muted=null!==(i=e.muted)&&void 0!==i&&i,n}};function bn(){return{room:void 0,participant:void 0,otherParticipants:[],serverVersion:"",iceServers:[],subscriberPrimary:!1,alternativeUrl:"",clientConfiguration:void 0,serverRegion:"",pingTimeout:0,pingInterval:0,serverInfo:void 0,sifTrailer:new Uint8Array}}const kn={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:st.Writer.create();void 0!==e.room&&Et.encode(e.room,t.uint32(10).fork()).ldelim(),void 0!==e.participant&&wt.encode(e.participant,t.uint32(18).fork()).ldelim();for(const i of e.otherParticipants)wt.encode(i,t.uint32(26).fork()).ldelim();""!==e.serverVersion&&t.uint32(34).string(e.serverVersion);for(const i of e.iceServers)In.encode(i,t.uint32(42).fork()).ldelim();return!0===e.subscriberPrimary&&t.uint32(48).bool(e.subscriberPrimary),""!==e.alternativeUrl&&t.uint32(58).string(e.alternativeUrl),void 0!==e.clientConfiguration&&Bt.encode(e.clientConfiguration,t.uint32(66).fork()).ldelim(),""!==e.serverRegion&&t.uint32(74).string(e.serverRegion),0!==e.pingTimeout&&t.uint32(80).int32(e.pingTimeout),0!==e.pingInterval&&t.uint32(88).int32(e.pingInterval),void 0!==e.serverInfo&&_t.encode(e.serverInfo,t.uint32(98).fork()).ldelim(),0!==e.sifTrailer.length&&t.uint32(106).bytes(e.sifTrailer),t},decode(e,t){const i=e instanceof st.Reader?e:st.Reader.create(e);let n=void 0===t?i.len:i.pos+t;const r=bn();for(;i.pos<n;){const e=i.uint32();switch(e>>>3){case 1:if(10!==e)break;r.room=Et.decode(i,i.uint32());continue;case 2:if(18!==e)break;r.participant=wt.decode(i,i.uint32());continue;case 3:if(26!==e)break;r.otherParticipants.push(wt.decode(i,i.uint32()));continue;case 4:if(34!==e)break;r.serverVersion=i.string();continue;case 5:if(42!==e)break;r.iceServers.push(In.decode(i,i.uint32()));continue;case 6:if(48!==e)break;r.subscriberPrimary=i.bool();continue;case 7:if(58!==e)break;r.alternativeUrl=i.string();continue;case 8:if(66!==e)break;r.clientConfiguration=Bt.decode(i,i.uint32());continue;case 9:if(74!==e)break;r.serverRegion=i.string();continue;case 10:if(80!==e)break;r.pingTimeout=i.int32();continue;case 11:if(88!==e)break;r.pingInterval=i.int32();continue;case 12:if(98!==e)break;r.serverInfo=_t.decode(i,i.uint32());continue;case 13:if(106!==e)break;r.sifTrailer=i.bytes();continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return r},fromJSON:e=>({room:Xn(e.room)?Et.fromJSON(e.room):void 0,participant:Xn(e.participant)?wt.fromJSON(e.participant):void 0,otherParticipants:Array.isArray(null==e?void 0:e.otherParticipants)?e.otherParticipants.map((e=>wt.fromJSON(e))):[],serverVersion:Xn(e.serverVersion)?String(e.serverVersion):"",iceServers:Array.isArray(null==e?void 0:e.iceServers)?e.iceServers.map((e=>In.fromJSON(e))):[],subscriberPrimary:!!Xn(e.subscriberPrimary)&&Boolean(e.subscriberPrimary),alternativeUrl:Xn(e.alternativeUrl)?String(e.alternativeUrl):"",clientConfiguration:Xn(e.clientConfiguration)?Bt.fromJSON(e.clientConfiguration):void 0,serverRegion:Xn(e.serverRegion)?String(e.serverRegion):"",pingTimeout:Xn(e.pingTimeout)?Number(e.pingTimeout):0,pingInterval:Xn(e.pingInterval)?Number(e.pingInterval):0,serverInfo:Xn(e.serverInfo)?_t.fromJSON(e.serverInfo):void 0,sifTrailer:Xn(e.sifTrailer)?zn(e.sifTrailer):new Uint8Array}),toJSON(e){const t={};return void 0!==e.room&&(t.room=e.room?Et.toJSON(e.room):void 0),void 0!==e.participant&&(t.participant=e.participant?wt.toJSON(e.participant):void 0),e.otherParticipants?t.otherParticipants=e.otherParticipants.map((e=>e?wt.toJSON(e):void 0)):t.otherParticipants=[],void 0!==e.serverVersion&&(t.serverVersion=e.serverVersion),e.iceServers?t.iceServers=e.iceServers.map((e=>e?In.toJSON(e):void 0)):t.iceServers=[],void 0!==e.subscriberPrimary&&(t.subscriberPrimary=e.subscriberPrimary),void 0!==e.alternativeUrl&&(t.alternativeUrl=e.alternativeUrl),void 0!==e.clientConfiguration&&(t.clientConfiguration=e.clientConfiguration?Bt.toJSON(e.clientConfiguration):void 0),void 0!==e.serverRegion&&(t.serverRegion=e.serverRegion),void 0!==e.pingTimeout&&(t.pingTimeout=Math.round(e.pingTimeout)),void 0!==e.pingInterval&&(t.pingInterval=Math.round(e.pingInterval)),void 0!==e.serverInfo&&(t.serverInfo=e.serverInfo?_t.toJSON(e.serverInfo):void 0),void 0!==e.sifTrailer&&(t.sifTrailer=function(e){if(Zn.Buffer)return Zn.Buffer.from(e).toString("base64");{const t=[];return e.forEach((e=>{t.push(String.fromCharCode(e))})),Zn.btoa(t.join(""))}}(void 0!==e.sifTrailer?e.sifTrailer:new Uint8Array)),t},create:e=>kn.fromPartial(null!=e?e:{}),fromPartial(e){var t,i,n,r,s,o,a,c,d;const u=bn();return u.room=void 0!==e.room&&null!==e.room?Et.fromPartial(e.room):void 0,u.participant=void 0!==e.participant&&null!==e.participant?wt.fromPartial(e.participant):void 0,u.otherParticipants=(null===(t=e.otherParticipants)||void 0===t?void 0:t.map((e=>wt.fromPartial(e))))||[],u.serverVersion=null!==(i=e.serverVersion)&&void 0!==i?i:"",u.iceServers=(null===(n=e.iceServers)||void 0===n?void 0:n.map((e=>In.fromPartial(e))))||[],u.subscriberPrimary=null!==(r=e.subscriberPrimary)&&void 0!==r&&r,u.alternativeUrl=null!==(s=e.alternativeUrl)&&void 0!==s?s:"",u.clientConfiguration=void 0!==e.clientConfiguration&&null!==e.clientConfiguration?Bt.fromPartial(e.clientConfiguration):void 0,u.serverRegion=null!==(o=e.serverRegion)&&void 0!==o?o:"",u.pingTimeout=null!==(a=e.pingTimeout)&&void 0!==a?a:0,u.pingInterval=null!==(c=e.pingInterval)&&void 0!==c?c:0,u.serverInfo=void 0!==e.serverInfo&&null!==e.serverInfo?_t.fromPartial(e.serverInfo):void 0,u.sifTrailer=null!==(d=e.sifTrailer)&&void 0!==d?d:new Uint8Array,u}};const yn={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:st.Writer.create();for(const i of e.iceServers)In.encode(i,t.uint32(10).fork()).ldelim();return void 0!==e.clientConfiguration&&Bt.encode(e.clientConfiguration,t.uint32(18).fork()).ldelim(),t},decode(e,t){const i=e instanceof st.Reader?e:st.Reader.create(e);let n=void 0===t?i.len:i.pos+t;const r={iceServers:[],clientConfiguration:void 0};for(;i.pos<n;){const e=i.uint32();switch(e>>>3){case 1:if(10!==e)break;r.iceServers.push(In.decode(i,i.uint32()));continue;case 2:if(18!==e)break;r.clientConfiguration=Bt.decode(i,i.uint32());continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return r},fromJSON:e=>({iceServers:Array.isArray(null==e?void 0:e.iceServers)?e.iceServers.map((e=>In.fromJSON(e))):[],clientConfiguration:Xn(e.clientConfiguration)?Bt.fromJSON(e.clientConfiguration):void 0}),toJSON(e){const t={};return e.iceServers?t.iceServers=e.iceServers.map((e=>e?In.toJSON(e):void 0)):t.iceServers=[],void 0!==e.clientConfiguration&&(t.clientConfiguration=e.clientConfiguration?Bt.toJSON(e.clientConfiguration):void 0),t},create:e=>yn.fromPartial(null!=e?e:{}),fromPartial(e){var t;const i={iceServers:[],clientConfiguration:void 0};return i.iceServers=(null===(t=e.iceServers)||void 0===t?void 0:t.map((e=>In.fromPartial(e))))||[],i.clientConfiguration=void 0!==e.clientConfiguration&&null!==e.clientConfiguration?Bt.fromPartial(e.clientConfiguration):void 0,i}};const Sn={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:st.Writer.create();return""!==e.cid&&t.uint32(10).string(e.cid),void 0!==e.track&&Nt.encode(e.track,t.uint32(18).fork()).ldelim(),t},decode(e,t){const i=e instanceof st.Reader?e:st.Reader.create(e);let n=void 0===t?i.len:i.pos+t;const r={cid:"",track:void 0};for(;i.pos<n;){const e=i.uint32();switch(e>>>3){case 1:if(10!==e)break;r.cid=i.string();continue;case 2:if(18!==e)break;r.track=Nt.decode(i,i.uint32());continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return r},fromJSON:e=>({cid:Xn(e.cid)?String(e.cid):"",track:Xn(e.track)?Nt.fromJSON(e.track):void 0}),toJSON(e){const t={};return void 0!==e.cid&&(t.cid=e.cid),void 0!==e.track&&(t.track=e.track?Nt.toJSON(e.track):void 0),t},create:e=>Sn.fromPartial(null!=e?e:{}),fromPartial(e){var t;const i={cid:"",track:void 0};return i.cid=null!==(t=e.cid)&&void 0!==t?t:"",i.track=void 0!==e.track&&null!==e.track?Nt.fromPartial(e.track):void 0,i}};const Cn={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:st.Writer.create();return""!==e.trackSid&&t.uint32(10).string(e.trackSid),t},decode(e,t){const i=e instanceof st.Reader?e:st.Reader.create(e);let n=void 0===t?i.len:i.pos+t;const r={trackSid:""};for(;i.pos<n;){const e=i.uint32();switch(e>>>3){case 1:if(10!==e)break;r.trackSid=i.string();continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return r},fromJSON:e=>({trackSid:Xn(e.trackSid)?String(e.trackSid):""}),toJSON(e){const t={};return void 0!==e.trackSid&&(t.trackSid=e.trackSid),t},create:e=>Cn.fromPartial(null!=e?e:{}),fromPartial(e){var t;const i={trackSid:""};return i.trackSid=null!==(t=e.trackSid)&&void 0!==t?t:"",i}};const En={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:st.Writer.create();return""!==e.type&&t.uint32(10).string(e.type),""!==e.sdp&&t.uint32(18).string(e.sdp),t},decode(e,t){const i=e instanceof st.Reader?e:st.Reader.create(e);let n=void 0===t?i.len:i.pos+t;const r={type:"",sdp:""};for(;i.pos<n;){const e=i.uint32();switch(e>>>3){case 1:if(10!==e)break;r.type=i.string();continue;case 2:if(18!==e)break;r.sdp=i.string();continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return r},fromJSON:e=>({type:Xn(e.type)?String(e.type):"",sdp:Xn(e.sdp)?String(e.sdp):""}),toJSON(e){const t={};return void 0!==e.type&&(t.type=e.type),void 0!==e.sdp&&(t.sdp=e.sdp),t},create:e=>En.fromPartial(null!=e?e:{}),fromPartial(e){var t,i;const n={type:"",sdp:""};return n.type=null!==(t=e.type)&&void 0!==t?t:"",n.sdp=null!==(i=e.sdp)&&void 0!==i?i:"",n}};const Tn={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:st.Writer.create();for(const i of e.participants)wt.encode(i,t.uint32(10).fork()).ldelim();return t},decode(e,t){const i=e instanceof st.Reader?e:st.Reader.create(e);let n=void 0===t?i.len:i.pos+t;const r={participants:[]};for(;i.pos<n;){const e=i.uint32();switch(e>>>3){case 1:if(10!==e)break;r.participants.push(wt.decode(i,i.uint32()));continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return r},fromJSON:e=>({participants:Array.isArray(null==e?void 0:e.participants)?e.participants.map((e=>wt.fromJSON(e))):[]}),toJSON(e){const t={};return e.participants?t.participants=e.participants.map((e=>e?wt.toJSON(e):void 0)):t.participants=[],t},create:e=>Tn.fromPartial(null!=e?e:{}),fromPartial(e){var t;const i={participants:[]};return i.participants=(null===(t=e.participants)||void 0===t?void 0:t.map((e=>wt.fromPartial(e))))||[],i}};const Pn={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:st.Writer.create();for(const i of e.trackSids)t.uint32(10).string(i);!0===e.subscribe&&t.uint32(16).bool(e.subscribe);for(const i of e.participantTracks)Lt.encode(i,t.uint32(26).fork()).ldelim();return t},decode(e,t){const i=e instanceof st.Reader?e:st.Reader.create(e);let n=void 0===t?i.len:i.pos+t;const r={trackSids:[],subscribe:!1,participantTracks:[]};for(;i.pos<n;){const e=i.uint32();switch(e>>>3){case 1:if(10!==e)break;r.trackSids.push(i.string());continue;case 2:if(16!==e)break;r.subscribe=i.bool();continue;case 3:if(26!==e)break;r.participantTracks.push(Lt.decode(i,i.uint32()));continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return r},fromJSON:e=>({trackSids:Array.isArray(null==e?void 0:e.trackSids)?e.trackSids.map((e=>String(e))):[],subscribe:!!Xn(e.subscribe)&&Boolean(e.subscribe),participantTracks:Array.isArray(null==e?void 0:e.participantTracks)?e.participantTracks.map((e=>Lt.fromJSON(e))):[]}),toJSON(e){const t={};return e.trackSids?t.trackSids=e.trackSids.map((e=>e)):t.trackSids=[],void 0!==e.subscribe&&(t.subscribe=e.subscribe),e.participantTracks?t.participantTracks=e.participantTracks.map((e=>e?Lt.toJSON(e):void 0)):t.participantTracks=[],t},create:e=>Pn.fromPartial(null!=e?e:{}),fromPartial(e){var t,i,n;const r={trackSids:[],subscribe:!1,participantTracks:[]};return r.trackSids=(null===(t=e.trackSids)||void 0===t?void 0:t.map((e=>e)))||[],r.subscribe=null!==(i=e.subscribe)&&void 0!==i&&i,r.participantTracks=(null===(n=e.participantTracks)||void 0===n?void 0:n.map((e=>Lt.fromPartial(e))))||[],r}};const wn={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:st.Writer.create();for(const i of e.trackSids)t.uint32(10).string(i);return!0===e.disabled&&t.uint32(24).bool(e.disabled),0!==e.quality&&t.uint32(32).int32(e.quality),0!==e.width&&t.uint32(40).uint32(e.width),0!==e.height&&t.uint32(48).uint32(e.height),0!==e.fps&&t.uint32(56).uint32(e.fps),0!==e.priority&&t.uint32(64).uint32(e.priority),t},decode(e,t){const i=e instanceof st.Reader?e:st.Reader.create(e);let n=void 0===t?i.len:i.pos+t;const r={trackSids:[],disabled:!1,quality:0,width:0,height:0,fps:0,priority:0};for(;i.pos<n;){const e=i.uint32();switch(e>>>3){case 1:if(10!==e)break;r.trackSids.push(i.string());continue;case 3:if(24!==e)break;r.disabled=i.bool();continue;case 4:if(32!==e)break;r.quality=i.int32();continue;case 5:if(40!==e)break;r.width=i.uint32();continue;case 6:if(48!==e)break;r.height=i.uint32();continue;case 7:if(56!==e)break;r.fps=i.uint32();continue;case 8:if(64!==e)break;r.priority=i.uint32();continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return r},fromJSON:e=>({trackSids:Array.isArray(null==e?void 0:e.trackSids)?e.trackSids.map((e=>String(e))):[],disabled:!!Xn(e.disabled)&&Boolean(e.disabled),quality:Xn(e.quality)?ut(e.quality):0,width:Xn(e.width)?Number(e.width):0,height:Xn(e.height)?Number(e.height):0,fps:Xn(e.fps)?Number(e.fps):0,priority:Xn(e.priority)?Number(e.priority):0}),toJSON(e){const t={};return e.trackSids?t.trackSids=e.trackSids.map((e=>e)):t.trackSids=[],void 0!==e.disabled&&(t.disabled=e.disabled),void 0!==e.quality&&(t.quality=lt(e.quality)),void 0!==e.width&&(t.width=Math.round(e.width)),void 0!==e.height&&(t.height=Math.round(e.height)),void 0!==e.fps&&(t.fps=Math.round(e.fps)),void 0!==e.priority&&(t.priority=Math.round(e.priority)),t},create:e=>wn.fromPartial(null!=e?e:{}),fromPartial(e){var t,i,n,r,s,o,a;const c={trackSids:[],disabled:!1,quality:0,width:0,height:0,fps:0,priority:0};return c.trackSids=(null===(t=e.trackSids)||void 0===t?void 0:t.map((e=>e)))||[],c.disabled=null!==(i=e.disabled)&&void 0!==i&&i,c.quality=null!==(n=e.quality)&&void 0!==n?n:0,c.width=null!==(r=e.width)&&void 0!==r?r:0,c.height=null!==(s=e.height)&&void 0!==s?s:0,c.fps=null!==(o=e.fps)&&void 0!==o?o:0,c.priority=null!==(a=e.priority)&&void 0!==a?a:0,c}};const Rn={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:st.Writer.create();return!0===e.canReconnect&&t.uint32(8).bool(e.canReconnect),0!==e.reason&&t.uint32(16).int32(e.reason),t},decode(e,t){const i=e instanceof st.Reader?e:st.Reader.create(e);let n=void 0===t?i.len:i.pos+t;const r={canReconnect:!1,reason:0};for(;i.pos<n;){const e=i.uint32();switch(e>>>3){case 1:if(8!==e)break;r.canReconnect=i.bool();continue;case 2:if(16!==e)break;r.reason=i.int32();continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return r},fromJSON:e=>({canReconnect:!!Xn(e.canReconnect)&&Boolean(e.canReconnect),reason:Xn(e.reason)?ft(e.reason):0}),toJSON(t){const i={};return void 0!==t.canReconnect&&(i.canReconnect=t.canReconnect),void 0!==t.reason&&(i.reason=function(t){switch(t){case e.DisconnectReason.UNKNOWN_REASON:return"UNKNOWN_REASON";case e.DisconnectReason.CLIENT_INITIATED:return"CLIENT_INITIATED";case e.DisconnectReason.DUPLICATE_IDENTITY:return"DUPLICATE_IDENTITY";case e.DisconnectReason.SERVER_SHUTDOWN:return"SERVER_SHUTDOWN";case e.DisconnectReason.PARTICIPANT_REMOVED:return"PARTICIPANT_REMOVED";case e.DisconnectReason.ROOM_DELETED:return"ROOM_DELETED";case e.DisconnectReason.STATE_MISMATCH:return"STATE_MISMATCH";case e.DisconnectReason.JOIN_FAILURE:return"JOIN_FAILURE";case e.DisconnectReason.UNRECOGNIZED:default:return"UNRECOGNIZED"}}(t.reason)),i},create:e=>Rn.fromPartial(null!=e?e:{}),fromPartial(e){var t,i;const n={canReconnect:!1,reason:0};return n.canReconnect=null!==(t=e.canReconnect)&&void 0!==t&&t,n.reason=null!==(i=e.reason)&&void 0!==i?i:0,n}};const Nn={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:st.Writer.create();""!==e.trackSid&&t.uint32(10).string(e.trackSid);for(const i of e.layers)Ot.encode(i,t.uint32(18).fork()).ldelim();return t},decode(e,t){const i=e instanceof st.Reader?e:st.Reader.create(e);let n=void 0===t?i.len:i.pos+t;const r={trackSid:"",layers:[]};for(;i.pos<n;){const e=i.uint32();switch(e>>>3){case 1:if(10!==e)break;r.trackSid=i.string();continue;case 2:if(18!==e)break;r.layers.push(Ot.decode(i,i.uint32()));continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return r},fromJSON:e=>({trackSid:Xn(e.trackSid)?String(e.trackSid):"",layers:Array.isArray(null==e?void 0:e.layers)?e.layers.map((e=>Ot.fromJSON(e))):[]}),toJSON(e){const t={};return void 0!==e.trackSid&&(t.trackSid=e.trackSid),e.layers?t.layers=e.layers.map((e=>e?Ot.toJSON(e):void 0)):t.layers=[],t},create:e=>Nn.fromPartial(null!=e?e:{}),fromPartial(e){var t,i;const n={trackSid:"",layers:[]};return n.trackSid=null!==(t=e.trackSid)&&void 0!==t?t:"",n.layers=(null===(i=e.layers)||void 0===i?void 0:i.map((e=>Ot.fromPartial(e))))||[],n}};const On={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:st.Writer.create();return""!==e.metadata&&t.uint32(10).string(e.metadata),""!==e.name&&t.uint32(18).string(e.name),t},decode(e,t){const i=e instanceof st.Reader?e:st.Reader.create(e);let n=void 0===t?i.len:i.pos+t;const r={metadata:"",name:""};for(;i.pos<n;){const e=i.uint32();switch(e>>>3){case 1:if(10!==e)break;r.metadata=i.string();continue;case 2:if(18!==e)break;r.name=i.string();continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return r},fromJSON:e=>({metadata:Xn(e.metadata)?String(e.metadata):"",name:Xn(e.name)?String(e.name):""}),toJSON(e){const t={};return void 0!==e.metadata&&(t.metadata=e.metadata),void 0!==e.name&&(t.name=e.name),t},create:e=>On.fromPartial(null!=e?e:{}),fromPartial(e){var t,i;const n={metadata:"",name:""};return n.metadata=null!==(t=e.metadata)&&void 0!==t?t:"",n.name=null!==(i=e.name)&&void 0!==i?i:"",n}};const In={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:st.Writer.create();for(const i of e.urls)t.uint32(10).string(i);return""!==e.username&&t.uint32(18).string(e.username),""!==e.credential&&t.uint32(26).string(e.credential),t},decode(e,t){const i=e instanceof st.Reader?e:st.Reader.create(e);let n=void 0===t?i.len:i.pos+t;const r={urls:[],username:"",credential:""};for(;i.pos<n;){const e=i.uint32();switch(e>>>3){case 1:if(10!==e)break;r.urls.push(i.string());continue;case 2:if(18!==e)break;r.username=i.string();continue;case 3:if(26!==e)break;r.credential=i.string();continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return r},fromJSON:e=>({urls:Array.isArray(null==e?void 0:e.urls)?e.urls.map((e=>String(e))):[],username:Xn(e.username)?String(e.username):"",credential:Xn(e.credential)?String(e.credential):""}),toJSON(e){const t={};return e.urls?t.urls=e.urls.map((e=>e)):t.urls=[],void 0!==e.username&&(t.username=e.username),void 0!==e.credential&&(t.credential=e.credential),t},create:e=>In.fromPartial(null!=e?e:{}),fromPartial(e){var t,i,n;const r={urls:[],username:"",credential:""};return r.urls=(null===(t=e.urls)||void 0===t?void 0:t.map((e=>e)))||[],r.username=null!==(i=e.username)&&void 0!==i?i:"",r.credential=null!==(n=e.credential)&&void 0!==n?n:"",r}};const Dn={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:st.Writer.create();for(const i of e.speakers)At.encode(i,t.uint32(10).fork()).ldelim();return t},decode(e,t){const i=e instanceof st.Reader?e:st.Reader.create(e);let n=void 0===t?i.len:i.pos+t;const r={speakers:[]};for(;i.pos<n;){const e=i.uint32();switch(e>>>3){case 1:if(10!==e)break;r.speakers.push(At.decode(i,i.uint32()));continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return r},fromJSON:e=>({speakers:Array.isArray(null==e?void 0:e.speakers)?e.speakers.map((e=>At.fromJSON(e))):[]}),toJSON(e){const t={};return e.speakers?t.speakers=e.speakers.map((e=>e?At.toJSON(e):void 0)):t.speakers=[],t},create:e=>Dn.fromPartial(null!=e?e:{}),fromPartial(e){var t;const i={speakers:[]};return i.speakers=(null===(t=e.speakers)||void 0===t?void 0:t.map((e=>At.fromPartial(e))))||[],i}};const An={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:st.Writer.create();return void 0!==e.room&&Et.encode(e.room,t.uint32(10).fork()).ldelim(),t},decode(e,t){const i=e instanceof st.Reader?e:st.Reader.create(e);let n=void 0===t?i.len:i.pos+t;const r={room:void 0};for(;i.pos<n;){const e=i.uint32();switch(e>>>3){case 1:if(10!==e)break;r.room=Et.decode(i,i.uint32());continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return r},fromJSON:e=>({room:Xn(e.room)?Et.fromJSON(e.room):void 0}),toJSON(e){const t={};return void 0!==e.room&&(t.room=e.room?Et.toJSON(e.room):void 0),t},create:e=>An.fromPartial(null!=e?e:{}),fromPartial(e){const t={room:void 0};return t.room=void 0!==e.room&&null!==e.room?Et.fromPartial(e.room):void 0,t}};const Un={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:st.Writer.create();return""!==e.participantSid&&t.uint32(10).string(e.participantSid),0!==e.quality&&t.uint32(16).int32(e.quality),0!==e.score&&t.uint32(29).float(e.score),t},decode(e,t){const i=e instanceof st.Reader?e:st.Reader.create(e);let n=void 0===t?i.len:i.pos+t;const r={participantSid:"",quality:0,score:0};for(;i.pos<n;){const e=i.uint32();switch(e>>>3){case 1:if(10!==e)break;r.participantSid=i.string();continue;case 2:if(16!==e)break;r.quality=i.int32();continue;case 3:if(29!==e)break;r.score=i.float();continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return r},fromJSON:e=>({participantSid:Xn(e.participantSid)?String(e.participantSid):"",quality:Xn(e.quality)?ht(e.quality):0,score:Xn(e.score)?Number(e.score):0}),toJSON(e){const t={};return void 0!==e.participantSid&&(t.participantSid=e.participantSid),void 0!==e.quality&&(t.quality=function(e){switch(e){case He.POOR:return"POOR";case He.GOOD:return"GOOD";case He.EXCELLENT:return"EXCELLENT";case He.UNRECOGNIZED:default:return"UNRECOGNIZED"}}(e.quality)),void 0!==e.score&&(t.score=e.score),t},create:e=>Un.fromPartial(null!=e?e:{}),fromPartial(e){var t,i,n;const r={participantSid:"",quality:0,score:0};return r.participantSid=null!==(t=e.participantSid)&&void 0!==t?t:"",r.quality=null!==(i=e.quality)&&void 0!==i?i:0,r.score=null!==(n=e.score)&&void 0!==n?n:0,r}};const Mn={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:st.Writer.create();for(const i of e.updates)Un.encode(i,t.uint32(10).fork()).ldelim();return t},decode(e,t){const i=e instanceof st.Reader?e:st.Reader.create(e);let n=void 0===t?i.len:i.pos+t;const r={updates:[]};for(;i.pos<n;){const e=i.uint32();switch(e>>>3){case 1:if(10!==e)break;r.updates.push(Un.decode(i,i.uint32()));continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return r},fromJSON:e=>({updates:Array.isArray(null==e?void 0:e.updates)?e.updates.map((e=>Un.fromJSON(e))):[]}),toJSON(e){const t={};return e.updates?t.updates=e.updates.map((e=>e?Un.toJSON(e):void 0)):t.updates=[],t},create:e=>Mn.fromPartial(null!=e?e:{}),fromPartial(e){var t;const i={updates:[]};return i.updates=(null===(t=e.updates)||void 0===t?void 0:t.map((e=>Un.fromPartial(e))))||[],i}};const Ln={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:st.Writer.create();return""!==e.participantSid&&t.uint32(10).string(e.participantSid),""!==e.trackSid&&t.uint32(18).string(e.trackSid),0!==e.state&&t.uint32(24).int32(e.state),t},decode(e,t){const i=e instanceof st.Reader?e:st.Reader.create(e);let n=void 0===t?i.len:i.pos+t;const r={participantSid:"",trackSid:"",state:0};for(;i.pos<n;){const e=i.uint32();switch(e>>>3){case 1:if(10!==e)break;r.participantSid=i.string();continue;case 2:if(18!==e)break;r.trackSid=i.string();continue;case 3:if(24!==e)break;r.state=i.int32();continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return r},fromJSON:e=>({participantSid:Xn(e.participantSid)?String(e.participantSid):"",trackSid:Xn(e.trackSid)?String(e.trackSid):"",state:Xn(e.state)?un(e.state):0}),toJSON(e){const t={};return void 0!==e.participantSid&&(t.participantSid=e.participantSid),void 0!==e.trackSid&&(t.trackSid=e.trackSid),void 0!==e.state&&(t.state=function(e){switch(e){case sn.ACTIVE:return"ACTIVE";case sn.PAUSED:return"PAUSED";case sn.UNRECOGNIZED:default:return"UNRECOGNIZED"}}(e.state)),t},create:e=>Ln.fromPartial(null!=e?e:{}),fromPartial(e){var t,i,n;const r={participantSid:"",trackSid:"",state:0};return r.participantSid=null!==(t=e.participantSid)&&void 0!==t?t:"",r.trackSid=null!==(i=e.trackSid)&&void 0!==i?i:"",r.state=null!==(n=e.state)&&void 0!==n?n:0,r}};const _n={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:st.Writer.create();for(const i of e.streamStates)Ln.encode(i,t.uint32(10).fork()).ldelim();return t},decode(e,t){const i=e instanceof st.Reader?e:st.Reader.create(e);let n=void 0===t?i.len:i.pos+t;const r={streamStates:[]};for(;i.pos<n;){const e=i.uint32();switch(e>>>3){case 1:if(10!==e)break;r.streamStates.push(Ln.decode(i,i.uint32()));continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return r},fromJSON:e=>({streamStates:Array.isArray(null==e?void 0:e.streamStates)?e.streamStates.map((e=>Ln.fromJSON(e))):[]}),toJSON(e){const t={};return e.streamStates?t.streamStates=e.streamStates.map((e=>e?Ln.toJSON(e):void 0)):t.streamStates=[],t},create:e=>_n.fromPartial(null!=e?e:{}),fromPartial(e){var t;const i={streamStates:[]};return i.streamStates=(null===(t=e.streamStates)||void 0===t?void 0:t.map((e=>Ln.fromPartial(e))))||[],i}};const xn={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:st.Writer.create();return 0!==e.quality&&t.uint32(8).int32(e.quality),!0===e.enabled&&t.uint32(16).bool(e.enabled),t},decode(e,t){const i=e instanceof st.Reader?e:st.Reader.create(e);let n=void 0===t?i.len:i.pos+t;const r={quality:0,enabled:!1};for(;i.pos<n;){const e=i.uint32();switch(e>>>3){case 1:if(8!==e)break;r.quality=i.int32();continue;case 2:if(16!==e)break;r.enabled=i.bool();continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return r},fromJSON:e=>({quality:Xn(e.quality)?ut(e.quality):0,enabled:!!Xn(e.enabled)&&Boolean(e.enabled)}),toJSON(e){const t={};return void 0!==e.quality&&(t.quality=lt(e.quality)),void 0!==e.enabled&&(t.enabled=e.enabled),t},create:e=>xn.fromPartial(null!=e?e:{}),fromPartial(e){var t,i;const n={quality:0,enabled:!1};return n.quality=null!==(t=e.quality)&&void 0!==t?t:0,n.enabled=null!==(i=e.enabled)&&void 0!==i&&i,n}};const Bn={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:st.Writer.create();""!==e.codec&&t.uint32(10).string(e.codec);for(const i of e.qualities)xn.encode(i,t.uint32(18).fork()).ldelim();return t},decode(e,t){const i=e instanceof st.Reader?e:st.Reader.create(e);let n=void 0===t?i.len:i.pos+t;const r={codec:"",qualities:[]};for(;i.pos<n;){const e=i.uint32();switch(e>>>3){case 1:if(10!==e)break;r.codec=i.string();continue;case 2:if(18!==e)break;r.qualities.push(xn.decode(i,i.uint32()));continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return r},fromJSON:e=>({codec:Xn(e.codec)?String(e.codec):"",qualities:Array.isArray(null==e?void 0:e.qualities)?e.qualities.map((e=>xn.fromJSON(e))):[]}),toJSON(e){const t={};return void 0!==e.codec&&(t.codec=e.codec),e.qualities?t.qualities=e.qualities.map((e=>e?xn.toJSON(e):void 0)):t.qualities=[],t},create:e=>Bn.fromPartial(null!=e?e:{}),fromPartial(e){var t,i;const n={codec:"",qualities:[]};return n.codec=null!==(t=e.codec)&&void 0!==t?t:"",n.qualities=(null===(i=e.qualities)||void 0===i?void 0:i.map((e=>xn.fromPartial(e))))||[],n}};const Jn={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:st.Writer.create();""!==e.trackSid&&t.uint32(10).string(e.trackSid);for(const i of e.subscribedQualities)xn.encode(i,t.uint32(18).fork()).ldelim();for(const i of e.subscribedCodecs)Bn.encode(i,t.uint32(26).fork()).ldelim();return t},decode(e,t){const i=e instanceof st.Reader?e:st.Reader.create(e);let n=void 0===t?i.len:i.pos+t;const r={trackSid:"",subscribedQualities:[],subscribedCodecs:[]};for(;i.pos<n;){const e=i.uint32();switch(e>>>3){case 1:if(10!==e)break;r.trackSid=i.string();continue;case 2:if(18!==e)break;r.subscribedQualities.push(xn.decode(i,i.uint32()));continue;case 3:if(26!==e)break;r.subscribedCodecs.push(Bn.decode(i,i.uint32()));continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return r},fromJSON:e=>({trackSid:Xn(e.trackSid)?String(e.trackSid):"",subscribedQualities:Array.isArray(null==e?void 0:e.subscribedQualities)?e.subscribedQualities.map((e=>xn.fromJSON(e))):[],subscribedCodecs:Array.isArray(null==e?void 0:e.subscribedCodecs)?e.subscribedCodecs.map((e=>Bn.fromJSON(e))):[]}),toJSON(e){const t={};return void 0!==e.trackSid&&(t.trackSid=e.trackSid),e.subscribedQualities?t.subscribedQualities=e.subscribedQualities.map((e=>e?xn.toJSON(e):void 0)):t.subscribedQualities=[],e.subscribedCodecs?t.subscribedCodecs=e.subscribedCodecs.map((e=>e?Bn.toJSON(e):void 0)):t.subscribedCodecs=[],t},create:e=>Jn.fromPartial(null!=e?e:{}),fromPartial(e){var t,i,n;const r={trackSid:"",subscribedQualities:[],subscribedCodecs:[]};return r.trackSid=null!==(t=e.trackSid)&&void 0!==t?t:"",r.subscribedQualities=(null===(i=e.subscribedQualities)||void 0===i?void 0:i.map((e=>xn.fromPartial(e))))||[],r.subscribedCodecs=(null===(n=e.subscribedCodecs)||void 0===n?void 0:n.map((e=>Bn.fromPartial(e))))||[],r}};const Fn={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:st.Writer.create();""!==e.participantSid&&t.uint32(10).string(e.participantSid),!0===e.allTracks&&t.uint32(16).bool(e.allTracks);for(const i of e.trackSids)t.uint32(26).string(i);return""!==e.participantIdentity&&t.uint32(34).string(e.participantIdentity),t},decode(e,t){const i=e instanceof st.Reader?e:st.Reader.create(e);let n=void 0===t?i.len:i.pos+t;const r={participantSid:"",allTracks:!1,trackSids:[],participantIdentity:""};for(;i.pos<n;){const e=i.uint32();switch(e>>>3){case 1:if(10!==e)break;r.participantSid=i.string();continue;case 2:if(16!==e)break;r.allTracks=i.bool();continue;case 3:if(26!==e)break;r.trackSids.push(i.string());continue;case 4:if(34!==e)break;r.participantIdentity=i.string();continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return r},fromJSON:e=>({participantSid:Xn(e.participantSid)?String(e.participantSid):"",allTracks:!!Xn(e.allTracks)&&Boolean(e.allTracks),trackSids:Array.isArray(null==e?void 0:e.trackSids)?e.trackSids.map((e=>String(e))):[],participantIdentity:Xn(e.participantIdentity)?String(e.participantIdentity):""}),toJSON(e){const t={};return void 0!==e.participantSid&&(t.participantSid=e.participantSid),void 0!==e.allTracks&&(t.allTracks=e.allTracks),e.trackSids?t.trackSids=e.trackSids.map((e=>e)):t.trackSids=[],void 0!==e.participantIdentity&&(t.participantIdentity=e.participantIdentity),t},create:e=>Fn.fromPartial(null!=e?e:{}),fromPartial(e){var t,i,n,r;const s={participantSid:"",allTracks:!1,trackSids:[],participantIdentity:""};return s.participantSid=null!==(t=e.participantSid)&&void 0!==t?t:"",s.allTracks=null!==(i=e.allTracks)&&void 0!==i&&i,s.trackSids=(null===(n=e.trackSids)||void 0===n?void 0:n.map((e=>e)))||[],s.participantIdentity=null!==(r=e.participantIdentity)&&void 0!==r?r:"",s}};const $n={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:st.Writer.create();!0===e.allParticipants&&t.uint32(8).bool(e.allParticipants);for(const i of e.trackPermissions)Fn.encode(i,t.uint32(18).fork()).ldelim();return t},decode(e,t){const i=e instanceof st.Reader?e:st.Reader.create(e);let n=void 0===t?i.len:i.pos+t;const r={allParticipants:!1,trackPermissions:[]};for(;i.pos<n;){const e=i.uint32();switch(e>>>3){case 1:if(8!==e)break;r.allParticipants=i.bool();continue;case 2:if(18!==e)break;r.trackPermissions.push(Fn.decode(i,i.uint32()));continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return r},fromJSON:e=>({allParticipants:!!Xn(e.allParticipants)&&Boolean(e.allParticipants),trackPermissions:Array.isArray(null==e?void 0:e.trackPermissions)?e.trackPermissions.map((e=>Fn.fromJSON(e))):[]}),toJSON(e){const t={};return void 0!==e.allParticipants&&(t.allParticipants=e.allParticipants),e.trackPermissions?t.trackPermissions=e.trackPermissions.map((e=>e?Fn.toJSON(e):void 0)):t.trackPermissions=[],t},create:e=>$n.fromPartial(null!=e?e:{}),fromPartial(e){var t,i;const n={allParticipants:!1,trackPermissions:[]};return n.allParticipants=null!==(t=e.allParticipants)&&void 0!==t&&t,n.trackPermissions=(null===(i=e.trackPermissions)||void 0===i?void 0:i.map((e=>Fn.fromPartial(e))))||[],n}};const Vn={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:st.Writer.create();return""!==e.participantSid&&t.uint32(10).string(e.participantSid),""!==e.trackSid&&t.uint32(18).string(e.trackSid),!0===e.allowed&&t.uint32(24).bool(e.allowed),t},decode(e,t){const i=e instanceof st.Reader?e:st.Reader.create(e);let n=void 0===t?i.len:i.pos+t;const r={participantSid:"",trackSid:"",allowed:!1};for(;i.pos<n;){const e=i.uint32();switch(e>>>3){case 1:if(10!==e)break;r.participantSid=i.string();continue;case 2:if(18!==e)break;r.trackSid=i.string();continue;case 3:if(24!==e)break;r.allowed=i.bool();continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return r},fromJSON:e=>({participantSid:Xn(e.participantSid)?String(e.participantSid):"",trackSid:Xn(e.trackSid)?String(e.trackSid):"",allowed:!!Xn(e.allowed)&&Boolean(e.allowed)}),toJSON(e){const t={};return void 0!==e.participantSid&&(t.participantSid=e.participantSid),void 0!==e.trackSid&&(t.trackSid=e.trackSid),void 0!==e.allowed&&(t.allowed=e.allowed),t},create:e=>Vn.fromPartial(null!=e?e:{}),fromPartial(e){var t,i,n;const r={participantSid:"",trackSid:"",allowed:!1};return r.participantSid=null!==(t=e.participantSid)&&void 0!==t?t:"",r.trackSid=null!==(i=e.trackSid)&&void 0!==i?i:"",r.allowed=null!==(n=e.allowed)&&void 0!==n&&n,r}};const jn={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:st.Writer.create();void 0!==e.answer&&En.encode(e.answer,t.uint32(10).fork()).ldelim(),void 0!==e.subscription&&Pn.encode(e.subscription,t.uint32(18).fork()).ldelim();for(const i of e.publishTracks)Sn.encode(i,t.uint32(26).fork()).ldelim();for(const i of e.dataChannels)qn.encode(i,t.uint32(34).fork()).ldelim();return void 0!==e.offer&&En.encode(e.offer,t.uint32(42).fork()).ldelim(),t},decode(e,t){const i=e instanceof st.Reader?e:st.Reader.create(e);let n=void 0===t?i.len:i.pos+t;const r={answer:void 0,subscription:void 0,publishTracks:[],dataChannels:[],offer:void 0};for(;i.pos<n;){const e=i.uint32();switch(e>>>3){case 1:if(10!==e)break;r.answer=En.decode(i,i.uint32());continue;case 2:if(18!==e)break;r.subscription=Pn.decode(i,i.uint32());continue;case 3:if(26!==e)break;r.publishTracks.push(Sn.decode(i,i.uint32()));continue;case 4:if(34!==e)break;r.dataChannels.push(qn.decode(i,i.uint32()));continue;case 5:if(42!==e)break;r.offer=En.decode(i,i.uint32());continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return r},fromJSON:e=>({answer:Xn(e.answer)?En.fromJSON(e.answer):void 0,subscription:Xn(e.subscription)?Pn.fromJSON(e.subscription):void 0,publishTracks:Array.isArray(null==e?void 0:e.publishTracks)?e.publishTracks.map((e=>Sn.fromJSON(e))):[],dataChannels:Array.isArray(null==e?void 0:e.dataChannels)?e.dataChannels.map((e=>qn.fromJSON(e))):[],offer:Xn(e.offer)?En.fromJSON(e.offer):void 0}),toJSON(e){const t={};return void 0!==e.answer&&(t.answer=e.answer?En.toJSON(e.answer):void 0),void 0!==e.subscription&&(t.subscription=e.subscription?Pn.toJSON(e.subscription):void 0),e.publishTracks?t.publishTracks=e.publishTracks.map((e=>e?Sn.toJSON(e):void 0)):t.publishTracks=[],e.dataChannels?t.dataChannels=e.dataChannels.map((e=>e?qn.toJSON(e):void 0)):t.dataChannels=[],void 0!==e.offer&&(t.offer=e.offer?En.toJSON(e.offer):void 0),t},create:e=>jn.fromPartial(null!=e?e:{}),fromPartial(e){var t,i;const n={answer:void 0,subscription:void 0,publishTracks:[],dataChannels:[],offer:void 0};return n.answer=void 0!==e.answer&&null!==e.answer?En.fromPartial(e.answer):void 0,n.subscription=void 0!==e.subscription&&null!==e.subscription?Pn.fromPartial(e.subscription):void 0,n.publishTracks=(null===(t=e.publishTracks)||void 0===t?void 0:t.map((e=>Sn.fromPartial(e))))||[],n.dataChannels=(null===(i=e.dataChannels)||void 0===i?void 0:i.map((e=>qn.fromPartial(e))))||[],n.offer=void 0!==e.offer&&null!==e.offer?En.fromPartial(e.offer):void 0,n}};const qn={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:st.Writer.create();return""!==e.label&&t.uint32(10).string(e.label),0!==e.id&&t.uint32(16).uint32(e.id),0!==e.target&&t.uint32(24).int32(e.target),t},decode(e,t){const i=e instanceof st.Reader?e:st.Reader.create(e);let n=void 0===t?i.len:i.pos+t;const r={label:"",id:0,target:0};for(;i.pos<n;){const e=i.uint32();switch(e>>>3){case 1:if(10!==e)break;r.label=i.string();continue;case 2:if(16!==e)break;r.id=i.uint32();continue;case 3:if(24!==e)break;r.target=i.int32();continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return r},fromJSON:e=>({label:Xn(e.label)?String(e.label):"",id:Xn(e.id)?Number(e.id):0,target:Xn(e.target)?cn(e.target):0}),toJSON(e){const t={};return void 0!==e.label&&(t.label=e.label),void 0!==e.id&&(t.id=Math.round(e.id)),void 0!==e.target&&(t.target=dn(e.target)),t},create:e=>qn.fromPartial(null!=e?e:{}),fromPartial(e){var t,i,n;const r={label:"",id:0,target:0};return r.label=null!==(t=e.label)&&void 0!==t?t:"",r.id=null!==(i=e.id)&&void 0!==i?i:0,r.target=null!==(n=e.target)&&void 0!==n?n:0,r}};const Wn={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:st.Writer.create();var i;switch(null===(i=e.scenario)||void 0===i?void 0:i.$case){case"speakerUpdate":t.uint32(8).int32(e.scenario.speakerUpdate);break;case"nodeFailure":t.uint32(16).bool(e.scenario.nodeFailure);break;case"migration":t.uint32(24).bool(e.scenario.migration);break;case"serverLeave":t.uint32(32).bool(e.scenario.serverLeave);break;case"switchCandidateProtocol":t.uint32(40).int32(e.scenario.switchCandidateProtocol);break;case"subscriberBandwidth":t.uint32(48).int64(e.scenario.subscriberBandwidth)}return t},decode(e,t){const i=e instanceof st.Reader?e:st.Reader.create(e);let n=void 0===t?i.len:i.pos+t;const r={scenario:void 0};for(;i.pos<n;){const e=i.uint32();switch(e>>>3){case 1:if(8!==e)break;r.scenario={$case:"speakerUpdate",speakerUpdate:i.int32()};continue;case 2:if(16!==e)break;r.scenario={$case:"nodeFailure",nodeFailure:i.bool()};continue;case 3:if(24!==e)break;r.scenario={$case:"migration",migration:i.bool()};continue;case 4:if(32!==e)break;r.scenario={$case:"serverLeave",serverLeave:i.bool()};continue;case 5:if(40!==e)break;r.scenario={$case:"switchCandidateProtocol",switchCandidateProtocol:i.int32()};continue;case 6:if(48!==e)break;r.scenario={$case:"subscriberBandwidth",subscriberBandwidth:Yn(i.int64())};continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return r},fromJSON:e=>({scenario:Xn(e.speakerUpdate)?{$case:"speakerUpdate",speakerUpdate:Number(e.speakerUpdate)}:Xn(e.nodeFailure)?{$case:"nodeFailure",nodeFailure:Boolean(e.nodeFailure)}:Xn(e.migration)?{$case:"migration",migration:Boolean(e.migration)}:Xn(e.serverLeave)?{$case:"serverLeave",serverLeave:Boolean(e.serverLeave)}:Xn(e.switchCandidateProtocol)?{$case:"switchCandidateProtocol",switchCandidateProtocol:ln(e.switchCandidateProtocol)}:Xn(e.subscriberBandwidth)?{$case:"subscriberBandwidth",subscriberBandwidth:Number(e.subscriberBandwidth)}:void 0}),toJSON(e){var t,i,n,r,s,o,a,c,d,u,l,h,p;const m={};return"speakerUpdate"===(null===(t=e.scenario)||void 0===t?void 0:t.$case)&&(m.speakerUpdate=Math.round(null===(i=e.scenario)||void 0===i?void 0:i.speakerUpdate)),"nodeFailure"===(null===(n=e.scenario)||void 0===n?void 0:n.$case)&&(m.nodeFailure=null===(r=e.scenario)||void 0===r?void 0:r.nodeFailure),"migration"===(null===(s=e.scenario)||void 0===s?void 0:s.$case)&&(m.migration=null===(o=e.scenario)||void 0===o?void 0:o.migration),"serverLeave"===(null===(a=e.scenario)||void 0===a?void 0:a.$case)&&(m.serverLeave=null===(c=e.scenario)||void 0===c?void 0:c.serverLeave),"switchCandidateProtocol"===(null===(d=e.scenario)||void 0===d?void 0:d.$case)&&(m.switchCandidateProtocol=void 0!==(null===(u=e.scenario)||void 0===u?void 0:u.switchCandidateProtocol)?function(e){switch(e){case on.UDP:return"UDP";case on.TCP:return"TCP";case on.TLS:return"TLS";case on.UNRECOGNIZED:default:return"UNRECOGNIZED"}}(null===(l=e.scenario)||void 0===l?void 0:l.switchCandidateProtocol):void 0),"subscriberBandwidth"===(null===(h=e.scenario)||void 0===h?void 0:h.$case)&&(m.subscriberBandwidth=Math.round(null===(p=e.scenario)||void 0===p?void 0:p.subscriberBandwidth)),m},create:e=>Wn.fromPartial(null!=e?e:{}),fromPartial(e){var t,i,n,r,s,o,a,c,d,u,l,h,p,m,f,v,g,b;const k={scenario:void 0};return"speakerUpdate"===(null===(t=e.scenario)||void 0===t?void 0:t.$case)&&void 0!==(null===(i=e.scenario)||void 0===i?void 0:i.speakerUpdate)&&null!==(null===(n=e.scenario)||void 0===n?void 0:n.speakerUpdate)&&(k.scenario={$case:"speakerUpdate",speakerUpdate:e.scenario.speakerUpdate}),"nodeFailure"===(null===(r=e.scenario)||void 0===r?void 0:r.$case)&&void 0!==(null===(s=e.scenario)||void 0===s?void 0:s.nodeFailure)&&null!==(null===(o=e.scenario)||void 0===o?void 0:o.nodeFailure)&&(k.scenario={$case:"nodeFailure",nodeFailure:e.scenario.nodeFailure}),"migration"===(null===(a=e.scenario)||void 0===a?void 0:a.$case)&&void 0!==(null===(c=e.scenario)||void 0===c?void 0:c.migration)&&null!==(null===(d=e.scenario)||void 0===d?void 0:d.migration)&&(k.scenario={$case:"migration",migration:e.scenario.migration}),"serverLeave"===(null===(u=e.scenario)||void 0===u?void 0:u.$case)&&void 0!==(null===(l=e.scenario)||void 0===l?void 0:l.serverLeave)&&null!==(null===(h=e.scenario)||void 0===h?void 0:h.serverLeave)&&(k.scenario={$case:"serverLeave",serverLeave:e.scenario.serverLeave}),"switchCandidateProtocol"===(null===(p=e.scenario)||void 0===p?void 0:p.$case)&&void 0!==(null===(m=e.scenario)||void 0===m?void 0:m.switchCandidateProtocol)&&null!==(null===(f=e.scenario)||void 0===f?void 0:f.switchCandidateProtocol)&&(k.scenario={$case:"switchCandidateProtocol",switchCandidateProtocol:e.scenario.switchCandidateProtocol}),"subscriberBandwidth"===(null===(v=e.scenario)||void 0===v?void 0:v.$case)&&void 0!==(null===(g=e.scenario)||void 0===g?void 0:g.subscriberBandwidth)&&null!==(null===(b=e.scenario)||void 0===b?void 0:b.subscriberBandwidth)&&(k.scenario={$case:"subscriberBandwidth",subscriberBandwidth:e.scenario.subscriberBandwidth}),k}};const Gn={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:st.Writer.create();return 0!==e.timestamp&&t.uint32(8).int64(e.timestamp),0!==e.rtt&&t.uint32(16).int64(e.rtt),t},decode(e,t){const i=e instanceof st.Reader?e:st.Reader.create(e);let n=void 0===t?i.len:i.pos+t;const r={timestamp:0,rtt:0};for(;i.pos<n;){const e=i.uint32();switch(e>>>3){case 1:if(8!==e)break;r.timestamp=Yn(i.int64());continue;case 2:if(16!==e)break;r.rtt=Yn(i.int64());continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return r},fromJSON:e=>({timestamp:Xn(e.timestamp)?Number(e.timestamp):0,rtt:Xn(e.rtt)?Number(e.rtt):0}),toJSON(e){const t={};return void 0!==e.timestamp&&(t.timestamp=Math.round(e.timestamp)),void 0!==e.rtt&&(t.rtt=Math.round(e.rtt)),t},create:e=>Gn.fromPartial(null!=e?e:{}),fromPartial(e){var t,i;const n={timestamp:0,rtt:0};return n.timestamp=null!==(t=e.timestamp)&&void 0!==t?t:0,n.rtt=null!==(i=e.rtt)&&void 0!==i?i:0,n}};const Kn={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:st.Writer.create();return 0!==e.lastPingTimestamp&&t.uint32(8).int64(e.lastPingTimestamp),0!==e.timestamp&&t.uint32(16).int64(e.timestamp),t},decode(e,t){const i=e instanceof st.Reader?e:st.Reader.create(e);let n=void 0===t?i.len:i.pos+t;const r={lastPingTimestamp:0,timestamp:0};for(;i.pos<n;){const e=i.uint32();switch(e>>>3){case 1:if(8!==e)break;r.lastPingTimestamp=Yn(i.int64());continue;case 2:if(16!==e)break;r.timestamp=Yn(i.int64());continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return r},fromJSON:e=>({lastPingTimestamp:Xn(e.lastPingTimestamp)?Number(e.lastPingTimestamp):0,timestamp:Xn(e.timestamp)?Number(e.timestamp):0}),toJSON(e){const t={};return void 0!==e.lastPingTimestamp&&(t.lastPingTimestamp=Math.round(e.lastPingTimestamp)),void 0!==e.timestamp&&(t.timestamp=Math.round(e.timestamp)),t},create:e=>Kn.fromPartial(null!=e?e:{}),fromPartial(e){var t,i;const n={lastPingTimestamp:0,timestamp:0};return n.lastPingTimestamp=null!==(t=e.lastPingTimestamp)&&void 0!==t?t:0,n.timestamp=null!==(i=e.timestamp)&&void 0!==i?i:0,n}};const Qn={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:st.Writer.create();return""!==e.trackSid&&t.uint32(10).string(e.trackSid),0!==e.err&&t.uint32(16).int32(e.err),t},decode(e,t){const i=e instanceof st.Reader?e:st.Reader.create(e);let n=void 0===t?i.len:i.pos+t;const r={trackSid:"",err:0};for(;i.pos<n;){const e=i.uint32();switch(e>>>3){case 1:if(10!==e)break;r.trackSid=i.string();continue;case 2:if(16!==e)break;r.err=i.int32();continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return r},fromJSON:e=>({trackSid:Xn(e.trackSid)?String(e.trackSid):"",err:Xn(e.err)?vt(e.err):0}),toJSON(e){const t={};return void 0!==e.trackSid&&(t.trackSid=e.trackSid),void 0!==e.err&&(t.err=function(e){switch(e){case Xe.SE_UNKNOWN:return"SE_UNKNOWN";case Xe.SE_CODEC_UNSUPPORTED:return"SE_CODEC_UNSUPPORTED";case Xe.SE_TRACK_NOTFOUND:return"SE_TRACK_NOTFOUND";case Xe.UNRECOGNIZED:default:return"UNRECOGNIZED"}}(e.err)),t},create:e=>Qn.fromPartial(null!=e?e:{}),fromPartial(e){var t,i;const n={trackSid:"",err:0};return n.trackSid=null!==(t=e.trackSid)&&void 0!==t?t:"",n.err=null!==(i=e.err)&&void 0!==i?i:0,n}};var Hn,Zn=(()=>{if("undefined"!=typeof globalThis)return globalThis;if("undefined"!=typeof self)return self;if("undefined"!=typeof window)return window;if("undefined"!=typeof global)return global;throw"Unable to locate global object"})();function zn(e){if(Zn.Buffer)return Uint8Array.from(Zn.Buffer.from(e,"base64"));{const t=Zn.atob(e),i=new Uint8Array(t.length);for(let e=0;e<t.length;++e)i[e]=t.charCodeAt(e);return i}}function Yn(e){if(e.gt(Number.MAX_SAFE_INTEGER))throw new Zn.Error("Value is larger than Number.MAX_SAFE_INTEGER");return e.toNumber()}function Xn(e){return null!=e}st.util.Long!==_&&(st.util.Long=_,st.configure());class er extends Error{constructor(e,t){super(t||"an error has occured"),this.code=e}}class tr extends er{constructor(e,t,i){super(1,e),this.status=i,this.reason=t}}class ir extends er{constructor(e){super(21,null!=e?e:"device is unsupported")}}class nr extends er{constructor(e){super(20,null!=e?e:"track is invalid")}}class rr extends er{constructor(e){super(10,null!=e?e:"unsupported server")}}class sr extends er{constructor(e){super(12,null!=e?e:"unexpected connection state")}}class or extends er{constructor(e){super(13,null!=e?e:"unable to negotiate")}}e.MediaDeviceFailure=void 0,(Hn=e.MediaDeviceFailure||(e.MediaDeviceFailure={})).PermissionDenied="PermissionDenied",Hn.NotFound="NotFound",Hn.DeviceInUse="DeviceInUse",Hn.Other="Other",function(e){e.getFailure=function(t){if(t&&"name"in t)return"NotFoundError"===t.name||"DevicesNotFoundError"===t.name?e.NotFound:"NotAllowedError"===t.name||"PermissionDeniedError"===t.name?e.PermissionDenied:"NotReadableError"===t.name||"TrackStartError"===t.name?e.DeviceInUse:e.Other}}(e.MediaDeviceFailure||(e.MediaDeviceFailure={}));class ar{}ar.setTimeout=function(){return setTimeout(...arguments)},ar.setInterval=function(){return setInterval(...arguments)},ar.clearTimeout=function(){return clearTimeout(...arguments)},ar.clearInterval=function(){return clearInterval(...arguments)};const cr=/version\/(\d+(\.?_?\d+)+)/i;let dr;function ur(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(void 0===e&&"undefined"==typeof navigator)return;const i=(null!=e?e:navigator.userAgent).toLowerCase();if(void 0===dr||t){const e=lr.find((e=>{let{test:t}=e;return t.test(i)}));dr=null==e?void 0:e.describe(i)}return dr}const lr=[{test:/firefox|iceweasel|fxios/i,describe:e=>({name:"Firefox",version:hr(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,e)})},{test:/chrom|crios|crmo/i,describe:e=>({name:"Chrome",version:hr(/(?:chrome|chromium|crios|crmo)\/(\d+(\.?_?\d+)+)/i,e)})},{test:/safari|applewebkit/i,describe:e=>({name:"Safari",version:hr(cr,e)})}];function hr(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1;const n=t.match(e);return n&&n.length>=i&&n[i]||""}const pr="1.12.0";class mr{constructor(e,t,i,n,r){this.width=e,this.height=t,this.encoding={maxBitrate:i,maxFramerate:n,priority:r}}get resolution(){return{width:this.width,height:this.height,frameRate:this.encoding.maxFramerate,aspectRatio:this.width/this.height}}}const fr=["vp8","h264"],vr=["vp8","h264","vp9","av1"];function gr(e){return!!fr.find((t=>t===e))}function br(e,t){return(null==e?void 0:e.toLowerCase().replace(/audio\/|video\//y,""))===(null==t?void 0:t.toLowerCase().replace(/audio\/|video\//y,""))}var kr;e.AudioPresets=void 0,(kr=e.AudioPresets||(e.AudioPresets={})).telephone={maxBitrate:12e3},kr.speech={maxBitrate:2e4},kr.music={maxBitrate:32e3},kr.musicStereo={maxBitrate:48e3},kr.musicHighQuality={maxBitrate:64e3},kr.musicHighQualityStereo={maxBitrate:96e3};const yr={h90:new mr(160,90,6e4,15),h180:new mr(320,180,12e4,15),h216:new mr(384,216,18e4,15),h360:new mr(640,360,3e5,20),h540:new mr(960,540,6e5,25),h720:new mr(1280,720,17e5,30),h1080:new mr(1920,1080,3e6,30),h1440:new mr(2560,1440,5e6,30),h2160:new mr(3840,2160,8e6,30)},Sr={h120:new mr(160,120,8e4,15),h180:new mr(240,180,1e5,15),h240:new mr(320,240,15e4,15),h360:new mr(480,360,225e3,20),h480:new mr(640,480,3e5,20),h540:new mr(720,540,45e4,25),h720:new mr(960,720,15e5,30),h1080:new mr(1440,1080,25e5,30),h1440:new mr(1920,1440,35e5,30)},Cr={h360fps3:new mr(640,360,2e5,3,"medium"),h720fps5:new mr(1280,720,4e5,5,"medium"),h720fps15:new mr(1280,720,1e6,15,"medium"),h1080fps15:new mr(1920,1080,15e5,15,"medium"),h1080fps30:new mr(1920,1080,3e6,30,"medium")};var Er,Tr,Pr,wr;e.RoomEvent=void 0,(Er=e.RoomEvent||(e.RoomEvent={})).Connected="connected",Er.Reconnecting="reconnecting",Er.Reconnected="reconnected",Er.Disconnected="disconnected",Er.ConnectionStateChanged="connectionStateChanged",Er.StateChanged="connectionStateChanged",Er.MediaDevicesChanged="mediaDevicesChanged",Er.ParticipantConnected="participantConnected",Er.ParticipantDisconnected="participantDisconnected",Er.TrackPublished="trackPublished",Er.TrackSubscribed="trackSubscribed",Er.TrackSubscriptionFailed="trackSubscriptionFailed",Er.TrackUnpublished="trackUnpublished",Er.TrackUnsubscribed="trackUnsubscribed",Er.TrackMuted="trackMuted",Er.TrackUnmuted="trackUnmuted",Er.LocalTrackPublished="localTrackPublished",Er.LocalTrackUnpublished="localTrackUnpublished",Er.LocalAudioSilenceDetected="localAudioSilenceDetected",Er.ActiveSpeakersChanged="activeSpeakersChanged",Er.ParticipantMetadataChanged="participantMetadataChanged",Er.ParticipantNameChanged="participantNameChanged",Er.RoomMetadataChanged="roomMetadataChanged",Er.DataReceived="dataReceived",Er.ConnectionQualityChanged="connectionQualityChanged",Er.TrackStreamStateChanged="trackStreamStateChanged",Er.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",Er.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",Er.AudioPlaybackStatusChanged="audioPlaybackChanged",Er.MediaDevicesError="mediaDevicesError",Er.ParticipantPermissionsChanged="participantPermissionsChanged",Er.SignalConnected="signalConnected",Er.RecordingStatusChanged="recordingStatusChanged",Er.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",Er.EncryptionError="encryptionError",Er.DCBufferStatusChanged="dcBufferStatusChanged",Er.ActiveDeviceChanged="activeDeviceChanged",e.ParticipantEvent=void 0,(Tr=e.ParticipantEvent||(e.ParticipantEvent={})).TrackPublished="trackPublished",Tr.TrackSubscribed="trackSubscribed",Tr.TrackSubscriptionFailed="trackSubscriptionFailed",Tr.TrackUnpublished="trackUnpublished",Tr.TrackUnsubscribed="trackUnsubscribed",Tr.TrackMuted="trackMuted",Tr.TrackUnmuted="trackUnmuted",Tr.LocalTrackPublished="localTrackPublished",Tr.LocalTrackUnpublished="localTrackUnpublished",Tr.ParticipantMetadataChanged="participantMetadataChanged",Tr.ParticipantNameChanged="participantNameChanged",Tr.DataReceived="dataReceived",Tr.IsSpeakingChanged="isSpeakingChanged",Tr.ConnectionQualityChanged="connectionQualityChanged",Tr.TrackStreamStateChanged="trackStreamStateChanged",Tr.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",Tr.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",Tr.MediaDevicesError="mediaDevicesError",Tr.ParticipantPermissionsChanged="participantPermissionsChanged",Tr.PCTrackAdded="pcTrackAdded",e.EngineEvent=void 0,(Pr=e.EngineEvent||(e.EngineEvent={})).TransportsCreated="transportsCreated",Pr.Connected="connected",Pr.Disconnected="disconnected",Pr.Resuming="resuming",Pr.Resumed="resumed",Pr.Restarting="restarting",Pr.Restarted="restarted",Pr.SignalResumed="signalResumed",Pr.SignalRestarted="signalRestarted",Pr.Closing="closing",Pr.MediaTrackAdded="mediaTrackAdded",Pr.ActiveSpeakersUpdate="activeSpeakersUpdate",Pr.DataPacketReceived="dataPacketReceived",Pr.RTPVideoMapUpdate="rtpVideoMapUpdate",Pr.DCBufferStatusChanged="dcBufferStatusChanged",Pr.ParticipantUpdate="participantUpdate",Pr.RoomUpdate="roomUpdate",Pr.SpeakersChanged="speakersChanged",Pr.StreamStateChanged="streamStateChanged",Pr.ConnectionQualityUpdate="connectionQualityUpdate",Pr.SubscriptionError="subscriptionError",Pr.SubscriptionPermissionUpdate="subscriptionPermissionUpdate",e.TrackEvent=void 0,(wr=e.TrackEvent||(e.TrackEvent={})).Message="message",wr.Muted="muted",wr.Unmuted="unmuted",wr.Restarted="restarted",wr.Ended="ended",wr.Subscribed="subscribed",wr.Unsubscribed="unsubscribed",wr.UpdateSettings="updateSettings",wr.UpdateSubscription="updateSubscription",wr.AudioPlaybackStarted="audioPlaybackStarted",wr.AudioPlaybackFailed="audioPlaybackFailed",wr.AudioSilenceDetected="audioSilenceDetected",wr.VisibilityChanged="visibilityChanged",wr.VideoDimensionsChanged="videoDimensionsChanged",wr.ElementAttached="elementAttached",wr.ElementDetached="elementDetached",wr.UpstreamPaused="upstreamPaused",wr.UpstreamResumed="upstreamResumed",wr.SubscriptionPermissionChanged="subscriptionPermissionChanged",wr.SubscriptionStatusChanged="subscriptionStatusChanged",wr.SubscriptionFailed="subscriptionFailed";const Rr=[];class Nr extends Yt{constructor(e,t){super(),this.attachedElements=[],this.isMuted=!1,this.streamState=Nr.StreamState.Active,this.isInBackground=!1,this._currentBitrate=0,this.appVisibilityChangedListener=()=>{this.backgroundTimeout&&clearTimeout(this.backgroundTimeout),"hidden"===document.visibilityState?this.backgroundTimeout=setTimeout((()=>this.handleAppVisibilityChanged()),5e3):this.handleAppVisibilityChanged()},this.kind=t,this._mediaStreamTrack=e,this._mediaStreamID=e.id,this.source=Nr.Source.Unknown}get currentBitrate(){return this._currentBitrate}get mediaStreamTrack(){return this._mediaStreamTrack}get mediaStreamID(){return this._mediaStreamID}attach(t){let i="audio";this.kind===Nr.Kind.Video&&(i="video"),0===this.attachedElements.length&&Nr.Kind.Video&&this.addAppVisibilityListener(),t||("audio"===i&&(Rr.forEach((e=>{null!==e.parentElement||t||(t=e)})),t&&Rr.splice(Rr.indexOf(t),1)),t||(t=document.createElement(i))),this.attachedElements.includes(t)||this.attachedElements.push(t),Or(this.mediaStreamTrack,t);const n=t.srcObject.getTracks();return n.some((e=>"audio"===e.kind))&&t.play().then((()=>{this.emit(e.TrackEvent.AudioPlaybackStarted)})).catch((i=>{"NotAllowedError"===i.name?this.emit(e.TrackEvent.AudioPlaybackFailed,i):c.warn("could not playback audio",i),t&&n.some((e=>"video"===e.kind))&&"NotAllowedError"===i.name&&(t.muted=!0,t.play().catch((()=>{})))})),this.emit(e.TrackEvent.ElementAttached,t),t}detach(t){try{if(t){Ir(this.mediaStreamTrack,t);const i=this.attachedElements.indexOf(t);return i>=0&&(this.attachedElements.splice(i,1),this.recycleElement(t),this.emit(e.TrackEvent.ElementDetached,t)),t}const i=[];return this.attachedElements.forEach((t=>{Ir(this.mediaStreamTrack,t),i.push(t),this.recycleElement(t),this.emit(e.TrackEvent.ElementDetached,t)})),this.attachedElements=[],i}finally{0===this.attachedElements.length&&this.removeAppVisibilityListener()}}stop(){this.stopMonitor(),this._mediaStreamTrack.stop()}enable(){this._mediaStreamTrack.enabled=!0}disable(){this._mediaStreamTrack.enabled=!1}stopMonitor(){this.monitorInterval&&clearInterval(this.monitorInterval)}recycleElement(e){if(e instanceof HTMLAudioElement){let t=!0;e.pause(),Rr.forEach((e=>{e.parentElement||(t=!1)})),t&&Rr.push(e)}}handleAppVisibilityChanged(){return Qt(this,void 0,void 0,(function*(){this.isInBackground="hidden"===document.visibilityState}))}addAppVisibilityListener(){Kr()?(this.isInBackground="hidden"===document.visibilityState,document.addEventListener("visibilitychange",this.appVisibilityChangedListener)):this.isInBackground=!1}removeAppVisibilityListener(){Kr()&&document.removeEventListener("visibilitychange",this.appVisibilityChangedListener)}}function Or(e,t){let i,n;i=t.srcObject instanceof MediaStream?t.srcObject:new MediaStream,n="audio"===e.kind?i.getAudioTracks():i.getVideoTracks(),n.includes(e)||(n.forEach((e=>{i.removeTrack(e)})),i.addTrack(e)),t.autoplay=!0,t.muted=0===i.getAudioTracks().length,t instanceof HTMLVideoElement&&(t.playsInline=!0),t.srcObject!==i&&(t.srcObject=i,(Wr()||qr())&&t instanceof HTMLVideoElement&&setTimeout((()=>{t.srcObject=i,t.play().catch((()=>{}))}),0))}function Ir(e,t){if(t.srcObject instanceof MediaStream){const i=t.srcObject;i.removeTrack(e),i.getTracks().length>0?t.srcObject=i:t.srcObject=null}}function Dr(e,t,i){const n=Object.assign({},e);return!0===n.audio&&(n.audio={}),!0===n.video&&(n.video={}),n.audio&&Ar(n.audio,t),n.video&&Ar(n.video,i),n}function Ar(e,t){return Object.keys(t).forEach((i=>{void 0===e[i]&&(e[i]=t[i])})),e}function Ur(e){const t={};if(e.video)if("object"==typeof e.video){const i={},n=i,r=e.video;Object.keys(r).forEach((e=>{if("resolution"===e)Ar(n,r.resolution);else n[e]=r[e]})),t.video=i}else t.video=e.video;else t.video=!1;return e.audio?"object"==typeof e.audio?t.audio=e.audio:t.audio=!0:t.audio=!1,t}function Mr(){const e="undefined"!=typeof window&&(window.AudioContext||window.webkitAudioContext);if(e)return new e({latencyHint:"interactive"})}!function(e){let t,i,n;!function(e){e.Audio="audio",e.Video="video",e.Unknown="unknown"}(t=e.Kind||(e.Kind={})),function(e){e.Camera="camera",e.Microphone="microphone",e.ScreenShare="screen_share",e.ScreenShareAudio="screen_share_audio",e.Unknown="unknown"}(i=e.Source||(e.Source={})),function(e){e.Active="active",e.Paused="paused",e.Unknown="unknown"}(n=e.StreamState||(e.StreamState={})),e.kindToProto=function(e){switch(e){case t.Audio:return Ge.AUDIO;case t.Video:return Ge.VIDEO;default:return Ge.UNRECOGNIZED}},e.kindFromProto=function(e){switch(e){case Ge.AUDIO:return t.Audio;case Ge.VIDEO:return t.Video;default:return t.Unknown}},e.sourceToProto=function(e){switch(e){case i.Camera:return Ke.CAMERA;case i.Microphone:return Ke.MICROPHONE;case i.ScreenShare:return Ke.SCREEN_SHARE;case i.ScreenShareAudio:return Ke.SCREEN_SHARE_AUDIO;default:return Ke.UNRECOGNIZED}},e.sourceFromProto=function(e){switch(e){case Ke.CAMERA:return i.Camera;case Ke.MICROPHONE:return i.Microphone;case Ke.SCREEN_SHARE:return i.ScreenShare;case Ke.SCREEN_SHARE_AUDIO:return i.ScreenShareAudio;default:return i.Unknown}},e.streamStateFromProto=function(e){switch(e){case sn.ACTIVE:return n.Active;case sn.PAUSED:return n.Paused;default:return n.Unknown}}}(Nr||(Nr={}));const Lr="https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension";function _r(e){return Qt(this,void 0,void 0,(function*(){return new Promise((t=>setTimeout(t,e)))}))}function xr(){return"addTransceiver"in RTCPeerConnection.prototype}function Br(){return"addTrack"in RTCPeerConnection.prototype}function Jr(){if(!("getCapabilities"in RTCRtpSender))return!1;const e=RTCRtpSender.getCapabilities("video");let t=!1;if(e)for(const i of e.codecs)if("video/AV1"===i.mimeType){t=!0;break}return t}function Fr(){if(!("getCapabilities"in RTCRtpSender))return!1;const e=RTCRtpSender.getCapabilities("video");let t=!1;if(e)for(const i of e.codecs)if("video/VP9"===i.mimeType){t=!0;break}return t}function $r(e){return"av1"===e||"vp9"===e}function Vr(e){return!!document&&(e||(e=document.createElement("audio")),"setSinkId"in e)}const jr={Chrome:"100",Safari:"15",Firefox:"100"};function qr(){var e;return"Firefox"===(null===(e=ur())||void 0===e?void 0:e.name)}function Wr(){var e;return"Safari"===(null===(e=ur())||void 0===e?void 0:e.name)}function Gr(){return!!Kr()&&/Tablet|iPad|Mobile|Android|BlackBerry/.test(navigator.userAgent)}function Kr(){return"undefined"!=typeof document}function Qr(){return"ReactNative"==navigator.product}function Hr(e){return e.hostname.endsWith(".livekit.cloud")}function Zr(){if(global&&global.LiveKitReactNativeGlobal)return global.LiveKitReactNativeGlobal}function zr(){if(!Qr())return;let e=Zr();return e?e.platform:void 0}function Yr(){if(Kr())return window.devicePixelRatio;if(Qr()){let e=Zr();if(e)return e.devicePixelRatio}return 1}function Xr(e,t){const i=e.split("."),n=t.split("."),r=Math.min(i.length,n.length);for(let e=0;e<r;++e){const t=parseInt(i[e],10),s=parseInt(n[e],10);if(t>s)return 1;if(t<s)return-1;if(e===r-1&&t===s)return 0}return""===e&&""!==t?-1:""===t?1:i.length==n.length?0:i.length<n.length?-1:1}function es(e){for(const t of e)t.target.handleResize(t)}function ts(e){for(const t of e)t.target.handleVisibilityChanged(t)}let is=null;const ns=()=>(is||(is=new ResizeObserver(es)),is);let rs=null;const ss=()=>(rs||(rs=new IntersectionObserver(ts,{root:null,rootMargin:"0px"})),rs);let os,as;function cs(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:16,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:16,i=arguments.length>2&&void 0!==arguments[2]&&arguments[2],n=arguments.length>3&&void 0!==arguments[3]&&arguments[3];const r=document.createElement("canvas");r.width=e,r.height=t;const s=r.getContext("2d");null==s||s.fillRect(0,0,r.width,r.height),n&&s&&(s.beginPath(),s.arc(e/2,t/2,50,0,2*Math.PI,!0),s.closePath(),s.fillStyle="grey",s.fill());const o=r.captureStream(),[a]=o.getTracks();if(!a)throw Error("Could not get empty media stream video track");return a.enabled=i,a}function ds(){if(!as){const e=new AudioContext,t=e.createOscillator(),i=e.createGain();i.gain.setValueAtTime(0,0);const n=e.createMediaStreamDestination();if(t.connect(i),i.connect(n),t.start(),[as]=n.stream.getAudioTracks(),!as)throw Error("Could not get empty media stream audio track");as.enabled=!1}return as.clone()}class us{constructor(e,t){this.onFinally=t,this.promise=new Promise(((t,i)=>Qt(this,void 0,void 0,(function*(){this.resolve=t,this.reject=i,e&&(yield e(t,i))})))).finally((()=>{var e;return null===(e=this.onFinally)||void 0===e?void 0:e.call(this)}))}}class ls{constructor(){this._locking=Promise.resolve(),this._locks=0}isLocked(){return this._locks>0}lock(){let e;this._locks+=1;const t=new Promise((t=>e=()=>{this._locks-=1,t()})),i=this._locking.then((()=>e));return this._locking=this._locking.then((()=>t)),i}}function hs(e){if("string"==typeof e)return e;if(Array.isArray(e))return e[0];if(e.exact)return Array.isArray(e.exact)?e.exact[0]:e.exact;if(e.ideal)return Array.isArray(e.ideal)?e.ideal[0]:e.ideal;throw Error("could not unwrap constraint")}var ps;!function(e){e[e.WAITING=0]="WAITING",e[e.RUNNING=1]="RUNNING",e[e.COMPLETED=2]="COMPLETED"}(ps||(ps={}));class ms{constructor(){this.pendingTasks=new Map,this.taskMutex=new ls,this.nextTaskIndex=0}run(e){return Qt(this,void 0,void 0,(function*(){const t={id:this.nextTaskIndex++,enqueuedAt:Date.now(),status:ps.WAITING};this.pendingTasks.set(t.id,t);const i=yield this.taskMutex.lock();try{return t.executedAt=Date.now(),t.status=ps.RUNNING,yield e()}finally{t.status=ps.COMPLETED,this.pendingTasks.delete(t.id),i()}}))}flush(){return Qt(this,void 0,void 0,(function*(){return this.run((()=>Qt(this,void 0,void 0,(function*(){}))))}))}snapshot(){return Array.from(this.pendingTasks.values())}}const fs=["syncState","trickle","offer","answer","simulate","leave"];class vs{constructor(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];this.rtt=0,this.resetCallbacks=()=>{this.onAnswer=void 0,this.onLeave=void 0,this.onLocalTrackPublished=void 0,this.onLocalTrackUnpublished=void 0,this.onNegotiateRequested=void 0,this.onOffer=void 0,this.onRemoteMuteChanged=void 0,this.onSubscribedQualityUpdate=void 0,this.onTokenRefresh=void 0,this.onTrickle=void 0,this.onClose=void 0},this.isConnected=!1,this.isReconnecting=!1,this.useJSON=e,this.requestQueue=new ms,this.queuedRequests=[],this.closingLock=new ls}join(e,t,i,n){return Qt(this,void 0,void 0,(function*(){this.isConnected=!1,this.options=i;return yield this.connect(e,t,i,n)}))}reconnect(e,t,i,n){return Qt(this,void 0,void 0,(function*(){if(!this.options)return void c.warn("attempted to reconnect without signal options being set, ignoring");this.isReconnecting=!0,this.clearPingInterval();return yield this.connect(e,t,Object.assign(Object.assign({},this.options),{reconnect:!0,sid:i,reconnectReason:n}))}))}connect(e,t,i,n){this.connectOptions=i,e.startsWith("http")&&(e=e.replace("http","ws")),e=e.replace(/\/$/,""),e+="/rtc";const r=function(e,t,i){var n;const r=new URLSearchParams;r.set("access_token",e),i.reconnect&&(r.set("reconnect","1"),i.sid&&r.set("sid",i.sid));r.set("auto_subscribe",i.autoSubscribe?"1":"0"),r.set("sdk",Qr()?"reactnative":"js"),r.set("version",t.version),r.set("protocol",t.protocol.toString()),t.deviceModel&&r.set("device_model",t.deviceModel);t.os&&r.set("os",t.os);t.osVersion&&r.set("os_version",t.osVersion);t.browser&&r.set("browser",t.browser);t.browserVersion&&r.set("browser_version",t.browserVersion);void 0!==i.publishOnly&&r.set("publish",i.publishOnly);i.adaptiveStream&&r.set("adaptive_stream","1");i.reconnectReason&&r.set("reconnect_reason",i.reconnectReason.toString());(null===(n=navigator.connection)||void 0===n?void 0:n.type)&&r.set("network",navigator.connection.type);return"?".concat(r.toString())}(t,function(){var e;const t=xt.fromPartial({sdk:rt.JS,protocol:9,version:pr});return Qr()&&(t.os=null!==(e=zr())&&void 0!==e?e:""),t}(),i);return new Promise(((t,s)=>Qt(this,void 0,void 0,(function*(){const o=()=>Qt(this,void 0,void 0,(function*(){this.close(),s(new tr("room connection has been cancelled (signal)"))}));(null==n?void 0:n.aborted)&&o(),null==n||n.addEventListener("abort",o),c.debug("connecting to ".concat(e+r)),this.ws&&(yield this.close()),this.ws=new WebSocket(e+r),this.ws.binaryType="arraybuffer",this.ws.onerror=t=>Qt(this,void 0,void 0,(function*(){if(this.isConnected)this.handleWSError(t);else try{const t=yield fetch("http".concat(e.substring(2),"/validate").concat(r));if(t.status.toFixed(0).startsWith("4")){const e=yield t.text();s(new tr(e,0,t.status))}else s(new tr("Internal error",2,t.status))}catch(e){s(new tr("server was not reachable",1))}})),this.ws.onmessage=e=>Qt(this,void 0,void 0,(function*(){var r,a,d,u;let l;if("string"==typeof e.data){const t=JSON.parse(e.data);l=pn.fromJSON(t)}else{if(!(e.data instanceof ArrayBuffer))return void c.error("could not decode websocket message: ".concat(typeof e.data));l=pn.decode(new Uint8Array(e.data))}if(!this.isConnected){let e=!1;if("join"===(null===(r=l.message)||void 0===r?void 0:r.$case)?(this.isConnected=!0,null==n||n.removeEventListener("abort",o),this.pingTimeoutDuration=l.message.join.pingTimeout,this.pingIntervalDuration=l.message.join.pingInterval,this.pingTimeoutDuration&&this.pingTimeoutDuration>0&&(c.debug("ping config",{timeout:this.pingTimeoutDuration,interval:this.pingIntervalDuration}),this.startPingInterval()),t(l.message.join)):i.reconnect?(this.isConnected=!0,null==n||n.removeEventListener("abort",o),this.startPingInterval(),"reconnect"===(null===(a=l.message)||void 0===a?void 0:a.$case)?t(null===(d=l.message)||void 0===d?void 0:d.reconnect):(t(),e=!0)):i.reconnect||s(new tr("did not receive join response, got ".concat(null===(u=l.message)||void 0===u?void 0:u.$case," instead"))),!e)return}this.signalLatency&&(yield _r(this.signalLatency)),this.handleSignalResponse(l)})),this.ws.onclose=e=>{c.warn("websocket closed",{ev:e}),this.handleOnClose(e.reason)}}))))}close(){return Qt(this,void 0,void 0,(function*(){const e=yield this.closingLock.lock();try{if(this.isConnected=!1,this.ws){this.ws.onmessage=null,this.ws.onopen=null,this.ws.onclose=null;const e=new Promise((e=>{this.ws?this.ws.onclose=()=>{e()}:e()}));this.ws.readyState<this.ws.CLOSING&&(this.ws.close(),yield Promise.race([e,_r(250)])),this.ws=void 0}}finally{this.clearPingInterval(),e()}}))}sendOffer(e){c.debug("sending offer",e),this.sendRequest({$case:"offer",offer:bs(e)})}sendAnswer(e){return c.debug("sending answer"),this.sendRequest({$case:"answer",answer:bs(e)})}sendIceCandidate(e,t){return c.trace("sending ice candidate",e),this.sendRequest({$case:"trickle",trickle:{candidateInit:JSON.stringify(e),target:t}})}sendMuteTrack(e,t){return this.sendRequest({$case:"mute",mute:{sid:e,muted:t}})}sendAddTrack(e){return this.sendRequest({$case:"addTrack",addTrack:e})}sendUpdateLocalMetadata(e,t){return this.sendRequest({$case:"updateMetadata",updateMetadata:{metadata:e,name:t}})}sendUpdateTrackSettings(e){this.sendRequest({$case:"trackSetting",trackSetting:e})}sendUpdateSubscription(e){return this.sendRequest({$case:"subscription",subscription:e})}sendSyncState(e){return this.sendRequest({$case:"syncState",syncState:e})}sendUpdateVideoLayers(e,t){return this.sendRequest({$case:"updateLayers",updateLayers:{trackSid:e,layers:t}})}sendUpdateSubscriptionPermissions(e,t){return this.sendRequest({$case:"subscriptionPermission",subscriptionPermission:{allParticipants:e,trackPermissions:t}})}sendSimulateScenario(e){return this.sendRequest({$case:"simulate",simulate:e})}sendPing(){return Promise.all([this.sendRequest({$case:"ping",ping:Date.now()}),this.sendRequest({$case:"pingReq",pingReq:{timestamp:Date.now(),rtt:this.rtt}})])}sendLeave(){return this.sendRequest({$case:"leave",leave:{canReconnect:!1,reason:e.DisconnectReason.CLIENT_INITIATED}})}sendRequest(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return Qt(this,void 0,void 0,(function*(){const i=!t&&!function(e){const t=fs.indexOf(e.$case)>=0;return c.trace("request allowed to bypass queue:",{canPass:t,req:e}),t}(e);if(i&&this.isReconnecting)return void this.queuedRequests.push((()=>Qt(this,void 0,void 0,(function*(){yield this.sendRequest(e,!0)}))));if(t||(yield this.requestQueue.flush()),this.signalLatency&&(yield _r(this.signalLatency)),!this.ws||this.ws.readyState!==this.ws.OPEN)return void c.error("cannot send signal request before connected, type: ".concat(null==e?void 0:e.$case));const n={message:e};try{this.useJSON?this.ws.send(JSON.stringify(hn.toJSON(n))):this.ws.send(hn.encode(n).finish())}catch(e){c.error("error sending signal message",{error:e})}}))}handleSignalResponse(e){var t,i;const n=e.message;if(null!=n)if("answer"===n.$case){const e=gs(n.answer);this.onAnswer&&this.onAnswer(e)}else if("offer"===n.$case){const e=gs(n.offer);this.onOffer&&this.onOffer(e)}else if("trickle"===n.$case){const e=JSON.parse(n.trickle.candidateInit);this.onTrickle&&this.onTrickle(e,n.trickle.target)}else"update"===n.$case?this.onParticipantUpdate&&this.onParticipantUpdate(null!==(t=n.update.participants)&&void 0!==t?t:[]):"trackPublished"===n.$case?this.onLocalTrackPublished&&this.onLocalTrackPublished(n.trackPublished):"speakersChanged"===n.$case?this.onSpeakersChanged&&this.onSpeakersChanged(null!==(i=n.speakersChanged.speakers)&&void 0!==i?i:[]):"leave"===n.$case?this.onLeave&&this.onLeave(n.leave):"mute"===n.$case?this.onRemoteMuteChanged&&this.onRemoteMuteChanged(n.mute.sid,n.mute.muted):"roomUpdate"===n.$case?this.onRoomUpdate&&n.roomUpdate.room&&this.onRoomUpdate(n.roomUpdate.room):"connectionQuality"===n.$case?this.onConnectionQuality&&this.onConnectionQuality(n.connectionQuality):"streamStateUpdate"===n.$case?this.onStreamStateUpdate&&this.onStreamStateUpdate(n.streamStateUpdate):"subscribedQualityUpdate"===n.$case?this.onSubscribedQualityUpdate&&this.onSubscribedQualityUpdate(n.subscribedQualityUpdate):"subscriptionPermissionUpdate"===n.$case?this.onSubscriptionPermissionUpdate&&this.onSubscriptionPermissionUpdate(n.subscriptionPermissionUpdate):"refreshToken"===n.$case?this.onTokenRefresh&&this.onTokenRefresh(n.refreshToken):"trackUnpublished"===n.$case?this.onLocalTrackUnpublished&&this.onLocalTrackUnpublished(n.trackUnpublished):"subscriptionResponse"===n.$case?this.onSubscriptionError&&this.onSubscriptionError(n.subscriptionResponse):"pong"===n.$case?this.resetPingTimeout():"pongResp"===n.$case?(this.rtt=Date.now()-n.pongResp.lastPingTimestamp,this.resetPingTimeout()):c.debug("unsupported message",n);else c.debug("received unsupported message")}setReconnected(){for(;this.queuedRequests.length>0;){const e=this.queuedRequests.shift();e&&this.requestQueue.run(e)}this.isReconnecting=!1}handleOnClose(e){return Qt(this,void 0,void 0,(function*(){if(!this.isConnected)return;const t=this.onClose;yield this.close(),c.debug("websocket connection closed: ".concat(e)),t&&t(e)}))}handleWSError(e){c.error("websocket error",e)}resetPingTimeout(){this.clearPingTimeout(),this.pingTimeoutDuration?this.pingTimeout=ar.setTimeout((()=>{c.warn("ping timeout triggered. last pong received at: ".concat(new Date(Date.now()-1e3*this.pingTimeoutDuration).toUTCString())),this.handleOnClose("ping timeout")}),1e3*this.pingTimeoutDuration):c.warn("ping timeout duration not set")}clearPingTimeout(){this.pingTimeout&&ar.clearTimeout(this.pingTimeout)}startPingInterval(){this.clearPingInterval(),this.resetPingTimeout(),this.pingIntervalDuration?(c.debug("start ping interval"),this.pingInterval=ar.setInterval((()=>{this.sendPing()}),1e3*this.pingIntervalDuration)):c.warn("ping interval duration not set")}clearPingInterval(){c.debug("clearing ping interval"),this.clearPingTimeout(),this.pingInterval&&ar.clearInterval(this.pingInterval)}}function gs(e){const t={type:"offer",sdp:e.sdp};switch(e.type){case"answer":case"offer":case"pranswer":case"rollback":t.type=e.type}return t}function bs(e){return{sdp:e.sdp,type:e.type}}const ks="AES-GCM",ys="lk_e2ee",Ss={sharedKey:!1,ratchetSalt:"LKFrameEncryptionKey",ratchetWindowSize:8};function Cs(){return Ts()||Es()}function Es(){return void 0!==window.RTCRtpScriptTransform}function Ts(){return void 0!==window.RTCRtpSender&&void 0!==window.RTCRtpSender.prototype.createEncodedStreams}function Ps(e){return Qt(this,void 0,void 0,(function*(){let t=new TextEncoder;return yield crypto.subtle.importKey("raw",t.encode(e),{name:"PBKDF2"},!1,["deriveBits","deriveKey"])}))}function ws(e,t){const i=(new TextEncoder).encode(t);switch(e){case"HKDF":return{name:"HKDF",salt:i,hash:"SHA-256",info:new ArrayBuffer(128)};case"PBKDF2":return{name:"PBKDF2",salt:i,hash:"SHA-256",iterations:1e5};default:throw new Error("algorithm ".concat(e," is currently unsupported"))}}function Rs(e){const t=e.split("/")[1].toLowerCase();if(!vr.includes(t))throw Error("Video codec not supported: ".concat(t));return t}class Ns extends Yt{constructor(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};super(),this.onKeyRatcheted=(e,t)=>{console.debug("key ratcheted event received",e,t)},this.keyInfoMap=new Map,this.options=Object.assign(Object.assign({},Ss),e),this.on("keyRatcheted",this.onKeyRatcheted)}onSetEncryptionKey(e,t,i){const n={key:e,participantId:t,keyIndex:i};this.keyInfoMap.set("".concat(null!=t?t:"shared","-").concat(null!=i?i:0),n),this.emit("setKey",n)}getKeys(){return Array.from(this.keyInfoMap.values())}getOptions(){return this.options}ratchetKey(e,t){this.emit("ratchetRequest",e,t)}}const Os={ParticipantEncryptionStatusChanged:"participantEncryptionStatusChanged",Error:"encryptionError"},Is="default";class Ds{static getInstance(){return void 0===this.instance&&(this.instance=new Ds),this.instance}getDevices(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];var i;return Qt(this,void 0,void 0,(function*(){if((null===(i=Ds.userMediaPromiseMap)||void 0===i?void 0:i.size)>0){c.debug("awaiting getUserMedia promise");try{e?yield Ds.userMediaPromiseMap.get(e):yield Promise.all(Ds.userMediaPromiseMap.values())}catch(e){c.warn("error waiting for media permissons")}}let n=yield navigator.mediaDevices.enumerateDevices();if(t&&e&&(!Ds.userMediaPromiseMap.get(e)||!Wr())){if(0===n.length||n.some((t=>{const i=""===t.label,n=!e||t.kind===e;return i&&n}))){const t={video:"audioinput"!==e&&"audiooutput"!==e,audio:"videoinput"!==e},i=yield navigator.mediaDevices.getUserMedia(t);n=yield navigator.mediaDevices.enumerateDevices(),i.getTracks().forEach((e=>{e.stop()}))}}return e&&(n=n.filter((t=>t.kind===e))),n}))}normalizeDeviceId(e,t,i){return Qt(this,void 0,void 0,(function*(){if(t!==Is)return t;const n=(yield this.getDevices(e)).find((e=>e.groupId===i&&e.deviceId!==Is));return null==n?void 0:n.deviceId}))}}Ds.mediaDeviceKinds=["audioinput","audiooutput","videoinput"],Ds.userMediaPromiseMap=new Map;class As extends Nr{get constraints(){return this._constraints}constructor(t,i,n){let r=arguments.length>3&&void 0!==arguments[3]&&arguments[3];super(t,i),this._isUpstreamPaused=!1,this.handleEnded=()=>{this.isInBackground&&(this.reacquireTrack=!0),this._mediaStreamTrack.removeEventListener("mute",this.pauseUpstream),this._mediaStreamTrack.removeEventListener("unmute",this.resumeUpstream),this.emit(e.TrackEvent.Ended,this)},this.pauseUpstream=()=>Qt(this,void 0,void 0,(function*(){const t=yield this.pauseUpstreamLock.lock();try{if(!0===this._isUpstreamPaused)return;if(!this.sender)return void c.warn("unable to pause upstream for an unpublished track");this._isUpstreamPaused=!0,this.emit(e.TrackEvent.UpstreamPaused,this);const t=ur();if("Safari"===(null==t?void 0:t.name)&&Xr(t.version,"12.0")<0)throw new ir("pauseUpstream is not supported on Safari < 12.");yield this.sender.replaceTrack(null)}finally{t()}})),this.resumeUpstream=()=>Qt(this,void 0,void 0,(function*(){const t=yield this.pauseUpstreamLock.lock();try{if(!1===this._isUpstreamPaused)return;if(!this.sender)return void c.warn("unable to resume upstream for an unpublished track");this._isUpstreamPaused=!1,this.emit(e.TrackEvent.UpstreamResumed,this),yield this.sender.replaceTrack(this._mediaStreamTrack)}finally{t()}})),this.reacquireTrack=!1,this.providedByUser=r,this.muteLock=new ls,this.pauseUpstreamLock=new ls,this.processorLock=new ls,this.setMediaStreamTrack(t,!0),this._constraints=t.getConstraints(),n&&(this._constraints=n)}get id(){return this._mediaStreamTrack.id}get dimensions(){if(this.kind!==Nr.Kind.Video)return;const{width:e,height:t}=this._mediaStreamTrack.getSettings();return e&&t?{width:e,height:t}:void 0}get isUpstreamPaused(){return this._isUpstreamPaused}get isUserProvided(){return this.providedByUser}get mediaStreamTrack(){var e,t;return null!==(t=null===(e=this.processor)||void 0===e?void 0:e.processedTrack)&&void 0!==t?t:this._mediaStreamTrack}setMediaStreamTrack(e,t){return Qt(this,void 0,void 0,(function*(){(e!==this._mediaStreamTrack||t)&&(this._mediaStreamTrack&&(this.attachedElements.forEach((e=>{Ir(this._mediaStreamTrack,e)})),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.removeEventListener("mute",this.pauseUpstream),this._mediaStreamTrack.removeEventListener("unmute",this.resumeUpstream),this.providedByUser||this._mediaStreamTrack===e||this._mediaStreamTrack.stop()),this.mediaStream=new MediaStream([e]),e&&(e.addEventListener("ended",this.handleEnded),e.addEventListener("mute",this.pauseUpstream),e.addEventListener("unmute",this.resumeUpstream),this._constraints=e.getConstraints()),this.sender&&(yield this.sender.replaceTrack(e)),this._mediaStreamTrack=e,e&&(this._mediaStreamTrack.enabled=!this.isMuted,yield this.resumeUpstream(),this.attachedElements.forEach((t=>{Or(e,t)}))))}))}waitForDimensions(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1e3;return Qt(this,void 0,void 0,(function*(){if(this.kind===Nr.Kind.Audio)throw new Error("cannot get dimensions for audio tracks");const t=Date.now();for(;Date.now()-t<e;){const e=this.dimensions;if(e)return e;yield _r(50)}throw new nr("unable to get track dimensions after timeout")}))}getDeviceId(){return Qt(this,void 0,void 0,(function*(){if(this.source===Nr.Source.ScreenShare)return;const{deviceId:e,groupId:t}=this._mediaStreamTrack.getSettings(),i=this.kind===Nr.Kind.Audio?"audioinput":"videoinput";return Ds.getInstance().normalizeDeviceId(i,e,t)}))}mute(){return Qt(this,void 0,void 0,(function*(){return this.setTrackMuted(!0),this}))}unmute(){return Qt(this,void 0,void 0,(function*(){return this.setTrackMuted(!1),this}))}replaceTrack(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return Qt(this,void 0,void 0,(function*(){if(!this.sender)throw new nr("unable to replace an unpublished track");return c.debug("replace MediaStreamTrack"),yield this.setMediaStreamTrack(e),this.providedByUser=t,this.processor&&(yield this.stopProcessor()),this}))}restart(t){return Qt(this,void 0,void 0,(function*(){t||(t=this._constraints),c.debug("restarting track with constraints",t);const i={audio:!1,video:!1};this.kind===Nr.Kind.Video?i.video=t:i.audio=t,this.attachedElements.forEach((e=>{Ir(this.mediaStreamTrack,e)})),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.stop();const n=(yield navigator.mediaDevices.getUserMedia(i)).getTracks()[0];if(n.addEventListener("ended",this.handleEnded),c.debug("re-acquired MediaStreamTrack"),yield this.setMediaStreamTrack(n),this._constraints=t,this.processor){const e=this.processor;yield this.setProcessor(e)}else this.attachedElements.forEach((e=>{Or(this._mediaStreamTrack,e)}));return this.emit(e.TrackEvent.Restarted,this),this}))}setTrackMuted(t){c.debug("setting ".concat(this.kind," track ").concat(t?"muted":"unmuted")),this.isMuted===t&&this._mediaStreamTrack.enabled!==t||(this.isMuted=t,this._mediaStreamTrack.enabled=!t,this.emit(t?e.TrackEvent.Muted:e.TrackEvent.Unmuted,this))}get needsReAcquisition(){return"live"!==this._mediaStreamTrack.readyState||this._mediaStreamTrack.muted||!this._mediaStreamTrack.enabled||this.reacquireTrack}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return Qt(this,void 0,void 0,(function*(){yield e.handleAppVisibilityChanged.call(this),Gr()&&(c.debug("visibility changed, is in Background: ".concat(this.isInBackground)),this.isInBackground||!this.needsReAcquisition||this.isUserProvided||this.isMuted||(c.debug("track needs to be reaquired, restarting ".concat(this.source)),yield this.restart(),this.reacquireTrack=!1))}))}stop(){var e;super.stop(),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.removeEventListener("mute",this.pauseUpstream),this._mediaStreamTrack.removeEventListener("unmute",this.resumeUpstream),null===(e=this.processor)||void 0===e||e.destroy(),this.processor=void 0}setProcessor(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];var i,n;return Qt(this,void 0,void 0,(function*(){const r=yield this.processorLock.lock();try{if(c.debug("setting up processor"),this.processor&&(yield this.stopProcessor()),"unknown"===this.kind)throw TypeError("cannot set processor on track of unknown kind");this.processorElement=null!==(i=this.processorElement)&&void 0!==i?i:document.createElement(this.kind),this.processorElement.muted=!0,Or(this._mediaStreamTrack,this.processorElement),this.processorElement.play().catch((e=>c.error("failed to play processor element",{error:e})));const r={kind:this.kind,track:this._mediaStreamTrack,element:this.processorElement};if(yield e.init(r),this.processor=e,this.processor.processedTrack){for(const e of this.attachedElements)e!==this.processorElement&&t&&(Ir(this._mediaStreamTrack,e),Or(this.processor.processedTrack,e));yield null===(n=this.sender)||void 0===n?void 0:n.replaceTrack(this.processor.processedTrack)}}finally{r()}}))}getProcessor(){return this.processor}stopProcessor(){var e,t;return Qt(this,void 0,void 0,(function*(){this.processor&&(c.debug("stopping processor"),null===(e=this.processor.processedTrack)||void 0===e||e.stop(),yield this.processor.destroy(),this.processor=void 0,null===(t=this.processorElement)||void 0===t||t.remove(),this.processorElement=void 0,yield this.restart())}))}}class Us extends Yt{get isEnabled(){return this.encryptionEnabled}constructor(e){super(),this.onWorkerMessage=e=>{var t,i;const{kind:n,data:r}=e.data;switch(n){case"error":console.error("error in worker",{data:r}),this.emit(Os.Error,r.error);break;case"enable":if(this.encryptionEnabled===r.enabled||r.participantId){if(r.participantId){const e=null===(i=this.room)||void 0===i?void 0:i.getParticipantByIdentity(r.participantId);this.emit(Os.ParticipantEncryptionStatusChanged,r.enabled,e)}}else this.emit(Os.ParticipantEncryptionStatusChanged,r.enabled,null===(t=this.room)||void 0===t?void 0:t.localParticipant),this.encryptionEnabled=r.enabled;this.encryptionEnabled&&this.keyProvider.getKeys().forEach((e=>{this.postKey(e)}));break;case"ratchetKey":this.keyProvider.emit("keyRatcheted",r.material,r.keyIndex)}},this.onWorkerError=e=>{c.error("e2ee worker encountered an error:",{error:e.error}),this.emit(Os.Error,e.error)},this.keyProvider=e.keyProvider,this.worker=e.worker,this.encryptionEnabled=!1}setup(e){if(!Cs())throw new ir("tried to setup end-to-end encryption on an unsupported browser");if(c.info("setting up e2ee"),e!==this.room){this.room=e,this.setupEventListeners(e,this.keyProvider);const t={kind:"init",data:{keyProviderOptions:this.keyProvider.getOptions()}};this.worker&&(c.info("initializing worker",{worker:this.worker}),this.worker.onmessage=this.onWorkerMessage,this.worker.onerror=this.onWorkerError,this.worker.postMessage(t))}}setParticipantCryptorEnabled(e,t){return Qt(this,void 0,void 0,(function*(){if(c.info("set e2ee to ".concat(e)),!this.worker)throw new ReferenceError("failed to enable e2ee, worker is not ready");{const i={kind:"enable",data:{enabled:e,participantId:t}};this.worker.postMessage(i)}}))}setupEngine(t){t.on(e.EngineEvent.RTPVideoMapUpdate,(e=>{this.postRTPMap(e)}))}setupEventListeners(t,i){t.on(e.RoomEvent.TrackPublished,((e,t)=>this.setParticipantCryptorEnabled(e.trackInfo.encryption!==tt.NONE,t.identity))),t.on(e.RoomEvent.ConnectionStateChanged,(i=>{i===e.ConnectionState.Connected&&t.participants.forEach((e=>{e.tracks.forEach((t=>{this.setParticipantCryptorEnabled(t.trackInfo.encryption!==tt.NONE,e.identity)}))}))})),t.on(e.RoomEvent.TrackUnsubscribed,((e,t,i)=>{var n;const r={kind:"removeTransform",data:{participantId:i.identity,trackId:e.mediaStreamID}};null===(n=this.worker)||void 0===n||n.postMessage(r)})),t.on(e.RoomEvent.TrackSubscribed,((e,t,i)=>{this.setupE2EEReceiver(e,i.identity,t.trackInfo)})),t.localParticipant.on(e.ParticipantEvent.LocalTrackPublished,(e=>Qt(this,void 0,void 0,(function*(){this.setupE2EESender(e.track,e.track.sender,t.localParticipant.identity)})))),i.on("setKey",(e=>this.postKey(e))).on("ratchetRequest",((e,t)=>this.postRatchetRequest(e,t)))}postRatchetRequest(e,t){if(!this.worker)throw Error("could not ratchet key, worker is missing");const i={kind:"ratchetRequest",data:{participantId:e,keyIndex:t}};this.worker.postMessage(i)}postKey(e){let{key:t,participantId:i,keyIndex:n}=e;if(!this.worker)throw Error("could not set key, worker is missing");const r={kind:"setKey",data:{participantId:i,key:t,keyIndex:n}};this.worker.postMessage(r)}postRTPMap(e){if(!this.worker)throw Error("could not post rtp map, worker is missing");const t={kind:"setRTPMap",data:{map:e}};this.worker.postMessage(t)}setupE2EEReceiver(e,t,i){if(e.receiver){if(!(null==i?void 0:i.mimeType)||""===i.mimeType)throw new TypeError("MimeType missing from trackInfo, cannot set up E2EE cryptor");this.handleReceiver(e.receiver,e.mediaStreamID,t,"video"===e.kind?Rs(i.mimeType):void 0)}}setupE2EESender(e,t,i){e instanceof As&&t?this.handleSender(t,e.mediaStreamID,i,void 0):t||c.warn("early return because sender is not ready")}handleReceiver(e,t,i,n){return Qt(this,void 0,void 0,(function*(){if(this.worker){if(Es()){const r={kind:"decode",participantId:i,trackId:t,codec:n};e.transform=new RTCRtpScriptTransform(this.worker,r)}else{if(ys in e&&n){const e={kind:"updateCodec",data:{trackId:t,codec:n,participantId:i}};return void this.worker.postMessage(e)}let r=e.writableStream,s=e.readableStream;if(!r||!s){const t=e.createEncodedStreams();e.writableStream=t.writable,r=t.writable,e.readableStream=t.readable,s=t.readable}const o={kind:"decode",data:{readableStream:s,writableStream:r,trackId:t,codec:n,participantId:i}};this.worker.postMessage(o,[s,r])}e[ys]=!0}}))}handleSender(e,t,i,n){if(!(ys in e)&&this.worker){if(Es()){c.warn("initialize script transform");const r={kind:"encode",participantId:i,trackId:t,codec:n};e.transform=new RTCRtpScriptTransform(this.worker,r)}else{c.warn("initialize encoded streams");const r=e.createEncodedStreams(),s={kind:"encode",data:{readableStream:r.readable,writableStream:r.writable,codec:n,trackId:t,participantId:i}};this.worker.postMessage(s,[r.readable,r.writable])}e[ys]=!0}}}var Ms={},Ls={exports:{}},_s=Ls.exports={v:[{name:"version",reg:/^(\d*)$/}],o:[{name:"origin",reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:["username","sessionId","sessionVersion","netType","ipVer","address"],format:"%s %s %d %s IP%d %s"}],s:[{name:"name"}],i:[{name:"description"}],u:[{name:"uri"}],e:[{name:"email"}],p:[{name:"phone"}],z:[{name:"timezones"}],r:[{name:"repeats"}],t:[{name:"timing",reg:/^(\d*) (\d*)/,names:["start","stop"],format:"%d %d"}],c:[{name:"connection",reg:/^IN IP(\d) (\S*)/,names:["version","ip"],format:"IN IP%d %s"}],b:[{push:"bandwidth",reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:["type","limit"],format:"%s:%s"}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:["type","port","protocol","payloads"],format:"%s %d %s %s"}],a:[{push:"rtp",reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:["payload","codec","rate","encoding"],format:function(e){return e.encoding?"rtpmap:%d %s/%s/%s":e.rate?"rtpmap:%d %s/%s":"rtpmap:%d %s"}},{push:"fmtp",reg:/^fmtp:(\d*) ([\S| ]*)/,names:["payload","config"],format:"fmtp:%d %s"},{name:"control",reg:/^control:(.*)/,format:"control:%s"},{name:"rtcp",reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:["port","netType","ipVer","address"],format:function(e){return null!=e.address?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%s trr-int %d"},{push:"rtcpFb",reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:["payload","type","subtype"],format:function(e){return null!=e.subtype?"rtcp-fb:%s %s %s":"rtcp-fb:%s %s"}},{push:"ext",reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:["value","direction","encrypt-uri","uri","config"],format:function(e){return"extmap:%d"+(e.direction?"/%s":"%v")+(e["encrypt-uri"]?" %s":"%v")+" %s"+(e.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(e){return null!=e.sessionConfig?"crypto:%d %s %s %s":"crypto:%d %s %s"}},{name:"setup",reg:/^setup:(\w*)/,format:"setup:%s"},{name:"connectionType",reg:/^connection:(new|existing)/,format:"connection:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{name:"msid",reg:/^msid:(.*)/,format:"msid:%s"},{name:"ptime",reg:/^ptime:(\d*(?:\.\d*)*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\d*(?:\.\d*)*)/,format:"maxptime:%d"},{name:"direction",reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:"icelite",reg:/^(ice-lite)/},{name:"iceUfrag",reg:/^ice-ufrag:(\S*)/,format:"ice-ufrag:%s"},{name:"icePwd",reg:/^ice-pwd:(\S*)/,format:"ice-pwd:%s"},{name:"fingerprint",reg:/^fingerprint:(\S*) (\S*)/,names:["type","hash"],format:"fingerprint:%s %s"},{push:"candidates",reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation","network-id","network-cost"],format:function(e){var t="candidate:%s %d %s %d %s %d typ %s";return t+=null!=e.raddr?" raddr %s rport %d":"%v%v",t+=null!=e.tcptype?" tcptype %s":"%v",null!=e.generation&&(t+=" generation %d"),t+=null!=e["network-id"]?" network-id %d":"%v",t+=null!=e["network-cost"]?" network-cost %d":"%v"}},{name:"endOfCandidates",reg:/^(end-of-candidates)/},{name:"remoteCandidates",reg:/^remote-candidates:(.*)/,format:"remote-candidates:%s"},{name:"iceOptions",reg:/^ice-options:(\S*)/,format:"ice-options:%s"},{push:"ssrcs",reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:["id","attribute","value"],format:function(e){var t="ssrc:%d";return null!=e.attribute&&(t+=" %s",null!=e.value&&(t+=":%s")),t}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","maxMessageSize"],format:function(e){return null!=e.maxMessageSize?"sctpmap:%s %s %s":"sctpmap:%s %s"}},{name:"xGoogleFlag",reg:/^x-google-flag:([^\s]*)/,format:"x-google-flag:%s"},{push:"rids",reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:["id","direction","params"],format:function(e){return e.params?"rid:%s %s %s":"rid:%s %s"}},{push:"imageattrs",reg:new RegExp("^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?"),names:["pt","dir1","attrs1","dir2","attrs2"],format:function(e){return"imageattr:%s %s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast",reg:new RegExp("^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$"),names:["dir1","list1","dir2","list2"],format:function(e){return"simulcast:%s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast_03",reg:/^simulcast:[\s\t]+([\S+\s\t]+)$/,names:["value"],format:"simulcast: %s"},{name:"framerate",reg:/^framerate:(\d+(?:$|\.\d+))/,format:"framerate:%s"},{name:"sourceFilter",reg:/^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,names:["filterMode","netType","addressTypes","destAddress","srcList"],format:"source-filter: %s %s %s %s %s"},{name:"bundleOnly",reg:/^(bundle-only)/},{name:"label",reg:/^label:(.+)/,format:"label:%s"},{name:"sctpPort",reg:/^sctp-port:(\d+)$/,format:"sctp-port:%s"},{name:"maxMessageSize",reg:/^max-message-size:(\d+)$/,format:"max-message-size:%s"},{push:"tsRefClocks",reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:["clksrc","clksrcExt"],format:function(e){return"ts-refclk:%s"+(null!=e.clksrcExt?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(e){var t="mediaclk:";return t+=null!=e.id?"id=%s %s":"%v%s",t+=null!=e.mediaClockValue?"=%s":"",t+=null!=e.rateNumerator?" rate=%s":"",t+=null!=e.rateDenominator?"/%s":""}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{push:"invalid",names:["value"]}]};Object.keys(_s).forEach((function(e){_s[e].forEach((function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")}))}));var xs=Ls.exports;!function(e){var t=function(e){return String(Number(e))===e?Number(e):e},i=function(e,i,n){var r=e.name&&e.names;e.push&&!i[e.push]?i[e.push]=[]:r&&!i[e.name]&&(i[e.name]={});var s=e.push?{}:r?i[e.name]:i;!function(e,i,n,r){if(r&&!n)i[r]=t(e[1]);else for(var s=0;s<n.length;s+=1)null!=e[s+1]&&(i[n[s]]=t(e[s+1]))}(n.match(e.reg),s,e.names,e.name),e.push&&i[e.push].push(s)},n=xs,r=RegExp.prototype.test.bind(/^([a-z])=(.*)/);e.parse=function(e){var t={},s=[],o=t;return e.split(/(\r\n|\r|\n)/).filter(r).forEach((function(e){var t=e[0],r=e.slice(2);"m"===t&&(s.push({rtp:[],fmtp:[]}),o=s[s.length-1]);for(var a=0;a<(n[t]||[]).length;a+=1){var c=n[t][a];if(c.reg.test(r))return i(c,o,r)}})),t.media=s,t};var s=function(e,i){var n=i.split(/=(.+)/,2);return 2===n.length?e[n[0]]=t(n[1]):1===n.length&&i.length>1&&(e[n[0]]=void 0),e};e.parseParams=function(e){return e.split(/;\s?/).reduce(s,{})},e.parseFmtpConfig=e.parseParams,e.parsePayloads=function(e){return e.toString().split(" ").map(Number)},e.parseRemoteCandidates=function(e){for(var i=[],n=e.split(" ").map(t),r=0;r<n.length;r+=3)i.push({component:n[r],ip:n[r+1],port:n[r+2]});return i},e.parseImageAttributes=function(e){return e.split(" ").map((function(e){return e.substring(1,e.length-1).split(",").reduce(s,{})}))},e.parseSimulcastStreamList=function(e){return e.split(";").map((function(e){return e.split(",").map((function(e){var i,n=!1;return"~"!==e[0]?i=t(e):(i=t(e.substring(1,e.length)),n=!0),{scid:i,paused:n}}))}))}}(Ms);var Bs=xs,Js=/%[sdv%]/g,Fs=function(e){var t=1,i=arguments,n=i.length;return e.replace(Js,(function(e){if(t>=n)return e;var r=i[t];switch(t+=1,e){case"%%":return"%";case"%s":return String(r);case"%d":return Number(r);case"%v":return""}}))},$s=function(e,t,i){var n=[e+"="+(t.format instanceof Function?t.format(t.push?i:i[t.name]):t.format)];if(t.names)for(var r=0;r<t.names.length;r+=1){var s=t.names[r];t.name?n.push(i[t.name][s]):n.push(i[t.names[r]])}else n.push(i[t.name]);return Fs.apply(null,n)},Vs=["v","o","s","i","u","e","p","c","b","t","r","z","a"],js=["i","c","b","a"],qs=Ms,Ws=function(e,t){t=t||{},null==e.version&&(e.version=0),null==e.name&&(e.name=" "),e.media.forEach((function(e){null==e.payloads&&(e.payloads="")}));var i=t.outerOrder||Vs,n=t.innerOrder||js,r=[];return i.forEach((function(t){Bs[t].forEach((function(i){i.name in e&&null!=e[i.name]?r.push($s(t,i,e)):i.push in e&&null!=e[i.push]&&e[i.push].forEach((function(e){r.push($s(t,i,e))}))}))})),e.media.forEach((function(e){r.push($s("m",Bs.m[0],e)),n.forEach((function(t){Bs[t].forEach((function(i){i.name in e&&null!=e[i.name]?r.push($s(t,i,e)):i.push in e&&null!=e[i.push]&&e[i.push].forEach((function(e){r.push($s(t,i,e))}))}))}))})),r.join("\r\n")+"\r\n"},Gs=Ws,Ks=qs.parse;function Qs(e,t,i){var n,r,s;void 0===t&&(t=50),void 0===i&&(i={});var o=null!=(n=i.isImmediate)&&n,a=null!=(r=i.callback)&&r,c=i.maxWait,d=Date.now(),u=[];function l(){if(void 0!==c){var e=Date.now()-d;if(e+t>=c)return c-e}return t}var h=function(){var t=[].slice.call(arguments),i=this;return new Promise((function(n,r){var c=o&&void 0===s;if(void 0!==s&&clearTimeout(s),s=setTimeout((function(){if(s=void 0,d=Date.now(),!o){var n=e.apply(i,t);a&&a(n),u.forEach((function(e){return(0,e.resolve)(n)})),u=[]}}),l()),c){var h=e.apply(i,t);return a&&a(h),n(h)}u.push({resolve:n,reject:r})}))};return h.cancel=function(e){void 0!==s&&clearTimeout(s),u.forEach((function(t){return(0,t.reject)(e)})),u=[]},h}const Hs="negotiationStarted",Zs="negotiationComplete",zs="rtpVideoPayloadTypes";class Ys extends Yt{get pc(){if(this._pc)return this._pc;throw new sr("Expected peer connection to be available")}constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};var i;super(),this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate=!1,this.trackBitrates=[],this.remoteStereoMids=[],this.remoteNackMids=[],this.negotiate=Qs((e=>{this.emit(Hs);try{this.createAndSendOffer()}catch(t){if(!e)throw t;e(t)}}),100),this._pc="Chrome"===(null===(i=ur())||void 0===i?void 0:i.name)?new RTCPeerConnection(e,t):new RTCPeerConnection(e)}get isICEConnected(){return null!==this._pc&&("connected"===this.pc.iceConnectionState||"completed"===this.pc.iceConnectionState)}addIceCandidate(e){return Qt(this,void 0,void 0,(function*(){if(this.pc.remoteDescription&&!this.restartingIce)return this.pc.addIceCandidate(e);this.pendingCandidates.push(e)}))}setRemoteDescription(e){var t;return Qt(this,void 0,void 0,(function*(){let i;if("offer"===e.type){let{stereoMids:t,nackMids:i}=function(e){var t;const i=[],n=[],r=Ks(null!==(t=e.sdp)&&void 0!==t?t:"");let s=0;return r.media.forEach((e=>{var t;"audio"===e.type&&(e.rtp.some((e=>"opus"===e.codec&&(s=e.payload,!0))),(null===(t=e.rtcpFb)||void 0===t?void 0:t.some((e=>e.payload===s&&"nack"===e.type)))&&n.push(e.mid),e.fmtp.some((t=>t.payload===s&&(t.config.includes("sprop-stereo=1")&&i.push(e.mid),!0))))})),{stereoMids:i,nackMids:n}}(e);this.remoteStereoMids=t,this.remoteNackMids=i}else if("answer"===e.type){const n=Ks(null!==(t=e.sdp)&&void 0!==t?t:"");n.media.forEach((e=>{"audio"===e.type&&this.trackBitrates.some((t=>{if(!t.transceiver||e.mid!=t.transceiver.mid)return!1;let i=0;if(e.rtp.some((e=>e.codec.toUpperCase()===t.codec.toUpperCase()&&(i=e.payload,!0))),0===i)return!0;let n=!1;for(const r of e.fmtp)if(r.payload===i){r.config=r.config.split(";").filter((e=>!e.includes("maxaveragebitrate"))).join(";"),t.maxbr>0&&(r.config+=";maxaveragebitrate=".concat(1e3*t.maxbr)),n=!0;break}return n||t.maxbr>0&&e.fmtp.push({payload:i,config:"maxaveragebitrate=".concat(1e3*t.maxbr)}),!0}))})),i=Gs(n)}if(yield this.setMungedSDP(e,i,!0),this.pendingCandidates.forEach((e=>{this.pc.addIceCandidate(e)})),this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate)this.renegotiate=!1,this.createAndSendOffer();else if("answer"===e.type&&(this.emit(Zs),e.sdp)){Ks(e.sdp).media.forEach((e=>{"video"===e.type&&this.emit(zs,e.rtp)}))}}))}createAndSendOffer(e){var t;return Qt(this,void 0,void 0,(function*(){if(void 0===this.onOffer)return;if((null==e?void 0:e.iceRestart)&&(c.debug("restarting ICE"),this.restartingIce=!0),this._pc&&"have-local-offer"===this._pc.signalingState){const t=this.pc.remoteDescription;if(!(null==e?void 0:e.iceRestart)||!t)return void(this.renegotiate=!0);yield this.pc.setRemoteDescription(t)}else if(!this._pc||"closed"===this._pc.signalingState)return void c.warn("could not createOffer with closed peer connection");c.debug("starting to negotiate");const i=yield this.pc.createOffer(e),n=Ks(null!==(t=i.sdp)&&void 0!==t?t:"");n.media.forEach((e=>{"audio"===e.type?Xs(e,[],[]):"video"===e.type&&(!function(e){var t,i,n,r;const s=null===(i=null===(t=e.rtp[0])||void 0===t?void 0:t.codec)||void 0===i?void 0:i.toLowerCase();if(!$r(s))return;let o=0;const a=null===(n=e.ext)||void 0===n?void 0:n.some((e=>e.uri===Lr||(e.value>o&&(o=e.value),!1)));a||null===(r=e.ext)||void 0===r||r.push({value:o+1,uri:Lr})}(e),this.trackBitrates.some((t=>{if(!e.msid||!t.cid||!e.msid.includes(t.cid))return!1;let i=0;if(e.rtp.some((e=>e.codec.toUpperCase()===t.codec.toUpperCase()&&(i=e.payload,!0))),0===i)return!0;let n=!1;for(const r of e.fmtp)if(r.payload===i){r.config.includes("x-google-start-bitrate")||(r.config+=";x-google-start-bitrate=".concat(.7*t.maxbr)),r.config.includes("x-google-max-bitrate")||(r.config+=";x-google-max-bitrate=".concat(t.maxbr)),n=!0;break}return n||e.fmtp.push({payload:i,config:"x-google-start-bitrate=".concat(.7*t.maxbr,";x-google-max-bitrate=").concat(t.maxbr)}),!0})))})),yield this.setMungedSDP(i,Gs(n)),this.onOffer(i)}))}createAndSetAnswer(){var e;return Qt(this,void 0,void 0,(function*(){const t=yield this.pc.createAnswer(),i=Ks(null!==(e=t.sdp)&&void 0!==e?e:"");return i.media.forEach((e=>{"audio"===e.type&&Xs(e,this.remoteStereoMids,this.remoteNackMids)})),yield this.setMungedSDP(t,Gs(i)),t}))}setTrackCodecBitrate(e){this.trackBitrates.push(e)}close(){this._pc&&(this._pc.close(),this._pc.onconnectionstatechange=null,this._pc.oniceconnectionstatechange=null,this._pc.onicegatheringstatechange=null,this._pc.ondatachannel=null,this._pc.onnegotiationneeded=null,this._pc.onsignalingstatechange=null,this._pc.onicecandidate=null,this._pc.ondatachannel=null,this._pc.ontrack=null,this._pc.onconnectionstatechange=null,this._pc.oniceconnectionstatechange=null,this._pc=null)}setMungedSDP(e,t,i){return Qt(this,void 0,void 0,(function*(){if(t){const n=e.sdp;e.sdp=t;try{return c.debug("setting munged ".concat(i?"remote":"local"," description")),void(i?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e))}catch(t){c.warn("not able to set ".concat(e.type,", falling back to unmodified sdp"),{error:t}),e.sdp=n}}try{i?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e)}catch(e){let t="unknown error";throw e instanceof Error?t=e.message:"string"==typeof e&&(t=e),new or(t)}}))}}function Xs(e,t,i){let n=0;e.rtp.some((e=>"opus"===e.codec&&(n=e.payload,!0))),n>0&&(e.rtcpFb||(e.rtcpFb=[]),i.includes(e.mid)&&!e.rtcpFb.some((e=>e.payload===n&&"nack"===e.type))&&e.rtcpFb.push({payload:n,type:"nack"}),t.includes(e.mid)&&e.fmtp.some((e=>e.payload===n&&(e.config.includes("stereo=1")||(e.config+=";stereo=1"),!0))))}class eo{constructor(e,t){this.lastUpdateAt=0,this.settingsCacheTime=3e3,this.attemptedRegions=[],this.serverUrl=new URL(e),this.token=t}isCloud(){return Hr(this.serverUrl)}getNextBestRegionUrl(e){return Qt(this,void 0,void 0,(function*(){if(!this.isCloud())throw Error("region availability is only supported for LiveKit Cloud domains");(!this.regionSettings||Date.now()-this.lastUpdateAt>this.settingsCacheTime)&&(this.regionSettings=yield this.fetchRegionSettings(e));const t=this.regionSettings.regions.filter((e=>!this.attemptedRegions.find((t=>t.url===e.url))));if(t.length>0){const e=t[0];return this.attemptedRegions.push(e),c.debug("next region: ".concat(e.region)),e.url}return null}))}resetAttempts(){this.attemptedRegions=[]}fetchRegionSettings(e){return Qt(this,void 0,void 0,(function*(){const t=yield fetch("".concat((i=this.serverUrl,"".concat(i.protocol.replace("ws","http"),"//").concat(i.host,"/settings")),"/regions"),{headers:{authorization:"Bearer ".concat(this.token)},signal:e});var i;if(t.ok){const e=yield t.json();return this.lastUpdateAt=Date.now(),e}throw new tr("Could not fetch region settings: ".concat(t.statusText),401===t.status?0:void 0,t.status)}))}}const to={audioBitrate:e.AudioPresets.music.maxBitrate,audioPreset:e.AudioPresets.music,dtx:!0,red:!0,forceStereo:!1,simulcast:!0,screenShareEncoding:Cr.h1080fps15.encoding,stopMicTrackOnMute:!1,videoCodec:"vp8",backupCodec:!1},io={autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0},no={resolution:yr.h720.resolution},ro={adaptiveStream:!1,dynacast:!1,stopLocalTrackOnUnpublish:!0,reconnectPolicy:new Kt,disconnectOnPageLeave:!0,expWebAudioMix:!1},so={autoSubscribe:!0,maxRetries:1,peerConnectionTimeout:15e3},oo="_lossy",ao="_reliable",co="leave-reconnect";var uo;!function(e){e[e.New=0]="New",e[e.Connected=1]="Connected",e[e.Disconnected=2]="Disconnected",e[e.Reconnecting=3]="Reconnecting",e[e.Closed=4]="Closed"}(uo||(uo={}));class lo extends Yt{get isClosed(){return this._isClosed}constructor(t){super(),this.options=t,this.rtcConfig={},this.peerConnectionTimeout=so.peerConnectionTimeout,this.fullReconnectOnNext=!1,this.subscriberPrimary=!1,this.pcState=uo.New,this._isClosed=!0,this.pendingTrackResolvers={},this.hasPublished=!1,this.reconnectAttempts=0,this.reconnectStart=0,this.attemptingReconnect=!1,this.joinAttempts=0,this.maxJoinAttempts=1,this.shouldFailNext=!1,this.handleDataChannel=e=>{let{channel:t}=e;return Qt(this,void 0,void 0,(function*(){if(t){if(t.label===ao)this.reliableDCSub=t;else{if(t.label!==oo)return;this.lossyDCSub=t}c.debug("on data channel ".concat(t.id,", ").concat(t.label)),t.onmessage=this.handleDataMessage}}))},this.handleDataMessage=t=>Qt(this,void 0,void 0,(function*(){var i,n;const r=yield this.dataProcessLock.lock();try{let r;if(t.data instanceof ArrayBuffer)r=t.data;else{if(!(t.data instanceof Blob))return void c.error("unsupported data type",t.data);r=yield t.data.arrayBuffer()}const s=It.decode(new Uint8Array(r));"speaker"===(null===(i=s.value)||void 0===i?void 0:i.$case)?this.emit(e.EngineEvent.ActiveSpeakersUpdate,s.value.speaker.speakers):"user"===(null===(n=s.value)||void 0===n?void 0:n.$case)&&this.emit(e.EngineEvent.DataPacketReceived,s.value.user,s.kind)}finally{r()}})),this.handleDataError=e=>{const t=0===e.currentTarget.maxRetransmits?"lossy":"reliable";if(e instanceof ErrorEvent){const{error:i}=e.error;c.error("DataChannel error on ".concat(t,": ").concat(e.message),i)}else c.error("Unknown DataChannel Error on ".concat(t),e)},this.handleBufferedAmountLow=t=>{const i=0===t.currentTarget.maxRetransmits?e.DataPacket_Kind.LOSSY:e.DataPacket_Kind.RELIABLE;this.updateAndEmitDCBufferStatus(i)},this.handleDisconnect=(t,i)=>{if(this._isClosed)return;c.warn("".concat(t," disconnected")),0===this.reconnectAttempts&&(this.reconnectStart=Date.now());const n=t=>{c.warn("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(t,"ms. giving up")),this.emit(e.EngineEvent.Disconnected),this.close()},r=Date.now()-this.reconnectStart;let s=this.getNextRetryDelay({elapsedMs:r,retryCount:this.reconnectAttempts});null!==s?(t===co&&(s=0),c.debug("reconnecting in ".concat(s,"ms")),this.clearReconnectTimeout(),this.url&&this.token&&Hr(new URL(this.url))&&(this.regionUrlProvider=new eo(this.url,this.token)),this.reconnectTimeout=ar.setTimeout((()=>this.attemptReconnect(i)),s)):n(r)},this.waitForRestarted=()=>new Promise(((t,i)=>{this.pcState===uo.Connected&&t();const n=()=>{this.off(e.EngineEvent.Disconnected,r),t()},r=()=>{this.off(e.EngineEvent.Restarted,n),i()};this.once(e.EngineEvent.Restarted,n),this.once(e.EngineEvent.Disconnected,r),this.once(e.EngineEvent.Closing,r)})),this.updateAndEmitDCBufferStatus=t=>{const i=this.isBufferStatusLow(t);void 0!==i&&i!==this.dcBufferStatus.get(t)&&(this.dcBufferStatus.set(t,i),this.emit(e.EngineEvent.DCBufferStatusChanged,i,t))},this.isBufferStatusLow=e=>{const t=this.dataChannelForKind(e);if(t)return t.bufferedAmount<=t.bufferedAmountLowThreshold},this.handleBrowserOnLine=()=>{this.client.isReconnecting&&(this.clearReconnectTimeout(),this.attemptReconnect(Ye.RR_SIGNAL_DISCONNECTED))},this.client=new vs,this.client.signalLatency=this.options.expSignalLatency,this.reconnectPolicy=this.options.reconnectPolicy,this.registerOnLineListener(),this.closingLock=new ls,this.dataProcessLock=new ls,this.dcBufferStatus=new Map([[e.DataPacket_Kind.LOSSY,!0],[e.DataPacket_Kind.RELIABLE,!0]]),this.client.onParticipantUpdate=t=>this.emit(e.EngineEvent.ParticipantUpdate,t),this.client.onConnectionQuality=t=>this.emit(e.EngineEvent.ConnectionQualityUpdate,t),this.client.onRoomUpdate=t=>this.emit(e.EngineEvent.RoomUpdate,t),this.client.onSubscriptionError=t=>this.emit(e.EngineEvent.SubscriptionError,t),this.client.onSubscriptionPermissionUpdate=t=>this.emit(e.EngineEvent.SubscriptionPermissionUpdate,t),this.client.onSpeakersChanged=t=>this.emit(e.EngineEvent.SpeakersChanged,t),this.client.onStreamStateUpdate=t=>this.emit(e.EngineEvent.StreamStateChanged,t)}join(e,t,i,n){return Qt(this,void 0,void 0,(function*(){this.url=e,this.token=t,this.signalOpts=i;try{this.joinAttempts+=1;const r=yield this.client.join(e,t,i,n);return this._isClosed=!1,this.latestJoinResponse=r,this.subscriberPrimary=r.subscriberPrimary,this.publisher||this.configure(r),this.subscriberPrimary||this.negotiate(),this.setupSignalClientCallbacks(),this.clientConfiguration=r.clientConfiguration,r}catch(r){if(r instanceof tr&&1===r.reason&&(c.warn("Couldn't connect to server, attempt ".concat(this.joinAttempts," of ").concat(this.maxJoinAttempts)),this.joinAttempts<this.maxJoinAttempts))return this.join(e,t,i,n);throw r}}))}close(){return Qt(this,void 0,void 0,(function*(){const t=yield this.closingLock.lock();if(this.isClosed)t();else try{this._isClosed=!0,this.emit(e.EngineEvent.Closing),this.removeAllListeners(),this.deregisterOnLineListener(),this.clearPendingReconnect(),yield this.cleanupPeerConnections(),yield this.cleanupClient()}finally{t()}}))}cleanupPeerConnections(){return Qt(this,void 0,void 0,(function*(){this.publisher&&"closed"!==this.publisher.pc.signalingState&&this.publisher.pc.getSenders().forEach((e=>{var t,i;try{(null===(t=this.publisher)||void 0===t?void 0:t.pc.removeTrack)&&(null===(i=this.publisher)||void 0===i||i.pc.removeTrack(e))}catch(e){c.warn("could not removeTrack",{error:e})}})),this.publisher&&(this.publisher.close(),this.publisher=void 0),this.subscriber&&(this.subscriber.close(),this.subscriber=void 0),this.primaryPC=void 0;const e=e=>{e&&(e.close(),e.onbufferedamountlow=null,e.onclose=null,e.onclosing=null,e.onerror=null,e.onmessage=null,e.onopen=null)};e(this.lossyDC),e(this.lossyDCSub),e(this.reliableDC),e(this.reliableDCSub),this.lossyDC=void 0,this.lossyDCSub=void 0,this.reliableDC=void 0,this.reliableDCSub=void 0}))}cleanupClient(){return Qt(this,void 0,void 0,(function*(){yield this.client.close(),this.client.resetCallbacks()}))}addTrack(e){if(this.pendingTrackResolvers[e.cid])throw new nr("a track with the same ID has already been published");return new Promise(((t,i)=>{const n=setTimeout((()=>{delete this.pendingTrackResolvers[e.cid],i(new tr("publication of local track timed out, no response from server"))}),1e4);this.pendingTrackResolvers[e.cid]={resolve:e=>{clearTimeout(n),t(e)},reject:()=>{clearTimeout(n),i(new Error("Cancelled publication by calling unpublish"))}},this.client.sendAddTrack(e)}))}removeTrack(e){var t;if(e.track&&this.pendingTrackResolvers[e.track.id]){const{reject:t}=this.pendingTrackResolvers[e.track.id];t&&t(),delete this.pendingTrackResolvers[e.track.id]}try{return null===(t=this.publisher)||void 0===t||t.pc.removeTrack(e),!0}catch(e){c.warn("failed to remove track",{error:e,method:"removeTrack"})}return!1}updateMuteStatus(e,t){this.client.sendMuteTrack(e,t)}get dataSubscriberReadyState(){var e;return null===(e=this.reliableDCSub)||void 0===e?void 0:e.readyState}getConnectedServerAddress(){return Qt(this,void 0,void 0,(function*(){if(void 0!==this.primaryPC)return function(e){var t;return Qt(this,void 0,void 0,(function*(){let i="";const n=new Map,r=new Map;if((yield e.getStats()).forEach((e=>{switch(e.type){case"transport":i=e.selectedCandidatePairId;break;case"candidate-pair":""===i&&e.selected&&(i=e.id),n.set(e.id,e);break;case"remote-candidate":r.set(e.id,"".concat(e.address,":").concat(e.port))}})),""===i)return;const s=null===(t=n.get(i))||void 0===t?void 0:t.remoteCandidateId;return void 0!==s?r.get(s):void 0}))}(this.primaryPC)}))}configure(t){var i,n;if(this.publisher||this.subscriber)return;this.participantSid=null===(i=t.participant)||void 0===i?void 0:i.sid;const r=this.makeRTCConfiguration(t);(null===(n=this.signalOpts)||void 0===n?void 0:n.e2eeEnabled)&&(c.debug("E2EE - setting up transports with insertable streams"),r.encodedInsertableStreams=!0);this.publisher=new Ys(r,{optional:[{googDscp:!0}]}),this.subscriber=new Ys(r),this.emit(e.EngineEvent.TransportsCreated,this.publisher,this.subscriber),this.publisher.pc.onicecandidate=e=>{e.candidate&&(c.trace("adding ICE candidate for peer",e.candidate),this.client.sendIceCandidate(e.candidate,rn.PUBLISHER))},this.subscriber.pc.onicecandidate=e=>{e.candidate&&this.client.sendIceCandidate(e.candidate,rn.SUBSCRIBER)},this.publisher.onOffer=e=>{this.client.sendOffer(e)};let s=this.publisher.pc,o=this.subscriber.pc,a=t.subscriberPrimary;a&&(s=this.subscriber.pc,o=this.publisher.pc,this.subscriber.pc.ondatachannel=this.handleDataChannel),this.primaryPC=s,s.onconnectionstatechange=()=>Qt(this,void 0,void 0,(function*(){if(c.debug("primary PC state changed ".concat(s.connectionState)),"connected"===s.connectionState){const i=this.pcState===uo.New;this.pcState=uo.Connected,i&&this.emit(e.EngineEvent.Connected,t)}else"failed"===s.connectionState&&this.pcState===uo.Connected&&(this.pcState=uo.Disconnected,this.handleDisconnect("primary peerconnection",a?Ye.RR_SUBSCRIBER_FAILED:Ye.RR_PUBLISHER_FAILED))})),o.onconnectionstatechange=()=>Qt(this,void 0,void 0,(function*(){c.debug("secondary PC state changed ".concat(o.connectionState)),"failed"===o.connectionState&&this.handleDisconnect("secondary peerconnection",a?Ye.RR_PUBLISHER_FAILED:Ye.RR_SUBSCRIBER_FAILED)})),this.subscriber.pc.ontrack=t=>{this.emit(e.EngineEvent.MediaTrackAdded,t.track,t.streams[0],t.receiver)},this.createDataChannels()}setupSignalClientCallbacks(){this.client.onAnswer=e=>Qt(this,void 0,void 0,(function*(){this.publisher&&(c.debug("received server answer",{RTCSdpType:e.type,signalingState:this.publisher.pc.signalingState.toString()}),yield this.publisher.setRemoteDescription(e))})),this.client.onTrickle=(e,t)=>{this.publisher&&this.subscriber&&(c.trace("got ICE candidate from peer",{candidate:e,target:t}),t===rn.PUBLISHER?this.publisher.addIceCandidate(e):this.subscriber.addIceCandidate(e))},this.client.onOffer=e=>Qt(this,void 0,void 0,(function*(){if(!this.subscriber)return;c.debug("received server offer",{RTCSdpType:e.type,signalingState:this.subscriber.pc.signalingState.toString()}),yield this.subscriber.setRemoteDescription(e);const t=yield this.subscriber.createAndSetAnswer();this.client.sendAnswer(t)})),this.client.onLocalTrackPublished=e=>{c.debug("received trackPublishedResponse",e);const{resolve:t}=this.pendingTrackResolvers[e.cid];t?(delete this.pendingTrackResolvers[e.cid],t(e.track)):c.error("missing track resolver for ".concat(e.cid))},this.client.onTokenRefresh=e=>{this.token=e},this.client.onClose=()=>{this.handleDisconnect("signal",Ye.RR_SIGNAL_DISCONNECTED)},this.client.onLeave=t=>{(null==t?void 0:t.canReconnect)?(this.fullReconnectOnNext=!0,this.primaryPC=void 0,this.handleDisconnect(co)):(this.emit(e.EngineEvent.Disconnected,null==t?void 0:t.reason),this.close()),c.trace("leave request",{leave:t})}}makeRTCConfiguration(e){const t=Object.assign({},this.rtcConfig);if(e.iceServers&&!t.iceServers){const i=[];e.iceServers.forEach((e=>{const t={urls:e.urls};e.username&&(t.username=e.username),e.credential&&(t.credential=e.credential),i.push(t)})),t.iceServers=i}return e.clientConfiguration&&e.clientConfiguration.forceRelay===Ze.ENABLED&&(t.iceTransportPolicy="relay"),t.sdpSemantics="unified-plan",t.continualGatheringPolicy="gather_continually",t}createDataChannels(){this.publisher&&(this.lossyDC&&(this.lossyDC.onmessage=null,this.lossyDC.onerror=null),this.reliableDC&&(this.reliableDC.onmessage=null,this.reliableDC.onerror=null),this.lossyDC=this.publisher.pc.createDataChannel(oo,{ordered:!0,maxRetransmits:0}),this.reliableDC=this.publisher.pc.createDataChannel(ao,{ordered:!0}),this.lossyDC.onmessage=this.handleDataMessage,this.reliableDC.onmessage=this.handleDataMessage,this.lossyDC.onerror=this.handleDataError,this.reliableDC.onerror=this.handleDataError,this.lossyDC.bufferedAmountLowThreshold=65535,this.reliableDC.bufferedAmountLowThreshold=65535,this.lossyDC.onbufferedamountlow=this.handleBufferedAmountLow,this.reliableDC.onbufferedamountlow=this.handleBufferedAmountLow)}setPreferredCodec(e,t,i){if(!("getCapabilities"in RTCRtpSender))return;const n=RTCRtpSender.getCapabilities(t);if(!n)return;c.debug("get capabilities",n);const r=[],s=[],o=[];n.codecs.forEach((e=>{const t=e.mimeType.toLowerCase();if("audio/opus"===t)return void r.push(e);t==="video/".concat(i)?"h264"!==i||e.sdpFmtpLine&&e.sdpFmtpLine.includes("profile-level-id=42e01f")?r.push(e):s.push(e):o.push(e)})),function(e){if(!Kr())return!1;if(!("setCodecPreferences"in e))return!1;const t=ur();if(!(null==t?void 0:t.name)||!t.version)return!1;const i=jr[t.name];return!!i&&Xr(t.version,i)>=0}(e)&&e.setCodecPreferences(r.concat(s,o))}createSender(e,t,i){return Qt(this,void 0,void 0,(function*(){if(xr()){return yield this.createTransceiverRTCRtpSender(e,t,i)}if(Br()){c.warn("using add-track fallback");return yield this.createRTCRtpSender(e.mediaStreamTrack)}throw new sr("Required webRTC APIs not supported on this device")}))}createSimulcastSender(e,t,i,n){return Qt(this,void 0,void 0,(function*(){if(xr())return this.createSimulcastTransceiverSender(e,t,i,n);if(Br())return c.debug("using add-track fallback"),this.createRTCRtpSender(e.mediaStreamTrack);throw new sr("Cannot stream on this device")}))}createTransceiverRTCRtpSender(e,t,i){return Qt(this,void 0,void 0,(function*(){if(!this.publisher)throw new sr("publisher is closed");const n=[];e.mediaStream&&n.push(e.mediaStream);const r={direction:"sendonly",streams:n};i&&(r.sendEncodings=i);const s=yield this.publisher.pc.addTransceiver(e.mediaStreamTrack,r);return e.kind===Nr.Kind.Video&&t.videoCodec&&(this.setPreferredCodec(s,e.kind,t.videoCodec),e.codec=t.videoCodec),s.sender}))}createSimulcastTransceiverSender(e,t,i,n){return Qt(this,void 0,void 0,(function*(){if(!this.publisher)throw new sr("publisher is closed");const r={direction:"sendonly"};n&&(r.sendEncodings=n);const s=yield this.publisher.pc.addTransceiver(t.mediaStreamTrack,r);if(i.videoCodec)return this.setPreferredCodec(s,e.kind,i.videoCodec),e.setSimulcastTrackSender(i.videoCodec,s.sender),s.sender}))}createRTCRtpSender(e){return Qt(this,void 0,void 0,(function*(){if(!this.publisher)throw new sr("publisher is closed");return this.publisher.pc.addTrack(e)}))}attemptReconnect(t){var i,n,r;return Qt(this,void 0,void 0,(function*(){if(!this._isClosed&&!this.attemptingReconnect){(null===(i=this.clientConfiguration)||void 0===i?void 0:i.resumeConnection)!==Ze.DISABLED&&"closed"!==(null!==(r=null===(n=this.primaryPC)||void 0===n?void 0:n.signalingState)&&void 0!==r?r:"closed")||(this.fullReconnectOnNext=!0);try{this.attemptingReconnect=!0,this.fullReconnectOnNext?yield this.restartConnection():yield this.resumeConnection(t),this.clearPendingReconnect(),this.fullReconnectOnNext=!1}catch(t){this.reconnectAttempts+=1;let i=!0;t instanceof sr?(c.debug("received unrecoverable error",{error:t}),i=!1):t instanceof ho||(this.fullReconnectOnNext=!0),i?this.handleDisconnect("reconnect",Ye.RR_UNKNOWN):(c.info("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(Date.now()-this.reconnectStart,"ms. giving up")),this.emit(e.EngineEvent.Disconnected),yield this.close())}finally{this.attemptingReconnect=!1}}}))}getNextRetryDelay(e){try{return this.reconnectPolicy.nextRetryDelayInMs(e)}catch(e){c.warn("encountered error in reconnect policy",{error:e})}return null}restartConnection(t){var i,n,r;return Qt(this,void 0,void 0,(function*(){try{if(!this.url||!this.token)throw new sr("could not reconnect, url or token not saved");let n;c.info("reconnecting, attempt: ".concat(this.reconnectAttempts)),this.emit(e.EngineEvent.Restarting),this.client.isConnected&&(yield this.client.sendLeave()),yield this.cleanupPeerConnections(),yield this.cleanupClient();try{if(!this.signalOpts)throw c.warn("attempted connection restart, without signal options present"),new ho;n=yield this.join(null!=t?t:this.url,this.token,this.signalOpts)}catch(e){if(e instanceof tr&&0===e.reason)throw new sr("could not reconnect, token might be expired");throw new ho}if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");this.client.setReconnected(),this.emit(e.EngineEvent.SignalRestarted,n),yield this.waitForPCReconnected(),null===(i=this.regionUrlProvider)||void 0===i||i.resetAttempts(),this.emit(e.EngineEvent.Restarted)}catch(e){const t=yield null===(n=this.regionUrlProvider)||void 0===n?void 0:n.getNextBestRegionUrl();if(t)return void(yield this.restartConnection(t));throw null===(r=this.regionUrlProvider)||void 0===r||r.resetAttempts(),e}}))}resumeConnection(t){var i;return Qt(this,void 0,void 0,(function*(){if(!this.url||!this.token)throw new sr("could not reconnect, url or token not saved");if(!this.publisher||!this.subscriber)throw new sr("publisher and subscriber connections unset");c.info("resuming signal connection, attempt ".concat(this.reconnectAttempts)),this.emit(e.EngineEvent.Resuming);try{this.setupSignalClientCallbacks();const e=yield this.client.reconnect(this.url,this.token,this.participantSid,t);if(e){const t=this.makeRTCConfiguration(e);this.publisher.pc.setConfiguration(t),this.subscriber.pc.setConfiguration(t)}}catch(e){let t="";if(e instanceof Error&&(t=e.message),e instanceof tr&&0===e.reason)throw new sr("could not reconnect, token might be expired");throw new ho(t)}if(this.emit(e.EngineEvent.SignalResumed),this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");this.subscriber.restartingIce=!0,this.hasPublished&&(yield this.publisher.createAndSendOffer({iceRestart:!0})),yield this.waitForPCReconnected(),this.client.setReconnected(),"open"===(null===(i=this.reliableDC)||void 0===i?void 0:i.readyState)&&null===this.reliableDC.id&&this.createDataChannels(),this.emit(e.EngineEvent.Resumed)}))}waitForPCInitialConnection(t,i){return Qt(this,void 0,void 0,(function*(){if(this.pcState!==uo.Connected){if(this.pcState!==uo.New)throw new sr("Expected peer connection to be new on initial connection");return new Promise(((n,r)=>{const s=()=>{c.warn("closing engine"),ar.clearTimeout(a),r(new tr("room connection has been cancelled",3))};(null==i?void 0:i.signal.aborted)&&s(),null==i||i.signal.addEventListener("abort",s);const o=()=>{ar.clearTimeout(a),null==i||i.signal.removeEventListener("abort",s),n()},a=ar.setTimeout((()=>{this.off(e.EngineEvent.Connected,o),r(new tr("could not establish pc connection"))}),null!=t?t:this.peerConnectionTimeout);this.once(e.EngineEvent.Connected,o)}))}}))}waitForPCReconnected(){var e;return Qt(this,void 0,void 0,(function*(){const t=Date.now();let i=t;for(this.pcState=uo.Reconnecting,c.debug("waiting for peer connection to reconnect");i-t<this.peerConnectionTimeout&&void 0!==this.primaryPC;){if(i-t>2e3&&"connected"===(null===(e=this.primaryPC)||void 0===e?void 0:e.connectionState)&&(this.pcState=uo.Connected),this.pcState===uo.Connected)return;yield _r(100),i=Date.now()}throw new tr("could not establish PC connection")}))}sendDataPacket(e,t){return Qt(this,void 0,void 0,(function*(){const i=It.encode(e).finish();yield this.ensurePublisherConnected(t);const n=this.dataChannelForKind(t);n&&n.send(i),this.updateAndEmitDCBufferStatus(t)}))}ensureDataTransportConnected(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.subscriberPrimary;var i,n,r;return Qt(this,void 0,void 0,(function*(){const s=t?this.subscriber:this.publisher,o=t?"Subscriber":"Publisher";if(!s)throw new tr("".concat(o," connection not set"));t||(null===(i=this.publisher)||void 0===i?void 0:i.isICEConnected)||"checking"===(null===(n=this.publisher)||void 0===n?void 0:n.pc.iceConnectionState)||this.negotiate();const a=this.dataChannelForKind(e,t);if("open"===(null==a?void 0:a.readyState))return;const c=(new Date).getTime()+this.peerConnectionTimeout;for(;(new Date).getTime()<c;){if(s.isICEConnected&&"open"===(null===(r=this.dataChannelForKind(e,t))||void 0===r?void 0:r.readyState))return;yield _r(50)}throw new tr("could not establish ".concat(o," connection, state: ").concat(s.pc.iceConnectionState))}))}ensurePublisherConnected(e){return Qt(this,void 0,void 0,(function*(){yield this.ensureDataTransportConnected(e,!1)}))}verifyTransport(){if(!this.primaryPC)return!1;if("closed"===this.primaryPC.connectionState||"failed"===this.primaryPC.connectionState)return!1;if(this.hasPublished&&this.subscriberPrimary){if(!this.publisher)return!1;if("closed"===this.publisher.pc.connectionState||"failed"===this.publisher.pc.connectionState)return!1}return!(!this.client.ws||this.client.ws.readyState===WebSocket.CLOSED)}negotiate(){return new Promise(((t,i)=>{if(!this.publisher)return void i(new or("publisher is not defined"));this.hasPublished=!0;const n=()=>{c.warn("engine disconnected while negotiation was ongoing"),s(),t()};this.isClosed&&i("cannot negotiate on closed engine"),this.on(e.EngineEvent.Closing,n);const r=setTimeout((()=>{i("negotiation timed out"),this.handleDisconnect("negotiation",Ye.RR_SIGNAL_DISCONNECTED)}),this.peerConnectionTimeout),s=()=>{clearTimeout(r),this.off(e.EngineEvent.Closing,n)};this.publisher.once(Hs,(()=>{var e;null===(e=this.publisher)||void 0===e||e.once(Zs,(()=>{s(),t()}))})),this.publisher.once(zs,(t=>{const i=new Map;t.forEach((e=>{const t=e.codec.toLowerCase();var n;n=t,vr.includes(n)&&i.set(e.payload,t)})),this.emit(e.EngineEvent.RTPVideoMapUpdate,i)})),this.publisher.negotiate((e=>{s(),i(e),e instanceof or&&(this.fullReconnectOnNext=!0),this.handleDisconnect("negotiation",Ye.RR_UNKNOWN)}))}))}dataChannelForKind(t,i){if(i){if(t===e.DataPacket_Kind.LOSSY)return this.lossyDCSub;if(t===e.DataPacket_Kind.RELIABLE)return this.reliableDCSub}else{if(t===e.DataPacket_Kind.LOSSY)return this.lossyDC;if(t===e.DataPacket_Kind.RELIABLE)return this.reliableDC}}failNext(){this.shouldFailNext=!0}clearReconnectTimeout(){this.reconnectTimeout&&ar.clearTimeout(this.reconnectTimeout)}clearPendingReconnect(){this.clearReconnectTimeout(),this.reconnectAttempts=0}registerOnLineListener(){Kr()&&window.addEventListener("online",this.handleBrowserOnLine)}deregisterOnLineListener(){Kr()&&window.removeEventListener("online",this.handleBrowserOnLine)}}class ho extends Error{}const po=2e3;function mo(e,t){if(!t)return 0;let i,n;return"bytesReceived"in e?(i=e.bytesReceived,n=t.bytesReceived):"bytesSent"in e&&(i=e.bytesSent,n=t.bytesSent),void 0===i||void 0===n||void 0===e.timestamp||void 0===t.timestamp?0:8*(i-n)*1e3/(e.timestamp-t.timestamp)}class fo extends As{constructor(e,t){let i=!(arguments.length>2&&void 0!==arguments[2])||arguments[2];super(e,Nr.Kind.Audio,t,i),this.stopOnMute=!1,this.monitorSender=()=>Qt(this,void 0,void 0,(function*(){if(!this.sender)return void(this._currentBitrate=0);let e;try{e=yield this.getSenderStats()}catch(e){return void c.error("could not get audio sender stats",{error:e})}e&&this.prevStats&&(this._currentBitrate=mo(e,this.prevStats)),this.prevStats=e})),this.checkForSilence()}setDeviceId(e){return Qt(this,void 0,void 0,(function*(){return this._constraints.deviceId===e||(this._constraints.deviceId=e,this.isMuted||(yield this.restartTrack()),this.isMuted||hs(e)===this.mediaStreamTrack.getSettings().deviceId)}))}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return Qt(this,void 0,void 0,(function*(){const t=yield this.muteLock.lock();try{return this.source===Nr.Source.Microphone&&this.stopOnMute&&!this.isUserProvided&&(c.debug("stopping mic track"),this._mediaStreamTrack.stop()),yield e.mute.call(this),this}finally{t()}}))}unmute(){const e=Object.create(null,{unmute:{get:()=>super.unmute}});return Qt(this,void 0,void 0,(function*(){const t=yield this.muteLock.lock();try{const t=this._constraints.deviceId&&this._mediaStreamTrack.getSettings().deviceId!==hs(this._constraints.deviceId);return this.source!==Nr.Source.Microphone||!this.stopOnMute&&"ended"!==this._mediaStreamTrack.readyState&&!t||this.isUserProvided||(c.debug("reacquiring mic track"),yield this.restartTrack()),yield e.unmute.call(this),this}finally{t()}}))}restartTrack(e){return Qt(this,void 0,void 0,(function*(){let t;if(e){const i=Ur({audio:e});"boolean"!=typeof i.audio&&(t=i.audio)}yield this.restart(t)}))}restart(e){const t=Object.create(null,{restart:{get:()=>super.restart}});return Qt(this,void 0,void 0,(function*(){const i=yield t.restart.call(this,e);return this.checkForSilence(),i}))}startMonitor(){Kr()&&(this.monitorInterval||(this.monitorInterval=setInterval((()=>{this.monitorSender()}),po)))}getSenderStats(){var e;return Qt(this,void 0,void 0,(function*(){if(!(null===(e=this.sender)||void 0===e?void 0:e.getStats))return;let t;return(yield this.sender.getStats()).forEach((e=>{"outbound-rtp"===e.type&&(t={type:"audio",streamId:e.id,packetsSent:e.packetsSent,packetsLost:e.packetsLost,bytesSent:e.bytesSent,timestamp:e.timestamp,roundTripTime:e.roundTripTime,jitter:e.jitter})})),t}))}checkForSilence(){return Qt(this,void 0,void 0,(function*(){const t=yield function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:200;return Qt(this,void 0,void 0,(function*(){const i=Mr();if(i){const n=i.createAnalyser();n.fftSize=2048;const r=n.frequencyBinCount,s=new Uint8Array(r);i.createMediaStreamSource(new MediaStream([e.mediaStreamTrack])).connect(n),yield _r(t),n.getByteTimeDomainData(s);const o=s.some((e=>128!==e&&0!==e));return i.close(),!o}return!1}))}(this);return t&&(this.isMuted||c.warn("silence detected on local audio track"),this.emit(e.TrackEvent.AudioSilenceDetected)),t}))}}function vo(e,t){switch(e.kind){case"audio":return new fo(e,t,!1);case"video":return new Io(e,t,!1);default:throw new nr("unsupported track type: ".concat(e.kind))}}const go=Object.values(yr),bo=Object.values(Sr),ko=Object.values(Cr),yo=[yr.h180,yr.h360],So=[Sr.h180,Sr.h360],Co=e=>[{scaleResolutionDownBy:2,fps:3}].map((t=>{var i;return new mr(Math.floor(e.width/t.scaleResolutionDownBy),Math.floor(e.height/t.scaleResolutionDownBy),Math.max(15e4,Math.floor(e.encoding.maxBitrate/(Math.pow(t.scaleResolutionDownBy,2)*((null!==(i=e.encoding.maxFramerate)&&void 0!==i?i:30)/t.fps)))),t.fps,e.encoding.priority)})),Eo=["q","h","f"];function To(e,t,i,n){var r,s;let o=null==n?void 0:n.videoEncoding;e&&(o=null==n?void 0:n.screenShareEncoding);const a=null==n?void 0:n.simulcast,d=null==n?void 0:n.scalabilityMode,u=null==n?void 0:n.videoCodec;if(!o&&!a&&!d||!t||!i)return[{}];o||(o=function(e,t,i,n){const r=function(e,t,i){if(e)return ko;const n=t>i?t/i:i/t;if(Math.abs(n-16/9)<Math.abs(n-4/3))return go;return bo}(e,t,i);let{encoding:s}=r[0];const o=Math.max(t,i);for(let e=0;e<r.length;e+=1){const t=r[e];if(s=t.encoding,t.width>=o)break}if(n)switch(n){case"av1":s=Object.assign({},s),s.maxBitrate=.7*s.maxBitrate;break;case"vp9":s=Object.assign({},s),s.maxBitrate=.85*s.maxBitrate}return s}(e,t,i,u),c.debug("using video encoding",o));const l=new mr(t,i,o.maxBitrate,o.maxFramerate,o.priority);if(d&&$r(u)){c.debug("using svc with scalabilityMode ".concat(d));const e=new Oo(d),t=[];if(e.spatial>3)throw new Error("unsupported scalabilityMode: ".concat(d));for(let i=0;i<e.spatial;i+=1)t.push({rid:Eo[2-i],maxBitrate:o.maxBitrate/Math.pow(3,i),maxFramerate:l.encoding.maxFramerate});return t[0].scalabilityMode=d,c.debug("encodings",t),t}if(!a)return[o];let h,p=[];if(p=e?null!==(r=No(null==n?void 0:n.screenShareSimulcastLayers))&&void 0!==r?r:wo(e,l):null!==(s=No(null==n?void 0:n.videoSimulcastLayers))&&void 0!==s?s:wo(e,l),p.length>0){const e=p[0];p.length>1&&([,h]=p);const n=Math.max(t,i);if(n>=960&&h)return Ro(t,i,[e,h,l]);if(n>=480)return Ro(t,i,[e,l])}return Ro(t,i,[l])}function Po(e,t,i){var n,r,s,o;if(!i.backupCodec||i.backupCodec.codec===i.videoCodec)return;t!==i.backupCodec.codec&&c.warn("requested a different codec than specified as backup",{serverRequested:t,backup:i.backupCodec.codec}),i.videoCodec=t,i.videoEncoding=i.backupCodec.encoding;const a=e.mediaStreamTrack.getSettings(),d=null!==(n=a.width)&&void 0!==n?n:null===(r=e.dimensions)||void 0===r?void 0:r.width,u=null!==(s=a.height)&&void 0!==s?s:null===(o=e.dimensions)||void 0===o?void 0:o.height;return To(e.source===Nr.Source.ScreenShare,d,u,i)}function wo(e,t){if(e)return Co(t);const{width:i,height:n}=t,r=i>n?i/n:n/i;return Math.abs(r-16/9)<Math.abs(r-4/3)?yo:So}function Ro(e,t,i){const n=[];if(i.forEach(((i,r)=>{if(r>=Eo.length)return;const s=Math.min(e,t),o={rid:Eo[r],scaleResolutionDownBy:Math.max(1,s/Math.min(i.width,i.height)),maxBitrate:i.encoding.maxBitrate};i.encoding.maxFramerate&&(o.maxFramerate=i.encoding.maxFramerate);const a=qr()||0===r;i.encoding.priority&&a&&(o.priority=i.encoding.priority,o.networkPriority=i.encoding.priority),n.push(o)})),Qr()&&"ios"===zr()){let e;n.forEach((t=>{e?t.maxFramerate&&t.maxFramerate>e&&(e=t.maxFramerate):e=t.maxFramerate}));let t=!0;n.forEach((i=>{var n;i.maxFramerate!=e&&(t&&(t=!1,c.info("Simulcast on iOS React-Native requires all encodings to share the same framerate.")),c.info('Setting framerate of encoding "'.concat(null!==(n=i.rid)&&void 0!==n?n:"",'" to ').concat(e)),i.maxFramerate=e)}))}return n}function No(e){if(e)return e.sort(((e,t)=>{const{encoding:i}=e,{encoding:n}=t;return i.maxBitrate>n.maxBitrate?1:i.maxBitrate<n.maxBitrate?-1:i.maxBitrate===n.maxBitrate&&i.maxFramerate&&n.maxFramerate?i.maxFramerate>n.maxFramerate?1:-1:0}))}class Oo{constructor(e){const t=e.match(/^L(\d)T(\d)(h|_KEY|_KEY_SHIFT){0,1}$/);if(!t)throw new Error("invalid scalability mode");if(this.spatial=parseInt(t[1]),this.temporal=parseInt(t[2]),t.length>3)switch(t[3]){case"h":case"_KEY":case"_KEY_SHIFT":this.suffix=t[3]}}toString(){var e;return"L".concat(this.spatial,"T").concat(this.temporal).concat(null!==(e=this.suffix)&&void 0!==e?e:"")}}class Io extends As{constructor(e,t){let i=!(arguments.length>2&&void 0!==arguments[2])||arguments[2];super(e,Nr.Kind.Video,t,i),this.simulcastCodecs=new Map,this.monitorSender=()=>Qt(this,void 0,void 0,(function*(){if(!this.sender)return void(this._currentBitrate=0);let e;try{e=yield this.getSenderStats()}catch(e){return void c.error("could not get audio sender stats",{error:e})}const t=new Map(e.map((e=>[e.rid,e])));if(this.prevStats){let e=0;t.forEach(((t,i)=>{var n;const r=null===(n=this.prevStats)||void 0===n?void 0:n.get(i);e+=mo(t,r)})),this._currentBitrate=e}this.prevStats=t})),this.senderLock=new ls}get isSimulcast(){return!!(this.sender&&this.sender.getParameters().encodings.length>1)}startMonitor(e){var t;if(this.signalClient=e,!Kr())return;const i=null===(t=this.sender)||void 0===t?void 0:t.getParameters();i&&(this.encodings=i.encodings),this.monitorInterval||(this.monitorInterval=setInterval((()=>{this.monitorSender()}),po))}stop(){this._mediaStreamTrack.getConstraints(),this.simulcastCodecs.forEach((e=>{e.mediaStreamTrack.stop()})),super.stop()}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return Qt(this,void 0,void 0,(function*(){const t=yield this.muteLock.lock();try{return this.source!==Nr.Source.Camera||this.isUserProvided||(c.debug("stopping camera track"),this._mediaStreamTrack.stop()),yield e.mute.call(this),this}finally{t()}}))}unmute(){const e=Object.create(null,{unmute:{get:()=>super.unmute}});return Qt(this,void 0,void 0,(function*(){const t=yield this.muteLock.lock();try{return this.source!==Nr.Source.Camera||this.isUserProvided||(c.debug("reacquiring camera track"),yield this.restartTrack()),yield e.unmute.call(this),this}finally{t()}}))}getSenderStats(){var e;return Qt(this,void 0,void 0,(function*(){if(!(null===(e=this.sender)||void 0===e?void 0:e.getStats))return[];const t=[],i=yield this.sender.getStats();return i.forEach((e=>{var n;if("outbound-rtp"===e.type){const r={type:"video",streamId:e.id,frameHeight:e.frameHeight,frameWidth:e.frameWidth,firCount:e.firCount,pliCount:e.pliCount,nackCount:e.nackCount,packetsSent:e.packetsSent,bytesSent:e.bytesSent,framesSent:e.framesSent,timestamp:e.timestamp,rid:null!==(n=e.rid)&&void 0!==n?n:e.id,retransmittedPacketsSent:e.retransmittedPacketsSent,qualityLimitationReason:e.qualityLimitationReason,qualityLimitationResolutionChanges:e.qualityLimitationResolutionChanges},s=i.get(e.remoteId);s&&(r.jitter=s.jitter,r.packetsLost=s.packetsLost,r.roundTripTime=s.roundTripTime),t.push(r)}})),t}))}setPublishingQuality(t){const i=[];for(let n=e.VideoQuality.LOW;n<=e.VideoQuality.HIGH;n+=1)i.push({quality:n,enabled:n<=t});c.debug("setting publishing quality. max quality ".concat(t)),this.setPublishingLayers(i)}setDeviceId(e){return Qt(this,void 0,void 0,(function*(){return this._constraints.deviceId===e&&this._mediaStreamTrack.getSettings().deviceId===hs(e)||(this._constraints.deviceId=e,this.isMuted||(yield this.restartTrack()),this.isMuted||hs(e)===this._mediaStreamTrack.getSettings().deviceId)}))}restartTrack(e){return Qt(this,void 0,void 0,(function*(){let t;if(e){const i=Ur({video:e});"boolean"!=typeof i.video&&(t=i.video)}yield this.restart(t)}))}addSimulcastTrack(e,t){if(this.simulcastCodecs.has(e))throw new Error("".concat(e," already added"));const i={codec:e,mediaStreamTrack:this.mediaStreamTrack.clone(),sender:void 0,encodings:t};return this.simulcastCodecs.set(e,i),i}setSimulcastTrackSender(e,t){const i=this.simulcastCodecs.get(e);i&&(i.sender=t,setTimeout((()=>{this.subscribedCodecs&&this.setPublishingCodecs(this.subscribedCodecs)}),5e3))}setPublishingCodecs(e){var t,i,n,r,s,o,a;return Qt(this,void 0,void 0,(function*(){if(c.debug("setting publishing codecs",{codecs:e,currentCodec:this.codec}),!this.codec&&e.length>0)return yield this.setPublishingLayers(e[0].qualities),[];this.subscribedCodecs=e;const d=[];try{for(t=!0,i=Zt(e);n=yield i.next(),!(r=n.done);t=!0){a=n.value,t=!1;const e=a;if(this.codec&&this.codec!==e.codec){const t=this.simulcastCodecs.get(e.codec);if(c.debug("try setPublishingCodec for ".concat(e.codec),t),t&&t.sender)t.encodings&&(c.debug("try setPublishingLayersForSender ".concat(e.codec)),yield Do(t.sender,t.encodings,e.qualities,this.senderLock));else for(const t of e.qualities)if(t.enabled){d.push(e.codec);break}}else yield this.setPublishingLayers(e.qualities)}}catch(e){s={error:e}}finally{try{t||r||!(o=i.return)||(yield o.call(i))}finally{if(s)throw s.error}}return d}))}setPublishingLayers(e){return Qt(this,void 0,void 0,(function*(){c.debug("setting publishing layers",e),this.sender&&this.encodings&&(yield Do(this.sender,this.encodings,e,this.senderLock))}))}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return Qt(this,void 0,void 0,(function*(){yield e.handleAppVisibilityChanged.call(this),Gr()&&this.isInBackground&&this.source===Nr.Source.Camera&&(this._mediaStreamTrack.enabled=!1)}))}}function Do(e,t,i,n){return Qt(this,void 0,void 0,(function*(){const r=yield n.lock();c.debug("setPublishingLayersForSender",{sender:e,qualities:i,senderEncodings:t});try{const n=e.getParameters(),{encodings:r}=n;if(!r)return;if(r.length!==t.length)return void c.warn("cannot set publishing layers, encodings mismatch");let s=!1;!1&&r[0].scalabilityMode||r.forEach(((e,n)=>{var r;let o=null!==(r=e.rid)&&void 0!==r?r:"";""===o&&(o="q");const a=Ao(o),d=i.find((e=>e.quality===a));d&&e.active!==d.enabled&&(s=!0,e.active=d.enabled,c.debug("setting layer ".concat(d.quality," to ").concat(e.active?"enabled":"disabled")),qr()&&(d.enabled?(e.scaleResolutionDownBy=t[n].scaleResolutionDownBy,e.maxBitrate=t[n].maxBitrate,e.maxFrameRate=t[n].maxFrameRate):(e.scaleResolutionDownBy=4,e.maxBitrate=10,e.maxFrameRate=2)))})),s&&(n.encodings=r,c.debug("setting encodings",n.encodings),yield e.setParameters(n))}finally{r()}}))}function Ao(t){switch(t){case"f":return e.VideoQuality.HIGH;case"h":return e.VideoQuality.MEDIUM;case"q":return e.VideoQuality.LOW;default:return e.VideoQuality.UNRECOGNIZED}}function Uo(t,i,n,r){if(!n)return[{quality:e.VideoQuality.HIGH,width:t,height:i,bitrate:0,ssrc:0}];if(r){const r=new Oo(n[0].scalabilityMode),s=[];for(let o=0;o<r.spatial;o+=1)s.push({quality:e.VideoQuality.HIGH-o,width:t/Math.pow(2,o),height:i/Math.pow(2,o),bitrate:n[0].maxBitrate?n[0].maxBitrate/Math.pow(3,o):0,ssrc:0});return s}return n.map((r=>{var s,o,a;const c=null!==(s=r.scaleResolutionDownBy)&&void 0!==s?s:1;let d=Ao(null!==(o=r.rid)&&void 0!==o?o:"");return d===e.VideoQuality.UNRECOGNIZED&&1===n.length&&(d=e.VideoQuality.HIGH),{quality:d,width:t/c,height:i/c,bitrate:null!==(a=r.maxBitrate)&&void 0!==a?a:0,ssrc:0}}))}class Mo extends Nr{constructor(e,t,i,n){super(e,i),this.sid=t,this.receiver=n}setMuted(t){this.isMuted!==t&&(this.isMuted=t,this._mediaStreamTrack.enabled=!t,this.emit(t?e.TrackEvent.Muted:e.TrackEvent.Unmuted,this))}setMediaStream(t){this.mediaStream=t,t.onremovetrack=()=>{this.receiver=void 0,this._currentBitrate=0,this.emit(e.TrackEvent.Ended,this)}}start(){this.startMonitor(),super.enable()}stop(){this.stopMonitor(),super.disable()}startMonitor(){this.monitorInterval||(this.monitorInterval=setInterval((()=>this.monitorReceiver()),po))}}class Lo extends Mo{constructor(e,t,i,n,r){super(e,t,Nr.Kind.Audio,i),this.monitorReceiver=()=>Qt(this,void 0,void 0,(function*(){if(!this.receiver)return void(this._currentBitrate=0);const e=yield this.getReceiverStats();e&&this.prevStats&&this.receiver&&(this._currentBitrate=mo(e,this.prevStats)),this.prevStats=e})),this.audioContext=n,this.webAudioPluginNodes=[],r&&(this.sinkId=r.deviceId)}setVolume(e){var t;for(const i of this.attachedElements)this.audioContext?null===(t=this.gainNode)||void 0===t||t.gain.setTargetAtTime(e,0,.1):i.volume=e;this.elementVolume=e}getVolume(){if(this.elementVolume)return this.elementVolume;let e=0;return this.attachedElements.forEach((t=>{t.volume>e&&(e=t.volume)})),e}setSinkId(e){return Qt(this,void 0,void 0,(function*(){this.sinkId=e,yield Promise.all(this.attachedElements.map((t=>{if(Vr(t))return t.setSinkId(e)})))}))}attach(e){const t=0===this.attachedElements.length;return e?super.attach(e):e=super.attach(),this.elementVolume&&(e.volume=this.elementVolume),this.sinkId&&Vr(e)&&e.setSinkId(this.sinkId),this.audioContext&&t&&(c.debug("using audio context mapping"),this.connectWebAudio(this.audioContext,e),e.volume=0,e.muted=!0),e}detach(e){let t;return e?(t=super.detach(e),this.audioContext&&(this.attachedElements.length>0?this.connectWebAudio(this.audioContext,this.attachedElements[0]):this.disconnectWebAudio())):(t=super.detach(),this.disconnectWebAudio()),t}setAudioContext(e){this.audioContext=e,e&&this.attachedElements.length>0?this.connectWebAudio(e,this.attachedElements[0]):e||this.disconnectWebAudio()}setWebAudioPlugins(e){this.webAudioPluginNodes=e,this.attachedElements.length>0&&this.audioContext&&this.connectWebAudio(this.audioContext,this.attachedElements[0])}connectWebAudio(t,i){this.disconnectWebAudio(),this.sourceNode=t.createMediaStreamSource(i.srcObject);let n=this.sourceNode;this.webAudioPluginNodes.forEach((e=>{n.connect(e),n=e})),this.gainNode=t.createGain(),n.connect(this.gainNode),this.gainNode.connect(t.destination),this.elementVolume&&this.gainNode.gain.setTargetAtTime(this.elementVolume,0,.1),"running"!==t.state&&t.resume().then((()=>{"running"!==t.state&&this.emit(e.TrackEvent.AudioPlaybackFailed,new Error("Audio Context couldn't be started automatically"))})).catch((t=>{this.emit(e.TrackEvent.AudioPlaybackFailed,t)}))}disconnectWebAudio(){var e,t;null===(e=this.gainNode)||void 0===e||e.disconnect(),null===(t=this.sourceNode)||void 0===t||t.disconnect(),this.gainNode=void 0,this.sourceNode=void 0}getReceiverStats(){return Qt(this,void 0,void 0,(function*(){if(!this.receiver||!this.receiver.getStats)return;let e;return(yield this.receiver.getStats()).forEach((t=>{"inbound-rtp"===t.type&&(e={type:"audio",timestamp:t.timestamp,jitter:t.jitter,bytesReceived:t.bytesReceived,concealedSamples:t.concealedSamples,concealmentEvents:t.concealmentEvents,silentConcealedSamples:t.silentConcealedSamples,silentConcealmentEvents:t.silentConcealmentEvents,totalAudioEnergy:t.totalAudioEnergy,totalSamplesDuration:t.totalSamplesDuration})})),e}))}}class _o extends Mo{constructor(e,t,i,n){super(e,t,Nr.Kind.Video,i),this.elementInfos=[],this.monitorReceiver=()=>Qt(this,void 0,void 0,(function*(){if(!this.receiver)return void(this._currentBitrate=0);const e=yield this.getReceiverStats();e&&this.prevStats&&this.receiver&&(this._currentBitrate=mo(e,this.prevStats)),this.prevStats=e})),this.debouncedHandleResize=Qs((()=>{this.updateDimensions()}),100),this.adaptiveStreamSettings=n}get isAdaptiveStream(){return void 0!==this.adaptiveStreamSettings}get mediaStreamTrack(){return this._mediaStreamTrack}setMuted(e){super.setMuted(e),this.attachedElements.forEach((t=>{e?Ir(this._mediaStreamTrack,t):Or(this._mediaStreamTrack,t)}))}attach(e){if(e?super.attach(e):e=super.attach(),this.adaptiveStreamSettings&&void 0===this.elementInfos.find((t=>t.element===e))){const t=new xo(e);this.observeElementInfo(t)}return e}observeElementInfo(e){this.adaptiveStreamSettings&&void 0===this.elementInfos.find((t=>t===e))?(e.handleResize=()=>{this.debouncedHandleResize()},e.handleVisibilityChanged=()=>{this.updateVisibility()},this.elementInfos.push(e),e.observe(),this.debouncedHandleResize(),this.updateVisibility()):c.warn("visibility resize observer not triggered")}stopObservingElementInfo(e){if(!this.isAdaptiveStream)return void c.warn("stopObservingElementInfo ignored");const t=this.elementInfos.filter((t=>t===e));for(const e of t)e.stopObserving();this.elementInfos=this.elementInfos.filter((t=>t!==e)),this.updateVisibility(),this.debouncedHandleResize()}detach(e){let t=[];if(e)return this.stopObservingElement(e),super.detach(e);t=super.detach();for(const e of t)this.stopObservingElement(e);return t}getDecoderImplementation(){var e;return null===(e=this.prevStats)||void 0===e?void 0:e.decoderImplementation}getReceiverStats(){return Qt(this,void 0,void 0,(function*(){if(!this.receiver||!this.receiver.getStats)return;let e;return(yield this.receiver.getStats()).forEach((t=>{"inbound-rtp"===t.type&&(e={type:"video",framesDecoded:t.framesDecoded,framesDropped:t.framesDropped,framesReceived:t.framesReceived,packetsReceived:t.packetsReceived,packetsLost:t.packetsLost,frameWidth:t.frameWidth,frameHeight:t.frameHeight,pliCount:t.pliCount,firCount:t.firCount,nackCount:t.nackCount,jitter:t.jitter,timestamp:t.timestamp,bytesReceived:t.bytesReceived,decoderImplementation:t.decoderImplementation})})),e}))}stopObservingElement(e){const t=this.elementInfos.filter((t=>t.element===e));for(const e of t)this.stopObservingElementInfo(e)}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return Qt(this,void 0,void 0,(function*(){yield e.handleAppVisibilityChanged.call(this),this.isAdaptiveStream&&this.updateVisibility()}))}updateVisibility(){var t,i;const n=this.elementInfos.reduce(((e,t)=>Math.max(e,t.visibilityChangedAt||0)),0),r=!(null!==(i=null===(t=this.adaptiveStreamSettings)||void 0===t?void 0:t.pauseVideoInBackground)&&void 0!==i&&!i)&&this.isInBackground,s=this.elementInfos.some((e=>e.pictureInPicture)),o=this.elementInfos.some((e=>e.visible))&&!r||s;this.lastVisible!==o&&(!o&&Date.now()-n<100?ar.setTimeout((()=>{this.updateVisibility()}),100):(this.lastVisible=o,this.emit(e.TrackEvent.VisibilityChanged,o,this)))}updateDimensions(){var t,i;let n=0,r=0;const s=this.getPixelDensity();for(const e of this.elementInfos){const t=e.width()*s,i=e.height()*s;t+i>n+r&&(n=t,r=i)}(null===(t=this.lastDimensions)||void 0===t?void 0:t.width)===n&&(null===(i=this.lastDimensions)||void 0===i?void 0:i.height)===r||(this.lastDimensions={width:n,height:r},this.emit(e.TrackEvent.VideoDimensionsChanged,this.lastDimensions,this))}getPixelDensity(){var e;const t=null===(e=this.adaptiveStreamSettings)||void 0===e?void 0:e.pixelDensity;if("screen"===t)return Yr();if(!t){return Yr()>2?2:1}return t}}class xo{get visible(){return this.isPiP||this.isIntersecting}get pictureInPicture(){return this.isPiP}constructor(e,t){this.onVisibilityChanged=e=>{var t;const{target:i,isIntersecting:n}=e;i===this.element&&(this.isIntersecting=n,this.visibilityChangedAt=Date.now(),null===(t=this.handleVisibilityChanged)||void 0===t||t.call(this))},this.onEnterPiP=()=>{var e;this.isPiP=!0,null===(e=this.handleVisibilityChanged)||void 0===e||e.call(this)},this.onLeavePiP=()=>{var e;this.isPiP=!1,null===(e=this.handleVisibilityChanged)||void 0===e||e.call(this)},this.element=e,this.isIntersecting=null!=t?t:Bo(e),this.isPiP=Kr()&&document.pictureInPictureElement===e,this.visibilityChangedAt=0}width(){return this.element.clientWidth}height(){return this.element.clientHeight}observe(){this.isIntersecting=Bo(this.element),this.isPiP=document.pictureInPictureElement===this.element,this.element.handleResize=()=>{var e;null===(e=this.handleResize)||void 0===e||e.call(this)},this.element.handleVisibilityChanged=this.onVisibilityChanged,ss().observe(this.element),ns().observe(this.element),this.element.addEventListener("enterpictureinpicture",this.onEnterPiP),this.element.addEventListener("leavepictureinpicture",this.onLeavePiP)}stopObserving(){var e,t;null===(e=ss())||void 0===e||e.unobserve(this.element),null===(t=ns())||void 0===t||t.unobserve(this.element),this.element.removeEventListener("enterpictureinpicture",this.onEnterPiP),this.element.removeEventListener("leavepictureinpicture",this.onLeavePiP)}}function Bo(e){let t=e.offsetTop,i=e.offsetLeft;const n=e.offsetWidth,r=e.offsetHeight,{hidden:s}=e,{opacity:o,display:a}=getComputedStyle(e);for(;e.offsetParent;)t+=(e=e.offsetParent).offsetTop,i+=e.offsetLeft;return t<window.pageYOffset+window.innerHeight&&i<window.pageXOffset+window.innerWidth&&t+r>window.pageYOffset&&i+n>window.pageXOffset&&!s&&(""===o||parseFloat(o)>0)&&"none"!==a}class Jo extends Yt{constructor(t,i,n){super(),this.metadataMuted=!1,this.encryption=tt.NONE,this.handleMuted=()=>{this.emit(e.TrackEvent.Muted)},this.handleUnmuted=()=>{this.emit(e.TrackEvent.Unmuted)},this.kind=t,this.trackSid=i,this.trackName=n,this.source=Nr.Source.Unknown}setTrack(t){this.track&&(this.track.off(e.TrackEvent.Muted,this.handleMuted),this.track.off(e.TrackEvent.Unmuted,this.handleUnmuted)),this.track=t,t&&(t.on(e.TrackEvent.Muted,this.handleMuted),t.on(e.TrackEvent.Unmuted,this.handleUnmuted))}get isMuted(){return this.metadataMuted}get isEnabled(){return!0}get isSubscribed(){return void 0!==this.track}get isEncrypted(){return this.encryption!==tt.NONE}get audioTrack(){if(this.track instanceof fo||this.track instanceof Lo)return this.track}get videoTrack(){if(this.track instanceof Io||this.track instanceof _o)return this.track}updateInfo(e){this.trackSid=e.sid,this.trackName=e.name,this.source=Nr.sourceFromProto(e.source),this.mimeType=e.mimeType,this.kind===Nr.Kind.Video&&e.width>0&&(this.dimensions={width:e.width,height:e.height},this.simulcasted=e.simulcast),this.encryption=e.encryption,this.trackInfo=e,c.debug("update publication info",{info:e})}}!function(e){var t,i;(t=e.SubscriptionStatus||(e.SubscriptionStatus={})).Desired="desired",t.Subscribed="subscribed",t.Unsubscribed="unsubscribed",(i=e.PermissionStatus||(e.PermissionStatus={})).Allowed="allowed",i.NotAllowed="not_allowed"}(Jo||(Jo={}));class Fo extends Jo{get isUpstreamPaused(){var e;return null===(e=this.track)||void 0===e?void 0:e.isUpstreamPaused}constructor(t,i,n){super(t,i.sid,i.name),this.track=void 0,this.handleTrackEnded=()=>{this.emit(e.TrackEvent.Ended)},this.updateInfo(i),this.setTrack(n)}setTrack(t){this.track&&this.track.off(e.TrackEvent.Ended,this.handleTrackEnded),super.setTrack(t),t&&t.on(e.TrackEvent.Ended,this.handleTrackEnded)}get isMuted(){return this.track?this.track.isMuted:super.isMuted}get audioTrack(){return super.audioTrack}get videoTrack(){return super.videoTrack}mute(){var e;return Qt(this,void 0,void 0,(function*(){return null===(e=this.track)||void 0===e?void 0:e.mute()}))}unmute(){var e;return Qt(this,void 0,void 0,(function*(){return null===(e=this.track)||void 0===e?void 0:e.unmute()}))}pauseUpstream(){var e;return Qt(this,void 0,void 0,(function*(){yield null===(e=this.track)||void 0===e?void 0:e.pauseUpstream()}))}resumeUpstream(){var e;return Qt(this,void 0,void 0,(function*(){yield null===(e=this.track)||void 0===e?void 0:e.resumeUpstream()}))}}e.ConnectionQuality=void 0,function(e){e.Excellent="excellent",e.Good="good",e.Poor="poor",e.Unknown="unknown"}(e.ConnectionQuality||(e.ConnectionQuality={}));class $o extends Yt{get isEncrypted(){return this.tracks.size>0&&Array.from(this.tracks.values()).every((e=>e.isEncrypted))}constructor(t,i,n,r){super(),this.audioLevel=0,this.isSpeaking=!1,this._connectionQuality=e.ConnectionQuality.Unknown,this.sid=t,this.identity=i,this.name=n,this.metadata=r,this.audioTracks=new Map,this.videoTracks=new Map,this.tracks=new Map}getTracks(){return Array.from(this.tracks.values())}getTrack(e){for(const[,t]of this.tracks)if(t.source===e)return t}getTrackByName(e){for(const[,t]of this.tracks)if(t.trackName===e)return t}get connectionQuality(){return this._connectionQuality}get isCameraEnabled(){var e;const t=this.getTrack(Nr.Source.Camera);return!(null===(e=null==t?void 0:t.isMuted)||void 0===e||e)}get isMicrophoneEnabled(){var e;const t=this.getTrack(Nr.Source.Microphone);return!(null===(e=null==t?void 0:t.isMuted)||void 0===e||e)}get isScreenShareEnabled(){return!!this.getTrack(Nr.Source.ScreenShare)}get isLocal(){return!1}get joinedAt(){return this.participantInfo?new Date(1e3*this.participantInfo.joinedAt):new Date}updateInfo(e){return!(this.participantInfo&&this.participantInfo.sid===e.sid&&this.participantInfo.version>e.version)&&(this.identity=e.identity,this.sid=e.sid,this.setName(e.name),this.setMetadata(e.metadata),e.permission&&this.setPermissions(e.permission),this.participantInfo=e,c.trace("update participant info",{info:e}),!0)}setMetadata(t){const i=this.metadata!==t,n=this.metadata;this.metadata=t,i&&this.emit(e.ParticipantEvent.ParticipantMetadataChanged,n)}setName(t){const i=this.name!==t;this.name=t,i&&this.emit(e.ParticipantEvent.ParticipantNameChanged,t)}setPermissions(t){var i,n,r,s,o;const a=this.permissions,c=t.canPublish!==(null===(i=this.permissions)||void 0===i?void 0:i.canPublish)||t.canSubscribe!==(null===(n=this.permissions)||void 0===n?void 0:n.canSubscribe)||t.canPublishData!==(null===(r=this.permissions)||void 0===r?void 0:r.canPublishData)||t.hidden!==(null===(s=this.permissions)||void 0===s?void 0:s.hidden)||t.recorder!==(null===(o=this.permissions)||void 0===o?void 0:o.recorder)||t.canPublishSources.length!==this.permissions.canPublishSources.length||t.canPublishSources.some(((e,t)=>{var i;return e!==(null===(i=this.permissions)||void 0===i?void 0:i.canPublishSources[t])}));return this.permissions=t,c&&this.emit(e.ParticipantEvent.ParticipantPermissionsChanged,a),c}setIsSpeaking(t){t!==this.isSpeaking&&(this.isSpeaking=t,t&&(this.lastSpokeAt=new Date),this.emit(e.ParticipantEvent.IsSpeakingChanged,t))}setConnectionQuality(t){const i=this._connectionQuality;this._connectionQuality=function(t){switch(t){case He.EXCELLENT:return e.ConnectionQuality.Excellent;case He.GOOD:return e.ConnectionQuality.Good;case He.POOR:return e.ConnectionQuality.Poor;default:return e.ConnectionQuality.Unknown}}(t),i!==this._connectionQuality&&this.emit(e.ParticipantEvent.ConnectionQualityChanged,this._connectionQuality)}addTrackPublication(t){t.on(e.TrackEvent.Muted,(()=>{this.emit(e.ParticipantEvent.TrackMuted,t)})),t.on(e.TrackEvent.Unmuted,(()=>{this.emit(e.ParticipantEvent.TrackUnmuted,t)}));const i=t;switch(i.track&&(i.track.sid=t.trackSid),this.tracks.set(t.trackSid,t),t.kind){case Nr.Kind.Audio:this.audioTracks.set(t.trackSid,t);break;case Nr.Kind.Video:this.videoTracks.set(t.trackSid,t)}}}class Vo extends Jo{constructor(t,i,n){super(t,i.sid,i.name),this.track=void 0,this.allowed=!0,this.disabled=!1,this.currentVideoQuality=e.VideoQuality.HIGH,this.handleEnded=t=>{this.setTrack(void 0),this.emit(e.TrackEvent.Ended,t)},this.handleVisibilityChange=e=>{c.debug("adaptivestream video visibility ".concat(this.trackSid,", visible=").concat(e),{trackSid:this.trackSid}),this.disabled=!e,this.emitTrackUpdate()},this.handleVideoDimensionsChange=e=>{c.debug("adaptivestream video dimensions ".concat(e.width,"x").concat(e.height),{trackSid:this.trackSid}),this.videoDimensions=e,this.emitTrackUpdate()},this.subscribed=n,this.updateInfo(i)}setSubscribed(t){const i=this.subscriptionStatus,n=this.permissionStatus;this.subscribed=t,t&&(this.allowed=!0);const r={trackSids:[this.trackSid],subscribe:this.subscribed,participantTracks:[{participantSid:"",trackSids:[this.trackSid]}]};this.emit(e.TrackEvent.UpdateSubscription,r),this.emitSubscriptionUpdateIfChanged(i),this.emitPermissionUpdateIfChanged(n)}get subscriptionStatus(){return!1===this.subscribed?Jo.SubscriptionStatus.Unsubscribed:super.isSubscribed?Jo.SubscriptionStatus.Subscribed:Jo.SubscriptionStatus.Desired}get permissionStatus(){return this.allowed?Jo.PermissionStatus.Allowed:Jo.PermissionStatus.NotAllowed}get isSubscribed(){return!1!==this.subscribed&&super.isSubscribed}get isDesired(){return!1!==this.subscribed}get isEnabled(){return!this.disabled}setEnabled(e){this.isManualOperationAllowed()&&this.disabled!==!e&&(this.disabled=!e,this.emitTrackUpdate())}setVideoQuality(e){this.isManualOperationAllowed()&&this.currentVideoQuality!==e&&(this.currentVideoQuality=e,this.videoDimensions=void 0,this.emitTrackUpdate())}setVideoDimensions(e){var t,i;this.isManualOperationAllowed()&&((null===(t=this.videoDimensions)||void 0===t?void 0:t.width)===e.width&&(null===(i=this.videoDimensions)||void 0===i?void 0:i.height)===e.height||(this.track instanceof _o&&(this.videoDimensions=e),this.currentVideoQuality=void 0,this.emitTrackUpdate()))}setVideoFPS(e){this.isManualOperationAllowed()&&this.track instanceof _o&&this.fps!==e&&(this.fps=e,this.emitTrackUpdate())}get videoQuality(){return this.currentVideoQuality}setTrack(t){const i=this.subscriptionStatus,n=this.permissionStatus,r=this.track;r!==t&&(r&&(r.off(e.TrackEvent.VideoDimensionsChanged,this.handleVideoDimensionsChange),r.off(e.TrackEvent.VisibilityChanged,this.handleVisibilityChange),r.off(e.TrackEvent.Ended,this.handleEnded),r.detach(),r.stopMonitor(),this.emit(e.TrackEvent.Unsubscribed,r)),super.setTrack(t),t&&(t.sid=this.trackSid,t.on(e.TrackEvent.VideoDimensionsChanged,this.handleVideoDimensionsChange),t.on(e.TrackEvent.VisibilityChanged,this.handleVisibilityChange),t.on(e.TrackEvent.Ended,this.handleEnded),this.emit(e.TrackEvent.Subscribed,t)),this.emitPermissionUpdateIfChanged(n),this.emitSubscriptionUpdateIfChanged(i))}setAllowed(e){const t=this.subscriptionStatus,i=this.permissionStatus;this.allowed=e,this.emitPermissionUpdateIfChanged(i),this.emitSubscriptionUpdateIfChanged(t)}setSubscriptionError(t){this.emit(e.TrackEvent.SubscriptionFailed,t)}updateInfo(t){super.updateInfo(t);const i=this.metadataMuted;this.metadataMuted=t.muted,this.track?this.track.setMuted(t.muted):i!==t.muted&&this.emit(t.muted?e.TrackEvent.Muted:e.TrackEvent.Unmuted)}emitSubscriptionUpdateIfChanged(t){const i=this.subscriptionStatus;t!==i&&this.emit(e.TrackEvent.SubscriptionStatusChanged,i,t)}emitPermissionUpdateIfChanged(t){this.permissionStatus!==t&&this.emit(e.TrackEvent.SubscriptionPermissionChanged,this.permissionStatus,t)}isManualOperationAllowed(){return this.kind===Nr.Kind.Video&&this.isAdaptiveStream?(c.warn("adaptive stream is enabled, cannot change video track settings",{trackSid:this.trackSid}),!1):!!this.isDesired||(c.warn("cannot update track settings when not subscribed",{trackSid:this.trackSid}),!1)}get isAdaptiveStream(){return this.track instanceof _o&&this.track.isAdaptiveStream}emitTrackUpdate(){const t=wn.fromPartial({trackSids:[this.trackSid],disabled:this.disabled,fps:this.fps});this.videoDimensions?(t.width=this.videoDimensions.width,t.height=this.videoDimensions.height):void 0!==this.currentVideoQuality?t.quality=this.currentVideoQuality:t.quality=e.VideoQuality.HIGH,this.emit(e.TrackEvent.UpdateSettings,t)}}class jo extends $o{static fromParticipantInfo(e,t){return new jo(e,t.sid,t.identity,t.name,t.metadata)}constructor(e,t,i,n,r){super(t,i||"",n,r),this.signalClient=e,this.tracks=new Map,this.audioTracks=new Map,this.videoTracks=new Map}addTrackPublication(t){super.addTrackPublication(t),t.on(e.TrackEvent.UpdateSettings,(e=>{c.debug("send update settings",e),this.signalClient.sendUpdateTrackSettings(e)})),t.on(e.TrackEvent.UpdateSubscription,(e=>{e.participantTracks.forEach((e=>{e.participantSid=this.sid})),this.signalClient.sendUpdateSubscription(e)})),t.on(e.TrackEvent.SubscriptionPermissionChanged,(i=>{this.emit(e.ParticipantEvent.TrackSubscriptionPermissionChanged,t,i)})),t.on(e.TrackEvent.SubscriptionStatusChanged,(i=>{this.emit(e.ParticipantEvent.TrackSubscriptionStatusChanged,t,i)})),t.on(e.TrackEvent.Subscribed,(i=>{this.emit(e.ParticipantEvent.TrackSubscribed,i,t)})),t.on(e.TrackEvent.Unsubscribed,(i=>{this.emit(e.ParticipantEvent.TrackUnsubscribed,i,t)})),t.on(e.TrackEvent.SubscriptionFailed,(i=>{this.emit(e.ParticipantEvent.TrackSubscriptionFailed,t.trackSid,i)}))}getTrack(e){const t=super.getTrack(e);if(t)return t}getTrackByName(e){const t=super.getTrackByName(e);if(t)return t}setVolume(e){this.volume=e;const t=this.getTrack(Nr.Source.Microphone);t&&t.track&&t.track.setVolume(e)}getVolume(){const e=this.getTrack(Nr.Source.Microphone);return e&&e.track?e.track.getVolume():this.volume}addSubscribedMediaTrack(t,i,n,r,s,o){let a=this.getTrackPublication(i);if(a||i.startsWith("TR")||this.tracks.forEach((e=>{a||t.kind!==e.kind.toString()||(a=e)})),!a)return 0===o?(c.error("could not find published track",{participant:this.sid,trackSid:i}),void this.emit(e.ParticipantEvent.TrackSubscriptionFailed,i)):(void 0===o&&(o=20),void setTimeout((()=>{this.addSubscribedMediaTrack(t,i,n,r,s,o-1)}),150));if("ended"===t.readyState)return c.error("unable to subscribe because MediaStreamTrack is ended. Do not call MediaStreamTrack.stop()",{participant:this.sid,trackSid:i}),void this.emit(e.ParticipantEvent.TrackSubscriptionFailed,i);let d;return d="video"===t.kind?new _o(t,i,r,s):new Lo(t,i,r,this.audioContext,this.audioOutput),d.source=a.source,d.isMuted=a.isMuted,d.setMediaStream(n),d.start(),a.setTrack(d),void 0!==this.volume&&d instanceof Lo&&d.source===Nr.Source.Microphone&&d.setVolume(this.volume),a}get hasMetadata(){return!!this.participantInfo}getTrackPublication(e){return this.tracks.get(e)}updateInfo(t){if(!super.updateInfo(t))return!1;const i=new Map,n=new Map;return t.tracks.forEach((e=>{var r;let s=this.getTrackPublication(e.sid);if(s)s.updateInfo(e);else{const i=Nr.kindFromProto(e.type);if(!i)return;s=new Vo(i,e,null===(r=this.signalClient.connectOptions)||void 0===r?void 0:r.autoSubscribe),s.updateInfo(e),n.set(e.sid,s);const o=Array.from(this.tracks.values()).find((e=>e.source===(null==s?void 0:s.source)));o&&s.source!==Nr.Source.Unknown&&c.debug("received a second track publication for ".concat(this.identity," with the same source: ").concat(s.source),{oldTrack:o,newTrack:s,participant:this,participantInfo:t}),this.addTrackPublication(s)}i.set(e.sid,s)})),this.tracks.forEach((e=>{i.has(e.trackSid)||(c.trace("detected removed track on remote participant, unpublishing",{publication:e,participantSid:this.sid}),this.unpublishTrack(e.trackSid,!0))})),n.forEach((t=>{this.emit(e.ParticipantEvent.TrackPublished,t)})),!0}unpublishTrack(t,i){const n=this.tracks.get(t);if(!n)return;const{track:r}=n;switch(r&&(r.stop(),n.setTrack(void 0)),this.tracks.delete(t),n.kind){case Nr.Kind.Audio:this.audioTracks.delete(t);break;case Nr.Kind.Video:this.videoTracks.delete(t)}i&&this.emit(e.ParticipantEvent.TrackUnpublished,n)}setAudioContext(e){this.audioContext=e,this.audioTracks.forEach((t=>t.track instanceof Lo&&t.track.setAudioContext(e)))}setAudioOutput(e){return Qt(this,void 0,void 0,(function*(){this.audioOutput=e;const t=[];this.audioTracks.forEach((i=>{var n;i.track instanceof Lo&&t.push(i.track.setSinkId(null!==(n=e.deviceId)&&void 0!==n?n:"default"))})),yield Promise.all(t)}))}emit(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),n=1;n<t;n++)i[n-1]=arguments[n];return c.trace("participant event",{participant:this.sid,event:e,args:i}),super.emit(e,...i)}}class qo extends $o{constructor(e,t,i,n){super(e,t),this.pendingPublishing=new Set,this.pendingPublishPromises=new Map,this.participantTrackPermissions=[],this.allParticipantsAllowedToSubscribe=!0,this.encryptionType=tt.NONE,this.handleReconnecting=()=>{this.reconnectFuture||(this.reconnectFuture=new us)},this.handleReconnected=()=>{var e,t;null===(t=null===(e=this.reconnectFuture)||void 0===e?void 0:e.resolve)||void 0===t||t.call(e),this.reconnectFuture=void 0,this.updateTrackSubscriptionPermissions()},this.handleDisconnected=()=>{var e,t;this.reconnectFuture&&(this.reconnectFuture.promise.catch((e=>c.warn(e))),null===(t=null===(e=this.reconnectFuture)||void 0===e?void 0:e.reject)||void 0===t||t.call(e,"Got disconnected during reconnection attempt"),this.reconnectFuture=void 0)},this.updateTrackSubscriptionPermissions=()=>{c.debug("updating track subscription permissions",{allParticipantsAllowed:this.allParticipantsAllowedToSubscribe,participantTrackPermissions:this.participantTrackPermissions}),this.engine.client.sendUpdateSubscriptionPermissions(this.allParticipantsAllowedToSubscribe,this.participantTrackPermissions.map((e=>function(e){var t,i,n;if(!e.participantSid&&!e.participantIdentity)throw new Error("Invalid track permission, must provide at least one of participantIdentity and participantSid");return{participantIdentity:null!==(t=e.participantIdentity)&&void 0!==t?t:"",participantSid:null!==(i=e.participantSid)&&void 0!==i?i:"",allTracks:null!==(n=e.allowAll)&&void 0!==n&&n,trackSids:e.allowedTrackSids||[]}}(e))))},this.onTrackUnmuted=e=>{this.onTrackMuted(e,e.isUpstreamPaused)},this.onTrackMuted=(e,t)=>{void 0===t&&(t=!0),e.sid?this.engine.updateMuteStatus(e.sid,t):c.error("could not update mute status for unpublished track",e)},this.onTrackUpstreamPaused=e=>{c.debug("upstream paused"),this.onTrackMuted(e,!0)},this.onTrackUpstreamResumed=e=>{c.debug("upstream resumed"),this.onTrackMuted(e,e.isMuted)},this.handleSubscribedQualityUpdate=e=>Qt(this,void 0,void 0,(function*(){var t,i,n,r,s,o;if(!(null===(s=this.roomOptions)||void 0===s?void 0:s.dynacast))return;const a=this.videoTracks.get(e.trackSid);if(a)if(e.subscribedCodecs.length>0){if(!a.videoTrack)return;const s=yield a.videoTrack.setPublishingCodecs(e.subscribedCodecs);try{for(var d,u=!0,l=Zt(s);!(t=(d=yield l.next()).done);u=!0){r=d.value,u=!1;const e=r;gr(e)&&(c.debug("publish ".concat(e," for ").concat(a.videoTrack.sid)),yield this.publishAdditionalCodecForTrack(a.videoTrack,e,a.options))}}catch(e){i={error:e}}finally{try{u||t||!(n=l.return)||(yield n.call(l))}finally{if(i)throw i.error}}}else e.subscribedQualities.length>0&&(yield null===(o=a.videoTrack)||void 0===o?void 0:o.setPublishingLayers(e.subscribedQualities));else c.warn("received subscribed quality update for unknown track",{method:"handleSubscribedQualityUpdate",sid:e.trackSid})})),this.handleLocalTrackUnpublished=e=>{const t=this.tracks.get(e.trackSid);t?this.unpublishTrack(t.track):c.warn("received unpublished event for unknown track",{method:"handleLocalTrackUnpublished",trackSid:e.trackSid})},this.handleTrackEnded=e=>Qt(this,void 0,void 0,(function*(){if(e.source===Nr.Source.ScreenShare||e.source===Nr.Source.ScreenShareAudio)c.debug("unpublishing local track due to TrackEnded",{track:e.sid}),this.unpublishTrack(e);else if(e.isUserProvided)yield e.mute();else if(e instanceof fo||e instanceof Io)try{if(Kr())try{const t=yield null===navigator||void 0===navigator?void 0:navigator.permissions.query({name:e.source===Nr.Source.Camera?"camera":"microphone"});if(t&&"denied"===t.state)throw c.warn("user has revoked access to ".concat(e.source)),t.onchange=()=>{"denied"!==t.state&&(e.isMuted||e.restartTrack(),t.onchange=null)},new Error("GetUserMedia Permission denied")}catch(e){}e.isMuted||(c.debug("track ended, attempting to use a different device"),yield e.restartTrack())}catch(t){c.warn("could not restart track, muting instead"),yield e.mute()}})),this.audioTracks=new Map,this.videoTracks=new Map,this.tracks=new Map,this.engine=i,this.roomOptions=n,this.setupEngine(i),this.activeDeviceMap=new Map}get lastCameraError(){return this.cameraError}get lastMicrophoneError(){return this.microphoneError}getTrack(e){const t=super.getTrack(e);if(t)return t}getTrackByName(e){const t=super.getTrackByName(e);if(t)return t}setupEngine(t){this.engine=t,this.engine.client.onRemoteMuteChanged=(e,t)=>{const i=this.tracks.get(e);i&&i.track&&(t?i.mute():i.unmute())},this.engine.client.onSubscribedQualityUpdate=this.handleSubscribedQualityUpdate,this.engine.client.onLocalTrackUnpublished=this.handleLocalTrackUnpublished,this.engine.on(e.EngineEvent.Connected,this.handleReconnected).on(e.EngineEvent.Restarted,this.handleReconnected).on(e.EngineEvent.Resumed,this.handleReconnected).on(e.EngineEvent.Restarting,this.handleReconnecting).on(e.EngineEvent.Resuming,this.handleReconnecting).on(e.EngineEvent.Disconnected,this.handleDisconnected)}setMetadata(e){var t;super.setMetadata(e),this.engine.client.sendUpdateLocalMetadata(e,null!==(t=this.name)&&void 0!==t?t:"")}setName(e){var t;super.setName(e),this.engine.client.sendUpdateLocalMetadata(null!==(t=this.metadata)&&void 0!==t?t:"",e)}setCameraEnabled(e,t,i){return this.setTrackEnabled(Nr.Source.Camera,e,t,i)}setMicrophoneEnabled(e,t,i){return this.setTrackEnabled(Nr.Source.Microphone,e,t,i)}setScreenShareEnabled(e,t,i){return this.setTrackEnabled(Nr.Source.ScreenShare,e,t,i)}setPermissions(t){const i=this.permissions,n=super.setPermissions(t);return n&&i&&this.emit(e.ParticipantEvent.ParticipantPermissionsChanged,i),n}setE2EEEnabled(e){return Qt(this,void 0,void 0,(function*(){this.encryptionType=e?tt.GCM:tt.NONE,yield this.republishAllTracks(void 0,!1)}))}setTrackEnabled(t,i,n,r){var s,o;return Qt(this,void 0,void 0,(function*(){c.debug("setTrackEnabled",{source:t,enabled:i});let a=this.getTrack(t);if(i)if(a)yield a.unmute();else{let i;if(this.pendingPublishing.has(t))return void c.info("skipping duplicate published source",{source:t});this.pendingPublishing.add(t);try{switch(t){case Nr.Source.Camera:i=yield this.createTracks({video:null===(s=n)||void 0===s||s});break;case Nr.Source.Microphone:i=yield this.createTracks({audio:null===(o=n)||void 0===o||o});break;case Nr.Source.ScreenShare:i=yield this.createScreenTracks(Object.assign({},n));break;default:throw new nr(t)}const e=[];for(const t of i)c.info("publishing track",{localTrack:t}),e.push(this.publishTrack(t,r));const d=yield Promise.all(e);[a]=d}catch(t){throw t instanceof Error&&!(t instanceof nr)&&this.emit(e.ParticipantEvent.MediaDevicesError,t),t}finally{this.pendingPublishing.delete(t)}}else if(a&&a.track)if(t===Nr.Source.ScreenShare){a=yield this.unpublishTrack(a.track);const e=this.getTrack(Nr.Source.ScreenShareAudio);e&&e.track&&this.unpublishTrack(e.track)}else yield a.mute();return a}))}enableCameraAndMicrophone(){return Qt(this,void 0,void 0,(function*(){if(!this.pendingPublishing.has(Nr.Source.Camera)&&!this.pendingPublishing.has(Nr.Source.Microphone)){this.pendingPublishing.add(Nr.Source.Camera),this.pendingPublishing.add(Nr.Source.Microphone);try{const e=yield this.createTracks({audio:!0,video:!0});yield Promise.all(e.map((e=>this.publishTrack(e))))}finally{this.pendingPublishing.delete(Nr.Source.Camera),this.pendingPublishing.delete(Nr.Source.Microphone)}}}))}createTracks(e){var t,i;return Qt(this,void 0,void 0,(function*(){const n=Ur(Dr(e,null===(t=this.roomOptions)||void 0===t?void 0:t.audioCaptureDefaults,null===(i=this.roomOptions)||void 0===i?void 0:i.videoCaptureDefaults));let r;try{r=yield navigator.mediaDevices.getUserMedia(n)}catch(e){throw e instanceof Error&&(n.audio&&(this.microphoneError=e),n.video&&(this.cameraError=e)),e}return n.audio&&(this.microphoneError=void 0),n.video&&(this.cameraError=void 0),r.getTracks().map((t=>{const i="audio"===t.kind;let s;i?e.audio:e.video;const o=i?n.audio:n.video;"boolean"!=typeof o&&(s=o);const a=vo(t,s);return a.kind===Nr.Kind.Video?a.source=Nr.Source.Camera:a.kind===Nr.Kind.Audio&&(a.source=Nr.Source.Microphone),a.mediaStream=r,a}))}))}createScreenTracks(e){var t;return Qt(this,void 0,void 0,(function*(){void 0===e&&(e={}),void 0===e.resolution&&(e.resolution=Cr.h1080fps15.resolution);let i=!0;if(e.resolution&&(i=Wr()?{width:{max:e.resolution.width},height:{max:e.resolution.height},frameRate:e.resolution.frameRate}:{width:{ideal:e.resolution.width},height:{ideal:e.resolution.height},frameRate:e.resolution.frameRate}),void 0===navigator.mediaDevices.getDisplayMedia)throw new ir("getDisplayMedia not supported");const n=yield navigator.mediaDevices.getDisplayMedia({audio:null!==(t=e.audio)&&void 0!==t&&t,video:i,controller:e.controller,selfBrowserSurface:e.selfBrowserSurface,surfaceSwitching:e.surfaceSwitching,systemAudio:e.systemAudio}),r=n.getVideoTracks();if(0===r.length)throw new nr("no video track found");const s=new Io(r[0],void 0,!1);s.source=Nr.Source.ScreenShare;const o=[s];if(n.getAudioTracks().length>0){const e=new fo(n.getAudioTracks()[0],void 0,!1);e.source=Nr.Source.ScreenShareAudio,o.push(e)}return o}))}publishTrack(e,t){var i,n,r,s;return Qt(this,void 0,void 0,(function*(){let o,a;if(yield null===(i=this.reconnectFuture)||void 0===i?void 0:i.promise,e instanceof As&&this.pendingPublishPromises.has(e)&&(yield this.pendingPublishPromises.get(e)),e instanceof MediaStreamTrack)o=e.getConstraints();else{let t;switch(o=e.constraints,e.source){case Nr.Source.Microphone:t="audioinput";break;case Nr.Source.Camera:t="videoinput"}t&&this.activeDeviceMap.has(t)&&(o=Object.assign(Object.assign({},o),{deviceId:this.activeDeviceMap.get(t)}))}if(e instanceof MediaStreamTrack)switch(e.kind){case"audio":e=new fo(e,o,!0);break;case"video":e=new Io(e,o,!0);break;default:throw new nr("unsupported MediaStreamTrack kind ".concat(e.kind))}if(this.tracks.forEach((t=>{t.track&&t.track===e&&(a=t)})),a)return c.warn("track has already been published, skipping"),a;const d="channelCount"in e.mediaStreamTrack.getSettings()&&2===e.mediaStreamTrack.getSettings().channelCount||2===e.mediaStreamTrack.getConstraints().channelCount,u=null!==(n=null==t?void 0:t.forceStereo)&&void 0!==n?n:d;u&&(t||(t={}),void 0===t.dtx&&c.info("Opus DTX will be disabled for stereo tracks by default. Enable them explicitly to make it work."),void 0===t.red&&c.info("Opus RED will be disabled for stereo tracks by default. Enable them explicitly to make it work."),null!==(r=t.dtx)&&void 0!==r||(t.dtx=!1),null!==(s=t.red)&&void 0!==s||(t.red=!1));const l=Object.assign(Object.assign({},this.roomOptions.publishDefaults),t);Wr()&&this.roomOptions.e2ee&&(c.info("End-to-end encryption is set up, simulcast publishing will be disabled on Safari"),l.simulcast=!1),l.source&&(e.source=l.source);const h=this.publish(e,l,t,u);this.pendingPublishPromises.set(e,h);try{return yield h}catch(e){throw e}finally{this.pendingPublishPromises.delete(e)}}))}publish(t,i,n,r){var s,o,a,d,u,l,h,p,m,f,v,g,b;return Qt(this,void 0,void 0,(function*(){const k=Array.from(this.tracks.values()).find((e=>t instanceof As&&e.source===t.source));if(k&&t.source!==Nr.Source.Unknown)try{throw Error("publishing a second track with the same source: ".concat(t.source))}catch(e){e instanceof Error&&c.warn(e.message,{oldTrack:k,newTrack:t,trace:e.stack})}i.stopMicTrackOnMute&&t instanceof fo&&(t.stopOnMute=!0),t.source===Nr.Source.ScreenShare&&qr()&&(i.simulcast=!1),"av1"!==i.videoCodec||Jr()||(i.videoCodec=void 0),"vp9"!==i.videoCodec||Fr()||(i.videoCodec=void 0),t.on(e.TrackEvent.Muted,this.onTrackMuted),t.on(e.TrackEvent.Unmuted,this.onTrackUnmuted),t.on(e.TrackEvent.Ended,this.handleTrackEnded),t.on(e.TrackEvent.UpstreamPaused,this.onTrackUpstreamPaused),t.on(e.TrackEvent.UpstreamResumed,this.onTrackUpstreamResumed);const y=fn.fromPartial({cid:t.mediaStreamTrack.id,name:null==n?void 0:n.name,type:Nr.kindToProto(t.kind),muted:t.isMuted,source:Nr.sourceToProto(t.source),disableDtx:!(null===(s=i.dtx)||void 0===s||s),encryption:this.encryptionType,stereo:r});let S,C;if(t.kind===Nr.Kind.Video){let e={width:0,height:0};try{e=yield t.waitForDimensions()}catch(t){const i=null!==(a=null===(o=this.roomOptions.videoCaptureDefaults)||void 0===o?void 0:o.resolution)&&void 0!==a?a:yr.h720.resolution;e={width:i.width,height:i.height},c.error("could not determine track dimensions, using defaults",e)}if(y.width=e.width,y.height=e.height,t instanceof Io)if($r(i.videoCodec)&&(i.scalabilityMode=null!==(d=i.scalabilityMode)&&void 0!==d?d:"L3T3_KEY"),i.videoCodec&&i.backupCodec&&i.videoCodec!==i.backupCodec.codec){const e=Object.assign({},i);e.simulcast=!0,C=Po(t,i.backupCodec.codec,e),y.simulcastCodecs=[{codec:i.videoCodec,cid:t.mediaStreamTrack.id,enableSimulcastLayers:!0},{codec:i.backupCodec.codec,cid:"",enableSimulcastLayers:!0}]}else i.videoCodec&&(y.simulcastCodecs=[{codec:i.videoCodec,cid:t.mediaStreamTrack.id,enableSimulcastLayers:null!==(u=i.simulcast)&&void 0!==u&&u}]);S=To(t.source===Nr.Source.ScreenShare,e.width,e.height,i),y.layers=Uo(y.width,y.height,S,$r(i.videoCodec))}else t.kind===Nr.Kind.Audio&&(S=[{maxBitrate:null!==(h=null===(l=i.audioPreset)||void 0===l?void 0:l.maxBitrate)&&void 0!==h?h:i.audioBitrate,priority:null!==(m=null===(p=i.audioPreset)||void 0===p?void 0:p.priority)&&void 0!==m?m:"high",networkPriority:null!==(v=null===(f=i.audioPreset)||void 0===f?void 0:f.priority)&&void 0!==v?v:"high"}]);if(!this.engine||this.engine.isClosed)throw new sr("cannot publish track when not connected");const E=yield this.engine.addTrack(y);let T=!1,P=!1;if(E.codecs.forEach((e=>{br(e.mimeType,i.videoCodec)?T=!0:i.backupCodec&&br(e.mimeType,i.backupCodec.codec)&&(P=!0)})),y.simulcastCodecs.length>0){if(!T&&!P)throw Error("cannot publish track, codec not supported by server");if(!T&&i.backupCodec){const e=i.backupCodec;i=Object.assign({},i),c.debug("primary codec ".concat(i.videoCodec," not supported, fallback to ").concat(e.codec)),i.videoCodec=e.codec,i.videoEncoding=e.encoding,S=C}}const w=new Fo(t.kind,E,t);if(w.options=i,t.sid=E.sid,!this.engine.publisher)throw new sr("publisher is closed");if(c.debug("publishing ".concat(t.kind," with encodings"),{encodings:S,trackInfo:E}),t.sender=yield this.engine.createSender(t,i,S),S)if(qr()&&t.kind===Nr.Kind.Audio){let e;for(const i of this.engine.publisher.pc.getTransceivers())if(i.sender===t.sender){e=i;break}e&&this.engine.publisher.setTrackCodecBitrate({transceiver:e,codec:"opus",maxbr:(null===(g=S[0])||void 0===g?void 0:g.maxBitrate)?S[0].maxBitrate/1e3:0})}else t.codec&&$r(t.codec)&&(null===(b=S[0])||void 0===b?void 0:b.maxBitrate)&&this.engine.publisher.setTrackCodecBitrate({cid:y.cid,codec:t.codec,maxbr:S[0].maxBitrate/1e3});return yield this.engine.negotiate(),t instanceof Io?t.startMonitor(this.engine.client):t instanceof fo&&t.startMonitor(),this.addTrackPublication(w),this.emit(e.ParticipantEvent.LocalTrackPublished,w),w}))}get isLocal(){return!0}publishAdditionalCodecForTrack(e,t,i){var n;return Qt(this,void 0,void 0,(function*(){let r;if(this.tracks.forEach((t=>{t.track&&t.track===e&&(r=t)})),!r)throw new nr("track is not published");if(!(e instanceof Io))throw new nr("track is not a video track");const s=Object.assign(Object.assign({},null===(n=this.roomOptions)||void 0===n?void 0:n.publishDefaults),i),o=Po(e,t,s);if(!o)return void c.info("backup codec has been disabled, ignoring request to add additional codec for track");const a=e.addSimulcastTrack(t,o),d=fn.fromPartial({cid:a.mediaStreamTrack.id,type:Nr.kindToProto(e.kind),muted:e.isMuted,source:Nr.sourceToProto(e.source),sid:e.sid,simulcastCodecs:[{codec:s.videoCodec,cid:a.mediaStreamTrack.id,enableSimulcastLayers:s.simulcast}]});if(d.layers=Uo(d.width,d.height,o),!this.engine||this.engine.isClosed)throw new sr("cannot publish track when not connected");const u=yield this.engine.addTrack(d);yield this.engine.createSimulcastSender(e,a,s,o),yield this.engine.negotiate(),c.debug("published ".concat(t," for track ").concat(e.sid),{encodings:o,trackInfo:u})}))}unpublishTrack(t,i){var n,r;return Qt(this,void 0,void 0,(function*(){const s=this.getPublicationForTrack(t);if(c.debug("unpublishing track",{track:t,method:"unpublishTrack"}),!s||!s.track)return void c.warn("track was not unpublished because no publication was found",{track:t,method:"unpublishTrack"});(t=s.track).off(e.TrackEvent.Muted,this.onTrackMuted),t.off(e.TrackEvent.Unmuted,this.onTrackUnmuted),t.off(e.TrackEvent.Ended,this.handleTrackEnded),t.off(e.TrackEvent.UpstreamPaused,this.onTrackUpstreamPaused),t.off(e.TrackEvent.UpstreamResumed,this.onTrackUpstreamResumed),void 0===i&&(i=null===(r=null===(n=this.roomOptions)||void 0===n?void 0:n.stopLocalTrackOnUnpublish)||void 0===r||r),i&&t.stop();let o=!1;const a=t.sender;if(t.sender=void 0,this.engine.publisher&&"closed"!==this.engine.publisher.pc.connectionState&&a)try{for(const e of this.engine.publisher.pc.getTransceivers())e.sender===a&&(e.direction="inactive",o=!0);if(this.engine.removeTrack(a)&&(o=!0),t instanceof Io){for(const[,e]of t.simulcastCodecs)e.sender&&(this.engine.removeTrack(e.sender)&&(o=!0),e.sender=void 0);t.simulcastCodecs.clear()}}catch(e){c.warn("failed to unpublish track",{error:e,method:"unpublishTrack"})}switch(this.tracks.delete(s.trackSid),s.kind){case Nr.Kind.Audio:this.audioTracks.delete(s.trackSid);break;case Nr.Kind.Video:this.videoTracks.delete(s.trackSid)}return this.emit(e.ParticipantEvent.LocalTrackUnpublished,s),s.setTrack(void 0),o&&(yield this.engine.negotiate()),s}))}unpublishTracks(e){return Qt(this,void 0,void 0,(function*(){return(yield Promise.all(e.map((e=>this.unpublishTrack(e))))).filter((e=>e instanceof Fo))}))}republishAllTracks(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return Qt(this,void 0,void 0,(function*(){const i=[];this.tracks.forEach((t=>{t.track&&(e&&(t.options=Object.assign(Object.assign({},t.options),e)),i.push(t))})),yield Promise.all(i.map((e=>Qt(this,void 0,void 0,(function*(){const i=e.track;yield this.unpublishTrack(i,!1),t&&!i.isMuted&&(i instanceof fo||i instanceof Io)&&!i.isUserProvided&&(c.debug("restarting existing track",{track:e.trackSid}),yield i.restartTrack()),yield this.publishTrack(i,e.options)})))))}))}publishData(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return Qt(this,void 0,void 0,(function*(){const n=Array.isArray(i)?i:null==i?void 0:i.destination,r=[],s=Array.isArray(i)?void 0:i.topic;void 0!==n&&n.forEach((e=>{e instanceof jo?r.push(e.sid):r.push(e)}));const o={kind:t,value:{$case:"user",user:{participantSid:this.sid,payload:e,destinationSids:r,topic:s}}};yield this.engine.sendDataPacket(o,t)}))}setTrackSubscriptionPermissions(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[];this.participantTrackPermissions=t,this.allParticipantsAllowedToSubscribe=e,this.engine.client.isConnected&&this.updateTrackSubscriptionPermissions()}updateInfo(e){return e.sid===this.sid&&(!!super.updateInfo(e)&&(e.tracks.forEach((e=>{var t,i;const n=this.tracks.get(e.sid);if(n){const r=n.isMuted||null!==(i=null===(t=n.track)||void 0===t?void 0:t.isUpstreamPaused)&&void 0!==i&&i;r!==e.muted&&(c.debug("updating server mute state after reconcile",{sid:e.sid,muted:r}),this.engine.client.sendMuteTrack(e.sid,r))}})),!0))}getPublicationForTrack(e){let t;return this.tracks.forEach((i=>{const n=i.track;n&&(e instanceof MediaStreamTrack?(n instanceof fo||n instanceof Io)&&n.mediaStreamTrack===e&&(t=i):e===n&&(t=i))})),t}publishedTracksInfo(){const e=[];return this.tracks.forEach((t=>{void 0!==t.track&&e.push({cid:t.track.mediaStreamID,track:t.trackInfo})})),e}dataChannelsInfo(){const t=[],i=(e,i)=>{void 0!==(null==e?void 0:e.id)&&null!==e.id&&t.push({label:e.label,id:e.id,target:i})};return i(this.engine.dataChannelForKind(e.DataPacket_Kind.LOSSY),rn.PUBLISHER),i(this.engine.dataChannelForKind(e.DataPacket_Kind.RELIABLE),rn.PUBLISHER),i(this.engine.dataChannelForKind(e.DataPacket_Kind.LOSSY,!0),rn.SUBSCRIBER),i(this.engine.dataChannelForKind(e.DataPacket_Kind.RELIABLE,!0),rn.SUBSCRIBER),t}}var Wo;e.ConnectionState=void 0,(Wo=e.ConnectionState||(e.ConnectionState={})).Disconnected="disconnected",Wo.Connecting="connecting",Wo.Connected="connected",Wo.Reconnecting="reconnecting";const Go=e.ConnectionState;class Ko extends Yt{constructor(t){var i,n;super(),i=this,this.state=e.ConnectionState.Disconnected,this.activeSpeakers=[],this.isE2EEEnabled=!1,this.audioEnabled=!0,this.connect=(t,i,n)=>Qt(this,void 0,void 0,(function*(){const r=yield this.disconnectLock.lock();if(this.state===e.ConnectionState.Connected)return c.info("already connected to room ".concat(this.name)),r(),Promise.resolve();if(this.connectFuture)return r(),this.connectFuture.promise;this.setAndEmitConnectionState(e.ConnectionState.Connecting);const s=new eo(t,i),o=(e,a,d)=>Qt(this,void 0,void 0,(function*(){var u;this.abortController&&this.abortController.abort(),this.abortController=new AbortController,null==r||r();try{yield this.attemptConnection(null!=d?d:t,i,n,this.abortController),this.abortController=void 0,e()}catch(i){if(Hr(new URL(t))&&i instanceof tr&&3!==i.reason){let t=null;try{t=yield s.getNextBestRegionUrl(null===(u=this.abortController)||void 0===u?void 0:u.signal)}catch(e){if(e instanceof tr&&(401===e.status||3===e.reason))return void a(e)}t?(c.debug("initial connection failed, retrying with another region"),yield o(e,a,t)):a(i)}else a(i)}}));return this.connectFuture=new us(o,(()=>{this.clearConnectionFutures()})),this.connectFuture.promise})),this.connectSignal=(e,t,i,n,r,s)=>Qt(this,void 0,void 0,(function*(){const o=yield i.join(e,t,{autoSubscribe:n.autoSubscribe,publishOnly:n.publishOnly,adaptiveStream:"object"==typeof r.adaptiveStream||r.adaptiveStream,maxRetries:n.maxRetries,e2eeEnabled:!!this.e2eeManager},s.signal);let a=o.serverInfo;if(a||(a={version:o.serverVersion,region:o.serverRegion}),c.debug("connected to Livekit Server ".concat(Object.entries(a).map((e=>{let[t,i]=e;return"".concat(t,": ").concat(i)})).join(", "))),!o.serverVersion)throw new rr("unknown server version");return"0.15.1"===o.serverVersion&&this.options.dynacast&&(c.debug("disabling dynacast due to server version"),r.dynacast=!1),o})),this.applyJoinResponse=e=>{const t=e.participant;this.localParticipant.sid=t.sid,this.localParticipant.identity=t.identity,this.handleParticipantUpdates([t,...e.otherParticipants]),e.room&&this.handleRoomUpdate(e.room)},this.attemptConnection=(t,i,n,r)=>Qt(this,void 0,void 0,(function*(){var s;this.state===e.ConnectionState.Reconnecting?(c.info("Reconnection attempt replaced by new connection attempt"),this.recreateEngine()):this.maybeCreateEngine(),this.acquireAudioContext(),this.connOptions=Object.assign(Object.assign({},so),n),this.connOptions.rtcConfig&&(this.engine.rtcConfig=this.connOptions.rtcConfig),this.connOptions.peerConnectionTimeout&&(this.engine.peerConnectionTimeout=this.connOptions.peerConnectionTimeout);try{const n=yield this.connectSignal(t,i,this.engine,this.connOptions,this.options,r);this.applyJoinResponse(n),this.setupLocalParticipantEvents(),this.emit(e.RoomEvent.SignalConnected)}catch(e){this.recreateEngine(),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish);const t=new tr("could not establish signal connection");throw e instanceof Error&&(t.message="".concat(t.message,": ").concat(e.message)),e instanceof tr&&(t.reason=e.reason,t.status=e.status),c.debug("error trying to establish signal connection",{error:e}),t}if(r.signal.aborted)throw this.recreateEngine(),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),new tr("Connection attempt aborted");try{yield this.engine.waitForPCInitialConnection(this.connOptions.peerConnectionTimeout,r)}catch(e){throw this.recreateEngine(),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),e}Kr()&&this.options.disconnectOnPageLeave&&(window.addEventListener("pagehide",this.onPageLeave),window.addEventListener("beforeunload",this.onPageLeave)),Kr()&&(document.addEventListener("freeze",this.onPageLeave),null===(s=navigator.mediaDevices)||void 0===s||s.addEventListener("devicechange",this.handleDeviceChange)),this.setAndEmitConnectionState(e.ConnectionState.Connected),this.emit(e.RoomEvent.Connected),this.registerConnectionReconcile()})),this.disconnect=function(){let t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return Qt(i,void 0,void 0,(function*(){var i,n,r,s;const o=yield this.disconnectLock.lock();try{if(this.state===e.ConnectionState.Disconnected)return void c.debug("already disconnected");c.info("disconnect from room",{identity:this.localParticipant.identity}),this.state!==e.ConnectionState.Connecting&&this.state!==e.ConnectionState.Reconnecting||(c.warn("abort connection attempt"),null===(i=this.abortController)||void 0===i||i.abort(),null===(r=null===(n=this.connectFuture)||void 0===n?void 0:n.reject)||void 0===r||r.call(n,new tr("Client initiated disconnect")),this.connectFuture=void 0),(null===(s=this.engine)||void 0===s?void 0:s.client.isConnected)&&(yield this.engine.client.sendLeave()),this.engine&&(yield this.engine.close()),this.handleDisconnect(t,e.DisconnectReason.CLIENT_INITIATED),this.engine=void 0}finally{o()}}))},this.onPageLeave=()=>Qt(this,void 0,void 0,(function*(){yield this.disconnect()})),this.handleRestarting=()=>{this.clearConnectionReconcile();for(const e of this.participants.values())this.handleParticipantDisconnected(e.sid,e);this.setAndEmitConnectionState(e.ConnectionState.Reconnecting)&&this.emit(e.RoomEvent.Reconnecting)},this.handleSignalRestarted=t=>Qt(this,void 0,void 0,(function*(){c.debug("signal reconnected to server",{region:t.serverRegion}),this.cachedParticipantSids=[],this.applyJoinResponse(t);try{const e=[];this.localParticipant.tracks.forEach((t=>{t.track&&e.push(t)})),yield Promise.all(e.map((e=>Qt(this,void 0,void 0,(function*(){const t=e.track;this.localParticipant.unpublishTrack(t,!1),t.isMuted||((t instanceof fo||t instanceof Io)&&!t.isUserProvided&&(c.debug("restarting existing track",{track:e.trackSid}),yield t.restartTrack()),c.debug("publishing new track",{track:e.trackSid}),yield this.localParticipant.publishTrack(t,e.options))})))))}catch(e){c.error("error trying to re-publish tracks after reconnection",{error:e})}try{yield this.engine.waitForRestarted(),c.debug("fully reconnected to server",{region:t.serverRegion})}catch(e){return}this.setAndEmitConnectionState(e.ConnectionState.Connected),this.emit(e.RoomEvent.Reconnected),this.registerConnectionReconcile(),this.participants.forEach((t=>{this.emit(e.RoomEvent.ParticipantConnected,t)}))})),this.handleParticipantUpdates=e=>{e.forEach((e=>{if(e.identity===this.localParticipant.identity)return void this.localParticipant.updateInfo(e);const t=this.identityToSid.get(e.identity);t&&t!==e.sid&&this.handleParticipantDisconnected(t,this.participants.get(t));let i=this.participants.get(e.sid);const n=!i;e.state===et.DISCONNECTED?this.handleParticipantDisconnected(e.sid,i):(i=this.getOrCreateParticipant(e.sid,e),n||i.updateInfo(e))}))},this.handleActiveSpeakersUpdate=t=>{const i=[],n={};t.forEach((e=>{if(n[e.sid]=!0,e.sid===this.localParticipant.sid)this.localParticipant.audioLevel=e.level,this.localParticipant.setIsSpeaking(!0),i.push(this.localParticipant);else{const t=this.participants.get(e.sid);t&&(t.audioLevel=e.level,t.setIsSpeaking(!0),i.push(t))}})),n[this.localParticipant.sid]||(this.localParticipant.audioLevel=0,this.localParticipant.setIsSpeaking(!1)),this.participants.forEach((e=>{n[e.sid]||(e.audioLevel=0,e.setIsSpeaking(!1))})),this.activeSpeakers=i,this.emitWhenConnected(e.RoomEvent.ActiveSpeakersChanged,i)},this.handleSpeakersChanged=t=>{const i=new Map;this.activeSpeakers.forEach((e=>{i.set(e.sid,e)})),t.forEach((e=>{let t=this.participants.get(e.sid);e.sid===this.localParticipant.sid&&(t=this.localParticipant),t&&(t.audioLevel=e.level,t.setIsSpeaking(e.active),e.active?i.set(e.sid,t):i.delete(e.sid))}));const n=Array.from(i.values());n.sort(((e,t)=>t.audioLevel-e.audioLevel)),this.activeSpeakers=n,this.emitWhenConnected(e.RoomEvent.ActiveSpeakersChanged,n)},this.handleStreamStateUpdate=t=>{t.streamStates.forEach((t=>{const i=this.participants.get(t.participantSid);if(!i)return;const n=i.getTrackPublication(t.trackSid);n&&n.track&&(n.track.streamState=Nr.streamStateFromProto(t.state),i.emit(e.ParticipantEvent.TrackStreamStateChanged,n,n.track.streamState),this.emitWhenConnected(e.RoomEvent.TrackStreamStateChanged,n,n.track.streamState,i))}))},this.handleSubscriptionPermissionUpdate=e=>{const t=this.participants.get(e.participantSid);if(!t)return;const i=t.getTrackPublication(e.trackSid);i&&i.setAllowed(e.allowed)},this.handleSubscriptionError=e=>{const t=Array.from(this.participants.values()).find((t=>t.tracks.has(e.trackSid)));if(!t)return;const i=t.getTrackPublication(e.trackSid);i&&i.setSubscriptionError(e.err)},this.handleDataPacket=(t,i)=>{const n=this.participants.get(t.participantSid);this.emit(e.RoomEvent.DataReceived,t.payload,n,i,t.topic),null==n||n.emit(e.ParticipantEvent.DataReceived,t.payload,i)},this.handleAudioPlaybackStarted=()=>{this.canPlaybackAudio||(this.audioEnabled=!0,this.emit(e.RoomEvent.AudioPlaybackStatusChanged,!0))},this.handleAudioPlaybackFailed=t=>{c.warn("could not playback audio",t),this.canPlaybackAudio&&(this.audioEnabled=!1,this.emit(e.RoomEvent.AudioPlaybackStatusChanged,!1))},this.handleDeviceChange=()=>Qt(this,void 0,void 0,(function*(){this.emit(e.RoomEvent.MediaDevicesChanged)})),this.handleRoomUpdate=t=>{const i=this.roomInfo;this.roomInfo=t,i&&i.metadata!==t.metadata&&this.emitWhenConnected(e.RoomEvent.RoomMetadataChanged,t.metadata),(null==i?void 0:i.activeRecording)!==t.activeRecording&&this.emitWhenConnected(e.RoomEvent.RecordingStatusChanged,t.activeRecording)},this.handleConnectionQualityUpdate=e=>{e.updates.forEach((e=>{if(e.participantSid===this.localParticipant.sid)return void this.localParticipant.setConnectionQuality(e.quality);const t=this.participants.get(e.participantSid);t&&t.setConnectionQuality(e.quality)}))},this.onLocalParticipantMetadataChanged=t=>{this.emit(e.RoomEvent.ParticipantMetadataChanged,t,this.localParticipant)},this.onLocalParticipantNameChanged=t=>{this.emit(e.RoomEvent.ParticipantNameChanged,t,this.localParticipant)},this.onLocalTrackMuted=t=>{this.emit(e.RoomEvent.TrackMuted,t,this.localParticipant)},this.onLocalTrackUnmuted=t=>{this.emit(e.RoomEvent.TrackUnmuted,t,this.localParticipant)},this.onLocalTrackPublished=t=>Qt(this,void 0,void 0,(function*(){var i;if(this.emit(e.RoomEvent.LocalTrackPublished,t,this.localParticipant),t.track instanceof fo){(yield t.track.checkForSilence())&&this.emit(e.RoomEvent.LocalAudioSilenceDetected,t)}const n=yield null===(i=t.track)||void 0===i?void 0:i.getDeviceId(),r=(s=t.source)===Nr.Source.Microphone?"audioinput":s===Nr.Source.Camera?"videoinput":void 0;var s;r&&n&&n!==this.localParticipant.activeDeviceMap.get(r)&&(this.localParticipant.activeDeviceMap.set(r,n),this.emit(e.RoomEvent.ActiveDeviceChanged,r,n))})),this.onLocalTrackUnpublished=t=>{this.emit(e.RoomEvent.LocalTrackUnpublished,t,this.localParticipant)},this.onLocalConnectionQualityChanged=t=>{this.emit(e.RoomEvent.ConnectionQualityChanged,t,this.localParticipant)},this.onMediaDevicesError=t=>{this.emit(e.RoomEvent.MediaDevicesError,t)},this.onLocalParticipantPermissionsChanged=t=>{this.emit(e.RoomEvent.ParticipantPermissionsChanged,t,this.localParticipant)},this.participants=new Map,this.cachedParticipantSids=[],this.identityToSid=new Map,this.options=Object.assign(Object.assign({},ro),t),this.options.audioCaptureDefaults=Object.assign(Object.assign({},io),null==t?void 0:t.audioCaptureDefaults),this.options.videoCaptureDefaults=Object.assign(Object.assign({},no),null==t?void 0:t.videoCaptureDefaults),this.options.publishDefaults=Object.assign(Object.assign({},to),null==t?void 0:t.publishDefaults),this.maybeCreateEngine(),this.disconnectLock=new ls,this.localParticipant=new qo("","",this.engine,this.options),this.options.videoCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("videoinput",hs(this.options.videoCaptureDefaults.deviceId)),this.options.audioCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("audioinput",hs(this.options.audioCaptureDefaults.deviceId)),(null===(n=this.options.audioOutput)||void 0===n?void 0:n.deviceId)&&this.switchActiveDevice("audiooutput",hs(this.options.audioOutput.deviceId)),this.options.e2ee&&this.setupE2EE()}setE2EEEnabled(e){return Qt(this,void 0,void 0,(function*(){if(!this.e2eeManager)throw Error("e2ee not configured, please set e2ee settings within the room options");yield Promise.all([this.localParticipant.setE2EEEnabled(e),this.e2eeManager.setParticipantCryptorEnabled(e)])}))}setupE2EE(){var t;this.options.e2ee&&(this.e2eeManager=new Us(this.options.e2ee),this.e2eeManager.on(Os.ParticipantEncryptionStatusChanged,((t,i)=>{i instanceof qo&&(this.isE2EEEnabled=t),this.emit(e.RoomEvent.ParticipantEncryptionStatusChanged,t,i)})),this.e2eeManager.on(Os.Error,(t=>this.emit(e.RoomEvent.EncryptionError,t))),null===(t=this.e2eeManager)||void 0===t||t.setup(this))}get isRecording(){var e,t;return null!==(t=null===(e=this.roomInfo)||void 0===e?void 0:e.activeRecording)&&void 0!==t&&t}get sid(){var e,t;return null!==(t=null===(e=this.roomInfo)||void 0===e?void 0:e.sid)&&void 0!==t?t:""}get name(){var e,t;return null!==(t=null===(e=this.roomInfo)||void 0===e?void 0:e.name)&&void 0!==t?t:""}get metadata(){var e;return null===(e=this.roomInfo)||void 0===e?void 0:e.metadata}get numParticipants(){var e,t;return null!==(t=null===(e=this.roomInfo)||void 0===e?void 0:e.numParticipants)&&void 0!==t?t:0}get numPublishers(){var e,t;return null!==(t=null===(e=this.roomInfo)||void 0===e?void 0:e.numPublishers)&&void 0!==t?t:0}maybeCreateEngine(){this.engine&&!this.engine.isClosed||(this.engine=new lo(this.options),this.engine.on(e.EngineEvent.ParticipantUpdate,this.handleParticipantUpdates).on(e.EngineEvent.RoomUpdate,this.handleRoomUpdate).on(e.EngineEvent.SpeakersChanged,this.handleSpeakersChanged).on(e.EngineEvent.StreamStateChanged,this.handleStreamStateUpdate).on(e.EngineEvent.ConnectionQualityUpdate,this.handleConnectionQualityUpdate).on(e.EngineEvent.SubscriptionError,this.handleSubscriptionError).on(e.EngineEvent.SubscriptionPermissionUpdate,this.handleSubscriptionPermissionUpdate).on(e.EngineEvent.MediaTrackAdded,((e,t,i)=>{this.onTrackAdded(e,t,i)})).on(e.EngineEvent.Disconnected,(e=>{this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e)})).on(e.EngineEvent.ActiveSpeakersUpdate,this.handleActiveSpeakersUpdate).on(e.EngineEvent.DataPacketReceived,this.handleDataPacket).on(e.EngineEvent.Resuming,(()=>{this.clearConnectionReconcile(),this.setAndEmitConnectionState(e.ConnectionState.Reconnecting)&&this.emit(e.RoomEvent.Reconnecting),this.cachedParticipantSids=Array.from(this.participants.keys())})).on(e.EngineEvent.Resumed,(()=>{this.setAndEmitConnectionState(e.ConnectionState.Connected),this.emit(e.RoomEvent.Reconnected),this.registerConnectionReconcile(),this.updateSubscriptions();Array.from(this.participants.values()).filter((e=>!this.cachedParticipantSids.includes(e.sid))).forEach((t=>this.emit(e.RoomEvent.ParticipantConnected,t))),this.cachedParticipantSids=[]})).on(e.EngineEvent.SignalResumed,(()=>{this.state===e.ConnectionState.Reconnecting&&this.sendSyncState()})).on(e.EngineEvent.Restarting,this.handleRestarting).on(e.EngineEvent.SignalRestarted,this.handleSignalRestarted).on(e.EngineEvent.DCBufferStatusChanged,((t,i)=>{this.emit(e.RoomEvent.DCBufferStatusChanged,t,i)})),this.localParticipant&&this.localParticipant.setupEngine(this.engine),this.e2eeManager&&this.e2eeManager.setupEngine(this.engine))}static getLocalDevices(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return Ds.getInstance().getDevices(e,t)}prepareConnection(e){return Qt(this,void 0,void 0,(function*(){yield fetch("http".concat(e.substring(2)),{method:"HEAD"})}))}getParticipantByIdentity(e){if(this.localParticipant.identity===e)return this.localParticipant;const t=this.identityToSid.get(e);return t?this.participants.get(t):void 0}clearConnectionFutures(){this.connectFuture=void 0}simulateScenario(t){return Qt(this,void 0,void 0,(function*(){let i,n=()=>{};switch(t){case"signal-reconnect":yield this.engine.client.handleOnClose("simulate disconnect");break;case"speaker":i=Wn.fromPartial({scenario:{$case:"speakerUpdate",speakerUpdate:3}});break;case"node-failure":i=Wn.fromPartial({scenario:{$case:"nodeFailure",nodeFailure:!0}});break;case"server-leave":i=Wn.fromPartial({scenario:{$case:"serverLeave",serverLeave:!0}});break;case"migration":i=Wn.fromPartial({scenario:{$case:"migration",migration:!0}});break;case"resume-reconnect":this.engine.failNext(),yield this.engine.client.handleOnClose("simulate resume-disconnect");break;case"full-reconnect":this.engine.fullReconnectOnNext=!0,yield this.engine.client.handleOnClose("simulate full-reconnect");break;case"force-tcp":case"force-tls":i=Wn.fromPartial({scenario:{$case:"switchCandidateProtocol",switchCandidateProtocol:"force-tls"===t?2:1}}),n=()=>Qt(this,void 0,void 0,(function*(){const t=this.engine.client.onLeave;t&&t({reason:e.DisconnectReason.CLIENT_INITIATED,canReconnect:!0})}))}i&&(this.engine.client.sendSimulateScenario(i),n())}))}startAudio(){return Qt(this,void 0,void 0,(function*(){yield this.acquireAudioContext();const e=[];if(Wr()){const t="livekit-dummy-audio-el";let i=document.getElementById(t);if(!i){i=document.createElement("audio"),i.autoplay=!0,i.hidden=!0;const e=ds();e.enabled=!0,i.srcObject=new MediaStream([e]),document.body.append(i)}e.push(i)}this.participants.forEach((t=>{t.audioTracks.forEach((t=>{t.track&&t.track.attachedElements.forEach((t=>{e.push(t)}))}))}));try{yield Promise.all(e.map((e=>(e.muted=!1,e.play())))),this.handleAudioPlaybackStarted()}catch(e){throw this.handleAudioPlaybackFailed(e),e}}))}get canPlaybackAudio(){return this.audioEnabled}getActiveAudioOutputDevice(){var e,t;return null!==(t=null===(e=this.options.audioOutput)||void 0===e?void 0:e.deviceId)&&void 0!==t?t:""}getActiveDevice(e){return this.localParticipant.activeDeviceMap.get(e)}switchActiveDevice(t,i){let n=arguments.length>2&&void 0!==arguments[2]&&arguments[2];var r,s,o;return Qt(this,void 0,void 0,(function*(){let a=!1,c=!0;const d=n?{exact:i}:i;if("audioinput"===t){const e=this.options.audioCaptureDefaults.deviceId;this.options.audioCaptureDefaults.deviceId=d,a=e!==d;const t=Array.from(this.localParticipant.audioTracks.values()).filter((e=>e.source===Nr.Source.Microphone));try{c=(yield Promise.all(t.map((e=>{var t;return null===(t=e.audioTrack)||void 0===t?void 0:t.setDeviceId(d)})))).every((e=>!0===e))}catch(t){throw this.options.audioCaptureDefaults.deviceId=e,t}}else if("videoinput"===t){const e=this.options.videoCaptureDefaults.deviceId;this.options.videoCaptureDefaults.deviceId=d,a=e!==d;const t=Array.from(this.localParticipant.videoTracks.values()).filter((e=>e.source===Nr.Source.Camera));try{c=(yield Promise.all(t.map((e=>{var t;return null===(t=e.videoTrack)||void 0===t?void 0:t.setDeviceId(d)})))).every((e=>!0===e))}catch(t){throw this.options.videoCaptureDefaults.deviceId=e,t}}else if("audiooutput"===t){if(!Vr()&&!this.options.expWebAudioMix||this.audioContext&&!("setSinkId"in this.audioContext))throw new Error("cannot switch audio output, setSinkId not supported");null!==(r=(o=this.options).audioOutput)&&void 0!==r||(o.audioOutput={});const e=this.options.audioOutput.deviceId;this.options.audioOutput.deviceId=i,a=e!==d;try{this.options.expWebAudioMix?null===(s=this.audioContext)||void 0===s||s.setSinkId(i):yield Promise.all(Array.from(this.participants.values()).map((e=>e.setAudioOutput({deviceId:i}))))}catch(t){throw this.options.audioOutput.deviceId=e,t}}return a&&c&&(this.localParticipant.activeDeviceMap.set(t,i),this.emit(e.RoomEvent.ActiveDeviceChanged,t,i)),c}))}setupLocalParticipantEvents(){this.localParticipant.on(e.ParticipantEvent.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).on(e.ParticipantEvent.ParticipantNameChanged,this.onLocalParticipantNameChanged).on(e.ParticipantEvent.TrackMuted,this.onLocalTrackMuted).on(e.ParticipantEvent.TrackUnmuted,this.onLocalTrackUnmuted).on(e.ParticipantEvent.LocalTrackPublished,this.onLocalTrackPublished).on(e.ParticipantEvent.LocalTrackUnpublished,this.onLocalTrackUnpublished).on(e.ParticipantEvent.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).on(e.ParticipantEvent.MediaDevicesError,this.onMediaDevicesError).on(e.ParticipantEvent.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged)}recreateEngine(){var e;null===(e=this.engine)||void 0===e||e.close(),this.engine=void 0,this.participants.clear(),this.maybeCreateEngine()}onTrackAdded(t,i,n){if(this.state===e.ConnectionState.Connecting||this.state===e.ConnectionState.Reconnecting){const r=()=>{this.onTrackAdded(t,i,n),s()},s=()=>{this.off(e.RoomEvent.Reconnected,r),this.off(e.RoomEvent.Connected,r),this.off(e.RoomEvent.Disconnected,s)};return this.once(e.RoomEvent.Reconnected,r),this.once(e.RoomEvent.Connected,r),void this.once(e.RoomEvent.Disconnected,s)}if(this.state===e.ConnectionState.Disconnected)return void c.warn("skipping incoming track after Room disconnected");const r=function(e){const t=e.split("|");return t.length>1?[t[0],e.substr(t[0].length+1)]:[e,""]}(i.id),s=r[0];let o=r[1];if(o&&""!==o||(o=t.id),s===this.localParticipant.sid)return void c.warn("tried to create RemoteParticipant for local participant");const a=this.getOrCreateParticipant(s);let d;this.options.adaptiveStream&&(d="object"==typeof this.options.adaptiveStream?this.options.adaptiveStream:{}),a.addSubscribedMediaTrack(t,o,i,n,d)}handleDisconnect(){let t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0],i=arguments.length>1?arguments[1]:void 0;var n;if(this.clearConnectionReconcile(),this.state!==e.ConnectionState.Disconnected)try{this.participants.forEach((e=>{e.tracks.forEach((t=>{e.unpublishTrack(t.trackSid)}))})),this.localParticipant.tracks.forEach((e=>{var i,n;e.track&&this.localParticipant.unpublishTrack(e.track,t),t&&(null===(i=e.track)||void 0===i||i.detach(),null===(n=e.track)||void 0===n||n.stop())})),this.localParticipant.off(e.ParticipantEvent.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).off(e.ParticipantEvent.ParticipantNameChanged,this.onLocalParticipantNameChanged).off(e.ParticipantEvent.TrackMuted,this.onLocalTrackMuted).off(e.ParticipantEvent.TrackUnmuted,this.onLocalTrackUnmuted).off(e.ParticipantEvent.LocalTrackPublished,this.onLocalTrackPublished).off(e.ParticipantEvent.LocalTrackUnpublished,this.onLocalTrackUnpublished).off(e.ParticipantEvent.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).off(e.ParticipantEvent.MediaDevicesError,this.onMediaDevicesError).off(e.ParticipantEvent.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged),this.localParticipant.tracks.clear(),this.localParticipant.videoTracks.clear(),this.localParticipant.audioTracks.clear(),this.participants.clear(),this.activeSpeakers=[],this.audioContext&&"boolean"==typeof this.options.expWebAudioMix&&(this.audioContext.close(),this.audioContext=void 0),Kr()&&(window.removeEventListener("beforeunload",this.onPageLeave),window.removeEventListener("pagehide",this.onPageLeave),window.removeEventListener("freeze",this.onPageLeave),null===(n=navigator.mediaDevices)||void 0===n||n.removeEventListener("devicechange",this.handleDeviceChange))}finally{this.setAndEmitConnectionState(e.ConnectionState.Disconnected),this.emit(e.RoomEvent.Disconnected,i)}}handleParticipantDisconnected(t,i){this.participants.delete(t),i&&(this.identityToSid.delete(i.identity),i.tracks.forEach((e=>{i.unpublishTrack(e.trackSid,!0)})),this.emit(e.RoomEvent.ParticipantDisconnected,i))}acquireAudioContext(){var t,i;return Qt(this,void 0,void 0,(function*(){"boolean"!=typeof this.options.expWebAudioMix&&this.options.expWebAudioMix.audioContext?(this.audioContext=this.options.expWebAudioMix.audioContext,yield this.audioContext.resume()):this.audioContext=null!==(t=Mr())&&void 0!==t?t:void 0,this.options.expWebAudioMix&&this.participants.forEach((e=>e.setAudioContext(this.audioContext)));const n="running"===(null===(i=this.audioContext)||void 0===i?void 0:i.state);n!==this.canPlaybackAudio&&(this.audioEnabled=n,this.emit(e.RoomEvent.AudioPlaybackStatusChanged,n))}))}createParticipant(e,t){let i;return i=t?jo.fromParticipantInfo(this.engine.client,t):new jo(this.engine.client,e,"",void 0,void 0),this.options.expWebAudioMix&&i.setAudioContext(this.audioContext),i}getOrCreateParticipant(t,i){if(this.participants.has(t))return this.participants.get(t);const n=this.createParticipant(t,i);return this.participants.set(t,n),i&&(this.identityToSid.set(i.identity,i.sid),this.emitWhenConnected(e.RoomEvent.ParticipantConnected,n)),n.on(e.ParticipantEvent.TrackPublished,(t=>{this.emitWhenConnected(e.RoomEvent.TrackPublished,t,n)})).on(e.ParticipantEvent.TrackSubscribed,((t,i)=>{t.kind===Nr.Kind.Audio&&(t.on(e.TrackEvent.AudioPlaybackStarted,this.handleAudioPlaybackStarted),t.on(e.TrackEvent.AudioPlaybackFailed,this.handleAudioPlaybackFailed)),this.emit(e.RoomEvent.TrackSubscribed,t,i,n)})).on(e.ParticipantEvent.TrackUnpublished,(t=>{this.emit(e.RoomEvent.TrackUnpublished,t,n)})).on(e.ParticipantEvent.TrackUnsubscribed,((t,i)=>{this.emit(e.RoomEvent.TrackUnsubscribed,t,i,n)})).on(e.ParticipantEvent.TrackSubscriptionFailed,(t=>{this.emit(e.RoomEvent.TrackSubscriptionFailed,t,n)})).on(e.ParticipantEvent.TrackMuted,(t=>{this.emitWhenConnected(e.RoomEvent.TrackMuted,t,n)})).on(e.ParticipantEvent.TrackUnmuted,(t=>{this.emitWhenConnected(e.RoomEvent.TrackUnmuted,t,n)})).on(e.ParticipantEvent.ParticipantMetadataChanged,(t=>{this.emitWhenConnected(e.RoomEvent.ParticipantMetadataChanged,t,n)})).on(e.ParticipantEvent.ParticipantNameChanged,(t=>{this.emitWhenConnected(e.RoomEvent.ParticipantNameChanged,t,n)})).on(e.ParticipantEvent.ConnectionQualityChanged,(t=>{this.emitWhenConnected(e.RoomEvent.ConnectionQualityChanged,t,n)})).on(e.ParticipantEvent.ParticipantPermissionsChanged,(t=>{this.emitWhenConnected(e.RoomEvent.ParticipantPermissionsChanged,t,n)})).on(e.ParticipantEvent.TrackSubscriptionStatusChanged,((t,i)=>{this.emitWhenConnected(e.RoomEvent.TrackSubscriptionStatusChanged,t,i,n)})).on(e.ParticipantEvent.TrackSubscriptionFailed,((t,i)=>{this.emit(e.RoomEvent.TrackSubscriptionFailed,t,n,i)})).on(e.ParticipantEvent.TrackSubscriptionPermissionChanged,((t,i)=>{this.emitWhenConnected(e.RoomEvent.TrackSubscriptionPermissionChanged,t,i,n)})),i&&n.updateInfo(i),n}sendSyncState(){var e,t;if(void 0===this.engine.subscriber||null===this.engine.subscriber.pc.localDescription)return;const i=this.engine.subscriber.pc.localDescription,n=this.engine.subscriber.pc.remoteDescription,r=null===(t=null===(e=this.connOptions)||void 0===e?void 0:e.autoSubscribe)||void 0===t||t,s=new Array;this.participants.forEach((e=>{e.tracks.forEach((e=>{e.isDesired!==r&&s.push(e.trackSid)}))})),this.engine.client.sendSyncState({answer:bs({sdp:i.sdp,type:i.type}),offer:n?bs({sdp:n.sdp,type:n.type}):void 0,subscription:{trackSids:s,subscribe:!r,participantTracks:[]},publishTracks:this.localParticipant.publishedTracksInfo(),dataChannels:this.localParticipant.dataChannelsInfo()})}updateSubscriptions(){for(const e of this.participants.values())for(const t of e.videoTracks.values())t.isSubscribed&&t instanceof Vo&&t.emitTrackUpdate()}registerConnectionReconcile(){this.clearConnectionReconcile();let t=0;this.connectionReconcileInterval=ar.setInterval((()=>{this.engine&&!this.engine.isClosed&&this.engine.verifyTransport()?t=0:(t++,c.warn("detected connection state mismatch",{numFailures:t}),t>=3&&(this.recreateEngine(),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e.DisconnectReason.STATE_MISMATCH)))}),2e3)}clearConnectionReconcile(){this.connectionReconcileInterval&&ar.clearInterval(this.connectionReconcileInterval)}setAndEmitConnectionState(t){return t!==this.state&&(this.state=t,this.emit(e.RoomEvent.ConnectionStateChanged,this.state),!0)}emitWhenConnected(t){if(this.state===e.ConnectionState.Connected){for(var i=arguments.length,n=new Array(i>1?i-1:0),r=1;r<i;r++)n[r-1]=arguments[r];return this.emit(t,...n)}return!1}simulateParticipants(t){var i,n;return Qt(this,void 0,void 0,(function*(){const r=Object.assign({audio:!0,video:!0,useRealTracks:!1},t.publish),s=Object.assign({count:9,audio:!1,video:!0,aspectRatios:[1.66,1.7,1.3]},t.participants);if(this.handleDisconnect(),this.roomInfo={sid:"RM_SIMULATED",name:"simulated-room",emptyTimeout:0,maxParticipants:0,creationTime:(new Date).getTime(),metadata:"",numParticipants:1,numPublishers:1,turnPassword:"",enabledCodecs:[],activeRecording:!1},this.localParticipant.updateInfo(wt.fromPartial({identity:"simulated-local",name:"local-name"})),this.setupLocalParticipantEvents(),this.emit(e.RoomEvent.SignalConnected),this.emit(e.RoomEvent.Connected),this.setAndEmitConnectionState(e.ConnectionState.Connected),r.video){const t=new Fo(Nr.Kind.Video,Nt.fromPartial({source:Ke.CAMERA,sid:Math.floor(1e4*Math.random()).toString(),type:Ge.AUDIO,name:"video-dummy"}),new Io(r.useRealTracks?(yield window.navigator.mediaDevices.getUserMedia({video:!0})).getVideoTracks()[0]:cs(null!==(i=160*s.aspectRatios[0])&&void 0!==i?i:1,160,!0,!0)));this.localParticipant.addTrackPublication(t),this.localParticipant.emit(e.ParticipantEvent.LocalTrackPublished,t)}if(r.audio){const t=new Fo(Nr.Kind.Audio,Nt.fromPartial({source:Ke.MICROPHONE,sid:Math.floor(1e4*Math.random()).toString(),type:Ge.AUDIO}),new fo(r.useRealTracks?(yield navigator.mediaDevices.getUserMedia({audio:!0})).getAudioTracks()[0]:ds()));this.localParticipant.addTrackPublication(t),this.localParticipant.emit(e.ParticipantEvent.LocalTrackPublished,t)}for(let e=0;e<s.count-1;e+=1){let t=wt.fromPartial({sid:Math.floor(1e4*Math.random()).toString(),identity:"simulated-".concat(e),state:et.ACTIVE,tracks:[],joinedAt:Date.now()});const i=this.getOrCreateParticipant(t.identity,t);if(s.video){const r=cs(null!==(n=160*s.aspectRatios[e%s.aspectRatios.length])&&void 0!==n?n:1,160,!1,!0),o=Nt.fromPartial({source:Ke.CAMERA,sid:Math.floor(1e4*Math.random()).toString(),type:Ge.AUDIO});i.addSubscribedMediaTrack(r,o.sid,new MediaStream([r])),t.tracks=[...t.tracks,o]}if(s.audio){const e=ds(),n=Nt.fromPartial({source:Ke.MICROPHONE,sid:Math.floor(1e4*Math.random()).toString(),type:Ge.AUDIO});i.addSubscribedMediaTrack(e,n.sid,new MediaStream([e])),t.tracks=[...t.tracks,n]}i.updateInfo(t)}}))}emit(t){for(var i=arguments.length,n=new Array(i>1?i-1:0),r=1;r<i;r++)n[r-1]=arguments[r];return t!==e.RoomEvent.ActiveSpeakersChanged&&c.debug("room event ".concat(t),{event:t,args:n}),super.emit(t,...n)}}var Qo;!function(e){e[e.IDLE=0]="IDLE",e[e.RUNNING=1]="RUNNING",e[e.SKIPPED=2]="SKIPPED",e[e.SUCCESS=3]="SUCCESS",e[e.FAILED=4]="FAILED"}(Qo||(Qo={}));class Ho extends Yt{constructor(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};super(),this.status=Qo.IDLE,this.logs=[],this.errorsAsWarnings=!1,this.url=e,this.token=t,this.name=this.constructor.name,this.room=new Ko(i.roomOptions),this.connectOptions=i.connectOptions,i.errorsAsWarnings&&(this.errorsAsWarnings=i.errorsAsWarnings)}run(e){return Qt(this,void 0,void 0,(function*(){if(this.status!==Qo.IDLE)throw Error("check is running already");this.setStatus(Qo.RUNNING),this.appendMessage("".concat(this.name," started."));try{yield this.perform()}catch(e){e instanceof Error&&(this.errorsAsWarnings?this.appendWarning(e.message):this.appendError(e.message))}return yield this.disconnect(),yield new Promise((e=>setTimeout(e,500))),this.status!==Qo.SKIPPED&&this.setStatus(this.isSuccess()?Qo.SUCCESS:Qo.FAILED),e&&e(),this.getInfo()}))}isSuccess(){return!this.logs.some((e=>"error"===e.level))}connect(){return Qt(this,void 0,void 0,(function*(){return this.room.state===e.ConnectionState.Connected||(yield this.room.connect(this.url,this.token)),this.room}))}disconnect(){return Qt(this,void 0,void 0,(function*(){this.room&&this.room.state!==e.ConnectionState.Disconnected&&(yield this.room.disconnect(),yield new Promise((e=>setTimeout(e,500))))}))}skip(){this.setStatus(Qo.SKIPPED)}appendMessage(e){this.logs.push({level:"info",message:e}),this.emit("update",this.getInfo())}appendWarning(e){this.logs.push({level:"warning",message:e}),this.emit("update",this.getInfo())}appendError(e){this.logs.push({level:"error",message:e}),this.emit("update",this.getInfo())}setStatus(e){this.status=e,this.emit("update",this.getInfo())}get engine(){var e;return null===(e=this.room)||void 0===e?void 0:e.engine}getInfo(){return{logs:this.logs,name:this.name,status:this.status,description:this.description}}}function Zo(e){var t,i;return Qt(this,void 0,void 0,(function*(){null!=e||(e={}),null!==(t=e.audio)&&void 0!==t||(e.audio=!0),null!==(i=e.video)&&void 0!==i||(e.video=!0);const n=Ur(Dr(e,io,no)),r=navigator.mediaDevices.getUserMedia(n);e.audio&&(Ds.userMediaPromiseMap.set("audioinput",r),r.catch((()=>Ds.userMediaPromiseMap.delete("audioinput")))),e.video&&(Ds.userMediaPromiseMap.set("videoinput",r),r.catch((()=>Ds.userMediaPromiseMap.delete("videoinput"))));const s=yield r;return s.getTracks().map((t=>{const i="audio"===t.kind;let r;i?e.audio:e.video;const o=i?n.audio:n.video;"boolean"!=typeof o&&(r=o);const a=vo(t,r);return a.kind===Nr.Kind.Video?a.source=Nr.Source.Camera:a.kind===Nr.Kind.Audio&&(a.source=Nr.Source.Microphone),a.mediaStream=s,a}))}))}function zo(e){return Qt(this,void 0,void 0,(function*(){return(yield Zo({audio:!1,video:e}))[0]}))}function Yo(e){return Qt(this,void 0,void 0,(function*(){return(yield Zo({audio:e,video:!1}))[0]}))}class Xo extends Ho{get description(){return"Can publish audio"}perform(){var e;return Qt(this,void 0,void 0,(function*(){const t=yield this.connect(),i=yield Yo();t.localParticipant.publishTrack(i),yield new Promise((e=>setTimeout(e,3e3)));const n=yield null===(e=i.sender)||void 0===e?void 0:e.getStats();if(!n)throw new Error("Could not get RTCStats");let r=0;if(n.forEach((e=>{"outbound-rtp"===e.type&&"audio"===e.mediaType&&(r=e.packetsSent)})),0===r)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(r," audio packets"))}))}}class ea extends Ho{get description(){return"Can publish video"}perform(){var e;return Qt(this,void 0,void 0,(function*(){const t=yield this.connect(),i=yield zo();t.localParticipant.publishTrack(i),yield new Promise((e=>setTimeout(e,3e3)));const n=yield null===(e=i.sender)||void 0===e?void 0:e.getStats();if(!n)throw new Error("Could not get RTCStats");let r=0;if(n.forEach((e=>{"outbound-rtp"===e.type&&"video"===e.mediaType&&(r=e.packetsSent)})),0===r)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(r," video packets"))}))}}class ta extends Ho{get description(){return"Resuming connection after interruption"}perform(){var t;return Qt(this,void 0,void 0,(function*(){const i=yield this.connect();let n,r=!1,s=!1;const o=new Promise((e=>{setTimeout(e,5e3),n=e}));i.on(e.RoomEvent.Reconnecting,(()=>{r=!0})).on(e.RoomEvent.Reconnected,(()=>{s=!0,n(!0)})),null===(t=i.engine.client.ws)||void 0===t||t.close();const a=i.engine.client.onClose;if(a&&a(""),yield o,!r)throw new Error("Did not attempt to reconnect");if(!s||i.state!==e.ConnectionState.Connected)throw this.appendWarning("reconnection is only possible in Redis-based configurations"),new Error("Not able to reconnect")}))}}class ia extends Ho{get description(){return"Can connect via TURN"}perform(){var e,t;return Qt(this,void 0,void 0,(function*(){const i=new vs,n=yield i.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1});let r=!1,s=!1,o=!1;for(let e of n.iceServers)for(let t of e.urls)t.startsWith("turn:")?(s=!0,o=!0):t.startsWith("turns:")&&(s=!0,o=!0,r=!0),t.startsWith("stun:")&&(o=!0);o?s&&!r&&this.appendWarning("TURN is configured server side, but TURN/TLS is unavailable."):this.appendWarning("No STUN servers configured on server side."),yield i.close(),(null===(t=null===(e=this.connectOptions)||void 0===e?void 0:e.rtcConfig)||void 0===t?void 0:t.iceServers)||s?yield this.room.connect(this.url,this.token,{rtcConfig:{iceTransportPolicy:"relay"}}):(this.appendWarning("No TURN servers configured."),this.skip(),yield new Promise((e=>setTimeout(e,0))))}))}}class na extends Ho{get description(){return"Establishing WebRTC connection"}perform(){return Qt(this,void 0,void 0,(function*(){try{console.log("initiating room connection"),this.room=yield this.connect(),console.log("now the room is connected")}catch(e){throw this.appendWarning("ports need to be open on firewall in order to connect."),e}}))}}class ra extends Ho{get description(){return"Connecting to signal connection via WebSocket"}perform(){return Qt(this,void 0,void 0,(function*(){(this.url.startsWith("ws:")||this.url.startsWith("http:"))&&this.appendWarning("Server is insecure, clients may block connections to it");let e=new vs;const t=yield e.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1});this.appendMessage("Connected to server, version ".concat(t.serverVersion,".")),yield e.close()}))}}const sa=new Map([["obs virtual camera",{facingMode:"environment",confidence:"medium"}]]),oa=new Map([["iphone",{facingMode:"environment",confidence:"medium"}],["ipad",{facingMode:"environment",confidence:"medium"}]]);function aa(e){var t;const i=e.trim().toLowerCase();if(""!==i)return sa.has(i)?sa.get(i):null===(t=Array.from(oa.entries()).find((e=>{let[t]=e;return i.includes(t)})))||void 0===t?void 0:t[1]}e.BaseKeyProvider=Ns,e.ConnectionCheck=class extends Yt{constructor(e,t){super(),this.checkResults=new Map,this.url=e,this.token=t}getNextCheckId(){const e=this.checkResults.size;return this.checkResults.set(e,{logs:[],status:Qo.IDLE,name:"",description:""}),e}updateCheck(e,t){this.checkResults.set(e,t),this.emit("checkUpdate",e,t)}isSuccess(){return Array.from(this.checkResults.values()).every((e=>e.status!==Qo.FAILED))}getResults(){return Array.from(this.checkResults.values())}createAndRunCheck(e){return Qt(this,void 0,void 0,(function*(){const t=this.getNextCheckId(),i=new e(this.url,this.token),n=e=>{this.updateCheck(t,e)};i.on("update",n);const r=yield i.run();return i.off("update",n),r}))}checkWebsocket(){return Qt(this,void 0,void 0,(function*(){return this.createAndRunCheck(ra)}))}checkWebRTC(){return Qt(this,void 0,void 0,(function*(){return this.createAndRunCheck(na)}))}checkTURN(){return Qt(this,void 0,void 0,(function*(){return this.createAndRunCheck(ia)}))}checkReconnect(){return Qt(this,void 0,void 0,(function*(){return this.createAndRunCheck(ta)}))}checkPublishAudio(){return Qt(this,void 0,void 0,(function*(){return this.createAndRunCheck(Xo)}))}checkPublishVideo(){return Qt(this,void 0,void 0,(function*(){return this.createAndRunCheck(ea)}))}},e.ConnectionError=tr,e.CriticalTimers=ar,e.CryptorEvent={Error:"cryptorError"},e.DefaultReconnectPolicy=Kt,e.DeviceUnsupportedError=ir,e.EncryptionEvent=Os,e.ExternalE2EEKeyProvider=class extends Ns{constructor(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};super(Object.assign(Object.assign({},e),{sharedKey:!0}))}setKey(e){return Qt(this,void 0,void 0,(function*(){const t=yield Ps(e);this.onSetEncryptionKey(t)}))}},e.LivekitError=er,e.LocalAudioTrack=fo,e.LocalParticipant=qo,e.LocalTrack=As,e.LocalTrackPublication=Fo,e.LocalVideoTrack=Io,e.NegotiationError=or,e.Participant=$o,e.PublishDataError=class extends er{constructor(e){super(13,null!=e?e:"unable to publish data")}},e.RemoteAudioTrack=Lo,e.RemoteParticipant=jo,e.RemoteTrack=Mo,e.RemoteTrackPublication=Vo,e.RemoteVideoTrack=_o,e.Room=Ko,e.RoomState=Go,e.ScreenSharePresets=Cr,e.Track=Nr,e.TrackInvalidError=nr,e.TrackPublication=Jo,e.UnexpectedConnectionState=sr,e.UnsupportedServer=rr,e.VideoPreset=mr,e.VideoPresets=yr,e.VideoPresets43=Sr,e.attachToElement=Or,e.createAudioAnalyser=function(e,t){const i=Object.assign({cloneTrack:!1,fftSize:2048,smoothingTimeConstant:.8,minDecibels:-100,maxDecibels:-80},t),n=Mr();if(!n)throw new Error("Audio Context not supported on this browser");const r=i.cloneTrack?e.mediaStreamTrack.clone():e.mediaStreamTrack,s=n.createMediaStreamSource(new MediaStream([r])),o=n.createAnalyser();o.minDecibels=i.minDecibels,o.maxDecibels=i.maxDecibels,o.fftSize=i.fftSize,o.smoothingTimeConstant=i.smoothingTimeConstant,s.connect(o);const a=new Uint8Array(o.frequencyBinCount);return{calculateVolume:()=>{o.getByteFrequencyData(a);let e=0;for(const t of a)e+=Math.pow(t/255,2);return Math.sqrt(e/a.length)},analyser:o,cleanup:()=>{n.close(),i.cloneTrack&&r.stop()}}},e.createE2EEKey=function(){return window.crypto.getRandomValues(new Uint8Array(32))},e.createKeyMaterialFromString=Ps,e.createLocalAudioTrack=Yo,e.createLocalScreenTracks=function(e){var t;return Qt(this,void 0,void 0,(function*(){void 0===e&&(e={}),void 0===e.resolution&&(e.resolution=yr.h1080.resolution);let i=!0;if(e.resolution&&(i={width:e.resolution.width,height:e.resolution.height}),void 0===navigator.mediaDevices.getDisplayMedia)throw new ir("getDisplayMedia not supported");const n=yield navigator.mediaDevices.getDisplayMedia({audio:null!==(t=e.audio)&&void 0!==t&&t,video:i}),r=n.getVideoTracks();if(0===r.length)throw new nr("no video track found");const s=new Io(r[0],void 0,!1);s.source=Nr.Source.ScreenShare;const o=[s];if(n.getAudioTracks().length>0){const e=new fo(n.getAudioTracks()[0],void 0,!1);e.source=Nr.Source.ScreenShareAudio,o.push(e)}return o}))},e.createLocalTracks=Zo,e.createLocalVideoTrack=zo,e.deriveKeys=function(e,t){return Qt(this,void 0,void 0,(function*(){const i=ws(e.algorithm.name,t),n=yield crypto.subtle.deriveKey(i,e,{name:ks,length:128},!1,["encrypt","decrypt"]);return{material:e,encryptionKey:n}}))},e.detachTrack=Ir,e.facingModeFromDeviceLabel=aa,e.facingModeFromLocalTrack=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};var i;const n=e instanceof As?e.mediaStreamTrack:e,r=n.getSettings();let s={facingMode:null!==(i=t.defaultFacingMode)&&void 0!==i?i:"user",confidence:"low"};if("facingMode"in r){const e=r.facingMode;a.debug("rawFacingMode",{rawFacingMode:e}),e&&"string"==typeof e&&function(e){const t=["user","environment","left","right"];return void 0===e||t.includes(e)}(e)&&(s={facingMode:e,confidence:"high"})}if(["low","medium"].includes(s.confidence)){a.debug("Try to get facing mode from device label: (".concat(n.label,")"));const e=aa(n.label);void 0!==e&&(s=e)}return s},e.getEmptyAudioStreamTrack=ds,e.getEmptyVideoStreamTrack=function(){return os||(os=cs()),os.clone()},e.importKey=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{name:ks},i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"encrypt";return Qt(this,void 0,void 0,(function*(){return crypto.subtle.importKey("raw",e,t,!1,"derive"===i?["deriveBits","deriveKey"]:["encrypt","decrypt"])}))},e.isBackupCodec=gr,e.isBrowserSupported=function(){return xr()||Br()},e.isCodecEqual=br,e.isE2EESupported=Cs,e.isInsertableStreamSupported=Ts,e.isScriptTransformSupported=Es,e.isVideoFrame=function(e){return"type"in e},e.mimeTypeToVideoCodecString=Rs,e.protocolVersion=9,e.ratchet=function(e,t){return Qt(this,void 0,void 0,(function*(){const i=ws(e.algorithm.name,t);return crypto.subtle.deriveBits(i,e,256)}))},e.setLogExtension=function(t){const i=c.methodFactory;c.methodFactory=(n,r,s)=>{const o=i(n,r,s),a=e.LogLevel[n],c=a>=r&&a<e.LogLevel.silent;return(e,i)=>{i?o(e,i):o(e),c&&t(a,e,i)}},c.setLevel(c.getLevel())},e.setLogLevel=function(e,t){t&&o.getLogger(t).setLevel(e);for(const t of Object.values(o.getLoggers()))t.setLevel(e)},e.supportsAV1=Jr,e.supportsAdaptiveStream=function(){return void 0!==typeof ResizeObserver&&void 0!==typeof IntersectionObserver},e.supportsDynacast=function(){return xr()},e.supportsVP9=Fr,e.version=pr,e.videoCodecs=vr}));
|
2
2
|
//# sourceMappingURL=livekit-client.umd.js.map
|