diff --git a/Bridge~/package-lock.json b/Bridge~/package-lock.json index 93cdc36..6c12fe9 100644 --- a/Bridge~/package-lock.json +++ b/Bridge~/package-lock.json @@ -1,15 +1,15 @@ { "name": "@livekit/livekit-unity", - "version": "0.1.10", + "version": "0.2.1", "lockfileVersion": 2, "requires": true, "packages": { "": { "name": "@livekit/livekit-unity", - "version": "0.1.10", + "version": "0.2.1", "license": "ISC", "dependencies": { - "livekit-client": "^0.18.2", + "livekit-client": "^1.0.0", "typed-emitter": "^2.1.0" }, "devDependencies": { @@ -914,9 +914,9 @@ } }, "node_modules/livekit-client": { - "version": "0.18.2", - "resolved": "https://registry.npmjs.org/livekit-client/-/livekit-client-0.18.2.tgz", - "integrity": "sha512-+uJhjAVoCJxytJxSgx/eUZxuuNsw3ReoNcFNqcLfPlHiI6CcQyAu1254kcLbS1azeuEz3DHnJKK7KFTnZJ47xQ==", + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/livekit-client/-/livekit-client-1.0.0.tgz", + "integrity": "sha512-UGcN1/B8LvBOy0bz1IPmntS91HTMLOjiZtCJJ2PcE/DhU4yS8g+A0CCTtZiCI3d51cjzLOQcY71G1I35uDBXZA==", "dependencies": { "events": "^3.3.0", "loglevel": "^1.8.0", @@ -2434,9 +2434,9 @@ "dev": true }, "livekit-client": { - "version": "0.18.2", - "resolved": "https://registry.npmjs.org/livekit-client/-/livekit-client-0.18.2.tgz", - "integrity": "sha512-+uJhjAVoCJxytJxSgx/eUZxuuNsw3ReoNcFNqcLfPlHiI6CcQyAu1254kcLbS1azeuEz3DHnJKK7KFTnZJ47xQ==", + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/livekit-client/-/livekit-client-1.0.0.tgz", + "integrity": "sha512-UGcN1/B8LvBOy0bz1IPmntS91HTMLOjiZtCJJ2PcE/DhU4yS8g+A0CCTtZiCI3d51cjzLOQcY71G1I35uDBXZA==", "requires": { "events": "^3.3.0", "loglevel": "^1.8.0", diff --git a/Bridge~/package.json b/Bridge~/package.json index 0787b82..4e5f5a1 100644 --- a/Bridge~/package.json +++ b/Bridge~/package.json @@ -1,6 +1,6 @@ { "name": "@livekit/livekit-unity", - "version": "0.2.1", + "version": "1.0.0", "description": "LiveKit Unity Bridge for WebGL", "main": "dist/index.js", "source": "src/index.ts", @@ -16,7 +16,7 @@ "author": "", "license": "ISC", "dependencies": { - "livekit-client": "^0.18.2", + "livekit-client": "^1.0.0", "typed-emitter": "^2.1.0" }, "devDependencies": { diff --git a/README.md b/README.md index 9393ad5..e73329a 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ This package only works on the WebGL platform of Unity ## Docs Docs and guides at https://docs.livekit.io -As this package is a bridge to [client-sdk-js](https://github.com/livekit/client-sdk-js), you can use its [SDK reference](https://docs.livekit.io/client-sdk-js/) +[SDK reference](https://livekit.github.io/client-sdk-unity-web/) ## Installation : Follow this [unity tutorial](https://docs.unity3d.com/Manual/upm-ui-giturl.html) using the `https://github.com/livekit/client-sdk-unity-web.git` link. diff --git a/Runtime/Plugins/livekit-client.jspre b/Runtime/Plugins/livekit-client.jspre index 17b2b04..73cb14c 100644 --- a/Runtime/Plugins/livekit-client.jspre +++ b/Runtime/Plugins/livekit-client.jspre @@ -1 +1 @@ -(()=>{"use strict";var e,t={},i={};function __webpack_require__(e){var n=i[e];if(void 0!==n)return n.exports;var s=i[e]={exports:{}};return t[e](s,s.exports,__webpack_require__),s.exports}__webpack_require__.m=t,e=[],__webpack_require__.O=(t,i,n,s)=>{if(!i){var a=1/0;for(l=0;l=s)&&Object.keys(__webpack_require__.O).every((e=>__webpack_require__.O[e](i[c])))?i.splice(c--,1):(o=!1,s0&&e[l-1][2]>s;l--)e[l]=e[l-1];e[l]=[i,n,s]},__webpack_require__.d=(e,t)=>{for(var i in t)__webpack_require__.o(t,i)&&!__webpack_require__.o(e,i)&&Object.defineProperty(e,i,{enumerable:!0,get:t[i]})},__webpack_require__.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),__webpack_require__.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),__webpack_require__.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},(()=>{var e={588:0};__webpack_require__.O.j=t=>0===e[t];var webpackJsonpCallback=(t,i)=>{var n,s,[a,o,c]=i,u=0;if(a.some((t=>0!==e[t]))){for(n in o)__webpack_require__.o(o,n)&&(__webpack_require__.m[n]=o[n]);if(c)var l=c(__webpack_require__)}for(t&&t(i);uFt,ConnectionError:()=>ConnectionError,ConnectionQuality:()=>qt,DataPacket_Kind:()=>Ce,EngineEvent:()=>Pt,LivekitError:()=>LivekitError,LocalAudioTrack:()=>LocalAudioTrack,LocalParticipant:()=>LocalParticipant,LocalTrack:()=>LocalTrack,LocalTrackPublication:()=>LocalTrackPublication,LocalVideoTrack:()=>LocalVideoTrack,LogLevel:()=>c,MediaDeviceFailure:()=>Tt,Participant:()=>Participant,ParticipantEvent:()=>Ct,PublishDataError:()=>PublishDataError,RemoteAudioTrack:()=>RemoteAudioTrack,RemoteParticipant:()=>RemoteParticipant,RemoteTrack:()=>RemoteTrack,RemoteTrackPublication:()=>RemoteTrackPublication,RemoteVideoTrack:()=>RemoteVideoTrack,Room:()=>Room,RoomEvent:()=>wt,RoomState:()=>mi,ScreenSharePresets:()=>$t,Track:()=>Track,TrackEvent:()=>Et,TrackInvalidError:()=>TrackInvalidError,TrackPublication:()=>TrackPublication,UnexpectedConnectionState:()=>UnexpectedConnectionState,UnsupportedServer:()=>UnsupportedServer,VideoPreset:()=>VideoPreset,VideoPresets:()=>Vt,VideoPresets43:()=>jt,VideoQuality:()=>ke,attachToElement:()=>attachToElement,connect:()=>connect,createLocalAudioTrack:()=>createLocalAudioTrack,createLocalScreenTracks:()=>createLocalScreenTracks,createLocalTracks:()=>createLocalTracks,createLocalVideoTrack:()=>createLocalVideoTrack,detachTrack:()=>detachTrack,protocolVersion:()=>_t,setLogExtension:()=>setLogExtension,setLogLevel:()=>setLogLevel,version:()=>Nt});var s,a,o,c,u="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:void 0!==__webpack_require__.g?__webpack_require__.g:"undefined"!=typeof self?self:{},l={exports:{}};a=u,o=function(){var noop=function(){},e="undefined",t=typeof window!==e&&typeof window.navigator!==e&&/Trident\/|MSIE /.test(window.navigator.userAgent),i=["trace","debug","info","warn","error"];function bindMethod(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 traceForIE(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function realMethod(i){return"debug"===i&&(i="log"),typeof console!==e&&("trace"===i&&t?traceForIE:void 0!==console[i]?bindMethod(console,i):void 0!==console.log?bindMethod(console,"log"):noop)}function replaceLoggingMethods(e,t){for(var n=0;n=0&&n<=o.levels.SILENT))throw"log.setLevel() called with invalid level: "+n;if(a=n,!1!==s&&function persistLevelIfPossible(t){var n=(i[t]||"silent").toUpperCase();if(typeof window!==e&&c){try{return void(window.localStorage[c]=n)}catch(e){}try{window.document.cookie=encodeURIComponent(c)+"="+n+";"}catch(e){}}}(n),replaceLoggingMethods.call(o,n,t),typeof console===e&&n{const a=t(i,n,s),o=h.getLevel(),u=n>=o&&n{i?a(t,i):a(t),u&&e(n,t,i)}},h.setLevel(h.getLevel())}h.setLevel(c.info);var p=Long,m=null;try{m=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 Long(e,t,i){this.low=0|e,this.high=0|t,this.unsigned=!!i}function isLong(e){return!0===(e&&e.__isLong__)}Long.prototype.__isLong__,Object.defineProperty(Long.prototype,"__isLong__",{value:!0}),Long.isLong=isLong;var g={},v={};function fromInt(e,t){var i,n,s;return t?(s=0<=(e>>>=0)&&e<256)&&(n=v[e])?n:(i=fromBits(e,(0|e)<0?-1:0,!0),s&&(v[e]=i),i):(s=-128<=(e|=0)&&e<128)&&(n=g[e])?n:(i=fromBits(e,e<0?-1:0,!1),s&&(g[e]=i),i)}function fromNumber(e,t){if(isNaN(e))return t?C:w;if(t){if(e<0)return C;if(e>=k)return N}else{if(e<=-y)return _;if(e+1>=y)return O}return e<0?fromNumber(-e,t).neg():fromBits(e%b|0,e/b|0,t)}function fromBits(e,t,i){return new Long(e,t,i)}Long.fromInt=fromInt,Long.fromNumber=fromNumber,Long.fromBits=fromBits;var S=Math.pow;function fromString(e,t,i){if(0===e.length)throw Error("empty string");if("NaN"===e||"Infinity"===e||"+Infinity"===e||"-Infinity"===e)return w;if("number"==typeof t?(i=t,t=!1):t=!!t,(i=i||10)<2||360)throw Error("interior hyphen");if(0===n)return fromString(e.substring(1),t,i).neg();for(var s=fromNumber(S(i,8)),a=w,o=0;o>>0:this.low},L.toNumber=function toNumber(){return this.unsigned?(this.high>>>0)*b+(this.low>>>0):this.high*b+(this.low>>>0)},L.toString=function toString(e){if((e=e||10)<2||36>>0).toString(e);if((a=c).isZero())return u+o;for(;u.length<6;)u="0"+u;o=""+u+o}},L.getHighBits=function getHighBits(){return this.high},L.getHighBitsUnsigned=function getHighBitsUnsigned(){return this.high>>>0},L.getLowBits=function getLowBits(){return this.low},L.getLowBitsUnsigned=function getLowBitsUnsigned(){return this.low>>>0},L.getNumBitsAbs=function getNumBitsAbs(){if(this.isNegative())return this.eq(_)?64:this.neg().getNumBitsAbs();for(var e=0!=this.high?this.high:this.low,t=31;t>0&&0==(e&1<=0},L.isOdd=function isOdd(){return 1==(1&this.low)},L.isEven=function isEven(){return 0==(1&this.low)},L.equals=function equals(e){return isLong(e)||(e=fromValue(e)),(this.unsigned===e.unsigned||this.high>>>31!=1||e.high>>>31!=1)&&(this.high===e.high&&this.low===e.low)},L.eq=L.equals,L.notEquals=function notEquals(e){return!this.eq(e)},L.neq=L.notEquals,L.ne=L.notEquals,L.lessThan=function lessThan(e){return this.comp(e)<0},L.lt=L.lessThan,L.lessThanOrEqual=function lessThanOrEqual(e){return this.comp(e)<=0},L.lte=L.lessThanOrEqual,L.le=L.lessThanOrEqual,L.greaterThan=function greaterThan(e){return this.comp(e)>0},L.gt=L.greaterThan,L.greaterThanOrEqual=function greaterThanOrEqual(e){return this.comp(e)>=0},L.gte=L.greaterThanOrEqual,L.ge=L.greaterThanOrEqual,L.compare=function compare(e){if(isLong(e)||(e=fromValue(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},L.comp=L.compare,L.negate=function negate(){return!this.unsigned&&this.eq(_)?_:this.not().add(P)},L.neg=L.negate,L.add=function add(e){isLong(e)||(e=fromValue(e));var t=this.high>>>16,i=65535&this.high,n=this.low>>>16,s=65535&this.low,a=e.high>>>16,o=65535&e.high,c=e.low>>>16,u=0,l=0,h=0,p=0;return h+=(p+=s+(65535&e.low))>>>16,l+=(h+=n+c)>>>16,u+=(l+=i+o)>>>16,u+=t+a,fromBits((h&=65535)<<16|(p&=65535),(u&=65535)<<16|(l&=65535),this.unsigned)},L.subtract=function subtract(e){return isLong(e)||(e=fromValue(e)),this.add(e.neg())},L.sub=L.subtract,L.multiply=function multiply(e){if(this.isZero())return w;if(isLong(e)||(e=fromValue(e)),m)return fromBits(m.mul(this.low,this.high,e.low,e.high),m.get_high(),this.unsigned);if(e.isZero())return w;if(this.eq(_))return e.isOdd()?_:w;if(e.eq(_))return this.isOdd()?_:w;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 fromNumber(this.toNumber()*e.toNumber(),this.unsigned);var t=this.high>>>16,i=65535&this.high,n=this.low>>>16,s=65535&this.low,a=e.high>>>16,o=65535&e.high,c=e.low>>>16,u=65535&e.low,l=0,h=0,p=0,g=0;return p+=(g+=s*u)>>>16,h+=(p+=n*u)>>>16,p&=65535,h+=(p+=s*c)>>>16,l+=(h+=i*u)>>>16,h&=65535,l+=(h+=n*c)>>>16,h&=65535,l+=(h+=s*o)>>>16,l+=t*u+i*c+n*o+s*a,fromBits((p&=65535)<<16|(g&=65535),(l&=65535)<<16|(h&=65535),this.unsigned)},L.mul=L.multiply,L.divide=function divide(e){if(isLong(e)||(e=fromValue(e)),e.isZero())throw Error("division by zero");var t,i,n;if(m)return this.unsigned||-2147483648!==this.high||-1!==e.low||-1!==e.high?fromBits((this.unsigned?m.div_u:m.div_s)(this.low,this.high,e.low,e.high),m.get_high(),this.unsigned):this;if(this.isZero())return this.unsigned?C:w;if(this.unsigned){if(e.unsigned||(e=e.toUnsigned()),e.gt(this))return C;if(e.gt(this.shru(1)))return E;n=C}else{if(this.eq(_))return e.eq(P)||e.eq(R)?_:e.eq(_)?P:(t=this.shr(1).div(e).shl(1)).eq(w)?e.isNegative()?P:R:(i=this.sub(e.mul(t)),n=t.add(i.div(e)));if(e.eq(_))return this.unsigned?C:w;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=w}for(i=this;i.gte(e);){t=Math.max(1,Math.floor(i.toNumber()/e.toNumber()));for(var s=Math.ceil(Math.log(t)/Math.LN2),a=s<=48?1:S(2,s-48),o=fromNumber(t),c=o.mul(e);c.isNegative()||c.gt(i);)c=(o=fromNumber(t-=a,this.unsigned)).mul(e);o.isZero()&&(o=P),n=n.add(o),i=i.sub(c)}return n},L.div=L.divide,L.modulo=function modulo(e){return isLong(e)||(e=fromValue(e)),m?fromBits((this.unsigned?m.rem_u:m.rem_s)(this.low,this.high,e.low,e.high),m.get_high(),this.unsigned):this.sub(this.div(e).mul(e))},L.mod=L.modulo,L.rem=L.modulo,L.not=function not(){return fromBits(~this.low,~this.high,this.unsigned)},L.and=function and(e){return isLong(e)||(e=fromValue(e)),fromBits(this.low&e.low,this.high&e.high,this.unsigned)},L.or=function or(e){return isLong(e)||(e=fromValue(e)),fromBits(this.low|e.low,this.high|e.high,this.unsigned)},L.xor=function xor(e){return isLong(e)||(e=fromValue(e)),fromBits(this.low^e.low,this.high^e.high,this.unsigned)},L.shiftLeft=function shiftLeft(e){return isLong(e)&&(e=e.toInt()),0==(e&=63)?this:e<32?fromBits(this.low<>>32-e,this.unsigned):fromBits(0,this.low<>>e|this.high<<32-e,this.high>>e,this.unsigned):fromBits(this.high>>e-32,this.high>=0?0:-1,this.unsigned)},L.shr=L.shiftRight,L.shiftRightUnsigned=function shiftRightUnsigned(e){if(isLong(e)&&(e=e.toInt()),0===(e&=63))return this;var t=this.high;return e<32?fromBits(this.low>>>e|t<<32-e,t>>>e,this.unsigned):fromBits(32===e?t:t>>>e-32,0,this.unsigned)},L.shru=L.shiftRightUnsigned,L.shr_u=L.shiftRightUnsigned,L.toSigned=function toSigned(){return this.unsigned?fromBits(this.low,this.high,!1):this},L.toUnsigned=function toUnsigned(){return this.unsigned?this:fromBits(this.low,this.high,!0)},L.toBytes=function toBytes(e){return e?this.toBytesLE():this.toBytesBE()},L.toBytesLE=function toBytesLE(){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]},L.toBytesBE=function toBytesBE(){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]},Long.fromBytes=function fromBytes(e,t,i){return i?Long.fromBytesLE(e,t):Long.fromBytesBE(e,t)},Long.fromBytesLE=function fromBytesLE(e,t){return new Long(e[0]|e[1]<<8|e[2]<<16|e[3]<<24,e[4]|e[5]<<8|e[6]<<16|e[7]<<24,t)},Long.fromBytesBE=function fromBytesBE(e,t){return new Long(e[4]<<24|e[5]<<16|e[6]<<8|e[7],e[0]<<24|e[1]<<16|e[2]<<8|e[3],t)};var D={},A={},I=function asPromise(e,t){var i=new Array(arguments.length-1),n=0,s=2,a=!0;for(;s1&&"="===e.charAt(t);)++i;return Math.ceil(3*e.length)/4-i};for(var i=new Array(64),n=new Array(123),s=0;s<64;)n[i[s]=s<26?s+65:s<52?s+71:s<62?s-4:s-59|43]=s++;t.encode=function encode(e,t,n){for(var s,a=null,o=[],c=0,u=0;t>2],s=(3&l)<<4,u=1;break;case 1:o[c++]=i[s|l>>4],s=(15&l)<<2,u=2;break;case 2:o[c++]=i[s|l>>6],o[c++]=i[63&l],u=0}c>8191&&((a||(a=[])).push(String.fromCharCode.apply(String,o)),c=0)}return u&&(o[c++]=i[s],o[c++]=61,1===u&&(o[c++]=61)),a?(c&&a.push(String.fromCharCode.apply(String,o.slice(0,c))),a.join("")):String.fromCharCode.apply(String,o.slice(0,c))};var a="invalid encoding";t.decode=function decode(e,t,i){for(var s,o=i,c=0,u=0;u1)break;if(void 0===(l=n[l]))throw Error(a);switch(c){case 0:s=l,c=1;break;case 1:t[i++]=s<<2|(48&l)>>4,s=l,c=2;break;case 2:t[i++]=(15&s)<<4|(60&l)>>2,s=l,c=3;break;case 3:t[i++]=(3&s)<<6|l,c=0}}if(1===c)throw Error(a);return i-o},t.test=function test(e){return/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(e)}}(U);var M=EventEmitter$1;function EventEmitter$1(){this._listeners={}}EventEmitter$1.prototype.on=function on(e,t,i){return(this._listeners[e]||(this._listeners[e]=[])).push({fn:t,ctx:i||this}),this},EventEmitter$1.prototype.off=function off(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;n0?0:2147483648,i,n);else if(isNaN(t))e(2143289344,i,n);else if(t>34028234663852886e22)e((s<<31|2139095040)>>>0,i,n);else if(t<11754943508222875e-54)e((s<<31|Math.round(t/1401298464324817e-60))>>>0,i,n);else{var a=Math.floor(Math.log(t)/Math.LN2);e((s<<31|a+127<<23|8388607&Math.round(t*Math.pow(2,-a)*8388608))>>>0,i,n)}}function readFloat_ieee754(e,t,i){var n=e(t,i),s=2*(n>>31)+1,a=n>>>23&255,o=8388607&n;return 255===a?o?NaN:s*(1/0):0===a?1401298464324817e-60*s*o:s*Math.pow(2,a-150)*(o+8388608)}e.writeFloatLE=writeFloat_ieee754.bind(null,writeUintLE),e.writeFloatBE=writeFloat_ieee754.bind(null,writeUintBE),e.readFloatLE=readFloat_ieee754.bind(null,readUintLE),e.readFloatBE=readFloat_ieee754.bind(null,readUintBE)}(),"undefined"!=typeof Float64Array?function(){var t=new Float64Array([-0]),i=new Uint8Array(t.buffer),n=128===i[7];function writeDouble_f64_cpy(e,n,s){t[0]=e,n[s]=i[0],n[s+1]=i[1],n[s+2]=i[2],n[s+3]=i[3],n[s+4]=i[4],n[s+5]=i[5],n[s+6]=i[6],n[s+7]=i[7]}function writeDouble_f64_rev(e,n,s){t[0]=e,n[s]=i[7],n[s+1]=i[6],n[s+2]=i[5],n[s+3]=i[4],n[s+4]=i[3],n[s+5]=i[2],n[s+6]=i[1],n[s+7]=i[0]}function readDouble_f64_cpy(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 readDouble_f64_rev(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?writeDouble_f64_cpy:writeDouble_f64_rev,e.writeDoubleBE=n?writeDouble_f64_rev:writeDouble_f64_cpy,e.readDoubleLE=n?readDouble_f64_cpy:readDouble_f64_rev,e.readDoubleBE=n?readDouble_f64_rev:readDouble_f64_cpy}():function(){function writeDouble_ieee754(e,t,i,n,s,a){var o=n<0?1:0;if(o&&(n=-n),0===n)e(0,s,a+t),e(1/n>0?0:2147483648,s,a+i);else if(isNaN(n))e(0,s,a+t),e(2146959360,s,a+i);else if(n>17976931348623157e292)e(0,s,a+t),e((o<<31|2146435072)>>>0,s,a+i);else{var c;if(n<22250738585072014e-324)e((c=n/5e-324)>>>0,s,a+t),e((o<<31|c/4294967296)>>>0,s,a+i);else{var u=Math.floor(Math.log(n)/Math.LN2);1024===u&&(u=1023),e(4503599627370496*(c=n*Math.pow(2,-u))>>>0,s,a+t),e((o<<31|u+1023<<20|1048576*c&1048575)>>>0,s,a+i)}}}function readDouble_ieee754(e,t,i,n,s){var a=e(n,s+t),o=e(n,s+i),c=2*(o>>31)+1,u=o>>>20&2047,l=4294967296*(1048575&o)+a;return 2047===u?l?NaN:c*(1/0):0===u?5e-324*c*l:c*Math.pow(2,u-1075)*(l+4503599627370496)}e.writeDoubleLE=writeDouble_ieee754.bind(null,writeUintLE,0,4),e.writeDoubleBE=writeDouble_ieee754.bind(null,writeUintBE,4,0),e.readDoubleLE=readDouble_ieee754.bind(null,readUintLE,0,4),e.readDoubleBE=readDouble_ieee754.bind(null,readUintBE,4,0)}(),e}function writeUintLE(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 writeUintBE(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 readUintLE(e,t){return(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0}function readUintBE(e,t){return(e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3])>>>0}var B=function inquire(e){try{var t=void 0;t}catch(e){}return null};var J={};!function(e){var t=e;t.length=function utf8_length(e){for(var t=0,i=0,n=0;n191&&n<224?a[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,a[o++]=55296+(n>>10),a[o++]=56320+(1023&n)):a[o++]=(15&n)<<12|(63&e[t++])<<6|63&e[t++],o>8191&&((s||(s=[])).push(String.fromCharCode.apply(String,a)),o=0);return s?(o&&s.push(String.fromCharCode.apply(String,a.slice(0,o))),s.join("")):String.fromCharCode.apply(String,a.slice(0,o))},t.write=function utf8_write(e,t,i){for(var n,s,a=i,o=0;o>6|192,t[i++]=63&n|128):55296==(64512&n)&&56320==(64512&(s=e.charCodeAt(o+1)))?(n=65536+((1023&n)<<10)+(1023&s),++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-a}}(J);var F=function pool(e,t,i){var n=i||8192,s=n>>>1,a=null,o=n;return function pool_alloc(i){if(i<1||i>s)return e(i);o+i>n&&(a=e(n),o=0);var c=t.call(a,o,o+=i);return 7&o&&(o=1+(7|o)),c}};var V=LongBits$2,j=A;function LongBits$2(e,t){this.lo=e>>>0,this.hi=t>>>0}var $=LongBits$2.zero=new LongBits$2(0,0);$.toNumber=function(){return 0},$.zzEncode=$.zzDecode=function(){return this},$.length=function(){return 1};var q=LongBits$2.zeroHash="\0\0\0\0\0\0\0\0";LongBits$2.fromNumber=function fromNumber(e){if(0===e)return $;var t=e<0;t&&(e=-e);var i=e>>>0,n=(e-i)/4294967296>>>0;return t&&(n=~n>>>0,i=~i>>>0,++i>4294967295&&(i=0,++n>4294967295&&(n=0))),new LongBits$2(i,n)},LongBits$2.from=function from(e){if("number"==typeof e)return LongBits$2.fromNumber(e);if(j.isString(e)){if(!j.Long)return LongBits$2.fromNumber(parseInt(e,10));e=j.Long.fromString(e)}return e.low||e.high?new LongBits$2(e.low>>>0,e.high>>>0):$},LongBits$2.prototype.toNumber=function toNumber(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},LongBits$2.prototype.toLong=function toLong(e){return j.Long?new j.Long(0|this.lo,0|this.hi,Boolean(e)):{low:0|this.lo,high:0|this.hi,unsigned:Boolean(e)}};var W=String.prototype.charCodeAt;LongBits$2.fromHash=function fromHash(e){return e===q?$:new LongBits$2((W.call(e,0)|W.call(e,1)<<8|W.call(e,2)<<16|W.call(e,3)<<24)>>>0,(W.call(e,4)|W.call(e,5)<<8|W.call(e,6)<<16|W.call(e,7)<<24)>>>0)},LongBits$2.prototype.toHash=function toHash(){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)},LongBits$2.prototype.zzEncode=function zzEncode(){var e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this},LongBits$2.prototype.zzDecode=function zzDecode(){var e=-(1&this.lo);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this},LongBits$2.prototype.length=function length(){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},function(e){var t=e;function merge(e,t,i){for(var n=Object.keys(t),s=0;s0)},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 newBuffer(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 longToHash(e){return e?t.LongBits.from(e).toHash():t.LongBits.zeroHash},t.longFromHash=function longFromHash(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=merge,t.lcFirst=function lcFirst(e){return e.charAt(0).toLowerCase()+e.substring(1)},t.newError=newError,t.ProtocolError=newError("ProtocolError"),t.oneOfGetter=function getOneOf(e){for(var t={},i=0;i-1;--i)if(1===t[e[i]]&&void 0!==this[e[i]]&&null!==this[e[i]])return e[i]}},t.oneOfSetter=function setOneOf(e){return function(t){for(var i=0;i>>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 writeFixed32(e,t,i){t[i]=255&e,t[i+1]=e>>>8&255,t[i+2]=e>>>16&255,t[i+3]=e>>>24}Writer$1.create=Y(),Writer$1.alloc=function alloc(e){return new H.Array(e)},H.Array!==Array&&(Writer$1.alloc=H.pool(Writer$1.alloc,H.Array.prototype.subarray)),Writer$1.prototype._push=function push(e,t,i){return this.tail=this.tail.next=new Op(e,t,i),this.len+=t,this},VarintOp.prototype=Object.create(Op.prototype),VarintOp.prototype.fn=function writeVarint32(e,t,i){for(;e>127;)t[i++]=127&e|128,e>>>=7;t[i]=e},Writer$1.prototype.uint32=function write_uint32(e){return this.len+=(this.tail=this.tail.next=new VarintOp((e>>>=0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this},Writer$1.prototype.int32=function write_int32(e){return e<0?this._push(writeVarint64,10,z.fromNumber(e)):this.uint32(e)},Writer$1.prototype.sint32=function write_sint32(e){return this.uint32((e<<1^e>>31)>>>0)},Writer$1.prototype.uint64=function write_uint64(e){var t=z.from(e);return this._push(writeVarint64,t.length(),t)},Writer$1.prototype.int64=Writer$1.prototype.uint64,Writer$1.prototype.sint64=function write_sint64(e){var t=z.from(e).zzEncode();return this._push(writeVarint64,t.length(),t)},Writer$1.prototype.bool=function write_bool(e){return this._push(writeByte,1,e?1:0)},Writer$1.prototype.fixed32=function write_fixed32(e){return this._push(writeFixed32,4,e>>>0)},Writer$1.prototype.sfixed32=Writer$1.prototype.fixed32,Writer$1.prototype.fixed64=function write_fixed64(e){var t=z.from(e);return this._push(writeFixed32,4,t.lo)._push(writeFixed32,4,t.hi)},Writer$1.prototype.sfixed64=Writer$1.prototype.fixed64,Writer$1.prototype.float=function write_float(e){return this._push(H.float.writeFloatLE,4,e)},Writer$1.prototype.double=function write_double(e){return this._push(H.float.writeDoubleLE,8,e)};var X=H.Array.prototype.set?function writeBytes_set(e,t,i){t.set(e,i)}:function writeBytes_for(e,t,i){for(var n=0;n>>0;if(!t)return this._push(writeByte,1,0);if(H.isString(e)){var i=Writer$1.alloc(t=K.length(e));K.decode(e,i,0),e=i}return this.uint32(t)._push(X,t,e)},Writer$1.prototype.string=function write_string(e){var t=Z.length(e);return t?this.uint32(t)._push(Z.write,t,e):this._push(writeByte,1,0)},Writer$1.prototype.fork=function fork(){return this.states=new State(this),this.head=this.tail=new Op(noop,0,0),this.len=0,this},Writer$1.prototype.reset=function reset(){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 Op(noop,0,0),this.len=0),this},Writer$1.prototype.ldelim=function ldelim(){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},Writer$1.prototype.finish=function finish(){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},Writer$1._configure=function(e){G=e,Writer$1.create=Y(),G._configure()};var ee=BufferWriter,te=Q;(BufferWriter.prototype=Object.create(te.prototype)).constructor=BufferWriter;var ie=A;function BufferWriter(){te.call(this)}function writeStringBuffer(e,t,i){e.length<40?ie.utf8.write(e,t,i):t.utf8Write?t.utf8Write(e,i):t.write(e,i)}BufferWriter._configure=function(){BufferWriter.alloc=ie._Buffer_allocUnsafe,BufferWriter.writeBytesBuffer=ie.Buffer&&ie.Buffer.prototype instanceof Uint8Array&&"set"===ie.Buffer.prototype.set.name?function writeBytesBuffer_set(e,t,i){t.set(e,i)}:function writeBytesBuffer_copy(e,t,i){if(e.copy)e.copy(t,i,0,e.length);else for(var n=0;n>>0;return this.uint32(t),t&&this._push(BufferWriter.writeBytesBuffer,t,e),this},BufferWriter.prototype.string=function write_string_buffer(e){var t=ie.Buffer.byteLength(e);return this.uint32(t),t&&this._push(writeStringBuffer,t,e),this},BufferWriter._configure();var re,ne=Reader$1,se=A,ae=se.LongBits,oe=se.utf8;function indexOutOfRange(e,t){return RangeError("index out of range: "+e.pos+" + "+(t||1)+" > "+e.len)}function Reader$1(e){this.buf=e,this.pos=0,this.len=e.length}var ce="undefined"!=typeof Uint8Array?function create_typed_array(e){if(e instanceof Uint8Array||Array.isArray(e))return new Reader$1(e);throw Error("illegal buffer")}:function create_array(e){if(Array.isArray(e))return new Reader$1(e);throw Error("illegal buffer")},de=function create(){return se.Buffer?function create_buffer_setup(e){return(Reader$1.create=function create_buffer(e){return se.Buffer.isBuffer(e)?new re(e):ce(e)})(e)}:ce};function readLongVarint(){var e=new ae(0,0),t=0;if(!(this.len-this.pos>4)){for(;t<3;++t){if(this.pos>=this.len)throw indexOutOfRange(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 indexOutOfRange(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 readFixed32_end(e,t){return(e[t-4]|e[t-3]<<8|e[t-2]<<16|e[t-1]<<24)>>>0}function readFixed64(){if(this.pos+8>this.len)throw indexOutOfRange(this,8);return new ae(readFixed32_end(this.buf,this.pos+=4),readFixed32_end(this.buf,this.pos+=4))}Reader$1.create=de(),Reader$1.prototype._slice=se.Array.prototype.subarray||se.Array.prototype.slice,Reader$1.prototype.uint32=function read_uint32_setup(){var e=4294967295;return function read_uint32(){if(e=(127&this.buf[this.pos])>>>0,this.buf[this.pos++]<128)return e;if(e=(e|(127&this.buf[this.pos])<<7)>>>0,this.buf[this.pos++]<128)return e;if(e=(e|(127&this.buf[this.pos])<<14)>>>0,this.buf[this.pos++]<128)return e;if(e=(e|(127&this.buf[this.pos])<<21)>>>0,this.buf[this.pos++]<128)return e;if(e=(e|(15&this.buf[this.pos])<<28)>>>0,this.buf[this.pos++]<128)return e;if((this.pos+=5)>this.len)throw this.pos=this.len,indexOutOfRange(this,10);return e}}(),Reader$1.prototype.int32=function read_int32(){return 0|this.uint32()},Reader$1.prototype.sint32=function read_sint32(){var e=this.uint32();return e>>>1^-(1&e)|0},Reader$1.prototype.bool=function read_bool(){return 0!==this.uint32()},Reader$1.prototype.fixed32=function read_fixed32(){if(this.pos+4>this.len)throw indexOutOfRange(this,4);return readFixed32_end(this.buf,this.pos+=4)},Reader$1.prototype.sfixed32=function read_sfixed32(){if(this.pos+4>this.len)throw indexOutOfRange(this,4);return 0|readFixed32_end(this.buf,this.pos+=4)},Reader$1.prototype.float=function read_float(){if(this.pos+4>this.len)throw indexOutOfRange(this,4);var e=se.float.readFloatLE(this.buf,this.pos);return this.pos+=4,e},Reader$1.prototype.double=function read_double(){if(this.pos+8>this.len)throw indexOutOfRange(this,4);var e=se.float.readDoubleLE(this.buf,this.pos);return this.pos+=8,e},Reader$1.prototype.bytes=function read_bytes(){var e=this.uint32(),t=this.pos,i=this.pos+e;if(i>this.len)throw indexOutOfRange(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)},Reader$1.prototype.string=function read_string(){var e=this.bytes();return oe.read(e,0,e.length)},Reader$1.prototype.skip=function skip(e){if("number"==typeof e){if(this.pos+e>this.len)throw indexOutOfRange(this,e);this.pos+=e}else do{if(this.pos>=this.len)throw indexOutOfRange(this)}while(128&this.buf[this.pos++]);return this},Reader$1.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},Reader$1._configure=function(e){re=e,Reader$1.create=de(),re._configure();var t=se.Long?"toLong":"toNumber";se.merge(Reader$1.prototype,{int64:function read_int64(){return readLongVarint.call(this)[t](!1)},uint64:function read_uint64(){return readLongVarint.call(this)[t](!0)},sint64:function read_sint64(){return readLongVarint.call(this).zzDecode()[t](!1)},fixed64:function read_fixed64(){return readFixed64.call(this)[t](!0)},sfixed64:function read_sfixed64(){return readFixed64.call(this)[t](!1)}})};var ue=BufferReader,le=ne;(BufferReader.prototype=Object.create(le.prototype)).constructor=BufferReader;var he=A;function BufferReader(e){le.call(this,e)}BufferReader._configure=function(){he.Buffer&&(BufferReader.prototype._slice=he.Buffer.prototype.slice)},BufferReader.prototype.string=function read_string_buffer(){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))},BufferReader._configure();var pe,me={},fe=Service,ge=A;function Service(e,t,i){if("function"!=typeof e)throw TypeError("rpcImpl must be a function");ge.EventEmitter.call(this),this.rpcImpl=e,this.requestDelimited=Boolean(t),this.responseDelimited=Boolean(i)}(Service.prototype=Object.create(ge.EventEmitter.prototype)).constructor=Service,Service.prototype.rpcCall=function rpcCall(e,t,i,n,s){if(!n)throw TypeError("request must be specified");var a=this;if(!s)return ge.asPromise(rpcCall,a,e,t,i,n);if(a.rpcImpl)try{return a.rpcImpl(e,t[a.requestDelimited?"encodeDelimited":"encode"](n).finish(),(function rpcCallback(t,n){if(t)return a.emit("error",t,e),s(t);if(null!==n){if(!(n instanceof i))try{n=i[a.responseDelimited?"decodeDelimited":"decode"](n)}catch(t){return a.emit("error",t,e),s(t)}return a.emit("data",n,e),s(null,n)}a.end(!0)}))}catch(t){return a.emit("error",t,e),void setTimeout((function(){s(t)}),0)}else setTimeout((function(){s(Error("already ended"))}),0)},Service.prototype.end=function end(e){return this.rpcImpl&&(e||this.rpcImpl(null,null,null),this.rpcImpl=null,this.emit("end").off()),this},pe=me,pe.Service=fe;var ve={};!function(e){var t=e;function configure(){t.util._configure(),t.Writer._configure(t.BufferWriter),t.Reader._configure(t.BufferReader)}t.build="minimal",t.Writer=Q,t.BufferWriter=ee,t.Reader=ne,t.BufferReader=ue,t.util=A,t.rpc=me,t.roots=ve,t.configure=configure,configure()}(D);var Se,be,ke,ye,Te,we,Ce,Pe,Ee=D,Re=(()=>{if(void 0!==Re)return Re;if("undefined"!=typeof self)return self;if("undefined"!=typeof window)return window;if(void 0!==__webpack_require__.g)return __webpack_require__.g;throw"Unable to locate global object"})();function trackTypeFromJSON(e){switch(e){case 0:case"AUDIO":return Se.AUDIO;case 1:case"VIDEO":return Se.VIDEO;case 2:case"DATA":return Se.DATA;default:return Se.UNRECOGNIZED}}function trackTypeToJSON(e){switch(e){case Se.AUDIO:return"AUDIO";case Se.VIDEO:return"VIDEO";case Se.DATA:return"DATA";default:return"UNKNOWN"}}function trackSourceFromJSON(e){switch(e){case 0:case"UNKNOWN":return be.UNKNOWN;case 1:case"CAMERA":return be.CAMERA;case 2:case"MICROPHONE":return be.MICROPHONE;case 3:case"SCREEN_SHARE":return be.SCREEN_SHARE;case 4:case"SCREEN_SHARE_AUDIO":return be.SCREEN_SHARE_AUDIO;default:return be.UNRECOGNIZED}}function trackSourceToJSON(e){switch(e){case be.UNKNOWN:return"UNKNOWN";case be.CAMERA:return"CAMERA";case be.MICROPHONE:return"MICROPHONE";case be.SCREEN_SHARE:return"SCREEN_SHARE";case be.SCREEN_SHARE_AUDIO:return"SCREEN_SHARE_AUDIO";default:return"UNKNOWN"}}function videoQualityFromJSON(e){switch(e){case 0:case"LOW":return ke.LOW;case 1:case"MEDIUM":return ke.MEDIUM;case 2:case"HIGH":return ke.HIGH;case 3:case"OFF":return ke.OFF;default:return ke.UNRECOGNIZED}}function videoQualityToJSON(e){switch(e){case ke.LOW:return"LOW";case ke.MEDIUM:return"MEDIUM";case ke.HIGH:return"HIGH";case ke.OFF:return"OFF";default:return"UNKNOWN"}}function connectionQualityFromJSON(e){switch(e){case 0:case"POOR":return ye.POOR;case 1:case"GOOD":return ye.GOOD;case 2:case"EXCELLENT":return ye.EXCELLENT;default:return ye.UNRECOGNIZED}}function clientConfigSettingFromJSON(e){switch(e){case 0:case"UNSET":return Te.UNSET;case 1:case"DISABLED":return Te.DISABLED;case 2:case"ENABLED":return Te.ENABLED;default:return Te.UNRECOGNIZED}}function clientConfigSettingToJSON(e){switch(e){case Te.UNSET:return"UNSET";case Te.DISABLED:return"DISABLED";case Te.ENABLED:return"ENABLED";default:return"UNKNOWN"}}function participantInfo_StateFromJSON(e){switch(e){case 0:case"JOINING":return we.JOINING;case 1:case"JOINED":return we.JOINED;case 2:case"ACTIVE":return we.ACTIVE;case 3:case"DISCONNECTED":return we.DISCONNECTED;default:return we.UNRECOGNIZED}}function dataPacket_KindFromJSON(e){switch(e){case 0:case"RELIABLE":return Ce.RELIABLE;case 1:case"LOSSY":return Ce.LOSSY;default:return Ce.UNRECOGNIZED}}function clientInfo_SDKFromJSON(e){switch(e){case 0:case"UNKNOWN":return Pe.UNKNOWN;case 1:case"JS":return Pe.JS;case 2:case"SWIFT":return Pe.SWIFT;case 3:case"ANDROID":return Pe.ANDROID;case 4:case"FLUTTER":return Pe.FLUTTER;case 5:case"GO":return Pe.GO;case 6:case"UNITY":return Pe.UNITY;default:return Pe.UNRECOGNIZED}}Ee.util.Long!==p&&(Ee.util.Long=p,Ee.configure()),function(e){e[e.AUDIO=0]="AUDIO",e[e.VIDEO=1]="VIDEO",e[e.DATA=2]="DATA",e[e.UNRECOGNIZED=-1]="UNRECOGNIZED"}(Se||(Se={})),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"}(be||(be={})),function(e){e[e.LOW=0]="LOW",e[e.MEDIUM=1]="MEDIUM",e[e.HIGH=2]="HIGH",e[e.OFF=3]="OFF",e[e.UNRECOGNIZED=-1]="UNRECOGNIZED"}(ke||(ke={})),function(e){e[e.POOR=0]="POOR",e[e.GOOD=1]="GOOD",e[e.EXCELLENT=2]="EXCELLENT",e[e.UNRECOGNIZED=-1]="UNRECOGNIZED"}(ye||(ye={})),function(e){e[e.UNSET=0]="UNSET",e[e.DISABLED=1]="DISABLED",e[e.ENABLED=2]="ENABLED",e[e.UNRECOGNIZED=-1]="UNRECOGNIZED"}(Te||(Te={})),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"}(we||(we={})),function(e){e[e.RELIABLE=0]="RELIABLE",e[e.LOSSY=1]="LOSSY",e[e.UNRECOGNIZED=-1]="UNRECOGNIZED"}(Ce||(Ce={})),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.UNRECOGNIZED=-1]="UNRECOGNIZED"}(Pe||(Pe={}));const Oe={encode(e,t=Ee.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)Ne.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.activeRecording&&t.uint32(80).bool(e.activeRecording),t},decode(e,t){const i=e instanceof Ee.Reader?e:new Ee.Reader(e);let n=void 0===t?i.len:i.pos+t;const s={sid:"",name:"",emptyTimeout:0,maxParticipants:0,creationTime:0,turnPassword:"",enabledCodecs:[],metadata:"",numParticipants:0,activeRecording:!1};for(;i.pos>>3){case 1:s.sid=i.string();break;case 2:s.name=i.string();break;case 3:s.emptyTimeout=i.uint32();break;case 4:s.maxParticipants=i.uint32();break;case 5:s.creationTime=longToNumber(i.int64());break;case 6:s.turnPassword=i.string();break;case 7:s.enabledCodecs.push(Ne.decode(i,i.uint32()));break;case 8:s.metadata=i.string();break;case 9:s.numParticipants=i.uint32();break;case 10:s.activeRecording=i.bool();break;default:i.skipType(7&e)}}return s},fromJSON:e=>({sid:isSet$1(e.sid)?String(e.sid):"",name:isSet$1(e.name)?String(e.name):"",emptyTimeout:isSet$1(e.emptyTimeout)?Number(e.emptyTimeout):0,maxParticipants:isSet$1(e.maxParticipants)?Number(e.maxParticipants):0,creationTime:isSet$1(e.creationTime)?Number(e.creationTime):0,turnPassword:isSet$1(e.turnPassword)?String(e.turnPassword):"",enabledCodecs:Array.isArray(e?.enabledCodecs)?e.enabledCodecs.map((e=>Ne.fromJSON(e))):[],metadata:isSet$1(e.metadata)?String(e.metadata):"",numParticipants:isSet$1(e.numParticipants)?Number(e.numParticipants):0,activeRecording:!!isSet$1(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?Ne.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.activeRecording&&(t.activeRecording=e.activeRecording),t},fromPartial(e){const t={sid:"",name:"",emptyTimeout:0,maxParticipants:0,creationTime:0,turnPassword:"",enabledCodecs:[],metadata:"",numParticipants:0,activeRecording:!1};return t.sid=e.sid??"",t.name=e.name??"",t.emptyTimeout=e.emptyTimeout??0,t.maxParticipants=e.maxParticipants??0,t.creationTime=e.creationTime??0,t.turnPassword=e.turnPassword??"",t.enabledCodecs=e.enabledCodecs?.map((e=>Ne.fromPartial(e)))||[],t.metadata=e.metadata??"",t.numParticipants=e.numParticipants??0,t.activeRecording=e.activeRecording??!1,t}};const Ne={encode:(e,t=Ee.Writer.create())=>(""!==e.mime&&t.uint32(10).string(e.mime),""!==e.fmtpLine&&t.uint32(18).string(e.fmtpLine),t),decode(e,t){const i=e instanceof Ee.Reader?e:new Ee.Reader(e);let n=void 0===t?i.len:i.pos+t;const s={mime:"",fmtpLine:""};for(;i.pos>>3){case 1:s.mime=i.string();break;case 2:s.fmtpLine=i.string();break;default:i.skipType(7&e)}}return s},fromJSON:e=>({mime:isSet$1(e.mime)?String(e.mime):"",fmtpLine:isSet$1(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},fromPartial(e){const t={mime:"",fmtpLine:""};return t.mime=e.mime??"",t.fmtpLine=e.fmtpLine??"",t}};const _e={encode:(e,t=Ee.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),!0===e.hidden&&t.uint32(56).bool(e.hidden),!0===e.recorder&&t.uint32(64).bool(e.recorder),t),decode(e,t){const i=e instanceof Ee.Reader?e:new Ee.Reader(e);let n=void 0===t?i.len:i.pos+t;const s={canSubscribe:!1,canPublish:!1,canPublishData:!1,hidden:!1,recorder:!1};for(;i.pos>>3){case 1:s.canSubscribe=i.bool();break;case 2:s.canPublish=i.bool();break;case 3:s.canPublishData=i.bool();break;case 7:s.hidden=i.bool();break;case 8:s.recorder=i.bool();break;default:i.skipType(7&e)}}return s},fromJSON:e=>({canSubscribe:!!isSet$1(e.canSubscribe)&&Boolean(e.canSubscribe),canPublish:!!isSet$1(e.canPublish)&&Boolean(e.canPublish),canPublishData:!!isSet$1(e.canPublishData)&&Boolean(e.canPublishData),hidden:!!isSet$1(e.hidden)&&Boolean(e.hidden),recorder:!!isSet$1(e.recorder)&&Boolean(e.recorder)}),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),void 0!==e.hidden&&(t.hidden=e.hidden),void 0!==e.recorder&&(t.recorder=e.recorder),t},fromPartial(e){const t={canSubscribe:!1,canPublish:!1,canPublishData:!1,hidden:!1,recorder:!1};return t.canSubscribe=e.canSubscribe??!1,t.canPublish=e.canPublish??!1,t.canPublishData=e.canPublishData??!1,t.hidden=e.hidden??!1,t.recorder=e.recorder??!1,t}};const Le={encode(e,t=Ee.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)De.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&&_e.encode(e.permission,t.uint32(90).fork()).ldelim(),""!==e.region&&t.uint32(98).string(e.region),t},decode(e,t){const i=e instanceof Ee.Reader?e:new Ee.Reader(e);let n=void 0===t?i.len:i.pos+t;const s={sid:"",identity:"",state:0,tracks:[],metadata:"",joinedAt:0,name:"",version:0,permission:void 0,region:""};for(;i.pos>>3){case 1:s.sid=i.string();break;case 2:s.identity=i.string();break;case 3:s.state=i.int32();break;case 4:s.tracks.push(De.decode(i,i.uint32()));break;case 5:s.metadata=i.string();break;case 6:s.joinedAt=longToNumber(i.int64());break;case 9:s.name=i.string();break;case 10:s.version=i.uint32();break;case 11:s.permission=_e.decode(i,i.uint32());break;case 12:s.region=i.string();break;default:i.skipType(7&e)}}return s},fromJSON:e=>({sid:isSet$1(e.sid)?String(e.sid):"",identity:isSet$1(e.identity)?String(e.identity):"",state:isSet$1(e.state)?participantInfo_StateFromJSON(e.state):0,tracks:Array.isArray(e?.tracks)?e.tracks.map((e=>De.fromJSON(e))):[],metadata:isSet$1(e.metadata)?String(e.metadata):"",joinedAt:isSet$1(e.joinedAt)?Number(e.joinedAt):0,name:isSet$1(e.name)?String(e.name):"",version:isSet$1(e.version)?Number(e.version):0,permission:isSet$1(e.permission)?_e.fromJSON(e.permission):void 0,region:isSet$1(e.region)?String(e.region):""}),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 participantInfo_StateToJSON(e){switch(e){case we.JOINING:return"JOINING";case we.JOINED:return"JOINED";case we.ACTIVE:return"ACTIVE";case we.DISCONNECTED:return"DISCONNECTED";default:return"UNKNOWN"}}(e.state)),e.tracks?t.tracks=e.tracks.map((e=>e?De.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?_e.toJSON(e.permission):void 0),void 0!==e.region&&(t.region=e.region),t},fromPartial(e){const t={sid:"",identity:"",state:0,tracks:[],metadata:"",joinedAt:0,name:"",version:0,permission:void 0,region:""};return t.sid=e.sid??"",t.identity=e.identity??"",t.state=e.state??0,t.tracks=e.tracks?.map((e=>De.fromPartial(e)))||[],t.metadata=e.metadata??"",t.joinedAt=e.joinedAt??0,t.name=e.name??"",t.version=e.version??0,t.permission=void 0!==e.permission&&null!==e.permission?_e.fromPartial(e.permission):void 0,t.region=e.region??"",t}};const De={encode(e,t=Ee.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)Ae.encode(i,t.uint32(82).fork()).ldelim();return""!==e.mimeType&&t.uint32(90).string(e.mimeType),""!==e.mid&&t.uint32(98).string(e.mid),t},decode(e,t){const i=e instanceof Ee.Reader?e:new Ee.Reader(e);let n=void 0===t?i.len:i.pos+t;const s={sid:"",type:0,name:"",muted:!1,width:0,height:0,simulcast:!1,disableDtx:!1,source:0,layers:[],mimeType:"",mid:""};for(;i.pos>>3){case 1:s.sid=i.string();break;case 2:s.type=i.int32();break;case 3:s.name=i.string();break;case 4:s.muted=i.bool();break;case 5:s.width=i.uint32();break;case 6:s.height=i.uint32();break;case 7:s.simulcast=i.bool();break;case 8:s.disableDtx=i.bool();break;case 9:s.source=i.int32();break;case 10:s.layers.push(Ae.decode(i,i.uint32()));break;case 11:s.mimeType=i.string();break;case 12:s.mid=i.string();break;default:i.skipType(7&e)}}return s},fromJSON:e=>({sid:isSet$1(e.sid)?String(e.sid):"",type:isSet$1(e.type)?trackTypeFromJSON(e.type):0,name:isSet$1(e.name)?String(e.name):"",muted:!!isSet$1(e.muted)&&Boolean(e.muted),width:isSet$1(e.width)?Number(e.width):0,height:isSet$1(e.height)?Number(e.height):0,simulcast:!!isSet$1(e.simulcast)&&Boolean(e.simulcast),disableDtx:!!isSet$1(e.disableDtx)&&Boolean(e.disableDtx),source:isSet$1(e.source)?trackSourceFromJSON(e.source):0,layers:Array.isArray(e?.layers)?e.layers.map((e=>Ae.fromJSON(e))):[],mimeType:isSet$1(e.mimeType)?String(e.mimeType):"",mid:isSet$1(e.mid)?String(e.mid):""}),toJSON(e){const t={};return void 0!==e.sid&&(t.sid=e.sid),void 0!==e.type&&(t.type=trackTypeToJSON(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=trackSourceToJSON(e.source)),e.layers?t.layers=e.layers.map((e=>e?Ae.toJSON(e):void 0)):t.layers=[],void 0!==e.mimeType&&(t.mimeType=e.mimeType),void 0!==e.mid&&(t.mid=e.mid),t},fromPartial(e){const t={sid:"",type:0,name:"",muted:!1,width:0,height:0,simulcast:!1,disableDtx:!1,source:0,layers:[],mimeType:"",mid:""};return t.sid=e.sid??"",t.type=e.type??0,t.name=e.name??"",t.muted=e.muted??!1,t.width=e.width??0,t.height=e.height??0,t.simulcast=e.simulcast??!1,t.disableDtx=e.disableDtx??!1,t.source=e.source??0,t.layers=e.layers?.map((e=>Ae.fromPartial(e)))||[],t.mimeType=e.mimeType??"",t.mid=e.mid??"",t}};const Ae={encode:(e,t=Ee.Writer.create())=>(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 Ee.Reader?e:new Ee.Reader(e);let n=void 0===t?i.len:i.pos+t;const s={quality:0,width:0,height:0,bitrate:0,ssrc:0};for(;i.pos>>3){case 1:s.quality=i.int32();break;case 2:s.width=i.uint32();break;case 3:s.height=i.uint32();break;case 4:s.bitrate=i.uint32();break;case 5:s.ssrc=i.uint32();break;default:i.skipType(7&e)}}return s},fromJSON:e=>({quality:isSet$1(e.quality)?videoQualityFromJSON(e.quality):0,width:isSet$1(e.width)?Number(e.width):0,height:isSet$1(e.height)?Number(e.height):0,bitrate:isSet$1(e.bitrate)?Number(e.bitrate):0,ssrc:isSet$1(e.ssrc)?Number(e.ssrc):0}),toJSON(e){const t={};return void 0!==e.quality&&(t.quality=videoQualityToJSON(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},fromPartial(e){const t={quality:0,width:0,height:0,bitrate:0,ssrc:0};return t.quality=e.quality??0,t.width=e.width??0,t.height=e.height??0,t.bitrate=e.bitrate??0,t.ssrc=e.ssrc??0,t}};const Ie={encode:(e,t=Ee.Writer.create())=>(0!==e.kind&&t.uint32(8).int32(e.kind),void 0!==e.user&&xe.encode(e.user,t.uint32(18).fork()).ldelim(),void 0!==e.speaker&&Ue.encode(e.speaker,t.uint32(26).fork()).ldelim(),t),decode(e,t){const i=e instanceof Ee.Reader?e:new Ee.Reader(e);let n=void 0===t?i.len:i.pos+t;const s={kind:0,user:void 0,speaker:void 0};for(;i.pos>>3){case 1:s.kind=i.int32();break;case 2:s.user=xe.decode(i,i.uint32());break;case 3:s.speaker=Ue.decode(i,i.uint32());break;default:i.skipType(7&e)}}return s},fromJSON:e=>({kind:isSet$1(e.kind)?dataPacket_KindFromJSON(e.kind):0,user:isSet$1(e.user)?xe.fromJSON(e.user):void 0,speaker:isSet$1(e.speaker)?Ue.fromJSON(e.speaker):void 0}),toJSON(e){const t={};return void 0!==e.kind&&(t.kind=function dataPacket_KindToJSON(e){switch(e){case Ce.RELIABLE:return"RELIABLE";case Ce.LOSSY:return"LOSSY";default:return"UNKNOWN"}}(e.kind)),void 0!==e.user&&(t.user=e.user?xe.toJSON(e.user):void 0),void 0!==e.speaker&&(t.speaker=e.speaker?Ue.toJSON(e.speaker):void 0),t},fromPartial(e){const t={kind:0,user:void 0,speaker:void 0};return t.kind=e.kind??0,t.user=void 0!==e.user&&null!==e.user?xe.fromPartial(e.user):void 0,t.speaker=void 0!==e.speaker&&null!==e.speaker?Ue.fromPartial(e.speaker):void 0,t}};const Ue={encode(e,t=Ee.Writer.create()){for(const i of e.speakers)Me.encode(i,t.uint32(10).fork()).ldelim();return t},decode(e,t){const i=e instanceof Ee.Reader?e:new Ee.Reader(e);let n=void 0===t?i.len:i.pos+t;const s={speakers:[]};for(;i.pos>>3==1)s.speakers.push(Me.decode(i,i.uint32()));else i.skipType(7&e)}return s},fromJSON:e=>({speakers:Array.isArray(e?.speakers)?e.speakers.map((e=>Me.fromJSON(e))):[]}),toJSON(e){const t={};return e.speakers?t.speakers=e.speakers.map((e=>e?Me.toJSON(e):void 0)):t.speakers=[],t},fromPartial(e){const t={speakers:[]};return t.speakers=e.speakers?.map((e=>Me.fromPartial(e)))||[],t}};const Me={encode:(e,t=Ee.Writer.create())=>(""!==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 Ee.Reader?e:new Ee.Reader(e);let n=void 0===t?i.len:i.pos+t;const s={sid:"",level:0,active:!1};for(;i.pos>>3){case 1:s.sid=i.string();break;case 2:s.level=i.float();break;case 3:s.active=i.bool();break;default:i.skipType(7&e)}}return s},fromJSON:e=>({sid:isSet$1(e.sid)?String(e.sid):"",level:isSet$1(e.level)?Number(e.level):0,active:!!isSet$1(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},fromPartial(e){const t={sid:"",level:0,active:!1};return t.sid=e.sid??"",t.level=e.level??0,t.active=e.active??!1,t}};function createBaseUserPacket(){return{participantSid:"",payload:new Uint8Array,destinationSids:[]}}const xe={encode(e,t=Ee.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 t},decode(e,t){const i=e instanceof Ee.Reader?e:new Ee.Reader(e);let n=void 0===t?i.len:i.pos+t;const s=createBaseUserPacket();for(;i.pos>>3){case 1:s.participantSid=i.string();break;case 2:s.payload=i.bytes();break;case 3:s.destinationSids.push(i.string());break;default:i.skipType(7&e)}}return s},fromJSON:e=>({participantSid:isSet$1(e.participantSid)?String(e.participantSid):"",payload:isSet$1(e.payload)?bytesFromBase64(e.payload):new Uint8Array,destinationSids:Array.isArray(e?.destinationSids)?e.destinationSids.map((e=>String(e))):[]}),toJSON(e){const t={};return void 0!==e.participantSid&&(t.participantSid=e.participantSid),void 0!==e.payload&&(t.payload=function base64FromBytes(e){const t=[];for(const i of e)t.push(String.fromCharCode(i));return qe(t.join(""))}(void 0!==e.payload?e.payload:new Uint8Array)),e.destinationSids?t.destinationSids=e.destinationSids.map((e=>e)):t.destinationSids=[],t},fromPartial(e){const t=createBaseUserPacket();return t.participantSid=e.participantSid??"",t.payload=e.payload??new Uint8Array,t.destinationSids=e.destinationSids?.map((e=>e))||[],t}};const Be={encode(e,t=Ee.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 Ee.Reader?e:new Ee.Reader(e);let n=void 0===t?i.len:i.pos+t;const s={participantSid:"",trackSids:[]};for(;i.pos>>3){case 1:s.participantSid=i.string();break;case 2:s.trackSids.push(i.string());break;default:i.skipType(7&e)}}return s},fromJSON:e=>({participantSid:isSet$1(e.participantSid)?String(e.participantSid):"",trackSids:Array.isArray(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},fromPartial(e){const t={participantSid:"",trackSids:[]};return t.participantSid=e.participantSid??"",t.trackSids=e.trackSids?.map((e=>e))||[],t}};const Je={encode:(e,t=Ee.Writer.create())=>(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),t),decode(e,t){const i=e instanceof Ee.Reader?e:new Ee.Reader(e);let n=void 0===t?i.len:i.pos+t;const s={sdk:0,version:"",protocol:0,os:"",osVersion:"",deviceModel:"",browser:"",browserVersion:"",address:""};for(;i.pos>>3){case 1:s.sdk=i.int32();break;case 2:s.version=i.string();break;case 3:s.protocol=i.int32();break;case 4:s.os=i.string();break;case 5:s.osVersion=i.string();break;case 6:s.deviceModel=i.string();break;case 7:s.browser=i.string();break;case 8:s.browserVersion=i.string();break;case 9:s.address=i.string();break;default:i.skipType(7&e)}}return s},fromJSON:e=>({sdk:isSet$1(e.sdk)?clientInfo_SDKFromJSON(e.sdk):0,version:isSet$1(e.version)?String(e.version):"",protocol:isSet$1(e.protocol)?Number(e.protocol):0,os:isSet$1(e.os)?String(e.os):"",osVersion:isSet$1(e.osVersion)?String(e.osVersion):"",deviceModel:isSet$1(e.deviceModel)?String(e.deviceModel):"",browser:isSet$1(e.browser)?String(e.browser):"",browserVersion:isSet$1(e.browserVersion)?String(e.browserVersion):"",address:isSet$1(e.address)?String(e.address):""}),toJSON(e){const t={};return void 0!==e.sdk&&(t.sdk=function clientInfo_SDKToJSON(e){switch(e){case Pe.UNKNOWN:return"UNKNOWN";case Pe.JS:return"JS";case Pe.SWIFT:return"SWIFT";case Pe.ANDROID:return"ANDROID";case Pe.FLUTTER:return"FLUTTER";case Pe.GO:return"GO";case Pe.UNITY:return"UNITY";default:return"UNKNOWN"}}(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),t},fromPartial(e){const t={sdk:0,version:"",protocol:0,os:"",osVersion:"",deviceModel:"",browser:"",browserVersion:"",address:""};return t.sdk=e.sdk??0,t.version=e.version??"",t.protocol=e.protocol??0,t.os=e.os??"",t.osVersion=e.osVersion??"",t.deviceModel=e.deviceModel??"",t.browser=e.browser??"",t.browserVersion=e.browserVersion??"",t.address=e.address??"",t}};const Fe={encode:(e,t=Ee.Writer.create())=>(void 0!==e.video&&Ve.encode(e.video,t.uint32(10).fork()).ldelim(),void 0!==e.screen&&Ve.encode(e.screen,t.uint32(18).fork()).ldelim(),0!==e.resumeConnection&&t.uint32(24).int32(e.resumeConnection),t),decode(e,t){const i=e instanceof Ee.Reader?e:new Ee.Reader(e);let n=void 0===t?i.len:i.pos+t;const s={video:void 0,screen:void 0,resumeConnection:0};for(;i.pos>>3){case 1:s.video=Ve.decode(i,i.uint32());break;case 2:s.screen=Ve.decode(i,i.uint32());break;case 3:s.resumeConnection=i.int32();break;default:i.skipType(7&e)}}return s},fromJSON:e=>({video:isSet$1(e.video)?Ve.fromJSON(e.video):void 0,screen:isSet$1(e.screen)?Ve.fromJSON(e.screen):void 0,resumeConnection:isSet$1(e.resumeConnection)?clientConfigSettingFromJSON(e.resumeConnection):0}),toJSON(e){const t={};return void 0!==e.video&&(t.video=e.video?Ve.toJSON(e.video):void 0),void 0!==e.screen&&(t.screen=e.screen?Ve.toJSON(e.screen):void 0),void 0!==e.resumeConnection&&(t.resumeConnection=clientConfigSettingToJSON(e.resumeConnection)),t},fromPartial(e){const t={video:void 0,screen:void 0,resumeConnection:0};return t.video=void 0!==e.video&&null!==e.video?Ve.fromPartial(e.video):void 0,t.screen=void 0!==e.screen&&null!==e.screen?Ve.fromPartial(e.screen):void 0,t.resumeConnection=e.resumeConnection??0,t}};const Ve={encode:(e,t=Ee.Writer.create())=>(0!==e.hardwareEncoder&&t.uint32(8).int32(e.hardwareEncoder),t),decode(e,t){const i=e instanceof Ee.Reader?e:new Ee.Reader(e);let n=void 0===t?i.len:i.pos+t;const s={hardwareEncoder:0};for(;i.pos>>3==1)s.hardwareEncoder=i.int32();else i.skipType(7&e)}return s},fromJSON:e=>({hardwareEncoder:isSet$1(e.hardwareEncoder)?clientConfigSettingFromJSON(e.hardwareEncoder):0}),toJSON(e){const t={};return void 0!==e.hardwareEncoder&&(t.hardwareEncoder=clientConfigSettingToJSON(e.hardwareEncoder)),t},fromPartial(e){const t={hardwareEncoder:0};return t.hardwareEncoder=e.hardwareEncoder??0,t}};var je=(()=>{if(void 0!==je)return je;if("undefined"!=typeof self)return self;if("undefined"!=typeof window)return window;if(void 0!==__webpack_require__.g)return __webpack_require__.g;throw"Unable to locate global object"})();const $e=je.atob||(e=>je.Buffer.from(e,"base64").toString("binary"));function bytesFromBase64(e){const t=$e(e),i=new Uint8Array(t.length);for(let e=0;eje.Buffer.from(e,"binary").toString("base64"));function longToNumber(e){if(e.gt(Number.MAX_SAFE_INTEGER))throw new je.Error("Value is larger than Number.MAX_SAFE_INTEGER");return e.toNumber()}function isSet$1(e){return null!=e}var We,Ge;function signalTargetFromJSON(e){switch(e){case 0:case"PUBLISHER":return We.PUBLISHER;case 1:case"SUBSCRIBER":return We.SUBSCRIBER;default:return We.UNRECOGNIZED}}function signalTargetToJSON(e){switch(e){case We.PUBLISHER:return"PUBLISHER";case We.SUBSCRIBER:return"SUBSCRIBER";default:return"UNKNOWN"}}function streamStateFromJSON(e){switch(e){case 0:case"ACTIVE":return Ge.ACTIVE;case 1:case"PAUSED":return Ge.PAUSED;default:return Ge.UNRECOGNIZED}}Ee.util.Long!==p&&(Ee.util.Long=p,Ee.configure()),function(e){e[e.PUBLISHER=0]="PUBLISHER",e[e.SUBSCRIBER=1]="SUBSCRIBER",e[e.UNRECOGNIZED=-1]="UNRECOGNIZED"}(We||(We={})),function(e){e[e.ACTIVE=0]="ACTIVE",e[e.PAUSED=1]="PAUSED",e[e.UNRECOGNIZED=-1]="UNRECOGNIZED"}(Ge||(Ge={}));const Qe={encode:(e,t=Ee.Writer.create())=>(void 0!==e.offer&&tt.encode(e.offer,t.uint32(10).fork()).ldelim(),void 0!==e.answer&&tt.encode(e.answer,t.uint32(18).fork()).ldelim(),void 0!==e.trickle&&Ke.encode(e.trickle,t.uint32(26).fork()).ldelim(),void 0!==e.addTrack&&ze.encode(e.addTrack,t.uint32(34).fork()).ldelim(),void 0!==e.mute&&Ze.encode(e.mute,t.uint32(42).fork()).ldelim(),void 0!==e.subscription&&rt.encode(e.subscription,t.uint32(50).fork()).ldelim(),void 0!==e.trackSetting&&nt.encode(e.trackSetting,t.uint32(58).fork()).ldelim(),void 0!==e.leave&&st.encode(e.leave,t.uint32(66).fork()).ldelim(),void 0!==e.updateLayers&&at.encode(e.updateLayers,t.uint32(82).fork()).ldelim(),void 0!==e.subscriptionPermission&&vt.encode(e.subscriptionPermission,t.uint32(90).fork()).ldelim(),void 0!==e.syncState&&bt.encode(e.syncState,t.uint32(98).fork()).ldelim(),void 0!==e.simulate&&yt.encode(e.simulate,t.uint32(106).fork()).ldelim(),t),decode(e,t){const i=e instanceof Ee.Reader?e:new Ee.Reader(e);let n=void 0===t?i.len:i.pos+t;const s={offer:void 0,answer:void 0,trickle:void 0,addTrack:void 0,mute:void 0,subscription:void 0,trackSetting:void 0,leave:void 0,updateLayers:void 0,subscriptionPermission:void 0,syncState:void 0,simulate:void 0};for(;i.pos>>3){case 1:s.offer=tt.decode(i,i.uint32());break;case 2:s.answer=tt.decode(i,i.uint32());break;case 3:s.trickle=Ke.decode(i,i.uint32());break;case 4:s.addTrack=ze.decode(i,i.uint32());break;case 5:s.mute=Ze.decode(i,i.uint32());break;case 6:s.subscription=rt.decode(i,i.uint32());break;case 7:s.trackSetting=nt.decode(i,i.uint32());break;case 8:s.leave=st.decode(i,i.uint32());break;case 10:s.updateLayers=at.decode(i,i.uint32());break;case 11:s.subscriptionPermission=vt.decode(i,i.uint32());break;case 12:s.syncState=bt.decode(i,i.uint32());break;case 13:s.simulate=yt.decode(i,i.uint32());break;default:i.skipType(7&e)}}return s},fromJSON:e=>({offer:isSet(e.offer)?tt.fromJSON(e.offer):void 0,answer:isSet(e.answer)?tt.fromJSON(e.answer):void 0,trickle:isSet(e.trickle)?Ke.fromJSON(e.trickle):void 0,addTrack:isSet(e.addTrack)?ze.fromJSON(e.addTrack):void 0,mute:isSet(e.mute)?Ze.fromJSON(e.mute):void 0,subscription:isSet(e.subscription)?rt.fromJSON(e.subscription):void 0,trackSetting:isSet(e.trackSetting)?nt.fromJSON(e.trackSetting):void 0,leave:isSet(e.leave)?st.fromJSON(e.leave):void 0,updateLayers:isSet(e.updateLayers)?at.fromJSON(e.updateLayers):void 0,subscriptionPermission:isSet(e.subscriptionPermission)?vt.fromJSON(e.subscriptionPermission):void 0,syncState:isSet(e.syncState)?bt.fromJSON(e.syncState):void 0,simulate:isSet(e.simulate)?yt.fromJSON(e.simulate):void 0}),toJSON(e){const t={};return void 0!==e.offer&&(t.offer=e.offer?tt.toJSON(e.offer):void 0),void 0!==e.answer&&(t.answer=e.answer?tt.toJSON(e.answer):void 0),void 0!==e.trickle&&(t.trickle=e.trickle?Ke.toJSON(e.trickle):void 0),void 0!==e.addTrack&&(t.addTrack=e.addTrack?ze.toJSON(e.addTrack):void 0),void 0!==e.mute&&(t.mute=e.mute?Ze.toJSON(e.mute):void 0),void 0!==e.subscription&&(t.subscription=e.subscription?rt.toJSON(e.subscription):void 0),void 0!==e.trackSetting&&(t.trackSetting=e.trackSetting?nt.toJSON(e.trackSetting):void 0),void 0!==e.leave&&(t.leave=e.leave?st.toJSON(e.leave):void 0),void 0!==e.updateLayers&&(t.updateLayers=e.updateLayers?at.toJSON(e.updateLayers):void 0),void 0!==e.subscriptionPermission&&(t.subscriptionPermission=e.subscriptionPermission?vt.toJSON(e.subscriptionPermission):void 0),void 0!==e.syncState&&(t.syncState=e.syncState?bt.toJSON(e.syncState):void 0),void 0!==e.simulate&&(t.simulate=e.simulate?yt.toJSON(e.simulate):void 0),t},fromPartial(e){const t={offer:void 0,answer:void 0,trickle:void 0,addTrack:void 0,mute:void 0,subscription:void 0,trackSetting:void 0,leave:void 0,updateLayers:void 0,subscriptionPermission:void 0,syncState:void 0,simulate:void 0};return t.offer=void 0!==e.offer&&null!==e.offer?tt.fromPartial(e.offer):void 0,t.answer=void 0!==e.answer&&null!==e.answer?tt.fromPartial(e.answer):void 0,t.trickle=void 0!==e.trickle&&null!==e.trickle?Ke.fromPartial(e.trickle):void 0,t.addTrack=void 0!==e.addTrack&&null!==e.addTrack?ze.fromPartial(e.addTrack):void 0,t.mute=void 0!==e.mute&&null!==e.mute?Ze.fromPartial(e.mute):void 0,t.subscription=void 0!==e.subscription&&null!==e.subscription?rt.fromPartial(e.subscription):void 0,t.trackSetting=void 0!==e.trackSetting&&null!==e.trackSetting?nt.fromPartial(e.trackSetting):void 0,t.leave=void 0!==e.leave&&null!==e.leave?st.fromPartial(e.leave):void 0,t.updateLayers=void 0!==e.updateLayers&&null!==e.updateLayers?at.fromPartial(e.updateLayers):void 0,t.subscriptionPermission=void 0!==e.subscriptionPermission&&null!==e.subscriptionPermission?vt.fromPartial(e.subscriptionPermission):void 0,t.syncState=void 0!==e.syncState&&null!==e.syncState?bt.fromPartial(e.syncState):void 0,t.simulate=void 0!==e.simulate&&null!==e.simulate?yt.fromPartial(e.simulate):void 0,t}};const He={encode:(e,t=Ee.Writer.create())=>(void 0!==e.join&&Ye.encode(e.join,t.uint32(10).fork()).ldelim(),void 0!==e.answer&&tt.encode(e.answer,t.uint32(18).fork()).ldelim(),void 0!==e.offer&&tt.encode(e.offer,t.uint32(26).fork()).ldelim(),void 0!==e.trickle&&Ke.encode(e.trickle,t.uint32(34).fork()).ldelim(),void 0!==e.update&&it.encode(e.update,t.uint32(42).fork()).ldelim(),void 0!==e.trackPublished&&Xe.encode(e.trackPublished,t.uint32(50).fork()).ldelim(),void 0!==e.leave&&st.encode(e.leave,t.uint32(66).fork()).ldelim(),void 0!==e.mute&&Ze.encode(e.mute,t.uint32(74).fork()).ldelim(),void 0!==e.speakersChanged&&ct.encode(e.speakersChanged,t.uint32(82).fork()).ldelim(),void 0!==e.roomUpdate&&dt.encode(e.roomUpdate,t.uint32(90).fork()).ldelim(),void 0!==e.connectionQuality&<.encode(e.connectionQuality,t.uint32(98).fork()).ldelim(),void 0!==e.streamStateUpdate&&pt.encode(e.streamStateUpdate,t.uint32(106).fork()).ldelim(),void 0!==e.subscribedQualityUpdate&&ft.encode(e.subscribedQualityUpdate,t.uint32(114).fork()).ldelim(),void 0!==e.subscriptionPermissionUpdate&&St.encode(e.subscriptionPermissionUpdate,t.uint32(122).fork()).ldelim(),void 0!==e.refreshToken&&t.uint32(130).string(e.refreshToken),void 0!==e.trackUnpublished&&et.encode(e.trackUnpublished,t.uint32(138).fork()).ldelim(),t),decode(e,t){const i=e instanceof Ee.Reader?e:new Ee.Reader(e);let n=void 0===t?i.len:i.pos+t;const s={join:void 0,answer:void 0,offer:void 0,trickle:void 0,update:void 0,trackPublished:void 0,leave:void 0,mute:void 0,speakersChanged:void 0,roomUpdate:void 0,connectionQuality:void 0,streamStateUpdate:void 0,subscribedQualityUpdate:void 0,subscriptionPermissionUpdate:void 0,refreshToken:void 0,trackUnpublished:void 0};for(;i.pos>>3){case 1:s.join=Ye.decode(i,i.uint32());break;case 2:s.answer=tt.decode(i,i.uint32());break;case 3:s.offer=tt.decode(i,i.uint32());break;case 4:s.trickle=Ke.decode(i,i.uint32());break;case 5:s.update=it.decode(i,i.uint32());break;case 6:s.trackPublished=Xe.decode(i,i.uint32());break;case 8:s.leave=st.decode(i,i.uint32());break;case 9:s.mute=Ze.decode(i,i.uint32());break;case 10:s.speakersChanged=ct.decode(i,i.uint32());break;case 11:s.roomUpdate=dt.decode(i,i.uint32());break;case 12:s.connectionQuality=lt.decode(i,i.uint32());break;case 13:s.streamStateUpdate=pt.decode(i,i.uint32());break;case 14:s.subscribedQualityUpdate=ft.decode(i,i.uint32());break;case 15:s.subscriptionPermissionUpdate=St.decode(i,i.uint32());break;case 16:s.refreshToken=i.string();break;case 17:s.trackUnpublished=et.decode(i,i.uint32());break;default:i.skipType(7&e)}}return s},fromJSON:e=>({join:isSet(e.join)?Ye.fromJSON(e.join):void 0,answer:isSet(e.answer)?tt.fromJSON(e.answer):void 0,offer:isSet(e.offer)?tt.fromJSON(e.offer):void 0,trickle:isSet(e.trickle)?Ke.fromJSON(e.trickle):void 0,update:isSet(e.update)?it.fromJSON(e.update):void 0,trackPublished:isSet(e.trackPublished)?Xe.fromJSON(e.trackPublished):void 0,leave:isSet(e.leave)?st.fromJSON(e.leave):void 0,mute:isSet(e.mute)?Ze.fromJSON(e.mute):void 0,speakersChanged:isSet(e.speakersChanged)?ct.fromJSON(e.speakersChanged):void 0,roomUpdate:isSet(e.roomUpdate)?dt.fromJSON(e.roomUpdate):void 0,connectionQuality:isSet(e.connectionQuality)?lt.fromJSON(e.connectionQuality):void 0,streamStateUpdate:isSet(e.streamStateUpdate)?pt.fromJSON(e.streamStateUpdate):void 0,subscribedQualityUpdate:isSet(e.subscribedQualityUpdate)?ft.fromJSON(e.subscribedQualityUpdate):void 0,subscriptionPermissionUpdate:isSet(e.subscriptionPermissionUpdate)?St.fromJSON(e.subscriptionPermissionUpdate):void 0,refreshToken:isSet(e.refreshToken)?String(e.refreshToken):void 0,trackUnpublished:isSet(e.trackUnpublished)?et.fromJSON(e.trackUnpublished):void 0}),toJSON(e){const t={};return void 0!==e.join&&(t.join=e.join?Ye.toJSON(e.join):void 0),void 0!==e.answer&&(t.answer=e.answer?tt.toJSON(e.answer):void 0),void 0!==e.offer&&(t.offer=e.offer?tt.toJSON(e.offer):void 0),void 0!==e.trickle&&(t.trickle=e.trickle?Ke.toJSON(e.trickle):void 0),void 0!==e.update&&(t.update=e.update?it.toJSON(e.update):void 0),void 0!==e.trackPublished&&(t.trackPublished=e.trackPublished?Xe.toJSON(e.trackPublished):void 0),void 0!==e.leave&&(t.leave=e.leave?st.toJSON(e.leave):void 0),void 0!==e.mute&&(t.mute=e.mute?Ze.toJSON(e.mute):void 0),void 0!==e.speakersChanged&&(t.speakersChanged=e.speakersChanged?ct.toJSON(e.speakersChanged):void 0),void 0!==e.roomUpdate&&(t.roomUpdate=e.roomUpdate?dt.toJSON(e.roomUpdate):void 0),void 0!==e.connectionQuality&&(t.connectionQuality=e.connectionQuality?lt.toJSON(e.connectionQuality):void 0),void 0!==e.streamStateUpdate&&(t.streamStateUpdate=e.streamStateUpdate?pt.toJSON(e.streamStateUpdate):void 0),void 0!==e.subscribedQualityUpdate&&(t.subscribedQualityUpdate=e.subscribedQualityUpdate?ft.toJSON(e.subscribedQualityUpdate):void 0),void 0!==e.subscriptionPermissionUpdate&&(t.subscriptionPermissionUpdate=e.subscriptionPermissionUpdate?St.toJSON(e.subscriptionPermissionUpdate):void 0),void 0!==e.refreshToken&&(t.refreshToken=e.refreshToken),void 0!==e.trackUnpublished&&(t.trackUnpublished=e.trackUnpublished?et.toJSON(e.trackUnpublished):void 0),t},fromPartial(e){const t={join:void 0,answer:void 0,offer:void 0,trickle:void 0,update:void 0,trackPublished:void 0,leave:void 0,mute:void 0,speakersChanged:void 0,roomUpdate:void 0,connectionQuality:void 0,streamStateUpdate:void 0,subscribedQualityUpdate:void 0,subscriptionPermissionUpdate:void 0,refreshToken:void 0,trackUnpublished:void 0};return t.join=void 0!==e.join&&null!==e.join?Ye.fromPartial(e.join):void 0,t.answer=void 0!==e.answer&&null!==e.answer?tt.fromPartial(e.answer):void 0,t.offer=void 0!==e.offer&&null!==e.offer?tt.fromPartial(e.offer):void 0,t.trickle=void 0!==e.trickle&&null!==e.trickle?Ke.fromPartial(e.trickle):void 0,t.update=void 0!==e.update&&null!==e.update?it.fromPartial(e.update):void 0,t.trackPublished=void 0!==e.trackPublished&&null!==e.trackPublished?Xe.fromPartial(e.trackPublished):void 0,t.leave=void 0!==e.leave&&null!==e.leave?st.fromPartial(e.leave):void 0,t.mute=void 0!==e.mute&&null!==e.mute?Ze.fromPartial(e.mute):void 0,t.speakersChanged=void 0!==e.speakersChanged&&null!==e.speakersChanged?ct.fromPartial(e.speakersChanged):void 0,t.roomUpdate=void 0!==e.roomUpdate&&null!==e.roomUpdate?dt.fromPartial(e.roomUpdate):void 0,t.connectionQuality=void 0!==e.connectionQuality&&null!==e.connectionQuality?lt.fromPartial(e.connectionQuality):void 0,t.streamStateUpdate=void 0!==e.streamStateUpdate&&null!==e.streamStateUpdate?pt.fromPartial(e.streamStateUpdate):void 0,t.subscribedQualityUpdate=void 0!==e.subscribedQualityUpdate&&null!==e.subscribedQualityUpdate?ft.fromPartial(e.subscribedQualityUpdate):void 0,t.subscriptionPermissionUpdate=void 0!==e.subscriptionPermissionUpdate&&null!==e.subscriptionPermissionUpdate?St.fromPartial(e.subscriptionPermissionUpdate):void 0,t.refreshToken=e.refreshToken??void 0,t.trackUnpublished=void 0!==e.trackUnpublished&&null!==e.trackUnpublished?et.fromPartial(e.trackUnpublished):void 0,t}};const ze={encode(e,t=Ee.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)Ae.encode(i,t.uint32(74).fork()).ldelim();return t},decode(e,t){const i=e instanceof Ee.Reader?e:new Ee.Reader(e);let n=void 0===t?i.len:i.pos+t;const s={cid:"",name:"",type:0,width:0,height:0,muted:!1,disableDtx:!1,source:0,layers:[]};for(;i.pos>>3){case 1:s.cid=i.string();break;case 2:s.name=i.string();break;case 3:s.type=i.int32();break;case 4:s.width=i.uint32();break;case 5:s.height=i.uint32();break;case 6:s.muted=i.bool();break;case 7:s.disableDtx=i.bool();break;case 8:s.source=i.int32();break;case 9:s.layers.push(Ae.decode(i,i.uint32()));break;default:i.skipType(7&e)}}return s},fromJSON:e=>({cid:isSet(e.cid)?String(e.cid):"",name:isSet(e.name)?String(e.name):"",type:isSet(e.type)?trackTypeFromJSON(e.type):0,width:isSet(e.width)?Number(e.width):0,height:isSet(e.height)?Number(e.height):0,muted:!!isSet(e.muted)&&Boolean(e.muted),disableDtx:!!isSet(e.disableDtx)&&Boolean(e.disableDtx),source:isSet(e.source)?trackSourceFromJSON(e.source):0,layers:Array.isArray(e?.layers)?e.layers.map((e=>Ae.fromJSON(e))):[]}),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=trackTypeToJSON(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=trackSourceToJSON(e.source)),e.layers?t.layers=e.layers.map((e=>e?Ae.toJSON(e):void 0)):t.layers=[],t},fromPartial(e){const t={cid:"",name:"",type:0,width:0,height:0,muted:!1,disableDtx:!1,source:0,layers:[]};return t.cid=e.cid??"",t.name=e.name??"",t.type=e.type??0,t.width=e.width??0,t.height=e.height??0,t.muted=e.muted??!1,t.disableDtx=e.disableDtx??!1,t.source=e.source??0,t.layers=e.layers?.map((e=>Ae.fromPartial(e)))||[],t}};const Ke={encode:(e,t=Ee.Writer.create())=>(""!==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 Ee.Reader?e:new Ee.Reader(e);let n=void 0===t?i.len:i.pos+t;const s={candidateInit:"",target:0};for(;i.pos>>3){case 1:s.candidateInit=i.string();break;case 2:s.target=i.int32();break;default:i.skipType(7&e)}}return s},fromJSON:e=>({candidateInit:isSet(e.candidateInit)?String(e.candidateInit):"",target:isSet(e.target)?signalTargetFromJSON(e.target):0}),toJSON(e){const t={};return void 0!==e.candidateInit&&(t.candidateInit=e.candidateInit),void 0!==e.target&&(t.target=signalTargetToJSON(e.target)),t},fromPartial(e){const t={candidateInit:"",target:0};return t.candidateInit=e.candidateInit??"",t.target=e.target??0,t}};const Ze={encode:(e,t=Ee.Writer.create())=>(""!==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 Ee.Reader?e:new Ee.Reader(e);let n=void 0===t?i.len:i.pos+t;const s={sid:"",muted:!1};for(;i.pos>>3){case 1:s.sid=i.string();break;case 2:s.muted=i.bool();break;default:i.skipType(7&e)}}return s},fromJSON:e=>({sid:isSet(e.sid)?String(e.sid):"",muted:!!isSet(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},fromPartial(e){const t={sid:"",muted:!1};return t.sid=e.sid??"",t.muted=e.muted??!1,t}};const Ye={encode(e,t=Ee.Writer.create()){void 0!==e.room&&Oe.encode(e.room,t.uint32(10).fork()).ldelim(),void 0!==e.participant&&Le.encode(e.participant,t.uint32(18).fork()).ldelim();for(const i of e.otherParticipants)Le.encode(i,t.uint32(26).fork()).ldelim();""!==e.serverVersion&&t.uint32(34).string(e.serverVersion);for(const i of e.iceServers)ot.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&&Fe.encode(e.clientConfiguration,t.uint32(66).fork()).ldelim(),""!==e.serverRegion&&t.uint32(74).string(e.serverRegion),t},decode(e,t){const i=e instanceof Ee.Reader?e:new Ee.Reader(e);let n=void 0===t?i.len:i.pos+t;const s={room:void 0,participant:void 0,otherParticipants:[],serverVersion:"",iceServers:[],subscriberPrimary:!1,alternativeUrl:"",clientConfiguration:void 0,serverRegion:""};for(;i.pos>>3){case 1:s.room=Oe.decode(i,i.uint32());break;case 2:s.participant=Le.decode(i,i.uint32());break;case 3:s.otherParticipants.push(Le.decode(i,i.uint32()));break;case 4:s.serverVersion=i.string();break;case 5:s.iceServers.push(ot.decode(i,i.uint32()));break;case 6:s.subscriberPrimary=i.bool();break;case 7:s.alternativeUrl=i.string();break;case 8:s.clientConfiguration=Fe.decode(i,i.uint32());break;case 9:s.serverRegion=i.string();break;default:i.skipType(7&e)}}return s},fromJSON:e=>({room:isSet(e.room)?Oe.fromJSON(e.room):void 0,participant:isSet(e.participant)?Le.fromJSON(e.participant):void 0,otherParticipants:Array.isArray(e?.otherParticipants)?e.otherParticipants.map((e=>Le.fromJSON(e))):[],serverVersion:isSet(e.serverVersion)?String(e.serverVersion):"",iceServers:Array.isArray(e?.iceServers)?e.iceServers.map((e=>ot.fromJSON(e))):[],subscriberPrimary:!!isSet(e.subscriberPrimary)&&Boolean(e.subscriberPrimary),alternativeUrl:isSet(e.alternativeUrl)?String(e.alternativeUrl):"",clientConfiguration:isSet(e.clientConfiguration)?Fe.fromJSON(e.clientConfiguration):void 0,serverRegion:isSet(e.serverRegion)?String(e.serverRegion):""}),toJSON(e){const t={};return void 0!==e.room&&(t.room=e.room?Oe.toJSON(e.room):void 0),void 0!==e.participant&&(t.participant=e.participant?Le.toJSON(e.participant):void 0),e.otherParticipants?t.otherParticipants=e.otherParticipants.map((e=>e?Le.toJSON(e):void 0)):t.otherParticipants=[],void 0!==e.serverVersion&&(t.serverVersion=e.serverVersion),e.iceServers?t.iceServers=e.iceServers.map((e=>e?ot.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?Fe.toJSON(e.clientConfiguration):void 0),void 0!==e.serverRegion&&(t.serverRegion=e.serverRegion),t},fromPartial(e){const t={room:void 0,participant:void 0,otherParticipants:[],serverVersion:"",iceServers:[],subscriberPrimary:!1,alternativeUrl:"",clientConfiguration:void 0,serverRegion:""};return t.room=void 0!==e.room&&null!==e.room?Oe.fromPartial(e.room):void 0,t.participant=void 0!==e.participant&&null!==e.participant?Le.fromPartial(e.participant):void 0,t.otherParticipants=e.otherParticipants?.map((e=>Le.fromPartial(e)))||[],t.serverVersion=e.serverVersion??"",t.iceServers=e.iceServers?.map((e=>ot.fromPartial(e)))||[],t.subscriberPrimary=e.subscriberPrimary??!1,t.alternativeUrl=e.alternativeUrl??"",t.clientConfiguration=void 0!==e.clientConfiguration&&null!==e.clientConfiguration?Fe.fromPartial(e.clientConfiguration):void 0,t.serverRegion=e.serverRegion??"",t}};const Xe={encode:(e,t=Ee.Writer.create())=>(""!==e.cid&&t.uint32(10).string(e.cid),void 0!==e.track&&De.encode(e.track,t.uint32(18).fork()).ldelim(),t),decode(e,t){const i=e instanceof Ee.Reader?e:new Ee.Reader(e);let n=void 0===t?i.len:i.pos+t;const s={cid:"",track:void 0};for(;i.pos>>3){case 1:s.cid=i.string();break;case 2:s.track=De.decode(i,i.uint32());break;default:i.skipType(7&e)}}return s},fromJSON:e=>({cid:isSet(e.cid)?String(e.cid):"",track:isSet(e.track)?De.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?De.toJSON(e.track):void 0),t},fromPartial(e){const t={cid:"",track:void 0};return t.cid=e.cid??"",t.track=void 0!==e.track&&null!==e.track?De.fromPartial(e.track):void 0,t}};const et={encode:(e,t=Ee.Writer.create())=>(""!==e.trackSid&&t.uint32(10).string(e.trackSid),t),decode(e,t){const i=e instanceof Ee.Reader?e:new Ee.Reader(e);let n=void 0===t?i.len:i.pos+t;const s={trackSid:""};for(;i.pos>>3==1)s.trackSid=i.string();else i.skipType(7&e)}return s},fromJSON:e=>({trackSid:isSet(e.trackSid)?String(e.trackSid):""}),toJSON(e){const t={};return void 0!==e.trackSid&&(t.trackSid=e.trackSid),t},fromPartial(e){const t={trackSid:""};return t.trackSid=e.trackSid??"",t}};const tt={encode:(e,t=Ee.Writer.create())=>(""!==e.type&&t.uint32(10).string(e.type),""!==e.sdp&&t.uint32(18).string(e.sdp),t),decode(e,t){const i=e instanceof Ee.Reader?e:new Ee.Reader(e);let n=void 0===t?i.len:i.pos+t;const s={type:"",sdp:""};for(;i.pos>>3){case 1:s.type=i.string();break;case 2:s.sdp=i.string();break;default:i.skipType(7&e)}}return s},fromJSON:e=>({type:isSet(e.type)?String(e.type):"",sdp:isSet(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},fromPartial(e){const t={type:"",sdp:""};return t.type=e.type??"",t.sdp=e.sdp??"",t}};const it={encode(e,t=Ee.Writer.create()){for(const i of e.participants)Le.encode(i,t.uint32(10).fork()).ldelim();return t},decode(e,t){const i=e instanceof Ee.Reader?e:new Ee.Reader(e);let n=void 0===t?i.len:i.pos+t;const s={participants:[]};for(;i.pos>>3==1)s.participants.push(Le.decode(i,i.uint32()));else i.skipType(7&e)}return s},fromJSON:e=>({participants:Array.isArray(e?.participants)?e.participants.map((e=>Le.fromJSON(e))):[]}),toJSON(e){const t={};return e.participants?t.participants=e.participants.map((e=>e?Le.toJSON(e):void 0)):t.participants=[],t},fromPartial(e){const t={participants:[]};return t.participants=e.participants?.map((e=>Le.fromPartial(e)))||[],t}};const rt={encode(e,t=Ee.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)Be.encode(i,t.uint32(26).fork()).ldelim();return t},decode(e,t){const i=e instanceof Ee.Reader?e:new Ee.Reader(e);let n=void 0===t?i.len:i.pos+t;const s={trackSids:[],subscribe:!1,participantTracks:[]};for(;i.pos>>3){case 1:s.trackSids.push(i.string());break;case 2:s.subscribe=i.bool();break;case 3:s.participantTracks.push(Be.decode(i,i.uint32()));break;default:i.skipType(7&e)}}return s},fromJSON:e=>({trackSids:Array.isArray(e?.trackSids)?e.trackSids.map((e=>String(e))):[],subscribe:!!isSet(e.subscribe)&&Boolean(e.subscribe),participantTracks:Array.isArray(e?.participantTracks)?e.participantTracks.map((e=>Be.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?Be.toJSON(e):void 0)):t.participantTracks=[],t},fromPartial(e){const t={trackSids:[],subscribe:!1,participantTracks:[]};return t.trackSids=e.trackSids?.map((e=>e))||[],t.subscribe=e.subscribe??!1,t.participantTracks=e.participantTracks?.map((e=>Be.fromPartial(e)))||[],t}};const nt={encode(e,t=Ee.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),t},decode(e,t){const i=e instanceof Ee.Reader?e:new Ee.Reader(e);let n=void 0===t?i.len:i.pos+t;const s={trackSids:[],disabled:!1,quality:0,width:0,height:0};for(;i.pos>>3){case 1:s.trackSids.push(i.string());break;case 3:s.disabled=i.bool();break;case 4:s.quality=i.int32();break;case 5:s.width=i.uint32();break;case 6:s.height=i.uint32();break;default:i.skipType(7&e)}}return s},fromJSON:e=>({trackSids:Array.isArray(e?.trackSids)?e.trackSids.map((e=>String(e))):[],disabled:!!isSet(e.disabled)&&Boolean(e.disabled),quality:isSet(e.quality)?videoQualityFromJSON(e.quality):0,width:isSet(e.width)?Number(e.width):0,height:isSet(e.height)?Number(e.height):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=videoQualityToJSON(e.quality)),void 0!==e.width&&(t.width=Math.round(e.width)),void 0!==e.height&&(t.height=Math.round(e.height)),t},fromPartial(e){const t={trackSids:[],disabled:!1,quality:0,width:0,height:0};return t.trackSids=e.trackSids?.map((e=>e))||[],t.disabled=e.disabled??!1,t.quality=e.quality??0,t.width=e.width??0,t.height=e.height??0,t}};const st={encode:(e,t=Ee.Writer.create())=>(!0===e.canReconnect&&t.uint32(8).bool(e.canReconnect),t),decode(e,t){const i=e instanceof Ee.Reader?e:new Ee.Reader(e);let n=void 0===t?i.len:i.pos+t;const s={canReconnect:!1};for(;i.pos>>3==1)s.canReconnect=i.bool();else i.skipType(7&e)}return s},fromJSON:e=>({canReconnect:!!isSet(e.canReconnect)&&Boolean(e.canReconnect)}),toJSON(e){const t={};return void 0!==e.canReconnect&&(t.canReconnect=e.canReconnect),t},fromPartial(e){const t={canReconnect:!1};return t.canReconnect=e.canReconnect??!1,t}};const at={encode(e,t=Ee.Writer.create()){""!==e.trackSid&&t.uint32(10).string(e.trackSid);for(const i of e.layers)Ae.encode(i,t.uint32(18).fork()).ldelim();return t},decode(e,t){const i=e instanceof Ee.Reader?e:new Ee.Reader(e);let n=void 0===t?i.len:i.pos+t;const s={trackSid:"",layers:[]};for(;i.pos>>3){case 1:s.trackSid=i.string();break;case 2:s.layers.push(Ae.decode(i,i.uint32()));break;default:i.skipType(7&e)}}return s},fromJSON:e=>({trackSid:isSet(e.trackSid)?String(e.trackSid):"",layers:Array.isArray(e?.layers)?e.layers.map((e=>Ae.fromJSON(e))):[]}),toJSON(e){const t={};return void 0!==e.trackSid&&(t.trackSid=e.trackSid),e.layers?t.layers=e.layers.map((e=>e?Ae.toJSON(e):void 0)):t.layers=[],t},fromPartial(e){const t={trackSid:"",layers:[]};return t.trackSid=e.trackSid??"",t.layers=e.layers?.map((e=>Ae.fromPartial(e)))||[],t}};const ot={encode(e,t=Ee.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 Ee.Reader?e:new Ee.Reader(e);let n=void 0===t?i.len:i.pos+t;const s={urls:[],username:"",credential:""};for(;i.pos>>3){case 1:s.urls.push(i.string());break;case 2:s.username=i.string();break;case 3:s.credential=i.string();break;default:i.skipType(7&e)}}return s},fromJSON:e=>({urls:Array.isArray(e?.urls)?e.urls.map((e=>String(e))):[],username:isSet(e.username)?String(e.username):"",credential:isSet(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},fromPartial(e){const t={urls:[],username:"",credential:""};return t.urls=e.urls?.map((e=>e))||[],t.username=e.username??"",t.credential=e.credential??"",t}};const ct={encode(e,t=Ee.Writer.create()){for(const i of e.speakers)Me.encode(i,t.uint32(10).fork()).ldelim();return t},decode(e,t){const i=e instanceof Ee.Reader?e:new Ee.Reader(e);let n=void 0===t?i.len:i.pos+t;const s={speakers:[]};for(;i.pos>>3==1)s.speakers.push(Me.decode(i,i.uint32()));else i.skipType(7&e)}return s},fromJSON:e=>({speakers:Array.isArray(e?.speakers)?e.speakers.map((e=>Me.fromJSON(e))):[]}),toJSON(e){const t={};return e.speakers?t.speakers=e.speakers.map((e=>e?Me.toJSON(e):void 0)):t.speakers=[],t},fromPartial(e){const t={speakers:[]};return t.speakers=e.speakers?.map((e=>Me.fromPartial(e)))||[],t}};const dt={encode:(e,t=Ee.Writer.create())=>(void 0!==e.room&&Oe.encode(e.room,t.uint32(10).fork()).ldelim(),t),decode(e,t){const i=e instanceof Ee.Reader?e:new Ee.Reader(e);let n=void 0===t?i.len:i.pos+t;const s={room:void 0};for(;i.pos>>3==1)s.room=Oe.decode(i,i.uint32());else i.skipType(7&e)}return s},fromJSON:e=>({room:isSet(e.room)?Oe.fromJSON(e.room):void 0}),toJSON(e){const t={};return void 0!==e.room&&(t.room=e.room?Oe.toJSON(e.room):void 0),t},fromPartial(e){const t={room:void 0};return t.room=void 0!==e.room&&null!==e.room?Oe.fromPartial(e.room):void 0,t}};const ut={encode:(e,t=Ee.Writer.create())=>(""!==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 Ee.Reader?e:new Ee.Reader(e);let n=void 0===t?i.len:i.pos+t;const s={participantSid:"",quality:0,score:0};for(;i.pos>>3){case 1:s.participantSid=i.string();break;case 2:s.quality=i.int32();break;case 3:s.score=i.float();break;default:i.skipType(7&e)}}return s},fromJSON:e=>({participantSid:isSet(e.participantSid)?String(e.participantSid):"",quality:isSet(e.quality)?connectionQualityFromJSON(e.quality):0,score:isSet(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 connectionQualityToJSON(e){switch(e){case ye.POOR:return"POOR";case ye.GOOD:return"GOOD";case ye.EXCELLENT:return"EXCELLENT";default:return"UNKNOWN"}}(e.quality)),void 0!==e.score&&(t.score=e.score),t},fromPartial(e){const t={participantSid:"",quality:0,score:0};return t.participantSid=e.participantSid??"",t.quality=e.quality??0,t.score=e.score??0,t}};const lt={encode(e,t=Ee.Writer.create()){for(const i of e.updates)ut.encode(i,t.uint32(10).fork()).ldelim();return t},decode(e,t){const i=e instanceof Ee.Reader?e:new Ee.Reader(e);let n=void 0===t?i.len:i.pos+t;const s={updates:[]};for(;i.pos>>3==1)s.updates.push(ut.decode(i,i.uint32()));else i.skipType(7&e)}return s},fromJSON:e=>({updates:Array.isArray(e?.updates)?e.updates.map((e=>ut.fromJSON(e))):[]}),toJSON(e){const t={};return e.updates?t.updates=e.updates.map((e=>e?ut.toJSON(e):void 0)):t.updates=[],t},fromPartial(e){const t={updates:[]};return t.updates=e.updates?.map((e=>ut.fromPartial(e)))||[],t}};const ht={encode:(e,t=Ee.Writer.create())=>(""!==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 Ee.Reader?e:new Ee.Reader(e);let n=void 0===t?i.len:i.pos+t;const s={participantSid:"",trackSid:"",state:0};for(;i.pos>>3){case 1:s.participantSid=i.string();break;case 2:s.trackSid=i.string();break;case 3:s.state=i.int32();break;default:i.skipType(7&e)}}return s},fromJSON:e=>({participantSid:isSet(e.participantSid)?String(e.participantSid):"",trackSid:isSet(e.trackSid)?String(e.trackSid):"",state:isSet(e.state)?streamStateFromJSON(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 streamStateToJSON(e){switch(e){case Ge.ACTIVE:return"ACTIVE";case Ge.PAUSED:return"PAUSED";default:return"UNKNOWN"}}(e.state)),t},fromPartial(e){const t={participantSid:"",trackSid:"",state:0};return t.participantSid=e.participantSid??"",t.trackSid=e.trackSid??"",t.state=e.state??0,t}};const pt={encode(e,t=Ee.Writer.create()){for(const i of e.streamStates)ht.encode(i,t.uint32(10).fork()).ldelim();return t},decode(e,t){const i=e instanceof Ee.Reader?e:new Ee.Reader(e);let n=void 0===t?i.len:i.pos+t;const s={streamStates:[]};for(;i.pos>>3==1)s.streamStates.push(ht.decode(i,i.uint32()));else i.skipType(7&e)}return s},fromJSON:e=>({streamStates:Array.isArray(e?.streamStates)?e.streamStates.map((e=>ht.fromJSON(e))):[]}),toJSON(e){const t={};return e.streamStates?t.streamStates=e.streamStates.map((e=>e?ht.toJSON(e):void 0)):t.streamStates=[],t},fromPartial(e){const t={streamStates:[]};return t.streamStates=e.streamStates?.map((e=>ht.fromPartial(e)))||[],t}};const mt={encode:(e,t=Ee.Writer.create())=>(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 Ee.Reader?e:new Ee.Reader(e);let n=void 0===t?i.len:i.pos+t;const s={quality:0,enabled:!1};for(;i.pos>>3){case 1:s.quality=i.int32();break;case 2:s.enabled=i.bool();break;default:i.skipType(7&e)}}return s},fromJSON:e=>({quality:isSet(e.quality)?videoQualityFromJSON(e.quality):0,enabled:!!isSet(e.enabled)&&Boolean(e.enabled)}),toJSON(e){const t={};return void 0!==e.quality&&(t.quality=videoQualityToJSON(e.quality)),void 0!==e.enabled&&(t.enabled=e.enabled),t},fromPartial(e){const t={quality:0,enabled:!1};return t.quality=e.quality??0,t.enabled=e.enabled??!1,t}};const ft={encode(e,t=Ee.Writer.create()){""!==e.trackSid&&t.uint32(10).string(e.trackSid);for(const i of e.subscribedQualities)mt.encode(i,t.uint32(18).fork()).ldelim();return t},decode(e,t){const i=e instanceof Ee.Reader?e:new Ee.Reader(e);let n=void 0===t?i.len:i.pos+t;const s={trackSid:"",subscribedQualities:[]};for(;i.pos>>3){case 1:s.trackSid=i.string();break;case 2:s.subscribedQualities.push(mt.decode(i,i.uint32()));break;default:i.skipType(7&e)}}return s},fromJSON:e=>({trackSid:isSet(e.trackSid)?String(e.trackSid):"",subscribedQualities:Array.isArray(e?.subscribedQualities)?e.subscribedQualities.map((e=>mt.fromJSON(e))):[]}),toJSON(e){const t={};return void 0!==e.trackSid&&(t.trackSid=e.trackSid),e.subscribedQualities?t.subscribedQualities=e.subscribedQualities.map((e=>e?mt.toJSON(e):void 0)):t.subscribedQualities=[],t},fromPartial(e){const t={trackSid:"",subscribedQualities:[]};return t.trackSid=e.trackSid??"",t.subscribedQualities=e.subscribedQualities?.map((e=>mt.fromPartial(e)))||[],t}};const gt={encode(e,t=Ee.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 t},decode(e,t){const i=e instanceof Ee.Reader?e:new Ee.Reader(e);let n=void 0===t?i.len:i.pos+t;const s={participantSid:"",allTracks:!1,trackSids:[]};for(;i.pos>>3){case 1:s.participantSid=i.string();break;case 2:s.allTracks=i.bool();break;case 3:s.trackSids.push(i.string());break;default:i.skipType(7&e)}}return s},fromJSON:e=>({participantSid:isSet(e.participantSid)?String(e.participantSid):"",allTracks:!!isSet(e.allTracks)&&Boolean(e.allTracks),trackSids:Array.isArray(e?.trackSids)?e.trackSids.map((e=>String(e))):[]}),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=[],t},fromPartial(e){const t={participantSid:"",allTracks:!1,trackSids:[]};return t.participantSid=e.participantSid??"",t.allTracks=e.allTracks??!1,t.trackSids=e.trackSids?.map((e=>e))||[],t}};const vt={encode(e,t=Ee.Writer.create()){!0===e.allParticipants&&t.uint32(8).bool(e.allParticipants);for(const i of e.trackPermissions)gt.encode(i,t.uint32(18).fork()).ldelim();return t},decode(e,t){const i=e instanceof Ee.Reader?e:new Ee.Reader(e);let n=void 0===t?i.len:i.pos+t;const s={allParticipants:!1,trackPermissions:[]};for(;i.pos>>3){case 1:s.allParticipants=i.bool();break;case 2:s.trackPermissions.push(gt.decode(i,i.uint32()));break;default:i.skipType(7&e)}}return s},fromJSON:e=>({allParticipants:!!isSet(e.allParticipants)&&Boolean(e.allParticipants),trackPermissions:Array.isArray(e?.trackPermissions)?e.trackPermissions.map((e=>gt.fromJSON(e))):[]}),toJSON(e){const t={};return void 0!==e.allParticipants&&(t.allParticipants=e.allParticipants),e.trackPermissions?t.trackPermissions=e.trackPermissions.map((e=>e?gt.toJSON(e):void 0)):t.trackPermissions=[],t},fromPartial(e){const t={allParticipants:!1,trackPermissions:[]};return t.allParticipants=e.allParticipants??!1,t.trackPermissions=e.trackPermissions?.map((e=>gt.fromPartial(e)))||[],t}};const St={encode:(e,t=Ee.Writer.create())=>(""!==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 Ee.Reader?e:new Ee.Reader(e);let n=void 0===t?i.len:i.pos+t;const s={participantSid:"",trackSid:"",allowed:!1};for(;i.pos>>3){case 1:s.participantSid=i.string();break;case 2:s.trackSid=i.string();break;case 3:s.allowed=i.bool();break;default:i.skipType(7&e)}}return s},fromJSON:e=>({participantSid:isSet(e.participantSid)?String(e.participantSid):"",trackSid:isSet(e.trackSid)?String(e.trackSid):"",allowed:!!isSet(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},fromPartial(e){const t={participantSid:"",trackSid:"",allowed:!1};return t.participantSid=e.participantSid??"",t.trackSid=e.trackSid??"",t.allowed=e.allowed??!1,t}};const bt={encode(e,t=Ee.Writer.create()){void 0!==e.answer&&tt.encode(e.answer,t.uint32(10).fork()).ldelim(),void 0!==e.subscription&&rt.encode(e.subscription,t.uint32(18).fork()).ldelim();for(const i of e.publishTracks)Xe.encode(i,t.uint32(26).fork()).ldelim();for(const i of e.dataChannels)kt.encode(i,t.uint32(34).fork()).ldelim();return t},decode(e,t){const i=e instanceof Ee.Reader?e:new Ee.Reader(e);let n=void 0===t?i.len:i.pos+t;const s={answer:void 0,subscription:void 0,publishTracks:[],dataChannels:[]};for(;i.pos>>3){case 1:s.answer=tt.decode(i,i.uint32());break;case 2:s.subscription=rt.decode(i,i.uint32());break;case 3:s.publishTracks.push(Xe.decode(i,i.uint32()));break;case 4:s.dataChannels.push(kt.decode(i,i.uint32()));break;default:i.skipType(7&e)}}return s},fromJSON:e=>({answer:isSet(e.answer)?tt.fromJSON(e.answer):void 0,subscription:isSet(e.subscription)?rt.fromJSON(e.subscription):void 0,publishTracks:Array.isArray(e?.publishTracks)?e.publishTracks.map((e=>Xe.fromJSON(e))):[],dataChannels:Array.isArray(e?.dataChannels)?e.dataChannels.map((e=>kt.fromJSON(e))):[]}),toJSON(e){const t={};return void 0!==e.answer&&(t.answer=e.answer?tt.toJSON(e.answer):void 0),void 0!==e.subscription&&(t.subscription=e.subscription?rt.toJSON(e.subscription):void 0),e.publishTracks?t.publishTracks=e.publishTracks.map((e=>e?Xe.toJSON(e):void 0)):t.publishTracks=[],e.dataChannels?t.dataChannels=e.dataChannels.map((e=>e?kt.toJSON(e):void 0)):t.dataChannels=[],t},fromPartial(e){const t={answer:void 0,subscription:void 0,publishTracks:[],dataChannels:[]};return t.answer=void 0!==e.answer&&null!==e.answer?tt.fromPartial(e.answer):void 0,t.subscription=void 0!==e.subscription&&null!==e.subscription?rt.fromPartial(e.subscription):void 0,t.publishTracks=e.publishTracks?.map((e=>Xe.fromPartial(e)))||[],t.dataChannels=e.dataChannels?.map((e=>kt.fromPartial(e)))||[],t}};const kt={encode:(e,t=Ee.Writer.create())=>(""!==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 Ee.Reader?e:new Ee.Reader(e);let n=void 0===t?i.len:i.pos+t;const s={label:"",id:0,target:0};for(;i.pos>>3){case 1:s.label=i.string();break;case 2:s.id=i.uint32();break;case 3:s.target=i.int32();break;default:i.skipType(7&e)}}return s},fromJSON:e=>({label:isSet(e.label)?String(e.label):"",id:isSet(e.id)?Number(e.id):0,target:isSet(e.target)?signalTargetFromJSON(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=signalTargetToJSON(e.target)),t},fromPartial(e){const t={label:"",id:0,target:0};return t.label=e.label??"",t.id=e.id??0,t.target=e.target??0,t}};const yt={encode:(e,t=Ee.Writer.create())=>(void 0!==e.speakerUpdate&&t.uint32(8).int32(e.speakerUpdate),void 0!==e.nodeFailure&&t.uint32(16).bool(e.nodeFailure),void 0!==e.migration&&t.uint32(24).bool(e.migration),void 0!==e.serverLeave&&t.uint32(32).bool(e.serverLeave),t),decode(e,t){const i=e instanceof Ee.Reader?e:new Ee.Reader(e);let n=void 0===t?i.len:i.pos+t;const s={speakerUpdate:void 0,nodeFailure:void 0,migration:void 0,serverLeave:void 0};for(;i.pos>>3){case 1:s.speakerUpdate=i.int32();break;case 2:s.nodeFailure=i.bool();break;case 3:s.migration=i.bool();break;case 4:s.serverLeave=i.bool();break;default:i.skipType(7&e)}}return s},fromJSON:e=>({speakerUpdate:isSet(e.speakerUpdate)?Number(e.speakerUpdate):void 0,nodeFailure:isSet(e.nodeFailure)?Boolean(e.nodeFailure):void 0,migration:isSet(e.migration)?Boolean(e.migration):void 0,serverLeave:isSet(e.serverLeave)?Boolean(e.serverLeave):void 0}),toJSON(e){const t={};return void 0!==e.speakerUpdate&&(t.speakerUpdate=Math.round(e.speakerUpdate)),void 0!==e.nodeFailure&&(t.nodeFailure=e.nodeFailure),void 0!==e.migration&&(t.migration=e.migration),void 0!==e.serverLeave&&(t.serverLeave=e.serverLeave),t},fromPartial(e){const t={speakerUpdate:void 0,nodeFailure:void 0,migration:void 0,serverLeave:void 0};return t.speakerUpdate=e.speakerUpdate??void 0,t.nodeFailure=e.nodeFailure??void 0,t.migration=e.migration??void 0,t.serverLeave=e.serverLeave??void 0,t}};function isSet(e){return null!=e}Ee.util.Long!==p&&(Ee.util.Long=p,Ee.configure());class LivekitError extends Error{constructor(e,t){super(t||"an error has occured"),this.code=e}}class ConnectionError extends LivekitError{constructor(e){super(1,e)}}class TrackInvalidError extends LivekitError{constructor(e){super(20,e||"Track is invalid")}}class UnsupportedServer extends LivekitError{constructor(e){super(10,e||"Unsupported server")}}class UnexpectedConnectionState extends LivekitError{constructor(e){super(12,e||"Unexpected connection state")}}class PublishDataError extends LivekitError{constructor(e){super(13,e||"Unable to publish data")}}var Tt,wt,Ct,Pt,Et;!function(e){e.PermissionDenied="PermissionDenied",e.NotFound="NotFound",e.DeviceInUse="DeviceInUse",e.Other="Other"}(Tt||(Tt={})),function(e){e.getFailure=function getFailure(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}}(Tt||(Tt={})),function(e){e.Reconnecting="reconnecting",e.Reconnected="reconnected",e.Disconnected="disconnected",e.StateChanged="stateChanged",e.MediaDevicesChanged="mediaDevicesChanged",e.ParticipantConnected="participantConnected",e.ParticipantDisconnected="participantDisconnected",e.TrackPublished="trackPublished",e.TrackSubscribed="trackSubscribed",e.TrackSubscriptionFailed="trackSubscriptionFailed",e.TrackUnpublished="trackUnpublished",e.TrackUnsubscribed="trackUnsubscribed",e.TrackMuted="trackMuted",e.TrackUnmuted="trackUnmuted",e.LocalTrackPublished="localTrackPublished",e.LocalTrackUnpublished="localTrackUnpublished",e.ActiveSpeakersChanged="activeSpeakersChanged",e.MetadataChanged="metadataChanged",e.ParticipantMetadataChanged="participantMetadataChanged",e.RoomMetadataChanged="roomMetadataChanged",e.DataReceived="dataReceived",e.ConnectionQualityChanged="connectionQualityChanged",e.TrackStreamStateChanged="trackStreamStateChanged",e.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",e.AudioPlaybackStatusChanged="audioPlaybackChanged",e.MediaDevicesError="mediaDevicesError",e.ParticipantPermissionsChanged="participantPermissionsChanged"}(wt||(wt={})),function(e){e.TrackPublished="trackPublished",e.TrackSubscribed="trackSubscribed",e.TrackSubscriptionFailed="trackSubscriptionFailed",e.TrackUnpublished="trackUnpublished",e.TrackUnsubscribed="trackUnsubscribed",e.TrackMuted="trackMuted",e.TrackUnmuted="trackUnmuted",e.LocalTrackPublished="localTrackPublished",e.LocalTrackUnpublished="localTrackUnpublished",e.MetadataChanged="metadataChanged",e.ParticipantMetadataChanged="participantMetadataChanged",e.DataReceived="dataReceived",e.IsSpeakingChanged="isSpeakingChanged",e.ConnectionQualityChanged="connectionQualityChanged",e.TrackStreamStateChanged="trackStreamStateChanged",e.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",e.MediaDevicesError="mediaDevicesError",e.ParticipantPermissionsChanged="participantPermissionsChanged"}(Ct||(Ct={})),function(e){e.TransportsCreated="transportsCreated",e.Connected="connected",e.Disconnected="disconnected",e.Resuming="resuming",e.Resumed="resumed",e.Restarting="restarting",e.Restarted="restarted",e.SignalResumed="signalResumed",e.MediaTrackAdded="mediaTrackAdded",e.ActiveSpeakersUpdate="activeSpeakersUpdate",e.DataPacketReceived="dataPacketReceived"}(Pt||(Pt={})),function(e){e.Message="message",e.Muted="muted",e.Unmuted="unmuted",e.Ended="ended",e.UpdateSettings="updateSettings",e.UpdateSubscription="updateSubscription",e.AudioPlaybackStarted="audioPlaybackStarted",e.AudioPlaybackFailed="audioPlaybackFailed",e.AudioSilenceDetected="audioSilenceDetected",e.VisibilityChanged="visibilityChanged",e.VideoDimensionsChanged="videoDimensionsChanged",e.ElementAttached="elementAttached",e.ElementDetached="elementDetached"}(Et||(Et={}));const Rt=2e3;function computeBitrate(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)}const Ot="default";class DeviceManager{static getInstance(){return void 0===this.instance&&(this.instance=new DeviceManager),this.instance}async getDevices(e,t=!0){let i=await navigator.mediaDevices.enumerateDevices();if(t){if(0===i.length||i.some((t=>{const i=""===t.label,n=!e||t.kind===e;return i&&n}))){const t={video:"audioinput"!==e&&"audiooutput"!==e,audio:"videoinput"!==e};await navigator.mediaDevices.getUserMedia(t),i=await navigator.mediaDevices.enumerateDevices()}}if(e&&(i=i.filter((t=>t.kind===e))),i.length>1&&i[0].deviceId===Ot){const e=i[0];for(let t=1;tt!==e))}return i}async normalizeDeviceId(e,t,i){if(t!==Ot)return t;return(await this.getDevices(e)).find((e=>e.groupId===i&&e.deviceId!==Ot))?.deviceId}}DeviceManager.mediaDeviceKinds=["audioinput","audiooutput","videoinput"];const Nt="0.18.2",_t=7;async function sleep(e){return new Promise((t=>setTimeout(t,e)))}function isFireFox(){return!!isWeb()&&-1!==navigator.userAgent.indexOf("Firefox")}function isMobile(){return!!isWeb()&&/Tablet|iPad|Mobile|Android|BlackBerry/.test(navigator.userAgent)}function isWeb(){return"undefined"!=typeof document}function roDispatchCallback(e){for(const t of e)t.target.handleResize(t)}function ioDispatchCallback(e){for(const t of e)t.target.handleVisibilityChanged(t)}let Lt=null;const getResizeObserver=()=>(Lt||(Lt=new ResizeObserver(roDispatchCallback)),Lt);let Dt=null;const getIntersectionObserver=()=>(Dt||(Dt=new IntersectionObserver(ioDispatchCallback,{root:document,rootMargin:"0px"})),Dt);var At,It={exports:{}},Ut="object"==typeof Reflect?Reflect:null,Mt=Ut&&"function"==typeof Ut.apply?Ut.apply:function ReflectApply(e,t,i){return Function.prototype.apply.call(e,t,i)};At=Ut&&"function"==typeof Ut.ownKeys?Ut.ownKeys:Object.getOwnPropertySymbols?function ReflectOwnKeys(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function ReflectOwnKeys(e){return Object.getOwnPropertyNames(e)};var xt=Number.isNaN||function NumberIsNaN(e){return e!=e};function EventEmitter(){EventEmitter.init.call(this)}It.exports=EventEmitter,It.exports.once=function once(e,t){return new Promise((function(i,n){function errorListener(i){e.removeListener(t,resolver),n(i)}function resolver(){"function"==typeof e.removeListener&&e.removeListener("error",errorListener),i([].slice.call(arguments))}eventTargetAgnosticAddListener(e,t,resolver,{once:!0}),"error"!==t&&function addErrorHandlerIfEventEmitter(e,t,i){"function"==typeof e.on&&eventTargetAgnosticAddListener(e,"error",t,i)}(e,errorListener,{once:!0})}))},EventEmitter.EventEmitter=EventEmitter,EventEmitter.prototype._events=void 0,EventEmitter.prototype._eventsCount=0,EventEmitter.prototype._maxListeners=void 0;var Bt=10;function checkListener(e){if("function"!=typeof e)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function _getMaxListeners(e){return void 0===e._maxListeners?EventEmitter.defaultMaxListeners:e._maxListeners}function _addListener(e,t,i,n){var s,a,o;if(checkListener(i),void 0===(a=e._events)?(a=e._events=Object.create(null),e._eventsCount=0):(void 0!==a.newListener&&(e.emit("newListener",t,i.listener?i.listener:i),a=e._events),o=a[t]),void 0===o)o=a[t]=i,++e._eventsCount;else if("function"==typeof o?o=a[t]=n?[i,o]:[o,i]:n?o.unshift(i):o.push(i),(s=_getMaxListeners(e))>0&&o.length>s&&!o.warned){o.warned=!0;var c=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");c.name="MaxListenersExceededWarning",c.emitter=e,c.type=t,c.count=o.length,function ProcessEmitWarning(e){console&&console.warn&&console.warn(e)}(c)}return e}function onceWrapper(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,0===arguments.length?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function _onceWrap(e,t,i){var n={fired:!1,wrapFn:void 0,target:e,type:t,listener:i},s=onceWrapper.bind(n);return s.listener=i,n.wrapFn=s,s}function _listeners(e,t,i){var n=e._events;if(void 0===n)return[];var s=n[t];return void 0===s?[]:"function"==typeof s?i?[s.listener||s]:[s]:i?function unwrapListeners(e){for(var t=new Array(e.length),i=0;i0&&(a=t[0]),a instanceof Error)throw a;var o=new Error("Unhandled error."+(a?" ("+a.message+")":""));throw o.context=a,o}var c=s[e];if(void 0===c)return!1;if("function"==typeof c)Mt(c,this,t);else{var u=c.length,l=arrayClone(c,u);for(i=0;i=0;a--)if(i[a]===t||i[a].listener===t){o=i[a].listener,s=a;break}if(s<0)return this;0===s?i.shift():function spliceOne(e,t){for(;t+1=0;n--)this.removeListener(e,t[n]);return this},EventEmitter.prototype.listeners=function listeners(e){return _listeners(this,e,!0)},EventEmitter.prototype.rawListeners=function rawListeners(e){return _listeners(this,e,!1)},EventEmitter.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):listenerCount.call(e,t)},EventEmitter.prototype.listenerCount=listenerCount,EventEmitter.prototype.eventNames=function eventNames(){return this._eventsCount>0?At(this._events):[]};const Jt=[];class Track extends It.exports.EventEmitter{constructor(e,t){super(),this.attachedElements=[],this.isMuted=!1,this._currentBitrate=0,this.appVisibilityChangedListener=()=>{this.handleAppVisibilityChanged()},this.kind=t,this.mediaStreamTrack=e,this.source=Track.Source.Unknown,isWeb()?(this.isInBackground="hidden"===document.visibilityState,document.addEventListener("visibilitychange",this.appVisibilityChangedListener)):this.isInBackground=!1}get currentBitrate(){return this._currentBitrate}attach(e){let t="audio";return this.kind===Track.Kind.Video&&(t="video"),e||("audio"===t&&(Jt.forEach((t=>{null!==t.parentElement||e||(e=t)})),e&&Jt.splice(Jt.indexOf(e),1)),e||(e=document.createElement(t))),this.attachedElements.includes(e)||this.attachedElements.push(e),attachToElement(this.mediaStreamTrack,e),e instanceof HTMLAudioElement&&e.play().then((()=>{this.emit(Et.AudioPlaybackStarted)})).catch((e=>{this.emit(Et.AudioPlaybackFailed,e)})),this.emit(Et.ElementAttached,e),e}detach(e){if(e){detachTrack(this.mediaStreamTrack,e);const t=this.attachedElements.indexOf(e);return t>=0&&(this.attachedElements.splice(t,1),this.recycleElement(e),this.emit(Et.ElementDetached,e)),e}const t=[];return this.attachedElements.forEach((e=>{detachTrack(this.mediaStreamTrack,e),t.push(e),this.recycleElement(e),this.emit(Et.ElementDetached,e)})),this.attachedElements=[],t}stop(){this.mediaStreamTrack.stop(),isWeb()&&document.removeEventListener("visibilitychange",this.appVisibilityChangedListener)}enable(){this.mediaStreamTrack.enabled=!0}disable(){this.mediaStreamTrack.enabled=!1}recycleElement(e){if(e instanceof HTMLAudioElement){let t=!0;e.pause(),Jt.forEach((e=>{e.parentElement||(t=!1)})),t&&Jt.push(e)}}async handleAppVisibilityChanged(){this.isInBackground="hidden"===document.visibilityState}}function attachToElement(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.srcObject!==i&&(t.srcObject=i,(function isSafari(){return!!isWeb()&&/^((?!chrome|android).)*safari/i.test(navigator.userAgent)}()||isFireFox())&&t instanceof HTMLVideoElement&&setTimeout((()=>{t.srcObject=i,t.play().catch((()=>{}))}),0)),t.autoplay=!0,t instanceof HTMLVideoElement&&(t.playsInline=!0)}function detachTrack(e,t){if(t.srcObject instanceof MediaStream){t.srcObject.removeTrack(e),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 kindToProto(e){switch(e){case t.Audio:return Se.AUDIO;case t.Video:return Se.VIDEO;default:return Se.UNRECOGNIZED}},e.kindFromProto=function kindFromProto(e){switch(e){case Se.AUDIO:return t.Audio;case Se.VIDEO:return t.Video;default:return t.Unknown}},e.sourceToProto=function sourceToProto(e){switch(e){case i.Camera:return be.CAMERA;case i.Microphone:return be.MICROPHONE;case i.ScreenShare:return be.SCREEN_SHARE;case i.ScreenShareAudio:return be.SCREEN_SHARE_AUDIO;default:return be.UNRECOGNIZED}},e.sourceFromProto=function sourceFromProto(e){switch(e){case be.CAMERA:return i.Camera;case be.MICROPHONE:return i.Microphone;case be.SCREEN_SHARE:return i.ScreenShare;case be.SCREEN_SHARE_AUDIO:return i.ScreenShareAudio;default:return i.Unknown}},e.streamStateFromProto=function streamStateFromProto(e){switch(e){case Ge.ACTIVE:return n.Active;case Ge.PAUSED:return n.Paused;default:return n.Unknown}}}(Track||(Track={}));class LocalTrack extends Track{constructor(e,t,i){super(e,t),this.handleEnded=()=>{this.isInBackground&&(this.reacquireTrack=!0),this.emit(Et.Ended,this)},this.mediaStreamTrack.addEventListener("ended",this.handleEnded),this.constraints=i??e.getConstraints(),this.reacquireTrack=!1,this.wasMuted=!1}get id(){return this.mediaStreamTrack.id}get dimensions(){if(this.kind!==Track.Kind.Video)return;const{width:e,height:t}=this.mediaStreamTrack.getSettings();return e&&t?{width:e,height:t}:void 0}async getDeviceId(){if(this.source===Track.Source.ScreenShare)return;const{deviceId:e,groupId:t}=this.mediaStreamTrack.getSettings(),i=this.kind===Track.Kind.Audio?"audioinput":"videoinput";return DeviceManager.getInstance().normalizeDeviceId(i,e,t)}async mute(){return this.setTrackMuted(!0),this}async unmute(){return this.setTrackMuted(!1),this}async restart(e){if(!this.sender)throw new TrackInvalidError("unable to restart an unpublished track");e||(e=this.constraints),h.debug("restarting track with constraints",e);const t={audio:!1,video:!1};this.kind===Track.Kind.Video?t.video=e:t.audio=e,this.attachedElements.forEach((e=>{detachTrack(this.mediaStreamTrack,e)})),this.mediaStreamTrack.removeEventListener("ended",this.handleEnded),this.mediaStreamTrack.stop();const i=await navigator.mediaDevices.getUserMedia(t),n=i.getTracks()[0];return n.addEventListener("ended",this.handleEnded),h.debug("re-acquired MediaStreamTrack"),await this.sender.replaceTrack(n),this.mediaStreamTrack=n,this.attachedElements.forEach((e=>{attachToElement(n,e)})),this.mediaStream=i,this.constraints=e,this}setTrackMuted(e){this.isMuted!==e&&(this.isMuted=e,this.mediaStreamTrack.enabled=!e,this.emit(e?Et.Muted:Et.Unmuted,this))}get needsReAcquisition(){return"live"!==this.mediaStreamTrack.readyState||this.mediaStreamTrack.muted||!this.mediaStreamTrack.enabled||this.reacquireTrack}async handleAppVisibilityChanged(){await super.handleAppVisibilityChanged(),isMobile()&&(h.debug(`visibility changed, is in Background: ${this.isInBackground}`),!this.isInBackground&&this.needsReAcquisition&&(h.debug(`track needs to be reaquired, restarting ${this.source}`),await this.restart(),this.reacquireTrack=!1,this.setTrackMuted(this.wasMuted)),this.isInBackground&&(this.wasMuted=this.isMuted))}}function mergeDefaultOptions(e,t,i){const n={...e};return!0===n.audio&&(n.audio={}),!0===n.video&&(n.video={}),n.audio&&mergeObjectWithoutOverwriting(n.audio,t),n.video&&mergeObjectWithoutOverwriting(n.video,i),n}function mergeObjectWithoutOverwriting(e,t){return Object.keys(t).forEach((i=>{void 0===e[i]&&(e[i]=t[i])})),e}function constraintsForOptions(e){const t={};if(e.video)if("object"==typeof e.video){const i={},n=i,s=e.video;Object.keys(s).forEach((e=>{if("resolution"===e)mergeObjectWithoutOverwriting(n,s.resolution);else n[e]=s[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 getNewAudioContext(){const e=window.AudioContext||window.webkitAudioContext;if(e)return new e}class LocalAudioTrack extends LocalTrack{constructor(e,t){super(e,Track.Kind.Audio,t),this.stopOnMute=!1,this.monitorSender=async()=>{if(!this.sender)return void(this._currentBitrate=0);let e;try{e=await this.getSenderStats()}catch(e){return void h.error("could not get audio sender stats",e)}e&&this.prevStats&&(this._currentBitrate=computeBitrate(e,this.prevStats)),this.prevStats=e,setTimeout((()=>{this.monitorSender()}),Rt)},this.checkForSilence()}async setDeviceId(e){this.constraints.deviceId!==e&&(this.constraints.deviceId=e,this.isMuted||await this.restartTrack())}async mute(){return this.source===Track.Source.Microphone&&this.stopOnMute&&(h.debug("stopping mic track"),this.mediaStreamTrack.stop()),await super.mute(),this}async unmute(){return this.source===Track.Source.Microphone&&this.stopOnMute&&(h.debug("reacquiring mic track"),await this.restartTrack()),await super.unmute(),this}async restartTrack(e){let t;if(e){const i=constraintsForOptions({audio:e});"boolean"!=typeof i.audio&&(t=i.audio)}await this.restart(t)}async restart(e){const t=await super.restart(e);return this.checkForSilence(),t}startMonitor(){setTimeout((()=>{this.monitorSender()}),Rt)}async getSenderStats(){if(!this.sender)return;let e;return(await this.sender.getStats()).forEach((t=>{"outbound-rtp"===t.type&&(e={type:"audio",streamId:t.id,packetsSent:t.packetsSent,packetsLost:t.packetsLost,bytesSent:t.bytesSent,timestamp:t.timestamp,roundTripTime:t.roundTripTime,jitter:t.jitter})})),e}async checkForSilence(){await async function detectSilence(e,t=200){const i=getNewAudioContext();if(i){const n=i.createAnalyser();n.fftSize=2048;const s=n.frequencyBinCount,a=new Uint8Array(s);i.createMediaStreamSource(new MediaStream([e.mediaStreamTrack])).connect(n),await sleep(t),n.getByteTimeDomainData(a);const o=a.some((e=>128!==e&&0!==e));return i.close(),!o}return!1}(this)&&(this.isMuted||h.warn("silence detected on local audio track"),this.emit(Et.AudioSilenceDetected))}}class LocalVideoTrack extends LocalTrack{constructor(e,t){super(e,Track.Kind.Video,t),this.monitorSender=async()=>{if(!this.sender)return void(this._currentBitrate=0);let e;try{e=await this.getSenderStats()}catch(e){return void h.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)=>{const n=this.prevStats?.get(i);e+=computeBitrate(t,n)})),this._currentBitrate=e}this.prevStats=t,setTimeout((()=>{this.monitorSender()}),Rt)}}get isSimulcast(){return!!(this.sender&&this.sender.getParameters().encodings.length>1)}startMonitor(e){this.signalClient=e;const t=this.sender?.getParameters();t&&(this.encodings=t.encodings),setTimeout((()=>{this.monitorSender()}),Rt)}stop(){this.sender=void 0,this.mediaStreamTrack.getConstraints(),super.stop()}async mute(){return this.source===Track.Source.Camera&&(h.debug("stopping camera track"),this.mediaStreamTrack.stop()),await super.mute(),this}async unmute(){return this.source===Track.Source.Camera&&(h.debug("reacquiring camera track"),await this.restartTrack()),await super.unmute(),this}async getSenderStats(){if(!this.sender)return[];const e=[],t=await this.sender.getStats();return t.forEach((i=>{if("outbound-rtp"===i.type){const n={type:"video",streamId:i.id,frameHeight:i.frameHeight,frameWidth:i.frameWidth,firCount:i.firCount,pliCount:i.pliCount,nackCount:i.nackCount,packetsSent:i.packetsSent,bytesSent:i.bytesSent,framesSent:i.framesSent,timestamp:i.timestamp,rid:i.rid??"",retransmittedPacketsSent:i.retransmittedPacketsSent,qualityLimitationReason:i.qualityLimitationReason,qualityLimitationResolutionChanges:i.qualityLimitationResolutionChanges},s=t.get(i.remoteId);s&&(n.jitter=s.jitter,n.packetsLost=s.packetsLost,n.roundTripTime=s.roundTripTime),e.push(n)}})),e}setPublishingQuality(e){const t=[];for(let i=ke.LOW;i<=ke.HIGH;i+=1)t.push({quality:i,enabled:i<=e});h.debug(`setting publishing quality. max quality ${e}`),this.setPublishingLayers(t)}async setDeviceId(e){this.constraints.deviceId!==e&&(this.constraints.deviceId=e,this.isMuted||await this.restartTrack())}async restartTrack(e){let t;if(e){const i=constraintsForOptions({video:e});"boolean"!=typeof i.video&&(t=i.video)}await this.restart(t)}async setPublishingLayers(e){if(h.debug("setting publishing layers",e),!this.sender||!this.encodings)return;const t=this.sender.getParameters(),{encodings:i}=t;if(!i)return;if(i.length!==this.encodings.length)return void h.warn("cannot set publishing layers, encodings mismatch");let n=!1;i.forEach(((t,i)=>{let s=t.rid??"";""===s&&(s="q");const a=videoQualityForRid(s),o=e.find((e=>e.quality===a));o&&t.active!==o.enabled&&(n=!0,t.active=o.enabled,h.debug(`setting layer ${o.quality} to ${t.active?"enabled":"disabled"}`),isFireFox()&&(o.enabled?(t.scaleResolutionDownBy=this.encodings[i].scaleResolutionDownBy,t.maxBitrate=this.encodings[i].maxBitrate,t.maxFrameRate=this.encodings[i].maxFrameRate):(t.scaleResolutionDownBy=4,t.maxBitrate=10,t.maxFrameRate=2)))})),n&&(t.encodings=i,await this.sender.setParameters(t))}async handleAppVisibilityChanged(){await super.handleAppVisibilityChanged(),isMobile()&&this.isInBackground&&this.source===Track.Source.Camera&&(this.mediaStreamTrack.enabled=!1)}}function videoQualityForRid(e){switch(e){case"f":return ke.HIGH;case"h":return ke.MEDIUM;case"q":return ke.LOW;default:return ke.UNRECOGNIZED}}class RemoteTrack extends Track{constructor(e,t,i,n){super(e,i),this.streamState=Track.StreamState.Active,this.sid=t,this.receiver=n}setMuted(e){this.isMuted!==e&&(this.isMuted=e,this.emit(e?Et.Muted:Et.Unmuted,this))}setMediaStream(e){this.mediaStream=e,e.onremovetrack=()=>{this.receiver=void 0,this._currentBitrate=0,this.emit(Et.Ended,this)}}start(){this.startMonitor(),super.enable()}stop(){super.disable()}startMonitor(){setTimeout((()=>{this.monitorReceiver()}),Rt)}}class RemoteAudioTrack extends RemoteTrack{constructor(e,t,i){super(e,t,Track.Kind.Audio,i),this.monitorReceiver=async()=>{if(!this.receiver)return void(this._currentBitrate=0);const e=await this.getReceiverStats();e&&this.prevStats&&this.receiver&&(this._currentBitrate=computeBitrate(e,this.prevStats)),this.prevStats=e,setTimeout((()=>{this.monitorReceiver()}),Rt)},this.elementVolume=1}setVolume(e){for(const t of this.attachedElements)t.volume=e;this.elementVolume=e}getVolume(){return this.elementVolume}attach(e){return e?super.attach(e):e=super.attach(),e.volume=this.elementVolume,e}async getReceiverStats(){if(!this.receiver)return;let e;return(await 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}}function r(e,t,i){var n,s,a;void 0===t&&(t=50),void 0===i&&(i={});var o=null!=(n=i.isImmediate)&&n,c=null!=(s=i.callback)&&s,u=i.maxWait,l=Date.now(),h=[];function f(){if(void 0!==u){var e=Date.now()-l;if(e+t>=u)return u-e}return t}var d=function(){var t=[].slice.call(arguments),i=this;return new Promise((function(n,s){var u=o&&void 0===a;if(void 0!==a&&clearTimeout(a),a=setTimeout((function(){if(a=void 0,l=Date.now(),!o){var n=e.apply(i,t);c&&c(n),h.forEach((function(e){return(0,e.resolve)(n)})),h=[]}}),f()),u){var p=e.apply(i,t);return c&&c(p),n(p)}h.push({resolve:n,reject:s})}))};return d.cancel=function(e){void 0!==a&&clearTimeout(a),h.forEach((function(t){return(0,t.reject)(e)})),h=[]},d}class RemoteVideoTrack extends RemoteTrack{constructor(e,t,i,n){super(e,t,Track.Kind.Video,i),this.elementInfos=[],this.monitorReceiver=async()=>{if(!this.receiver)return void(this._currentBitrate=0);const e=await this.getReceiverStats();e&&this.prevStats&&this.receiver&&(this._currentBitrate=computeBitrate(e,this.prevStats)),this.prevStats=e,setTimeout((()=>{this.monitorReceiver()}),Rt)},this.handleVisibilityChanged=e=>{const{target:t,isIntersecting:i}=e,n=this.elementInfos.find((e=>e.element===t));n&&(n.visible=i,n.visibilityChangedAt=Date.now()),this.updateVisibility()},this.debouncedHandleResize=r((()=>{this.updateDimensions()}),100),this.adaptiveStreamSettings=n}get isAdaptiveStream(){return void 0!==this.adaptiveStreamSettings}setMuted(e){super.setMuted(e),this.attachedElements.forEach((t=>{e?detachTrack(this.mediaStreamTrack,t):attachToElement(this.mediaStreamTrack,t)}))}attach(e){return e?super.attach(e):e=super.attach(),this.adaptiveStreamSettings&&void 0===this.elementInfos.find((t=>t.element===e))&&(this.elementInfos.push({element:e,visible:!0}),e.handleResize=this.debouncedHandleResize,e.handleVisibilityChanged=this.handleVisibilityChanged,getIntersectionObserver().observe(e),getResizeObserver().observe(e),this.debouncedHandleResize()),e}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}async getReceiverStats(){if(!this.receiver)return;let e;return(await 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})})),e}stopObservingElement(e){getIntersectionObserver()?.unobserve(e),getResizeObserver()?.unobserve(e),this.elementInfos=this.elementInfos.filter((t=>t.element!==e))}async handleAppVisibilityChanged(){await super.handleAppVisibilityChanged(),this.isAdaptiveStream&&isMobile()&&this.updateVisibility()}updateVisibility(){const e=this.elementInfos.reduce(((e,t)=>Math.max(e,t.visibilityChangedAt||0)),0),t=this.elementInfos.some((e=>e.visible))&&!this.isInBackground;this.lastVisible!==t&&(!t&&Date.now()-e<100?setTimeout((()=>{this.updateVisibility()}),100):(this.lastVisible=t,this.emit(Et.VisibilityChanged,t,this)))}updateDimensions(){let e=0,t=0;for(const i of this.elementInfos){const n=this.adaptiveStreamSettings?.pixelDensity??1,s="screen"===n?window.devicePixelRatio:n,a=i.element.clientWidth*s,o=i.element.clientHeight*s;a+o>e+t&&(e=a,t=o)}this.lastDimensions?.width===e&&this.lastDimensions?.height===t||(this.lastDimensions={width:e,height:t},this.emit(Et.VideoDimensionsChanged,this.lastDimensions,this))}}class TrackPublication extends It.exports.EventEmitter{constructor(e,t,i){super(),this.metadataMuted=!1,this.handleMuted=()=>{this.emit(Et.Muted)},this.handleUnmuted=()=>{this.emit(Et.Unmuted)},this.kind=e,this.trackSid=t,this.trackName=i,this.source=Track.Source.Unknown}setTrack(e){this.track&&(this.track.off(Et.Muted,this.handleMuted),this.track.off(Et.Unmuted,this.handleUnmuted)),this.track=e,e&&(e.on(Et.Muted,this.handleMuted),e.on(Et.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 LocalAudioTrack||this.track instanceof RemoteAudioTrack)return this.track}get videoTrack(){if(this.track instanceof LocalVideoTrack||this.track instanceof RemoteVideoTrack)return this.track}updateInfo(e){this.trackSid=e.sid,this.trackName=e.name,this.source=Track.sourceFromProto(e.source),this.mimeType=e.mimeType,this.kind===Track.Kind.Video&&e.width>0&&(this.dimensions={width:e.width,height:e.height},this.simulcasted=e.simulcast),this.trackInfo=e}}!function(e){var t;(t=e.SubscriptionStatus||(e.SubscriptionStatus={})).Subscribed="subscribed",t.NotAllowed="not_allowed",t.Unsubscribed="unsubscribed"}(TrackPublication||(TrackPublication={}));class LocalTrackPublication extends TrackPublication{constructor(e,t,i){super(e,t.sid,t.name),this.handleTrackEnded=e=>{this.emit(Et.Ended,e)},this.updateInfo(t),this.setTrack(i)}setTrack(e){this.track&&this.track.off(Et.Ended,this.handleTrackEnded),super.setTrack(e),e&&e.on(Et.Ended,this.handleTrackEnded)}get isMuted(){return this.track?this.track.isMuted:super.isMuted}get audioTrack(){return super.audioTrack}get videoTrack(){return super.videoTrack}async mute(){return this.track?.mute()}async unmute(){return this.track?.unmute()}}class VideoPreset{constructor(e,t,i,n){this.width=e,this.height=t,this.encoding={maxBitrate:i,maxFramerate:n}}get resolution(){return{width:this.width,height:this.height,frameRate:this.encoding.maxFramerate,aspectRatio:this.width/this.height}}}var Ft;!function(e){e.telephone={maxBitrate:12e3},e.speech={maxBitrate:2e4},e.music={maxBitrate:32e3}}(Ft||(Ft={}));const Vt={h90:new VideoPreset(160,90,6e4,15),h180:new VideoPreset(320,180,12e4,15),h216:new VideoPreset(384,216,18e4,15),h360:new VideoPreset(640,360,3e5,20),h540:new VideoPreset(960,540,6e5,25),h720:new VideoPreset(1280,720,2e6,30),h1080:new VideoPreset(1920,1080,3e6,30),h1440:new VideoPreset(2560,1440,5e6,30),h2160:new VideoPreset(3840,2160,8e6,30),qvga:new VideoPreset(320,180,12e4,10),vga:new VideoPreset(640,360,3e5,20),qhd:new VideoPreset(960,540,6e5,25),hd:new VideoPreset(1280,720,2e6,30),fhd:new VideoPreset(1920,1080,3e6,30)},jt={h120:new VideoPreset(160,120,8e4,15),h180:new VideoPreset(240,180,1e5,15),h240:new VideoPreset(320,240,15e4,15),h360:new VideoPreset(480,360,225e3,20),h480:new VideoPreset(640,480,3e5,20),h540:new VideoPreset(720,540,45e4,25),h720:new VideoPreset(960,720,15e5,30),h1080:new VideoPreset(1440,1080,25e5,30),h1440:new VideoPreset(1920,1440,35e5,30),qvga:new VideoPreset(240,180,9e4,10),vga:new VideoPreset(480,360,225e3,20),qhd:new VideoPreset(720,540,45e4,25),hd:new VideoPreset(960,720,15e5,30),fhd:new VideoPreset(1440,1080,28e5,30)},$t={h360fps3:new VideoPreset(640,360,2e5,3),h720fps5:new VideoPreset(1280,720,4e5,5),h720fps15:new VideoPreset(1280,720,1e6,15),h1080fps15:new VideoPreset(1920,1080,15e5,15),h1080fps30:new VideoPreset(1920,1080,3e6,30),vga:new VideoPreset(640,360,2e5,3),hd_8:new VideoPreset(1280,720,4e5,5),hd_15:new VideoPreset(1280,720,1e6,15),fhd_15:new VideoPreset(1920,1080,15e5,15),fhd_30:new VideoPreset(1920,1080,3e6,30)};var qt;!function(e){e.Excellent="excellent",e.Good="good",e.Poor="poor",e.Unknown="unknown"}(qt||(qt={}));class Participant extends It.exports.EventEmitter{constructor(e,t){super(),this.audioLevel=0,this.isSpeaking=!1,this._connectionQuality=qt.Unknown,this.sid=e,this.identity=t,this.audioTracks=new Map,this.videoTracks=new Map,this.tracks=new Map}getTracks(){return Array.from(this.tracks.values())}getTrack(e){if(e!==Track.Source.Unknown)for(const[,t]of this.tracks){if(t.source===e)return t;if(t.source===Track.Source.Unknown){if(e===Track.Source.Microphone&&t.kind===Track.Kind.Audio&&"screen"!==t.trackName)return t;if(e===Track.Source.Camera&&t.kind===Track.Kind.Video&&"screen"!==t.trackName)return t;if(e===Track.Source.ScreenShare&&t.kind===Track.Kind.Video&&"screen"===t.trackName)return t;if(e===Track.Source.ScreenShareAudio&&t.kind===Track.Kind.Audio&&"screen"===t.trackName)return t}}}getTrackByName(e){for(const[,t]of this.tracks)if(t.trackName===e)return t}get connectionQuality(){return this._connectionQuality}get isCameraEnabled(){return!(this.getTrack(Track.Source.Camera)?.isMuted??1)}get isMicrophoneEnabled(){return!(this.getTrack(Track.Source.Microphone)?.isMuted??1)}get isScreenShareEnabled(){return!!this.getTrack(Track.Source.ScreenShare)}get joinedAt(){return this.participantInfo?new Date(1e3*this.participantInfo.joinedAt):new Date}updateInfo(e){this.identity=e.identity,this.sid=e.sid,this.name=e.name,this.setMetadata(e.metadata),e.permission&&this.setPermissions(e.permission),this.participantInfo=e}setMetadata(e){const t=this.metadata!==e,i=this.metadata;this.metadata=e,t&&(this.emit(Ct.MetadataChanged,i),this.emit(Ct.ParticipantMetadataChanged,i))}setPermissions(e){const t=e.canPublish!==this.permissions?.canPublish||e.canSubscribe!==this.permissions?.canSubscribe||e.canPublishData!==this.permissions?.canPublishData||e.hidden!==this.permissions?.hidden||e.recorder!==this.permissions?.recorder;return this.permissions=e,t}setIsSpeaking(e){e!==this.isSpeaking&&(this.isSpeaking=e,e&&(this.lastSpokeAt=new Date),this.emit(Ct.IsSpeakingChanged,e))}setConnectionQuality(e){const t=this._connectionQuality;this._connectionQuality=function qualityFromProto(e){switch(e){case ye.EXCELLENT:return qt.Excellent;case ye.GOOD:return qt.Good;case ye.POOR:return qt.Poor;default:return qt.Unknown}}(e),t!==this._connectionQuality&&this.emit(Ct.ConnectionQualityChanged,this._connectionQuality)}addTrackPublication(e){e.on(Et.Muted,(()=>{this.emit(Ct.TrackMuted,e)})),e.on(Et.Unmuted,(()=>{this.emit(Ct.TrackUnmuted,e)}));const t=e;switch(t.track&&(t.track.sid=e.trackSid),this.tracks.set(e.trackSid,e),e.kind){case Track.Kind.Audio:this.audioTracks.set(e.trackSid,e);break;case Track.Kind.Video:this.videoTracks.set(e.trackSid,e)}}}function mediaTrackToLocalTrack(e,t){switch(e.kind){case"audio":return new LocalAudioTrack(e,t);case"video":return new LocalVideoTrack(e,t);default:throw new TrackInvalidError(`unsupported track type: ${e.kind}`)}}const Wt=Object.values(Vt),Gt=Object.values(jt),Qt=Object.values($t),Ht=[Vt.h180,Vt.h360],zt=[jt.h180,jt.h360],Kt=["q","h","f"];function computeVideoEncodings(e,t,i,n){let s=n?.videoEncoding;e&&(s=n?.screenShareEncoding);const a=n?.simulcast;if(!s&&!a||!t||!i)return[{}];if(s||(s=function determineAppropriateEncoding(e,t,i){const n=function presetsForResolution(e,t,i){if(e)return Qt;const n=t>i?t/i:i/t;if(Math.abs(n-16/9)=a)break}return s}(e,t,i),h.debug("using video encoding",s)),!a)return[s];const o=new VideoPreset(t,i,s.maxBitrate,s.maxFramerate);let c,u=[];u=e?sortPresets(n?.screenShareSimulcastLayers)??defaultSimulcastLayers(e,o):sortPresets(n?.videoSimulcastLayers)??defaultSimulcastLayers(e,o);const l=u[0];u.length>1&&([,c]=u);const p=Math.max(t,i);return encodingsFromPresets(t,i,p>=960&&c?[l,c,o]:p>=480?[l,o]:[o])}function defaultSimulcastLayers(e,t){if(e)return i=t,[{scaleResolutionDownBy:2,fps:3}].map((e=>new VideoPreset(Math.floor(i.width/e.scaleResolutionDownBy),Math.floor(i.height/e.scaleResolutionDownBy),Math.max(15e4,Math.floor(i.encoding.maxBitrate/(e.scaleResolutionDownBy**2*((i.encoding.maxFramerate??30)/e.fps)))),e.fps)));var i;const{width:n,height:s}=t,a=n>s?n/s:s/n;return Math.abs(a-16/9){if(s>=Kt.length)return;const a=Math.min(e,t),o=Kt[s];n.push({rid:o,scaleResolutionDownBy:a/Math.min(i.width,i.height),maxBitrate:i.encoding.maxBitrate,maxFramerate:i.encoding.maxFramerate})})),n}function sortPresets(e){if(e)return e.sort(((e,t)=>{const{encoding:i}=e,{encoding:n}=t;return i.maxBitrate>n.maxBitrate?1:i.maxBitraten.maxFramerate?1:-1:0}))}class RemoteTrackPublication extends TrackPublication{constructor(){super(...arguments),this._allowed=!0,this.disabled=!1,this.currentVideoQuality=ke.HIGH,this.handleEnded=e=>{this.emit(Et.Ended,e)},this.handleVisibilityChange=e=>{h.debug(`adaptivestream video visibility ${this.trackSid}, visible=${e}`,{trackSid:this.trackSid}),this.disabled=!e,this.emitTrackUpdate()},this.handleVideoDimensionsChange=e=>{h.debug(`adaptivestream video dimensions ${e.width}x${e.height}`,{trackSid:this.trackSid}),this.videoDimensions=e,this.emitTrackUpdate()}}setSubscribed(e){this.subscribed=e;const t={trackSids:[this.trackSid],subscribe:this.subscribed,participantTracks:[{participantSid:"",trackSids:[this.trackSid]}]};this.emit(Et.UpdateSubscription,t)}get subscriptionStatus(){return!1!==this.subscribed&&super.isSubscribed?this._allowed?TrackPublication.SubscriptionStatus.Subscribed:TrackPublication.SubscriptionStatus.NotAllowed:TrackPublication.SubscriptionStatus.Unsubscribed}get isSubscribed(){return!1!==this.subscribed&&(!!this._allowed&&super.isSubscribed)}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){this.isManualOperationAllowed()&&(this.videoDimensions?.width===e.width&&this.videoDimensions?.height===e.height||(this.track instanceof RemoteVideoTrack&&(this.videoDimensions=e),this.currentVideoQuality=void 0,this.emitTrackUpdate()))}get videoQuality(){return this.currentVideoQuality}setTrack(e){this.track&&(this.track.off(Et.VideoDimensionsChanged,this.handleVideoDimensionsChange),this.track.off(Et.VisibilityChanged,this.handleVisibilityChange),this.track.off(Et.Ended,this.handleEnded)),super.setTrack(e),e&&(e.sid=this.trackSid,e.on(Et.VideoDimensionsChanged,this.handleVideoDimensionsChange),e.on(Et.VisibilityChanged,this.handleVisibilityChange),e.on(Et.Ended,this.handleEnded))}updateInfo(e){super.updateInfo(e),this.metadataMuted=e.muted,this.track?.setMuted(e.muted)}isManualOperationAllowed(){return this.isAdaptiveStream?(h.warn("adaptive stream is enabled, cannot change track settings",{trackSid:this.trackSid}),!1):!!this.isSubscribed||(h.warn("cannot update track settings when not subscribed",{trackSid:this.trackSid}),!1)}get isAdaptiveStream(){return this.track instanceof RemoteVideoTrack&&this.track.isAdaptiveStream}emitTrackUpdate(){const e=nt.fromPartial({trackSids:[this.trackSid],disabled:this.disabled});this.videoDimensions?(e.width=this.videoDimensions.width,e.height=this.videoDimensions.height):void 0!==this.currentVideoQuality?e.quality=this.currentVideoQuality:e.quality=ke.HIGH,this.emit(Et.UpdateSettings,e)}}class RemoteParticipant extends Participant{constructor(e,t,i){super(t,i||""),this.signalClient=e,this.tracks=new Map,this.audioTracks=new Map,this.videoTracks=new Map}static fromParticipantInfo(e,t){const i=new RemoteParticipant(e,t.sid,t.identity);return i.updateInfo(t),i}addTrackPublication(e){super.addTrackPublication(e),e.on(Et.UpdateSettings,(e=>{this.signalClient.sendUpdateTrackSettings(e)})),e.on(Et.UpdateSubscription,(e=>{e.participantTracks.forEach((e=>{e.participantSid=this.sid})),this.signalClient.sendUpdateSubscription(e)})),e.on(Et.Ended,(t=>{this.emit(Ct.TrackUnsubscribed,t,e)}))}getTrack(e){const t=super.getTrack(e);if(t)return t}getTrackByName(e){const t=super.getTrackByName(e);if(t)return t}setVolume(e){const t=this.getTrack(Track.Source.Microphone);t&&t.track.setVolume(e)}getVolume(){const e=this.getTrack(Track.Source.Microphone);if(e)return e.track.getVolume()}addSubscribedMediaTrack(e,t,i,n,s,a){let o=this.getTrackPublication(t);if(o||t.startsWith("TR")||this.tracks.forEach((t=>{o||e.kind!==t.kind.toString()||(o=t)})),!o)return 0===a?(h.error("could not find published track",{participant:this.sid,trackSid:t}),void this.emit(Ct.TrackSubscriptionFailed,t)):(void 0===a&&(a=20),void setTimeout((()=>{this.addSubscribedMediaTrack(e,t,i,n,s,a-1)}),150));let c;return c="video"===e.kind?new RemoteVideoTrack(e,t,n,s):new RemoteAudioTrack(e,t,n),c.source=o.source,c.isMuted=o.isMuted,c.setMediaStream(i),c.start(),o.setTrack(c),this.emit(Ct.TrackSubscribed,c,o),o}get hasMetadata(){return!!this.participantInfo}getTrackPublication(e){return this.tracks.get(e)}updateInfo(e){const t=this.hasMetadata;super.updateInfo(e);const i=new Map,n=new Map;e.tracks.forEach((e=>{let t=this.getTrackPublication(e.sid);if(t)t.updateInfo(e);else{const i=Track.kindFromProto(e.type);if(!i)return;t=new RemoteTrackPublication(i,e.sid,e.name),t.updateInfo(e),n.set(e.sid,t),this.addTrackPublication(t)}i.set(e.sid,t)})),t&&n.forEach((e=>{this.emit(Ct.TrackPublished,e)})),this.tracks.forEach((e=>{i.has(e.trackSid)||this.unpublishTrack(e.trackSid,!0)}))}unpublishTrack(e,t){const i=this.tracks.get(e);if(!i)return;switch(this.tracks.delete(e),i.kind){case Track.Kind.Audio:this.audioTracks.delete(e);break;case Track.Kind.Video:this.videoTracks.delete(e)}const{track:n}=i;if(n){const{isSubscribed:e}=i;n.stop(),i.setTrack(void 0),e&&this.emit(Ct.TrackUnsubscribed,n,i)}t&&this.emit(Ct.TrackUnpublished,i)}emit(e,...t){return h.trace("participant event",{participant:this.sid,event:e,args:t}),super.emit(e,...t)}}class LocalParticipant extends Participant{constructor(e,t,i,n){super(e,t),this.pendingPublishing=new Set,this.onTrackUnmuted=e=>{this.onTrackMuted(e,!1)},this.onTrackMuted=(e,t)=>{void 0===t&&(t=!0),e.sid?this.engine.updateMuteStatus(e.sid,t):h.error("could not update mute status for unpublished track",e)},this.handleSubscribedQualityUpdate=e=>{if(!this.roomOptions?.dynacast)return;const t=this.videoTracks.get(e.trackSid);t?t.videoTrack?.setPublishingLayers(e.subscribedQualities):h.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):h.warn("received unpublished event for unknown track",{method:"handleLocalTrackUnpublished",trackSid:e.trackSid})},this.onTrackUnpublish=e=>{this.unpublishTrack(e)},this.audioTracks=new Map,this.videoTracks=new Map,this.tracks=new Map,this.engine=i,this.roomOptions=n,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}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}setCameraEnabled(e){return this.setTrackEnabled(Track.Source.Camera,e)}setMicrophoneEnabled(e){return this.setTrackEnabled(Track.Source.Microphone,e)}setScreenShareEnabled(e){return this.setTrackEnabled(Track.Source.ScreenShare,e)}setPermissions(e){const t=this.permissions,i=super.setPermissions(e);return i&&t&&this.emit(Ct.ParticipantPermissionsChanged,t),i}async setTrackEnabled(e,t){h.debug("setTrackEnabled",{source:e,enabled:t});let i=this.getTrack(e);if(t)if(i)await i.unmute();else{let t;if(this.pendingPublishing.has(e))return void h.info("skipping duplicate published source",{source:e});this.pendingPublishing.add(e);try{switch(e){case Track.Source.Camera:[t]=await this.createTracks({video:!0});break;case Track.Source.Microphone:[t]=await this.createTracks({audio:!0});break;case Track.Source.ScreenShare:[t]=await this.createScreenTracks({audio:!1});break;default:throw new TrackInvalidError(e)}i=await this.publishTrack(t)}catch(e){throw e instanceof Error&&!(e instanceof TrackInvalidError)&&this.emit(Ct.MediaDevicesError,e),e}finally{this.pendingPublishing.delete(e)}}else i&&i.track&&(e===Track.Source.ScreenShare?i=this.unpublishTrack(i.track):await i.mute());return i}async enableCameraAndMicrophone(){if(!this.pendingPublishing.has(Track.Source.Camera)&&!this.pendingPublishing.has(Track.Source.Microphone)){this.pendingPublishing.add(Track.Source.Camera),this.pendingPublishing.add(Track.Source.Microphone);try{const e=await this.createTracks({audio:!0,video:!0});await Promise.all(e.map((e=>this.publishTrack(e))))}finally{this.pendingPublishing.delete(Track.Source.Camera),this.pendingPublishing.delete(Track.Source.Microphone)}}}async createTracks(e){const t=constraintsForOptions(mergeDefaultOptions(e,this.roomOptions?.audioCaptureDefaults,this.roomOptions?.videoCaptureDefaults));let i;try{i=await navigator.mediaDevices.getUserMedia(t)}catch(e){throw e instanceof Error&&(t.audio&&(this.microphoneError=e),t.video&&(this.cameraError=e)),e}return t.audio&&(this.microphoneError=void 0),t.video&&(this.cameraError=void 0),i.getTracks().map((n=>{const s="audio"===n.kind;let a;s?e.audio:e.video;const o=s?t.audio:t.video;"boolean"!=typeof o&&(a=o);const c=mediaTrackToLocalTrack(n,a);return c.kind===Track.Kind.Video?c.source=Track.Source.Camera:c.kind===Track.Kind.Audio&&(c.source=Track.Source.Microphone),c.mediaStream=i,c}))}async createScreenTracks(e){void 0===e&&(e={}),void 0===e.resolution&&(e.resolution=$t.h1080fps15.resolution);let t=!0;e.resolution&&(t={width:e.resolution.width,height:e.resolution.height,frameRate:e.resolution.frameRate});const i=await navigator.mediaDevices.getDisplayMedia({audio:e.audio??!1,video:t}),n=i.getVideoTracks();if(0===n.length)throw new TrackInvalidError("no video track found");const s=new LocalVideoTrack(n[0]);s.source=Track.Source.ScreenShare;const a=[s];if(i.getAudioTracks().length>0){const e=new LocalAudioTrack(i.getAudioTracks()[0]);e.source=Track.Source.ScreenShareAudio,a.push(e)}return a}async publishTrack(e,t){const i={...this.roomOptions?.publishDefaults,...t};if(e instanceof MediaStreamTrack)switch(e.kind){case"audio":e=new LocalAudioTrack(e);break;case"video":e=new LocalVideoTrack(e);break;default:throw new TrackInvalidError(`unsupported MediaStreamTrack kind ${e.kind}`)}let n;if(this.tracks.forEach((t=>{t.track&&t.track===e&&(n=t)})),n)return n;i.source&&(e.source=i.source),i.stopMicTrackOnMute&&e instanceof LocalAudioTrack&&(e.stopOnMute=!0),e.source===Track.Source.ScreenShare&&isFireFox()&&(i.simulcast=!1),e.on(Et.Muted,this.onTrackMuted),e.on(Et.Unmuted,this.onTrackUnmuted),e.on(Et.Ended,this.onTrackUnpublish);const s=ze.fromPartial({cid:e.mediaStreamTrack.id,name:t?.name,type:Track.kindToProto(e.kind),muted:e.isMuted,source:Track.sourceToProto(e.source),disableDtx:!(i?.dtx??1)});let a;if(e.kind===Track.Kind.Video){const t=e.mediaStreamTrack.getSettings(),n=t.width??e.dimensions?.width,o=t.height??e.dimensions?.height;s.width=n??0,s.height=o??0,a=computeVideoEncodings(e.source===Track.Source.ScreenShare,n,o,i),s.layers=function videoLayersFromEncodings(e,t,i){return i?i.map((n=>{const s=n.scaleResolutionDownBy??1;let a=videoQualityForRid(n.rid??"");return a===ke.UNRECOGNIZED&&1===i.length&&(a=ke.HIGH),{quality:a,width:e/s,height:t/s,bitrate:n.maxBitrate??0,ssrc:0}})):[{quality:ke.HIGH,width:e,height:t,bitrate:0,ssrc:0}]}(s.width,s.height,a)}else e.kind===Track.Kind.Audio&&i.audioBitrate&&(a=[{maxBitrate:i.audioBitrate}]);const o=await this.engine.addTrack(s),c=new LocalTrackPublication(e.kind,o,e);if(e.sid=o.sid,!this.engine.publisher)throw new UnexpectedConnectionState("publisher is closed");h.debug(`publishing ${e.kind} with encodings`,{encodings:a,trackInfo:o});const u={direction:"sendonly"};a&&(u.sendEncodings=a);const l=this.engine.publisher.pc.addTransceiver(e.mediaStreamTrack,u);return this.engine.negotiate(),e.sender=l.sender,e instanceof LocalVideoTrack?e.startMonitor(this.engine.client):e instanceof LocalAudioTrack&&e.startMonitor(),i.videoCodec&&this.setPreferredCodec(l,e.kind,i.videoCodec),this.addTrackPublication(c),this.emit(Ct.LocalTrackPublished,c),c}unpublishTrack(e,t){const i=this.getPublicationForTrack(e);if(h.debug("unpublishing track",{track:e,method:"unpublishTrack"}),!i||!i.track)return void h.warn("track was not unpublished because no publication was found",{track:e,method:"unpublishTrack"});(e=i.track).off(Et.Muted,this.onTrackMuted),e.off(Et.Unmuted,this.onTrackUnmuted),e.off(Et.Ended,this.onTrackUnpublish),void 0===t&&(t=this.roomOptions?.stopLocalTrackOnUnpublish??!0),t&&e.stop();const{mediaStreamTrack:n}=e;if(this.engine.publisher){this.engine.publisher.pc.getSenders().forEach((e=>{if(e.track===n)try{this.engine.publisher?.pc.removeTrack(e),this.engine.negotiate()}catch(e){h.warn("failed to remove track",{error:e,method:"unpublishTrack"})}}))}switch(this.tracks.delete(i.trackSid),i.kind){case Track.Kind.Audio:this.audioTracks.delete(i.trackSid);break;case Track.Kind.Video:this.videoTracks.delete(i.trackSid)}return this.emit(Ct.LocalTrackUnpublished,i),i.setTrack(void 0),i}unpublishTracks(e){const t=[];return e.forEach((e=>{const i=this.unpublishTrack(e);i&&t.push(i)})),t}async publishData(e,t,i){const n=[];void 0!==i&&i.forEach((e=>{e instanceof RemoteParticipant?n.push(e.sid):n.push(e)}));const s={kind:t,user:{participantSid:this.sid,payload:e,destinationSids:n}};await this.engine.sendDataPacket(s,t)}setTrackSubscriptionPermissions(e,t=[]){this.engine.client.sendUpdateSubscriptionPermissions(e,t.map((e=>function trackPermissionToProto(e){if(!e.participantSid)throw new Error("Invalid track permission, missing participantSid");return{participantSid:e.participantSid,allTracks:e.allowAll??!1,trackSids:e.allowedTrackSids||[]}}(e))))}getPublicationForTrack(e){let t;return this.tracks.forEach((i=>{const n=i.track;n&&(e instanceof MediaStreamTrack?(n instanceof LocalAudioTrack||n instanceof LocalVideoTrack)&&n.mediaStreamTrack===e&&(t=i):e===n&&(t=i))})),t}setPreferredCodec(e,t,i){if(!("getCapabilities"in RTCRtpSender))return;const n=RTCRtpSender.getCapabilities(t);if(!n)return;const s=n.codecs.find((e=>{const t=e.mimeType.toLowerCase(),n=t===`video/${i}`;return"h264"===i&&e.sdpFmtpLine?n&&e.sdpFmtpLine.includes("profile-level-id=42e01f"):n||"audio/opus"===t}));s&&"setCodecPreferences"in e&&e.setCodecPreferences([s])}publishedTracksInfo(){const e=[];return this.tracks.forEach((t=>{void 0!==t.track&&e.push({cid:t.track.mediaStreamTrack.id,track:t.trackInfo})})),e}dataChannelsInfo(){const e=[],getInfo=(t,i)=>{void 0!==t?.id&&null!==t.id&&e.push({label:t.label,id:t.id,target:i})};return getInfo(this.engine.dataChannelForKind(Ce.LOSSY),We.PUBLISHER),getInfo(this.engine.dataChannelForKind(Ce.RELIABLE),We.PUBLISHER),getInfo(this.engine.dataChannelForKind(Ce.LOSSY,!0),We.SUBSCRIBER),getInfo(this.engine.dataChannelForKind(Ce.RELIABLE,!0),We.SUBSCRIBER),e}}class Queue{constructor(){this.queue=[],this.running=!1}enqueue(e){h.trace("enqueuing request to fire later"),this.queue.push(e)}dequeue(){const e=this.queue.shift();e&&e(),h.trace("firing request from queue")}async run(){if(!this.running){for(h.trace("start queue"),this.running=!0;this.running&&this.queue.length>0;)this.dequeue();this.running=!1,h.trace("queue finished")}}pause(){h.trace("pausing queue"),this.running=!1}reset(){h.trace("resetting queue"),this.running=!1,this.queue=[]}isRunning(){return this.running}isEmpty(){return 0===this.queue.length}}let Zt=!0,Yt=!0;function extractVersion(e,t,i){const n=e.match(t);return n&&n.length>=i&&parseInt(n[i],10)}function wrapPeerConnectionEvent(e,t,i){if(!e.RTCPeerConnection)return;const n=e.RTCPeerConnection.prototype,s=n.addEventListener;n.addEventListener=function(e,n){if(e!==t)return s.apply(this,arguments);const wrappedCallback=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,wrappedCallback),s.apply(this,[e,wrappedCallback])};const a=n.removeEventListener;n.removeEventListener=function(e,i){if(e!==t||!this._eventMap||!this._eventMap[t])return a.apply(this,arguments);if(!this._eventMap[t].has(i))return a.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,a.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 disableLog(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(Zt=e,e?"adapter.js logging disabled":"adapter.js logging enabled")}function disableWarnings(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(Yt=!e,"adapter.js deprecation warnings "+(e?"disabled":"enabled"))}function log(){if("object"==typeof window){if(Zt)return;"undefined"!=typeof console&&"function"==typeof console.log&&console.log.apply(console,arguments)}}function deprecated(e,t){Yt&&console.warn(e+" is deprecated, please use "+t+" instead.")}function detectBrowser(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=extractVersion(i.userAgent,/Firefox\/(\d+)\./,1);else if(i.webkitGetUserMedia||!1===e.isSecureContext&&e.webkitRTCPeerConnection&&!e.RTCIceGatherer)t.browser="chrome",t.version=extractVersion(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=extractVersion(i.userAgent,/AppleWebKit\/(\d+)\./,1),t.supportsUnifiedPlan=e.RTCRtpTransceiver&&"currentDirection"in e.RTCRtpTransceiver.prototype}return t}function isObject(e){return"[object Object]"===Object.prototype.toString.call(e)}function compactObject(e){return isObject(e)?Object.keys(e).reduce((function(t,i){const n=isObject(e[i]),s=n?compactObject(e[i]):e[i],a=n&&!Object.keys(s).length;return void 0===s||a?t:Object.assign(t,{[i]:s})}),{}):e}function walkStats(e,t,i){t&&!i.has(t.id)&&(i.set(t.id,t),Object.keys(t).forEach((n=>{n.endsWith("Id")?walkStats(e,e.get(t[n]),i):n.endsWith("Ids")&&t[n].forEach((t=>{walkStats(e,e.get(t),i)}))})))}function filterStats(e,t,i){const n=i?"outbound-rtp":"inbound-rtp",s=new Map;if(null===t)return s;const a=[];return e.forEach((e=>{"track"===e.type&&e.trackIdentifier===t.id&&a.push(e)})),a.forEach((t=>{e.forEach((i=>{i.type===n&&i.trackId===t.id&&walkStats(e,i,s)}))})),s}const Xt=log;function shimGetUserMedia$2(e,t){const i=e&&e.navigator;if(!i.mediaDevices)return;const constraintsToChrome_=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 oldname_=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[oldname_("min",i)]=n.ideal,t.optional.push(e),e={},e[oldname_("max",i)]=n.ideal,t.optional.push(e)):(e[oldname_("",i)]=n.ideal,t.optional.push(e))}void 0!==n.exact&&"number"!=typeof n.exact?(t.mandatory=t.mandatory||{},t.mandatory[oldname_("",i)]=n.exact):["min","max"].forEach((e=>{void 0!==n[e]&&(t.mandatory=t.mandatory||{},t.mandatory[oldname_(e,i)]=n[e])}))})),e.advanced&&(t.optional=(t.optional||[]).concat(e.advanced)),t},shimConstraints_=function(e,n){if(t.version>=61)return n(e);if((e=JSON.parse(JSON.stringify(e)))&&"object"==typeof e.audio){const remap=function(e,t,i){t in e&&!(i in e)&&(e[i]=e[t],delete e[t])};remap((e=JSON.parse(JSON.stringify(e))).audio,"autoGainControl","googAutoGainControl"),remap(e.audio,"noiseSuppression","googNoiseSuppression"),e.audio=constraintsToChrome_(e.audio)}if(e&&"object"==typeof e.video){let s=e.video.facingMode;s=s&&("object"==typeof s?s:{ideal:s});const a=t.version<66;if(s&&("user"===s.exact||"environment"===s.exact||"user"===s.ideal||"environment"===s.ideal)&&(!i.mediaDevices.getSupportedConstraints||!i.mediaDevices.getSupportedConstraints().facingMode||a)){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 a=(i=i.filter((e=>"videoinput"===e.kind))).find((e=>t.some((t=>e.label.toLowerCase().includes(t)))));return!a&&i.length&&t.includes("back")&&(a=i[i.length-1]),a&&(e.video.deviceId=s.exact?{exact:a.deviceId}:{ideal:a.deviceId}),e.video=constraintsToChrome_(e.video),Xt("chrome: "+JSON.stringify(e)),n(e)}))}e.video=constraintsToChrome_(e.video)}return Xt("chrome: "+JSON.stringify(e)),n(e)},shimError_=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){shimConstraints_(e,(e=>{i.webkitGetUserMedia(e,t,(e=>{n&&n(shimError_(e))}))}))}.bind(i),i.mediaDevices.getUserMedia){const e=i.mediaDevices.getUserMedia.bind(i.mediaDevices);i.mediaDevices.getUserMedia=function(t){return shimConstraints_(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(shimError_(e))))))}}}function shimMediaStream(e){e.MediaStream=e.MediaStream||e.webkitMediaStream}function shimOnTrack$1(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 setRemoteDescription(){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 s=new Event("track");s.track=i.track,s.receiver=n,s.transceiver={receiver:n},s.streams=[t.stream],this.dispatchEvent(s)})),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 s=new Event("track");s.track=i,s.receiver=n,s.transceiver={receiver:n},s.streams=[t.stream],this.dispatchEvent(s)}))},this.addEventListener("addstream",this._ontrackpoly)),t.apply(this,arguments)}}else wrapPeerConnectionEvent(e,"track",(e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e)))}function shimGetSendersWithDtmf(e){if("object"==typeof e&&e.RTCPeerConnection&&!("getSenders"in e.RTCPeerConnection.prototype)&&"createDTMFSender"in e.RTCPeerConnection.prototype){const shimSenderWithDtmf=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 getSenders(){return this._senders=this._senders||[],this._senders.slice()};const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function addTrack(e,i){let n=t.apply(this,arguments);return n||(n=shimSenderWithDtmf(this,e),this._senders.push(n)),n};const i=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function removeTrack(e){i.apply(this,arguments);const t=this._senders.indexOf(e);-1!==t&&this._senders.splice(t,1)}}const t=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function addStream(e){this._senders=this._senders||[],t.apply(this,[e]),e.getTracks().forEach((e=>{this._senders.push(shimSenderWithDtmf(this,e))}))};const i=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function removeStream(e){this._senders=this._senders||[],i.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 getSenders(){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 shimGetStats(e){if(!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function getStats(){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 fixChromeStats_=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},makeMapStats=function(e){return new Map(Object.keys(e).map((t=>[t,e[t]])))};if(arguments.length>=2){const successCallbackWrapper_=function(e){i(makeMapStats(fixChromeStats_(e)))};return t.apply(this,[successCallbackWrapper_,e])}return new Promise(((e,i)=>{t.apply(this,[function(t){e(makeMapStats(fixChromeStats_(t)))},i])})).then(i,n)}}function shimSenderReceiverGetStats(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 getSenders(){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 addTrack(){const e=i.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function getStats(){const e=this;return this._pc.getStats().then((t=>filterStats(t,e.track,!0)))}}if(!("getStats"in e.RTCRtpReceiver.prototype)){const t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function getReceivers(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e}),wrapPeerConnectionEvent(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function getStats(){const e=this;return this._pc.getStats().then((t=>filterStats(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 getStats(){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 shimAddTrackRemoveTrackWithNative(e){e.RTCPeerConnection.prototype.getLocalStreams=function getLocalStreams(){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 addTrack(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 addStream(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 removeStream(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[e.id],n.apply(this,arguments)};const s=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function removeTrack(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]})),s.apply(this,arguments)}}function shimAddTrackRemoveTrack(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return shimAddTrackRemoveTrackWithNative(e);const i=e.RTCPeerConnection.prototype.getLocalStreams;e.RTCPeerConnection.prototype.getLocalStreams=function getLocalStreams(){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 addStream(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 s=e.RTCPeerConnection.prototype.removeStream;function replaceInternalStreamId(e,t){let i=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((t=>{const n=e._reverseStreams[t],s=e._streams[n.id];i=i.replace(new RegExp(s.id,"g"),n.id)})),new RTCSessionDescription({type:t.type,sdp:i})}function replaceExternalStreamId(e,t){let i=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((t=>{const n=e._reverseStreams[t],s=e._streams[n.id];i=i.replace(new RegExp(n.id,"g"),s.id)})),new RTCSessionDescription({type:t.type,sdp:i})}e.RTCPeerConnection.prototype.removeStream=function removeStream(e){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},s.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 addTrack(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");const s=this.getSenders().find((e=>e.track===t));if(s)throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};const a=this._streams[i.id];if(a)a.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=replaceInternalStreamId(this,t);e[0].apply(null,[i])},t=>{e[1]&&e[1].apply(null,t)},arguments[2]]):i.apply(this,arguments).then((e=>replaceInternalStreamId(this,e)))}};e.RTCPeerConnection.prototype[t]=n[t]}));const a=e.RTCPeerConnection.prototype.setLocalDescription;e.RTCPeerConnection.prototype.setLocalDescription=function setLocalDescription(){return arguments.length&&arguments[0].type?(arguments[0]=replaceExternalStreamId(this,arguments[0]),a.apply(this,arguments)):a.apply(this,arguments)};const o=Object.getOwnPropertyDescriptor(e.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(e.RTCPeerConnection.prototype,"localDescription",{get(){const e=o.get.apply(this);return""===e.type?e:replaceInternalStreamId(this,e)}}),e.RTCPeerConnection.prototype.removeTrack=function removeTrack(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 shimPeerConnection$1(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 fixNegotiationNeeded(e,t){wrapPeerConnectionEvent(e,"negotiationneeded",(e=>{const i=e.target;if(!(t.version<72||i.getConfiguration&&"plan-b"===i.getConfiguration().sdpSemantics)||"stable"===i.signalingState)return e}))}var ei=Object.freeze({__proto__:null,shimMediaStream,shimOnTrack:shimOnTrack$1,shimGetSendersWithDtmf,shimGetStats,shimSenderReceiverGetStats,shimAddTrackRemoveTrackWithNative,shimAddTrackRemoveTrack,shimPeerConnection:shimPeerConnection$1,fixNegotiationNeeded,shimGetUserMedia:shimGetUserMedia$2,shimGetDisplayMedia:function shimGetDisplayMedia$1(e,t){e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||e.navigator.mediaDevices&&("function"==typeof t?e.navigator.mediaDevices.getDisplayMedia=function getDisplayMedia(i){return t(i).then((t=>{const n=i.video&&i.video.width,s=i.video&&i.video.height,a=i.video&&i.video.frameRate;return i.video={mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:t,maxFrameRate:a||3}},n&&(i.video.mandatory.maxWidth=n),s&&(i.video.mandatory.maxHeight=s),e.navigator.mediaDevices.getUserMedia(i)}))}:console.error("shimGetDisplayMedia: getSourceId argument is not a function"))}});function shimGetUserMedia$1(e,t){const i=e&&e.navigator,n=e&&e.MediaStreamTrack;if(i.getUserMedia=function(e,t,n){deprecated("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),i.mediaDevices.getUserMedia(e).then(t,n)},!(t.version>55&&"autoGainControl"in i.mediaDevices.getSupportedConstraints())){const remap=function(e,t,i){t in e&&!(i in e)&&(e[i]=e[t],delete e[t])},e=i.mediaDevices.getUserMedia.bind(i.mediaDevices);if(i.mediaDevices.getUserMedia=function(t){return"object"==typeof t&&"object"==typeof t.audio&&(t=JSON.parse(JSON.stringify(t)),remap(t.audio,"autoGainControl","mozAutoGainControl"),remap(t.audio,"noiseSuppression","mozNoiseSuppression")),e(t)},n&&n.prototype.getSettings){const e=n.prototype.getSettings;n.prototype.getSettings=function(){const t=e.apply(this,arguments);return remap(t,"mozAutoGainControl","autoGainControl"),remap(t,"mozNoiseSuppression","noiseSuppression"),t}}if(n&&n.prototype.applyConstraints){const e=n.prototype.applyConstraints;n.prototype.applyConstraints=function(t){return"audio"===this.kind&&"object"==typeof t&&(t=JSON.parse(JSON.stringify(t)),remap(t,"autoGainControl","mozAutoGainControl"),remap(t,"noiseSuppression","mozNoiseSuppression")),e.apply(this,[t])}}}}function shimOnTrack(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 shimPeerConnection(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 getStats(){const[e,s,a]=arguments;return n.apply(this,[e||null]).then((e=>{if(t.version<53&&!s)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(s,a)}}function shimSenderGetStats(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 getSenders(){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 addTrack(){const e=i.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function getStats(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function shimReceiverGetStats(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 getReceivers(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e}),wrapPeerConnectionEvent(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function getStats(){return this._pc.getStats(this.track)}}function shimRemoveStream(e){e.RTCPeerConnection&&!("removeStream"in e.RTCPeerConnection.prototype)&&(e.RTCPeerConnection.prototype.removeStream=function removeStream(e){deprecated("removeStream","removeTrack"),this.getSenders().forEach((t=>{t.track&&e.getTracks().includes(t.track)&&this.removeTrack(t)}))})}function shimRTCDataChannel(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)}function shimAddTransceiver(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.addTransceiver;t&&(e.RTCPeerConnection.prototype.addTransceiver=function addTransceiver(){this.setParametersPromises=[];const e=arguments[1],i=e&&"sendEncodings"in e;i&&e.sendEncodings.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.sendEncodings,t.sendEncodings=e.sendEncodings,this.setParametersPromises.push(t.setParameters(i).then((()=>{delete t.sendEncodings})).catch((()=>{delete t.sendEncodings}))))}return n})}function shimGetParameters(e){if("object"!=typeof e||!e.RTCRtpSender)return;const t=e.RTCRtpSender.prototype.getParameters;t&&(e.RTCRtpSender.prototype.getParameters=function getParameters(){const e=t.apply(this,arguments);return"encodings"in e||(e.encodings=[].concat(this.sendEncodings||[{}])),e})}function shimCreateOffer(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function createOffer(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then((()=>t.apply(this,arguments))).finally((()=>{this.setParametersPromises=[]})):t.apply(this,arguments)}}function shimCreateAnswer(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.createAnswer;e.RTCPeerConnection.prototype.createAnswer=function createAnswer(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then((()=>t.apply(this,arguments))).finally((()=>{this.setParametersPromises=[]})):t.apply(this,arguments)}}var ti=Object.freeze({__proto__:null,shimOnTrack,shimPeerConnection,shimSenderGetStats,shimReceiverGetStats,shimRemoveStream,shimRTCDataChannel,shimAddTransceiver,shimGetParameters,shimCreateOffer,shimCreateAnswer,shimGetUserMedia:shimGetUserMedia$1,shimGetDisplayMedia:function shimGetDisplayMedia(e,t){e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||e.navigator.mediaDevices&&(e.navigator.mediaDevices.getDisplayMedia=function getDisplayMedia(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)})}});function shimLocalStreamsAPI(e){if("object"==typeof e&&e.RTCPeerConnection){if("getLocalStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getLocalStreams=function getLocalStreams(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in e.RTCPeerConnection.prototype)){const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addStream=function addStream(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 addTrack(e){for(var i=arguments.length,n=new Array(i>1?i-1:0),s=1;s{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 removeStream(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 shimRemoteStreamsAPI(e){if("object"==typeof e&&e.RTCPeerConnection&&("getRemoteStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getRemoteStreams=function getRemoteStreams(){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 setRemoteDescription(){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 shimCallbacksAPI(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype,i=t.createOffer,n=t.createAnswer,s=t.setLocalDescription,a=t.setRemoteDescription,o=t.addIceCandidate;t.createOffer=function createOffer(e,t){const n=arguments.length>=2?arguments[2]:arguments[0],s=i.apply(this,[n]);return t?(s.then(e,t),Promise.resolve()):s},t.createAnswer=function createAnswer(e,t){const i=arguments.length>=2?arguments[2]:arguments[0],s=n.apply(this,[i]);return t?(s.then(e,t),Promise.resolve()):s};let withCallback=function(e,t,i){const n=s.apply(this,[e]);return i?(n.then(t,i),Promise.resolve()):n};t.setLocalDescription=withCallback,withCallback=function(e,t,i){const n=a.apply(this,[e]);return i?(n.then(t,i),Promise.resolve()):n},t.setRemoteDescription=withCallback,withCallback=function(e,t,i){const n=o.apply(this,[e]);return i?(n.then(t,i),Promise.resolve()):n},t.addIceCandidate=withCallback}function shimGetUserMedia(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(shimConstraints(e))}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=function getUserMedia(e,i,n){t.mediaDevices.getUserMedia(e).then(i,n)}.bind(t))}function shimConstraints(e){return e&&void 0!==e.video?Object.assign({},e,{video:compactObject(e.video)}):e}function shimRTCIceServerUrls(e){if(!e.RTCPeerConnection)return;const t=e.RTCPeerConnection;e.RTCPeerConnection=function RTCPeerConnection(e,i){if(e&&e.iceServers){const t=[];for(let i=0;it.generateCertificate})}function shimTrackEventTransceiver(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 shimCreateOfferLegacy(e){const t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function createOffer(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 shimAudioContext(e){"object"!=typeof e||e.AudioContext||(e.AudioContext=e.webkitAudioContext)}var ii=Object.freeze({__proto__:null,shimLocalStreamsAPI,shimRemoteStreamsAPI,shimCallbacksAPI,shimGetUserMedia,shimConstraints,shimRTCIceServerUrls,shimTrackEventTransceiver,shimCreateOfferLegacy,shimAudioContext}),ri={exports:{}};!function(e){const t={generateIdentifier:function(){return Math.random().toString(36).substr(2,10)}};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;e0?t[0].split("/")[1]:"sendrecv",uri:t[1]}},t.writeExtmap=function(e){return"a=extmap:"+(e.id||e.preferredId)+(e.direction&&"sendrecv"!==e.direction?"/"+e.direction:"")+" "+e.uri+"\r\n"},t.parseFmtp=function(e){const t={};let i;const n=e.substr(e.indexOf(" ")+1).split(";");for(let e=0;e{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.substr(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.substr(7,t-7),10)},n=e.indexOf(":",t);return n>-1?(i.attribute=e.substr(t+1,n-t-1),i.value=e.substr(n+1)):i.attribute=e.substr(t+1),i},t.parseSsrcGroup=function(e){const t=e.substr(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.substr(6)},t.parseFingerprint=function(e){const t=e.substr(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.substr(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.substr(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],s=t.matchPrefix(e+i,"a=ice-pwd:")[0];return n&&s?{usernameFragment:n.substr(12),password:s.substr(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(" ");for(let s=3;s{i.headerExtensions.push(t.parseExtmap(e))})),i},t.writeRtpDescription=function(e,i){let n="";n+="m="+e+" ",n+=i.codecs.length>0?"9":"0",n+=" 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 s=0;return i.codecs.forEach((e=>{e.maxptime>s&&(s=e.maxptime)})),s>0&&(n+="a=maxptime:"+s+"\r\n"),i.headerExtensions&&i.headerExtensions.forEach((e=>{n+=t.writeExtmap(e)})),n},t.parseRtpEncodingParameters=function(e){const i=[],n=t.parseRtpParameters(e),s=-1!==n.fecMechanisms.indexOf("RED"),a=-1!==n.fecMechanisms.indexOf("ULPFEC"),o=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"cname"===e.attribute)),c=o.length>0&&o[0].ssrc;let u;const l=t.matchPrefix(e,"a=ssrc-group:FID").map((e=>e.substr(17).split(" ").map((e=>parseInt(e,10)))));l.length>0&&l[0].length>1&&l[0][0]===c&&(u=l[0][1]),n.codecs.forEach((e=>{if("RTX"===e.name.toUpperCase()&&e.parameters.apt){let t={ssrc:c,codecPayloadType:parseInt(e.parameters.apt,10)};c&&u&&(t.rtx={ssrc:u}),i.push(t),s&&(t=JSON.parse(JSON.stringify(t)),t.fec={ssrc:c,mechanism:a?"red+ulpfec":"red"},i.push(t))}})),0===i.length&&c&&i.push({ssrc:c});let h=t.matchPrefix(e,"b=");return h.length&&(h=0===h[0].indexOf("b=TIAS:")?parseInt(h[0].substr(7),10):0===h[0].indexOf("b=AS:")?1e3*parseInt(h[0].substr(5),10)*.95-16e3:void 0,i.forEach((e=>{e.maxBitrate=h}))),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 s=t.matchPrefix(e,"a=rtcp-rsize");i.reducedSize=s.length>0,i.compound=0===s.length;const a=t.matchPrefix(e,"a=rtcp-mux");return i.mux=a.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].substr(7).split(" "),{stream:i[0],track:i[1]};const s=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"msid"===e.attribute));return s.length>0?(i=s[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 s;n.length>0&&(s=parseInt(n[0].substr(19),10)),isNaN(s)&&(s=65536);const a=t.matchPrefix(e,"a=sctp-port:");if(a.length>0)return{port:parseInt(a[0].substr(12),10),protocol:i.fmt,maxMessageSize:s};const o=t.matchPrefix(e,"a=sctpmap:");if(o.length>0){const e=o[0].substr(10).split(" ");return{port:parseInt(e[0],10),protocol:e[1],maxMessageSize:s}}},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,21)},t.writeSessionBoilerplate=function(e,i,n){let s;const a=void 0!==i?i:2;s=e||t.generateSessionId();return"v=0\r\no="+(n||"thisisadapterortc")+" "+s+" "+a+" 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(t.candidate&&Object.defineProperty(t,"candidate",{value:new e.RTCIceCandidate(t.candidate),writable:"false"}),t)))}function shimMaxMessageSize(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 sctpInDescription=function(e){if(!e||!e.sdp)return!1;const t=ni.splitSections(e.sdp);return t.shift(),t.some((e=>{const t=ni.parseMLine(e);return t&&"application"===t.kind&&-1!==t.protocol.indexOf("SCTP")}))},getRemoteFirefoxVersion=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},getCanSendMaxMessageSize=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},getMaxMessageSize=function(e,i){let n=65536;"firefox"===t.browser&&57===t.version&&(n=65535);const s=ni.matchPrefix(e.sdp,"a=max-message-size:");return s.length>0?n=parseInt(s[0].substr(19),10):"firefox"===t.browser&&-1!==i&&(n=2147483637),n},i=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function setRemoteDescription(){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(sctpInDescription(arguments[0])){const e=getRemoteFirefoxVersion(arguments[0]),t=getCanSendMaxMessageSize(e),i=getMaxMessageSize(arguments[0],e);let n;n=0===t&&0===i?Number.POSITIVE_INFINITY:0===t||0===i?Math.max(t,i):Math.min(t,i);const s={};Object.defineProperty(s,"maxMessageSize",{get:()=>n}),this._sctp=s}return i.apply(this,arguments)}}function shimSendThrowTypeError(e){if(!e.RTCPeerConnection||!("createDataChannel"in e.RTCPeerConnection.prototype))return;function wrapDcSend(e,t){const i=e.send;e.send=function send(){const n=arguments[0],s=n.length||n.size||n.byteLength;if("open"===e.readyState&&t.sctp&&s>t.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+t.sctp.maxMessageSize+" bytes)");return i.apply(e,arguments)}}const t=e.RTCPeerConnection.prototype.createDataChannel;e.RTCPeerConnection.prototype.createDataChannel=function createDataChannel(){const e=t.apply(this,arguments);return wrapDcSend(e,this),e},wrapPeerConnectionEvent(e,"datachannel",(e=>(wrapDcSend(e.channel,e.target),e)))}function shimConnectionState(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 removeExtmapAllowMixed(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 setRemoteDescription(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 shimAddIceCandidateNullOrEmpty(e,t){if(!e.RTCPeerConnection||!e.RTCPeerConnection.prototype)return;const i=e.RTCPeerConnection.prototype.addIceCandidate;i&&0!==i.length&&(e.RTCPeerConnection.prototype.addIceCandidate=function addIceCandidate(){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 shimParameterlessSetLocalDescription(e,t){if(!e.RTCPeerConnection||!e.RTCPeerConnection.prototype)return;const i=e.RTCPeerConnection.prototype.setLocalDescription;i&&0!==i.length&&(e.RTCPeerConnection.prototype.setLocalDescription=function setLocalDescription(){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]);const t="offer"===e.type?this.createOffer:this.createAnswer;return t.apply(this).then((e=>i.apply(this,[e])))})}var ai=Object.freeze({__proto__:null,shimRTCIceCandidate,shimMaxMessageSize,shimSendThrowTypeError,shimConnectionState,removeExtmapAllowMixed,shimAddIceCandidateNullOrEmpty,shimParameterlessSetLocalDescription});!function adapterFactory(){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=log,n=detectBrowser(e),s={browserDetails:n,commonShim:ai,extractVersion,disableLog,disableWarnings,sdp:si};switch(n.browser){case"chrome":if(!ei||!shimPeerConnection$1||!t.shimChrome)return i("Chrome shim is not included in this adapter release."),s;if(null===n.version)return i("Chrome shim can not determine version, not shimming."),s;i("adapter.js shimming chrome."),s.browserShim=ei,shimAddIceCandidateNullOrEmpty(e,n),shimParameterlessSetLocalDescription(e),shimGetUserMedia$2(e,n),shimMediaStream(e),shimPeerConnection$1(e,n),shimOnTrack$1(e),shimAddTrackRemoveTrack(e,n),shimGetSendersWithDtmf(e),shimGetStats(e),shimSenderReceiverGetStats(e),fixNegotiationNeeded(e,n),shimRTCIceCandidate(e),shimConnectionState(e),shimMaxMessageSize(e,n),shimSendThrowTypeError(e),removeExtmapAllowMixed(e,n);break;case"firefox":if(!ti||!shimPeerConnection||!t.shimFirefox)return i("Firefox shim is not included in this adapter release."),s;i("adapter.js shimming firefox."),s.browserShim=ti,shimAddIceCandidateNullOrEmpty(e,n),shimParameterlessSetLocalDescription(e),shimGetUserMedia$1(e,n),shimPeerConnection(e,n),shimOnTrack(e),shimRemoveStream(e),shimSenderGetStats(e),shimReceiverGetStats(e),shimRTCDataChannel(e),shimAddTransceiver(e),shimGetParameters(e),shimCreateOffer(e),shimCreateAnswer(e),shimRTCIceCandidate(e),shimConnectionState(e),shimMaxMessageSize(e,n),shimSendThrowTypeError(e);break;case"safari":if(!ii||!t.shimSafari)return i("Safari shim is not included in this adapter release."),s;i("adapter.js shimming safari."),s.browserShim=ii,shimAddIceCandidateNullOrEmpty(e,n),shimParameterlessSetLocalDescription(e),shimRTCIceServerUrls(e),shimCreateOfferLegacy(e),shimCallbacksAPI(e),shimLocalStreamsAPI(e),shimRemoteStreamsAPI(e),shimTrackEventTransceiver(e),shimGetUserMedia(e),shimAudioContext(e),shimRTCIceCandidate(e),shimMaxMessageSize(e,n),shimSendThrowTypeError(e),removeExtmapAllowMixed(e,n);break;default:i("Unsupported browser!")}return s}({window:"undefined"==typeof window?void 0:window});const oi=["syncState","trickle","offer","answer","simulate","leave"];class SignalClient{constructor(e=!1){this.isConnected=!1,this.isReconnecting=!1,this.useJSON=e,this.requestQueue=new Queue}async join(e,t,i){this.isConnected=!1;return await this.connect(e,t,{autoSubscribe:i?.autoSubscribe,publishOnly:i?.publishOnly,adaptiveStream:i?.adaptiveStream})}async reconnect(e,t){this.isReconnecting=!0,await this.connect(e,t,{reconnect:!0})}connect(e,t,i){e.startsWith("http")&&(e=e.replace("http","ws")),e=e.replace(/\/$/,""),e+="/rtc";const n=function createConnectionParams(e,t,i){const n=new URLSearchParams;n.set("access_token",e),i?.reconnect&&n.set("reconnect","1");void 0!==i?.autoSubscribe&&n.set("auto_subscribe",i.autoSubscribe?"1":"0");n.set("sdk","js"),n.set("version",t.version),n.set("protocol",t.protocol.toString()),t.deviceModel&&n.set("device_model",t.deviceModel);t.os&&n.set("os",t.os);t.osVersion&&n.set("os_version",t.osVersion);t.browser&&n.set("browser",t.browser);t.browserVersion&&n.set("browser_version",t.browserVersion);void 0!==i?.publishOnly&&n.set("publish",i.publishOnly);i?.adaptiveStream&&n.set("adaptive_stream","1");return`?${n.toString()}`}(t,function getClientInfo(){return Je.fromPartial({sdk:Pe.JS,protocol:_t,version:Nt})}(),i);return new Promise(((t,s)=>{h.debug(`connecting to ${e+n}`),this.ws=void 0;const a=new WebSocket(e+n);a.binaryType="arraybuffer",a.onerror=async t=>{if(this.ws)this.handleWSError(t);else try{const t=await fetch(`http${e.substring(2)}/validate${n}`);if(t.ok)s(new ConnectionError("Internal error"));else{const e=await t.text();s(new ConnectionError(e))}}catch(e){s(new ConnectionError("server was not reachable"))}},a.onopen=()=>{this.ws=a,i.reconnect&&(this.isConnected=!0,t())},a.onmessage=async e=>{let i;if("string"==typeof e.data){const t=JSON.parse(e.data);i=He.fromJSON(t)}else{if(!(e.data instanceof ArrayBuffer))return void h.error("could not decode websocket message: "+typeof e.data);i=He.decode(new Uint8Array(e.data))}this.isConnected?(this.signalLatency&&await sleep(this.signalLatency),this.handleSignalResponse(i)):i.join?(this.isConnected=!0,t(i.join)):s(new ConnectionError("did not receive join response"))},a.onclose=e=>{this.isConnected&&this.ws===a&&(h.debug(`websocket connection closed: ${e.reason}`),this.isConnected=!1,this.onClose&&this.onClose(e.reason),this.ws===a&&(this.ws=void 0))}}))}close(){this.isConnected=!1,this.ws&&(this.ws.onclose=null),this.ws?.close(),this.ws=void 0}sendOffer(e){h.debug("sending offer",e),this.sendRequest({offer:toProtoSessionDescription(e)})}sendAnswer(e){h.debug("sending answer"),this.sendRequest({answer:toProtoSessionDescription(e)})}sendIceCandidate(e,t){h.trace("sending ice candidate",e),this.sendRequest({trickle:{candidateInit:JSON.stringify(e),target:t}})}sendMuteTrack(e,t){this.sendRequest({mute:{sid:e,muted:t}})}sendAddTrack(e){this.sendRequest({addTrack:ze.fromPartial(e)})}sendUpdateTrackSettings(e){this.sendRequest({trackSetting:e})}sendUpdateSubscription(e){this.sendRequest({subscription:e})}sendSyncState(e){this.sendRequest({syncState:e})}sendUpdateVideoLayers(e,t){this.sendRequest({updateLayers:{trackSid:e,layers:t}})}sendUpdateSubscriptionPermissions(e,t){this.sendRequest({subscriptionPermission:{allParticipants:e,trackPermissions:t}})}sendSimulateScenario(e){this.sendRequest({simulate:e})}sendLeave(){this.sendRequest(Qe.fromPartial({leave:{}}))}async sendRequest(e,t=!1){const i=!t&&!function canPassThroughQueue(e){const t=void 0!==Object.keys(e).find((e=>oi.includes(e)));return h.trace("request allowed to bypass queue:",{canPass:t,req:e}),t}(e);if(!i||!this.isReconnecting&&this.requestQueue.isEmpty())if(this.signalLatency&&await sleep(this.signalLatency),this.ws)try{this.useJSON?this.ws.send(JSON.stringify(Qe.toJSON(e))):this.ws.send(Qe.encode(e).finish())}catch(e){h.error("error sending signal message",{error:e})}else h.error("cannot send signal request before connected");else this.requestQueue.enqueue((()=>this.sendRequest(e,!0)))}handleSignalResponse(e){if(e.answer){const t=fromProtoSessionDescription(e.answer);this.onAnswer&&this.onAnswer(t)}else if(e.offer){const t=fromProtoSessionDescription(e.offer);this.onOffer&&this.onOffer(t)}else if(e.trickle){const t=JSON.parse(e.trickle.candidateInit);this.onTrickle&&this.onTrickle(t,e.trickle.target)}else e.update?this.onParticipantUpdate&&this.onParticipantUpdate(e.update.participants):e.trackPublished?this.onLocalTrackPublished&&this.onLocalTrackPublished(e.trackPublished):e.speakersChanged?this.onSpeakersChanged&&this.onSpeakersChanged(e.speakersChanged.speakers):e.leave?this.onLeave&&this.onLeave(e.leave):e.mute?this.onRemoteMuteChanged&&this.onRemoteMuteChanged(e.mute.sid,e.mute.muted):e.roomUpdate?this.onRoomUpdate&&this.onRoomUpdate(e.roomUpdate.room):e.connectionQuality?this.onConnectionQuality&&this.onConnectionQuality(e.connectionQuality):e.streamStateUpdate?this.onStreamStateUpdate&&this.onStreamStateUpdate(e.streamStateUpdate):e.subscribedQualityUpdate?this.onSubscribedQualityUpdate&&this.onSubscribedQualityUpdate(e.subscribedQualityUpdate):e.subscriptionPermissionUpdate?this.onSubscriptionPermissionUpdate&&this.onSubscriptionPermissionUpdate(e.subscriptionPermissionUpdate):e.refreshToken?this.onTokenRefresh&&this.onTokenRefresh(e.refreshToken):e.trackUnpublished?this.onLocalTrackUnpublished&&this.onLocalTrackUnpublished(e.trackUnpublished):h.debug("unsupported message",e)}setReconnected(){this.isReconnecting=!1,this.requestQueue.run()}handleWSError(e){h.error("websocket error",e)}}function fromProtoSessionDescription(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 toProtoSessionDescription(e){return{sdp:e.sdp,type:e.type}}class PCTransport{constructor(e){this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate=!1,this.negotiate=r((()=>{this.createAndSendOffer()}),100),this.pc=new RTCPeerConnection(e)}get isICEConnected(){return"connected"===this.pc.iceConnectionState||"completed"===this.pc.iceConnectionState}async addIceCandidate(e){if(this.pc.remoteDescription&&!this.restartingIce)return this.pc.addIceCandidate(e);this.pendingCandidates.push(e)}async setRemoteDescription(e){await this.pc.setRemoteDescription(e),this.pendingCandidates.forEach((e=>{this.pc.addIceCandidate(e)})),this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate&&(this.renegotiate=!1,this.createAndSendOffer())}async createAndSendOffer(e){if(void 0===this.onOffer)return;if(e?.iceRestart&&(h.debug("restarting ICE"),this.restartingIce=!0),"have-local-offer"===this.pc.signalingState){const t=this.pc.remoteDescription;if(!e?.iceRestart||!t)return void(this.renegotiate=!0);await this.pc.setRemoteDescription(t)}else if("closed"===this.pc.signalingState)return void h.warn("could not createOffer with closed peer connection");h.debug("starting to negotiate");const t=await this.pc.createOffer(e);await this.pc.setLocalDescription(t),this.onOffer(t)}close(){this.pc.close()}}const ci="_lossy",di="_reliable",ui=15e3;class RTCEngine extends It.exports.EventEmitter{constructor(){super(),this.rtcConfig={},this.subscriberPrimary=!1,this.pcConnected=!1,this.isClosed=!0,this.pendingTrackResolvers={},this.hasPublished=!1,this.reconnectAttempts=0,this.reconnectStart=0,this.fullReconnectOnNext=!1,this.handleDataChannel=async({channel:e})=>{if(e){if(e.label===di)this.reliableDCSub=e;else{if(e.label!==ci)return;this.lossyDCSub=e}h.debug(`on data channel ${e.id}, ${e.label}`),e.onmessage=this.handleDataMessage}},this.handleDataMessage=async e=>{let t;if(e.data instanceof ArrayBuffer)t=e.data;else{if(!(e.data instanceof Blob))return void h.error("unsupported data type",e.data);t=await e.data.arrayBuffer()}const i=Ie.decode(new Uint8Array(t));i.speaker?this.emit(Pt.ActiveSpeakersUpdate,i.speaker.speakers):i.user&&this.emit(Pt.DataPacketReceived,i.user,i.kind)},this.handleDataError=e=>{const t=0===e.currentTarget.maxRetransmits?"lossy":"reliable";if(e instanceof ErrorEvent){const{error:i}=e.error;h.error(`DataChannel error on ${t}: ${e.message}`,i)}else h.error(`Unknown DataChannel Error on ${t}`,e)},this.handleDisconnect=e=>{if(this.isClosed)return;h.debug(`${e} disconnected`),0===this.reconnectAttempts&&(this.reconnectStart=Date.now());const t=this.reconnectAttempts*this.reconnectAttempts*300;setTimeout((async()=>{if(!this.isClosed){(isFireFox()||this.clientConfiguration?.resumeConnection===Te.DISABLED)&&(this.fullReconnectOnNext=!0);try{this.fullReconnectOnNext?await this.restartConnection():await this.resumeConnection(),this.reconnectAttempts=0,this.fullReconnectOnNext=!1}catch(e){this.reconnectAttempts+=1;let t=!0;e instanceof UnexpectedConnectionState?(h.debug("received unrecoverable error",{error:e}),t=!1):e instanceof SignalReconnectError||(this.fullReconnectOnNext=!0);const i=Date.now()-this.reconnectStart;(this.reconnectAttempts>=10||i>6e4)&&(t=!1),t?this.handleDisconnect("reconnect"):(h.info(`could not recover connection after 10 attempts, ${i}ms. giving up`),this.emit(Pt.Disconnected),this.close())}}}),t)},this.client=new SignalClient}async join(e,t,i){this.url=e,this.token=t,this.signalOpts=i;const n=await this.client.join(e,t,i);return this.isClosed=!1,this.subscriberPrimary=n.subscriberPrimary,this.publisher||this.configure(n),this.subscriberPrimary||this.negotiate(),this.clientConfiguration=n.clientConfiguration,n}close(){this.isClosed=!0,this.removeAllListeners(),this.publisher&&"closed"!==this.publisher.pc.signalingState&&(this.publisher.pc.getSenders().forEach((e=>{try{this.publisher?.pc.removeTrack&&this.publisher?.pc.removeTrack(e)}catch(e){h.warn("could not removeTrack",{error:e})}})),this.publisher.close(),this.publisher=void 0),this.subscriber&&(this.subscriber.close(),this.subscriber=void 0),this.client.close()}addTrack(e){if(this.pendingTrackResolvers[e.cid])throw new TrackInvalidError("a track with the same ID has already been published");return new Promise((t=>{this.pendingTrackResolvers[e.cid]=t,this.client.sendAddTrack(e)}))}updateMuteStatus(e,t){this.client.sendMuteTrack(e,t)}get dataSubscriberReadyState(){return this.reliableDCSub?.readyState}get connectedServerAddress(){return this.connectedServerAddr}configure(e){if(this.publisher||this.subscriber)return;if(e.iceServers&&!this.rtcConfig.iceServers){const t=[];e.iceServers.forEach((e=>{const i={urls:e.urls};e.username&&(i.username=e.username),e.credential&&(i.credential=e.credential),t.push(i)})),this.rtcConfig.iceServers=t}this.rtcConfig.sdpSemantics="unified-plan",this.rtcConfig.continualGatheringPolicy="gather_continually",this.publisher=new PCTransport(this.rtcConfig),this.subscriber=new PCTransport(this.rtcConfig),this.emit(Pt.TransportsCreated,this.publisher,this.subscriber),this.publisher.pc.onicecandidate=e=>{e.candidate&&(h.trace("adding ICE candidate for peer",e.candidate),this.client.sendIceCandidate(e.candidate,We.PUBLISHER))},this.subscriber.pc.onicecandidate=e=>{e.candidate&&this.client.sendIceCandidate(e.candidate,We.SUBSCRIBER)},this.publisher.onOffer=e=>{this.client.sendOffer(e)};let t=this.publisher.pc;e.subscriberPrimary&&(t=this.subscriber.pc,this.subscriber.pc.ondatachannel=this.handleDataChannel),this.primaryPC=t,t.onconnectionstatechange=async()=>{if("connected"===t.connectionState){h.trace("pc connected");try{this.connectedServerAddr=await async function getConnectedAddress(e){let t="";const i=new Map,n=new Map;if((await e.getStats()).forEach((e=>{switch(e.type){case"transport":t=e.selectedCandidatePairId;break;case"candidate-pair":""===t&&e.selected&&(t=e.id),i.set(e.id,e);break;case"remote-candidate":n.set(e.id,`${e.address}:${e.port}`)}})),""===t)return;const s=i.get(t)?.remoteCandidateId;if(void 0===s)return;return n.get(s)}(t)}catch(e){h.warn("could not get connected server address",{error:e})}this.pcConnected||(this.pcConnected=!0,this.emit(Pt.Connected))}else"failed"===t.connectionState&&(h.trace("pc disconnected"),this.pcConnected&&(this.pcConnected=!1,this.handleDisconnect("peerconnection")))},isWeb()?this.subscriber.pc.ontrack=e=>{this.emit(Pt.MediaTrackAdded,e.track,e.streams[0],e.receiver)}:this.subscriber.pc.onaddstream=e=>{const t=e.stream.getTracks()[0];this.emit(Pt.MediaTrackAdded,t,e.stream)},this.lossyDC=this.publisher.pc.createDataChannel(ci,{ordered:!0,maxRetransmits:0}),this.reliableDC=this.publisher.pc.createDataChannel(di,{ordered:!0}),this.lossyDC.onmessage=this.handleDataMessage,this.reliableDC.onmessage=this.handleDataMessage,this.lossyDC.onerror=this.handleDataError,this.reliableDC.onerror=this.handleDataError,this.client.onAnswer=async e=>{this.publisher&&(h.debug("received server answer",{RTCSdpType:e.type,signalingState:this.publisher.pc.signalingState}),await this.publisher.setRemoteDescription(e))},this.client.onTrickle=(e,t)=>{this.publisher&&this.subscriber&&(h.trace("got ICE candidate from peer",{candidate:e,target:t}),t===We.PUBLISHER?this.publisher.addIceCandidate(e):this.subscriber.addIceCandidate(e))},this.client.onOffer=async e=>{if(!this.subscriber)return;h.debug("received server offer",{RTCSdpType:e.type,signalingState:this.subscriber.pc.signalingState}),await this.subscriber.setRemoteDescription(e);const t=await this.subscriber.pc.createAnswer();await this.subscriber.pc.setLocalDescription(t),this.client.sendAnswer(t)},this.client.onLocalTrackPublished=e=>{h.debug("received trackPublishedResponse",e);const t=this.pendingTrackResolvers[e.cid];t?(delete this.pendingTrackResolvers[e.cid],t(e.track)):h.error(`missing track resolver for ${e.cid}`)},this.client.onTokenRefresh=e=>{this.token=e},this.client.onClose=()=>{this.handleDisconnect("signal")},this.client.onLeave=e=>{e?.canReconnect?(this.fullReconnectOnNext=!0,this.primaryPC=void 0):(this.emit(Pt.Disconnected),this.close())}}async restartConnection(){if(!this.url||!this.token)throw new UnexpectedConnectionState("could not reconnect, url or token not saved");let e;h.info(`reconnecting, attempt: ${this.reconnectAttempts}`),0===this.reconnectAttempts&&this.emit(Pt.Restarting),this.primaryPC=void 0,this.publisher?.close(),this.publisher=void 0,this.subscriber?.close(),this.subscriber=void 0;try{e=await this.join(this.url,this.token,this.signalOpts)}catch(e){throw new SignalReconnectError}await this.waitForPCConnected(),this.client.setReconnected(),this.emit(Pt.Restarted,e)}async resumeConnection(){if(!this.url||!this.token)throw new UnexpectedConnectionState("could not reconnect, url or token not saved");if(!this.publisher||!this.subscriber)throw new UnexpectedConnectionState("publisher and subscriber connections unset");h.info(`resuming signal connection, attempt ${this.reconnectAttempts}`),0===this.reconnectAttempts&&this.emit(Pt.Resuming);try{await this.client.reconnect(this.url,this.token)}catch(e){throw new SignalReconnectError}this.emit(Pt.SignalResumed),this.subscriber.restartingIce=!0,this.hasPublished&&await this.publisher.createAndSendOffer({iceRestart:!0}),await this.waitForPCConnected(),this.client.setReconnected(),this.emit(Pt.Resumed)}async waitForPCConnected(){const e=(new Date).getTime();let t=e;for(this.pcConnected=!1;t-e1e3&&"connected"===this.primaryPC?.connectionState&&(this.pcConnected=!0),this.pcConnected)return;await sleep(100),t=(new Date).getTime()}throw new ConnectionError("could not establish PC connection")}async sendDataPacket(e,t){const i=Ie.encode(e).finish();await this.ensurePublisherConnected(t),t===Ce.LOSSY&&this.lossyDC?this.lossyDC.send(i):t===Ce.RELIABLE&&this.reliableDC&&this.reliableDC.send(i)}async ensurePublisherConnected(e){if(!this.subscriberPrimary)return;if(!this.publisher)throw new ConnectionError("publisher connection not set");this.publisher.isICEConnected||"checking"===this.publisher.pc.iceConnectionState||this.negotiate();if("open"===this.dataChannelForKind(e)?.readyState)return;const t=(new Date).getTime()+ui;for(;(new Date).getTime(){if(this.state===mi.Disconnected){this.createEngine(),this.acquireAudioContext(),i?.rtcConfig&&(this.engine.rtcConfig=i.rtcConfig),this.connOptions=i;try{const n=await this.engine.join(e,t,{autoSubscribe:i?.autoSubscribe,publishOnly:i?.publishOnly,adaptiveStream:"object"==typeof this.options?.adaptiveStream||this.options?.adaptiveStream});if(h.debug(`connected to Livekit Server version: ${n.serverVersion}, region: ${n.serverRegion}`),!n.serverVersion)throw new UnsupportedServer("unknown server version");"0.15.1"===n.serverVersion&&this.options.dynacast&&(h.debug("disabling dynacast due to server version"),this.options.dynacast=!1),this.state=mi.Connected;const s=n.participant;this.localParticipant.sid=s.sid,this.localParticipant.identity=s.identity,this.localParticipant.updateInfo(s),this.localParticipant.on(Ct.MetadataChanged,(e=>{this.emit(wt.MetadataChanged,e,this.localParticipant)})).on(Ct.ParticipantMetadataChanged,(e=>{this.emit(wt.ParticipantMetadataChanged,e,this.localParticipant)})).on(Ct.TrackMuted,(e=>{this.emit(wt.TrackMuted,e,this.localParticipant)})).on(Ct.TrackUnmuted,(e=>{this.emit(wt.TrackUnmuted,e,this.localParticipant)})).on(Ct.LocalTrackPublished,(e=>{this.emit(wt.LocalTrackPublished,e,this.localParticipant)})).on(Ct.LocalTrackUnpublished,(e=>{this.emit(wt.LocalTrackUnpublished,e,this.localParticipant)})).on(Ct.ConnectionQualityChanged,(e=>{this.emit(wt.ConnectionQualityChanged,e,this.localParticipant)})).on(Ct.MediaDevicesError,(e=>{this.emit(wt.MediaDevicesError,e)})).on(Ct.ParticipantPermissionsChanged,(e=>{this.emit(wt.ParticipantPermissionsChanged,e,this.localParticipant)})),n.otherParticipants.forEach((e=>{this.getOrCreateParticipant(e.sid,e)})),this.name=n.room.name,this.sid=n.room.sid,this.metadata=n.room.metadata,this.emit(wt.StateChanged,this.state)}catch(e){throw this.engine.close(),e}return new Promise(((e,t)=>{const i=setTimeout((()=>{this.engine.close(),t(new ConnectionError("could not connect after timeout"))}),ui);this.engine.once(Pt.Connected,(()=>{clearTimeout(i),isWeb()&&(window.addEventListener("beforeunload",this.onBeforeUnload),navigator.mediaDevices?.addEventListener("devicechange",this.handleDeviceChange)),e(this)}))}))}h.warn(`already connected to room ${this.name}`)},this.disconnect=(e=!0)=>{this.engine&&(this.engine.client.sendLeave(),this.engine.close()),this.handleDisconnect(e),this.engine=void 0},this.onBeforeUnload=()=>{this.disconnect()},this.handleRestarting=()=>{this.state=mi.Reconnecting,this.emit(wt.Reconnecting),this.emit(wt.StateChanged,this.state);for(const e of this.participants.values())this.handleParticipantDisconnected(e.sid,e)},this.handleRestarted=async e=>{h.debug(`reconnected to server region ${e.serverRegion}`),this.state=mi.Connected,this.emit(wt.Reconnected),this.emit(wt.StateChanged,this.state),e.participant&&(this.localParticipant.sid=e.participant.sid,this.handleParticipantUpdates([e.participant])),this.handleParticipantUpdates(e.otherParticipants);const t=[];this.localParticipant.tracks.forEach((e=>{e.track&&t.push(e)})),await Promise.all(t.map((async e=>{const t=e.track;this.localParticipant.unpublishTrack(t,!1),this.localParticipant.publishTrack(t,e.options)})))},this.handleParticipantUpdates=e=>{e.forEach((e=>{if(e.sid===this.localParticipant.sid||e.identity===this.localParticipant.identity)return void this.localParticipant.updateInfo(e);let t=this.participants.get(e.sid);const i=!t;t=this.getOrCreateParticipant(e.sid,e),e.state===we.DISCONNECTED?this.handleParticipantDisconnected(e.sid,t):i?this.emit(wt.ParticipantConnected,t):t.updateInfo(e)}))},this.handleActiveSpeakersUpdate=e=>{const t=[],i={};e.forEach((e=>{if(i[e.sid]=!0,e.sid===this.localParticipant.sid)this.localParticipant.audioLevel=e.level,this.localParticipant.setIsSpeaking(!0),t.push(this.localParticipant);else{const i=this.participants.get(e.sid);i&&(i.audioLevel=e.level,i.setIsSpeaking(!0),t.push(i))}})),i[this.localParticipant.sid]||(this.localParticipant.audioLevel=0,this.localParticipant.setIsSpeaking(!1)),this.participants.forEach((e=>{i[e.sid]||(e.audioLevel=0,e.setIsSpeaking(!1))})),this.activeSpeakers=t,this.emit(wt.ActiveSpeakersChanged,t)},this.handleSpeakersChanged=e=>{const t=new Map;this.activeSpeakers.forEach((e=>{t.set(e.sid,e)})),e.forEach((e=>{let i=this.participants.get(e.sid);e.sid===this.localParticipant.sid&&(i=this.localParticipant),i&&(i.audioLevel=e.level,i.setIsSpeaking(e.active),e.active?t.set(e.sid,i):t.delete(e.sid))}));const i=Array.from(t.values());i.sort(((e,t)=>t.audioLevel-e.audioLevel)),this.activeSpeakers=i,this.emit(wt.ActiveSpeakersChanged,i)},this.handleStreamStateUpdate=e=>{e.streamStates.forEach((e=>{const t=this.participants.get(e.participantSid);if(!t)return;const i=t.getTrackPublication(e.trackSid);i&&i.track&&(i.track.streamState=Track.streamStateFromProto(e.state),t.emit(Ct.TrackStreamStateChanged,i,i.track.streamState),this.emit(Ct.TrackStreamStateChanged,i,i.track.streamState,t))}))},this.handleSubscriptionPermissionUpdate=e=>{const t=this.participants.get(e.participantSid);if(!t)return;const i=t.getTrackPublication(e.trackSid);i&&(i._allowed=e.allowed,t.emit(Ct.TrackSubscriptionPermissionChanged,i,i.subscriptionStatus),this.emit(Ct.TrackSubscriptionPermissionChanged,i,i.subscriptionStatus,t))},this.handleDataPacket=(e,t)=>{const i=this.participants.get(e.participantSid);this.emit(wt.DataReceived,e.payload,i,t),i?.emit(Ct.DataReceived,e.payload,t)},this.handleAudioPlaybackStarted=()=>{this.canPlaybackAudio||(this.audioEnabled=!0,this.emit(wt.AudioPlaybackStatusChanged,!0))},this.handleAudioPlaybackFailed=e=>{h.warn("could not playback audio",e),this.canPlaybackAudio&&(this.audioEnabled=!1,this.emit(wt.AudioPlaybackStatusChanged,!1))},this.handleDeviceChange=async()=>{this.emit(wt.MediaDevicesChanged)},this.handleRoomUpdate=e=>{this.metadata=e.metadata,this.emit(wt.RoomMetadataChanged,e.metadata)},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.participants=new Map,this.options=e||{},this.options?.publishDefaults?.videoCodec){case"av1":case"vp9":this.options.publishDefaults.simulcast=void 0}this.options.audioCaptureDefaults={...hi,...e?.audioCaptureDefaults},this.options.videoCaptureDefaults={...pi,...e?.videoCaptureDefaults},this.options.publishDefaults={...li,...e?.publishDefaults},this.createEngine(),this.localParticipant=new LocalParticipant("","",this.engine,this.options)}createEngine(){this.engine||(this.engine=new RTCEngine,this.engine.client.signalLatency=this.options.expSignalLatency,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.on(Pt.MediaTrackAdded,((e,t,i)=>{this.onTrackAdded(e,t,i)})).on(Pt.Disconnected,(()=>{this.handleDisconnect()})).on(Pt.ActiveSpeakersUpdate,this.handleActiveSpeakersUpdate).on(Pt.DataPacketReceived,this.handleDataPacket).on(Pt.Resuming,(()=>{this.state=mi.Reconnecting,this.emit(wt.Reconnecting),this.emit(wt.StateChanged,this.state)})).on(Pt.Resumed,(()=>{this.state=mi.Connected,this.emit(wt.Reconnected),this.emit(wt.StateChanged,this.state),this.updateSubscriptions()})).on(Pt.SignalResumed,(()=>{this.state===mi.Reconnecting&&this.sendSyncState()})).on(Pt.Restarting,this.handleRestarting).on(Pt.Restarted,this.handleRestarted))}static getLocalDevices(e,t=!0){return DeviceManager.getInstance().getDevices(e,t)}getParticipantByIdentity(e){for(const[,t]of this.participants)if(t.identity===e)return t;if(this.localParticipant.identity===e)return this.localParticipant}simulateScenario(e){let t;switch(e){case"speaker":t=yt.fromPartial({speakerUpdate:3});break;case"node-failure":t=yt.fromPartial({nodeFailure:!0});break;case"server-leave":t=yt.fromPartial({serverLeave:!0});break;case"migration":t=yt.fromPartial({migration:!0})}t&&this.engine.client.sendSimulateScenario(t)}async startAudio(){this.acquireAudioContext();const e=[];this.participants.forEach((t=>{t.audioTracks.forEach((t=>{t.track&&t.track.attachedElements.forEach((t=>{e.push(t)}))}))}));try{await Promise.all(e.map((e=>e.play()))),this.handleAudioPlaybackStarted()}catch(e){throw this.handleAudioPlaybackFailed(e),e}}get canPlaybackAudio(){return this.audioEnabled}async switchActiveDevice(e,t){if("audioinput"===e){const e=Array.from(this.localParticipant.audioTracks.values()).filter((e=>e.source===Track.Source.Microphone));await Promise.all(e.map((e=>e.audioTrack?.setDeviceId(t)))),this.options.audioCaptureDefaults.deviceId=t}else if("videoinput"===e){const e=Array.from(this.localParticipant.videoTracks.values()).filter((e=>e.source===Track.Source.Camera));await Promise.all(e.map((e=>e.videoTrack?.setDeviceId(t)))),this.options.videoCaptureDefaults.deviceId=t}else if("audiooutput"===e){const e=[];this.participants.forEach((t=>{t.audioTracks.forEach((t=>{t.isSubscribed&&t.track&&t.track.attachedElements.forEach((t=>{e.push(t)}))}))})),await Promise.all(e.map((async e=>{"setSinkId"in e&&await e.setSinkId(t)})))}}onTrackAdded(e,t,i){const n=function unpackStreamId(e){const t=e.split("|");return t.length>1?[t[0],e.substr(t[0].length+1)]:[e,""]}(t.id),s=n[0];let a=n[1];a&&""!==a||(a=e.id);const o=this.getOrCreateParticipant(s);let c;this.options.adaptiveStream&&(c="object"==typeof this.options.adaptiveStream?this.options.adaptiveStream:{}),o.addSubscribedMediaTrack(e,a,t,i,c)}handleDisconnect(e=!0){this.state!==mi.Disconnected&&(this.participants.forEach((e=>{e.tracks.forEach((t=>{e.unpublishTrack(t.trackSid)}))})),this.localParticipant.tracks.forEach((t=>{t.track&&this.localParticipant.unpublishTrack(t.track),e&&(t.track?.detach(),t.track?.stop())})),this.participants.clear(),this.activeSpeakers=[],this.audioContext&&(this.audioContext.close(),this.audioContext=void 0),isWeb()&&(window.removeEventListener("beforeunload",this.onBeforeUnload),navigator.mediaDevices?.removeEventListener("devicechange",this.handleDeviceChange)),this.state=mi.Disconnected,this.emit(wt.Disconnected),this.emit(wt.StateChanged,this.state))}handleParticipantDisconnected(e,t){this.participants.delete(e),t&&(t.tracks.forEach((e=>{t.unpublishTrack(e.trackSid)})),this.emit(wt.ParticipantDisconnected,t))}acquireAudioContext(){this.audioContext&&this.audioContext.close();const e=getNewAudioContext();e&&(this.audioContext=e)}createParticipant(e,t){let i;return i=t?RemoteParticipant.fromParticipantInfo(this.engine.client,t):new RemoteParticipant(this.engine.client,e,""),i}getOrCreateParticipant(e,t){if(this.participants.has(e))return this.participants.get(e);const i=this.createParticipant(e,t);return this.participants.set(e,i),i.on(Ct.TrackPublished,(e=>{this.emit(wt.TrackPublished,e,i)})).on(Ct.TrackSubscribed,((e,t)=>{e.kind===Track.Kind.Audio&&(e.on(Et.AudioPlaybackStarted,this.handleAudioPlaybackStarted),e.on(Et.AudioPlaybackFailed,this.handleAudioPlaybackFailed)),this.emit(wt.TrackSubscribed,e,t,i)})).on(Ct.TrackUnpublished,(e=>{this.emit(wt.TrackUnpublished,e,i)})).on(Ct.TrackUnsubscribed,((e,t)=>{this.emit(wt.TrackUnsubscribed,e,t,i)})).on(Ct.TrackSubscriptionFailed,(e=>{this.emit(wt.TrackSubscriptionFailed,e,i)})).on(Ct.TrackMuted,(e=>{this.emit(wt.TrackMuted,e,i)})).on(Ct.TrackUnmuted,(e=>{this.emit(wt.TrackUnmuted,e,i)})).on(Ct.MetadataChanged,(e=>{this.emit(wt.MetadataChanged,e,i)})).on(Ct.ParticipantMetadataChanged,(e=>{this.emit(wt.ParticipantMetadataChanged,e,i)})).on(Ct.ConnectionQualityChanged,(e=>{this.emit(wt.ConnectionQualityChanged,e,i)})).on(Ct.ParticipantPermissionsChanged,(e=>{this.emit(wt.ParticipantPermissionsChanged,e,i)})),i}sendSyncState(){if(void 0===this.engine.subscriber||null===this.engine.subscriber.pc.localDescription)return;const e=this.engine.subscriber.pc.localDescription,t=this.connOptions?.autoSubscribe||!1,i=new Array;this.participants.forEach((e=>{e.tracks.forEach((e=>{e.isSubscribed!==t&&i.push(e.trackSid)}))})),this.engine.client.sendSyncState({answer:toProtoSessionDescription({sdp:e.sdp,type:e.type}),subscription:{trackSids:i,subscribe:!t,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 RemoteTrackPublication&&t.emitTrackUpdate()}emit(e,...t){return h.debug("room event",{event:e,args:t}),super.emit(e,...t)}}async function connect(e,t,i){i??={},void 0===i.adaptiveStream&&(i.adaptiveStream=!0===i.autoManageVideo?{}:void 0),setLogLevel(i.logLevel??c.warn);const n=i.rtcConfig??{};i.iceServers&&(n.iceServers=i.iceServers);const s=new Room(i);await s.connect(e,t,i);const a=i.audio??!1,o=i.video??!1;return(a||o)&&setTimeout((async()=>{let e;if(a&&o)try{await s.localParticipant.enableCameraAndMicrophone()}catch(t){const i=Tt.getFailure(t);if(h.warn("received error while creating media",{error:i}),t instanceof Error&&h.warn(t.message),i===Tt.NotFound||i===Tt.DeviceInUse)try{await s.localParticipant.setMicrophoneEnabled(!0)}catch(t){e=t}else e=t}else if(a)try{await s.localParticipant.setMicrophoneEnabled(!0)}catch(t){e=t}else if(o)try{await s.localParticipant.setCameraEnabled(!0)}catch(t){e=t}e&&(s.emit(wt.MediaDevicesError,e),h.error("could not create media",e))})),s}async function createLocalTracks(e){e??={},e.audio??=!0,e.video??=!0;const t=constraintsForOptions(mergeDefaultOptions(e,hi,pi)),i=await navigator.mediaDevices.getUserMedia(t);return i.getTracks().map((n=>{const s="audio"===n.kind;let a;s?e.audio:e.video;const o=s?t.audio:t.video;"boolean"!=typeof o&&(a=o);const c=mediaTrackToLocalTrack(n,a);return c.kind===Track.Kind.Video?c.source=Track.Source.Camera:c.kind===Track.Kind.Audio&&(c.source=Track.Source.Microphone),c.mediaStream=i,c}))}async function createLocalVideoTrack(e){return(await createLocalTracks({audio:!1,video:e}))[0]}async function createLocalAudioTrack(e){return(await createLocalTracks({audio:e,video:!1}))[0]}async function createLocalScreenTracks(e){void 0===e&&(e={}),void 0===e.resolution&&(e.resolution=Vt.fhd.resolution);let t=!0;e.resolution&&(t={width:e.resolution.width,height:e.resolution.height});const i=await navigator.mediaDevices.getDisplayMedia({audio:e.audio??!1,video:t}),n=i.getVideoTracks();if(0===n.length)throw new TrackInvalidError("no video track found");const s=new LocalVideoTrack(n[0]);s.source=Track.Source.ScreenShare;const a=[s];if(i.getAudioTracks().length>0){const e=new LocalAudioTrack(i.getAudioTracks()[0]);e.source=Track.Source.ScreenShareAudio,a.push(e)}return a}n=__webpack_require__.O(n),window.livekit=n})(); \ No newline at end of file +(()=>{"use strict";var e,t={},i={};function __webpack_require__(e){var n=i[e];if(void 0!==n)return n.exports;var s=i[e]={exports:{}};return t[e](s,s.exports,__webpack_require__),s.exports}__webpack_require__.m=t,e=[],__webpack_require__.O=(t,i,n,s)=>{if(!i){var a=1/0;for(l=0;l=s)&&Object.keys(__webpack_require__.O).every((e=>__webpack_require__.O[e](i[c])))?i.splice(c--,1):(o=!1,s0&&e[l-1][2]>s;l--)e[l]=e[l-1];e[l]=[i,n,s]},__webpack_require__.d=(e,t)=>{for(var i in t)__webpack_require__.o(t,i)&&!__webpack_require__.o(e,i)&&Object.defineProperty(e,i,{enumerable:!0,get:t[i]})},__webpack_require__.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),__webpack_require__.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},(()=>{var e={588:0};__webpack_require__.O.j=t=>0===e[t];var webpackJsonpCallback=(t,i)=>{var n,s,[a,o,c]=i,u=0;if(a.some((t=>0!==e[t]))){for(n in o)__webpack_require__.o(o,n)&&(__webpack_require__.m[n]=o[n]);if(c)var l=c(__webpack_require__)}for(t&&t(i);ujt,ConnectionError:()=>ConnectionError,ConnectionQuality:()=>Gt,ConnectionState:()=>gi,DataPacket_Kind:()=>Ce,EngineEvent:()=>Pt,LivekitError:()=>LivekitError,LocalAudioTrack:()=>LocalAudioTrack,LocalParticipant:()=>LocalParticipant,LocalTrack:()=>LocalTrack,LocalTrackPublication:()=>LocalTrackPublication,LocalVideoTrack:()=>LocalVideoTrack,LogLevel:()=>c,MediaDeviceFailure:()=>Tt,Participant:()=>Participant,ParticipantEvent:()=>Ct,PublishDataError:()=>PublishDataError,RemoteAudioTrack:()=>RemoteAudioTrack,RemoteParticipant:()=>RemoteParticipant,RemoteTrack:()=>RemoteTrack,RemoteTrackPublication:()=>RemoteTrackPublication,RemoteVideoTrack:()=>RemoteVideoTrack,Room:()=>Room,RoomEvent:()=>wt,RoomState:()=>Si,ScreenSharePresets:()=>$t,Track:()=>Track,TrackEvent:()=>Et,TrackInvalidError:()=>TrackInvalidError,TrackPublication:()=>TrackPublication,UnexpectedConnectionState:()=>UnexpectedConnectionState,UnsupportedServer:()=>UnsupportedServer,VideoPreset:()=>VideoPreset,VideoPresets:()=>qt,VideoPresets43:()=>Wt,VideoQuality:()=>ke,attachToElement:()=>attachToElement,createLocalAudioTrack:()=>createLocalAudioTrack,createLocalScreenTracks:()=>createLocalScreenTracks,createLocalTracks:()=>createLocalTracks,createLocalVideoTrack:()=>createLocalVideoTrack,detachTrack:()=>detachTrack,protocolVersion:()=>_t,setLogExtension:()=>setLogExtension,setLogLevel:()=>setLogLevel,version:()=>Nt});var s,a,o,c,u="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},l={exports:{}};a=u,o=function(){var noop=function(){},e="undefined",t=typeof window!==e&&typeof window.navigator!==e&&/Trident\/|MSIE /.test(window.navigator.userAgent),i=["trace","debug","info","warn","error"];function bindMethod(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 traceForIE(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function realMethod(i){return"debug"===i&&(i="log"),typeof console!==e&&("trace"===i&&t?traceForIE:void 0!==console[i]?bindMethod(console,i):void 0!==console.log?bindMethod(console,"log"):noop)}function replaceLoggingMethods(e,t){for(var n=0;n=0&&n<=o.levels.SILENT))throw"log.setLevel() called with invalid level: "+n;if(a=n,!1!==s&&function persistLevelIfPossible(t){var n=(i[t]||"silent").toUpperCase();if(typeof window!==e&&c){try{return void(window.localStorage[c]=n)}catch(e){}try{window.document.cookie=encodeURIComponent(c)+"="+n+";"}catch(e){}}}(n),replaceLoggingMethods.call(o,n,t),typeof console===e&&n{const a=t(i,n,s),o=h.getLevel(),u=n>=o&&n{i?a(t,i):a(t),u&&e(n,t,i)}},h.setLevel(h.getLevel())}h.setLevel(c.info);var p=Long,m=null;try{m=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 Long(e,t,i){this.low=0|e,this.high=0|t,this.unsigned=!!i}function isLong(e){return!0===(e&&e.__isLong__)}Long.prototype.__isLong__,Object.defineProperty(Long.prototype,"__isLong__",{value:!0}),Long.isLong=isLong;var v={},g={};function fromInt(e,t){var i,n,s;return t?(s=0<=(e>>>=0)&&e<256)&&(n=g[e])?n:(i=fromBits(e,(0|e)<0?-1:0,!0),s&&(g[e]=i),i):(s=-128<=(e|=0)&&e<128)&&(n=v[e])?n:(i=fromBits(e,e<0?-1:0,!1),s&&(v[e]=i),i)}function fromNumber(e,t){if(isNaN(e))return t?C:w;if(t){if(e<0)return C;if(e>=k)return N}else{if(e<=-y)return _;if(e+1>=y)return O}return e<0?fromNumber(-e,t).neg():fromBits(e%b|0,e/b|0,t)}function fromBits(e,t,i){return new Long(e,t,i)}Long.fromInt=fromInt,Long.fromNumber=fromNumber,Long.fromBits=fromBits;var S=Math.pow;function fromString(e,t,i){if(0===e.length)throw Error("empty string");if("NaN"===e||"Infinity"===e||"+Infinity"===e||"-Infinity"===e)return w;if("number"==typeof t?(i=t,t=!1):t=!!t,(i=i||10)<2||360)throw Error("interior hyphen");if(0===n)return fromString(e.substring(1),t,i).neg();for(var s=fromNumber(S(i,8)),a=w,o=0;o>>0:this.low},L.toNumber=function toNumber(){return this.unsigned?(this.high>>>0)*b+(this.low>>>0):this.high*b+(this.low>>>0)},L.toString=function toString(e){if((e=e||10)<2||36>>0).toString(e);if((a=c).isZero())return u+o;for(;u.length<6;)u="0"+u;o=""+u+o}},L.getHighBits=function getHighBits(){return this.high},L.getHighBitsUnsigned=function getHighBitsUnsigned(){return this.high>>>0},L.getLowBits=function getLowBits(){return this.low},L.getLowBitsUnsigned=function getLowBitsUnsigned(){return this.low>>>0},L.getNumBitsAbs=function getNumBitsAbs(){if(this.isNegative())return this.eq(_)?64:this.neg().getNumBitsAbs();for(var e=0!=this.high?this.high:this.low,t=31;t>0&&0==(e&1<=0},L.isOdd=function isOdd(){return 1==(1&this.low)},L.isEven=function isEven(){return 0==(1&this.low)},L.equals=function equals(e){return isLong(e)||(e=fromValue(e)),(this.unsigned===e.unsigned||this.high>>>31!=1||e.high>>>31!=1)&&(this.high===e.high&&this.low===e.low)},L.eq=L.equals,L.notEquals=function notEquals(e){return!this.eq(e)},L.neq=L.notEquals,L.ne=L.notEquals,L.lessThan=function lessThan(e){return this.comp(e)<0},L.lt=L.lessThan,L.lessThanOrEqual=function lessThanOrEqual(e){return this.comp(e)<=0},L.lte=L.lessThanOrEqual,L.le=L.lessThanOrEqual,L.greaterThan=function greaterThan(e){return this.comp(e)>0},L.gt=L.greaterThan,L.greaterThanOrEqual=function greaterThanOrEqual(e){return this.comp(e)>=0},L.gte=L.greaterThanOrEqual,L.ge=L.greaterThanOrEqual,L.compare=function compare(e){if(isLong(e)||(e=fromValue(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},L.comp=L.compare,L.negate=function negate(){return!this.unsigned&&this.eq(_)?_:this.not().add(P)},L.neg=L.negate,L.add=function add(e){isLong(e)||(e=fromValue(e));var t=this.high>>>16,i=65535&this.high,n=this.low>>>16,s=65535&this.low,a=e.high>>>16,o=65535&e.high,c=e.low>>>16,u=0,l=0,h=0,p=0;return h+=(p+=s+(65535&e.low))>>>16,l+=(h+=n+c)>>>16,u+=(l+=i+o)>>>16,u+=t+a,fromBits((h&=65535)<<16|(p&=65535),(u&=65535)<<16|(l&=65535),this.unsigned)},L.subtract=function subtract(e){return isLong(e)||(e=fromValue(e)),this.add(e.neg())},L.sub=L.subtract,L.multiply=function multiply(e){if(this.isZero())return w;if(isLong(e)||(e=fromValue(e)),m)return fromBits(m.mul(this.low,this.high,e.low,e.high),m.get_high(),this.unsigned);if(e.isZero())return w;if(this.eq(_))return e.isOdd()?_:w;if(e.eq(_))return this.isOdd()?_:w;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 fromNumber(this.toNumber()*e.toNumber(),this.unsigned);var t=this.high>>>16,i=65535&this.high,n=this.low>>>16,s=65535&this.low,a=e.high>>>16,o=65535&e.high,c=e.low>>>16,u=65535&e.low,l=0,h=0,p=0,v=0;return p+=(v+=s*u)>>>16,h+=(p+=n*u)>>>16,p&=65535,h+=(p+=s*c)>>>16,l+=(h+=i*u)>>>16,h&=65535,l+=(h+=n*c)>>>16,h&=65535,l+=(h+=s*o)>>>16,l+=t*u+i*c+n*o+s*a,fromBits((p&=65535)<<16|(v&=65535),(l&=65535)<<16|(h&=65535),this.unsigned)},L.mul=L.multiply,L.divide=function divide(e){if(isLong(e)||(e=fromValue(e)),e.isZero())throw Error("division by zero");var t,i,n;if(m)return this.unsigned||-2147483648!==this.high||-1!==e.low||-1!==e.high?fromBits((this.unsigned?m.div_u:m.div_s)(this.low,this.high,e.low,e.high),m.get_high(),this.unsigned):this;if(this.isZero())return this.unsigned?C:w;if(this.unsigned){if(e.unsigned||(e=e.toUnsigned()),e.gt(this))return C;if(e.gt(this.shru(1)))return E;n=C}else{if(this.eq(_))return e.eq(P)||e.eq(R)?_:e.eq(_)?P:(t=this.shr(1).div(e).shl(1)).eq(w)?e.isNegative()?P:R:(i=this.sub(e.mul(t)),n=t.add(i.div(e)));if(e.eq(_))return this.unsigned?C:w;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=w}for(i=this;i.gte(e);){t=Math.max(1,Math.floor(i.toNumber()/e.toNumber()));for(var s=Math.ceil(Math.log(t)/Math.LN2),a=s<=48?1:S(2,s-48),o=fromNumber(t),c=o.mul(e);c.isNegative()||c.gt(i);)c=(o=fromNumber(t-=a,this.unsigned)).mul(e);o.isZero()&&(o=P),n=n.add(o),i=i.sub(c)}return n},L.div=L.divide,L.modulo=function modulo(e){return isLong(e)||(e=fromValue(e)),m?fromBits((this.unsigned?m.rem_u:m.rem_s)(this.low,this.high,e.low,e.high),m.get_high(),this.unsigned):this.sub(this.div(e).mul(e))},L.mod=L.modulo,L.rem=L.modulo,L.not=function not(){return fromBits(~this.low,~this.high,this.unsigned)},L.and=function and(e){return isLong(e)||(e=fromValue(e)),fromBits(this.low&e.low,this.high&e.high,this.unsigned)},L.or=function or(e){return isLong(e)||(e=fromValue(e)),fromBits(this.low|e.low,this.high|e.high,this.unsigned)},L.xor=function xor(e){return isLong(e)||(e=fromValue(e)),fromBits(this.low^e.low,this.high^e.high,this.unsigned)},L.shiftLeft=function shiftLeft(e){return isLong(e)&&(e=e.toInt()),0==(e&=63)?this:e<32?fromBits(this.low<>>32-e,this.unsigned):fromBits(0,this.low<>>e|this.high<<32-e,this.high>>e,this.unsigned):fromBits(this.high>>e-32,this.high>=0?0:-1,this.unsigned)},L.shr=L.shiftRight,L.shiftRightUnsigned=function shiftRightUnsigned(e){if(isLong(e)&&(e=e.toInt()),0===(e&=63))return this;var t=this.high;return e<32?fromBits(this.low>>>e|t<<32-e,t>>>e,this.unsigned):fromBits(32===e?t:t>>>e-32,0,this.unsigned)},L.shru=L.shiftRightUnsigned,L.shr_u=L.shiftRightUnsigned,L.toSigned=function toSigned(){return this.unsigned?fromBits(this.low,this.high,!1):this},L.toUnsigned=function toUnsigned(){return this.unsigned?this:fromBits(this.low,this.high,!0)},L.toBytes=function toBytes(e){return e?this.toBytesLE():this.toBytesBE()},L.toBytesLE=function toBytesLE(){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]},L.toBytesBE=function toBytesBE(){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]},Long.fromBytes=function fromBytes(e,t,i){return i?Long.fromBytesLE(e,t):Long.fromBytesBE(e,t)},Long.fromBytesLE=function fromBytesLE(e,t){return new Long(e[0]|e[1]<<8|e[2]<<16|e[3]<<24,e[4]|e[5]<<8|e[6]<<16|e[7]<<24,t)},Long.fromBytesBE=function fromBytesBE(e,t){return new Long(e[4]<<24|e[5]<<16|e[6]<<8|e[7],e[0]<<24|e[1]<<16|e[2]<<8|e[3],t)};var D={},A={},U=function asPromise(e,t){var i=new Array(arguments.length-1),n=0,s=2,a=!0;for(;s1&&"="===e.charAt(t);)++i;return Math.ceil(3*e.length)/4-i};for(var i=new Array(64),n=new Array(123),s=0;s<64;)n[i[s]=s<26?s+65:s<52?s+71:s<62?s-4:s-59|43]=s++;t.encode=function encode(e,t,n){for(var s,a=null,o=[],c=0,u=0;t>2],s=(3&l)<<4,u=1;break;case 1:o[c++]=i[s|l>>4],s=(15&l)<<2,u=2;break;case 2:o[c++]=i[s|l>>6],o[c++]=i[63&l],u=0}c>8191&&((a||(a=[])).push(String.fromCharCode.apply(String,o)),c=0)}return u&&(o[c++]=i[s],o[c++]=61,1===u&&(o[c++]=61)),a?(c&&a.push(String.fromCharCode.apply(String,o.slice(0,c))),a.join("")):String.fromCharCode.apply(String,o.slice(0,c))};var a="invalid encoding";t.decode=function decode(e,t,i){for(var s,o=i,c=0,u=0;u1)break;if(void 0===(l=n[l]))throw Error(a);switch(c){case 0:s=l,c=1;break;case 1:t[i++]=s<<2|(48&l)>>4,s=l,c=2;break;case 2:t[i++]=(15&s)<<4|(60&l)>>2,s=l,c=3;break;case 3:t[i++]=(3&s)<<6|l,c=0}}if(1===c)throw Error(a);return i-o},t.test=function test(e){return/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(e)}}(I);var M=EventEmitter$1;function EventEmitter$1(){this._listeners={}}EventEmitter$1.prototype.on=function on(e,t,i){return(this._listeners[e]||(this._listeners[e]=[])).push({fn:t,ctx:i||this}),this},EventEmitter$1.prototype.off=function off(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;n0?0:2147483648,i,n);else if(isNaN(t))e(2143289344,i,n);else if(t>34028234663852886e22)e((s<<31|2139095040)>>>0,i,n);else if(t<11754943508222875e-54)e((s<<31|Math.round(t/1401298464324817e-60))>>>0,i,n);else{var a=Math.floor(Math.log(t)/Math.LN2);e((s<<31|a+127<<23|8388607&Math.round(t*Math.pow(2,-a)*8388608))>>>0,i,n)}}function readFloat_ieee754(e,t,i){var n=e(t,i),s=2*(n>>31)+1,a=n>>>23&255,o=8388607&n;return 255===a?o?NaN:s*(1/0):0===a?1401298464324817e-60*s*o:s*Math.pow(2,a-150)*(o+8388608)}e.writeFloatLE=writeFloat_ieee754.bind(null,writeUintLE),e.writeFloatBE=writeFloat_ieee754.bind(null,writeUintBE),e.readFloatLE=readFloat_ieee754.bind(null,readUintLE),e.readFloatBE=readFloat_ieee754.bind(null,readUintBE)}(),"undefined"!=typeof Float64Array?function(){var t=new Float64Array([-0]),i=new Uint8Array(t.buffer),n=128===i[7];function writeDouble_f64_cpy(e,n,s){t[0]=e,n[s]=i[0],n[s+1]=i[1],n[s+2]=i[2],n[s+3]=i[3],n[s+4]=i[4],n[s+5]=i[5],n[s+6]=i[6],n[s+7]=i[7]}function writeDouble_f64_rev(e,n,s){t[0]=e,n[s]=i[7],n[s+1]=i[6],n[s+2]=i[5],n[s+3]=i[4],n[s+4]=i[3],n[s+5]=i[2],n[s+6]=i[1],n[s+7]=i[0]}function readDouble_f64_cpy(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 readDouble_f64_rev(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?writeDouble_f64_cpy:writeDouble_f64_rev,e.writeDoubleBE=n?writeDouble_f64_rev:writeDouble_f64_cpy,e.readDoubleLE=n?readDouble_f64_cpy:readDouble_f64_rev,e.readDoubleBE=n?readDouble_f64_rev:readDouble_f64_cpy}():function(){function writeDouble_ieee754(e,t,i,n,s,a){var o=n<0?1:0;if(o&&(n=-n),0===n)e(0,s,a+t),e(1/n>0?0:2147483648,s,a+i);else if(isNaN(n))e(0,s,a+t),e(2146959360,s,a+i);else if(n>17976931348623157e292)e(0,s,a+t),e((o<<31|2146435072)>>>0,s,a+i);else{var c;if(n<22250738585072014e-324)e((c=n/5e-324)>>>0,s,a+t),e((o<<31|c/4294967296)>>>0,s,a+i);else{var u=Math.floor(Math.log(n)/Math.LN2);1024===u&&(u=1023),e(4503599627370496*(c=n*Math.pow(2,-u))>>>0,s,a+t),e((o<<31|u+1023<<20|1048576*c&1048575)>>>0,s,a+i)}}}function readDouble_ieee754(e,t,i,n,s){var a=e(n,s+t),o=e(n,s+i),c=2*(o>>31)+1,u=o>>>20&2047,l=4294967296*(1048575&o)+a;return 2047===u?l?NaN:c*(1/0):0===u?5e-324*c*l:c*Math.pow(2,u-1075)*(l+4503599627370496)}e.writeDoubleLE=writeDouble_ieee754.bind(null,writeUintLE,0,4),e.writeDoubleBE=writeDouble_ieee754.bind(null,writeUintBE,4,0),e.readDoubleLE=readDouble_ieee754.bind(null,readUintLE,0,4),e.readDoubleBE=readDouble_ieee754.bind(null,readUintBE,4,0)}(),e}function writeUintLE(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 writeUintBE(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 readUintLE(e,t){return(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0}function readUintBE(e,t){return(e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3])>>>0}var B=function inquire(e){try{var t=void 0;t}catch(e){}return null};var J={};!function(e){var t=e;t.length=function utf8_length(e){for(var t=0,i=0,n=0;n191&&n<224?a[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,a[o++]=55296+(n>>10),a[o++]=56320+(1023&n)):a[o++]=(15&n)<<12|(63&e[t++])<<6|63&e[t++],o>8191&&((s||(s=[])).push(String.fromCharCode.apply(String,a)),o=0);return s?(o&&s.push(String.fromCharCode.apply(String,a.slice(0,o))),s.join("")):String.fromCharCode.apply(String,a.slice(0,o))},t.write=function utf8_write(e,t,i){for(var n,s,a=i,o=0;o>6|192,t[i++]=63&n|128):55296==(64512&n)&&56320==(64512&(s=e.charCodeAt(o+1)))?(n=65536+((1023&n)<<10)+(1023&s),++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-a}}(J);var F=function pool(e,t,i){var n=i||8192,s=n>>>1,a=null,o=n;return function pool_alloc(i){if(i<1||i>s)return e(i);o+i>n&&(a=e(n),o=0);var c=t.call(a,o,o+=i);return 7&o&&(o=1+(7|o)),c}};var V=LongBits$2,j=A;function LongBits$2(e,t){this.lo=e>>>0,this.hi=t>>>0}var q=LongBits$2.zero=new LongBits$2(0,0);q.toNumber=function(){return 0},q.zzEncode=q.zzDecode=function(){return this},q.length=function(){return 1};var W=LongBits$2.zeroHash="\0\0\0\0\0\0\0\0";LongBits$2.fromNumber=function fromNumber(e){if(0===e)return q;var t=e<0;t&&(e=-e);var i=e>>>0,n=(e-i)/4294967296>>>0;return t&&(n=~n>>>0,i=~i>>>0,++i>4294967295&&(i=0,++n>4294967295&&(n=0))),new LongBits$2(i,n)},LongBits$2.from=function from(e){if("number"==typeof e)return LongBits$2.fromNumber(e);if(j.isString(e)){if(!j.Long)return LongBits$2.fromNumber(parseInt(e,10));e=j.Long.fromString(e)}return e.low||e.high?new LongBits$2(e.low>>>0,e.high>>>0):q},LongBits$2.prototype.toNumber=function toNumber(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},LongBits$2.prototype.toLong=function toLong(e){return j.Long?new j.Long(0|this.lo,0|this.hi,Boolean(e)):{low:0|this.lo,high:0|this.hi,unsigned:Boolean(e)}};var $=String.prototype.charCodeAt;LongBits$2.fromHash=function fromHash(e){return e===W?q:new LongBits$2(($.call(e,0)|$.call(e,1)<<8|$.call(e,2)<<16|$.call(e,3)<<24)>>>0,($.call(e,4)|$.call(e,5)<<8|$.call(e,6)<<16|$.call(e,7)<<24)>>>0)},LongBits$2.prototype.toHash=function toHash(){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)},LongBits$2.prototype.zzEncode=function zzEncode(){var e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this},LongBits$2.prototype.zzDecode=function zzDecode(){var e=-(1&this.lo);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this},LongBits$2.prototype.length=function length(){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},function(e){var t=e;function merge(e,t,i){for(var n=Object.keys(t),s=0;s0)},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 newBuffer(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 longToHash(e){return e?t.LongBits.from(e).toHash():t.LongBits.zeroHash},t.longFromHash=function longFromHash(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=merge,t.lcFirst=function lcFirst(e){return e.charAt(0).toLowerCase()+e.substring(1)},t.newError=newError,t.ProtocolError=newError("ProtocolError"),t.oneOfGetter=function getOneOf(e){for(var t={},i=0;i-1;--i)if(1===t[e[i]]&&void 0!==this[e[i]]&&null!==this[e[i]])return e[i]}},t.oneOfSetter=function setOneOf(e){return function(t){for(var i=0;i>>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 writeFixed32(e,t,i){t[i]=255&e,t[i+1]=e>>>8&255,t[i+2]=e>>>16&255,t[i+3]=e>>>24}Writer$1.create=Y(),Writer$1.alloc=function alloc(e){return new H.Array(e)},H.Array!==Array&&(Writer$1.alloc=H.pool(Writer$1.alloc,H.Array.prototype.subarray)),Writer$1.prototype._push=function push(e,t,i){return this.tail=this.tail.next=new Op(e,t,i),this.len+=t,this},VarintOp.prototype=Object.create(Op.prototype),VarintOp.prototype.fn=function writeVarint32(e,t,i){for(;e>127;)t[i++]=127&e|128,e>>>=7;t[i]=e},Writer$1.prototype.uint32=function write_uint32(e){return this.len+=(this.tail=this.tail.next=new VarintOp((e>>>=0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this},Writer$1.prototype.int32=function write_int32(e){return e<0?this._push(writeVarint64,10,K.fromNumber(e)):this.uint32(e)},Writer$1.prototype.sint32=function write_sint32(e){return this.uint32((e<<1^e>>31)>>>0)},Writer$1.prototype.uint64=function write_uint64(e){var t=K.from(e);return this._push(writeVarint64,t.length(),t)},Writer$1.prototype.int64=Writer$1.prototype.uint64,Writer$1.prototype.sint64=function write_sint64(e){var t=K.from(e).zzEncode();return this._push(writeVarint64,t.length(),t)},Writer$1.prototype.bool=function write_bool(e){return this._push(writeByte,1,e?1:0)},Writer$1.prototype.fixed32=function write_fixed32(e){return this._push(writeFixed32,4,e>>>0)},Writer$1.prototype.sfixed32=Writer$1.prototype.fixed32,Writer$1.prototype.fixed64=function write_fixed64(e){var t=K.from(e);return this._push(writeFixed32,4,t.lo)._push(writeFixed32,4,t.hi)},Writer$1.prototype.sfixed64=Writer$1.prototype.fixed64,Writer$1.prototype.float=function write_float(e){return this._push(H.float.writeFloatLE,4,e)},Writer$1.prototype.double=function write_double(e){return this._push(H.float.writeDoubleLE,8,e)};var X=H.Array.prototype.set?function writeBytes_set(e,t,i){t.set(e,i)}:function writeBytes_for(e,t,i){for(var n=0;n>>0;if(!t)return this._push(writeByte,1,0);if(H.isString(e)){var i=Writer$1.alloc(t=z.length(e));z.decode(e,i,0),e=i}return this.uint32(t)._push(X,t,e)},Writer$1.prototype.string=function write_string(e){var t=Z.length(e);return t?this.uint32(t)._push(Z.write,t,e):this._push(writeByte,1,0)},Writer$1.prototype.fork=function fork(){return this.states=new State(this),this.head=this.tail=new Op(noop,0,0),this.len=0,this},Writer$1.prototype.reset=function reset(){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 Op(noop,0,0),this.len=0),this},Writer$1.prototype.ldelim=function ldelim(){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},Writer$1.prototype.finish=function finish(){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},Writer$1._configure=function(e){G=e,Writer$1.create=Y(),G._configure()};var ee=BufferWriter,te=Q;(BufferWriter.prototype=Object.create(te.prototype)).constructor=BufferWriter;var ie=A;function BufferWriter(){te.call(this)}function writeStringBuffer(e,t,i){e.length<40?ie.utf8.write(e,t,i):t.utf8Write?t.utf8Write(e,i):t.write(e,i)}BufferWriter._configure=function(){BufferWriter.alloc=ie._Buffer_allocUnsafe,BufferWriter.writeBytesBuffer=ie.Buffer&&ie.Buffer.prototype instanceof Uint8Array&&"set"===ie.Buffer.prototype.set.name?function writeBytesBuffer_set(e,t,i){t.set(e,i)}:function writeBytesBuffer_copy(e,t,i){if(e.copy)e.copy(t,i,0,e.length);else for(var n=0;n>>0;return this.uint32(t),t&&this._push(BufferWriter.writeBytesBuffer,t,e),this},BufferWriter.prototype.string=function write_string_buffer(e){var t=ie.Buffer.byteLength(e);return this.uint32(t),t&&this._push(writeStringBuffer,t,e),this},BufferWriter._configure();var re,ne=Reader$1,se=A,ae=se.LongBits,oe=se.utf8;function indexOutOfRange(e,t){return RangeError("index out of range: "+e.pos+" + "+(t||1)+" > "+e.len)}function Reader$1(e){this.buf=e,this.pos=0,this.len=e.length}var ce="undefined"!=typeof Uint8Array?function create_typed_array(e){if(e instanceof Uint8Array||Array.isArray(e))return new Reader$1(e);throw Error("illegal buffer")}:function create_array(e){if(Array.isArray(e))return new Reader$1(e);throw Error("illegal buffer")},de=function create(){return se.Buffer?function create_buffer_setup(e){return(Reader$1.create=function create_buffer(e){return se.Buffer.isBuffer(e)?new re(e):ce(e)})(e)}:ce};function readLongVarint(){var e=new ae(0,0),t=0;if(!(this.len-this.pos>4)){for(;t<3;++t){if(this.pos>=this.len)throw indexOutOfRange(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 indexOutOfRange(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 readFixed32_end(e,t){return(e[t-4]|e[t-3]<<8|e[t-2]<<16|e[t-1]<<24)>>>0}function readFixed64(){if(this.pos+8>this.len)throw indexOutOfRange(this,8);return new ae(readFixed32_end(this.buf,this.pos+=4),readFixed32_end(this.buf,this.pos+=4))}Reader$1.create=de(),Reader$1.prototype._slice=se.Array.prototype.subarray||se.Array.prototype.slice,Reader$1.prototype.uint32=function read_uint32_setup(){var e=4294967295;return function read_uint32(){if(e=(127&this.buf[this.pos])>>>0,this.buf[this.pos++]<128)return e;if(e=(e|(127&this.buf[this.pos])<<7)>>>0,this.buf[this.pos++]<128)return e;if(e=(e|(127&this.buf[this.pos])<<14)>>>0,this.buf[this.pos++]<128)return e;if(e=(e|(127&this.buf[this.pos])<<21)>>>0,this.buf[this.pos++]<128)return e;if(e=(e|(15&this.buf[this.pos])<<28)>>>0,this.buf[this.pos++]<128)return e;if((this.pos+=5)>this.len)throw this.pos=this.len,indexOutOfRange(this,10);return e}}(),Reader$1.prototype.int32=function read_int32(){return 0|this.uint32()},Reader$1.prototype.sint32=function read_sint32(){var e=this.uint32();return e>>>1^-(1&e)|0},Reader$1.prototype.bool=function read_bool(){return 0!==this.uint32()},Reader$1.prototype.fixed32=function read_fixed32(){if(this.pos+4>this.len)throw indexOutOfRange(this,4);return readFixed32_end(this.buf,this.pos+=4)},Reader$1.prototype.sfixed32=function read_sfixed32(){if(this.pos+4>this.len)throw indexOutOfRange(this,4);return 0|readFixed32_end(this.buf,this.pos+=4)},Reader$1.prototype.float=function read_float(){if(this.pos+4>this.len)throw indexOutOfRange(this,4);var e=se.float.readFloatLE(this.buf,this.pos);return this.pos+=4,e},Reader$1.prototype.double=function read_double(){if(this.pos+8>this.len)throw indexOutOfRange(this,4);var e=se.float.readDoubleLE(this.buf,this.pos);return this.pos+=8,e},Reader$1.prototype.bytes=function read_bytes(){var e=this.uint32(),t=this.pos,i=this.pos+e;if(i>this.len)throw indexOutOfRange(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)},Reader$1.prototype.string=function read_string(){var e=this.bytes();return oe.read(e,0,e.length)},Reader$1.prototype.skip=function skip(e){if("number"==typeof e){if(this.pos+e>this.len)throw indexOutOfRange(this,e);this.pos+=e}else do{if(this.pos>=this.len)throw indexOutOfRange(this)}while(128&this.buf[this.pos++]);return this},Reader$1.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},Reader$1._configure=function(e){re=e,Reader$1.create=de(),re._configure();var t=se.Long?"toLong":"toNumber";se.merge(Reader$1.prototype,{int64:function read_int64(){return readLongVarint.call(this)[t](!1)},uint64:function read_uint64(){return readLongVarint.call(this)[t](!0)},sint64:function read_sint64(){return readLongVarint.call(this).zzDecode()[t](!1)},fixed64:function read_fixed64(){return readFixed64.call(this)[t](!0)},sfixed64:function read_sfixed64(){return readFixed64.call(this)[t](!1)}})};var ue=BufferReader,le=ne;(BufferReader.prototype=Object.create(le.prototype)).constructor=BufferReader;var he=A;function BufferReader(e){le.call(this,e)}BufferReader._configure=function(){he.Buffer&&(BufferReader.prototype._slice=he.Buffer.prototype.slice)},BufferReader.prototype.string=function read_string_buffer(){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))},BufferReader._configure();var pe,me={},fe=Service,ve=A;function Service(e,t,i){if("function"!=typeof e)throw TypeError("rpcImpl must be a function");ve.EventEmitter.call(this),this.rpcImpl=e,this.requestDelimited=Boolean(t),this.responseDelimited=Boolean(i)}(Service.prototype=Object.create(ve.EventEmitter.prototype)).constructor=Service,Service.prototype.rpcCall=function rpcCall(e,t,i,n,s){if(!n)throw TypeError("request must be specified");var a=this;if(!s)return ve.asPromise(rpcCall,a,e,t,i,n);if(a.rpcImpl)try{return a.rpcImpl(e,t[a.requestDelimited?"encodeDelimited":"encode"](n).finish(),(function rpcCallback(t,n){if(t)return a.emit("error",t,e),s(t);if(null!==n){if(!(n instanceof i))try{n=i[a.responseDelimited?"decodeDelimited":"decode"](n)}catch(t){return a.emit("error",t,e),s(t)}return a.emit("data",n,e),s(null,n)}a.end(!0)}))}catch(t){return a.emit("error",t,e),void setTimeout((function(){s(t)}),0)}else setTimeout((function(){s(Error("already ended"))}),0)},Service.prototype.end=function end(e){return this.rpcImpl&&(e||this.rpcImpl(null,null,null),this.rpcImpl=null,this.emit("end").off()),this},pe=me,pe.Service=fe;var ge={};!function(e){var t=e;function configure(){t.util._configure(),t.Writer._configure(t.BufferWriter),t.Reader._configure(t.BufferReader)}t.build="minimal",t.Writer=Q,t.BufferWriter=ee,t.Reader=ne,t.BufferReader=ue,t.util=A,t.rpc=me,t.roots=ge,t.configure=configure,configure()}(D);var Se,be,ke,ye,Te,we,Ce,Pe,Ee=D,Re=(()=>{if(void 0!==Re)return Re;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 trackTypeFromJSON(e){switch(e){case 0:case"AUDIO":return Se.AUDIO;case 1:case"VIDEO":return Se.VIDEO;case 2:case"DATA":return Se.DATA;default:return Se.UNRECOGNIZED}}function trackTypeToJSON(e){switch(e){case Se.AUDIO:return"AUDIO";case Se.VIDEO:return"VIDEO";case Se.DATA:return"DATA";default:return"UNKNOWN"}}function trackSourceFromJSON(e){switch(e){case 0:case"UNKNOWN":return be.UNKNOWN;case 1:case"CAMERA":return be.CAMERA;case 2:case"MICROPHONE":return be.MICROPHONE;case 3:case"SCREEN_SHARE":return be.SCREEN_SHARE;case 4:case"SCREEN_SHARE_AUDIO":return be.SCREEN_SHARE_AUDIO;default:return be.UNRECOGNIZED}}function trackSourceToJSON(e){switch(e){case be.UNKNOWN:return"UNKNOWN";case be.CAMERA:return"CAMERA";case be.MICROPHONE:return"MICROPHONE";case be.SCREEN_SHARE:return"SCREEN_SHARE";case be.SCREEN_SHARE_AUDIO:return"SCREEN_SHARE_AUDIO";default:return"UNKNOWN"}}function videoQualityFromJSON(e){switch(e){case 0:case"LOW":return ke.LOW;case 1:case"MEDIUM":return ke.MEDIUM;case 2:case"HIGH":return ke.HIGH;case 3:case"OFF":return ke.OFF;default:return ke.UNRECOGNIZED}}function videoQualityToJSON(e){switch(e){case ke.LOW:return"LOW";case ke.MEDIUM:return"MEDIUM";case ke.HIGH:return"HIGH";case ke.OFF:return"OFF";default:return"UNKNOWN"}}function connectionQualityFromJSON(e){switch(e){case 0:case"POOR":return ye.POOR;case 1:case"GOOD":return ye.GOOD;case 2:case"EXCELLENT":return ye.EXCELLENT;default:return ye.UNRECOGNIZED}}function clientConfigSettingFromJSON(e){switch(e){case 0:case"UNSET":return Te.UNSET;case 1:case"DISABLED":return Te.DISABLED;case 2:case"ENABLED":return Te.ENABLED;default:return Te.UNRECOGNIZED}}function clientConfigSettingToJSON(e){switch(e){case Te.UNSET:return"UNSET";case Te.DISABLED:return"DISABLED";case Te.ENABLED:return"ENABLED";default:return"UNKNOWN"}}function participantInfo_StateFromJSON(e){switch(e){case 0:case"JOINING":return we.JOINING;case 1:case"JOINED":return we.JOINED;case 2:case"ACTIVE":return we.ACTIVE;case 3:case"DISCONNECTED":return we.DISCONNECTED;default:return we.UNRECOGNIZED}}function dataPacket_KindFromJSON(e){switch(e){case 0:case"RELIABLE":return Ce.RELIABLE;case 1:case"LOSSY":return Ce.LOSSY;default:return Ce.UNRECOGNIZED}}function clientInfo_SDKFromJSON(e){switch(e){case 0:case"UNKNOWN":return Pe.UNKNOWN;case 1:case"JS":return Pe.JS;case 2:case"SWIFT":return Pe.SWIFT;case 3:case"ANDROID":return Pe.ANDROID;case 4:case"FLUTTER":return Pe.FLUTTER;case 5:case"GO":return Pe.GO;case 6:case"UNITY":return Pe.UNITY;default:return Pe.UNRECOGNIZED}}Ee.util.Long!==p&&(Ee.util.Long=p,Ee.configure()),function(e){e[e.AUDIO=0]="AUDIO",e[e.VIDEO=1]="VIDEO",e[e.DATA=2]="DATA",e[e.UNRECOGNIZED=-1]="UNRECOGNIZED"}(Se||(Se={})),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"}(be||(be={})),function(e){e[e.LOW=0]="LOW",e[e.MEDIUM=1]="MEDIUM",e[e.HIGH=2]="HIGH",e[e.OFF=3]="OFF",e[e.UNRECOGNIZED=-1]="UNRECOGNIZED"}(ke||(ke={})),function(e){e[e.POOR=0]="POOR",e[e.GOOD=1]="GOOD",e[e.EXCELLENT=2]="EXCELLENT",e[e.UNRECOGNIZED=-1]="UNRECOGNIZED"}(ye||(ye={})),function(e){e[e.UNSET=0]="UNSET",e[e.DISABLED=1]="DISABLED",e[e.ENABLED=2]="ENABLED",e[e.UNRECOGNIZED=-1]="UNRECOGNIZED"}(Te||(Te={})),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"}(we||(we={})),function(e){e[e.RELIABLE=0]="RELIABLE",e[e.LOSSY=1]="LOSSY",e[e.UNRECOGNIZED=-1]="UNRECOGNIZED"}(Ce||(Ce={})),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.UNRECOGNIZED=-1]="UNRECOGNIZED"}(Pe||(Pe={}));const Oe={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Ee.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)Ne.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.activeRecording&&t.uint32(80).bool(e.activeRecording),t},decode(e,t){const i=e instanceof Ee.Reader?e:new Ee.Reader(e);let n=void 0===t?i.len:i.pos+t;const s={sid:"",name:"",emptyTimeout:0,maxParticipants:0,creationTime:0,turnPassword:"",enabledCodecs:[],metadata:"",numParticipants:0,activeRecording:!1};for(;i.pos>>3){case 1:s.sid=i.string();break;case 2:s.name=i.string();break;case 3:s.emptyTimeout=i.uint32();break;case 4:s.maxParticipants=i.uint32();break;case 5:s.creationTime=longToNumber(i.int64());break;case 6:s.turnPassword=i.string();break;case 7:s.enabledCodecs.push(Ne.decode(i,i.uint32()));break;case 8:s.metadata=i.string();break;case 9:s.numParticipants=i.uint32();break;case 10:s.activeRecording=i.bool();break;default:i.skipType(7&e)}}return s},fromJSON:e=>({sid:isSet$1(e.sid)?String(e.sid):"",name:isSet$1(e.name)?String(e.name):"",emptyTimeout:isSet$1(e.emptyTimeout)?Number(e.emptyTimeout):0,maxParticipants:isSet$1(e.maxParticipants)?Number(e.maxParticipants):0,creationTime:isSet$1(e.creationTime)?Number(e.creationTime):0,turnPassword:isSet$1(e.turnPassword)?String(e.turnPassword):"",enabledCodecs:Array.isArray(null==e?void 0:e.enabledCodecs)?e.enabledCodecs.map((e=>Ne.fromJSON(e))):[],metadata:isSet$1(e.metadata)?String(e.metadata):"",numParticipants:isSet$1(e.numParticipants)?Number(e.numParticipants):0,activeRecording:!!isSet$1(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?Ne.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.activeRecording&&(t.activeRecording=e.activeRecording),t},fromPartial(e){var t,i,n,s,a,o,c,u,l,h;const p={sid:"",name:"",emptyTimeout:0,maxParticipants:0,creationTime:0,turnPassword:"",enabledCodecs:[],metadata:"",numParticipants:0,activeRecording:!1};return p.sid=null!==(t=e.sid)&&void 0!==t?t:"",p.name=null!==(i=e.name)&&void 0!==i?i:"",p.emptyTimeout=null!==(n=e.emptyTimeout)&&void 0!==n?n:0,p.maxParticipants=null!==(s=e.maxParticipants)&&void 0!==s?s:0,p.creationTime=null!==(a=e.creationTime)&&void 0!==a?a:0,p.turnPassword=null!==(o=e.turnPassword)&&void 0!==o?o:"",p.enabledCodecs=(null===(c=e.enabledCodecs)||void 0===c?void 0:c.map((e=>Ne.fromPartial(e))))||[],p.metadata=null!==(u=e.metadata)&&void 0!==u?u:"",p.numParticipants=null!==(l=e.numParticipants)&&void 0!==l?l:0,p.activeRecording=null!==(h=e.activeRecording)&&void 0!==h&&h,p}};const Ne={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Ee.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 Ee.Reader?e:new Ee.Reader(e);let n=void 0===t?i.len:i.pos+t;const s={mime:"",fmtpLine:""};for(;i.pos>>3){case 1:s.mime=i.string();break;case 2:s.fmtpLine=i.string();break;default:i.skipType(7&e)}}return s},fromJSON:e=>({mime:isSet$1(e.mime)?String(e.mime):"",fmtpLine:isSet$1(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},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 _e={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Ee.Writer.create();return!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),!0===e.hidden&&t.uint32(56).bool(e.hidden),!0===e.recorder&&t.uint32(64).bool(e.recorder),t},decode(e,t){const i=e instanceof Ee.Reader?e:new Ee.Reader(e);let n=void 0===t?i.len:i.pos+t;const s={canSubscribe:!1,canPublish:!1,canPublishData:!1,hidden:!1,recorder:!1};for(;i.pos>>3){case 1:s.canSubscribe=i.bool();break;case 2:s.canPublish=i.bool();break;case 3:s.canPublishData=i.bool();break;case 7:s.hidden=i.bool();break;case 8:s.recorder=i.bool();break;default:i.skipType(7&e)}}return s},fromJSON:e=>({canSubscribe:!!isSet$1(e.canSubscribe)&&Boolean(e.canSubscribe),canPublish:!!isSet$1(e.canPublish)&&Boolean(e.canPublish),canPublishData:!!isSet$1(e.canPublishData)&&Boolean(e.canPublishData),hidden:!!isSet$1(e.hidden)&&Boolean(e.hidden),recorder:!!isSet$1(e.recorder)&&Boolean(e.recorder)}),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),void 0!==e.hidden&&(t.hidden=e.hidden),void 0!==e.recorder&&(t.recorder=e.recorder),t},fromPartial(e){var t,i,n,s,a;const o={canSubscribe:!1,canPublish:!1,canPublishData:!1,hidden:!1,recorder:!1};return o.canSubscribe=null!==(t=e.canSubscribe)&&void 0!==t&&t,o.canPublish=null!==(i=e.canPublish)&&void 0!==i&&i,o.canPublishData=null!==(n=e.canPublishData)&&void 0!==n&&n,o.hidden=null!==(s=e.hidden)&&void 0!==s&&s,o.recorder=null!==(a=e.recorder)&&void 0!==a&&a,o}};const Le={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Ee.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)De.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&&_e.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 Ee.Reader?e:new Ee.Reader(e);let n=void 0===t?i.len:i.pos+t;const s={sid:"",identity:"",state:0,tracks:[],metadata:"",joinedAt:0,name:"",version:0,permission:void 0,region:"",isPublisher:!1};for(;i.pos>>3){case 1:s.sid=i.string();break;case 2:s.identity=i.string();break;case 3:s.state=i.int32();break;case 4:s.tracks.push(De.decode(i,i.uint32()));break;case 5:s.metadata=i.string();break;case 6:s.joinedAt=longToNumber(i.int64());break;case 9:s.name=i.string();break;case 10:s.version=i.uint32();break;case 11:s.permission=_e.decode(i,i.uint32());break;case 12:s.region=i.string();break;case 13:s.isPublisher=i.bool();break;default:i.skipType(7&e)}}return s},fromJSON:e=>({sid:isSet$1(e.sid)?String(e.sid):"",identity:isSet$1(e.identity)?String(e.identity):"",state:isSet$1(e.state)?participantInfo_StateFromJSON(e.state):0,tracks:Array.isArray(null==e?void 0:e.tracks)?e.tracks.map((e=>De.fromJSON(e))):[],metadata:isSet$1(e.metadata)?String(e.metadata):"",joinedAt:isSet$1(e.joinedAt)?Number(e.joinedAt):0,name:isSet$1(e.name)?String(e.name):"",version:isSet$1(e.version)?Number(e.version):0,permission:isSet$1(e.permission)?_e.fromJSON(e.permission):void 0,region:isSet$1(e.region)?String(e.region):"",isPublisher:!!isSet$1(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 participantInfo_StateToJSON(e){switch(e){case we.JOINING:return"JOINING";case we.JOINED:return"JOINED";case we.ACTIVE:return"ACTIVE";case we.DISCONNECTED:return"DISCONNECTED";default:return"UNKNOWN"}}(e.state)),e.tracks?t.tracks=e.tracks.map((e=>e?De.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?_e.toJSON(e.permission):void 0),void 0!==e.region&&(t.region=e.region),void 0!==e.isPublisher&&(t.isPublisher=e.isPublisher),t},fromPartial(e){var t,i,n,s,a,o,c,u,l,h;const p={sid:"",identity:"",state:0,tracks:[],metadata:"",joinedAt:0,name:"",version:0,permission:void 0,region:"",isPublisher:!1};return p.sid=null!==(t=e.sid)&&void 0!==t?t:"",p.identity=null!==(i=e.identity)&&void 0!==i?i:"",p.state=null!==(n=e.state)&&void 0!==n?n:0,p.tracks=(null===(s=e.tracks)||void 0===s?void 0:s.map((e=>De.fromPartial(e))))||[],p.metadata=null!==(a=e.metadata)&&void 0!==a?a:"",p.joinedAt=null!==(o=e.joinedAt)&&void 0!==o?o:0,p.name=null!==(c=e.name)&&void 0!==c?c:"",p.version=null!==(u=e.version)&&void 0!==u?u:0,p.permission=void 0!==e.permission&&null!==e.permission?_e.fromPartial(e.permission):void 0,p.region=null!==(l=e.region)&&void 0!==l?l:"",p.isPublisher=null!==(h=e.isPublisher)&&void 0!==h&&h,p}};const De={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Ee.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)Ae.encode(i,t.uint32(82).fork()).ldelim();return""!==e.mimeType&&t.uint32(90).string(e.mimeType),""!==e.mid&&t.uint32(98).string(e.mid),t},decode(e,t){const i=e instanceof Ee.Reader?e:new Ee.Reader(e);let n=void 0===t?i.len:i.pos+t;const s={sid:"",type:0,name:"",muted:!1,width:0,height:0,simulcast:!1,disableDtx:!1,source:0,layers:[],mimeType:"",mid:""};for(;i.pos>>3){case 1:s.sid=i.string();break;case 2:s.type=i.int32();break;case 3:s.name=i.string();break;case 4:s.muted=i.bool();break;case 5:s.width=i.uint32();break;case 6:s.height=i.uint32();break;case 7:s.simulcast=i.bool();break;case 8:s.disableDtx=i.bool();break;case 9:s.source=i.int32();break;case 10:s.layers.push(Ae.decode(i,i.uint32()));break;case 11:s.mimeType=i.string();break;case 12:s.mid=i.string();break;default:i.skipType(7&e)}}return s},fromJSON:e=>({sid:isSet$1(e.sid)?String(e.sid):"",type:isSet$1(e.type)?trackTypeFromJSON(e.type):0,name:isSet$1(e.name)?String(e.name):"",muted:!!isSet$1(e.muted)&&Boolean(e.muted),width:isSet$1(e.width)?Number(e.width):0,height:isSet$1(e.height)?Number(e.height):0,simulcast:!!isSet$1(e.simulcast)&&Boolean(e.simulcast),disableDtx:!!isSet$1(e.disableDtx)&&Boolean(e.disableDtx),source:isSet$1(e.source)?trackSourceFromJSON(e.source):0,layers:Array.isArray(null==e?void 0:e.layers)?e.layers.map((e=>Ae.fromJSON(e))):[],mimeType:isSet$1(e.mimeType)?String(e.mimeType):"",mid:isSet$1(e.mid)?String(e.mid):""}),toJSON(e){const t={};return void 0!==e.sid&&(t.sid=e.sid),void 0!==e.type&&(t.type=trackTypeToJSON(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=trackSourceToJSON(e.source)),e.layers?t.layers=e.layers.map((e=>e?Ae.toJSON(e):void 0)):t.layers=[],void 0!==e.mimeType&&(t.mimeType=e.mimeType),void 0!==e.mid&&(t.mid=e.mid),t},fromPartial(e){var t,i,n,s,a,o,c,u,l,h,p,m;const v={sid:"",type:0,name:"",muted:!1,width:0,height:0,simulcast:!1,disableDtx:!1,source:0,layers:[],mimeType:"",mid:""};return v.sid=null!==(t=e.sid)&&void 0!==t?t:"",v.type=null!==(i=e.type)&&void 0!==i?i:0,v.name=null!==(n=e.name)&&void 0!==n?n:"",v.muted=null!==(s=e.muted)&&void 0!==s&&s,v.width=null!==(a=e.width)&&void 0!==a?a:0,v.height=null!==(o=e.height)&&void 0!==o?o:0,v.simulcast=null!==(c=e.simulcast)&&void 0!==c&&c,v.disableDtx=null!==(u=e.disableDtx)&&void 0!==u&&u,v.source=null!==(l=e.source)&&void 0!==l?l:0,v.layers=(null===(h=e.layers)||void 0===h?void 0:h.map((e=>Ae.fromPartial(e))))||[],v.mimeType=null!==(p=e.mimeType)&&void 0!==p?p:"",v.mid=null!==(m=e.mid)&&void 0!==m?m:"",v}};const Ae={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Ee.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 Ee.Reader?e:new Ee.Reader(e);let n=void 0===t?i.len:i.pos+t;const s={quality:0,width:0,height:0,bitrate:0,ssrc:0};for(;i.pos>>3){case 1:s.quality=i.int32();break;case 2:s.width=i.uint32();break;case 3:s.height=i.uint32();break;case 4:s.bitrate=i.uint32();break;case 5:s.ssrc=i.uint32();break;default:i.skipType(7&e)}}return s},fromJSON:e=>({quality:isSet$1(e.quality)?videoQualityFromJSON(e.quality):0,width:isSet$1(e.width)?Number(e.width):0,height:isSet$1(e.height)?Number(e.height):0,bitrate:isSet$1(e.bitrate)?Number(e.bitrate):0,ssrc:isSet$1(e.ssrc)?Number(e.ssrc):0}),toJSON(e){const t={};return void 0!==e.quality&&(t.quality=videoQualityToJSON(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},fromPartial(e){var t,i,n,s,a;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!==(s=e.bitrate)&&void 0!==s?s:0,o.ssrc=null!==(a=e.ssrc)&&void 0!==a?a:0,o}};const Ue={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Ee.Writer.create();return 0!==e.kind&&t.uint32(8).int32(e.kind),void 0!==e.user&&xe.encode(e.user,t.uint32(18).fork()).ldelim(),void 0!==e.speaker&&Ie.encode(e.speaker,t.uint32(26).fork()).ldelim(),t},decode(e,t){const i=e instanceof Ee.Reader?e:new Ee.Reader(e);let n=void 0===t?i.len:i.pos+t;const s={kind:0,user:void 0,speaker:void 0};for(;i.pos>>3){case 1:s.kind=i.int32();break;case 2:s.user=xe.decode(i,i.uint32());break;case 3:s.speaker=Ie.decode(i,i.uint32());break;default:i.skipType(7&e)}}return s},fromJSON:e=>({kind:isSet$1(e.kind)?dataPacket_KindFromJSON(e.kind):0,user:isSet$1(e.user)?xe.fromJSON(e.user):void 0,speaker:isSet$1(e.speaker)?Ie.fromJSON(e.speaker):void 0}),toJSON(e){const t={};return void 0!==e.kind&&(t.kind=function dataPacket_KindToJSON(e){switch(e){case Ce.RELIABLE:return"RELIABLE";case Ce.LOSSY:return"LOSSY";default:return"UNKNOWN"}}(e.kind)),void 0!==e.user&&(t.user=e.user?xe.toJSON(e.user):void 0),void 0!==e.speaker&&(t.speaker=e.speaker?Ie.toJSON(e.speaker):void 0),t},fromPartial(e){var t;const i={kind:0,user:void 0,speaker:void 0};return i.kind=null!==(t=e.kind)&&void 0!==t?t:0,i.user=void 0!==e.user&&null!==e.user?xe.fromPartial(e.user):void 0,i.speaker=void 0!==e.speaker&&null!==e.speaker?Ie.fromPartial(e.speaker):void 0,i}};const Ie={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Ee.Writer.create();for(const i of e.speakers)Me.encode(i,t.uint32(10).fork()).ldelim();return t},decode(e,t){const i=e instanceof Ee.Reader?e:new Ee.Reader(e);let n=void 0===t?i.len:i.pos+t;const s={speakers:[]};for(;i.pos>>3==1)s.speakers.push(Me.decode(i,i.uint32()));else i.skipType(7&e)}return s},fromJSON:e=>({speakers:Array.isArray(null==e?void 0:e.speakers)?e.speakers.map((e=>Me.fromJSON(e))):[]}),toJSON(e){const t={};return e.speakers?t.speakers=e.speakers.map((e=>e?Me.toJSON(e):void 0)):t.speakers=[],t},fromPartial(e){var t;const i={speakers:[]};return i.speakers=(null===(t=e.speakers)||void 0===t?void 0:t.map((e=>Me.fromPartial(e))))||[],i}};const Me={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Ee.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 Ee.Reader?e:new Ee.Reader(e);let n=void 0===t?i.len:i.pos+t;const s={sid:"",level:0,active:!1};for(;i.pos>>3){case 1:s.sid=i.string();break;case 2:s.level=i.float();break;case 3:s.active=i.bool();break;default:i.skipType(7&e)}}return s},fromJSON:e=>({sid:isSet$1(e.sid)?String(e.sid):"",level:isSet$1(e.level)?Number(e.level):0,active:!!isSet$1(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},fromPartial(e){var t,i,n;const s={sid:"",level:0,active:!1};return s.sid=null!==(t=e.sid)&&void 0!==t?t:"",s.level=null!==(i=e.level)&&void 0!==i?i:0,s.active=null!==(n=e.active)&&void 0!==n&&n,s}};function createBaseUserPacket(){return{participantSid:"",payload:new Uint8Array,destinationSids:[]}}const xe={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Ee.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 t},decode(e,t){const i=e instanceof Ee.Reader?e:new Ee.Reader(e);let n=void 0===t?i.len:i.pos+t;const s=createBaseUserPacket();for(;i.pos>>3){case 1:s.participantSid=i.string();break;case 2:s.payload=i.bytes();break;case 3:s.destinationSids.push(i.string());break;default:i.skipType(7&e)}}return s},fromJSON:e=>({participantSid:isSet$1(e.participantSid)?String(e.participantSid):"",payload:isSet$1(e.payload)?bytesFromBase64(e.payload):new Uint8Array,destinationSids:Array.isArray(null==e?void 0:e.destinationSids)?e.destinationSids.map((e=>String(e))):[]}),toJSON(e){const t={};return void 0!==e.participantSid&&(t.participantSid=e.participantSid),void 0!==e.payload&&(t.payload=function base64FromBytes(e){const t=[];return e.forEach((e=>{t.push(String.fromCharCode(e))})),We(t.join(""))}(void 0!==e.payload?e.payload:new Uint8Array)),e.destinationSids?t.destinationSids=e.destinationSids.map((e=>e)):t.destinationSids=[],t},fromPartial(e){var t,i,n;const s=createBaseUserPacket();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}};const Be={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Ee.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 Ee.Reader?e:new Ee.Reader(e);let n=void 0===t?i.len:i.pos+t;const s={participantSid:"",trackSids:[]};for(;i.pos>>3){case 1:s.participantSid=i.string();break;case 2:s.trackSids.push(i.string());break;default:i.skipType(7&e)}}return s},fromJSON:e=>({participantSid:isSet$1(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},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 Je={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Ee.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),t},decode(e,t){const i=e instanceof Ee.Reader?e:new Ee.Reader(e);let n=void 0===t?i.len:i.pos+t;const s={sdk:0,version:"",protocol:0,os:"",osVersion:"",deviceModel:"",browser:"",browserVersion:"",address:""};for(;i.pos>>3){case 1:s.sdk=i.int32();break;case 2:s.version=i.string();break;case 3:s.protocol=i.int32();break;case 4:s.os=i.string();break;case 5:s.osVersion=i.string();break;case 6:s.deviceModel=i.string();break;case 7:s.browser=i.string();break;case 8:s.browserVersion=i.string();break;case 9:s.address=i.string();break;default:i.skipType(7&e)}}return s},fromJSON:e=>({sdk:isSet$1(e.sdk)?clientInfo_SDKFromJSON(e.sdk):0,version:isSet$1(e.version)?String(e.version):"",protocol:isSet$1(e.protocol)?Number(e.protocol):0,os:isSet$1(e.os)?String(e.os):"",osVersion:isSet$1(e.osVersion)?String(e.osVersion):"",deviceModel:isSet$1(e.deviceModel)?String(e.deviceModel):"",browser:isSet$1(e.browser)?String(e.browser):"",browserVersion:isSet$1(e.browserVersion)?String(e.browserVersion):"",address:isSet$1(e.address)?String(e.address):""}),toJSON(e){const t={};return void 0!==e.sdk&&(t.sdk=function clientInfo_SDKToJSON(e){switch(e){case Pe.UNKNOWN:return"UNKNOWN";case Pe.JS:return"JS";case Pe.SWIFT:return"SWIFT";case Pe.ANDROID:return"ANDROID";case Pe.FLUTTER:return"FLUTTER";case Pe.GO:return"GO";case Pe.UNITY:return"UNITY";default:return"UNKNOWN"}}(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),t},fromPartial(e){var t,i,n,s,a,o,c,u,l;const h={sdk:0,version:"",protocol:0,os:"",osVersion:"",deviceModel:"",browser:"",browserVersion:"",address:""};return h.sdk=null!==(t=e.sdk)&&void 0!==t?t:0,h.version=null!==(i=e.version)&&void 0!==i?i:"",h.protocol=null!==(n=e.protocol)&&void 0!==n?n:0,h.os=null!==(s=e.os)&&void 0!==s?s:"",h.osVersion=null!==(a=e.osVersion)&&void 0!==a?a:"",h.deviceModel=null!==(o=e.deviceModel)&&void 0!==o?o:"",h.browser=null!==(c=e.browser)&&void 0!==c?c:"",h.browserVersion=null!==(u=e.browserVersion)&&void 0!==u?u:"",h.address=null!==(l=e.address)&&void 0!==l?l:"",h}};const Fe={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Ee.Writer.create();return void 0!==e.video&&Ve.encode(e.video,t.uint32(10).fork()).ldelim(),void 0!==e.screen&&Ve.encode(e.screen,t.uint32(18).fork()).ldelim(),0!==e.resumeConnection&&t.uint32(24).int32(e.resumeConnection),t},decode(e,t){const i=e instanceof Ee.Reader?e:new Ee.Reader(e);let n=void 0===t?i.len:i.pos+t;const s={video:void 0,screen:void 0,resumeConnection:0};for(;i.pos>>3){case 1:s.video=Ve.decode(i,i.uint32());break;case 2:s.screen=Ve.decode(i,i.uint32());break;case 3:s.resumeConnection=i.int32();break;default:i.skipType(7&e)}}return s},fromJSON:e=>({video:isSet$1(e.video)?Ve.fromJSON(e.video):void 0,screen:isSet$1(e.screen)?Ve.fromJSON(e.screen):void 0,resumeConnection:isSet$1(e.resumeConnection)?clientConfigSettingFromJSON(e.resumeConnection):0}),toJSON(e){const t={};return void 0!==e.video&&(t.video=e.video?Ve.toJSON(e.video):void 0),void 0!==e.screen&&(t.screen=e.screen?Ve.toJSON(e.screen):void 0),void 0!==e.resumeConnection&&(t.resumeConnection=clientConfigSettingToJSON(e.resumeConnection)),t},fromPartial(e){var t;const i={video:void 0,screen:void 0,resumeConnection:0};return i.video=void 0!==e.video&&null!==e.video?Ve.fromPartial(e.video):void 0,i.screen=void 0!==e.screen&&null!==e.screen?Ve.fromPartial(e.screen):void 0,i.resumeConnection=null!==(t=e.resumeConnection)&&void 0!==t?t:0,i}};const Ve={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Ee.Writer.create();return 0!==e.hardwareEncoder&&t.uint32(8).int32(e.hardwareEncoder),t},decode(e,t){const i=e instanceof Ee.Reader?e:new Ee.Reader(e);let n=void 0===t?i.len:i.pos+t;const s={hardwareEncoder:0};for(;i.pos>>3==1)s.hardwareEncoder=i.int32();else i.skipType(7&e)}return s},fromJSON:e=>({hardwareEncoder:isSet$1(e.hardwareEncoder)?clientConfigSettingFromJSON(e.hardwareEncoder):0}),toJSON(e){const t={};return void 0!==e.hardwareEncoder&&(t.hardwareEncoder=clientConfigSettingToJSON(e.hardwareEncoder)),t},fromPartial(e){var t;const i={hardwareEncoder:0};return i.hardwareEncoder=null!==(t=e.hardwareEncoder)&&void 0!==t?t:0,i}};var je=(()=>{if(void 0!==je)return je;if("undefined"!=typeof self)return self;if("undefined"!=typeof window)return window;if("undefined"!=typeof global)return global;throw"Unable to locate global object"})();const qe=je.atob||(e=>je.Buffer.from(e,"base64").toString("binary"));function bytesFromBase64(e){const t=qe(e),i=new Uint8Array(t.length);for(let e=0;eje.Buffer.from(e,"binary").toString("base64"));function longToNumber(e){if(e.gt(Number.MAX_SAFE_INTEGER))throw new je.Error("Value is larger than Number.MAX_SAFE_INTEGER");return e.toNumber()}function isSet$1(e){return null!=e}function ownKeys(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function _objectSpread2(e){for(var t=1;t1&&void 0!==arguments[1]?arguments[1]:Ee.Writer.create();return void 0!==e.offer&&tt.encode(e.offer,t.uint32(10).fork()).ldelim(),void 0!==e.answer&&tt.encode(e.answer,t.uint32(18).fork()).ldelim(),void 0!==e.trickle&&ze.encode(e.trickle,t.uint32(26).fork()).ldelim(),void 0!==e.addTrack&&Ke.encode(e.addTrack,t.uint32(34).fork()).ldelim(),void 0!==e.mute&&Ze.encode(e.mute,t.uint32(42).fork()).ldelim(),void 0!==e.subscription&&rt.encode(e.subscription,t.uint32(50).fork()).ldelim(),void 0!==e.trackSetting&&nt.encode(e.trackSetting,t.uint32(58).fork()).ldelim(),void 0!==e.leave&&st.encode(e.leave,t.uint32(66).fork()).ldelim(),void 0!==e.updateLayers&&at.encode(e.updateLayers,t.uint32(82).fork()).ldelim(),void 0!==e.subscriptionPermission&>.encode(e.subscriptionPermission,t.uint32(90).fork()).ldelim(),void 0!==e.syncState&&bt.encode(e.syncState,t.uint32(98).fork()).ldelim(),void 0!==e.simulate&&yt.encode(e.simulate,t.uint32(106).fork()).ldelim(),t},decode(e,t){const i=e instanceof Ee.Reader?e:new Ee.Reader(e);let n=void 0===t?i.len:i.pos+t;const s={offer:void 0,answer:void 0,trickle:void 0,addTrack:void 0,mute:void 0,subscription:void 0,trackSetting:void 0,leave:void 0,updateLayers:void 0,subscriptionPermission:void 0,syncState:void 0,simulate:void 0};for(;i.pos>>3){case 1:s.offer=tt.decode(i,i.uint32());break;case 2:s.answer=tt.decode(i,i.uint32());break;case 3:s.trickle=ze.decode(i,i.uint32());break;case 4:s.addTrack=Ke.decode(i,i.uint32());break;case 5:s.mute=Ze.decode(i,i.uint32());break;case 6:s.subscription=rt.decode(i,i.uint32());break;case 7:s.trackSetting=nt.decode(i,i.uint32());break;case 8:s.leave=st.decode(i,i.uint32());break;case 10:s.updateLayers=at.decode(i,i.uint32());break;case 11:s.subscriptionPermission=gt.decode(i,i.uint32());break;case 12:s.syncState=bt.decode(i,i.uint32());break;case 13:s.simulate=yt.decode(i,i.uint32());break;default:i.skipType(7&e)}}return s},fromJSON:e=>({offer:isSet(e.offer)?tt.fromJSON(e.offer):void 0,answer:isSet(e.answer)?tt.fromJSON(e.answer):void 0,trickle:isSet(e.trickle)?ze.fromJSON(e.trickle):void 0,addTrack:isSet(e.addTrack)?Ke.fromJSON(e.addTrack):void 0,mute:isSet(e.mute)?Ze.fromJSON(e.mute):void 0,subscription:isSet(e.subscription)?rt.fromJSON(e.subscription):void 0,trackSetting:isSet(e.trackSetting)?nt.fromJSON(e.trackSetting):void 0,leave:isSet(e.leave)?st.fromJSON(e.leave):void 0,updateLayers:isSet(e.updateLayers)?at.fromJSON(e.updateLayers):void 0,subscriptionPermission:isSet(e.subscriptionPermission)?gt.fromJSON(e.subscriptionPermission):void 0,syncState:isSet(e.syncState)?bt.fromJSON(e.syncState):void 0,simulate:isSet(e.simulate)?yt.fromJSON(e.simulate):void 0}),toJSON(e){const t={};return void 0!==e.offer&&(t.offer=e.offer?tt.toJSON(e.offer):void 0),void 0!==e.answer&&(t.answer=e.answer?tt.toJSON(e.answer):void 0),void 0!==e.trickle&&(t.trickle=e.trickle?ze.toJSON(e.trickle):void 0),void 0!==e.addTrack&&(t.addTrack=e.addTrack?Ke.toJSON(e.addTrack):void 0),void 0!==e.mute&&(t.mute=e.mute?Ze.toJSON(e.mute):void 0),void 0!==e.subscription&&(t.subscription=e.subscription?rt.toJSON(e.subscription):void 0),void 0!==e.trackSetting&&(t.trackSetting=e.trackSetting?nt.toJSON(e.trackSetting):void 0),void 0!==e.leave&&(t.leave=e.leave?st.toJSON(e.leave):void 0),void 0!==e.updateLayers&&(t.updateLayers=e.updateLayers?at.toJSON(e.updateLayers):void 0),void 0!==e.subscriptionPermission&&(t.subscriptionPermission=e.subscriptionPermission?gt.toJSON(e.subscriptionPermission):void 0),void 0!==e.syncState&&(t.syncState=e.syncState?bt.toJSON(e.syncState):void 0),void 0!==e.simulate&&(t.simulate=e.simulate?yt.toJSON(e.simulate):void 0),t},fromPartial(e){const t={offer:void 0,answer:void 0,trickle:void 0,addTrack:void 0,mute:void 0,subscription:void 0,trackSetting:void 0,leave:void 0,updateLayers:void 0,subscriptionPermission:void 0,syncState:void 0,simulate:void 0};return t.offer=void 0!==e.offer&&null!==e.offer?tt.fromPartial(e.offer):void 0,t.answer=void 0!==e.answer&&null!==e.answer?tt.fromPartial(e.answer):void 0,t.trickle=void 0!==e.trickle&&null!==e.trickle?ze.fromPartial(e.trickle):void 0,t.addTrack=void 0!==e.addTrack&&null!==e.addTrack?Ke.fromPartial(e.addTrack):void 0,t.mute=void 0!==e.mute&&null!==e.mute?Ze.fromPartial(e.mute):void 0,t.subscription=void 0!==e.subscription&&null!==e.subscription?rt.fromPartial(e.subscription):void 0,t.trackSetting=void 0!==e.trackSetting&&null!==e.trackSetting?nt.fromPartial(e.trackSetting):void 0,t.leave=void 0!==e.leave&&null!==e.leave?st.fromPartial(e.leave):void 0,t.updateLayers=void 0!==e.updateLayers&&null!==e.updateLayers?at.fromPartial(e.updateLayers):void 0,t.subscriptionPermission=void 0!==e.subscriptionPermission&&null!==e.subscriptionPermission?gt.fromPartial(e.subscriptionPermission):void 0,t.syncState=void 0!==e.syncState&&null!==e.syncState?bt.fromPartial(e.syncState):void 0,t.simulate=void 0!==e.simulate&&null!==e.simulate?yt.fromPartial(e.simulate):void 0,t}};const He={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Ee.Writer.create();return void 0!==e.join&&Ye.encode(e.join,t.uint32(10).fork()).ldelim(),void 0!==e.answer&&tt.encode(e.answer,t.uint32(18).fork()).ldelim(),void 0!==e.offer&&tt.encode(e.offer,t.uint32(26).fork()).ldelim(),void 0!==e.trickle&&ze.encode(e.trickle,t.uint32(34).fork()).ldelim(),void 0!==e.update&&it.encode(e.update,t.uint32(42).fork()).ldelim(),void 0!==e.trackPublished&&Xe.encode(e.trackPublished,t.uint32(50).fork()).ldelim(),void 0!==e.leave&&st.encode(e.leave,t.uint32(66).fork()).ldelim(),void 0!==e.mute&&Ze.encode(e.mute,t.uint32(74).fork()).ldelim(),void 0!==e.speakersChanged&&ct.encode(e.speakersChanged,t.uint32(82).fork()).ldelim(),void 0!==e.roomUpdate&&dt.encode(e.roomUpdate,t.uint32(90).fork()).ldelim(),void 0!==e.connectionQuality&<.encode(e.connectionQuality,t.uint32(98).fork()).ldelim(),void 0!==e.streamStateUpdate&&pt.encode(e.streamStateUpdate,t.uint32(106).fork()).ldelim(),void 0!==e.subscribedQualityUpdate&&ft.encode(e.subscribedQualityUpdate,t.uint32(114).fork()).ldelim(),void 0!==e.subscriptionPermissionUpdate&&St.encode(e.subscriptionPermissionUpdate,t.uint32(122).fork()).ldelim(),void 0!==e.refreshToken&&t.uint32(130).string(e.refreshToken),void 0!==e.trackUnpublished&&et.encode(e.trackUnpublished,t.uint32(138).fork()).ldelim(),t},decode(e,t){const i=e instanceof Ee.Reader?e:new Ee.Reader(e);let n=void 0===t?i.len:i.pos+t;const s={join:void 0,answer:void 0,offer:void 0,trickle:void 0,update:void 0,trackPublished:void 0,leave:void 0,mute:void 0,speakersChanged:void 0,roomUpdate:void 0,connectionQuality:void 0,streamStateUpdate:void 0,subscribedQualityUpdate:void 0,subscriptionPermissionUpdate:void 0,refreshToken:void 0,trackUnpublished:void 0};for(;i.pos>>3){case 1:s.join=Ye.decode(i,i.uint32());break;case 2:s.answer=tt.decode(i,i.uint32());break;case 3:s.offer=tt.decode(i,i.uint32());break;case 4:s.trickle=ze.decode(i,i.uint32());break;case 5:s.update=it.decode(i,i.uint32());break;case 6:s.trackPublished=Xe.decode(i,i.uint32());break;case 8:s.leave=st.decode(i,i.uint32());break;case 9:s.mute=Ze.decode(i,i.uint32());break;case 10:s.speakersChanged=ct.decode(i,i.uint32());break;case 11:s.roomUpdate=dt.decode(i,i.uint32());break;case 12:s.connectionQuality=lt.decode(i,i.uint32());break;case 13:s.streamStateUpdate=pt.decode(i,i.uint32());break;case 14:s.subscribedQualityUpdate=ft.decode(i,i.uint32());break;case 15:s.subscriptionPermissionUpdate=St.decode(i,i.uint32());break;case 16:s.refreshToken=i.string();break;case 17:s.trackUnpublished=et.decode(i,i.uint32());break;default:i.skipType(7&e)}}return s},fromJSON:e=>({join:isSet(e.join)?Ye.fromJSON(e.join):void 0,answer:isSet(e.answer)?tt.fromJSON(e.answer):void 0,offer:isSet(e.offer)?tt.fromJSON(e.offer):void 0,trickle:isSet(e.trickle)?ze.fromJSON(e.trickle):void 0,update:isSet(e.update)?it.fromJSON(e.update):void 0,trackPublished:isSet(e.trackPublished)?Xe.fromJSON(e.trackPublished):void 0,leave:isSet(e.leave)?st.fromJSON(e.leave):void 0,mute:isSet(e.mute)?Ze.fromJSON(e.mute):void 0,speakersChanged:isSet(e.speakersChanged)?ct.fromJSON(e.speakersChanged):void 0,roomUpdate:isSet(e.roomUpdate)?dt.fromJSON(e.roomUpdate):void 0,connectionQuality:isSet(e.connectionQuality)?lt.fromJSON(e.connectionQuality):void 0,streamStateUpdate:isSet(e.streamStateUpdate)?pt.fromJSON(e.streamStateUpdate):void 0,subscribedQualityUpdate:isSet(e.subscribedQualityUpdate)?ft.fromJSON(e.subscribedQualityUpdate):void 0,subscriptionPermissionUpdate:isSet(e.subscriptionPermissionUpdate)?St.fromJSON(e.subscriptionPermissionUpdate):void 0,refreshToken:isSet(e.refreshToken)?String(e.refreshToken):void 0,trackUnpublished:isSet(e.trackUnpublished)?et.fromJSON(e.trackUnpublished):void 0}),toJSON(e){const t={};return void 0!==e.join&&(t.join=e.join?Ye.toJSON(e.join):void 0),void 0!==e.answer&&(t.answer=e.answer?tt.toJSON(e.answer):void 0),void 0!==e.offer&&(t.offer=e.offer?tt.toJSON(e.offer):void 0),void 0!==e.trickle&&(t.trickle=e.trickle?ze.toJSON(e.trickle):void 0),void 0!==e.update&&(t.update=e.update?it.toJSON(e.update):void 0),void 0!==e.trackPublished&&(t.trackPublished=e.trackPublished?Xe.toJSON(e.trackPublished):void 0),void 0!==e.leave&&(t.leave=e.leave?st.toJSON(e.leave):void 0),void 0!==e.mute&&(t.mute=e.mute?Ze.toJSON(e.mute):void 0),void 0!==e.speakersChanged&&(t.speakersChanged=e.speakersChanged?ct.toJSON(e.speakersChanged):void 0),void 0!==e.roomUpdate&&(t.roomUpdate=e.roomUpdate?dt.toJSON(e.roomUpdate):void 0),void 0!==e.connectionQuality&&(t.connectionQuality=e.connectionQuality?lt.toJSON(e.connectionQuality):void 0),void 0!==e.streamStateUpdate&&(t.streamStateUpdate=e.streamStateUpdate?pt.toJSON(e.streamStateUpdate):void 0),void 0!==e.subscribedQualityUpdate&&(t.subscribedQualityUpdate=e.subscribedQualityUpdate?ft.toJSON(e.subscribedQualityUpdate):void 0),void 0!==e.subscriptionPermissionUpdate&&(t.subscriptionPermissionUpdate=e.subscriptionPermissionUpdate?St.toJSON(e.subscriptionPermissionUpdate):void 0),void 0!==e.refreshToken&&(t.refreshToken=e.refreshToken),void 0!==e.trackUnpublished&&(t.trackUnpublished=e.trackUnpublished?et.toJSON(e.trackUnpublished):void 0),t},fromPartial(e){var t;const i={join:void 0,answer:void 0,offer:void 0,trickle:void 0,update:void 0,trackPublished:void 0,leave:void 0,mute:void 0,speakersChanged:void 0,roomUpdate:void 0,connectionQuality:void 0,streamStateUpdate:void 0,subscribedQualityUpdate:void 0,subscriptionPermissionUpdate:void 0,refreshToken:void 0,trackUnpublished:void 0};return i.join=void 0!==e.join&&null!==e.join?Ye.fromPartial(e.join):void 0,i.answer=void 0!==e.answer&&null!==e.answer?tt.fromPartial(e.answer):void 0,i.offer=void 0!==e.offer&&null!==e.offer?tt.fromPartial(e.offer):void 0,i.trickle=void 0!==e.trickle&&null!==e.trickle?ze.fromPartial(e.trickle):void 0,i.update=void 0!==e.update&&null!==e.update?it.fromPartial(e.update):void 0,i.trackPublished=void 0!==e.trackPublished&&null!==e.trackPublished?Xe.fromPartial(e.trackPublished):void 0,i.leave=void 0!==e.leave&&null!==e.leave?st.fromPartial(e.leave):void 0,i.mute=void 0!==e.mute&&null!==e.mute?Ze.fromPartial(e.mute):void 0,i.speakersChanged=void 0!==e.speakersChanged&&null!==e.speakersChanged?ct.fromPartial(e.speakersChanged):void 0,i.roomUpdate=void 0!==e.roomUpdate&&null!==e.roomUpdate?dt.fromPartial(e.roomUpdate):void 0,i.connectionQuality=void 0!==e.connectionQuality&&null!==e.connectionQuality?lt.fromPartial(e.connectionQuality):void 0,i.streamStateUpdate=void 0!==e.streamStateUpdate&&null!==e.streamStateUpdate?pt.fromPartial(e.streamStateUpdate):void 0,i.subscribedQualityUpdate=void 0!==e.subscribedQualityUpdate&&null!==e.subscribedQualityUpdate?ft.fromPartial(e.subscribedQualityUpdate):void 0,i.subscriptionPermissionUpdate=void 0!==e.subscriptionPermissionUpdate&&null!==e.subscriptionPermissionUpdate?St.fromPartial(e.subscriptionPermissionUpdate):void 0,i.refreshToken=null!==(t=e.refreshToken)&&void 0!==t?t:void 0,i.trackUnpublished=void 0!==e.trackUnpublished&&null!==e.trackUnpublished?et.fromPartial(e.trackUnpublished):void 0,i}};const Ke={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Ee.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)Ae.encode(i,t.uint32(74).fork()).ldelim();return t},decode(e,t){const i=e instanceof Ee.Reader?e:new Ee.Reader(e);let n=void 0===t?i.len:i.pos+t;const s={cid:"",name:"",type:0,width:0,height:0,muted:!1,disableDtx:!1,source:0,layers:[]};for(;i.pos>>3){case 1:s.cid=i.string();break;case 2:s.name=i.string();break;case 3:s.type=i.int32();break;case 4:s.width=i.uint32();break;case 5:s.height=i.uint32();break;case 6:s.muted=i.bool();break;case 7:s.disableDtx=i.bool();break;case 8:s.source=i.int32();break;case 9:s.layers.push(Ae.decode(i,i.uint32()));break;default:i.skipType(7&e)}}return s},fromJSON:e=>({cid:isSet(e.cid)?String(e.cid):"",name:isSet(e.name)?String(e.name):"",type:isSet(e.type)?trackTypeFromJSON(e.type):0,width:isSet(e.width)?Number(e.width):0,height:isSet(e.height)?Number(e.height):0,muted:!!isSet(e.muted)&&Boolean(e.muted),disableDtx:!!isSet(e.disableDtx)&&Boolean(e.disableDtx),source:isSet(e.source)?trackSourceFromJSON(e.source):0,layers:Array.isArray(null==e?void 0:e.layers)?e.layers.map((e=>Ae.fromJSON(e))):[]}),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=trackTypeToJSON(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=trackSourceToJSON(e.source)),e.layers?t.layers=e.layers.map((e=>e?Ae.toJSON(e):void 0)):t.layers=[],t},fromPartial(e){var t,i,n,s,a,o,c,u,l;const h={cid:"",name:"",type:0,width:0,height:0,muted:!1,disableDtx:!1,source:0,layers:[]};return h.cid=null!==(t=e.cid)&&void 0!==t?t:"",h.name=null!==(i=e.name)&&void 0!==i?i:"",h.type=null!==(n=e.type)&&void 0!==n?n:0,h.width=null!==(s=e.width)&&void 0!==s?s:0,h.height=null!==(a=e.height)&&void 0!==a?a:0,h.muted=null!==(o=e.muted)&&void 0!==o&&o,h.disableDtx=null!==(c=e.disableDtx)&&void 0!==c&&c,h.source=null!==(u=e.source)&&void 0!==u?u:0,h.layers=(null===(l=e.layers)||void 0===l?void 0:l.map((e=>Ae.fromPartial(e))))||[],h}};const ze={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Ee.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 Ee.Reader?e:new Ee.Reader(e);let n=void 0===t?i.len:i.pos+t;const s={candidateInit:"",target:0};for(;i.pos>>3){case 1:s.candidateInit=i.string();break;case 2:s.target=i.int32();break;default:i.skipType(7&e)}}return s},fromJSON:e=>({candidateInit:isSet(e.candidateInit)?String(e.candidateInit):"",target:isSet(e.target)?signalTargetFromJSON(e.target):0}),toJSON(e){const t={};return void 0!==e.candidateInit&&(t.candidateInit=e.candidateInit),void 0!==e.target&&(t.target=signalTargetToJSON(e.target)),t},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 Ze={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Ee.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 Ee.Reader?e:new Ee.Reader(e);let n=void 0===t?i.len:i.pos+t;const s={sid:"",muted:!1};for(;i.pos>>3){case 1:s.sid=i.string();break;case 2:s.muted=i.bool();break;default:i.skipType(7&e)}}return s},fromJSON:e=>({sid:isSet(e.sid)?String(e.sid):"",muted:!!isSet(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},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}};const Ye={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Ee.Writer.create();void 0!==e.room&&Oe.encode(e.room,t.uint32(10).fork()).ldelim(),void 0!==e.participant&&Le.encode(e.participant,t.uint32(18).fork()).ldelim();for(const i of e.otherParticipants)Le.encode(i,t.uint32(26).fork()).ldelim();""!==e.serverVersion&&t.uint32(34).string(e.serverVersion);for(const i of e.iceServers)ot.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&&Fe.encode(e.clientConfiguration,t.uint32(66).fork()).ldelim(),""!==e.serverRegion&&t.uint32(74).string(e.serverRegion),t},decode(e,t){const i=e instanceof Ee.Reader?e:new Ee.Reader(e);let n=void 0===t?i.len:i.pos+t;const s={room:void 0,participant:void 0,otherParticipants:[],serverVersion:"",iceServers:[],subscriberPrimary:!1,alternativeUrl:"",clientConfiguration:void 0,serverRegion:""};for(;i.pos>>3){case 1:s.room=Oe.decode(i,i.uint32());break;case 2:s.participant=Le.decode(i,i.uint32());break;case 3:s.otherParticipants.push(Le.decode(i,i.uint32()));break;case 4:s.serverVersion=i.string();break;case 5:s.iceServers.push(ot.decode(i,i.uint32()));break;case 6:s.subscriberPrimary=i.bool();break;case 7:s.alternativeUrl=i.string();break;case 8:s.clientConfiguration=Fe.decode(i,i.uint32());break;case 9:s.serverRegion=i.string();break;default:i.skipType(7&e)}}return s},fromJSON:e=>({room:isSet(e.room)?Oe.fromJSON(e.room):void 0,participant:isSet(e.participant)?Le.fromJSON(e.participant):void 0,otherParticipants:Array.isArray(null==e?void 0:e.otherParticipants)?e.otherParticipants.map((e=>Le.fromJSON(e))):[],serverVersion:isSet(e.serverVersion)?String(e.serverVersion):"",iceServers:Array.isArray(null==e?void 0:e.iceServers)?e.iceServers.map((e=>ot.fromJSON(e))):[],subscriberPrimary:!!isSet(e.subscriberPrimary)&&Boolean(e.subscriberPrimary),alternativeUrl:isSet(e.alternativeUrl)?String(e.alternativeUrl):"",clientConfiguration:isSet(e.clientConfiguration)?Fe.fromJSON(e.clientConfiguration):void 0,serverRegion:isSet(e.serverRegion)?String(e.serverRegion):""}),toJSON(e){const t={};return void 0!==e.room&&(t.room=e.room?Oe.toJSON(e.room):void 0),void 0!==e.participant&&(t.participant=e.participant?Le.toJSON(e.participant):void 0),e.otherParticipants?t.otherParticipants=e.otherParticipants.map((e=>e?Le.toJSON(e):void 0)):t.otherParticipants=[],void 0!==e.serverVersion&&(t.serverVersion=e.serverVersion),e.iceServers?t.iceServers=e.iceServers.map((e=>e?ot.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?Fe.toJSON(e.clientConfiguration):void 0),void 0!==e.serverRegion&&(t.serverRegion=e.serverRegion),t},fromPartial(e){var t,i,n,s,a,o;const c={room:void 0,participant:void 0,otherParticipants:[],serverVersion:"",iceServers:[],subscriberPrimary:!1,alternativeUrl:"",clientConfiguration:void 0,serverRegion:""};return c.room=void 0!==e.room&&null!==e.room?Oe.fromPartial(e.room):void 0,c.participant=void 0!==e.participant&&null!==e.participant?Le.fromPartial(e.participant):void 0,c.otherParticipants=(null===(t=e.otherParticipants)||void 0===t?void 0:t.map((e=>Le.fromPartial(e))))||[],c.serverVersion=null!==(i=e.serverVersion)&&void 0!==i?i:"",c.iceServers=(null===(n=e.iceServers)||void 0===n?void 0:n.map((e=>ot.fromPartial(e))))||[],c.subscriberPrimary=null!==(s=e.subscriberPrimary)&&void 0!==s&&s,c.alternativeUrl=null!==(a=e.alternativeUrl)&&void 0!==a?a:"",c.clientConfiguration=void 0!==e.clientConfiguration&&null!==e.clientConfiguration?Fe.fromPartial(e.clientConfiguration):void 0,c.serverRegion=null!==(o=e.serverRegion)&&void 0!==o?o:"",c}};const Xe={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Ee.Writer.create();return""!==e.cid&&t.uint32(10).string(e.cid),void 0!==e.track&&De.encode(e.track,t.uint32(18).fork()).ldelim(),t},decode(e,t){const i=e instanceof Ee.Reader?e:new Ee.Reader(e);let n=void 0===t?i.len:i.pos+t;const s={cid:"",track:void 0};for(;i.pos>>3){case 1:s.cid=i.string();break;case 2:s.track=De.decode(i,i.uint32());break;default:i.skipType(7&e)}}return s},fromJSON:e=>({cid:isSet(e.cid)?String(e.cid):"",track:isSet(e.track)?De.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?De.toJSON(e.track):void 0),t},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?De.fromPartial(e.track):void 0,i}};const et={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Ee.Writer.create();return""!==e.trackSid&&t.uint32(10).string(e.trackSid),t},decode(e,t){const i=e instanceof Ee.Reader?e:new Ee.Reader(e);let n=void 0===t?i.len:i.pos+t;const s={trackSid:""};for(;i.pos>>3==1)s.trackSid=i.string();else i.skipType(7&e)}return s},fromJSON:e=>({trackSid:isSet(e.trackSid)?String(e.trackSid):""}),toJSON(e){const t={};return void 0!==e.trackSid&&(t.trackSid=e.trackSid),t},fromPartial(e){var t;const i={trackSid:""};return i.trackSid=null!==(t=e.trackSid)&&void 0!==t?t:"",i}};const tt={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Ee.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 Ee.Reader?e:new Ee.Reader(e);let n=void 0===t?i.len:i.pos+t;const s={type:"",sdp:""};for(;i.pos>>3){case 1:s.type=i.string();break;case 2:s.sdp=i.string();break;default:i.skipType(7&e)}}return s},fromJSON:e=>({type:isSet(e.type)?String(e.type):"",sdp:isSet(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},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 it={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Ee.Writer.create();for(const i of e.participants)Le.encode(i,t.uint32(10).fork()).ldelim();return t},decode(e,t){const i=e instanceof Ee.Reader?e:new Ee.Reader(e);let n=void 0===t?i.len:i.pos+t;const s={participants:[]};for(;i.pos>>3==1)s.participants.push(Le.decode(i,i.uint32()));else i.skipType(7&e)}return s},fromJSON:e=>({participants:Array.isArray(null==e?void 0:e.participants)?e.participants.map((e=>Le.fromJSON(e))):[]}),toJSON(e){const t={};return e.participants?t.participants=e.participants.map((e=>e?Le.toJSON(e):void 0)):t.participants=[],t},fromPartial(e){var t;const i={participants:[]};return i.participants=(null===(t=e.participants)||void 0===t?void 0:t.map((e=>Le.fromPartial(e))))||[],i}};const rt={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Ee.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)Be.encode(i,t.uint32(26).fork()).ldelim();return t},decode(e,t){const i=e instanceof Ee.Reader?e:new Ee.Reader(e);let n=void 0===t?i.len:i.pos+t;const s={trackSids:[],subscribe:!1,participantTracks:[]};for(;i.pos>>3){case 1:s.trackSids.push(i.string());break;case 2:s.subscribe=i.bool();break;case 3:s.participantTracks.push(Be.decode(i,i.uint32()));break;default:i.skipType(7&e)}}return s},fromJSON:e=>({trackSids:Array.isArray(null==e?void 0:e.trackSids)?e.trackSids.map((e=>String(e))):[],subscribe:!!isSet(e.subscribe)&&Boolean(e.subscribe),participantTracks:Array.isArray(null==e?void 0:e.participantTracks)?e.participantTracks.map((e=>Be.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?Be.toJSON(e):void 0)):t.participantTracks=[],t},fromPartial(e){var t,i,n;const s={trackSids:[],subscribe:!1,participantTracks:[]};return s.trackSids=(null===(t=e.trackSids)||void 0===t?void 0:t.map((e=>e)))||[],s.subscribe=null!==(i=e.subscribe)&&void 0!==i&&i,s.participantTracks=(null===(n=e.participantTracks)||void 0===n?void 0:n.map((e=>Be.fromPartial(e))))||[],s}};const nt={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Ee.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),t},decode(e,t){const i=e instanceof Ee.Reader?e:new Ee.Reader(e);let n=void 0===t?i.len:i.pos+t;const s={trackSids:[],disabled:!1,quality:0,width:0,height:0};for(;i.pos>>3){case 1:s.trackSids.push(i.string());break;case 3:s.disabled=i.bool();break;case 4:s.quality=i.int32();break;case 5:s.width=i.uint32();break;case 6:s.height=i.uint32();break;default:i.skipType(7&e)}}return s},fromJSON:e=>({trackSids:Array.isArray(null==e?void 0:e.trackSids)?e.trackSids.map((e=>String(e))):[],disabled:!!isSet(e.disabled)&&Boolean(e.disabled),quality:isSet(e.quality)?videoQualityFromJSON(e.quality):0,width:isSet(e.width)?Number(e.width):0,height:isSet(e.height)?Number(e.height):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=videoQualityToJSON(e.quality)),void 0!==e.width&&(t.width=Math.round(e.width)),void 0!==e.height&&(t.height=Math.round(e.height)),t},fromPartial(e){var t,i,n,s,a;const o={trackSids:[],disabled:!1,quality:0,width:0,height:0};return o.trackSids=(null===(t=e.trackSids)||void 0===t?void 0:t.map((e=>e)))||[],o.disabled=null!==(i=e.disabled)&&void 0!==i&&i,o.quality=null!==(n=e.quality)&&void 0!==n?n:0,o.width=null!==(s=e.width)&&void 0!==s?s:0,o.height=null!==(a=e.height)&&void 0!==a?a:0,o}};const st={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Ee.Writer.create();return!0===e.canReconnect&&t.uint32(8).bool(e.canReconnect),t},decode(e,t){const i=e instanceof Ee.Reader?e:new Ee.Reader(e);let n=void 0===t?i.len:i.pos+t;const s={canReconnect:!1};for(;i.pos>>3==1)s.canReconnect=i.bool();else i.skipType(7&e)}return s},fromJSON:e=>({canReconnect:!!isSet(e.canReconnect)&&Boolean(e.canReconnect)}),toJSON(e){const t={};return void 0!==e.canReconnect&&(t.canReconnect=e.canReconnect),t},fromPartial(e){var t;const i={canReconnect:!1};return i.canReconnect=null!==(t=e.canReconnect)&&void 0!==t&&t,i}};const at={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Ee.Writer.create();""!==e.trackSid&&t.uint32(10).string(e.trackSid);for(const i of e.layers)Ae.encode(i,t.uint32(18).fork()).ldelim();return t},decode(e,t){const i=e instanceof Ee.Reader?e:new Ee.Reader(e);let n=void 0===t?i.len:i.pos+t;const s={trackSid:"",layers:[]};for(;i.pos>>3){case 1:s.trackSid=i.string();break;case 2:s.layers.push(Ae.decode(i,i.uint32()));break;default:i.skipType(7&e)}}return s},fromJSON:e=>({trackSid:isSet(e.trackSid)?String(e.trackSid):"",layers:Array.isArray(null==e?void 0:e.layers)?e.layers.map((e=>Ae.fromJSON(e))):[]}),toJSON(e){const t={};return void 0!==e.trackSid&&(t.trackSid=e.trackSid),e.layers?t.layers=e.layers.map((e=>e?Ae.toJSON(e):void 0)):t.layers=[],t},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=>Ae.fromPartial(e))))||[],n}};const ot={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Ee.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 Ee.Reader?e:new Ee.Reader(e);let n=void 0===t?i.len:i.pos+t;const s={urls:[],username:"",credential:""};for(;i.pos>>3){case 1:s.urls.push(i.string());break;case 2:s.username=i.string();break;case 3:s.credential=i.string();break;default:i.skipType(7&e)}}return s},fromJSON:e=>({urls:Array.isArray(null==e?void 0:e.urls)?e.urls.map((e=>String(e))):[],username:isSet(e.username)?String(e.username):"",credential:isSet(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},fromPartial(e){var t,i,n;const s={urls:[],username:"",credential:""};return s.urls=(null===(t=e.urls)||void 0===t?void 0:t.map((e=>e)))||[],s.username=null!==(i=e.username)&&void 0!==i?i:"",s.credential=null!==(n=e.credential)&&void 0!==n?n:"",s}};const ct={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Ee.Writer.create();for(const i of e.speakers)Me.encode(i,t.uint32(10).fork()).ldelim();return t},decode(e,t){const i=e instanceof Ee.Reader?e:new Ee.Reader(e);let n=void 0===t?i.len:i.pos+t;const s={speakers:[]};for(;i.pos>>3==1)s.speakers.push(Me.decode(i,i.uint32()));else i.skipType(7&e)}return s},fromJSON:e=>({speakers:Array.isArray(null==e?void 0:e.speakers)?e.speakers.map((e=>Me.fromJSON(e))):[]}),toJSON(e){const t={};return e.speakers?t.speakers=e.speakers.map((e=>e?Me.toJSON(e):void 0)):t.speakers=[],t},fromPartial(e){var t;const i={speakers:[]};return i.speakers=(null===(t=e.speakers)||void 0===t?void 0:t.map((e=>Me.fromPartial(e))))||[],i}};const dt={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Ee.Writer.create();return void 0!==e.room&&Oe.encode(e.room,t.uint32(10).fork()).ldelim(),t},decode(e,t){const i=e instanceof Ee.Reader?e:new Ee.Reader(e);let n=void 0===t?i.len:i.pos+t;const s={room:void 0};for(;i.pos>>3==1)s.room=Oe.decode(i,i.uint32());else i.skipType(7&e)}return s},fromJSON:e=>({room:isSet(e.room)?Oe.fromJSON(e.room):void 0}),toJSON(e){const t={};return void 0!==e.room&&(t.room=e.room?Oe.toJSON(e.room):void 0),t},fromPartial(e){const t={room:void 0};return t.room=void 0!==e.room&&null!==e.room?Oe.fromPartial(e.room):void 0,t}};const ut={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Ee.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 Ee.Reader?e:new Ee.Reader(e);let n=void 0===t?i.len:i.pos+t;const s={participantSid:"",quality:0,score:0};for(;i.pos>>3){case 1:s.participantSid=i.string();break;case 2:s.quality=i.int32();break;case 3:s.score=i.float();break;default:i.skipType(7&e)}}return s},fromJSON:e=>({participantSid:isSet(e.participantSid)?String(e.participantSid):"",quality:isSet(e.quality)?connectionQualityFromJSON(e.quality):0,score:isSet(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 connectionQualityToJSON(e){switch(e){case ye.POOR:return"POOR";case ye.GOOD:return"GOOD";case ye.EXCELLENT:return"EXCELLENT";default:return"UNKNOWN"}}(e.quality)),void 0!==e.score&&(t.score=e.score),t},fromPartial(e){var t,i,n;const s={participantSid:"",quality:0,score:0};return s.participantSid=null!==(t=e.participantSid)&&void 0!==t?t:"",s.quality=null!==(i=e.quality)&&void 0!==i?i:0,s.score=null!==(n=e.score)&&void 0!==n?n:0,s}};const lt={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Ee.Writer.create();for(const i of e.updates)ut.encode(i,t.uint32(10).fork()).ldelim();return t},decode(e,t){const i=e instanceof Ee.Reader?e:new Ee.Reader(e);let n=void 0===t?i.len:i.pos+t;const s={updates:[]};for(;i.pos>>3==1)s.updates.push(ut.decode(i,i.uint32()));else i.skipType(7&e)}return s},fromJSON:e=>({updates:Array.isArray(null==e?void 0:e.updates)?e.updates.map((e=>ut.fromJSON(e))):[]}),toJSON(e){const t={};return e.updates?t.updates=e.updates.map((e=>e?ut.toJSON(e):void 0)):t.updates=[],t},fromPartial(e){var t;const i={updates:[]};return i.updates=(null===(t=e.updates)||void 0===t?void 0:t.map((e=>ut.fromPartial(e))))||[],i}};const ht={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Ee.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 Ee.Reader?e:new Ee.Reader(e);let n=void 0===t?i.len:i.pos+t;const s={participantSid:"",trackSid:"",state:0};for(;i.pos>>3){case 1:s.participantSid=i.string();break;case 2:s.trackSid=i.string();break;case 3:s.state=i.int32();break;default:i.skipType(7&e)}}return s},fromJSON:e=>({participantSid:isSet(e.participantSid)?String(e.participantSid):"",trackSid:isSet(e.trackSid)?String(e.trackSid):"",state:isSet(e.state)?streamStateFromJSON(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 streamStateToJSON(e){switch(e){case Ge.ACTIVE:return"ACTIVE";case Ge.PAUSED:return"PAUSED";default:return"UNKNOWN"}}(e.state)),t},fromPartial(e){var t,i,n;const s={participantSid:"",trackSid:"",state:0};return s.participantSid=null!==(t=e.participantSid)&&void 0!==t?t:"",s.trackSid=null!==(i=e.trackSid)&&void 0!==i?i:"",s.state=null!==(n=e.state)&&void 0!==n?n:0,s}};const pt={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Ee.Writer.create();for(const i of e.streamStates)ht.encode(i,t.uint32(10).fork()).ldelim();return t},decode(e,t){const i=e instanceof Ee.Reader?e:new Ee.Reader(e);let n=void 0===t?i.len:i.pos+t;const s={streamStates:[]};for(;i.pos>>3==1)s.streamStates.push(ht.decode(i,i.uint32()));else i.skipType(7&e)}return s},fromJSON:e=>({streamStates:Array.isArray(null==e?void 0:e.streamStates)?e.streamStates.map((e=>ht.fromJSON(e))):[]}),toJSON(e){const t={};return e.streamStates?t.streamStates=e.streamStates.map((e=>e?ht.toJSON(e):void 0)):t.streamStates=[],t},fromPartial(e){var t;const i={streamStates:[]};return i.streamStates=(null===(t=e.streamStates)||void 0===t?void 0:t.map((e=>ht.fromPartial(e))))||[],i}};const mt={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Ee.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 Ee.Reader?e:new Ee.Reader(e);let n=void 0===t?i.len:i.pos+t;const s={quality:0,enabled:!1};for(;i.pos>>3){case 1:s.quality=i.int32();break;case 2:s.enabled=i.bool();break;default:i.skipType(7&e)}}return s},fromJSON:e=>({quality:isSet(e.quality)?videoQualityFromJSON(e.quality):0,enabled:!!isSet(e.enabled)&&Boolean(e.enabled)}),toJSON(e){const t={};return void 0!==e.quality&&(t.quality=videoQualityToJSON(e.quality)),void 0!==e.enabled&&(t.enabled=e.enabled),t},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 ft={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Ee.Writer.create();""!==e.trackSid&&t.uint32(10).string(e.trackSid);for(const i of e.subscribedQualities)mt.encode(i,t.uint32(18).fork()).ldelim();return t},decode(e,t){const i=e instanceof Ee.Reader?e:new Ee.Reader(e);let n=void 0===t?i.len:i.pos+t;const s={trackSid:"",subscribedQualities:[]};for(;i.pos>>3){case 1:s.trackSid=i.string();break;case 2:s.subscribedQualities.push(mt.decode(i,i.uint32()));break;default:i.skipType(7&e)}}return s},fromJSON:e=>({trackSid:isSet(e.trackSid)?String(e.trackSid):"",subscribedQualities:Array.isArray(null==e?void 0:e.subscribedQualities)?e.subscribedQualities.map((e=>mt.fromJSON(e))):[]}),toJSON(e){const t={};return void 0!==e.trackSid&&(t.trackSid=e.trackSid),e.subscribedQualities?t.subscribedQualities=e.subscribedQualities.map((e=>e?mt.toJSON(e):void 0)):t.subscribedQualities=[],t},fromPartial(e){var t,i;const n={trackSid:"",subscribedQualities:[]};return n.trackSid=null!==(t=e.trackSid)&&void 0!==t?t:"",n.subscribedQualities=(null===(i=e.subscribedQualities)||void 0===i?void 0:i.map((e=>mt.fromPartial(e))))||[],n}};const vt={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Ee.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 Ee.Reader?e:new Ee.Reader(e);let n=void 0===t?i.len:i.pos+t;const s={participantSid:"",allTracks:!1,trackSids:[],participantIdentity:""};for(;i.pos>>3){case 1:s.participantSid=i.string();break;case 2:s.allTracks=i.bool();break;case 3:s.trackSids.push(i.string());break;case 4:s.participantIdentity=i.string();break;default:i.skipType(7&e)}}return s},fromJSON:e=>({participantSid:isSet(e.participantSid)?String(e.participantSid):"",allTracks:!!isSet(e.allTracks)&&Boolean(e.allTracks),trackSids:Array.isArray(null==e?void 0:e.trackSids)?e.trackSids.map((e=>String(e))):[],participantIdentity:isSet(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},fromPartial(e){var t,i,n,s;const a={participantSid:"",allTracks:!1,trackSids:[],participantIdentity:""};return a.participantSid=null!==(t=e.participantSid)&&void 0!==t?t:"",a.allTracks=null!==(i=e.allTracks)&&void 0!==i&&i,a.trackSids=(null===(n=e.trackSids)||void 0===n?void 0:n.map((e=>e)))||[],a.participantIdentity=null!==(s=e.participantIdentity)&&void 0!==s?s:"",a}};const gt={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Ee.Writer.create();!0===e.allParticipants&&t.uint32(8).bool(e.allParticipants);for(const i of e.trackPermissions)vt.encode(i,t.uint32(18).fork()).ldelim();return t},decode(e,t){const i=e instanceof Ee.Reader?e:new Ee.Reader(e);let n=void 0===t?i.len:i.pos+t;const s={allParticipants:!1,trackPermissions:[]};for(;i.pos>>3){case 1:s.allParticipants=i.bool();break;case 2:s.trackPermissions.push(vt.decode(i,i.uint32()));break;default:i.skipType(7&e)}}return s},fromJSON:e=>({allParticipants:!!isSet(e.allParticipants)&&Boolean(e.allParticipants),trackPermissions:Array.isArray(null==e?void 0:e.trackPermissions)?e.trackPermissions.map((e=>vt.fromJSON(e))):[]}),toJSON(e){const t={};return void 0!==e.allParticipants&&(t.allParticipants=e.allParticipants),e.trackPermissions?t.trackPermissions=e.trackPermissions.map((e=>e?vt.toJSON(e):void 0)):t.trackPermissions=[],t},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=>vt.fromPartial(e))))||[],n}};const St={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Ee.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 Ee.Reader?e:new Ee.Reader(e);let n=void 0===t?i.len:i.pos+t;const s={participantSid:"",trackSid:"",allowed:!1};for(;i.pos>>3){case 1:s.participantSid=i.string();break;case 2:s.trackSid=i.string();break;case 3:s.allowed=i.bool();break;default:i.skipType(7&e)}}return s},fromJSON:e=>({participantSid:isSet(e.participantSid)?String(e.participantSid):"",trackSid:isSet(e.trackSid)?String(e.trackSid):"",allowed:!!isSet(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},fromPartial(e){var t,i,n;const s={participantSid:"",trackSid:"",allowed:!1};return s.participantSid=null!==(t=e.participantSid)&&void 0!==t?t:"",s.trackSid=null!==(i=e.trackSid)&&void 0!==i?i:"",s.allowed=null!==(n=e.allowed)&&void 0!==n&&n,s}};const bt={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Ee.Writer.create();void 0!==e.answer&&tt.encode(e.answer,t.uint32(10).fork()).ldelim(),void 0!==e.subscription&&rt.encode(e.subscription,t.uint32(18).fork()).ldelim();for(const i of e.publishTracks)Xe.encode(i,t.uint32(26).fork()).ldelim();for(const i of e.dataChannels)kt.encode(i,t.uint32(34).fork()).ldelim();return t},decode(e,t){const i=e instanceof Ee.Reader?e:new Ee.Reader(e);let n=void 0===t?i.len:i.pos+t;const s={answer:void 0,subscription:void 0,publishTracks:[],dataChannels:[]};for(;i.pos>>3){case 1:s.answer=tt.decode(i,i.uint32());break;case 2:s.subscription=rt.decode(i,i.uint32());break;case 3:s.publishTracks.push(Xe.decode(i,i.uint32()));break;case 4:s.dataChannels.push(kt.decode(i,i.uint32()));break;default:i.skipType(7&e)}}return s},fromJSON:e=>({answer:isSet(e.answer)?tt.fromJSON(e.answer):void 0,subscription:isSet(e.subscription)?rt.fromJSON(e.subscription):void 0,publishTracks:Array.isArray(null==e?void 0:e.publishTracks)?e.publishTracks.map((e=>Xe.fromJSON(e))):[],dataChannels:Array.isArray(null==e?void 0:e.dataChannels)?e.dataChannels.map((e=>kt.fromJSON(e))):[]}),toJSON(e){const t={};return void 0!==e.answer&&(t.answer=e.answer?tt.toJSON(e.answer):void 0),void 0!==e.subscription&&(t.subscription=e.subscription?rt.toJSON(e.subscription):void 0),e.publishTracks?t.publishTracks=e.publishTracks.map((e=>e?Xe.toJSON(e):void 0)):t.publishTracks=[],e.dataChannels?t.dataChannels=e.dataChannels.map((e=>e?kt.toJSON(e):void 0)):t.dataChannels=[],t},fromPartial(e){var t,i;const n={answer:void 0,subscription:void 0,publishTracks:[],dataChannels:[]};return n.answer=void 0!==e.answer&&null!==e.answer?tt.fromPartial(e.answer):void 0,n.subscription=void 0!==e.subscription&&null!==e.subscription?rt.fromPartial(e.subscription):void 0,n.publishTracks=(null===(t=e.publishTracks)||void 0===t?void 0:t.map((e=>Xe.fromPartial(e))))||[],n.dataChannels=(null===(i=e.dataChannels)||void 0===i?void 0:i.map((e=>kt.fromPartial(e))))||[],n}};const kt={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Ee.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 Ee.Reader?e:new Ee.Reader(e);let n=void 0===t?i.len:i.pos+t;const s={label:"",id:0,target:0};for(;i.pos>>3){case 1:s.label=i.string();break;case 2:s.id=i.uint32();break;case 3:s.target=i.int32();break;default:i.skipType(7&e)}}return s},fromJSON:e=>({label:isSet(e.label)?String(e.label):"",id:isSet(e.id)?Number(e.id):0,target:isSet(e.target)?signalTargetFromJSON(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=signalTargetToJSON(e.target)),t},fromPartial(e){var t,i,n;const s={label:"",id:0,target:0};return s.label=null!==(t=e.label)&&void 0!==t?t:"",s.id=null!==(i=e.id)&&void 0!==i?i:0,s.target=null!==(n=e.target)&&void 0!==n?n:0,s}};const yt={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Ee.Writer.create();return void 0!==e.speakerUpdate&&t.uint32(8).int32(e.speakerUpdate),void 0!==e.nodeFailure&&t.uint32(16).bool(e.nodeFailure),void 0!==e.migration&&t.uint32(24).bool(e.migration),void 0!==e.serverLeave&&t.uint32(32).bool(e.serverLeave),t},decode(e,t){const i=e instanceof Ee.Reader?e:new Ee.Reader(e);let n=void 0===t?i.len:i.pos+t;const s={speakerUpdate:void 0,nodeFailure:void 0,migration:void 0,serverLeave:void 0};for(;i.pos>>3){case 1:s.speakerUpdate=i.int32();break;case 2:s.nodeFailure=i.bool();break;case 3:s.migration=i.bool();break;case 4:s.serverLeave=i.bool();break;default:i.skipType(7&e)}}return s},fromJSON:e=>({speakerUpdate:isSet(e.speakerUpdate)?Number(e.speakerUpdate):void 0,nodeFailure:isSet(e.nodeFailure)?Boolean(e.nodeFailure):void 0,migration:isSet(e.migration)?Boolean(e.migration):void 0,serverLeave:isSet(e.serverLeave)?Boolean(e.serverLeave):void 0}),toJSON(e){const t={};return void 0!==e.speakerUpdate&&(t.speakerUpdate=Math.round(e.speakerUpdate)),void 0!==e.nodeFailure&&(t.nodeFailure=e.nodeFailure),void 0!==e.migration&&(t.migration=e.migration),void 0!==e.serverLeave&&(t.serverLeave=e.serverLeave),t},fromPartial(e){var t,i,n,s;const a={speakerUpdate:void 0,nodeFailure:void 0,migration:void 0,serverLeave:void 0};return a.speakerUpdate=null!==(t=e.speakerUpdate)&&void 0!==t?t:void 0,a.nodeFailure=null!==(i=e.nodeFailure)&&void 0!==i?i:void 0,a.migration=null!==(n=e.migration)&&void 0!==n?n:void 0,a.serverLeave=null!==(s=e.serverLeave)&&void 0!==s?s:void 0,a}};function isSet(e){return null!=e}Ee.util.Long!==p&&(Ee.util.Long=p,Ee.configure());class LivekitError extends Error{constructor(e,t){super(t||"an error has occured"),this.code=e}}class ConnectionError extends LivekitError{constructor(e){super(1,e)}}class TrackInvalidError extends LivekitError{constructor(e){super(20,e||"Track is invalid")}}class UnsupportedServer extends LivekitError{constructor(e){super(10,e||"Unsupported server")}}class UnexpectedConnectionState extends LivekitError{constructor(e){super(12,e||"Unexpected connection state")}}class PublishDataError extends LivekitError{constructor(e){super(13,e||"Unable to publish data")}}var Tt,wt,Ct,Pt,Et;!function(e){e.PermissionDenied="PermissionDenied",e.NotFound="NotFound",e.DeviceInUse="DeviceInUse",e.Other="Other"}(Tt||(Tt={})),function(e){e.getFailure=function getFailure(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}}(Tt||(Tt={})),function(e){e.Reconnecting="reconnecting",e.Reconnected="reconnected",e.Disconnected="disconnected",e.ConnectionStateChanged="connectionStateChanged",e.StateChanged="connectionStateChanged",e.MediaDevicesChanged="mediaDevicesChanged",e.ParticipantConnected="participantConnected",e.ParticipantDisconnected="participantDisconnected",e.TrackPublished="trackPublished",e.TrackSubscribed="trackSubscribed",e.TrackSubscriptionFailed="trackSubscriptionFailed",e.TrackUnpublished="trackUnpublished",e.TrackUnsubscribed="trackUnsubscribed",e.TrackMuted="trackMuted",e.TrackUnmuted="trackUnmuted",e.LocalTrackPublished="localTrackPublished",e.LocalTrackUnpublished="localTrackUnpublished",e.ActiveSpeakersChanged="activeSpeakersChanged",e.ParticipantMetadataChanged="participantMetadataChanged",e.RoomMetadataChanged="roomMetadataChanged",e.DataReceived="dataReceived",e.ConnectionQualityChanged="connectionQualityChanged",e.TrackStreamStateChanged="trackStreamStateChanged",e.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",e.AudioPlaybackStatusChanged="audioPlaybackChanged",e.MediaDevicesError="mediaDevicesError",e.ParticipantPermissionsChanged="participantPermissionsChanged"}(wt||(wt={})),function(e){e.TrackPublished="trackPublished",e.TrackSubscribed="trackSubscribed",e.TrackSubscriptionFailed="trackSubscriptionFailed",e.TrackUnpublished="trackUnpublished",e.TrackUnsubscribed="trackUnsubscribed",e.TrackMuted="trackMuted",e.TrackUnmuted="trackUnmuted",e.LocalTrackPublished="localTrackPublished",e.LocalTrackUnpublished="localTrackUnpublished",e.ParticipantMetadataChanged="participantMetadataChanged",e.DataReceived="dataReceived",e.IsSpeakingChanged="isSpeakingChanged",e.ConnectionQualityChanged="connectionQualityChanged",e.TrackStreamStateChanged="trackStreamStateChanged",e.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",e.MediaDevicesError="mediaDevicesError",e.ParticipantPermissionsChanged="participantPermissionsChanged"}(Ct||(Ct={})),function(e){e.TransportsCreated="transportsCreated",e.Connected="connected",e.Disconnected="disconnected",e.Resuming="resuming",e.Resumed="resumed",e.Restarting="restarting",e.Restarted="restarted",e.SignalResumed="signalResumed",e.MediaTrackAdded="mediaTrackAdded",e.ActiveSpeakersUpdate="activeSpeakersUpdate",e.DataPacketReceived="dataPacketReceived"}(Pt||(Pt={})),function(e){e.Message="message",e.Muted="muted",e.Unmuted="unmuted",e.Ended="ended",e.UpdateSettings="updateSettings",e.UpdateSubscription="updateSubscription",e.AudioPlaybackStarted="audioPlaybackStarted",e.AudioPlaybackFailed="audioPlaybackFailed",e.AudioSilenceDetected="audioSilenceDetected",e.VisibilityChanged="visibilityChanged",e.VideoDimensionsChanged="videoDimensionsChanged",e.ElementAttached="elementAttached",e.ElementDetached="elementDetached",e.UpstreamPaused="upstreamPaused",e.UpstreamResumed="upstreamResumed"}(Et||(Et={}));const Rt=2e3;function computeBitrate(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)}const Ot="default";class DeviceManager{static getInstance(){return void 0===this.instance&&(this.instance=new DeviceManager),this.instance}async getDevices(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1],i=await navigator.mediaDevices.enumerateDevices();if(t){if(0===i.length||i.some((t=>{const i=""===t.label,n=!e||t.kind===e;return i&&n}))){const t={video:"audioinput"!==e&&"audiooutput"!==e,audio:"videoinput"!==e},n=await navigator.mediaDevices.getUserMedia(t);i=await navigator.mediaDevices.enumerateDevices(),n.getTracks().forEach((e=>{e.stop()}))}}if(e&&(i=i.filter((t=>t.kind===e))),i.length>1&&i[0].deviceId===Ot){const e=i[0];for(let t=1;tt!==e))}return i}async normalizeDeviceId(e,t,i){if(t!==Ot)return t;const n=(await this.getDevices(e)).find((e=>e.groupId===i&&e.deviceId!==Ot));return null==n?void 0:n.deviceId}}DeviceManager.mediaDeviceKinds=["audioinput","audiooutput","videoinput"];const Nt="1.0.0",_t=7;async function sleep(e){return new Promise((t=>setTimeout(t,e)))}function isFireFox(){return!!isWeb()&&-1!==navigator.userAgent.indexOf("Firefox")}function isMobile(){return!!isWeb()&&/Tablet|iPad|Mobile|Android|BlackBerry/.test(navigator.userAgent)}function isWeb(){return"undefined"!=typeof document}function roDispatchCallback(e){for(const t of e)t.target.handleResize(t)}function ioDispatchCallback(e){for(const t of e)t.target.handleVisibilityChanged(t)}let Lt=null;const getResizeObserver=()=>(Lt||(Lt=new ResizeObserver(roDispatchCallback)),Lt);let Dt=null;const getIntersectionObserver=()=>(Dt||(Dt=new IntersectionObserver(ioDispatchCallback,{root:document,rootMargin:"0px"})),Dt);let At,Ut;var It,Mt={exports:{}},xt="object"==typeof Reflect?Reflect:null,Bt=xt&&"function"==typeof xt.apply?xt.apply:function ReflectApply(e,t,i){return Function.prototype.apply.call(e,t,i)};It=xt&&"function"==typeof xt.ownKeys?xt.ownKeys:Object.getOwnPropertySymbols?function ReflectOwnKeys(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function ReflectOwnKeys(e){return Object.getOwnPropertyNames(e)};var Jt=Number.isNaN||function NumberIsNaN(e){return e!=e};function EventEmitter(){EventEmitter.init.call(this)}Mt.exports=EventEmitter,Mt.exports.once=function once(e,t){return new Promise((function(i,n){function errorListener(i){e.removeListener(t,resolver),n(i)}function resolver(){"function"==typeof e.removeListener&&e.removeListener("error",errorListener),i([].slice.call(arguments))}eventTargetAgnosticAddListener(e,t,resolver,{once:!0}),"error"!==t&&function addErrorHandlerIfEventEmitter(e,t,i){"function"==typeof e.on&&eventTargetAgnosticAddListener(e,"error",t,i)}(e,errorListener,{once:!0})}))},EventEmitter.EventEmitter=EventEmitter,EventEmitter.prototype._events=void 0,EventEmitter.prototype._eventsCount=0,EventEmitter.prototype._maxListeners=void 0;var Ft=10;function checkListener(e){if("function"!=typeof e)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function _getMaxListeners(e){return void 0===e._maxListeners?EventEmitter.defaultMaxListeners:e._maxListeners}function _addListener(e,t,i,n){var s,a,o;if(checkListener(i),void 0===(a=e._events)?(a=e._events=Object.create(null),e._eventsCount=0):(void 0!==a.newListener&&(e.emit("newListener",t,i.listener?i.listener:i),a=e._events),o=a[t]),void 0===o)o=a[t]=i,++e._eventsCount;else if("function"==typeof o?o=a[t]=n?[i,o]:[o,i]:n?o.unshift(i):o.push(i),(s=_getMaxListeners(e))>0&&o.length>s&&!o.warned){o.warned=!0;var c=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");c.name="MaxListenersExceededWarning",c.emitter=e,c.type=t,c.count=o.length,function ProcessEmitWarning(e){console&&console.warn&&console.warn(e)}(c)}return e}function onceWrapper(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,0===arguments.length?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function _onceWrap(e,t,i){var n={fired:!1,wrapFn:void 0,target:e,type:t,listener:i},s=onceWrapper.bind(n);return s.listener=i,n.wrapFn=s,s}function _listeners(e,t,i){var n=e._events;if(void 0===n)return[];var s=n[t];return void 0===s?[]:"function"==typeof s?i?[s.listener||s]:[s]:i?function unwrapListeners(e){for(var t=new Array(e.length),i=0;i0&&(a=t[0]),a instanceof Error)throw a;var o=new Error("Unhandled error."+(a?" ("+a.message+")":""));throw o.context=a,o}var c=s[e];if(void 0===c)return!1;if("function"==typeof c)Bt(c,this,t);else{var u=c.length,l=arrayClone(c,u);for(i=0;i=0;a--)if(i[a]===t||i[a].listener===t){o=i[a].listener,s=a;break}if(s<0)return this;0===s?i.shift():function spliceOne(e,t){for(;t+1=0;n--)this.removeListener(e,t[n]);return this},EventEmitter.prototype.listeners=function listeners(e){return _listeners(this,e,!0)},EventEmitter.prototype.rawListeners=function rawListeners(e){return _listeners(this,e,!1)},EventEmitter.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):listenerCount.call(e,t)},EventEmitter.prototype.listenerCount=listenerCount,EventEmitter.prototype.eventNames=function eventNames(){return this._eventsCount>0?It(this._events):[]};const Vt=[];class Track extends Mt.exports.EventEmitter{constructor(e,t){super(),this.attachedElements=[],this.isMuted=!1,this._currentBitrate=0,this.appVisibilityChangedListener=()=>{this.handleAppVisibilityChanged()},this.kind=t,this._mediaStreamTrack=e,this.source=Track.Source.Unknown,isWeb()?(this.isInBackground="hidden"===document.visibilityState,document.addEventListener("visibilitychange",this.appVisibilityChangedListener)):this.isInBackground=!1}get currentBitrate(){return this._currentBitrate}get mediaStreamTrack(){return this._mediaStreamTrack}attach(e){let t="audio";return this.kind===Track.Kind.Video&&(t="video"),e||("audio"===t&&(Vt.forEach((t=>{null!==t.parentElement||e||(e=t)})),e&&Vt.splice(Vt.indexOf(e),1)),e||(e=document.createElement(t))),this.attachedElements.includes(e)||this.attachedElements.push(e),attachToElement(this._mediaStreamTrack,e),e instanceof HTMLAudioElement&&e.play().then((()=>{this.emit(Et.AudioPlaybackStarted)})).catch((e=>{this.emit(Et.AudioPlaybackFailed,e)})),this.emit(Et.ElementAttached,e),e}detach(e){if(e){detachTrack(this._mediaStreamTrack,e);const t=this.attachedElements.indexOf(e);return t>=0&&(this.attachedElements.splice(t,1),this.recycleElement(e),this.emit(Et.ElementDetached,e)),e}const t=[];return this.attachedElements.forEach((e=>{detachTrack(this._mediaStreamTrack,e),t.push(e),this.recycleElement(e),this.emit(Et.ElementDetached,e)})),this.attachedElements=[],t}stop(){this._mediaStreamTrack.stop(),isWeb()&&document.removeEventListener("visibilitychange",this.appVisibilityChangedListener)}enable(){this._mediaStreamTrack.enabled=!0}disable(){this._mediaStreamTrack.enabled=!1}recycleElement(e){if(e instanceof HTMLAudioElement){let t=!0;e.pause(),Vt.forEach((e=>{e.parentElement||(t=!1)})),t&&Vt.push(e)}}async handleAppVisibilityChanged(){this.isInBackground="hidden"===document.visibilityState}}function attachToElement(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.srcObject!==i&&(t.srcObject=i,(function isSafari(){return!!isWeb()&&/^((?!chrome|android).)*safari/i.test(navigator.userAgent)}()||isFireFox())&&t instanceof HTMLVideoElement&&setTimeout((()=>{t.srcObject=i,t.play().catch((()=>{}))}),0)),t.autoplay=!0,t instanceof HTMLVideoElement&&(t.playsInline=!0)}function detachTrack(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 kindToProto(e){switch(e){case t.Audio:return Se.AUDIO;case t.Video:return Se.VIDEO;default:return Se.UNRECOGNIZED}},e.kindFromProto=function kindFromProto(e){switch(e){case Se.AUDIO:return t.Audio;case Se.VIDEO:return t.Video;default:return t.Unknown}},e.sourceToProto=function sourceToProto(e){switch(e){case i.Camera:return be.CAMERA;case i.Microphone:return be.MICROPHONE;case i.ScreenShare:return be.SCREEN_SHARE;case i.ScreenShareAudio:return be.SCREEN_SHARE_AUDIO;default:return be.UNRECOGNIZED}},e.sourceFromProto=function sourceFromProto(e){switch(e){case be.CAMERA:return i.Camera;case be.MICROPHONE:return i.Microphone;case be.SCREEN_SHARE:return i.ScreenShare;case be.SCREEN_SHARE_AUDIO:return i.ScreenShareAudio;default:return i.Unknown}},e.streamStateFromProto=function streamStateFromProto(e){switch(e){case Ge.ACTIVE:return n.Active;case Ge.PAUSED:return n.Paused;default:return n.Unknown}}}(Track||(Track={}));class LocalTrack extends Track{constructor(e,t,i){super(e,t),this._isUpstreamPaused=!1,this.handleEnded=()=>{this.isInBackground&&(this.reacquireTrack=!0),this.emit(Et.Ended,this)},this._mediaStreamTrack.addEventListener("ended",this.handleEnded),this.constraints=null!=i?i:e.getConstraints(),this.reacquireTrack=!1,this.wasMuted=!1}get id(){return this._mediaStreamTrack.id}get dimensions(){if(this.kind!==Track.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}async getDeviceId(){if(this.source===Track.Source.ScreenShare)return;const{deviceId:e,groupId:t}=this._mediaStreamTrack.getSettings(),i=this.kind===Track.Kind.Audio?"audioinput":"videoinput";return DeviceManager.getInstance().normalizeDeviceId(i,e,t)}async mute(){return this.setTrackMuted(!0),this}async unmute(){return this.setTrackMuted(!1),this}async replaceTrack(e){if(!this.sender)throw new TrackInvalidError("unable to replace an unpublished track");return this.attachedElements.forEach((e=>{detachTrack(this._mediaStreamTrack,e)})),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.stop(),e.addEventListener("ended",this.handleEnded),h.debug("replace MediaStreamTrack"),await this.sender.replaceTrack(e),this._mediaStreamTrack=e,this.attachedElements.forEach((t=>{attachToElement(e,t)})),this.mediaStream=new MediaStream([e]),this}async restart(e){if(!this.sender)throw new TrackInvalidError("unable to restart an unpublished track");e||(e=this.constraints),h.debug("restarting track with constraints",e);const t={audio:!1,video:!1};this.kind===Track.Kind.Video?t.video=e:t.audio=e,this.attachedElements.forEach((e=>{detachTrack(this._mediaStreamTrack,e)})),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.stop();const i=await navigator.mediaDevices.getUserMedia(t),n=i.getTracks()[0];return n.addEventListener("ended",this.handleEnded),h.debug("re-acquired MediaStreamTrack"),await this.sender.replaceTrack(n),this._mediaStreamTrack=n,this.attachedElements.forEach((e=>{attachToElement(n,e)})),this.mediaStream=i,this.constraints=e,this}setTrackMuted(e){this.isMuted!==e&&(this.isMuted=e,this._mediaStreamTrack.enabled=!e,this.emit(e?Et.Muted:Et.Unmuted,this))}get needsReAcquisition(){return"live"!==this._mediaStreamTrack.readyState||this._mediaStreamTrack.muted||!this._mediaStreamTrack.enabled||this.reacquireTrack}async handleAppVisibilityChanged(){await super.handleAppVisibilityChanged(),isMobile()&&(h.debug("visibility changed, is in Background: ".concat(this.isInBackground)),!this.isInBackground&&this.needsReAcquisition&&(h.debug("track needs to be reaquired, restarting ".concat(this.source)),await this.restart(),this.reacquireTrack=!1,this.setTrackMuted(this.wasMuted)),this.isInBackground&&(this.wasMuted=this.isMuted))}async pauseUpstream(){if(!0===this._isUpstreamPaused)return;if(!this.sender)return void h.warn("unable to pause upstream for an unpublished track");this._isUpstreamPaused=!0,this.emit(Et.UpstreamPaused,this);const e=this.kind===Track.Kind.Audio?function getEmptyAudioStreamTrack(){if(!Ut){const e=new AudioContext,t=e.createOscillator(),i=e.createMediaStreamDestination();if(t.connect(i),t.start(),[Ut]=i.stream.getAudioTracks(),!Ut)throw Error("Could not get empty media stream audio track");Ut.enabled=!1}return Ut}():function getEmptyVideoStreamTrack(){var e;if(!At){const t=document.createElement("canvas");t.width=2,t.height=2,null===(e=t.getContext("2d"))||void 0===e||e.fillRect(0,0,t.width,t.height);const i=t.captureStream();if([At]=i.getTracks(),!At)throw Error("Could not get empty media stream video track");At.enabled=!1}return At}();await this.sender.replaceTrack(e)}async resumeUpstream(){!1!==this._isUpstreamPaused&&(this.sender?(this._isUpstreamPaused=!1,this.emit(Et.UpstreamResumed,this),await this.sender.replaceTrack(this._mediaStreamTrack)):h.warn("unable to resume upstream for an unpublished track"))}}function mergeDefaultOptions(e,t,i){const n=_objectSpread2({},e);return!0===n.audio&&(n.audio={}),!0===n.video&&(n.video={}),n.audio&&mergeObjectWithoutOverwriting(n.audio,t),n.video&&mergeObjectWithoutOverwriting(n.video,i),n}function mergeObjectWithoutOverwriting(e,t){return Object.keys(t).forEach((i=>{void 0===e[i]&&(e[i]=t[i])})),e}function constraintsForOptions(e){const t={};if(e.video)if("object"==typeof e.video){const i={},n=i,s=e.video;Object.keys(s).forEach((e=>{if("resolution"===e)mergeObjectWithoutOverwriting(n,s.resolution);else n[e]=s[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 getNewAudioContext(){const e=window.AudioContext||window.webkitAudioContext;if(e)return new e}class LocalAudioTrack extends LocalTrack{constructor(e,t){super(e,Track.Kind.Audio,t),this.stopOnMute=!1,this.monitorSender=async()=>{if(!this.sender)return void(this._currentBitrate=0);let e;try{e=await this.getSenderStats()}catch(e){return void h.error("could not get audio sender stats",{error:e})}e&&this.prevStats&&(this._currentBitrate=computeBitrate(e,this.prevStats)),this.prevStats=e,setTimeout((()=>{this.monitorSender()}),Rt)},this.checkForSilence()}async setDeviceId(e){this.constraints.deviceId!==e&&(this.constraints.deviceId=e,this.isMuted||await this.restartTrack())}async mute(){return this.source===Track.Source.Microphone&&this.stopOnMute&&(h.debug("stopping mic track"),this._mediaStreamTrack.stop()),await super.mute(),this}async unmute(){return this.source===Track.Source.Microphone&&this.stopOnMute&&(h.debug("reacquiring mic track"),await this.restartTrack()),await super.unmute(),this}async restartTrack(e){let t;if(e){const i=constraintsForOptions({audio:e});"boolean"!=typeof i.audio&&(t=i.audio)}await this.restart(t)}async restart(e){const t=await super.restart(e);return this.checkForSilence(),t}startMonitor(){setTimeout((()=>{this.monitorSender()}),Rt)}async getSenderStats(){if(!this.sender)return;let e;return(await this.sender.getStats()).forEach((t=>{"outbound-rtp"===t.type&&(e={type:"audio",streamId:t.id,packetsSent:t.packetsSent,packetsLost:t.packetsLost,bytesSent:t.bytesSent,timestamp:t.timestamp,roundTripTime:t.roundTripTime,jitter:t.jitter})})),e}async checkForSilence(){const e=await async function detectSilence(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:200;const i=getNewAudioContext();if(i){const n=i.createAnalyser();n.fftSize=2048;const s=n.frequencyBinCount,a=new Uint8Array(s);i.createMediaStreamSource(new MediaStream([e.mediaStreamTrack])).connect(n),await sleep(t),n.getByteTimeDomainData(a);const o=a.some((e=>128!==e&&0!==e));return i.close(),!o}return!1}(this);e&&(this.isMuted||h.warn("silence detected on local audio track"),this.emit(Et.AudioSilenceDetected))}}class LocalVideoTrack extends LocalTrack{constructor(e,t){super(e,Track.Kind.Video,t),this.monitorSender=async()=>{if(!this.sender)return void(this._currentBitrate=0);let e;try{e=await this.getSenderStats()}catch(e){return void h.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 s=null===(n=this.prevStats)||void 0===n?void 0:n.get(i);e+=computeBitrate(t,s)})),this._currentBitrate=e}this.prevStats=t,setTimeout((()=>{this.monitorSender()}),Rt)}}get isSimulcast(){return!!(this.sender&&this.sender.getParameters().encodings.length>1)}startMonitor(e){var t;this.signalClient=e;const i=null===(t=this.sender)||void 0===t?void 0:t.getParameters();i&&(this.encodings=i.encodings),setTimeout((()=>{this.monitorSender()}),Rt)}stop(){this.sender=void 0,this._mediaStreamTrack.getConstraints(),super.stop()}async mute(){return this.source===Track.Source.Camera&&(h.debug("stopping camera track"),this._mediaStreamTrack.stop()),await super.mute(),this}async unmute(){return this.source===Track.Source.Camera&&(h.debug("reacquiring camera track"),await this.restartTrack()),await super.unmute(),this}async getSenderStats(){if(!this.sender)return[];const e=[],t=await this.sender.getStats();return t.forEach((i=>{var n;if("outbound-rtp"===i.type){const s={type:"video",streamId:i.id,frameHeight:i.frameHeight,frameWidth:i.frameWidth,firCount:i.firCount,pliCount:i.pliCount,nackCount:i.nackCount,packetsSent:i.packetsSent,bytesSent:i.bytesSent,framesSent:i.framesSent,timestamp:i.timestamp,rid:null!==(n=i.rid)&&void 0!==n?n:"",retransmittedPacketsSent:i.retransmittedPacketsSent,qualityLimitationReason:i.qualityLimitationReason,qualityLimitationResolutionChanges:i.qualityLimitationResolutionChanges},a=t.get(i.remoteId);a&&(s.jitter=a.jitter,s.packetsLost=a.packetsLost,s.roundTripTime=a.roundTripTime),e.push(s)}})),e}setPublishingQuality(e){const t=[];for(let i=ke.LOW;i<=ke.HIGH;i+=1)t.push({quality:i,enabled:i<=e});h.debug("setting publishing quality. max quality ".concat(e)),this.setPublishingLayers(t)}async setDeviceId(e){this.constraints.deviceId!==e&&(this.constraints.deviceId=e,this.isMuted||await this.restartTrack())}async restartTrack(e){let t;if(e){const i=constraintsForOptions({video:e});"boolean"!=typeof i.video&&(t=i.video)}await this.restart(t)}async setPublishingLayers(e){if(h.debug("setting publishing layers",e),!this.sender||!this.encodings)return;const t=this.sender.getParameters(),{encodings:i}=t;if(!i)return;if(i.length!==this.encodings.length)return void h.warn("cannot set publishing layers, encodings mismatch");let n=!1;i.forEach(((t,i)=>{var s;let a=null!==(s=t.rid)&&void 0!==s?s:"";""===a&&(a="q");const o=videoQualityForRid(a),c=e.find((e=>e.quality===o));c&&t.active!==c.enabled&&(n=!0,t.active=c.enabled,h.debug("setting layer ".concat(c.quality," to ").concat(t.active?"enabled":"disabled")),isFireFox()&&(c.enabled?(t.scaleResolutionDownBy=this.encodings[i].scaleResolutionDownBy,t.maxBitrate=this.encodings[i].maxBitrate,t.maxFrameRate=this.encodings[i].maxFrameRate):(t.scaleResolutionDownBy=4,t.maxBitrate=10,t.maxFrameRate=2)))})),n&&(t.encodings=i,await this.sender.setParameters(t))}async handleAppVisibilityChanged(){await super.handleAppVisibilityChanged(),isMobile()&&this.isInBackground&&this.source===Track.Source.Camera&&(this._mediaStreamTrack.enabled=!1)}}function videoQualityForRid(e){switch(e){case"f":return ke.HIGH;case"h":return ke.MEDIUM;case"q":return ke.LOW;default:return ke.UNRECOGNIZED}}class RemoteTrack extends Track{constructor(e,t,i,n){super(e,i),this.streamState=Track.StreamState.Active,this.sid=t,this.receiver=n}setMuted(e){this.isMuted!==e&&(this.isMuted=e,this.emit(e?Et.Muted:Et.Unmuted,this))}setMediaStream(e){this.mediaStream=e,e.onremovetrack=()=>{this.receiver=void 0,this._currentBitrate=0,this.emit(Et.Ended,this)}}start(){this.startMonitor(),super.enable()}stop(){super.disable()}startMonitor(){setTimeout((()=>{this.monitorReceiver()}),Rt)}}class RemoteAudioTrack extends RemoteTrack{constructor(e,t,i){super(e,t,Track.Kind.Audio,i),this.monitorReceiver=async()=>{if(!this.receiver)return void(this._currentBitrate=0);const e=await this.getReceiverStats();e&&this.prevStats&&this.receiver&&(this._currentBitrate=computeBitrate(e,this.prevStats)),this.prevStats=e,setTimeout((()=>{this.monitorReceiver()}),Rt)},this.elementVolume=1}setVolume(e){for(const t of this.attachedElements)t.volume=e;this.elementVolume=e}getVolume(){return this.elementVolume}attach(e){return e?super.attach(e):e=super.attach(),e.volume=this.elementVolume,e}async getReceiverStats(){if(!this.receiver)return;let e;return(await 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}}function r(e,t,i){var n,s,a;void 0===t&&(t=50),void 0===i&&(i={});var o=null!=(n=i.isImmediate)&&n,c=null!=(s=i.callback)&&s,u=i.maxWait,l=Date.now(),h=[];function f(){if(void 0!==u){var e=Date.now()-l;if(e+t>=u)return u-e}return t}var d=function(){var t=[].slice.call(arguments),i=this;return new Promise((function(n,s){var u=o&&void 0===a;if(void 0!==a&&clearTimeout(a),a=setTimeout((function(){if(a=void 0,l=Date.now(),!o){var n=e.apply(i,t);c&&c(n),h.forEach((function(e){return(0,e.resolve)(n)})),h=[]}}),f()),u){var p=e.apply(i,t);return c&&c(p),n(p)}h.push({resolve:n,reject:s})}))};return d.cancel=function(e){void 0!==a&&clearTimeout(a),h.forEach((function(t){return(0,t.reject)(e)})),h=[]},d}class RemoteVideoTrack extends RemoteTrack{constructor(e,t,i,n){super(e,t,Track.Kind.Video,i),this.elementInfos=[],this.hasUsedAttach=!1,this.monitorReceiver=async()=>{if(!this.receiver)return void(this._currentBitrate=0);const e=await this.getReceiverStats();e&&this.prevStats&&this.receiver&&(this._currentBitrate=computeBitrate(e,this.prevStats)),this.prevStats=e,setTimeout((()=>{this.monitorReceiver()}),Rt)},this.handleVisibilityChanged=e=>{const{target:t,isIntersecting:i}=e,n=this.elementInfos.find((e=>e.element===t));n&&(n.visible=i,n.visibilityChangedAt=Date.now()),this.updateVisibility()},this.debouncedHandleResize=r((()=>{this.updateDimensions()}),100),this.adaptiveStreamSettings=n,this.isAdaptiveStream&&(this.streamState=Track.StreamState.Paused)}get isAdaptiveStream(){return void 0!==this.adaptiveStreamSettings}get mediaStreamTrack(){return this.isAdaptiveStream&&!this.hasUsedAttach&&h.warn("When using adaptiveStream, you need to use remoteVideoTrack.attach() to add the track to a HTMLVideoElement, otherwise your video tracks might never start"),this._mediaStreamTrack}setMuted(e){super.setMuted(e),this.attachedElements.forEach((t=>{e?detachTrack(this._mediaStreamTrack,t):attachToElement(this._mediaStreamTrack,t)}))}attach(e){return e?super.attach(e):e=super.attach(),this.adaptiveStreamSettings&&void 0===this.elementInfos.find((t=>t.element===e))&&(this.elementInfos.push({element:e,visible:!0}),e.handleResize=this.debouncedHandleResize,e.handleVisibilityChanged=this.handleVisibilityChanged,getIntersectionObserver().observe(e),getResizeObserver().observe(e),this.debouncedHandleResize()),this.hasUsedAttach=!0,e}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}async getReceiverStats(){if(!this.receiver)return;let e;return(await 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})})),e}stopObservingElement(e){var t,i;null===(t=getIntersectionObserver())||void 0===t||t.unobserve(e),null===(i=getResizeObserver())||void 0===i||i.unobserve(e),this.elementInfos=this.elementInfos.filter((t=>t.element!==e))}async handleAppVisibilityChanged(){await super.handleAppVisibilityChanged(),this.isAdaptiveStream&&isMobile()&&this.updateVisibility()}updateVisibility(){const e=this.elementInfos.reduce(((e,t)=>Math.max(e,t.visibilityChangedAt||0)),0),t=this.elementInfos.some((e=>e.visible))&&!this.isInBackground;this.lastVisible!==t&&(!t&&Date.now()-e<100?setTimeout((()=>{this.updateVisibility()}),100):(this.lastVisible=t,this.emit(Et.VisibilityChanged,t,this)))}updateDimensions(){var e,t,i,n;let s=0,a=0;for(const i of this.elementInfos){const n=null!==(t=null===(e=this.adaptiveStreamSettings)||void 0===e?void 0:e.pixelDensity)&&void 0!==t?t:1,o="screen"===n?window.devicePixelRatio:n,c=i.element.clientWidth*o,u=i.element.clientHeight*o;c+u>s+a&&(s=c,a=u)}(null===(i=this.lastDimensions)||void 0===i?void 0:i.width)===s&&(null===(n=this.lastDimensions)||void 0===n?void 0:n.height)===a||(this.lastDimensions={width:s,height:a},this.emit(Et.VideoDimensionsChanged,this.lastDimensions,this))}}class TrackPublication extends Mt.exports.EventEmitter{constructor(e,t,i){super(),this.metadataMuted=!1,this.handleMuted=()=>{this.emit(Et.Muted)},this.handleUnmuted=()=>{this.emit(Et.Unmuted)},this.kind=e,this.trackSid=t,this.trackName=i,this.source=Track.Source.Unknown}setTrack(e){this.track&&(this.track.off(Et.Muted,this.handleMuted),this.track.off(Et.Unmuted,this.handleUnmuted)),this.track=e,e&&(e.on(Et.Muted,this.handleMuted),e.on(Et.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 LocalAudioTrack||this.track instanceof RemoteAudioTrack)return this.track}get videoTrack(){if(this.track instanceof LocalVideoTrack||this.track instanceof RemoteVideoTrack)return this.track}updateInfo(e){this.trackSid=e.sid,this.trackName=e.name,this.source=Track.sourceFromProto(e.source),this.mimeType=e.mimeType,this.kind===Track.Kind.Video&&e.width>0&&(this.dimensions={width:e.width,height:e.height},this.simulcasted=e.simulcast),this.trackInfo=e}}!function(e){var t;(t=e.SubscriptionStatus||(e.SubscriptionStatus={})).Subscribed="subscribed",t.NotAllowed="not_allowed",t.Unsubscribed="unsubscribed"}(TrackPublication||(TrackPublication={}));class LocalTrackPublication extends TrackPublication{constructor(e,t,i){super(e,t.sid,t.name),this.track=void 0,this.handleTrackEnded=()=>{this.emit(Et.Ended)},this.updateInfo(t),this.setTrack(i)}get isUpstreamPaused(){var e;return null===(e=this.track)||void 0===e?void 0:e.isUpstreamPaused}setTrack(e){this.track&&this.track.off(Et.Ended,this.handleTrackEnded),super.setTrack(e),e&&e.on(Et.Ended,this.handleTrackEnded)}get isMuted(){return this.track?this.track.isMuted:super.isMuted}get audioTrack(){return super.audioTrack}get videoTrack(){return super.videoTrack}async mute(){var e;return null===(e=this.track)||void 0===e?void 0:e.mute()}async unmute(){var e;return null===(e=this.track)||void 0===e?void 0:e.unmute()}async pauseUpstream(){var e;await(null===(e=this.track)||void 0===e?void 0:e.pauseUpstream())}async resumeUpstream(){var e;await(null===(e=this.track)||void 0===e?void 0:e.resumeUpstream())}}class VideoPreset{constructor(e,t,i,n){this.width=e,this.height=t,this.encoding={maxBitrate:i,maxFramerate:n}}get resolution(){return{width:this.width,height:this.height,frameRate:this.encoding.maxFramerate,aspectRatio:this.width/this.height}}}var jt;!function(e){e.telephone={maxBitrate:12e3},e.speech={maxBitrate:2e4},e.music={maxBitrate:32e3}}(jt||(jt={}));const qt={h90:new VideoPreset(160,90,6e4,15),h180:new VideoPreset(320,180,12e4,15),h216:new VideoPreset(384,216,18e4,15),h360:new VideoPreset(640,360,3e5,20),h540:new VideoPreset(960,540,6e5,25),h720:new VideoPreset(1280,720,17e5,30),h1080:new VideoPreset(1920,1080,3e6,30),h1440:new VideoPreset(2560,1440,5e6,30),h2160:new VideoPreset(3840,2160,8e6,30)},Wt={h120:new VideoPreset(160,120,8e4,15),h180:new VideoPreset(240,180,1e5,15),h240:new VideoPreset(320,240,15e4,15),h360:new VideoPreset(480,360,225e3,20),h480:new VideoPreset(640,480,3e5,20),h540:new VideoPreset(720,540,45e4,25),h720:new VideoPreset(960,720,15e5,30),h1080:new VideoPreset(1440,1080,25e5,30),h1440:new VideoPreset(1920,1440,35e5,30)},$t={h360fps3:new VideoPreset(640,360,2e5,3),h720fps5:new VideoPreset(1280,720,4e5,5),h720fps15:new VideoPreset(1280,720,1e6,15),h1080fps15:new VideoPreset(1920,1080,15e5,15),h1080fps30:new VideoPreset(1920,1080,3e6,30)};var Gt;!function(e){e.Excellent="excellent",e.Good="good",e.Poor="poor",e.Unknown="unknown"}(Gt||(Gt={}));class Participant extends Mt.exports.EventEmitter{constructor(e,t){super(),this.audioLevel=0,this.isSpeaking=!1,this._connectionQuality=Gt.Unknown,this.sid=e,this.identity=t,this.audioTracks=new Map,this.videoTracks=new Map,this.tracks=new Map}getTracks(){return Array.from(this.tracks.values())}getTrack(e){if(e!==Track.Source.Unknown)for(const[,t]of this.tracks){if(t.source===e)return t;if(t.source===Track.Source.Unknown){if(e===Track.Source.Microphone&&t.kind===Track.Kind.Audio&&"screen"!==t.trackName)return t;if(e===Track.Source.Camera&&t.kind===Track.Kind.Video&&"screen"!==t.trackName)return t;if(e===Track.Source.ScreenShare&&t.kind===Track.Kind.Video&&"screen"===t.trackName)return t;if(e===Track.Source.ScreenShareAudio&&t.kind===Track.Kind.Audio&&"screen"===t.trackName)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(Track.Source.Camera);return!(null===(e=null==t?void 0:t.isMuted)||void 0===e||e)}get isMicrophoneEnabled(){var e;const t=this.getTrack(Track.Source.Microphone);return!(null===(e=null==t?void 0:t.isMuted)||void 0===e||e)}get isScreenShareEnabled(){return!!this.getTrack(Track.Source.ScreenShare)}get joinedAt(){return this.participantInfo?new Date(1e3*this.participantInfo.joinedAt):new Date}updateInfo(e){this.identity=e.identity,this.sid=e.sid,this.name=e.name,this.setMetadata(e.metadata),e.permission&&this.setPermissions(e.permission),this.participantInfo=e}setMetadata(e){const t=this.metadata!==e,i=this.metadata;this.metadata=e,t&&this.emit(Ct.ParticipantMetadataChanged,i)}setPermissions(e){var t,i,n,s,a;const o=e.canPublish!==(null===(t=this.permissions)||void 0===t?void 0:t.canPublish)||e.canSubscribe!==(null===(i=this.permissions)||void 0===i?void 0:i.canSubscribe)||e.canPublishData!==(null===(n=this.permissions)||void 0===n?void 0:n.canPublishData)||e.hidden!==(null===(s=this.permissions)||void 0===s?void 0:s.hidden)||e.recorder!==(null===(a=this.permissions)||void 0===a?void 0:a.recorder);return this.permissions=e,o}setIsSpeaking(e){e!==this.isSpeaking&&(this.isSpeaking=e,e&&(this.lastSpokeAt=new Date),this.emit(Ct.IsSpeakingChanged,e))}setConnectionQuality(e){const t=this._connectionQuality;this._connectionQuality=function qualityFromProto(e){switch(e){case ye.EXCELLENT:return Gt.Excellent;case ye.GOOD:return Gt.Good;case ye.POOR:return Gt.Poor;default:return Gt.Unknown}}(e),t!==this._connectionQuality&&this.emit(Ct.ConnectionQualityChanged,this._connectionQuality)}addTrackPublication(e){e.on(Et.Muted,(()=>{this.emit(Ct.TrackMuted,e)})),e.on(Et.Unmuted,(()=>{this.emit(Ct.TrackUnmuted,e)}));const t=e;switch(t.track&&(t.track.sid=e.trackSid),this.tracks.set(e.trackSid,e),e.kind){case Track.Kind.Audio:this.audioTracks.set(e.trackSid,e);break;case Track.Kind.Video:this.videoTracks.set(e.trackSid,e)}}}function mediaTrackToLocalTrack(e,t){switch(e.kind){case"audio":return new LocalAudioTrack(e,t);case"video":return new LocalVideoTrack(e,t);default:throw new TrackInvalidError("unsupported track type: ".concat(e.kind))}}const Qt=Object.values(qt),Ht=Object.values(Wt),Kt=Object.values($t),zt=[qt.h180,qt.h360],Zt=[Wt.h180,Wt.h360],Yt=["q","h","f"];function computeVideoEncodings(e,t,i,n){var s,a;let o=null==n?void 0:n.videoEncoding;e&&(o=null==n?void 0:n.screenShareEncoding);const c=null==n?void 0:n.simulcast,u=null==n?void 0:n.scalabilityMode;if(!o&&!c&&!u||!t||!i)return[{}];o||(o=function determineAppropriateEncoding(e,t,i){const n=function presetsForResolution(e,t,i){if(e)return Kt;const n=t>i?t/i:i/t;if(Math.abs(n-16/9)=a)break}return s}(e,t,i),h.debug("using video encoding",o));const l=new VideoPreset(t,i,o.maxBitrate,o.maxFramerate);if(h.debug("scalabilityMode ".concat(u)),u){const e=[];if("L3T3"===u){for(let t=0;t<3;t+=1)e.push({rid:Yt[2-t],scaleResolutionDownBy:2**t,maxBitrate:o?o.maxBitrate/2**t:0,maxFramerate:l.encoding.maxFramerate,scalabilityMode:"L3T3"});return h.debug("encodings",e),e}throw new Error("unsupported scalabilityMode: ".concat(u))}if(!c)return[o];let p,m=[];m=e?null!==(s=sortPresets(null==n?void 0:n.screenShareSimulcastLayers))&&void 0!==s?s:defaultSimulcastLayers(e,l):null!==(a=sortPresets(null==n?void 0:n.videoSimulcastLayers))&&void 0!==a?a:defaultSimulcastLayers(e,l);const v=m[0];m.length>1&&([,p]=m);const g=Math.max(t,i);return encodingsFromPresets(t,i,g>=960&&p?[v,p,l]:g>=480?[v,l]:[l])}function defaultSimulcastLayers(e,t){if(e)return i=t,[{scaleResolutionDownBy:2,fps:3}].map((e=>{var t;return new VideoPreset(Math.floor(i.width/e.scaleResolutionDownBy),Math.floor(i.height/e.scaleResolutionDownBy),Math.max(15e4,Math.floor(i.encoding.maxBitrate/(e.scaleResolutionDownBy**2*((null!==(t=i.encoding.maxFramerate)&&void 0!==t?t:30)/e.fps)))),e.fps)}));var i;const{width:n,height:s}=t,a=n>s?n/s:s/n;return Math.abs(a-16/9){if(s>=Yt.length)return;const a=Math.min(e,t),o=Yt[s];n.push({rid:o,scaleResolutionDownBy:a/Math.min(i.width,i.height),maxBitrate:i.encoding.maxBitrate,maxFramerate:i.encoding.maxFramerate})})),n}function sortPresets(e){if(e)return e.sort(((e,t)=>{const{encoding:i}=e,{encoding:n}=t;return i.maxBitrate>n.maxBitrate?1:i.maxBitraten.maxFramerate?1:-1:0}))}class RemoteTrackPublication extends TrackPublication{constructor(){super(...arguments),this._allowed=!0,this.disabled=!1,this.currentVideoQuality=ke.HIGH,this.handleEnded=e=>{this.emit(Et.Ended,e)},this.handleVisibilityChange=e=>{h.debug("adaptivestream video visibility ".concat(this.trackSid,", visible=").concat(e),{trackSid:this.trackSid}),this.disabled=!e,this.emitTrackUpdate()},this.handleVideoDimensionsChange=e=>{h.debug("adaptivestream video dimensions ".concat(e.width,"x").concat(e.height),{trackSid:this.trackSid}),this.videoDimensions=e,this.emitTrackUpdate()}}setSubscribed(e){this.subscribed=e;const t={trackSids:[this.trackSid],subscribe:this.subscribed,participantTracks:[{participantSid:"",trackSids:[this.trackSid]}]};this.emit(Et.UpdateSubscription,t)}get subscriptionStatus(){return!1!==this.subscribed&&super.isSubscribed?this._allowed?TrackPublication.SubscriptionStatus.Subscribed:TrackPublication.SubscriptionStatus.NotAllowed:TrackPublication.SubscriptionStatus.Unsubscribed}get isSubscribed(){return!1!==this.subscribed&&(!!this._allowed&&super.isSubscribed)}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 RemoteVideoTrack&&(this.videoDimensions=e),this.currentVideoQuality=void 0,this.emitTrackUpdate()))}get videoQuality(){return this.currentVideoQuality}setTrack(e){this.track&&(this.track.off(Et.VideoDimensionsChanged,this.handleVideoDimensionsChange),this.track.off(Et.VisibilityChanged,this.handleVisibilityChange),this.track.off(Et.Ended,this.handleEnded)),super.setTrack(e),e&&(e.sid=this.trackSid,e.on(Et.VideoDimensionsChanged,this.handleVideoDimensionsChange),e.on(Et.VisibilityChanged,this.handleVisibilityChange),e.on(Et.Ended,this.handleEnded))}updateInfo(e){var t;super.updateInfo(e),this.metadataMuted=e.muted,null===(t=this.track)||void 0===t||t.setMuted(e.muted)}isManualOperationAllowed(){return this.isAdaptiveStream?(h.warn("adaptive stream is enabled, cannot change track settings",{trackSid:this.trackSid}),!1):!!this.isSubscribed||(h.warn("cannot update track settings when not subscribed",{trackSid:this.trackSid}),!1)}get isAdaptiveStream(){return this.track instanceof RemoteVideoTrack&&this.track.isAdaptiveStream}emitTrackUpdate(){const e=nt.fromPartial({trackSids:[this.trackSid],disabled:this.disabled});this.videoDimensions?(e.width=this.videoDimensions.width,e.height=this.videoDimensions.height):void 0!==this.currentVideoQuality?e.quality=this.currentVideoQuality:e.quality=ke.HIGH,this.emit(Et.UpdateSettings,e)}}class RemoteParticipant extends Participant{constructor(e,t,i){super(t,i||""),this.signalClient=e,this.tracks=new Map,this.audioTracks=new Map,this.videoTracks=new Map}static fromParticipantInfo(e,t){const i=new RemoteParticipant(e,t.sid,t.identity);return i.updateInfo(t),i}addTrackPublication(e){super.addTrackPublication(e),e.on(Et.UpdateSettings,(e=>{this.signalClient.sendUpdateTrackSettings(e)})),e.on(Et.UpdateSubscription,(e=>{e.participantTracks.forEach((e=>{e.participantSid=this.sid})),this.signalClient.sendUpdateSubscription(e)})),e.on(Et.Ended,(t=>{this.emit(Ct.TrackUnsubscribed,t,e)}))}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(Track.Source.Microphone);t&&t.track&&t.track.setVolume(e)}getVolume(){const e=this.getTrack(Track.Source.Microphone);return e&&e.track?e.track.getVolume():this.volume}addSubscribedMediaTrack(e,t,i,n,s,a){let o=this.getTrackPublication(t);if(o||t.startsWith("TR")||this.tracks.forEach((t=>{o||e.kind!==t.kind.toString()||(o=t)})),!o)return 0===a?(h.error("could not find published track",{participant:this.sid,trackSid:t}),void this.emit(Ct.TrackSubscriptionFailed,t)):(void 0===a&&(a=20),void setTimeout((()=>{this.addSubscribedMediaTrack(e,t,i,n,s,a-1)}),150));let c;return c="video"===e.kind?new RemoteVideoTrack(e,t,n,s):new RemoteAudioTrack(e,t,n),c.source=o.source,c.isMuted=o.isMuted,c.setMediaStream(i),c.start(),o.setTrack(c),void 0!==this.volume&&c instanceof RemoteAudioTrack&&c.source===Track.Source.Microphone&&c.setVolume(this.volume),this.emit(Ct.TrackSubscribed,c,o),o}get hasMetadata(){return!!this.participantInfo}getTrackPublication(e){return this.tracks.get(e)}updateInfo(e){const t=this.hasMetadata;super.updateInfo(e);const i=new Map,n=new Map;e.tracks.forEach((e=>{let t=this.getTrackPublication(e.sid);if(t)t.updateInfo(e);else{const i=Track.kindFromProto(e.type);if(!i)return;t=new RemoteTrackPublication(i,e.sid,e.name),t.updateInfo(e),n.set(e.sid,t),this.addTrackPublication(t)}i.set(e.sid,t)})),t&&n.forEach((e=>{this.emit(Ct.TrackPublished,e)})),this.tracks.forEach((e=>{i.has(e.trackSid)||this.unpublishTrack(e.trackSid,!0)}))}unpublishTrack(e,t){const i=this.tracks.get(e);if(!i)return;switch(this.tracks.delete(e),i.kind){case Track.Kind.Audio:this.audioTracks.delete(e);break;case Track.Kind.Video:this.videoTracks.delete(e)}const{track:n}=i;if(n){const{isSubscribed:e}=i;n.stop(),i.setTrack(void 0),e&&this.emit(Ct.TrackUnsubscribed,n,i)}t&&this.emit(Ct.TrackUnpublished,i)}emit(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),n=1;n{this.onTrackMuted(e,e.isUpstreamPaused)},this.onTrackMuted=(e,t)=>{void 0===t&&(t=!0),e.sid?this.engine.updateMuteStatus(e.sid,t):h.error("could not update mute status for unpublished track",e)},this.onTrackUpstreamPaused=e=>{h.debug("upstream paused"),this.onTrackMuted(e,!0)},this.onTrackUpstreamResumed=e=>{h.debug("upstream resumed"),this.onTrackMuted(e,e.isMuted)},this.handleSubscribedQualityUpdate=e=>{var t,i;if(!(null===(t=this.roomOptions)||void 0===t?void 0:t.dynacast))return;const n=this.videoTracks.get(e.trackSid);n?null===(i=n.videoTrack)||void 0===i||i.setPublishingLayers(e.subscribedQualities):h.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):h.warn("received unpublished event for unknown track",{method:"handleLocalTrackUnpublished",trackSid:e.trackSid})},this.onTrackUnpublish=e=>{this.unpublishTrack(e)},this.audioTracks=new Map,this.videoTracks=new Map,this.tracks=new Map,this.engine=i,this.roomOptions=n,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}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}setCameraEnabled(e){return this.setTrackEnabled(Track.Source.Camera,e)}setMicrophoneEnabled(e){return this.setTrackEnabled(Track.Source.Microphone,e)}setScreenShareEnabled(e){return this.setTrackEnabled(Track.Source.ScreenShare,e)}setPermissions(e){const t=this.permissions,i=super.setPermissions(e);return i&&t&&this.emit(Ct.ParticipantPermissionsChanged,t),i}async setTrackEnabled(e,t){h.debug("setTrackEnabled",{source:e,enabled:t});let i=this.getTrack(e);if(t)if(i)await i.unmute();else{let t;if(this.pendingPublishing.has(e))return void h.info("skipping duplicate published source",{source:e});this.pendingPublishing.add(e);try{switch(e){case Track.Source.Camera:[t]=await this.createTracks({video:!0});break;case Track.Source.Microphone:[t]=await this.createTracks({audio:!0});break;case Track.Source.ScreenShare:[t]=await this.createScreenTracks({audio:!1});break;default:throw new TrackInvalidError(e)}i=await this.publishTrack(t)}catch(e){throw e instanceof Error&&!(e instanceof TrackInvalidError)&&this.emit(Ct.MediaDevicesError,e),e}finally{this.pendingPublishing.delete(e)}}else i&&i.track&&(e===Track.Source.ScreenShare?i=this.unpublishTrack(i.track):await i.mute());return i}async enableCameraAndMicrophone(){if(!this.pendingPublishing.has(Track.Source.Camera)&&!this.pendingPublishing.has(Track.Source.Microphone)){this.pendingPublishing.add(Track.Source.Camera),this.pendingPublishing.add(Track.Source.Microphone);try{const e=await this.createTracks({audio:!0,video:!0});await Promise.all(e.map((e=>this.publishTrack(e))))}finally{this.pendingPublishing.delete(Track.Source.Camera),this.pendingPublishing.delete(Track.Source.Microphone)}}}async createTracks(e){var t,i;const n=constraintsForOptions(mergeDefaultOptions(e,null===(t=this.roomOptions)||void 0===t?void 0:t.audioCaptureDefaults,null===(i=this.roomOptions)||void 0===i?void 0:i.videoCaptureDefaults));let s;try{s=await 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),s.getTracks().map((t=>{const i="audio"===t.kind;let a;i?e.audio:e.video;const o=i?n.audio:n.video;"boolean"!=typeof o&&(a=o);const c=mediaTrackToLocalTrack(t,a);return c.kind===Track.Kind.Video?c.source=Track.Source.Camera:c.kind===Track.Kind.Audio&&(c.source=Track.Source.Microphone),c.mediaStream=s,c}))}async createScreenTracks(e){var t;void 0===e&&(e={}),void 0===e.resolution&&(e.resolution=$t.h1080fps15.resolution);let i=!0;e.resolution&&(i={width:e.resolution.width,height:e.resolution.height,frameRate:e.resolution.frameRate});const n=await navigator.mediaDevices.getDisplayMedia({audio:null!==(t=e.audio)&&void 0!==t&&t,video:i}),s=n.getVideoTracks();if(0===s.length)throw new TrackInvalidError("no video track found");const a=new LocalVideoTrack(s[0]);a.source=Track.Source.ScreenShare;const o=[a];if(n.getAudioTracks().length>0){const e=new LocalAudioTrack(n.getAudioTracks()[0]);e.source=Track.Source.ScreenShareAudio,o.push(e)}return o}async publishTrack(e,t){var i,n,s,a,o,c,u;const l=_objectSpread2(_objectSpread2({},null===(i=this.roomOptions)||void 0===i?void 0:i.publishDefaults),t);if(e instanceof MediaStreamTrack)switch(e.kind){case"audio":e=new LocalAudioTrack(e);break;case"video":e=new LocalVideoTrack(e);break;default:throw new TrackInvalidError("unsupported MediaStreamTrack kind ".concat(e.kind))}let p;if(this.tracks.forEach((t=>{t.track&&t.track===e&&(p=t)})),p)return p;l.source&&(e.source=l.source),l.stopMicTrackOnMute&&e instanceof LocalAudioTrack&&(e.stopOnMute=!0),e.source===Track.Source.ScreenShare&&isFireFox()&&(l.simulcast=!1),e.on(Et.Muted,this.onTrackMuted),e.on(Et.Unmuted,this.onTrackUnmuted),e.on(Et.Ended,this.onTrackUnpublish),e.on(Et.UpstreamPaused,this.onTrackUpstreamPaused),e.on(Et.UpstreamResumed,this.onTrackUpstreamResumed);const m=Ke.fromPartial({cid:e.mediaStreamTrack.id,name:null==t?void 0:t.name,type:Track.kindToProto(e.kind),muted:e.isMuted,source:Track.sourceToProto(e.source),disableDtx:!(null===(n=null==l?void 0:l.dtx)||void 0===n||n)});let v;if(e.kind===Track.Kind.Video){const t=e.mediaStreamTrack.getSettings(),i=null!==(s=t.width)&&void 0!==s?s:null===(a=e.dimensions)||void 0===a?void 0:a.width,n=null!==(o=t.height)&&void 0!==o?o:null===(c=e.dimensions)||void 0===c?void 0:c.height;m.width=null!=i?i:0,m.height=null!=n?n:0,e instanceof LocalVideoTrack&&("vp9"===(null==l?void 0:l.videoCodec)||"av1"===(null==l?void 0:l.videoCodec)?(l.simulcast=!1,l.scalabilityMode=null!==(u=l.scalabilityMode)&&void 0!==u?u:"L3T3"):l.scalabilityMode=void 0),v=computeVideoEncodings(e.source===Track.Source.ScreenShare,i,n,l),m.layers=function videoLayersFromEncodings(e,t,i){return i?i.map((n=>{var s,a,o;const c=null!==(s=n.scaleResolutionDownBy)&&void 0!==s?s:1;let u=videoQualityForRid(null!==(a=n.rid)&&void 0!==a?a:"");return u===ke.UNRECOGNIZED&&1===i.length&&(u=ke.HIGH),{quality:u,width:e/c,height:t/c,bitrate:null!==(o=n.maxBitrate)&&void 0!==o?o:0,ssrc:0}})):[{quality:ke.HIGH,width:e,height:t,bitrate:0,ssrc:0}]}(m.width,m.height,v)}else e.kind===Track.Kind.Audio&&l.audioBitrate&&(v=[{maxBitrate:l.audioBitrate}]);if(!this.engine||this.engine.isClosed)throw new UnexpectedConnectionState("cannot publish track when not connected");const g=await this.engine.addTrack(m),S=new LocalTrackPublication(e.kind,g,e);if(e.sid=g.sid,!this.engine.publisher)throw new UnexpectedConnectionState("publisher is closed");h.debug("publishing ".concat(e.kind," with encodings"),{encodings:v,trackInfo:g});const b={direction:"sendonly"};v&&(b.sendEncodings=v);const k=this.engine.publisher.pc.addTransceiver(e.mediaStreamTrack,b);return l.videoCodec&&this.setPreferredCodec(k,e.kind,l.videoCodec),this.engine.negotiate(),e.sender=k.sender,e instanceof LocalVideoTrack?e.startMonitor(this.engine.client):e instanceof LocalAudioTrack&&e.startMonitor(),this.addTrackPublication(S),this.emit(Ct.LocalTrackPublished,S),S}unpublishTrack(e,t){var i,n;const s=this.getPublicationForTrack(e);if(h.debug("unpublishing track",{track:e,method:"unpublishTrack"}),!s||!s.track)return void h.warn("track was not unpublished because no publication was found",{track:e,method:"unpublishTrack"});(e=s.track).off(Et.Muted,this.onTrackMuted),e.off(Et.Unmuted,this.onTrackUnmuted),e.off(Et.Ended,this.onTrackUnpublish),e.off(Et.UpstreamPaused,this.onTrackUpstreamPaused),e.off(Et.UpstreamResumed,this.onTrackUpstreamResumed),void 0===t&&(t=null===(n=null===(i=this.roomOptions)||void 0===i?void 0:i.stopLocalTrackOnUnpublish)||void 0===n||n),t&&e.stop();const{mediaStreamTrack:a}=e;if(this.engine.publisher){this.engine.publisher.pc.getSenders().forEach((e=>{var t;if(e.track===a)try{null===(t=this.engine.publisher)||void 0===t||t.pc.removeTrack(e),this.engine.negotiate()}catch(e){h.warn("failed to remove track",{error:e,method:"unpublishTrack"})}}))}switch(this.tracks.delete(s.trackSid),s.kind){case Track.Kind.Audio:this.audioTracks.delete(s.trackSid);break;case Track.Kind.Video:this.videoTracks.delete(s.trackSid)}return this.emit(Ct.LocalTrackUnpublished,s),s.setTrack(void 0),s}unpublishTracks(e){const t=[];return e.forEach((e=>{const i=this.unpublishTrack(e);i&&t.push(i)})),t}async publishData(e,t,i){const n=[];void 0!==i&&i.forEach((e=>{e instanceof RemoteParticipant?n.push(e.sid):n.push(e)}));const s={kind:t,user:{participantSid:this.sid,payload:e,destinationSids:n}};await this.engine.sendDataPacket(s,t)}setTrackSubscriptionPermissions(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[];this.engine.client.sendUpdateSubscriptionPermissions(e,t.map((e=>function trackPermissionToProto(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))))}getPublicationForTrack(e){let t;return this.tracks.forEach((i=>{const n=i.track;n&&(e instanceof MediaStreamTrack?(n instanceof LocalAudioTrack||n instanceof LocalVideoTrack)&&n.mediaStreamTrack===e&&(t=i):e===n&&(t=i))})),t}setPreferredCodec(e,t,i){if(!("getCapabilities"in RTCRtpSender))return;const n=RTCRtpSender.getCapabilities(t);if(!n)return;let s;const a=[];n.codecs.forEach((e=>{const t=e.mimeType.toLowerCase(),n=t==="video/".concat(i);void 0===s&&("h264"===i&&e.sdpFmtpLine&&n&&e.sdpFmtpLine.includes("profile-level-id=42e01f")||n||"audio/opus"===t)?s=e:a.push(e)})),s&&"setCodecPreferences"in e&&(a.unshift(s),e.setCodecPreferences(a))}publishedTracksInfo(){const e=[];return this.tracks.forEach((t=>{void 0!==t.track&&e.push({cid:t.track.mediaStreamTrack.id,track:t.trackInfo})})),e}dataChannelsInfo(){const e=[],getInfo=(t,i)=>{void 0!==(null==t?void 0:t.id)&&null!==t.id&&e.push({label:t.label,id:t.id,target:i})};return getInfo(this.engine.dataChannelForKind(Ce.LOSSY),$e.PUBLISHER),getInfo(this.engine.dataChannelForKind(Ce.RELIABLE),$e.PUBLISHER),getInfo(this.engine.dataChannelForKind(Ce.LOSSY,!0),$e.SUBSCRIBER),getInfo(this.engine.dataChannelForKind(Ce.RELIABLE,!0),$e.SUBSCRIBER),e}}class Queue{constructor(){this.queue=[],this.running=!1}enqueue(e){h.trace("enqueuing request to fire later"),this.queue.push(e)}dequeue(){const e=this.queue.shift();e&&e(),h.trace("firing request from queue")}async run(){if(!this.running){for(h.trace("start queue"),this.running=!0;this.running&&this.queue.length>0;)this.dequeue();this.running=!1,h.trace("queue finished")}}pause(){h.trace("pausing queue"),this.running=!1}reset(){h.trace("resetting queue"),this.running=!1,this.queue=[]}isRunning(){return this.running}isEmpty(){return 0===this.queue.length}}let Xt=!0,ei=!0;function extractVersion(e,t,i){const n=e.match(t);return n&&n.length>=i&&parseInt(n[i],10)}function wrapPeerConnectionEvent(e,t,i){if(!e.RTCPeerConnection)return;const n=e.RTCPeerConnection.prototype,s=n.addEventListener;n.addEventListener=function(e,n){if(e!==t)return s.apply(this,arguments);const wrappedCallback=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,wrappedCallback),s.apply(this,[e,wrappedCallback])};const a=n.removeEventListener;n.removeEventListener=function(e,i){if(e!==t||!this._eventMap||!this._eventMap[t])return a.apply(this,arguments);if(!this._eventMap[t].has(i))return a.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,a.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 disableLog(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 disableWarnings(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 log(){if("object"==typeof window){if(Xt)return;"undefined"!=typeof console&&"function"==typeof console.log&&console.log.apply(console,arguments)}}function deprecated(e,t){ei&&console.warn(e+" is deprecated, please use "+t+" instead.")}function detectBrowser(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=extractVersion(i.userAgent,/Firefox\/(\d+)\./,1);else if(i.webkitGetUserMedia||!1===e.isSecureContext&&e.webkitRTCPeerConnection&&!e.RTCIceGatherer)t.browser="chrome",t.version=extractVersion(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=extractVersion(i.userAgent,/AppleWebKit\/(\d+)\./,1),t.supportsUnifiedPlan=e.RTCRtpTransceiver&&"currentDirection"in e.RTCRtpTransceiver.prototype}return t}function isObject(e){return"[object Object]"===Object.prototype.toString.call(e)}function compactObject(e){return isObject(e)?Object.keys(e).reduce((function(t,i){const n=isObject(e[i]),s=n?compactObject(e[i]):e[i],a=n&&!Object.keys(s).length;return void 0===s||a?t:Object.assign(t,{[i]:s})}),{}):e}function walkStats(e,t,i){t&&!i.has(t.id)&&(i.set(t.id,t),Object.keys(t).forEach((n=>{n.endsWith("Id")?walkStats(e,e.get(t[n]),i):n.endsWith("Ids")&&t[n].forEach((t=>{walkStats(e,e.get(t),i)}))})))}function filterStats(e,t,i){const n=i?"outbound-rtp":"inbound-rtp",s=new Map;if(null===t)return s;const a=[];return e.forEach((e=>{"track"===e.type&&e.trackIdentifier===t.id&&a.push(e)})),a.forEach((t=>{e.forEach((i=>{i.type===n&&i.trackId===t.id&&walkStats(e,i,s)}))})),s}const ti=log;function shimGetUserMedia$2(e,t){const i=e&&e.navigator;if(!i.mediaDevices)return;const constraintsToChrome_=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 oldname_=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[oldname_("min",i)]=n.ideal,t.optional.push(e),e={},e[oldname_("max",i)]=n.ideal,t.optional.push(e)):(e[oldname_("",i)]=n.ideal,t.optional.push(e))}void 0!==n.exact&&"number"!=typeof n.exact?(t.mandatory=t.mandatory||{},t.mandatory[oldname_("",i)]=n.exact):["min","max"].forEach((e=>{void 0!==n[e]&&(t.mandatory=t.mandatory||{},t.mandatory[oldname_(e,i)]=n[e])}))})),e.advanced&&(t.optional=(t.optional||[]).concat(e.advanced)),t},shimConstraints_=function(e,n){if(t.version>=61)return n(e);if((e=JSON.parse(JSON.stringify(e)))&&"object"==typeof e.audio){const remap=function(e,t,i){t in e&&!(i in e)&&(e[i]=e[t],delete e[t])};remap((e=JSON.parse(JSON.stringify(e))).audio,"autoGainControl","googAutoGainControl"),remap(e.audio,"noiseSuppression","googNoiseSuppression"),e.audio=constraintsToChrome_(e.audio)}if(e&&"object"==typeof e.video){let s=e.video.facingMode;s=s&&("object"==typeof s?s:{ideal:s});const a=t.version<66;if(s&&("user"===s.exact||"environment"===s.exact||"user"===s.ideal||"environment"===s.ideal)&&(!i.mediaDevices.getSupportedConstraints||!i.mediaDevices.getSupportedConstraints().facingMode||a)){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 a=(i=i.filter((e=>"videoinput"===e.kind))).find((e=>t.some((t=>e.label.toLowerCase().includes(t)))));return!a&&i.length&&t.includes("back")&&(a=i[i.length-1]),a&&(e.video.deviceId=s.exact?{exact:a.deviceId}:{ideal:a.deviceId}),e.video=constraintsToChrome_(e.video),ti("chrome: "+JSON.stringify(e)),n(e)}))}e.video=constraintsToChrome_(e.video)}return ti("chrome: "+JSON.stringify(e)),n(e)},shimError_=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){shimConstraints_(e,(e=>{i.webkitGetUserMedia(e,t,(e=>{n&&n(shimError_(e))}))}))}.bind(i),i.mediaDevices.getUserMedia){const e=i.mediaDevices.getUserMedia.bind(i.mediaDevices);i.mediaDevices.getUserMedia=function(t){return shimConstraints_(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(shimError_(e))))))}}}function shimMediaStream(e){e.MediaStream=e.MediaStream||e.webkitMediaStream}function shimOnTrack$1(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 setRemoteDescription(){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 s=new Event("track");s.track=i.track,s.receiver=n,s.transceiver={receiver:n},s.streams=[t.stream],this.dispatchEvent(s)})),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 s=new Event("track");s.track=i,s.receiver=n,s.transceiver={receiver:n},s.streams=[t.stream],this.dispatchEvent(s)}))},this.addEventListener("addstream",this._ontrackpoly)),t.apply(this,arguments)}}else wrapPeerConnectionEvent(e,"track",(e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e)))}function shimGetSendersWithDtmf(e){if("object"==typeof e&&e.RTCPeerConnection&&!("getSenders"in e.RTCPeerConnection.prototype)&&"createDTMFSender"in e.RTCPeerConnection.prototype){const shimSenderWithDtmf=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 getSenders(){return this._senders=this._senders||[],this._senders.slice()};const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function addTrack(e,i){let n=t.apply(this,arguments);return n||(n=shimSenderWithDtmf(this,e),this._senders.push(n)),n};const i=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function removeTrack(e){i.apply(this,arguments);const t=this._senders.indexOf(e);-1!==t&&this._senders.splice(t,1)}}const t=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function addStream(e){this._senders=this._senders||[],t.apply(this,[e]),e.getTracks().forEach((e=>{this._senders.push(shimSenderWithDtmf(this,e))}))};const i=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function removeStream(e){this._senders=this._senders||[],i.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 getSenders(){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 shimGetStats(e){if(!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function getStats(){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 fixChromeStats_=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},makeMapStats=function(e){return new Map(Object.keys(e).map((t=>[t,e[t]])))};if(arguments.length>=2){const successCallbackWrapper_=function(e){i(makeMapStats(fixChromeStats_(e)))};return t.apply(this,[successCallbackWrapper_,e])}return new Promise(((e,i)=>{t.apply(this,[function(t){e(makeMapStats(fixChromeStats_(t)))},i])})).then(i,n)}}function shimSenderReceiverGetStats(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 getSenders(){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 addTrack(){const e=i.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function getStats(){const e=this;return this._pc.getStats().then((t=>filterStats(t,e.track,!0)))}}if(!("getStats"in e.RTCRtpReceiver.prototype)){const t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function getReceivers(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e}),wrapPeerConnectionEvent(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function getStats(){const e=this;return this._pc.getStats().then((t=>filterStats(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 getStats(){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 shimAddTrackRemoveTrackWithNative(e){e.RTCPeerConnection.prototype.getLocalStreams=function getLocalStreams(){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 addTrack(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 addStream(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 removeStream(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[e.id],n.apply(this,arguments)};const s=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function removeTrack(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]})),s.apply(this,arguments)}}function shimAddTrackRemoveTrack(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return shimAddTrackRemoveTrackWithNative(e);const i=e.RTCPeerConnection.prototype.getLocalStreams;e.RTCPeerConnection.prototype.getLocalStreams=function getLocalStreams(){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 addStream(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 s=e.RTCPeerConnection.prototype.removeStream;function replaceInternalStreamId(e,t){let i=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((t=>{const n=e._reverseStreams[t],s=e._streams[n.id];i=i.replace(new RegExp(s.id,"g"),n.id)})),new RTCSessionDescription({type:t.type,sdp:i})}function replaceExternalStreamId(e,t){let i=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((t=>{const n=e._reverseStreams[t],s=e._streams[n.id];i=i.replace(new RegExp(n.id,"g"),s.id)})),new RTCSessionDescription({type:t.type,sdp:i})}e.RTCPeerConnection.prototype.removeStream=function removeStream(e){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},s.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 addTrack(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");const s=this.getSenders().find((e=>e.track===t));if(s)throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};const a=this._streams[i.id];if(a)a.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=replaceInternalStreamId(this,t);e[0].apply(null,[i])},t=>{e[1]&&e[1].apply(null,t)},arguments[2]]):i.apply(this,arguments).then((e=>replaceInternalStreamId(this,e)))}};e.RTCPeerConnection.prototype[t]=n[t]}));const a=e.RTCPeerConnection.prototype.setLocalDescription;e.RTCPeerConnection.prototype.setLocalDescription=function setLocalDescription(){return arguments.length&&arguments[0].type?(arguments[0]=replaceExternalStreamId(this,arguments[0]),a.apply(this,arguments)):a.apply(this,arguments)};const o=Object.getOwnPropertyDescriptor(e.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(e.RTCPeerConnection.prototype,"localDescription",{get(){const e=o.get.apply(this);return""===e.type?e:replaceInternalStreamId(this,e)}}),e.RTCPeerConnection.prototype.removeTrack=function removeTrack(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 shimPeerConnection$1(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 fixNegotiationNeeded(e,t){wrapPeerConnectionEvent(e,"negotiationneeded",(e=>{const i=e.target;if(!(t.version<72||i.getConfiguration&&"plan-b"===i.getConfiguration().sdpSemantics)||"stable"===i.signalingState)return e}))}var ii=Object.freeze({__proto__:null,shimMediaStream,shimOnTrack:shimOnTrack$1,shimGetSendersWithDtmf,shimGetStats,shimSenderReceiverGetStats,shimAddTrackRemoveTrackWithNative,shimAddTrackRemoveTrack,shimPeerConnection:shimPeerConnection$1,fixNegotiationNeeded,shimGetUserMedia:shimGetUserMedia$2,shimGetDisplayMedia:function shimGetDisplayMedia$1(e,t){e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||e.navigator.mediaDevices&&("function"==typeof t?e.navigator.mediaDevices.getDisplayMedia=function getDisplayMedia(i){return t(i).then((t=>{const n=i.video&&i.video.width,s=i.video&&i.video.height,a=i.video&&i.video.frameRate;return i.video={mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:t,maxFrameRate:a||3}},n&&(i.video.mandatory.maxWidth=n),s&&(i.video.mandatory.maxHeight=s),e.navigator.mediaDevices.getUserMedia(i)}))}:console.error("shimGetDisplayMedia: getSourceId argument is not a function"))}});function shimGetUserMedia$1(e,t){const i=e&&e.navigator,n=e&&e.MediaStreamTrack;if(i.getUserMedia=function(e,t,n){deprecated("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),i.mediaDevices.getUserMedia(e).then(t,n)},!(t.version>55&&"autoGainControl"in i.mediaDevices.getSupportedConstraints())){const remap=function(e,t,i){t in e&&!(i in e)&&(e[i]=e[t],delete e[t])},e=i.mediaDevices.getUserMedia.bind(i.mediaDevices);if(i.mediaDevices.getUserMedia=function(t){return"object"==typeof t&&"object"==typeof t.audio&&(t=JSON.parse(JSON.stringify(t)),remap(t.audio,"autoGainControl","mozAutoGainControl"),remap(t.audio,"noiseSuppression","mozNoiseSuppression")),e(t)},n&&n.prototype.getSettings){const e=n.prototype.getSettings;n.prototype.getSettings=function(){const t=e.apply(this,arguments);return remap(t,"mozAutoGainControl","autoGainControl"),remap(t,"mozNoiseSuppression","noiseSuppression"),t}}if(n&&n.prototype.applyConstraints){const e=n.prototype.applyConstraints;n.prototype.applyConstraints=function(t){return"audio"===this.kind&&"object"==typeof t&&(t=JSON.parse(JSON.stringify(t)),remap(t,"autoGainControl","mozAutoGainControl"),remap(t,"noiseSuppression","mozNoiseSuppression")),e.apply(this,[t])}}}}function shimOnTrack(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 shimPeerConnection(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 getStats(){const[e,s,a]=arguments;return n.apply(this,[e||null]).then((e=>{if(t.version<53&&!s)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(s,a)}}function shimSenderGetStats(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 getSenders(){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 addTrack(){const e=i.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function getStats(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function shimReceiverGetStats(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 getReceivers(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e}),wrapPeerConnectionEvent(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function getStats(){return this._pc.getStats(this.track)}}function shimRemoveStream(e){e.RTCPeerConnection&&!("removeStream"in e.RTCPeerConnection.prototype)&&(e.RTCPeerConnection.prototype.removeStream=function removeStream(e){deprecated("removeStream","removeTrack"),this.getSenders().forEach((t=>{t.track&&e.getTracks().includes(t.track)&&this.removeTrack(t)}))})}function shimRTCDataChannel(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)}function shimAddTransceiver(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.addTransceiver;t&&(e.RTCPeerConnection.prototype.addTransceiver=function addTransceiver(){this.setParametersPromises=[];const e=arguments[1],i=e&&"sendEncodings"in e;i&&e.sendEncodings.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.sendEncodings,t.sendEncodings=e.sendEncodings,this.setParametersPromises.push(t.setParameters(i).then((()=>{delete t.sendEncodings})).catch((()=>{delete t.sendEncodings}))))}return n})}function shimGetParameters(e){if("object"!=typeof e||!e.RTCRtpSender)return;const t=e.RTCRtpSender.prototype.getParameters;t&&(e.RTCRtpSender.prototype.getParameters=function getParameters(){const e=t.apply(this,arguments);return"encodings"in e||(e.encodings=[].concat(this.sendEncodings||[{}])),e})}function shimCreateOffer(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function createOffer(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then((()=>t.apply(this,arguments))).finally((()=>{this.setParametersPromises=[]})):t.apply(this,arguments)}}function shimCreateAnswer(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.createAnswer;e.RTCPeerConnection.prototype.createAnswer=function createAnswer(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then((()=>t.apply(this,arguments))).finally((()=>{this.setParametersPromises=[]})):t.apply(this,arguments)}}var ri=Object.freeze({__proto__:null,shimOnTrack,shimPeerConnection,shimSenderGetStats,shimReceiverGetStats,shimRemoveStream,shimRTCDataChannel,shimAddTransceiver,shimGetParameters,shimCreateOffer,shimCreateAnswer,shimGetUserMedia:shimGetUserMedia$1,shimGetDisplayMedia:function shimGetDisplayMedia(e,t){e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||e.navigator.mediaDevices&&(e.navigator.mediaDevices.getDisplayMedia=function getDisplayMedia(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)})}});function shimLocalStreamsAPI(e){if("object"==typeof e&&e.RTCPeerConnection){if("getLocalStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getLocalStreams=function getLocalStreams(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in e.RTCPeerConnection.prototype)){const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addStream=function addStream(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 addTrack(e){for(var i=arguments.length,n=new Array(i>1?i-1:0),s=1;s{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 removeStream(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 shimRemoteStreamsAPI(e){if("object"==typeof e&&e.RTCPeerConnection&&("getRemoteStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getRemoteStreams=function getRemoteStreams(){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 setRemoteDescription(){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 shimCallbacksAPI(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype,i=t.createOffer,n=t.createAnswer,s=t.setLocalDescription,a=t.setRemoteDescription,o=t.addIceCandidate;t.createOffer=function createOffer(e,t){const n=arguments.length>=2?arguments[2]:arguments[0],s=i.apply(this,[n]);return t?(s.then(e,t),Promise.resolve()):s},t.createAnswer=function createAnswer(e,t){const i=arguments.length>=2?arguments[2]:arguments[0],s=n.apply(this,[i]);return t?(s.then(e,t),Promise.resolve()):s};let withCallback=function(e,t,i){const n=s.apply(this,[e]);return i?(n.then(t,i),Promise.resolve()):n};t.setLocalDescription=withCallback,withCallback=function(e,t,i){const n=a.apply(this,[e]);return i?(n.then(t,i),Promise.resolve()):n},t.setRemoteDescription=withCallback,withCallback=function(e,t,i){const n=o.apply(this,[e]);return i?(n.then(t,i),Promise.resolve()):n},t.addIceCandidate=withCallback}function shimGetUserMedia(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(shimConstraints(e))}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=function getUserMedia(e,i,n){t.mediaDevices.getUserMedia(e).then(i,n)}.bind(t))}function shimConstraints(e){return e&&void 0!==e.video?Object.assign({},e,{video:compactObject(e.video)}):e}function shimRTCIceServerUrls(e){if(!e.RTCPeerConnection)return;const t=e.RTCPeerConnection;e.RTCPeerConnection=function RTCPeerConnection(e,i){if(e&&e.iceServers){const t=[];for(let i=0;it.generateCertificate})}function shimTrackEventTransceiver(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 shimCreateOfferLegacy(e){const t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function createOffer(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 shimAudioContext(e){"object"!=typeof e||e.AudioContext||(e.AudioContext=e.webkitAudioContext)}var ni=Object.freeze({__proto__:null,shimLocalStreamsAPI,shimRemoteStreamsAPI,shimCallbacksAPI,shimGetUserMedia,shimConstraints,shimRTCIceServerUrls,shimTrackEventTransceiver,shimCreateOfferLegacy,shimAudioContext}),si={exports:{}};!function(e){const t={generateIdentifier:function(){return Math.random().toString(36).substr(2,10)}};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;e0?t[0].split("/")[1]:"sendrecv",uri:t[1]}},t.writeExtmap=function(e){return"a=extmap:"+(e.id||e.preferredId)+(e.direction&&"sendrecv"!==e.direction?"/"+e.direction:"")+" "+e.uri+"\r\n"},t.parseFmtp=function(e){const t={};let i;const n=e.substr(e.indexOf(" ")+1).split(";");for(let e=0;e{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.substr(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.substr(7,t-7),10)},n=e.indexOf(":",t);return n>-1?(i.attribute=e.substr(t+1,n-t-1),i.value=e.substr(n+1)):i.attribute=e.substr(t+1),i},t.parseSsrcGroup=function(e){const t=e.substr(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.substr(6)},t.parseFingerprint=function(e){const t=e.substr(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.substr(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.substr(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],s=t.matchPrefix(e+i,"a=ice-pwd:")[0];return n&&s?{usernameFragment:n.substr(12),password:s.substr(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(" ");for(let s=3;s{i.headerExtensions.push(t.parseExtmap(e))})),i},t.writeRtpDescription=function(e,i){let n="";n+="m="+e+" ",n+=i.codecs.length>0?"9":"0",n+=" 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 s=0;return i.codecs.forEach((e=>{e.maxptime>s&&(s=e.maxptime)})),s>0&&(n+="a=maxptime:"+s+"\r\n"),i.headerExtensions&&i.headerExtensions.forEach((e=>{n+=t.writeExtmap(e)})),n},t.parseRtpEncodingParameters=function(e){const i=[],n=t.parseRtpParameters(e),s=-1!==n.fecMechanisms.indexOf("RED"),a=-1!==n.fecMechanisms.indexOf("ULPFEC"),o=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"cname"===e.attribute)),c=o.length>0&&o[0].ssrc;let u;const l=t.matchPrefix(e,"a=ssrc-group:FID").map((e=>e.substr(17).split(" ").map((e=>parseInt(e,10)))));l.length>0&&l[0].length>1&&l[0][0]===c&&(u=l[0][1]),n.codecs.forEach((e=>{if("RTX"===e.name.toUpperCase()&&e.parameters.apt){let t={ssrc:c,codecPayloadType:parseInt(e.parameters.apt,10)};c&&u&&(t.rtx={ssrc:u}),i.push(t),s&&(t=JSON.parse(JSON.stringify(t)),t.fec={ssrc:c,mechanism:a?"red+ulpfec":"red"},i.push(t))}})),0===i.length&&c&&i.push({ssrc:c});let h=t.matchPrefix(e,"b=");return h.length&&(h=0===h[0].indexOf("b=TIAS:")?parseInt(h[0].substr(7),10):0===h[0].indexOf("b=AS:")?1e3*parseInt(h[0].substr(5),10)*.95-16e3:void 0,i.forEach((e=>{e.maxBitrate=h}))),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 s=t.matchPrefix(e,"a=rtcp-rsize");i.reducedSize=s.length>0,i.compound=0===s.length;const a=t.matchPrefix(e,"a=rtcp-mux");return i.mux=a.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].substr(7).split(" "),{stream:i[0],track:i[1]};const s=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"msid"===e.attribute));return s.length>0?(i=s[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 s;n.length>0&&(s=parseInt(n[0].substr(19),10)),isNaN(s)&&(s=65536);const a=t.matchPrefix(e,"a=sctp-port:");if(a.length>0)return{port:parseInt(a[0].substr(12),10),protocol:i.fmt,maxMessageSize:s};const o=t.matchPrefix(e,"a=sctpmap:");if(o.length>0){const e=o[0].substr(10).split(" ");return{port:parseInt(e[0],10),protocol:e[1],maxMessageSize:s}}},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,21)},t.writeSessionBoilerplate=function(e,i,n){let s;const a=void 0!==i?i:2;s=e||t.generateSessionId();return"v=0\r\no="+(n||"thisisadapterortc")+" "+s+" "+a+" 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(t.candidate&&Object.defineProperty(t,"candidate",{value:new e.RTCIceCandidate(t.candidate),writable:"false"}),t)))}function shimMaxMessageSize(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 sctpInDescription=function(e){if(!e||!e.sdp)return!1;const t=ai.splitSections(e.sdp);return t.shift(),t.some((e=>{const t=ai.parseMLine(e);return t&&"application"===t.kind&&-1!==t.protocol.indexOf("SCTP")}))},getRemoteFirefoxVersion=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},getCanSendMaxMessageSize=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},getMaxMessageSize=function(e,i){let n=65536;"firefox"===t.browser&&57===t.version&&(n=65535);const s=ai.matchPrefix(e.sdp,"a=max-message-size:");return s.length>0?n=parseInt(s[0].substr(19),10):"firefox"===t.browser&&-1!==i&&(n=2147483637),n},i=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function setRemoteDescription(){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(sctpInDescription(arguments[0])){const e=getRemoteFirefoxVersion(arguments[0]),t=getCanSendMaxMessageSize(e),i=getMaxMessageSize(arguments[0],e);let n;n=0===t&&0===i?Number.POSITIVE_INFINITY:0===t||0===i?Math.max(t,i):Math.min(t,i);const s={};Object.defineProperty(s,"maxMessageSize",{get:()=>n}),this._sctp=s}return i.apply(this,arguments)}}function shimSendThrowTypeError(e){if(!e.RTCPeerConnection||!("createDataChannel"in e.RTCPeerConnection.prototype))return;function wrapDcSend(e,t){const i=e.send;e.send=function send(){const n=arguments[0],s=n.length||n.size||n.byteLength;if("open"===e.readyState&&t.sctp&&s>t.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+t.sctp.maxMessageSize+" bytes)");return i.apply(e,arguments)}}const t=e.RTCPeerConnection.prototype.createDataChannel;e.RTCPeerConnection.prototype.createDataChannel=function createDataChannel(){const e=t.apply(this,arguments);return wrapDcSend(e,this),e},wrapPeerConnectionEvent(e,"datachannel",(e=>(wrapDcSend(e.channel,e.target),e)))}function shimConnectionState(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 removeExtmapAllowMixed(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 setRemoteDescription(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 shimAddIceCandidateNullOrEmpty(e,t){if(!e.RTCPeerConnection||!e.RTCPeerConnection.prototype)return;const i=e.RTCPeerConnection.prototype.addIceCandidate;i&&0!==i.length&&(e.RTCPeerConnection.prototype.addIceCandidate=function addIceCandidate(){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 shimParameterlessSetLocalDescription(e,t){if(!e.RTCPeerConnection||!e.RTCPeerConnection.prototype)return;const i=e.RTCPeerConnection.prototype.setLocalDescription;i&&0!==i.length&&(e.RTCPeerConnection.prototype.setLocalDescription=function setLocalDescription(){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]);const t="offer"===e.type?this.createOffer:this.createAnswer;return t.apply(this).then((e=>i.apply(this,[e])))})}var ci=Object.freeze({__proto__:null,shimRTCIceCandidate,shimMaxMessageSize,shimSendThrowTypeError,shimConnectionState,removeExtmapAllowMixed,shimAddIceCandidateNullOrEmpty,shimParameterlessSetLocalDescription});!function adapterFactory(){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=log,n=detectBrowser(e),s={browserDetails:n,commonShim:ci,extractVersion,disableLog,disableWarnings,sdp:oi};switch(n.browser){case"chrome":if(!ii||!shimPeerConnection$1||!t.shimChrome)return i("Chrome shim is not included in this adapter release."),s;if(null===n.version)return i("Chrome shim can not determine version, not shimming."),s;i("adapter.js shimming chrome."),s.browserShim=ii,shimAddIceCandidateNullOrEmpty(e,n),shimParameterlessSetLocalDescription(e),shimGetUserMedia$2(e,n),shimMediaStream(e),shimPeerConnection$1(e,n),shimOnTrack$1(e),shimAddTrackRemoveTrack(e,n),shimGetSendersWithDtmf(e),shimGetStats(e),shimSenderReceiverGetStats(e),fixNegotiationNeeded(e,n),shimRTCIceCandidate(e),shimConnectionState(e),shimMaxMessageSize(e,n),shimSendThrowTypeError(e),removeExtmapAllowMixed(e,n);break;case"firefox":if(!ri||!shimPeerConnection||!t.shimFirefox)return i("Firefox shim is not included in this adapter release."),s;i("adapter.js shimming firefox."),s.browserShim=ri,shimAddIceCandidateNullOrEmpty(e,n),shimParameterlessSetLocalDescription(e),shimGetUserMedia$1(e,n),shimPeerConnection(e,n),shimOnTrack(e),shimRemoveStream(e),shimSenderGetStats(e),shimReceiverGetStats(e),shimRTCDataChannel(e),shimAddTransceiver(e),shimGetParameters(e),shimCreateOffer(e),shimCreateAnswer(e),shimRTCIceCandidate(e),shimConnectionState(e),shimMaxMessageSize(e,n),shimSendThrowTypeError(e);break;case"safari":if(!ni||!t.shimSafari)return i("Safari shim is not included in this adapter release."),s;i("adapter.js shimming safari."),s.browserShim=ni,shimAddIceCandidateNullOrEmpty(e,n),shimParameterlessSetLocalDescription(e),shimRTCIceServerUrls(e),shimCreateOfferLegacy(e),shimCallbacksAPI(e),shimLocalStreamsAPI(e),shimRemoteStreamsAPI(e),shimTrackEventTransceiver(e),shimGetUserMedia(e),shimAudioContext(e),shimRTCIceCandidate(e),shimMaxMessageSize(e,n),shimSendThrowTypeError(e),removeExtmapAllowMixed(e,n);break;default:i("Unsupported browser!")}return s}({window:"undefined"==typeof window?void 0:window});const di=["syncState","trickle","offer","answer","simulate","leave"];class SignalClient{constructor(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];this.isConnected=!1,this.isReconnecting=!1,this.useJSON=e,this.requestQueue=new Queue}async join(e,t,i,n){this.isConnected=!1;return await this.connect(e,t,{autoSubscribe:null==i?void 0:i.autoSubscribe,publishOnly:null==i?void 0:i.publishOnly,adaptiveStream:null==i?void 0:i.adaptiveStream},n)}async reconnect(e,t){this.isReconnecting=!0,await this.connect(e,t,{reconnect:!0})}connect(e,t,i,n){e.startsWith("http")&&(e=e.replace("http","ws")),e=e.replace(/\/$/,""),e+="/rtc";const s=function createConnectionParams(e,t,i){const n=new URLSearchParams;n.set("access_token",e),(null==i?void 0:i.reconnect)&&n.set("reconnect","1");void 0!==(null==i?void 0:i.autoSubscribe)&&n.set("auto_subscribe",i.autoSubscribe?"1":"0");n.set("sdk","js"),n.set("version",t.version),n.set("protocol",t.protocol.toString()),t.deviceModel&&n.set("device_model",t.deviceModel);t.os&&n.set("os",t.os);t.osVersion&&n.set("os_version",t.osVersion);t.browser&&n.set("browser",t.browser);t.browserVersion&&n.set("browser_version",t.browserVersion);void 0!==(null==i?void 0:i.publishOnly)&&n.set("publish",i.publishOnly);(null==i?void 0:i.adaptiveStream)&&n.set("adaptive_stream","1");return"?".concat(n.toString())}(t,function getClientInfo(){return Je.fromPartial({sdk:Pe.JS,protocol:_t,version:Nt})}(),i);return new Promise(((t,a)=>{const abortHandler=()=>{o.close(),this.close(),a(new ConnectionError("room connection has been cancelled"))};(null==n?void 0:n.aborted)&&abortHandler(),null==n||n.addEventListener("abort",abortHandler),h.debug("connecting to ".concat(e+s)),this.ws=void 0;const o=new WebSocket(e+s);o.binaryType="arraybuffer",o.onerror=async t=>{if(this.ws)this.handleWSError(t);else try{const t=await fetch("http".concat(e.substring(2),"/validate").concat(s));if(t.ok)a(new ConnectionError("Internal error"));else{const e=await t.text();a(new ConnectionError(e))}}catch(e){a(new ConnectionError("server was not reachable"))}},o.onopen=()=>{this.ws=o,i.reconnect&&(this.isConnected=!0,t())},o.onmessage=async e=>{let i;if("string"==typeof e.data){const t=JSON.parse(e.data);i=He.fromJSON(t)}else{if(!(e.data instanceof ArrayBuffer))return void h.error("could not decode websocket message: ".concat(typeof e.data));i=He.decode(new Uint8Array(e.data))}this.isConnected?(this.signalLatency&&await sleep(this.signalLatency),this.handleSignalResponse(i)):i.join?(this.isConnected=!0,null==n||n.removeEventListener("abort",abortHandler),t(i.join)):a(new ConnectionError("did not receive join response"))},o.onclose=e=>{this.isConnected&&this.ws===o&&(h.debug("websocket connection closed: ".concat(e.reason)),this.isConnected=!1,this.onClose&&this.onClose(e.reason),this.ws===o&&(this.ws=void 0))}}))}close(){var e;this.isConnected=!1,this.ws&&(this.ws.onclose=null),null===(e=this.ws)||void 0===e||e.close(),this.ws=void 0}sendOffer(e){h.debug("sending offer",e),this.sendRequest({offer:toProtoSessionDescription(e)})}sendAnswer(e){h.debug("sending answer"),this.sendRequest({answer:toProtoSessionDescription(e)})}sendIceCandidate(e,t){h.trace("sending ice candidate",e),this.sendRequest({trickle:{candidateInit:JSON.stringify(e),target:t}})}sendMuteTrack(e,t){this.sendRequest({mute:{sid:e,muted:t}})}sendAddTrack(e){this.sendRequest({addTrack:Ke.fromPartial(e)})}sendUpdateTrackSettings(e){this.sendRequest({trackSetting:e})}sendUpdateSubscription(e){this.sendRequest({subscription:e})}sendSyncState(e){this.sendRequest({syncState:e})}sendUpdateVideoLayers(e,t){this.sendRequest({updateLayers:{trackSid:e,layers:t}})}sendUpdateSubscriptionPermissions(e,t){this.sendRequest({subscriptionPermission:{allParticipants:e,trackPermissions:t}})}sendSimulateScenario(e){this.sendRequest({simulate:e})}sendLeave(){this.sendRequest(Qe.fromPartial({leave:{}}))}async sendRequest(e){const t=!(arguments.length>1&&void 0!==arguments[1]&&arguments[1])&&!function canPassThroughQueue(e){const t=void 0!==Object.keys(e).find((e=>di.includes(e)));return h.trace("request allowed to bypass queue:",{canPass:t,req:e}),t}(e);if(!t||!this.isReconnecting&&this.requestQueue.isEmpty())if(this.signalLatency&&await sleep(this.signalLatency),this.ws)try{this.useJSON?this.ws.send(JSON.stringify(Qe.toJSON(e))):this.ws.send(Qe.encode(e).finish())}catch(e){h.error("error sending signal message",{error:e})}else h.error("cannot send signal request before connected");else this.requestQueue.enqueue((()=>this.sendRequest(e,!0)))}handleSignalResponse(e){if(e.answer){const t=fromProtoSessionDescription(e.answer);this.onAnswer&&this.onAnswer(t)}else if(e.offer){const t=fromProtoSessionDescription(e.offer);this.onOffer&&this.onOffer(t)}else if(e.trickle){const t=JSON.parse(e.trickle.candidateInit);this.onTrickle&&this.onTrickle(t,e.trickle.target)}else e.update?this.onParticipantUpdate&&this.onParticipantUpdate(e.update.participants):e.trackPublished?this.onLocalTrackPublished&&this.onLocalTrackPublished(e.trackPublished):e.speakersChanged?this.onSpeakersChanged&&this.onSpeakersChanged(e.speakersChanged.speakers):e.leave?this.onLeave&&this.onLeave(e.leave):e.mute?this.onRemoteMuteChanged&&this.onRemoteMuteChanged(e.mute.sid,e.mute.muted):e.roomUpdate?this.onRoomUpdate&&this.onRoomUpdate(e.roomUpdate.room):e.connectionQuality?this.onConnectionQuality&&this.onConnectionQuality(e.connectionQuality):e.streamStateUpdate?this.onStreamStateUpdate&&this.onStreamStateUpdate(e.streamStateUpdate):e.subscribedQualityUpdate?this.onSubscribedQualityUpdate&&this.onSubscribedQualityUpdate(e.subscribedQualityUpdate):e.subscriptionPermissionUpdate?this.onSubscriptionPermissionUpdate&&this.onSubscriptionPermissionUpdate(e.subscriptionPermissionUpdate):e.refreshToken?this.onTokenRefresh&&this.onTokenRefresh(e.refreshToken):e.trackUnpublished?this.onLocalTrackUnpublished&&this.onLocalTrackUnpublished(e.trackUnpublished):h.debug("unsupported message",e)}setReconnected(){this.isReconnecting=!1,this.requestQueue.run()}handleWSError(e){h.error("websocket error",e)}}function fromProtoSessionDescription(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 toProtoSessionDescription(e){return{sdp:e.sdp,type:e.type}}class PCTransport{constructor(e){this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate=!1,this.negotiate=r((()=>{this.createAndSendOffer()}),100),this.pc=new RTCPeerConnection(e)}get isICEConnected(){return"connected"===this.pc.iceConnectionState||"completed"===this.pc.iceConnectionState}async addIceCandidate(e){if(this.pc.remoteDescription&&!this.restartingIce)return this.pc.addIceCandidate(e);this.pendingCandidates.push(e)}async setRemoteDescription(e){await this.pc.setRemoteDescription(e),this.pendingCandidates.forEach((e=>{this.pc.addIceCandidate(e)})),this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate&&(this.renegotiate=!1,this.createAndSendOffer())}async createAndSendOffer(e){if(void 0===this.onOffer)return;if((null==e?void 0:e.iceRestart)&&(h.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);await this.pc.setRemoteDescription(t)}else if("closed"===this.pc.signalingState)return void h.warn("could not createOffer with closed peer connection");h.debug("starting to negotiate");const t=await this.pc.createOffer(e);await this.pc.setLocalDescription(t),this.onOffer(t)}close(){this.pc.close()}}const ui="_lossy",li="_reliable",hi=15e3;var pi;!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"}(pi||(pi={}));class RTCEngine extends Mt.exports.EventEmitter{constructor(){super(),this.rtcConfig={},this.subscriberPrimary=!1,this.pcState=pi.New,this._isClosed=!0,this.pendingTrackResolvers={},this.hasPublished=!1,this.reconnectAttempts=0,this.reconnectStart=0,this.fullReconnectOnNext=!1,this.handleDataChannel=async e=>{let{channel:t}=e;if(t){if(t.label===li)this.reliableDCSub=t;else{if(t.label!==ui)return;this.lossyDCSub=t}h.debug("on data channel ".concat(t.id,", ").concat(t.label)),t.onmessage=this.handleDataMessage}},this.handleDataMessage=async e=>{let t;if(e.data instanceof ArrayBuffer)t=e.data;else{if(!(e.data instanceof Blob))return void h.error("unsupported data type",e.data);t=await e.data.arrayBuffer()}const i=Ue.decode(new Uint8Array(t));i.speaker?this.emit(Pt.ActiveSpeakersUpdate,i.speaker.speakers):i.user&&this.emit(Pt.DataPacketReceived,i.user,i.kind)},this.handleDataError=e=>{const t=0===e.currentTarget.maxRetransmits?"lossy":"reliable";if(e instanceof ErrorEvent){const{error:i}=e.error;h.error("DataChannel error on ".concat(t,": ").concat(e.message),i)}else h.error("Unknown DataChannel Error on ".concat(t),e)},this.handleDisconnect=e=>{if(this._isClosed)return;h.debug("".concat(e," disconnected")),0===this.reconnectAttempts&&(this.reconnectStart=Date.now());const t=this.reconnectAttempts*this.reconnectAttempts*300;setTimeout((async()=>{var e;if(!this._isClosed){(isFireFox()||(null===(e=this.clientConfiguration)||void 0===e?void 0:e.resumeConnection)===Te.DISABLED)&&(this.fullReconnectOnNext=!0);try{this.fullReconnectOnNext?await this.restartConnection():await this.resumeConnection(),this.reconnectAttempts=0,this.fullReconnectOnNext=!1}catch(e){this.reconnectAttempts+=1;let t=!0;e instanceof UnexpectedConnectionState?(h.debug("received unrecoverable error",{error:e}),t=!1):e instanceof SignalReconnectError||(this.fullReconnectOnNext=!0);const i=Date.now()-this.reconnectStart;(this.reconnectAttempts>=10||i>6e4)&&(t=!1),t?this.handleDisconnect("reconnect"):(h.info("could not recover connection after ".concat(10," attempts, ").concat(i,"ms. giving up")),this.emit(Pt.Disconnected),this.close())}}}),t)},this.client=new SignalClient}get isClosed(){return this._isClosed}async join(e,t,i,n){this.url=e,this.token=t,this.signalOpts=i;const s=await this.client.join(e,t,i,n);return this._isClosed=!1,this.subscriberPrimary=s.subscriberPrimary,this.publisher||this.configure(s),this.subscriberPrimary||this.negotiate(),this.clientConfiguration=s.clientConfiguration,s}close(){this._isClosed=!0,this.removeAllListeners(),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){h.warn("could not removeTrack",{error:e})}})),this.publisher.close(),this.publisher=void 0),this.subscriber&&(this.subscriber.close(),this.subscriber=void 0),this.client.close()}addTrack(e){if(this.pendingTrackResolvers[e.cid])throw new TrackInvalidError("a track with the same ID has already been published");return new Promise((t=>{this.pendingTrackResolvers[e.cid]=t,this.client.sendAddTrack(e)}))}updateMuteStatus(e,t){this.client.sendMuteTrack(e,t)}get dataSubscriberReadyState(){var e;return null===(e=this.reliableDCSub)||void 0===e?void 0:e.readyState}get connectedServerAddress(){return this.connectedServerAddr}configure(e){if(this.publisher||this.subscriber)return;if(e.iceServers&&!this.rtcConfig.iceServers){const t=[];e.iceServers.forEach((e=>{const i={urls:e.urls};e.username&&(i.username=e.username),e.credential&&(i.credential=e.credential),t.push(i)})),this.rtcConfig.iceServers=t}this.rtcConfig.sdpSemantics="unified-plan",this.rtcConfig.continualGatheringPolicy="gather_continually",this.publisher=new PCTransport(this.rtcConfig),this.subscriber=new PCTransport(this.rtcConfig),this.emit(Pt.TransportsCreated,this.publisher,this.subscriber),this.publisher.pc.onicecandidate=e=>{e.candidate&&(h.trace("adding ICE candidate for peer",e.candidate),this.client.sendIceCandidate(e.candidate,$e.PUBLISHER))},this.subscriber.pc.onicecandidate=e=>{e.candidate&&this.client.sendIceCandidate(e.candidate,$e.SUBSCRIBER)},this.publisher.onOffer=e=>{this.client.sendOffer(e)};let t=this.publisher.pc,i=this.subscriber.pc;e.subscriberPrimary&&(t=this.subscriber.pc,i=this.publisher.pc,this.subscriber.pc.ondatachannel=this.handleDataChannel),this.primaryPC=t,t.onconnectionstatechange=async()=>{if(h.trace("connection state changed",{state:t.connectionState}),"connected"===t.connectionState){try{this.connectedServerAddr=await getConnectedAddress(t)}catch(e){h.warn("could not get connected server address",{error:e})}const e=this.pcState===pi.New;this.pcState=pi.Connected,e&&this.emit(Pt.Connected)}else"failed"===t.connectionState&&this.pcState===pi.Connected&&(this.pcState=pi.Disconnected,this.handleDisconnect("primary peerconnection"))},i.onconnectionstatechange=async()=>{"failed"===i.connectionState&&this.handleDisconnect("secondary peerconnection")},isWeb()?this.subscriber.pc.ontrack=e=>{this.emit(Pt.MediaTrackAdded,e.track,e.streams[0],e.receiver)}:this.subscriber.pc.onaddstream=e=>{const t=e.stream.getTracks()[0];this.emit(Pt.MediaTrackAdded,t,e.stream)},this.lossyDC=this.publisher.pc.createDataChannel(ui,{ordered:!0,maxRetransmits:0}),this.reliableDC=this.publisher.pc.createDataChannel(li,{ordered:!0}),this.lossyDC.onmessage=this.handleDataMessage,this.reliableDC.onmessage=this.handleDataMessage,this.lossyDC.onerror=this.handleDataError,this.reliableDC.onerror=this.handleDataError,this.client.onAnswer=async e=>{this.publisher&&(h.debug("received server answer",{RTCSdpType:e.type,signalingState:this.publisher.pc.signalingState}),await this.publisher.setRemoteDescription(e))},this.client.onTrickle=(e,t)=>{this.publisher&&this.subscriber&&(h.trace("got ICE candidate from peer",{candidate:e,target:t}),t===$e.PUBLISHER?this.publisher.addIceCandidate(e):this.subscriber.addIceCandidate(e))},this.client.onOffer=async e=>{if(!this.subscriber)return;h.debug("received server offer",{RTCSdpType:e.type,signalingState:this.subscriber.pc.signalingState}),await this.subscriber.setRemoteDescription(e);const t=await this.subscriber.pc.createAnswer();await this.subscriber.pc.setLocalDescription(t),this.client.sendAnswer(t)},this.client.onLocalTrackPublished=e=>{h.debug("received trackPublishedResponse",e);const t=this.pendingTrackResolvers[e.cid];t?(delete this.pendingTrackResolvers[e.cid],t(e.track)):h.error("missing track resolver for ".concat(e.cid))},this.client.onTokenRefresh=e=>{this.token=e},this.client.onClose=()=>{this.handleDisconnect("signal")},this.client.onLeave=e=>{(null==e?void 0:e.canReconnect)?(this.fullReconnectOnNext=!0,this.primaryPC=void 0):(this.emit(Pt.Disconnected),this.close())}}async restartConnection(){var e,t;if(!this.url||!this.token)throw new UnexpectedConnectionState("could not reconnect, url or token not saved");let i;h.info("reconnecting, attempt: ".concat(this.reconnectAttempts)),0===this.reconnectAttempts&&this.emit(Pt.Restarting),this.primaryPC=void 0,null===(e=this.publisher)||void 0===e||e.close(),this.publisher=void 0,null===(t=this.subscriber)||void 0===t||t.close(),this.subscriber=void 0;try{i=await this.join(this.url,this.token,this.signalOpts)}catch(e){throw new SignalReconnectError}await this.waitForPCConnected(),this.client.setReconnected(),this.emit(Pt.Restarted,i)}async resumeConnection(){if(!this.url||!this.token)throw new UnexpectedConnectionState("could not reconnect, url or token not saved");if(!this.publisher||!this.subscriber)throw new UnexpectedConnectionState("publisher and subscriber connections unset");h.info("resuming signal connection, attempt ".concat(this.reconnectAttempts)),0===this.reconnectAttempts&&this.emit(Pt.Resuming);try{await this.client.reconnect(this.url,this.token)}catch(e){throw new SignalReconnectError}this.emit(Pt.SignalResumed),this.subscriber.restartingIce=!0,this.hasPublished&&await this.publisher.createAndSendOffer({iceRestart:!0}),await this.waitForPCConnected(),this.client.setReconnected(),this.emit(Pt.Resumed)}async waitForPCConnected(){var e;const t=Date.now();let i=t;for(this.pcState=pi.Reconnecting,h.debug("waiting for peer connection to reconnect");i-t2e3&&"connected"===(null===(e=this.primaryPC)||void 0===e?void 0:e.connectionState)){this.pcState=pi.Connected;try{this.connectedServerAddr=await getConnectedAddress(this.primaryPC)}catch(e){h.warn("could not get connected server address",{error:e})}}if(this.pcState===pi.Connected)return;await sleep(100),i=Date.now()}throw new ConnectionError("could not establish PC connection")}async sendDataPacket(e,t){const i=Ue.encode(e).finish();await this.ensurePublisherConnected(t),t===Ce.LOSSY&&this.lossyDC?this.lossyDC.send(i):t===Ce.RELIABLE&&this.reliableDC&&this.reliableDC.send(i)}async ensurePublisherConnected(e){var t,i;if(!this.subscriberPrimary)return;if(!this.publisher)throw new ConnectionError("publisher connection not set");this.publisher.isICEConnected||"checking"===this.publisher.pc.iceConnectionState||this.negotiate();const n=this.dataChannelForKind(e);if("open"===(null==n?void 0:n.readyState))return;const s=(new Date).getTime()+hi;for(;(new Date).getTime(){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":s.set(e.id,"".concat(e.address,":").concat(e.port))}})),""===i)return;const a=null===(t=n.get(i))||void 0===t?void 0:t.remoteCandidateId;return void 0!==a?s.get(a):void 0}class SignalReconnectError extends Error{}const mi={audioBitrate:jt.speech.maxBitrate,dtx:!0,simulcast:!0,screenShareEncoding:$t.h1080fps15.encoding,stopMicTrackOnMute:!1},fi={autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0},vi={resolution:qt.h720.resolution};var gi;!function(e){e.Disconnected="disconnected",e.Connecting="connecting",e.Connected="connected",e.Reconnecting="reconnecting"}(gi||(gi={}));const Si=gi;class Room extends Mt.exports.EventEmitter{constructor(e){var t,i,n;switch(super(),t=this,this.state=gi.Disconnected,this.activeSpeakers=[],this.sid="",this.name="",this.metadata=void 0,this.audioEnabled=!0,this.connect=async(e,t,i)=>{var n,s;if(this.state===gi.Disconnected){this.setAndEmitConnectionState(gi.Connecting),this.abortController&&!this.abortController.signal.aborted||(this.abortController=new AbortController),this.createEngine(),this.acquireAudioContext(),(null==i?void 0:i.rtcConfig)&&(this.engine.rtcConfig=i.rtcConfig),this.connOptions=i;try{const a=await this.engine.join(e,t,{autoSubscribe:null==i?void 0:i.autoSubscribe,publishOnly:null==i?void 0:i.publishOnly,adaptiveStream:"object"==typeof(null===(n=this.options)||void 0===n?void 0:n.adaptiveStream)||(null===(s=this.options)||void 0===s?void 0:s.adaptiveStream)},this.abortController.signal);if(h.debug("connected to Livekit Server version: ".concat(a.serverVersion,", region: ").concat(a.serverRegion)),!a.serverVersion)throw new UnsupportedServer("unknown server version");"0.15.1"===a.serverVersion&&this.options.dynacast&&(h.debug("disabling dynacast due to server version"),this.options.dynacast=!1);const o=a.participant;this.localParticipant.sid=o.sid,this.localParticipant.identity=o.identity,this.localParticipant.updateInfo(o),this.localParticipant.on(Ct.ParticipantMetadataChanged,(e=>{this.emit(wt.ParticipantMetadataChanged,e,this.localParticipant)})).on(Ct.TrackMuted,(e=>{this.emit(wt.TrackMuted,e,this.localParticipant)})).on(Ct.TrackUnmuted,(e=>{this.emit(wt.TrackUnmuted,e,this.localParticipant)})).on(Ct.LocalTrackPublished,(e=>{this.emit(wt.LocalTrackPublished,e,this.localParticipant)})).on(Ct.LocalTrackUnpublished,(e=>{this.emit(wt.LocalTrackUnpublished,e,this.localParticipant)})).on(Ct.ConnectionQualityChanged,(e=>{this.emit(wt.ConnectionQualityChanged,e,this.localParticipant)})).on(Ct.MediaDevicesError,(e=>{this.emit(wt.MediaDevicesError,e)})).on(Ct.ParticipantPermissionsChanged,(e=>{this.emit(wt.ParticipantPermissionsChanged,e,this.localParticipant)})),a.otherParticipants.forEach((e=>{this.getOrCreateParticipant(e.sid,e)})),this.name=a.room.name,this.sid=a.room.sid,this.metadata=a.room.metadata}catch(e){throw this.engine.close(),this.setAndEmitConnectionState(gi.Disconnected),e}return new Promise(((e,t)=>{var i,n;const s=setTimeout((()=>{this.engine.close(),this.setAndEmitConnectionState(gi.Disconnected),t(new ConnectionError("could not connect after timeout"))}),hi),abortHandler=()=>{h.warn("closing engine"),clearTimeout(s),this.engine.close(),this.setAndEmitConnectionState(gi.Disconnected),t(new ConnectionError("room connection has been cancelled"))};(null===(i=this.abortController)||void 0===i?void 0:i.signal.aborted)&&abortHandler(),null===(n=this.abortController)||void 0===n||n.signal.addEventListener("abort",abortHandler),this.engine.once(Pt.Connected,(()=>{var t,i;clearTimeout(s),null===(t=this.abortController)||void 0===t||t.signal.removeEventListener("abort",abortHandler),isWeb()&&(window.addEventListener("beforeunload",this.onBeforeUnload),null===(i=navigator.mediaDevices)||void 0===i||i.addEventListener("devicechange",this.handleDeviceChange)),this.setAndEmitConnectionState(gi.Connected),e(this)}))}))}h.warn("already connected to room ".concat(this.name))},this.disconnect=function(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];var i;if(t.state===gi.Connecting)return h.warn("abort connection attempt"),void(null===(i=t.abortController)||void 0===i||i.abort());t.engine&&(t.engine.client.sendLeave(),t.engine.close()),t.handleDisconnect(e),t.engine=void 0},this.onBeforeUnload=()=>{this.disconnect()},this.handleRestarting=()=>{this.setAndEmitConnectionState(gi.Reconnecting),this.emit(wt.Reconnecting);for(const e of this.participants.values())this.handleParticipantDisconnected(e.sid,e)},this.handleRestarted=async e=>{h.debug("reconnected to server region ".concat(e.serverRegion)),this.setAndEmitConnectionState(gi.Connected),this.emit(wt.Reconnected),e.participant&&(this.localParticipant.sid=e.participant.sid,this.handleParticipantUpdates([e.participant])),this.handleParticipantUpdates(e.otherParticipants);const t=[];this.localParticipant.tracks.forEach((e=>{e.track&&t.push(e)})),await Promise.all(t.map((async e=>{const t=e.track;this.localParticipant.unpublishTrack(t,!1),this.localParticipant.publishTrack(t,e.options)})))},this.handleParticipantUpdates=e=>{e.forEach((e=>{if(e.sid===this.localParticipant.sid||e.identity===this.localParticipant.identity)return void this.localParticipant.updateInfo(e);let t=this.participants.get(e.sid);const i=!t;t=this.getOrCreateParticipant(e.sid,e),e.state===we.DISCONNECTED?this.handleParticipantDisconnected(e.sid,t):i?this.emit(wt.ParticipantConnected,t):t.updateInfo(e)}))},this.handleActiveSpeakersUpdate=e=>{const t=[],i={};e.forEach((e=>{if(i[e.sid]=!0,e.sid===this.localParticipant.sid)this.localParticipant.audioLevel=e.level,this.localParticipant.setIsSpeaking(!0),t.push(this.localParticipant);else{const i=this.participants.get(e.sid);i&&(i.audioLevel=e.level,i.setIsSpeaking(!0),t.push(i))}})),i[this.localParticipant.sid]||(this.localParticipant.audioLevel=0,this.localParticipant.setIsSpeaking(!1)),this.participants.forEach((e=>{i[e.sid]||(e.audioLevel=0,e.setIsSpeaking(!1))})),this.activeSpeakers=t,this.emit(wt.ActiveSpeakersChanged,t)},this.handleSpeakersChanged=e=>{const t=new Map;this.activeSpeakers.forEach((e=>{t.set(e.sid,e)})),e.forEach((e=>{let i=this.participants.get(e.sid);e.sid===this.localParticipant.sid&&(i=this.localParticipant),i&&(i.audioLevel=e.level,i.setIsSpeaking(e.active),e.active?t.set(e.sid,i):t.delete(e.sid))}));const i=Array.from(t.values());i.sort(((e,t)=>t.audioLevel-e.audioLevel)),this.activeSpeakers=i,this.emit(wt.ActiveSpeakersChanged,i)},this.handleStreamStateUpdate=e=>{e.streamStates.forEach((e=>{const t=this.participants.get(e.participantSid);if(!t)return;const i=t.getTrackPublication(e.trackSid);i&&i.track&&(i.track.streamState=Track.streamStateFromProto(e.state),t.emit(Ct.TrackStreamStateChanged,i,i.track.streamState),this.emit(Ct.TrackStreamStateChanged,i,i.track.streamState,t))}))},this.handleSubscriptionPermissionUpdate=e=>{const t=this.participants.get(e.participantSid);if(!t)return;const i=t.getTrackPublication(e.trackSid);i&&(i._allowed=e.allowed,t.emit(Ct.TrackSubscriptionPermissionChanged,i,i.subscriptionStatus),this.emit(Ct.TrackSubscriptionPermissionChanged,i,i.subscriptionStatus,t))},this.handleDataPacket=(e,t)=>{const i=this.participants.get(e.participantSid);this.emit(wt.DataReceived,e.payload,i,t),null==i||i.emit(Ct.DataReceived,e.payload,t)},this.handleAudioPlaybackStarted=()=>{this.canPlaybackAudio||(this.audioEnabled=!0,this.emit(wt.AudioPlaybackStatusChanged,!0))},this.handleAudioPlaybackFailed=e=>{h.warn("could not playback audio",e),this.canPlaybackAudio&&(this.audioEnabled=!1,this.emit(wt.AudioPlaybackStatusChanged,!1))},this.handleDeviceChange=async()=>{this.emit(wt.MediaDevicesChanged)},this.handleRoomUpdate=e=>{this.metadata=e.metadata,this.emit(wt.RoomMetadataChanged,e.metadata)},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.participants=new Map,this.options=e||{},null===(n=null===(i=this.options)||void 0===i?void 0:i.publishDefaults)||void 0===n?void 0:n.videoCodec){case"av1":case"vp9":this.options.publishDefaults.simulcast=void 0}this.options.audioCaptureDefaults=_objectSpread2(_objectSpread2({},fi),null==e?void 0:e.audioCaptureDefaults),this.options.videoCaptureDefaults=_objectSpread2(_objectSpread2({},vi),null==e?void 0:e.videoCaptureDefaults),this.options.publishDefaults=_objectSpread2(_objectSpread2({},mi),null==e?void 0:e.publishDefaults),this.createEngine(),this.localParticipant=new LocalParticipant("","",this.engine,this.options)}createEngine(){this.engine||(this.engine=new RTCEngine,this.engine.client.signalLatency=this.options.expSignalLatency,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.on(Pt.MediaTrackAdded,((e,t,i)=>{this.onTrackAdded(e,t,i)})).on(Pt.Disconnected,(()=>{this.handleDisconnect()})).on(Pt.ActiveSpeakersUpdate,this.handleActiveSpeakersUpdate).on(Pt.DataPacketReceived,this.handleDataPacket).on(Pt.Resuming,(()=>{this.setAndEmitConnectionState(gi.Reconnecting),this.emit(wt.Reconnecting)})).on(Pt.Resumed,(()=>{this.setAndEmitConnectionState(gi.Connected),this.emit(wt.Reconnected),this.updateSubscriptions()})).on(Pt.SignalResumed,(()=>{this.state===gi.Reconnecting&&this.sendSyncState()})).on(Pt.Restarting,this.handleRestarting).on(Pt.Restarted,this.handleRestarted))}static getLocalDevices(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return DeviceManager.getInstance().getDevices(e,t)}getParticipantByIdentity(e){for(const[,t]of this.participants)if(t.identity===e)return t;if(this.localParticipant.identity===e)return this.localParticipant}simulateScenario(e){let t;switch(e){case"speaker":t=yt.fromPartial({speakerUpdate:3});break;case"node-failure":t=yt.fromPartial({nodeFailure:!0});break;case"server-leave":t=yt.fromPartial({serverLeave:!0});break;case"migration":t=yt.fromPartial({migration:!0})}t&&this.engine.client.sendSimulateScenario(t)}async startAudio(){this.acquireAudioContext();const e=[];this.participants.forEach((t=>{t.audioTracks.forEach((t=>{t.track&&t.track.attachedElements.forEach((t=>{e.push(t)}))}))}));try{await Promise.all(e.map((e=>e.play()))),this.handleAudioPlaybackStarted()}catch(e){throw this.handleAudioPlaybackFailed(e),e}}get canPlaybackAudio(){return this.audioEnabled}async switchActiveDevice(e,t){if("audioinput"===e){const e=Array.from(this.localParticipant.audioTracks.values()).filter((e=>e.source===Track.Source.Microphone));await Promise.all(e.map((e=>{var i;return null===(i=e.audioTrack)||void 0===i?void 0:i.setDeviceId(t)}))),this.options.audioCaptureDefaults.deviceId=t}else if("videoinput"===e){const e=Array.from(this.localParticipant.videoTracks.values()).filter((e=>e.source===Track.Source.Camera));await Promise.all(e.map((e=>{var i;return null===(i=e.videoTrack)||void 0===i?void 0:i.setDeviceId(t)}))),this.options.videoCaptureDefaults.deviceId=t}else if("audiooutput"===e){const e=[];this.participants.forEach((t=>{t.audioTracks.forEach((t=>{t.isSubscribed&&t.track&&t.track.attachedElements.forEach((t=>{e.push(t)}))}))})),await Promise.all(e.map((async e=>{"setSinkId"in e&&await e.setSinkId(t)})))}}onTrackAdded(e,t,i){const n=function unpackStreamId(e){const t=e.split("|");return t.length>1?[t[0],e.substr(t[0].length+1)]:[e,""]}(t.id),s=n[0];let a=n[1];a&&""!==a||(a=e.id);const o=this.getOrCreateParticipant(s);let c;this.options.adaptiveStream&&(c="object"==typeof this.options.adaptiveStream?this.options.adaptiveStream:{}),o.addSubscribedMediaTrack(e,a,t,i,c)}handleDisconnect(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];var t;this.participants.forEach((e=>{e.tracks.forEach((t=>{e.unpublishTrack(t.trackSid)}))})),this.localParticipant.tracks.forEach((t=>{var i,n;t.track&&this.localParticipant.unpublishTrack(t.track),e&&(null===(i=t.track)||void 0===i||i.detach(),null===(n=t.track)||void 0===n||n.stop())})),this.participants.clear(),this.activeSpeakers=[],this.audioContext&&(this.audioContext.close(),this.audioContext=void 0),isWeb()&&(window.removeEventListener("beforeunload",this.onBeforeUnload),null===(t=navigator.mediaDevices)||void 0===t||t.removeEventListener("devicechange",this.handleDeviceChange)),this.setAndEmitConnectionState(gi.Disconnected),this.emit(wt.Disconnected)}handleParticipantDisconnected(e,t){this.participants.delete(e),t&&(t.tracks.forEach((e=>{t.unpublishTrack(e.trackSid)})),this.emit(wt.ParticipantDisconnected,t))}acquireAudioContext(){this.audioContext&&this.audioContext.close();const e=getNewAudioContext();e&&(this.audioContext=e)}createParticipant(e,t){let i;return i=t?RemoteParticipant.fromParticipantInfo(this.engine.client,t):new RemoteParticipant(this.engine.client,e,""),i}getOrCreateParticipant(e,t){if(this.participants.has(e))return this.participants.get(e);const i=this.createParticipant(e,t);return this.participants.set(e,i),i.on(Ct.TrackPublished,(e=>{this.emit(wt.TrackPublished,e,i)})).on(Ct.TrackSubscribed,((e,t)=>{e.kind===Track.Kind.Audio&&(e.on(Et.AudioPlaybackStarted,this.handleAudioPlaybackStarted),e.on(Et.AudioPlaybackFailed,this.handleAudioPlaybackFailed)),this.emit(wt.TrackSubscribed,e,t,i)})).on(Ct.TrackUnpublished,(e=>{this.emit(wt.TrackUnpublished,e,i)})).on(Ct.TrackUnsubscribed,((e,t)=>{this.emit(wt.TrackUnsubscribed,e,t,i)})).on(Ct.TrackSubscriptionFailed,(e=>{this.emit(wt.TrackSubscriptionFailed,e,i)})).on(Ct.TrackMuted,(e=>{this.emit(wt.TrackMuted,e,i)})).on(Ct.TrackUnmuted,(e=>{this.emit(wt.TrackUnmuted,e,i)})).on(Ct.ParticipantMetadataChanged,(e=>{this.emit(wt.ParticipantMetadataChanged,e,i)})).on(Ct.ConnectionQualityChanged,(e=>{this.emit(wt.ConnectionQualityChanged,e,i)})).on(Ct.ParticipantPermissionsChanged,(e=>{this.emit(wt.ParticipantPermissionsChanged,e,i)})),i}sendSyncState(){var e;if(void 0===this.engine.subscriber||null===this.engine.subscriber.pc.localDescription)return;const t=this.engine.subscriber.pc.localDescription,i=(null===(e=this.connOptions)||void 0===e?void 0:e.autoSubscribe)||!1,n=new Array;this.participants.forEach((e=>{e.tracks.forEach((e=>{e.isSubscribed!==i&&n.push(e.trackSid)}))})),this.engine.client.sendSyncState({answer:toProtoSessionDescription({sdp:t.sdp,type:t.type}),subscription:{trackSids:n,subscribe:!i,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 RemoteTrackPublication&&t.emitTrackUpdate()}setAndEmitConnectionState(e){e!==this.state&&(this.state=e,this.emit(wt.ConnectionStateChanged,this.state))}emit(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),n=1;n{const i="audio"===t.kind;let a;i?e.audio:e.video;const o=i?n.audio:n.video;"boolean"!=typeof o&&(a=o);const c=mediaTrackToLocalTrack(t,a);return c.kind===Track.Kind.Video?c.source=Track.Source.Camera:c.kind===Track.Kind.Audio&&(c.source=Track.Source.Microphone),c.mediaStream=s,c}))}async function createLocalVideoTrack(e){return(await createLocalTracks({audio:!1,video:e}))[0]}async function createLocalAudioTrack(e){return(await createLocalTracks({audio:e,video:!1}))[0]}async function createLocalScreenTracks(e){var t;void 0===e&&(e={}),void 0===e.resolution&&(e.resolution=qt.h1080.resolution);let i=!0;e.resolution&&(i={width:e.resolution.width,height:e.resolution.height});const n=await navigator.mediaDevices.getDisplayMedia({audio:null!==(t=e.audio)&&void 0!==t&&t,video:i}),s=n.getVideoTracks();if(0===s.length)throw new TrackInvalidError("no video track found");const a=new LocalVideoTrack(s[0]);a.source=Track.Source.ScreenShare;const o=[a];if(n.getAudioTracks().length>0){const e=new LocalAudioTrack(n.getAudioTracks()[0]);e.source=Track.Source.ScreenShareAudio,o.push(e)}return o}n=__webpack_require__.O(n),window.livekit=n})(); \ No newline at end of file diff --git a/Runtime/Scripts/Client.cs b/Runtime/Scripts/Client.cs index 3c9418c..3c7f826 100644 --- a/Runtime/Scripts/Client.cs +++ b/Runtime/Scripts/Client.cs @@ -42,17 +42,5 @@ public static JSPromise> CreateLocalScreenTracks(ScreenShare return JSRef.Acquire>>(JSNative.CallMethod(JSNative.LiveKit, "createLocalScreenTracks")); } - - [Obsolete("Use room.connect() instead")] - public static ConnectOperation Connect(string url, string token, ConnectOptions? options) - { - JSNative.PushString(url); - JSNative.PushString(token); - - if (options != null) - JSNative.PushStruct(JsonConvert.SerializeObject(options, JSNative.JsonSettings)); - - return JSRef.Acquire(JSNative.CallMethod(JSNative.LiveKit, "connect")); - } } } \ No newline at end of file diff --git a/Runtime/Scripts/Options.cs b/Runtime/Scripts/Options.cs index dd76d01..2ae8e02 100644 --- a/Runtime/Scripts/Options.cs +++ b/Runtime/Scripts/Options.cs @@ -49,48 +49,4 @@ public struct RoomConnectOptions [JsonProperty("publishOnly")] public string PublishOnly; } - - [Obsolete("Use new Room(RoomOptions) and room.connect(RoomConnectOptions) instead")] - public struct ConnectOptions - { - [JsonProperty("autoSubscribe")] - public bool? AutoSubscribe; - [JsonProperty("adaptiveStream")] - public bool? AdaptiveStream; - [JsonProperty("autoManageVideo")] - public bool? AutoManageVideo; - [JsonProperty("dynacast")] - public bool? Dynacast; - [JsonProperty("logLevel")] - public LogLevel? LogLevel; - [JsonProperty("iceServers")] - public RTCIceServer[] iceServers; - [JsonProperty("rtcConfig")] - public RTCConfiguration? RTCConfig; - [JsonProperty("audio")] - public bool? PublishAudio; - [JsonProperty("video")] - public bool? PublishVideo; - [JsonProperty("audioCaptureDefaults")] - public AudioCaptureOptions? AudioCaptureDefaults; - [JsonProperty("videoCaptureDefaults")] - public VideoCaptureOptions? VideoCaptureDefaults; - [JsonProperty("publishDefaults")] - public TrackPublishDefaults? PublishDefaults; - [JsonProperty("stopLocalTrackOnUnpublish")] - public bool? StopLocalTrackOnUnpublish; - [JsonProperty("expDisableLayerPause")] - public bool? ExpDisableLayerPause; - - // CreateLocalTracksOptions TODO - /*[JsonProperty("audio")] - public bool? AudioEnabled; - [JsonProperty("audio")] - public AudioCaptureOptions? Audio; - - [JsonProperty("video")] - public bool? VideoEnabled; - [JsonProperty("video")] - public VideoCaptureOptions? Video;*/ - } } \ No newline at end of file diff --git a/Runtime/Scripts/Room/Room.cs b/Runtime/Scripts/Room/Room.cs index 47b198e..e27bbe2 100644 --- a/Runtime/Scripts/Room/Room.cs +++ b/Runtime/Scripts/Room/Room.cs @@ -3,15 +3,16 @@ using AOT; using Newtonsoft.Json; using Newtonsoft.Json.Converters; -using UnityEngine; using UnityEngine.Scripting; namespace LiveKit { [JsonConverter(typeof(StringEnumConverter))] - public enum RoomState { + public enum ConnectionState { [EnumMember(Value = "disconnected")] Disconnected, + [EnumMember(Value = "connecting")] + Connecting, [EnumMember(Value = "connected")] Connected, [EnumMember(Value = "reconnecting")] @@ -23,7 +24,7 @@ public class Room : JSEventEmitter public delegate void ReconnectingDelegate(); public delegate void ReconnectedDelegate(); public delegate void DisconnectedDelegate(); - public delegate void StateChangedDelegate(RoomState state); + public delegate void StateChangedDelegate(ConnectionState state); public delegate void MediaDevicesChangedDelegate(); public delegate void ParticipantConnectedDelegate(RemoteParticipant participant); public delegate void ParticipantDisconnectedDelegate(RemoteParticipant participant); @@ -100,7 +101,7 @@ private static void EventReceived(IntPtr iptr) { var str = JSNative.GetString(JSNative.ShiftStack()); Log.Debug($"Room: Received StateChanged(\"{str}\""); - room.StateChanged?.Invoke(Utils.ToEnum(str)); + room.StateChanged?.Invoke(Utils.ToEnum(str)); break; } case RoomEvent.MediaDevicesChanged: @@ -293,13 +294,22 @@ private static void EventReceived(IntPtr iptr) throw; } } + + public bool IsClosed + { + get + { + JSNative.PushString("isClosed"); + return JSNative.GetBoolean(JSNative.GetProperty(NativeHandle)); + } + } - public RoomState State + public ConnectionState State { get { JSNative.PushString("state"); - return Utils.ToEnum(JSNative.GetString(JSNative.GetProperty(NativeHandle))); + return Utils.ToEnum(JSNative.GetString(JSNative.GetProperty(NativeHandle))); } } diff --git a/Runtime/Scripts/Room/Track/Options.cs b/Runtime/Scripts/Room/Track/Options.cs index 473c384..69b48fe 100644 --- a/Runtime/Scripts/Room/Track/Options.cs +++ b/Runtime/Scripts/Room/Track/Options.cs @@ -239,15 +239,10 @@ public class VideoPresets public static readonly VideoPreset H216 = new VideoPreset(384, 216, 180_000, 15); public static readonly VideoPreset H360 = new VideoPreset(640, 360, 300_000, 20); public static readonly VideoPreset H540 = new VideoPreset(960, 540, 600_000, 25); - public static readonly VideoPreset H720 = new VideoPreset(1280, 720, 2_000_000, 30); + public static readonly VideoPreset H720 = new VideoPreset(1280, 720, 1_700_000, 30); public static readonly VideoPreset H1080 = new VideoPreset(1920, 1080, 3_000_000, 30); public static readonly VideoPreset H1440 = new VideoPreset(2560, 1440, 5_000_000, 30); public static readonly VideoPreset H2160 = new VideoPreset(3840, 2160, 8_000_000, 30); - [Obsolete] public static readonly VideoPreset QVGA = new VideoPreset(320, 180, 120_000, 10); - [Obsolete] public static readonly VideoPreset VGA = new VideoPreset(320, 180, 120_000, 10); - [Obsolete] public static readonly VideoPreset QHD = new VideoPreset(320, 180, 120_000, 10); - [Obsolete] public static readonly VideoPreset HD = new VideoPreset(320, 180, 120_000, 10); - [Obsolete] public static readonly VideoPreset FHD = new VideoPreset(320, 180, 120_000, 10); } public class VideoPresets43 @@ -261,11 +256,6 @@ public class VideoPresets43 public static readonly VideoPreset H720 = new VideoPreset(960, 720, 1_500_000, 30); public static readonly VideoPreset H1080 = new VideoPreset(1440, 1080, 2_500_000, 30); public static readonly VideoPreset H1440 = new VideoPreset(1920, 1440, 3_500_000, 30); - [Obsolete] public static readonly VideoPreset QVGA = new VideoPreset(240, 180, 90_000, 10); - [Obsolete] public static readonly VideoPreset VGA = new VideoPreset(480, 360, 225_000, 20); - [Obsolete] public static readonly VideoPreset QHD = new VideoPreset(720, 540, 450_000, 25); - [Obsolete] public static readonly VideoPreset HD = new VideoPreset(960, 720, 1_500_000, 30); - [Obsolete] public static readonly VideoPreset FHD = new VideoPreset(1440, 1080, 2_800_000, 30); } public class ScreenSharePresets @@ -275,10 +265,5 @@ public class ScreenSharePresets public static readonly VideoPreset H720_FPS15 = new VideoPreset(1280, 720, 1_000_000, 15); public static readonly VideoPreset H1080_FPS15 = new VideoPreset(1920, 1080, 1_500_000, 15); public static readonly VideoPreset H1080_FPS30 = new VideoPreset(1920, 1080, 3_000_000, 30); - [Obsolete] public static readonly VideoPreset VGA = new VideoPreset(640, 360, 200_000, 3); - [Obsolete] public static readonly VideoPreset HD_8 = new VideoPreset(1280, 720, 400_000, 5); - [Obsolete] public static readonly VideoPreset HD_15 = new VideoPreset(1280, 720, 1_000_000, 15); - [Obsolete] public static readonly VideoPreset FHD_15 = new VideoPreset(1920, 1080, 1_500_000, 15); - [Obsolete] public static readonly VideoPreset FHD_30 = new VideoPreset(1920, 1080, 3_000_000, 30); } } \ No newline at end of file diff --git a/package.json b/package.json index d471f42..99ca577 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "io.livekit.unity", - "version": "0.2.1", + "version": "1.0.0", "displayName": "LiveKit WebGL SDK", "description": "LiveKit Unity Bridge for WebGL", "unity": "2021.3",