diff --git a/Bridge~/package.json b/Bridge~/package.json index 659bec9..ac10fbb 100644 --- a/Bridge~/package.json +++ b/Bridge~/package.json @@ -20,14 +20,14 @@ "author": "", "license": "ISC", "dependencies": { - "livekit-client": "^1.6.3", + "livekit-client": "^1.7.1", "typed-emitter": "^2.1.0" }, "devDependencies": { "ts-loader": "^9.2.6", "typescript": "^4.5.5", "webpack": "^5.68.0", - "webpack-cli": "^4.9.2" + "webpack-cli": "^5.0.1" }, "bugs": { "url": "https://github.com/livekit/client-sdk-unity-web/issues" diff --git a/Bridge~/yarn.lock b/Bridge~/yarn.lock index d16b37d..5dc9247 100644 --- a/Bridge~/yarn.lock +++ b/Bridge~/yarn.lock @@ -252,22 +252,20 @@ "@webassemblyjs/ast" "1.11.1" "@xtuc/long" "4.2.2" -"@webpack-cli/configtest@^1.2.0": - version "1.2.0" - resolved "https://registry.yarnpkg.com/@webpack-cli/configtest/-/configtest-1.2.0.tgz#7b20ce1c12533912c3b217ea68262365fa29a6f5" - integrity sha512-4FB8Tj6xyVkyqjj1OaTqCjXYULB9FMkqQ8yGrZjRDrYh0nOE+7Lhs45WioWQQMV+ceFlE368Ukhe6xdvJM9Egg== +"@webpack-cli/configtest@^2.0.1": + version "2.0.1" + resolved "https://registry.yarnpkg.com/@webpack-cli/configtest/-/configtest-2.0.1.tgz#a69720f6c9bad6aef54a8fa6ba9c3533e7ef4c7f" + integrity sha512-njsdJXJSiS2iNbQVS0eT8A/KPnmyH4pv1APj2K0d1wrZcBLw+yppxOy4CGqa0OxDJkzfL/XELDhD8rocnIwB5A== -"@webpack-cli/info@^1.5.0": - version "1.5.0" - resolved "https://registry.yarnpkg.com/@webpack-cli/info/-/info-1.5.0.tgz#6c78c13c5874852d6e2dd17f08a41f3fe4c261b1" - integrity sha512-e8tSXZpw2hPl2uMJY6fsMswaok5FdlGNRTktvFk2sD8RjH0hE2+XistawJx1vmKteh4NmGmNUrp+Tb2w+udPcQ== - dependencies: - envinfo "^7.7.3" +"@webpack-cli/info@^2.0.1": + version "2.0.1" + resolved "https://registry.yarnpkg.com/@webpack-cli/info/-/info-2.0.1.tgz#eed745799c910d20081e06e5177c2b2569f166c0" + integrity sha512-fE1UEWTwsAxRhrJNikE7v4EotYflkEhBL7EbajfkPlf6E37/2QshOy/D48Mw8G5XMFlQtS6YV42vtbG9zBpIQA== -"@webpack-cli/serve@^1.7.0": - version "1.7.0" - resolved "https://registry.yarnpkg.com/@webpack-cli/serve/-/serve-1.7.0.tgz#e1993689ac42d2b16e9194376cfb6753f6254db1" - integrity sha512-oxnCNGj88fL+xzV+dacXs44HcDwf1ovs3AuEzvP7mqXw7fQntqIhQ1BRmynh4qEKQSSSRSWVyXRjmTbZIX9V2Q== +"@webpack-cli/serve@^2.0.1": + version "2.0.1" + resolved "https://registry.yarnpkg.com/@webpack-cli/serve/-/serve-2.0.1.tgz#34bdc31727a1889198855913db2f270ace6d7bf8" + integrity sha512-0G7tNyS+yW8TdgHwZKlDWYXFA6OJQnoLCQvYKkQP0Q2X205PSQ6RNUj0M+1OB/9gRQaUZ/ccYfaxd0nhaWKfjw== "@xtuc/ieee754@^1.2.0": version "1.2.0" @@ -388,10 +386,10 @@ commander@^2.20.0: resolved "https://registry.yarnpkg.com/commander/-/commander-2.20.3.tgz#fd485e84c03eb4881c20722ba48035e8531aeb33" integrity sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ== -commander@^7.0.0: - version "7.2.0" - resolved "https://registry.yarnpkg.com/commander/-/commander-7.2.0.tgz#a36cb57d0b501ce108e4d20559a150a391d97ab7" - integrity sha512-QrWXB+ZQSVPmIWIhtEO9H+gwHaMGYiF5ChvoJ+K9ZGHG/sVsa6yiesAD1GC/x46sET00Xlwo1u49RVVVzvcSkw== +commander@^9.4.1: + version "9.5.0" + resolved "https://registry.yarnpkg.com/commander/-/commander-9.5.0.tgz#bc08d1eb5cedf7ccb797a96199d41c7bc3e60d30" + integrity sha512-KRs7WVDKg86PWiuAqhDrAQnTXZKraVcCc6vFdL14qrZ/DcWwuRo7VoiYXalXO7S5GKpqYiVEwCbgFDfxNHKJBQ== cross-spawn@^7.0.3: version "7.0.3" @@ -525,15 +523,15 @@ import-local@^3.0.2: pkg-dir "^4.2.0" resolve-cwd "^3.0.0" -interpret@^2.2.0: - version "2.2.0" - resolved "https://registry.yarnpkg.com/interpret/-/interpret-2.2.0.tgz#1a78a0b5965c40a5416d007ad6f50ad27c417df9" - integrity sha512-Ju0Bz/cEia55xDwUWEa8+olFpCiQoypjnQySseKtmjNrnps3P+xfpUmGr90T7yjlVJmOtybRvPXhKMbHr+fWnw== +interpret@^3.1.1: + version "3.1.1" + resolved "https://registry.yarnpkg.com/interpret/-/interpret-3.1.1.tgz#5be0ceed67ca79c6c4bc5cf0d7ee843dcea110c4" + integrity sha512-6xwYfHbajpoF0xLW+iwLkhwgvLoZDfjYfoFNu8ftMoXINzwuymNLd9u/KmwtdT2GbR+/Cz66otEGEVVUHX9QLQ== -is-core-module@^2.8.1: - version "2.9.0" - resolved "https://registry.yarnpkg.com/is-core-module/-/is-core-module-2.9.0.tgz#e1c34429cd51c6dd9e09e0799e396e27b19a9c69" - integrity sha512-+5FPy5PnwmO3lvfMb0AsoPaBG+5KHUI0wYFXOtYPnVVVspTFUuMZNfNaNVRt3FZadstu2c8x23vykRW/NBoU6A== +is-core-module@^2.11.0: + version "2.11.0" + resolved "https://registry.yarnpkg.com/is-core-module/-/is-core-module-2.11.0.tgz#ad4cb3e3863e814523c96f3f58d26cc570ff0144" + integrity sha512-RRjxlvLDkD1YJwDbroBHMb+cukurkDWNyHx7D3oNB5x9rb5ogcksMC5wHCadcXoo67gVr/+3GFySh3134zi6rw== dependencies: has "^1.0.3" @@ -583,10 +581,10 @@ kind-of@^6.0.2: resolved "https://registry.yarnpkg.com/kind-of/-/kind-of-6.0.3.tgz#07c05034a6c349fa06e24fa35aa76db4580ce4dd" integrity sha512-dcS1ul+9tmeD95T+x28/ehLgd9mENa3LsvDTtzm3vyBEO7RPptvAD+t44WVXaUjTBRcrpFeFlC8WCruUR456hw== -livekit-client@^1.6.3: - version "1.6.3" - resolved "https://registry.yarnpkg.com/livekit-client/-/livekit-client-1.6.3.tgz#4ff46f1fbdaaa7982c339738964d18e8b43fd3d5" - integrity sha512-hnVN/rQ9pVWK0L1lemLSOzBI6IXoJepgHP/USqmGJ6eucaoLMx1jK0iMWpR5T2/pg97GmZaUaRSUcXlELNSsoA== +livekit-client@^1.7.1: + version "1.7.1" + resolved "https://registry.yarnpkg.com/livekit-client/-/livekit-client-1.7.1.tgz#0d21f8484c52ca858e474a9ebe844de143874f71" + integrity sha512-MFLgXdyxd6VateuHFn+diXqFtuaQc/cB4TZBkAJMCMN7oXIvo0IxEEK+wsqRyEloln4eEBNjpFNZiIffJ2Ph9A== dependencies: async-await-queue "^1.2.1" events "^3.3.0" @@ -743,12 +741,12 @@ randombytes@^2.1.0: dependencies: safe-buffer "^5.1.0" -rechoir@^0.7.0: - version "0.7.1" - resolved "https://registry.yarnpkg.com/rechoir/-/rechoir-0.7.1.tgz#9478a96a1ca135b5e88fc027f03ee92d6c645686" - integrity sha512-/njmZ8s1wVeR6pjTZ+0nCnv8SpZNRMT2D1RLOJQESlYFDBvwpTA4KWJpZ+sBJ4+vhjILRcK7JIFdGCdxEAAitg== +rechoir@^0.8.0: + version "0.8.0" + resolved "https://registry.yarnpkg.com/rechoir/-/rechoir-0.8.0.tgz#49f866e0d32146142da3ad8f0eff352b3215ff22" + integrity sha512-/vxpCXddiX8NGfGO/mTafwjq4aFa/71pvamip0++IQk3zG8cbCj0fifNPrjjF1XMXUne91jL9OoxmdykoEtifQ== dependencies: - resolve "^1.9.0" + resolve "^1.20.0" resolve-cwd@^3.0.0: version "3.0.0" @@ -762,12 +760,12 @@ resolve-from@^5.0.0: resolved "https://registry.yarnpkg.com/resolve-from/-/resolve-from-5.0.0.tgz#c35225843df8f776df21c57557bc087e9dfdfc69" integrity sha512-qYg9KP24dD5qka9J47d0aVky0N+b4fTU89LN9iDnjB5waksiC49rvMB0PrUJQGoTmH50XPiqOvAjDfaijGxYZw== -resolve@^1.9.0: - version "1.22.0" - resolved "https://registry.yarnpkg.com/resolve/-/resolve-1.22.0.tgz#5e0b8c67c15df57a89bdbabe603a002f21731198" - integrity sha512-Hhtrw0nLeSrFQ7phPp4OOcVjLPIeMnRlr5mcnVuMe7M/7eBn98A3hmFRLoFo3DLZkivSYwhRUJTyPyWAk56WLw== +resolve@^1.20.0: + version "1.22.2" + resolved "https://registry.yarnpkg.com/resolve/-/resolve-1.22.2.tgz#0ed0943d4e301867955766c9f3e1ae6d01c6845f" + integrity sha512-Sb+mjNHOULsBv818T40qSPeRiuWLyaGMa5ewydRLFimneixmVy2zdivRl+AF6jaYPC8ERxGDmFSiqui6SfPd+g== dependencies: - is-core-module "^2.8.1" + is-core-module "^2.11.0" path-parse "^1.0.7" supports-preserve-symlinks-flag "^1.0.0" @@ -952,22 +950,23 @@ watchpack@^2.3.1: glob-to-regexp "^0.4.1" graceful-fs "^4.1.2" -webpack-cli@^4.9.2: - version "4.10.0" - resolved "https://registry.yarnpkg.com/webpack-cli/-/webpack-cli-4.10.0.tgz#37c1d69c8d85214c5a65e589378f53aec64dab31" - integrity sha512-NLhDfH/h4O6UOy+0LSso42xvYypClINuMNBVVzX4vX98TmTaTUxwRbXdhucbFMd2qLaCTcLq/PdYrvi8onw90w== +webpack-cli@^5.0.1: + version "5.0.1" + resolved "https://registry.yarnpkg.com/webpack-cli/-/webpack-cli-5.0.1.tgz#95fc0495ac4065e9423a722dec9175560b6f2d9a" + integrity sha512-S3KVAyfwUqr0Mo/ur3NzIp6jnerNpo7GUO6so51mxLi1spqsA17YcMXy0WOIJtBSnj748lthxC6XLbNKh/ZC+A== dependencies: "@discoveryjs/json-ext" "^0.5.0" - "@webpack-cli/configtest" "^1.2.0" - "@webpack-cli/info" "^1.5.0" - "@webpack-cli/serve" "^1.7.0" + "@webpack-cli/configtest" "^2.0.1" + "@webpack-cli/info" "^2.0.1" + "@webpack-cli/serve" "^2.0.1" colorette "^2.0.14" - commander "^7.0.0" + commander "^9.4.1" cross-spawn "^7.0.3" + envinfo "^7.7.3" fastest-levenshtein "^1.0.12" import-local "^3.0.2" - interpret "^2.2.0" - rechoir "^0.7.0" + interpret "^3.1.1" + rechoir "^0.8.0" webpack-merge "^5.7.3" webpack-merge@^5.7.3: diff --git a/Runtime/Plugins/livekit-client.jspre b/Runtime/Plugins/livekit-client.jspre index 1b54a3c..f7b046d 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 o=1/0;for(l=0;l=s)&&Object.keys(__webpack_require__.O).every((e=>__webpack_require__.O[e](i[c])))?i.splice(c--,1):(a=!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,[o,a,c]=i,u=0;if(o.some((t=>0!==e[t]))){for(n in a)__webpack_require__.o(a,n)&&(__webpack_require__.m[n]=a[n]);if(c)var l=c(__webpack_require__)}for(t&&t(i);uyi,ConnectionCheck:()=>ConnectionCheck,ConnectionError:()=>ConnectionError,ConnectionQuality:()=>Pi,ConnectionState:()=>en,CriticalTimers:()=>CriticalTimers,DataPacket_Kind:()=>Ae,DefaultReconnectPolicy:()=>DefaultReconnectPolicy,DisconnectReason:()=>Ie,EngineEvent:()=>Yt,LivekitError:()=>LivekitError,LocalAudioTrack:()=>LocalAudioTrack,LocalParticipant:()=>LocalParticipant,LocalTrack:()=>LocalTrack,LocalTrackPublication:()=>LocalTrackPublication,LocalVideoTrack:()=>LocalVideoTrack,LogLevel:()=>u,MediaDeviceFailure:()=>Ht,NegotiationError:()=>NegotiationError,Participant:()=>Participant,ParticipantEvent:()=>Kt,PublishDataError:()=>PublishDataError,RemoteAudioTrack:()=>RemoteAudioTrack,RemoteParticipant:()=>RemoteParticipant,RemoteTrack:()=>RemoteTrack,RemoteTrackPublication:()=>RemoteTrackPublication,RemoteVideoTrack:()=>RemoteVideoTrack,Room:()=>Room,RoomEvent:()=>Zt,RoomState:()=>tn,ScreenSharePresets:()=>Ci,Track:()=>Track,TrackEvent:()=>Xt,TrackInvalidError:()=>TrackInvalidError,TrackPublication:()=>TrackPublication,UnexpectedConnectionState:()=>UnexpectedConnectionState,UnsupportedServer:()=>UnsupportedServer,VideoPreset:()=>VideoPreset,VideoPresets:()=>wi,VideoPresets43:()=>Ti,VideoQuality:()=>Re,attachToElement:()=>attachToElement,createAudioAnalyser:()=>createAudioAnalyser,createLocalAudioTrack:()=>createLocalAudioTrack,createLocalScreenTracks:()=>createLocalScreenTracks,createLocalTracks:()=>createLocalTracks,createLocalVideoTrack:()=>createLocalVideoTrack,detachTrack:()=>detachTrack,getEmptyAudioStreamTrack:()=>getEmptyAudioStreamTrack,getEmptyVideoStreamTrack:()=>getEmptyVideoStreamTrack,isBackupCodec:()=>isBackupCodec,isBrowserSupported:()=>isBrowserSupported,protocolVersion:()=>si,setLogExtension:()=>setLogExtension,setLogLevel:()=>setLogLevel,supportsAV1:()=>supportsAV1,supportsAdaptiveStream:()=>supportsAdaptiveStream,supportsDynacast:()=>supportsDynacast,version:()=>ri});var s="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function getDefaultExportFromCjs(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var o,a,c,u,l={};a=s,c=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<=a.levels.SILENT))throw"log.setLevel() called with invalid level: "+n;if(o=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(a,n,t),typeof console===e&&n{const o=t(i,n,s),a=h.getLevel(),c=n>=a&&n{i?o(t,i):o(t),c&&e(n,t,i)}},h.setLevel(h.getLevel())}h.setLevel(u.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:T;if(t){if(e<0)return C;if(e>=k)return N}else{if(e<=-y)return I;if(e+1>=y)return O}return e<0?fromNumber(-e,t).neg():fromBits(e%S|0,e/S|0,t)}function fromBits(e,t,i){return new Long(e,t,i)}Long.fromInt=fromInt,Long.fromNumber=fromNumber,Long.fromBits=fromBits;var b=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 T;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(b(i,8)),o=T,a=0;a>>0:this.low},D.toNumber=function toNumber(){return this.unsigned?(this.high>>>0)*S+(this.low>>>0):this.high*S+(this.low>>>0)},D.toString=function toString(e){if((e=e||10)<2||36>>0).toString(e);if((o=c).isZero())return u+a;for(;u.length<6;)u="0"+u;a=""+u+a}},D.getHighBits=function getHighBits(){return this.high},D.getHighBitsUnsigned=function getHighBitsUnsigned(){return this.high>>>0},D.getLowBits=function getLowBits(){return this.low},D.getLowBitsUnsigned=function getLowBitsUnsigned(){return this.low>>>0},D.getNumBitsAbs=function getNumBitsAbs(){if(this.isNegative())return this.eq(I)?64:this.neg().getNumBitsAbs();for(var e=0!=this.high?this.high:this.low,t=31;t>0&&0==(e&1<=0},D.isOdd=function isOdd(){return 1==(1&this.low)},D.isEven=function isEven(){return 0==(1&this.low)},D.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)},D.eq=D.equals,D.notEquals=function notEquals(e){return!this.eq(e)},D.neq=D.notEquals,D.ne=D.notEquals,D.lessThan=function lessThan(e){return this.comp(e)<0},D.lt=D.lessThan,D.lessThanOrEqual=function lessThanOrEqual(e){return this.comp(e)<=0},D.lte=D.lessThanOrEqual,D.le=D.lessThanOrEqual,D.greaterThan=function greaterThan(e){return this.comp(e)>0},D.gt=D.greaterThan,D.greaterThanOrEqual=function greaterThanOrEqual(e){return this.comp(e)>=0},D.gte=D.greaterThanOrEqual,D.ge=D.greaterThanOrEqual,D.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},D.comp=D.compare,D.negate=function negate(){return!this.unsigned&&this.eq(I)?I:this.not().add(P)},D.neg=D.negate,D.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,o=e.high>>>16,a=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+a)>>>16,u+=t+o,fromBits((h&=65535)<<16|(p&=65535),(u&=65535)<<16|(l&=65535),this.unsigned)},D.subtract=function subtract(e){return isLong(e)||(e=fromValue(e)),this.add(e.neg())},D.sub=D.subtract,D.multiply=function multiply(e){if(this.isZero())return T;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 T;if(this.eq(I))return e.isOdd()?I:T;if(e.eq(I))return this.isOdd()?I:T;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(w)&&e.lt(w))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,o=e.high>>>16,a=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*a)>>>16,l+=t*u+i*c+n*a+s*o,fromBits((p&=65535)<<16|(v&=65535),(l&=65535)<<16|(h&=65535),this.unsigned)},D.mul=D.multiply,D.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:T;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(I))return e.eq(P)||e.eq(R)?I:e.eq(I)?P:(t=this.shr(1).div(e).shl(1)).eq(T)?e.isNegative()?P:R:(i=this.sub(e.mul(t)),n=t.add(i.div(e)));if(e.eq(I))return this.unsigned?C:T;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=T}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),o=s<=48?1:b(2,s-48),a=fromNumber(t),c=a.mul(e);c.isNegative()||c.gt(i);)c=(a=fromNumber(t-=o,this.unsigned)).mul(e);a.isZero()&&(a=P),n=n.add(a),i=i.sub(c)}return n},D.div=D.divide,D.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))},D.mod=D.modulo,D.rem=D.modulo,D.not=function not(){return fromBits(~this.low,~this.high,this.unsigned)},D.and=function and(e){return isLong(e)||(e=fromValue(e)),fromBits(this.low&e.low,this.high&e.high,this.unsigned)},D.or=function or(e){return isLong(e)||(e=fromValue(e)),fromBits(this.low|e.low,this.high|e.high,this.unsigned)},D.xor=function xor(e){return isLong(e)||(e=fromValue(e)),fromBits(this.low^e.low,this.high^e.high,this.unsigned)},D.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)},D.shr=D.shiftRight,D.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)},D.shru=D.shiftRightUnsigned,D.shr_u=D.shiftRightUnsigned,D.toSigned=function toSigned(){return this.unsigned?fromBits(this.low,this.high,!1):this},D.toUnsigned=function toUnsigned(){return this.unsigned?this:fromBits(this.low,this.high,!0)},D.toBytes=function toBytes(e){return e?this.toBytesLE():this.toBytesBE()},D.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]},D.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 _,A,L={},U={get exports(){return L},set exports(e){L=e}},x={},M={};var $,B,F,J,V,j,W,q={};var G,Q,z,H,Z,K,Y={};function requireMinimal(){return K||(K=1,function(e){var t=e;function merge(e,t,i){for(var n=Object.keys(t),s=0;se,set:void 0,enumerable:!1,configurable:!0},toString:{value(){return this.name+": "+this.message},writable:!0,enumerable:!1,configurable:!0}}),CustomError}t.asPromise=function requireAspromise(){return A||(A=1,_=function asPromise(e,t){for(var i=new Array(arguments.length-1),n=0,s=2,o=!0;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,o=null,a=[],c=0,u=0;t>2],s=(3&l)<<4,u=1;break;case 1:a[c++]=i[s|l>>4],s=(15&l)<<2,u=2;break;case 2:a[c++]=i[s|l>>6],a[c++]=i[63&l],u=0}c>8191&&((o||(o=[])).push(String.fromCharCode.apply(String,a)),c=0)}return u&&(a[c++]=i[s],a[c++]=61,1===u&&(a[c++]=61)),o?(c&&o.push(String.fromCharCode.apply(String,a.slice(0,c))),o.join("")):String.fromCharCode.apply(String,a.slice(0,c))};var o="invalid encoding";t.decode=function decode(e,t,i){for(var s,a=i,c=0,u=0;u1)break;if(void 0===(l=n[l]))throw Error(o);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(o);return i-a},t.test=function test(e){return/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(e)}}(q)),q}(),t.EventEmitter=function requireEventemitter(){if(F)return B;function EventEmitter(){this._listeners={}}return F=1,B=EventEmitter,EventEmitter.prototype.on=function on(e,t,i){return(this._listeners[e]||(this._listeners[e]=[])).push({fn:t,ctx:i||this}),this},EventEmitter.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 o=Math.floor(Math.log(t)/Math.LN2);e((s<<31|o+127<<23|8388607&Math.round(t*Math.pow(2,-o)*8388608))>>>0,i,n)}}function readFloat_ieee754(e,t,i){var n=e(t,i),s=2*(n>>31)+1,o=n>>>23&255,a=8388607&n;return 255===o?a?NaN:s*(1/0):0===o?1401298464324817e-60*s*a:s*Math.pow(2,o-150)*(a+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,o){var a=n<0?1:0;if(a&&(n=-n),0===n)e(0,s,o+t),e(1/n>0?0:2147483648,s,o+i);else if(isNaN(n))e(0,s,o+t),e(2146959360,s,o+i);else if(n>17976931348623157e292)e(0,s,o+t),e((a<<31|2146435072)>>>0,s,o+i);else{var c;if(n<22250738585072014e-324)e((c=n/5e-324)>>>0,s,o+t),e((a<<31|c/4294967296)>>>0,s,o+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,o+t),e((a<<31|u+1023<<20|1048576*c&1048575)>>>0,s,o+i)}}}function readDouble_ieee754(e,t,i,n,s){var o=e(n,s+t),a=e(n,s+i),c=2*(a>>31)+1,u=a>>>20&2047,l=4294967296*(1048575&a)+o;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}return V=1,J=factory(factory)}(),t.inquire=function requireInquire(){return W?j:(W=1,j=function inquire(e){try{}catch(e){}return null})}(),t.utf8=function requireUtf8(){return G||(G=1,function(e){var t=e;t.length=function utf8_length(e){for(var t=0,i=0,n=0;n191&&n<224?o[a++]=(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,o[a++]=55296+(n>>10),o[a++]=56320+(1023&n)):o[a++]=(15&n)<<12|(63&e[t++])<<6|63&e[t++],a>8191&&((s||(s=[])).push(String.fromCharCode.apply(String,o)),a=0);return s?(a&&s.push(String.fromCharCode.apply(String,o.slice(0,a))),s.join("")):String.fromCharCode.apply(String,o.slice(0,a))},t.write=function utf8_write(e,t,i){for(var n,s,o=i,a=0;a>6|192,t[i++]=63&n|128):55296==(64512&n)&&56320==(64512&(s=e.charCodeAt(a+1)))?(n=65536+((1023&n)<<10)+(1023&s),++a,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-o}}(Y)),Y}(),t.pool=function requirePool(){return z?Q:(z=1,Q=function pool(e,t,i){var n=i||8192,s=n>>>1,o=null,a=n;return function pool_alloc(i){if(i<1||i>s)return e(i);a+i>n&&(o=e(n),a=0);var c=t.call(o,a,a+=i);return 7&a&&(a=1+(7|a)),c}})}(),t.LongBits=function requireLongbits(){if(Z)return H;Z=1,H=LongBits;var e=requireMinimal();function LongBits(e,t){this.lo=e>>>0,this.hi=t>>>0}var t=LongBits.zero=new LongBits(0,0);t.toNumber=function(){return 0},t.zzEncode=t.zzDecode=function(){return this},t.length=function(){return 1};var i=LongBits.zeroHash="\0\0\0\0\0\0\0\0";LongBits.fromNumber=function fromNumber(e){if(0===e)return t;var i=e<0;i&&(e=-e);var n=e>>>0,s=(e-n)/4294967296>>>0;return i&&(s=~s>>>0,n=~n>>>0,++n>4294967295&&(n=0,++s>4294967295&&(s=0))),new LongBits(n,s)},LongBits.from=function from(i){if("number"==typeof i)return LongBits.fromNumber(i);if(e.isString(i)){if(!e.Long)return LongBits.fromNumber(parseInt(i,10));i=e.Long.fromString(i)}return i.low||i.high?new LongBits(i.low>>>0,i.high>>>0):t},LongBits.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.prototype.toLong=function toLong(t){return e.Long?new e.Long(0|this.lo,0|this.hi,Boolean(t)):{low:0|this.lo,high:0|this.hi,unsigned:Boolean(t)}};var n=String.prototype.charCodeAt;return LongBits.fromHash=function fromHash(e){return e===i?t:new LongBits((n.call(e,0)|n.call(e,1)<<8|n.call(e,2)<<16|n.call(e,3)<<24)>>>0,(n.call(e,4)|n.call(e,5)<<8|n.call(e,6)<<16|n.call(e,7)<<24)>>>0)},LongBits.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.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.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.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},H}(),t.isNode=Boolean(void 0!==s&&s&&s.process&&s.process.versions&&s.process.versions.node),t.global=t.isNode&&s||"undefined"!=typeof window&&window||"undefined"!=typeof self&&self||s,t.emptyArray=Object.freeze?Object.freeze([]):[],t.emptyObject=Object.freeze?Object.freeze({}):{},t.isInteger=Number.isInteger||function isInteger(e){return"number"==typeof e&&isFinite(e)&&Math.floor(e)===e},t.isString=function isString(e){return"string"==typeof e||e instanceof String},t.isObject=function isObject(e){return e&&"object"==typeof e},t.isset=t.isSet=function isSet(e,t){var i=e[t];return!(null==i||!e.hasOwnProperty(t))&&("object"!=typeof i||(Array.isArray(i)?i.length:Object.keys(i).length)>0)},t.Buffer=function(){try{var e=t.inquire("buffer").Buffer;return e.prototype.utf8Write?e:null}catch(e){return null}}(),t._Buffer_from=null,t._Buffer_allocUnsafe=null,t.newBuffer=function 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=se(),Writer$1.alloc=function alloc(e){return new te.Array(e)},te.Array!==Array&&(Writer$1.alloc=te.pool(Writer$1.alloc,te.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,ie.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=ie.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=ie.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=ie.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(te.float.writeFloatLE,4,e)},Writer$1.prototype.double=function write_double(e){return this._push(te.float.writeDoubleLE,8,e)};var oe=te.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(te.isString(e)){var i=Writer$1.alloc(t=ne.length(e));ne.decode(e,i,0),e=i}return this.uint32(t)._push(oe,t,e)},Writer$1.prototype.string=function write_string(e){var t=re.length(e);return t?this.uint32(t)._push(re.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){X=e,Writer$1.create=se(),X._configure()};var ae=BufferWriter,ce=ee;(BufferWriter.prototype=Object.create(ce.prototype)).constructor=BufferWriter;var de=requireMinimal();function BufferWriter(){ce.call(this)}function writeStringBuffer(e,t,i){e.length<40?de.utf8.write(e,t,i):t.utf8Write?t.utf8Write(e,i):t.write(e,i)}BufferWriter._configure=function(){BufferWriter.alloc=de._Buffer_allocUnsafe,BufferWriter.writeBytesBuffer=de.Buffer&&de.Buffer.prototype instanceof Uint8Array&&"set"===de.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=de.Buffer.byteLength(e);return this.uint32(t),t&&this._push(writeStringBuffer,t,e),this},BufferWriter._configure();var ue,le=Reader$1,he=requireMinimal(),pe=he.LongBits,me=he.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 fe="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")},ve=function create(){return he.Buffer?function create_buffer_setup(e){return(Reader$1.create=function create_buffer(e){return he.Buffer.isBuffer(e)?new ue(e):fe(e)})(e)}:fe};function readLongVarint(){var e=new pe(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 pe(readFixed32_end(this.buf,this.pos+=4),readFixed32_end(this.buf,this.pos+=4))}Reader$1.create=ve(),Reader$1.prototype._slice=he.Array.prototype.subarray||he.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=he.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=he.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 me.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){ue=e,Reader$1.create=ve(),ue._configure();var t=he.Long?"toLong":"toNumber";he.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 ge=BufferReader,be=le;(BufferReader.prototype=Object.create(be.prototype)).constructor=BufferReader;var Se=requireMinimal();function BufferReader(e){be.call(this,e)}BufferReader._configure=function(){Se.Buffer&&(BufferReader.prototype._slice=Se.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 ke,ye={},we=Service,Te=requireMinimal();function Service(e,t,i){if("function"!=typeof e)throw TypeError("rpcImpl must be a function");Te.EventEmitter.call(this),this.rpcImpl=e,this.requestDelimited=Boolean(t),this.responseDelimited=Boolean(i)}(Service.prototype=Object.create(Te.EventEmitter.prototype)).constructor=Service,Service.prototype.rpcCall=function rpcCall(e,t,i,n,s){if(!n)throw TypeError("request must be specified");var o=this;if(!s)return Te.asPromise(rpcCall,o,e,t,i,n);if(o.rpcImpl)try{return o.rpcImpl(e,t[o.requestDelimited?"encodeDelimited":"encode"](n).finish(),(function rpcCallback(t,n){if(t)return o.emit("error",t,e),s(t);if(null!==n){if(!(n instanceof i))try{n=i[o.responseDelimited?"decodeDelimited":"decode"](n)}catch(t){return o.emit("error",t,e),s(t)}return o.emit("data",n,e),s(null,n)}o.end(!0)}))}catch(t){return o.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},ke=ye,ke.Service=we;var Ce={};!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=ee,t.BufferWriter=ae,t.Reader=le,t.BufferReader=ge,t.util=requireMinimal(),t.rpc=ye,t.roots=Ce,t.configure=configure,configure()}(x),function(e){e.exports=x}(U);var Pe,Ee,Re,Oe,Ne,Ie,De,_e,Ae,Le,Ue,xe=getDefaultExportFromCjs(L),Me=(()=>{if(void 0!==Me)return Me;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 Pe.AUDIO;case 1:case"VIDEO":return Pe.VIDEO;case 2:case"DATA":return Pe.DATA;default:return Pe.UNRECOGNIZED}}function trackTypeToJSON(e){switch(e){case Pe.AUDIO:return"AUDIO";case Pe.VIDEO:return"VIDEO";case Pe.DATA:return"DATA";case Pe.UNRECOGNIZED:default:return"UNRECOGNIZED"}}function trackSourceFromJSON(e){switch(e){case 0:case"UNKNOWN":return Ee.UNKNOWN;case 1:case"CAMERA":return Ee.CAMERA;case 2:case"MICROPHONE":return Ee.MICROPHONE;case 3:case"SCREEN_SHARE":return Ee.SCREEN_SHARE;case 4:case"SCREEN_SHARE_AUDIO":return Ee.SCREEN_SHARE_AUDIO;default:return Ee.UNRECOGNIZED}}function trackSourceToJSON(e){switch(e){case Ee.UNKNOWN:return"UNKNOWN";case Ee.CAMERA:return"CAMERA";case Ee.MICROPHONE:return"MICROPHONE";case Ee.SCREEN_SHARE:return"SCREEN_SHARE";case Ee.SCREEN_SHARE_AUDIO:return"SCREEN_SHARE_AUDIO";case Ee.UNRECOGNIZED:default:return"UNRECOGNIZED"}}function videoQualityFromJSON(e){switch(e){case 0:case"LOW":return Re.LOW;case 1:case"MEDIUM":return Re.MEDIUM;case 2:case"HIGH":return Re.HIGH;case 3:case"OFF":return Re.OFF;default:return Re.UNRECOGNIZED}}function videoQualityToJSON(e){switch(e){case Re.LOW:return"LOW";case Re.MEDIUM:return"MEDIUM";case Re.HIGH:return"HIGH";case Re.OFF:return"OFF";case Re.UNRECOGNIZED:default:return"UNRECOGNIZED"}}function connectionQualityFromJSON(e){switch(e){case 0:case"POOR":return Oe.POOR;case 1:case"GOOD":return Oe.GOOD;case 2:case"EXCELLENT":return Oe.EXCELLENT;default:return Oe.UNRECOGNIZED}}function clientConfigSettingFromJSON(e){switch(e){case 0:case"UNSET":return Ne.UNSET;case 1:case"DISABLED":return Ne.DISABLED;case 2:case"ENABLED":return Ne.ENABLED;default:return Ne.UNRECOGNIZED}}function clientConfigSettingToJSON(e){switch(e){case Ne.UNSET:return"UNSET";case Ne.DISABLED:return"DISABLED";case Ne.ENABLED:return"ENABLED";case Ne.UNRECOGNIZED:default:return"UNRECOGNIZED"}}function disconnectReasonFromJSON(e){switch(e){case 0:case"UNKNOWN_REASON":return Ie.UNKNOWN_REASON;case 1:case"CLIENT_INITIATED":return Ie.CLIENT_INITIATED;case 2:case"DUPLICATE_IDENTITY":return Ie.DUPLICATE_IDENTITY;case 3:case"SERVER_SHUTDOWN":return Ie.SERVER_SHUTDOWN;case 4:case"PARTICIPANT_REMOVED":return Ie.PARTICIPANT_REMOVED;case 5:case"ROOM_DELETED":return Ie.ROOM_DELETED;case 6:case"STATE_MISMATCH":return Ie.STATE_MISMATCH;case 7:case"JOIN_FAILURE":return Ie.JOIN_FAILURE;default:return Ie.UNRECOGNIZED}}function participantInfo_StateFromJSON(e){switch(e){case 0:case"JOINING":return De.JOINING;case 1:case"JOINED":return De.JOINED;case 2:case"ACTIVE":return De.ACTIVE;case 3:case"DISCONNECTED":return De.DISCONNECTED;default:return De.UNRECOGNIZED}}function encryption_TypeFromJSON(e){switch(e){case 0:case"NONE":return _e.NONE;case 1:case"GCM":return _e.GCM;case 2:case"CUSTOM":return _e.CUSTOM;default:return _e.UNRECOGNIZED}}function encryption_TypeToJSON(e){switch(e){case _e.NONE:return"NONE";case _e.GCM:return"GCM";case _e.CUSTOM:return"CUSTOM";case _e.UNRECOGNIZED:default:return"UNRECOGNIZED"}}function dataPacket_KindFromJSON(e){switch(e){case 0:case"RELIABLE":return Ae.RELIABLE;case 1:case"LOSSY":return Ae.LOSSY;default:return Ae.UNRECOGNIZED}}function serverInfo_EditionFromJSON(e){switch(e){case 0:case"Standard":return Le.Standard;case 1:case"Cloud":return Le.Cloud;default:return Le.UNRECOGNIZED}}function clientInfo_SDKFromJSON(e){switch(e){case 0:case"UNKNOWN":return Ue.UNKNOWN;case 1:case"JS":return Ue.JS;case 2:case"SWIFT":return Ue.SWIFT;case 3:case"ANDROID":return Ue.ANDROID;case 4:case"FLUTTER":return Ue.FLUTTER;case 5:case"GO":return Ue.GO;case 6:case"UNITY":return Ue.UNITY;default:return Ue.UNRECOGNIZED}}xe.util.Long!==p&&(xe.util.Long=p,xe.configure()),function(e){e[e.AUDIO=0]="AUDIO",e[e.VIDEO=1]="VIDEO",e[e.DATA=2]="DATA",e[e.UNRECOGNIZED=-1]="UNRECOGNIZED"}(Pe||(Pe={})),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"}(Ee||(Ee={})),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"}(Re||(Re={})),function(e){e[e.POOR=0]="POOR",e[e.GOOD=1]="GOOD",e[e.EXCELLENT=2]="EXCELLENT",e[e.UNRECOGNIZED=-1]="UNRECOGNIZED"}(Oe||(Oe={})),function(e){e[e.UNSET=0]="UNSET",e[e.DISABLED=1]="DISABLED",e[e.ENABLED=2]="ENABLED",e[e.UNRECOGNIZED=-1]="UNRECOGNIZED"}(Ne||(Ne={})),function(e){e[e.UNKNOWN_REASON=0]="UNKNOWN_REASON",e[e.CLIENT_INITIATED=1]="CLIENT_INITIATED",e[e.DUPLICATE_IDENTITY=2]="DUPLICATE_IDENTITY",e[e.SERVER_SHUTDOWN=3]="SERVER_SHUTDOWN",e[e.PARTICIPANT_REMOVED=4]="PARTICIPANT_REMOVED",e[e.ROOM_DELETED=5]="ROOM_DELETED",e[e.STATE_MISMATCH=6]="STATE_MISMATCH",e[e.JOIN_FAILURE=7]="JOIN_FAILURE",e[e.UNRECOGNIZED=-1]="UNRECOGNIZED"}(Ie||(Ie={})),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"}(De||(De={})),function(e){e[e.NONE=0]="NONE",e[e.GCM=1]="GCM",e[e.CUSTOM=2]="CUSTOM",e[e.UNRECOGNIZED=-1]="UNRECOGNIZED"}(_e||(_e={})),function(e){e[e.RELIABLE=0]="RELIABLE",e[e.LOSSY=1]="LOSSY",e[e.UNRECOGNIZED=-1]="UNRECOGNIZED"}(Ae||(Ae={})),function(e){e[e.Standard=0]="Standard",e[e.Cloud=1]="Cloud",e[e.UNRECOGNIZED=-1]="UNRECOGNIZED"}(Le||(Le={})),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"}(Ue||(Ue={}));const $e={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xe.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)Be.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 xe.Reader?e:new xe.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$1(i.int64());break;case 6:s.turnPassword=i.string();break;case 7:s.enabledCodecs.push(Be.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=>Be.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?Be.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,o,a,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!==(o=e.creationTime)&&void 0!==o?o:0,p.turnPassword=null!==(a=e.turnPassword)&&void 0!==a?a:"",p.enabledCodecs=(null===(c=e.enabledCodecs)||void 0===c?void 0:c.map((e=>Be.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 Be={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xe.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 xe.Reader?e:new xe.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 Fe={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xe.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 xe.Reader?e:new xe.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,o;const a={canSubscribe:!1,canPublish:!1,canPublishData:!1,hidden:!1,recorder:!1};return a.canSubscribe=null!==(t=e.canSubscribe)&&void 0!==t&&t,a.canPublish=null!==(i=e.canPublish)&&void 0!==i&&i,a.canPublishData=null!==(n=e.canPublishData)&&void 0!==n&&n,a.hidden=null!==(s=e.hidden)&&void 0!==s&&s,a.recorder=null!==(o=e.recorder)&&void 0!==o&&o,a}};const Je={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xe.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)je.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&&Fe.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 xe.Reader?e:new xe.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(je.decode(i,i.uint32()));break;case 5:s.metadata=i.string();break;case 6:s.joinedAt=longToNumber$1(i.int64());break;case 9:s.name=i.string();break;case 10:s.version=i.uint32();break;case 11:s.permission=Fe.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=>je.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)?Fe.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 De.JOINING:return"JOINING";case De.JOINED:return"JOINED";case De.ACTIVE:return"ACTIVE";case De.DISCONNECTED:return"DISCONNECTED";case De.UNRECOGNIZED:default:return"UNRECOGNIZED"}}(e.state)),e.tracks?t.tracks=e.tracks.map((e=>e?je.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?Fe.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,o,a,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=>je.fromPartial(e))))||[],p.metadata=null!==(o=e.metadata)&&void 0!==o?o:"",p.joinedAt=null!==(a=e.joinedAt)&&void 0!==a?a: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?Fe.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 Ve={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xe.Writer.create();""!==e.mimeType&&t.uint32(10).string(e.mimeType),""!==e.mid&&t.uint32(18).string(e.mid),""!==e.cid&&t.uint32(26).string(e.cid);for(const i of e.layers)We.encode(i,t.uint32(34).fork()).ldelim();return t},decode(e,t){const i=e instanceof xe.Reader?e:new xe.Reader(e);let n=void 0===t?i.len:i.pos+t;const s={mimeType:"",mid:"",cid:"",layers:[]};for(;i.pos>>3){case 1:s.mimeType=i.string();break;case 2:s.mid=i.string();break;case 3:s.cid=i.string();break;case 4:s.layers.push(We.decode(i,i.uint32()));break;default:i.skipType(7&e)}}return s},fromJSON:e=>({mimeType:isSet$1(e.mimeType)?String(e.mimeType):"",mid:isSet$1(e.mid)?String(e.mid):"",cid:isSet$1(e.cid)?String(e.cid):"",layers:Array.isArray(null==e?void 0:e.layers)?e.layers.map((e=>We.fromJSON(e))):[]}),toJSON(e){const t={};return void 0!==e.mimeType&&(t.mimeType=e.mimeType),void 0!==e.mid&&(t.mid=e.mid),void 0!==e.cid&&(t.cid=e.cid),e.layers?t.layers=e.layers.map((e=>e?We.toJSON(e):void 0)):t.layers=[],t},fromPartial(e){var t,i,n,s;const o={mimeType:"",mid:"",cid:"",layers:[]};return o.mimeType=null!==(t=e.mimeType)&&void 0!==t?t:"",o.mid=null!==(i=e.mid)&&void 0!==i?i:"",o.cid=null!==(n=e.cid)&&void 0!==n?n:"",o.layers=(null===(s=e.layers)||void 0===s?void 0:s.map((e=>We.fromPartial(e))))||[],o}};const je={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xe.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)We.encode(i,t.uint32(82).fork()).ldelim();""!==e.mimeType&&t.uint32(90).string(e.mimeType),""!==e.mid&&t.uint32(98).string(e.mid);for(const i of e.codecs)Ve.encode(i,t.uint32(106).fork()).ldelim();return!0===e.stereo&&t.uint32(112).bool(e.stereo),!0===e.disableRed&&t.uint32(120).bool(e.disableRed),0!==e.encryption&&t.uint32(128).int32(e.encryption),t},decode(e,t){const i=e instanceof xe.Reader?e:new xe.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:"",codecs:[],stereo:!1,disableRed:!1,encryption:0};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(We.decode(i,i.uint32()));break;case 11:s.mimeType=i.string();break;case 12:s.mid=i.string();break;case 13:s.codecs.push(Ve.decode(i,i.uint32()));break;case 14:s.stereo=i.bool();break;case 15:s.disableRed=i.bool();break;case 16:s.encryption=i.int32();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=>We.fromJSON(e))):[],mimeType:isSet$1(e.mimeType)?String(e.mimeType):"",mid:isSet$1(e.mid)?String(e.mid):"",codecs:Array.isArray(null==e?void 0:e.codecs)?e.codecs.map((e=>Ve.fromJSON(e))):[],stereo:!!isSet$1(e.stereo)&&Boolean(e.stereo),disableRed:!!isSet$1(e.disableRed)&&Boolean(e.disableRed),encryption:isSet$1(e.encryption)?encryption_TypeFromJSON(e.encryption):0}),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?We.toJSON(e):void 0)):t.layers=[],void 0!==e.mimeType&&(t.mimeType=e.mimeType),void 0!==e.mid&&(t.mid=e.mid),e.codecs?t.codecs=e.codecs.map((e=>e?Ve.toJSON(e):void 0)):t.codecs=[],void 0!==e.stereo&&(t.stereo=e.stereo),void 0!==e.disableRed&&(t.disableRed=e.disableRed),void 0!==e.encryption&&(t.encryption=encryption_TypeToJSON(e.encryption)),t},fromPartial(e){var t,i,n,s,o,a,c,u,l,h,p,m,v,g,b,S;const k={sid:"",type:0,name:"",muted:!1,width:0,height:0,simulcast:!1,disableDtx:!1,source:0,layers:[],mimeType:"",mid:"",codecs:[],stereo:!1,disableRed:!1,encryption:0};return k.sid=null!==(t=e.sid)&&void 0!==t?t:"",k.type=null!==(i=e.type)&&void 0!==i?i:0,k.name=null!==(n=e.name)&&void 0!==n?n:"",k.muted=null!==(s=e.muted)&&void 0!==s&&s,k.width=null!==(o=e.width)&&void 0!==o?o:0,k.height=null!==(a=e.height)&&void 0!==a?a:0,k.simulcast=null!==(c=e.simulcast)&&void 0!==c&&c,k.disableDtx=null!==(u=e.disableDtx)&&void 0!==u&&u,k.source=null!==(l=e.source)&&void 0!==l?l:0,k.layers=(null===(h=e.layers)||void 0===h?void 0:h.map((e=>We.fromPartial(e))))||[],k.mimeType=null!==(p=e.mimeType)&&void 0!==p?p:"",k.mid=null!==(m=e.mid)&&void 0!==m?m:"",k.codecs=(null===(v=e.codecs)||void 0===v?void 0:v.map((e=>Ve.fromPartial(e))))||[],k.stereo=null!==(g=e.stereo)&&void 0!==g&&g,k.disableRed=null!==(b=e.disableRed)&&void 0!==b&&b,k.encryption=null!==(S=e.encryption)&&void 0!==S?S:0,k}};const We={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xe.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 xe.Reader?e:new xe.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,o;const a={quality:0,width:0,height:0,bitrate:0,ssrc:0};return a.quality=null!==(t=e.quality)&&void 0!==t?t:0,a.width=null!==(i=e.width)&&void 0!==i?i:0,a.height=null!==(n=e.height)&&void 0!==n?n:0,a.bitrate=null!==(s=e.bitrate)&&void 0!==s?s:0,a.ssrc=null!==(o=e.ssrc)&&void 0!==o?o:0,a}};const qe={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xe.Writer.create();var i,n;return 0!==e.kind&&t.uint32(8).int32(e.kind),"user"===(null===(i=e.value)||void 0===i?void 0:i.$case)&&ze.encode(e.value.user,t.uint32(18).fork()).ldelim(),"speaker"===(null===(n=e.value)||void 0===n?void 0:n.$case)&&Ge.encode(e.value.speaker,t.uint32(26).fork()).ldelim(),t},decode(e,t){const i=e instanceof xe.Reader?e:new xe.Reader(e);let n=void 0===t?i.len:i.pos+t;const s={kind:0,value:void 0};for(;i.pos>>3){case 1:s.kind=i.int32();break;case 2:s.value={$case:"user",user:ze.decode(i,i.uint32())};break;case 3:s.value={$case:"speaker",speaker:Ge.decode(i,i.uint32())};break;default:i.skipType(7&e)}}return s},fromJSON:e=>({kind:isSet$1(e.kind)?dataPacket_KindFromJSON(e.kind):0,value:isSet$1(e.user)?{$case:"user",user:ze.fromJSON(e.user)}:isSet$1(e.speaker)?{$case:"speaker",speaker:Ge.fromJSON(e.speaker)}:void 0}),toJSON(e){var t,i,n,s,o,a;const c={};return void 0!==e.kind&&(c.kind=function dataPacket_KindToJSON(e){switch(e){case Ae.RELIABLE:return"RELIABLE";case Ae.LOSSY:return"LOSSY";case Ae.UNRECOGNIZED:default:return"UNRECOGNIZED"}}(e.kind)),"user"===(null===(t=e.value)||void 0===t?void 0:t.$case)&&(c.user=(null===(i=e.value)||void 0===i?void 0:i.user)?ze.toJSON(null===(n=e.value)||void 0===n?void 0:n.user):void 0),"speaker"===(null===(s=e.value)||void 0===s?void 0:s.$case)&&(c.speaker=(null===(o=e.value)||void 0===o?void 0:o.speaker)?Ge.toJSON(null===(a=e.value)||void 0===a?void 0:a.speaker):void 0),c},fromPartial(e){var t,i,n,s,o,a,c;const u={kind:0,value:void 0};return u.kind=null!==(t=e.kind)&&void 0!==t?t:0,"user"===(null===(i=e.value)||void 0===i?void 0:i.$case)&&void 0!==(null===(n=e.value)||void 0===n?void 0:n.user)&&null!==(null===(s=e.value)||void 0===s?void 0:s.user)&&(u.value={$case:"user",user:ze.fromPartial(e.value.user)}),"speaker"===(null===(o=e.value)||void 0===o?void 0:o.$case)&&void 0!==(null===(a=e.value)||void 0===a?void 0:a.speaker)&&null!==(null===(c=e.value)||void 0===c?void 0:c.speaker)&&(u.value={$case:"speaker",speaker:Ge.fromPartial(e.value.speaker)}),u}};const Ge={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xe.Writer.create();for(const i of e.speakers)Qe.encode(i,t.uint32(10).fork()).ldelim();return t},decode(e,t){const i=e instanceof xe.Reader?e:new xe.Reader(e);let n=void 0===t?i.len:i.pos+t;const s={speakers:[]};for(;i.pos>>3==1)s.speakers.push(Qe.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=>Qe.fromJSON(e))):[]}),toJSON(e){const t={};return e.speakers?t.speakers=e.speakers.map((e=>e?Qe.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=>Qe.fromPartial(e))))||[],i}};const Qe={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xe.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 xe.Reader?e:new xe.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 ze={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xe.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 xe.Reader?e:new xe.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){if(tt.Buffer)return tt.Buffer.from(e).toString("base64");{const t=[];return e.forEach((e=>{t.push(String.fromCharCode(e))})),tt.btoa(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 He={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xe.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 xe.Reader?e:new xe.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 Ze={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xe.Writer.create();return 0!==e.edition&&t.uint32(8).int32(e.edition),""!==e.version&&t.uint32(18).string(e.version),0!==e.protocol&&t.uint32(24).int32(e.protocol),""!==e.region&&t.uint32(34).string(e.region),""!==e.nodeId&&t.uint32(42).string(e.nodeId),""!==e.debugInfo&&t.uint32(50).string(e.debugInfo),t},decode(e,t){const i=e instanceof xe.Reader?e:new xe.Reader(e);let n=void 0===t?i.len:i.pos+t;const s={edition:0,version:"",protocol:0,region:"",nodeId:"",debugInfo:""};for(;i.pos>>3){case 1:s.edition=i.int32();break;case 2:s.version=i.string();break;case 3:s.protocol=i.int32();break;case 4:s.region=i.string();break;case 5:s.nodeId=i.string();break;case 6:s.debugInfo=i.string();break;default:i.skipType(7&e)}}return s},fromJSON:e=>({edition:isSet$1(e.edition)?serverInfo_EditionFromJSON(e.edition):0,version:isSet$1(e.version)?String(e.version):"",protocol:isSet$1(e.protocol)?Number(e.protocol):0,region:isSet$1(e.region)?String(e.region):"",nodeId:isSet$1(e.nodeId)?String(e.nodeId):"",debugInfo:isSet$1(e.debugInfo)?String(e.debugInfo):""}),toJSON(e){const t={};return void 0!==e.edition&&(t.edition=function serverInfo_EditionToJSON(e){switch(e){case Le.Standard:return"Standard";case Le.Cloud:return"Cloud";case Le.UNRECOGNIZED:default:return"UNRECOGNIZED"}}(e.edition)),void 0!==e.version&&(t.version=e.version),void 0!==e.protocol&&(t.protocol=Math.round(e.protocol)),void 0!==e.region&&(t.region=e.region),void 0!==e.nodeId&&(t.nodeId=e.nodeId),void 0!==e.debugInfo&&(t.debugInfo=e.debugInfo),t},fromPartial(e){var t,i,n,s,o,a;const c={edition:0,version:"",protocol:0,region:"",nodeId:"",debugInfo:""};return c.edition=null!==(t=e.edition)&&void 0!==t?t:0,c.version=null!==(i=e.version)&&void 0!==i?i:"",c.protocol=null!==(n=e.protocol)&&void 0!==n?n:0,c.region=null!==(s=e.region)&&void 0!==s?s:"",c.nodeId=null!==(o=e.nodeId)&&void 0!==o?o:"",c.debugInfo=null!==(a=e.debugInfo)&&void 0!==a?a:"",c}};const Ke={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xe.Writer.create();return 0!==e.sdk&&t.uint32(8).int32(e.sdk),""!==e.version&&t.uint32(18).string(e.version),0!==e.protocol&&t.uint32(24).int32(e.protocol),""!==e.os&&t.uint32(34).string(e.os),""!==e.osVersion&&t.uint32(42).string(e.osVersion),""!==e.deviceModel&&t.uint32(50).string(e.deviceModel),""!==e.browser&&t.uint32(58).string(e.browser),""!==e.browserVersion&&t.uint32(66).string(e.browserVersion),""!==e.address&&t.uint32(74).string(e.address),""!==e.network&&t.uint32(82).string(e.network),t},decode(e,t){const i=e instanceof xe.Reader?e:new xe.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:"",network:""};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;case 10:s.network=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):"",network:isSet$1(e.network)?String(e.network):""}),toJSON(e){const t={};return void 0!==e.sdk&&(t.sdk=function clientInfo_SDKToJSON(e){switch(e){case Ue.UNKNOWN:return"UNKNOWN";case Ue.JS:return"JS";case Ue.SWIFT:return"SWIFT";case Ue.ANDROID:return"ANDROID";case Ue.FLUTTER:return"FLUTTER";case Ue.GO:return"GO";case Ue.UNITY:return"UNITY";case Ue.UNRECOGNIZED:default:return"UNRECOGNIZED"}}(e.sdk)),void 0!==e.version&&(t.version=e.version),void 0!==e.protocol&&(t.protocol=Math.round(e.protocol)),void 0!==e.os&&(t.os=e.os),void 0!==e.osVersion&&(t.osVersion=e.osVersion),void 0!==e.deviceModel&&(t.deviceModel=e.deviceModel),void 0!==e.browser&&(t.browser=e.browser),void 0!==e.browserVersion&&(t.browserVersion=e.browserVersion),void 0!==e.address&&(t.address=e.address),void 0!==e.network&&(t.network=e.network),t},fromPartial(e){var t,i,n,s,o,a,c,u,l,h;const p={sdk:0,version:"",protocol:0,os:"",osVersion:"",deviceModel:"",browser:"",browserVersion:"",address:"",network:""};return p.sdk=null!==(t=e.sdk)&&void 0!==t?t:0,p.version=null!==(i=e.version)&&void 0!==i?i:"",p.protocol=null!==(n=e.protocol)&&void 0!==n?n:0,p.os=null!==(s=e.os)&&void 0!==s?s:"",p.osVersion=null!==(o=e.osVersion)&&void 0!==o?o:"",p.deviceModel=null!==(a=e.deviceModel)&&void 0!==a?a:"",p.browser=null!==(c=e.browser)&&void 0!==c?c:"",p.browserVersion=null!==(u=e.browserVersion)&&void 0!==u?u:"",p.address=null!==(l=e.address)&&void 0!==l?l:"",p.network=null!==(h=e.network)&&void 0!==h?h:"",p}};const Ye={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xe.Writer.create();return void 0!==e.video&&Xe.encode(e.video,t.uint32(10).fork()).ldelim(),void 0!==e.screen&&Xe.encode(e.screen,t.uint32(18).fork()).ldelim(),0!==e.resumeConnection&&t.uint32(24).int32(e.resumeConnection),void 0!==e.disabledCodecs&&et.encode(e.disabledCodecs,t.uint32(34).fork()).ldelim(),0!==e.forceRelay&&t.uint32(40).int32(e.forceRelay),t},decode(e,t){const i=e instanceof xe.Reader?e:new xe.Reader(e);let n=void 0===t?i.len:i.pos+t;const s={video:void 0,screen:void 0,resumeConnection:0,disabledCodecs:void 0,forceRelay:0};for(;i.pos>>3){case 1:s.video=Xe.decode(i,i.uint32());break;case 2:s.screen=Xe.decode(i,i.uint32());break;case 3:s.resumeConnection=i.int32();break;case 4:s.disabledCodecs=et.decode(i,i.uint32());break;case 5:s.forceRelay=i.int32();break;default:i.skipType(7&e)}}return s},fromJSON:e=>({video:isSet$1(e.video)?Xe.fromJSON(e.video):void 0,screen:isSet$1(e.screen)?Xe.fromJSON(e.screen):void 0,resumeConnection:isSet$1(e.resumeConnection)?clientConfigSettingFromJSON(e.resumeConnection):0,disabledCodecs:isSet$1(e.disabledCodecs)?et.fromJSON(e.disabledCodecs):void 0,forceRelay:isSet$1(e.forceRelay)?clientConfigSettingFromJSON(e.forceRelay):0}),toJSON(e){const t={};return void 0!==e.video&&(t.video=e.video?Xe.toJSON(e.video):void 0),void 0!==e.screen&&(t.screen=e.screen?Xe.toJSON(e.screen):void 0),void 0!==e.resumeConnection&&(t.resumeConnection=clientConfigSettingToJSON(e.resumeConnection)),void 0!==e.disabledCodecs&&(t.disabledCodecs=e.disabledCodecs?et.toJSON(e.disabledCodecs):void 0),void 0!==e.forceRelay&&(t.forceRelay=clientConfigSettingToJSON(e.forceRelay)),t},fromPartial(e){var t,i;const n={video:void 0,screen:void 0,resumeConnection:0,disabledCodecs:void 0,forceRelay:0};return n.video=void 0!==e.video&&null!==e.video?Xe.fromPartial(e.video):void 0,n.screen=void 0!==e.screen&&null!==e.screen?Xe.fromPartial(e.screen):void 0,n.resumeConnection=null!==(t=e.resumeConnection)&&void 0!==t?t:0,n.disabledCodecs=void 0!==e.disabledCodecs&&null!==e.disabledCodecs?et.fromPartial(e.disabledCodecs):void 0,n.forceRelay=null!==(i=e.forceRelay)&&void 0!==i?i:0,n}};const Xe={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xe.Writer.create();return 0!==e.hardwareEncoder&&t.uint32(8).int32(e.hardwareEncoder),t},decode(e,t){const i=e instanceof xe.Reader?e:new xe.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}};const et={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xe.Writer.create();for(const i of e.codecs)Be.encode(i,t.uint32(10).fork()).ldelim();return t},decode(e,t){const i=e instanceof xe.Reader?e:new xe.Reader(e);let n=void 0===t?i.len:i.pos+t;const s={codecs:[]};for(;i.pos>>3==1)s.codecs.push(Be.decode(i,i.uint32()));else i.skipType(7&e)}return s},fromJSON:e=>({codecs:Array.isArray(null==e?void 0:e.codecs)?e.codecs.map((e=>Be.fromJSON(e))):[]}),toJSON(e){const t={};return e.codecs?t.codecs=e.codecs.map((e=>e?Be.toJSON(e):void 0)):t.codecs=[],t},fromPartial(e){var t;const i={codecs:[]};return i.codecs=(null===(t=e.codecs)||void 0===t?void 0:t.map((e=>Be.fromPartial(e))))||[],i}};var tt=(()=>{if(void 0!==tt)return tt;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 bytesFromBase64(e){if(tt.Buffer)return Uint8Array.from(tt.Buffer.from(e,"base64"));{const t=tt.atob(e),i=new Uint8Array(t.length);for(let e=0;e=this._retryDelays.length)return null;const t=this._retryDelays[e.retryCount];return e.retryCount<=1?t:t+1e3*Math.random()}}function _asyncIterator(e){var t,i,n,s=2;for("undefined"!=typeof Symbol&&(i=Symbol.asyncIterator,n=Symbol.iterator);s--;){if(i&&null!=(t=e[i]))return t.call(e);if(n&&null!=(t=e[n]))return new AsyncFromSyncIterator(t.call(e));i="@@asyncIterator",n="@@iterator"}throw new TypeError("Object is not async iterable")}function AsyncFromSyncIterator(e){function AsyncFromSyncIteratorContinuation(e){if(Object(e)!==e)return Promise.reject(new TypeError(e+" is not an object."));var t=e.done;return Promise.resolve(e.value).then((function(e){return{value:e,done:t}}))}return AsyncFromSyncIterator=function(e){this.s=e,this.n=e.next},AsyncFromSyncIterator.prototype={s:null,n:null,next:function(){return AsyncFromSyncIteratorContinuation(this.n.apply(this.s,arguments))},return:function(e){var t=this.s.return;return void 0===t?Promise.resolve({value:e,done:!0}):AsyncFromSyncIteratorContinuation(t.apply(this.s,arguments))},throw:function(e){var t=this.s.return;return void 0===t?Promise.reject(e):AsyncFromSyncIteratorContinuation(t.apply(this.s,arguments))}},new AsyncFromSyncIterator(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;t=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 o=n.removeEventListener;n.removeEventListener=function(e,i){if(e!==t||!this._eventMap||!this._eventMap[t])return o.apply(this,arguments);if(!this._eventMap[t].has(i))return o.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,o.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."):(rt=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."):(st=!e,"adapter.js deprecation warnings "+(e?"disabled":"enabled"))}function log(){if("object"==typeof window){if(rt)return;"undefined"!=typeof console&&"function"==typeof console.log&&console.log.apply(console,arguments)}}function deprecated(e,t){st&&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],o=n&&!Object.keys(s).length;return void 0===s||o?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 o=[];return e.forEach((e=>{"track"===e.type&&e.trackIdentifier===t.id&&o.push(e)})),o.forEach((t=>{e.forEach((i=>{i.type===n&&i.trackId===t.id&&walkStats(e,i,s)}))})),s}const ot=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 o=t.version<66;if(s&&("user"===s.exact||"environment"===s.exact||"user"===s.ideal||"environment"===s.ideal)&&(!i.mediaDevices.getSupportedConstraints||!i.mediaDevices.getSupportedConstraints().facingMode||o)){let t;if(delete e.video.facingMode,"environment"===s.exact||"environment"===s.ideal?t=["back","rear"]:"user"!==s.exact&&"user"!==s.ideal||(t=["front"]),t)return i.mediaDevices.enumerateDevices().then((i=>{let o=(i=i.filter((e=>"videoinput"===e.kind))).find((e=>t.some((t=>e.label.toLowerCase().includes(t)))));return!o&&i.length&&t.includes("back")&&(o=i[i.length-1]),o&&(e.video.deviceId=s.exact?{exact:o.deviceId}:{ideal:o.deviceId}),e.video=constraintsToChrome_(e.video),ot("chrome: "+JSON.stringify(e)),n(e)}))}e.video=constraintsToChrome_(e.video)}return ot("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 o=this._streams[i.id];if(o)o.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 o=e.RTCPeerConnection.prototype.setLocalDescription;e.RTCPeerConnection.prototype.setLocalDescription=function setLocalDescription(){return arguments.length&&arguments[0].type?(arguments[0]=replaceExternalStreamId(this,arguments[0]),o.apply(this,arguments)):o.apply(this,arguments)};const a=Object.getOwnPropertyDescriptor(e.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(e.RTCPeerConnection.prototype,"localDescription",{get(){const e=a.get.apply(this);return""===e.type?e: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 at=Object.freeze({__proto__:null,fixNegotiationNeeded,shimAddTrackRemoveTrack,shimAddTrackRemoveTrackWithNative,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,o=i.video&&i.video.frameRate;return i.video={mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:t,maxFrameRate:o||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"))},shimGetSendersWithDtmf,shimGetStats,shimGetUserMedia:shimGetUserMedia$2,shimMediaStream,shimOnTrack:shimOnTrack$1,shimPeerConnection:shimPeerConnection$1,shimSenderReceiverGetStats});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,o]=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,o)}}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 ct=Object.freeze({__proto__:null,shimAddTransceiver,shimCreateAnswer,shimCreateOffer,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)})},shimGetParameters,shimGetUserMedia:shimGetUserMedia$1,shimOnTrack,shimPeerConnection,shimRTCDataChannel,shimReceiverGetStats,shimRemoveStream,shimSenderGetStats});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,o=t.setRemoteDescription,a=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=o.apply(this,[e]);return i?(n.then(t,i),Promise.resolve()):n},t.setRemoteDescription=withCallback,withCallback=function(e,t,i){const n=a.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 dt=Object.freeze({__proto__:null,shimAudioContext,shimCallbacksAPI,shimConstraints,shimCreateOfferLegacy,shimGetUserMedia,shimLocalStreamsAPI,shimRTCIceServerUrls,shimRemoteStreamsAPI,shimTrackEventTransceiver}),ut={};!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"),o=-1!==n.fecMechanisms.indexOf("ULPFEC"),a=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"cname"===e.attribute)),c=a.length>0&&a[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:o?"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 o=t.matchPrefix(e,"a=rtcp-mux");return i.mux=o.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 o=t.matchPrefix(e,"a=sctp-port:");if(o.length>0)return{port:parseInt(o[0].substr(12),10),protocol:i.fmt,maxMessageSize:s};const a=t.matchPrefix(e,"a=sctpmap:");if(a.length>0){const e=a[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 o=void 0!==i?i:2;s=e||t.generateSessionId();return"v=0\r\no="+(n||"thisisadapterortc")+" "+s+" "+o+" 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=lt.splitSections(e.sdp);return t.shift(),t.some((e=>{const t=lt.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=lt.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 pt,mt,ft,vt=Object.freeze({__proto__:null,removeExtmapAllowMixed,shimAddIceCandidateNullOrEmpty,shimConnectionState,shimMaxMessageSize,shimParameterlessSetLocalDescription,shimRTCIceCandidate,shimSendThrowTypeError});function signalTargetFromJSON(e){switch(e){case 0:case"PUBLISHER":return pt.PUBLISHER;case 1:case"SUBSCRIBER":return pt.SUBSCRIBER;default:return pt.UNRECOGNIZED}}function signalTargetToJSON(e){switch(e){case pt.PUBLISHER:return"PUBLISHER";case pt.SUBSCRIBER:return"SUBSCRIBER";case pt.UNRECOGNIZED:default:return"UNRECOGNIZED"}}function streamStateFromJSON(e){switch(e){case 0:case"ACTIVE":return mt.ACTIVE;case 1:case"PAUSED":return mt.PAUSED;default:return mt.UNRECOGNIZED}}function candidateProtocolFromJSON(e){switch(e){case 0:case"UDP":return ft.UDP;case 1:case"TCP":return ft.TCP;case 2:case"TLS":return ft.TLS;default:return ft.UNRECOGNIZED}}!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:vt,extractVersion,disableLog,disableWarnings,sdp:ht};switch(n.browser){case"chrome":if(!at||!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=at,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(!ct||!shimPeerConnection||!t.shimFirefox)return i("Firefox shim is not included in this adapter release."),s;i("adapter.js shimming firefox."),s.browserShim=ct,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(!dt||!t.shimSafari)return i("Safari shim is not included in this adapter release."),s;i("adapter.js shimming safari."),s.browserShim=dt,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}),function(e){e[e.PUBLISHER=0]="PUBLISHER",e[e.SUBSCRIBER=1]="SUBSCRIBER",e[e.UNRECOGNIZED=-1]="UNRECOGNIZED"}(pt||(pt={})),function(e){e[e.ACTIVE=0]="ACTIVE",e[e.PAUSED=1]="PAUSED",e[e.UNRECOGNIZED=-1]="UNRECOGNIZED"}(mt||(mt={})),function(e){e[e.UDP=0]="UDP",e[e.TCP=1]="TCP",e[e.TLS=2]="TLS",e[e.UNRECOGNIZED=-1]="UNRECOGNIZED"}(ft||(ft={}));const gt={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xe.Writer.create();var i,n,s,o,a,c,u,l,h,p,m,v,g;return"offer"===(null===(i=e.message)||void 0===i?void 0:i.$case)&&Rt.encode(e.message.offer,t.uint32(10).fork()).ldelim(),"answer"===(null===(n=e.message)||void 0===n?void 0:n.$case)&&Rt.encode(e.message.answer,t.uint32(18).fork()).ldelim(),"trickle"===(null===(s=e.message)||void 0===s?void 0:s.$case)&&yt.encode(e.message.trickle,t.uint32(26).fork()).ldelim(),"addTrack"===(null===(o=e.message)||void 0===o?void 0:o.$case)&&kt.encode(e.message.addTrack,t.uint32(34).fork()).ldelim(),"mute"===(null===(a=e.message)||void 0===a?void 0:a.$case)&&wt.encode(e.message.mute,t.uint32(42).fork()).ldelim(),"subscription"===(null===(c=e.message)||void 0===c?void 0:c.$case)&&Nt.encode(e.message.subscription,t.uint32(50).fork()).ldelim(),"trackSetting"===(null===(u=e.message)||void 0===u?void 0:u.$case)&&It.encode(e.message.trackSetting,t.uint32(58).fork()).ldelim(),"leave"===(null===(l=e.message)||void 0===l?void 0:l.$case)&&Dt.encode(e.message.leave,t.uint32(66).fork()).ldelim(),"updateLayers"===(null===(h=e.message)||void 0===h?void 0:h.$case)&&_t.encode(e.message.updateLayers,t.uint32(82).fork()).ldelim(),"subscriptionPermission"===(null===(p=e.message)||void 0===p?void 0:p.$case)&&Wt.encode(e.message.subscriptionPermission,t.uint32(90).fork()).ldelim(),"syncState"===(null===(m=e.message)||void 0===m?void 0:m.$case)&&Gt.encode(e.message.syncState,t.uint32(98).fork()).ldelim(),"simulate"===(null===(v=e.message)||void 0===v?void 0:v.$case)&&zt.encode(e.message.simulate,t.uint32(106).fork()).ldelim(),"ping"===(null===(g=e.message)||void 0===g?void 0:g.$case)&&t.uint32(112).int64(e.message.ping),t},decode(e,t){const i=e instanceof xe.Reader?e:new xe.Reader(e);let n=void 0===t?i.len:i.pos+t;const s={message:void 0};for(;i.pos>>3){case 1:s.message={$case:"offer",offer:Rt.decode(i,i.uint32())};break;case 2:s.message={$case:"answer",answer:Rt.decode(i,i.uint32())};break;case 3:s.message={$case:"trickle",trickle:yt.decode(i,i.uint32())};break;case 4:s.message={$case:"addTrack",addTrack:kt.decode(i,i.uint32())};break;case 5:s.message={$case:"mute",mute:wt.decode(i,i.uint32())};break;case 6:s.message={$case:"subscription",subscription:Nt.decode(i,i.uint32())};break;case 7:s.message={$case:"trackSetting",trackSetting:It.decode(i,i.uint32())};break;case 8:s.message={$case:"leave",leave:Dt.decode(i,i.uint32())};break;case 10:s.message={$case:"updateLayers",updateLayers:_t.decode(i,i.uint32())};break;case 11:s.message={$case:"subscriptionPermission",subscriptionPermission:Wt.decode(i,i.uint32())};break;case 12:s.message={$case:"syncState",syncState:Gt.decode(i,i.uint32())};break;case 13:s.message={$case:"simulate",simulate:zt.decode(i,i.uint32())};break;case 14:s.message={$case:"ping",ping:longToNumber(i.int64())};break;default:i.skipType(7&e)}}return s},fromJSON:e=>({message:isSet(e.offer)?{$case:"offer",offer:Rt.fromJSON(e.offer)}:isSet(e.answer)?{$case:"answer",answer:Rt.fromJSON(e.answer)}:isSet(e.trickle)?{$case:"trickle",trickle:yt.fromJSON(e.trickle)}:isSet(e.addTrack)?{$case:"addTrack",addTrack:kt.fromJSON(e.addTrack)}:isSet(e.mute)?{$case:"mute",mute:wt.fromJSON(e.mute)}:isSet(e.subscription)?{$case:"subscription",subscription:Nt.fromJSON(e.subscription)}:isSet(e.trackSetting)?{$case:"trackSetting",trackSetting:It.fromJSON(e.trackSetting)}:isSet(e.leave)?{$case:"leave",leave:Dt.fromJSON(e.leave)}:isSet(e.updateLayers)?{$case:"updateLayers",updateLayers:_t.fromJSON(e.updateLayers)}:isSet(e.subscriptionPermission)?{$case:"subscriptionPermission",subscriptionPermission:Wt.fromJSON(e.subscriptionPermission)}:isSet(e.syncState)?{$case:"syncState",syncState:Gt.fromJSON(e.syncState)}:isSet(e.simulate)?{$case:"simulate",simulate:zt.fromJSON(e.simulate)}:isSet(e.ping)?{$case:"ping",ping:Number(e.ping)}:void 0}),toJSON(e){var t,i,n,s,o,a,c,u,l,h,p,m,v,g,b,S,k,y,w,T,C,P,E,R,O,N,I,D,_,A,L,U,x,M,$,B,F,J;const V={};return"offer"===(null===(t=e.message)||void 0===t?void 0:t.$case)&&(V.offer=(null===(i=e.message)||void 0===i?void 0:i.offer)?Rt.toJSON(null===(n=e.message)||void 0===n?void 0:n.offer):void 0),"answer"===(null===(s=e.message)||void 0===s?void 0:s.$case)&&(V.answer=(null===(o=e.message)||void 0===o?void 0:o.answer)?Rt.toJSON(null===(a=e.message)||void 0===a?void 0:a.answer):void 0),"trickle"===(null===(c=e.message)||void 0===c?void 0:c.$case)&&(V.trickle=(null===(u=e.message)||void 0===u?void 0:u.trickle)?yt.toJSON(null===(l=e.message)||void 0===l?void 0:l.trickle):void 0),"addTrack"===(null===(h=e.message)||void 0===h?void 0:h.$case)&&(V.addTrack=(null===(p=e.message)||void 0===p?void 0:p.addTrack)?kt.toJSON(null===(m=e.message)||void 0===m?void 0:m.addTrack):void 0),"mute"===(null===(v=e.message)||void 0===v?void 0:v.$case)&&(V.mute=(null===(g=e.message)||void 0===g?void 0:g.mute)?wt.toJSON(null===(b=e.message)||void 0===b?void 0:b.mute):void 0),"subscription"===(null===(S=e.message)||void 0===S?void 0:S.$case)&&(V.subscription=(null===(k=e.message)||void 0===k?void 0:k.subscription)?Nt.toJSON(null===(y=e.message)||void 0===y?void 0:y.subscription):void 0),"trackSetting"===(null===(w=e.message)||void 0===w?void 0:w.$case)&&(V.trackSetting=(null===(T=e.message)||void 0===T?void 0:T.trackSetting)?It.toJSON(null===(C=e.message)||void 0===C?void 0:C.trackSetting):void 0),"leave"===(null===(P=e.message)||void 0===P?void 0:P.$case)&&(V.leave=(null===(E=e.message)||void 0===E?void 0:E.leave)?Dt.toJSON(null===(R=e.message)||void 0===R?void 0:R.leave):void 0),"updateLayers"===(null===(O=e.message)||void 0===O?void 0:O.$case)&&(V.updateLayers=(null===(N=e.message)||void 0===N?void 0:N.updateLayers)?_t.toJSON(null===(I=e.message)||void 0===I?void 0:I.updateLayers):void 0),"subscriptionPermission"===(null===(D=e.message)||void 0===D?void 0:D.$case)&&(V.subscriptionPermission=(null===(_=e.message)||void 0===_?void 0:_.subscriptionPermission)?Wt.toJSON(null===(A=e.message)||void 0===A?void 0:A.subscriptionPermission):void 0),"syncState"===(null===(L=e.message)||void 0===L?void 0:L.$case)&&(V.syncState=(null===(U=e.message)||void 0===U?void 0:U.syncState)?Gt.toJSON(null===(x=e.message)||void 0===x?void 0:x.syncState):void 0),"simulate"===(null===(M=e.message)||void 0===M?void 0:M.$case)&&(V.simulate=(null===($=e.message)||void 0===$?void 0:$.simulate)?zt.toJSON(null===(B=e.message)||void 0===B?void 0:B.simulate):void 0),"ping"===(null===(F=e.message)||void 0===F?void 0:F.$case)&&(V.ping=Math.round(null===(J=e.message)||void 0===J?void 0:J.ping)),V},fromPartial(e){var t,i,n,s,o,a,c,u,l,h,p,m,v,g,b,S,k,y,w,T,C,P,E,R,O,N,I,D,_,A,L,U,x,M,$,B,F,J,V;const j={message:void 0};return"offer"===(null===(t=e.message)||void 0===t?void 0:t.$case)&&void 0!==(null===(i=e.message)||void 0===i?void 0:i.offer)&&null!==(null===(n=e.message)||void 0===n?void 0:n.offer)&&(j.message={$case:"offer",offer:Rt.fromPartial(e.message.offer)}),"answer"===(null===(s=e.message)||void 0===s?void 0:s.$case)&&void 0!==(null===(o=e.message)||void 0===o?void 0:o.answer)&&null!==(null===(a=e.message)||void 0===a?void 0:a.answer)&&(j.message={$case:"answer",answer:Rt.fromPartial(e.message.answer)}),"trickle"===(null===(c=e.message)||void 0===c?void 0:c.$case)&&void 0!==(null===(u=e.message)||void 0===u?void 0:u.trickle)&&null!==(null===(l=e.message)||void 0===l?void 0:l.trickle)&&(j.message={$case:"trickle",trickle:yt.fromPartial(e.message.trickle)}),"addTrack"===(null===(h=e.message)||void 0===h?void 0:h.$case)&&void 0!==(null===(p=e.message)||void 0===p?void 0:p.addTrack)&&null!==(null===(m=e.message)||void 0===m?void 0:m.addTrack)&&(j.message={$case:"addTrack",addTrack:kt.fromPartial(e.message.addTrack)}),"mute"===(null===(v=e.message)||void 0===v?void 0:v.$case)&&void 0!==(null===(g=e.message)||void 0===g?void 0:g.mute)&&null!==(null===(b=e.message)||void 0===b?void 0:b.mute)&&(j.message={$case:"mute",mute:wt.fromPartial(e.message.mute)}),"subscription"===(null===(S=e.message)||void 0===S?void 0:S.$case)&&void 0!==(null===(k=e.message)||void 0===k?void 0:k.subscription)&&null!==(null===(y=e.message)||void 0===y?void 0:y.subscription)&&(j.message={$case:"subscription",subscription:Nt.fromPartial(e.message.subscription)}),"trackSetting"===(null===(w=e.message)||void 0===w?void 0:w.$case)&&void 0!==(null===(T=e.message)||void 0===T?void 0:T.trackSetting)&&null!==(null===(C=e.message)||void 0===C?void 0:C.trackSetting)&&(j.message={$case:"trackSetting",trackSetting:It.fromPartial(e.message.trackSetting)}),"leave"===(null===(P=e.message)||void 0===P?void 0:P.$case)&&void 0!==(null===(E=e.message)||void 0===E?void 0:E.leave)&&null!==(null===(R=e.message)||void 0===R?void 0:R.leave)&&(j.message={$case:"leave",leave:Dt.fromPartial(e.message.leave)}),"updateLayers"===(null===(O=e.message)||void 0===O?void 0:O.$case)&&void 0!==(null===(N=e.message)||void 0===N?void 0:N.updateLayers)&&null!==(null===(I=e.message)||void 0===I?void 0:I.updateLayers)&&(j.message={$case:"updateLayers",updateLayers:_t.fromPartial(e.message.updateLayers)}),"subscriptionPermission"===(null===(D=e.message)||void 0===D?void 0:D.$case)&&void 0!==(null===(_=e.message)||void 0===_?void 0:_.subscriptionPermission)&&null!==(null===(A=e.message)||void 0===A?void 0:A.subscriptionPermission)&&(j.message={$case:"subscriptionPermission",subscriptionPermission:Wt.fromPartial(e.message.subscriptionPermission)}),"syncState"===(null===(L=e.message)||void 0===L?void 0:L.$case)&&void 0!==(null===(U=e.message)||void 0===U?void 0:U.syncState)&&null!==(null===(x=e.message)||void 0===x?void 0:x.syncState)&&(j.message={$case:"syncState",syncState:Gt.fromPartial(e.message.syncState)}),"simulate"===(null===(M=e.message)||void 0===M?void 0:M.$case)&&void 0!==(null===($=e.message)||void 0===$?void 0:$.simulate)&&null!==(null===(B=e.message)||void 0===B?void 0:B.simulate)&&(j.message={$case:"simulate",simulate:zt.fromPartial(e.message.simulate)}),"ping"===(null===(F=e.message)||void 0===F?void 0:F.$case)&&void 0!==(null===(J=e.message)||void 0===J?void 0:J.ping)&&null!==(null===(V=e.message)||void 0===V?void 0:V.ping)&&(j.message={$case:"ping",ping:e.message.ping}),j}};const bt={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xe.Writer.create();var i,n,s,o,a,c,u,l,h,p,m,v,g,b,S,k,y,w;return"join"===(null===(i=e.message)||void 0===i?void 0:i.$case)&&Tt.encode(e.message.join,t.uint32(10).fork()).ldelim(),"answer"===(null===(n=e.message)||void 0===n?void 0:n.$case)&&Rt.encode(e.message.answer,t.uint32(18).fork()).ldelim(),"offer"===(null===(s=e.message)||void 0===s?void 0:s.$case)&&Rt.encode(e.message.offer,t.uint32(26).fork()).ldelim(),"trickle"===(null===(o=e.message)||void 0===o?void 0:o.$case)&&yt.encode(e.message.trickle,t.uint32(34).fork()).ldelim(),"update"===(null===(a=e.message)||void 0===a?void 0:a.$case)&&Ot.encode(e.message.update,t.uint32(42).fork()).ldelim(),"trackPublished"===(null===(c=e.message)||void 0===c?void 0:c.$case)&&Pt.encode(e.message.trackPublished,t.uint32(50).fork()).ldelim(),"leave"===(null===(u=e.message)||void 0===u?void 0:u.$case)&&Dt.encode(e.message.leave,t.uint32(66).fork()).ldelim(),"mute"===(null===(l=e.message)||void 0===l?void 0:l.$case)&&wt.encode(e.message.mute,t.uint32(74).fork()).ldelim(),"speakersChanged"===(null===(h=e.message)||void 0===h?void 0:h.$case)&&Lt.encode(e.message.speakersChanged,t.uint32(82).fork()).ldelim(),"roomUpdate"===(null===(p=e.message)||void 0===p?void 0:p.$case)&&Ut.encode(e.message.roomUpdate,t.uint32(90).fork()).ldelim(),"connectionQuality"===(null===(m=e.message)||void 0===m?void 0:m.$case)&&Mt.encode(e.message.connectionQuality,t.uint32(98).fork()).ldelim(),"streamStateUpdate"===(null===(v=e.message)||void 0===v?void 0:v.$case)&&Bt.encode(e.message.streamStateUpdate,t.uint32(106).fork()).ldelim(),"subscribedQualityUpdate"===(null===(g=e.message)||void 0===g?void 0:g.$case)&&Vt.encode(e.message.subscribedQualityUpdate,t.uint32(114).fork()).ldelim(),"subscriptionPermissionUpdate"===(null===(b=e.message)||void 0===b?void 0:b.$case)&&qt.encode(e.message.subscriptionPermissionUpdate,t.uint32(122).fork()).ldelim(),"refreshToken"===(null===(S=e.message)||void 0===S?void 0:S.$case)&&t.uint32(130).string(e.message.refreshToken),"trackUnpublished"===(null===(k=e.message)||void 0===k?void 0:k.$case)&&Et.encode(e.message.trackUnpublished,t.uint32(138).fork()).ldelim(),"pong"===(null===(y=e.message)||void 0===y?void 0:y.$case)&&t.uint32(144).int64(e.message.pong),"reconnect"===(null===(w=e.message)||void 0===w?void 0:w.$case)&&Ct.encode(e.message.reconnect,t.uint32(154).fork()).ldelim(),t},decode(e,t){const i=e instanceof xe.Reader?e:new xe.Reader(e);let n=void 0===t?i.len:i.pos+t;const s={message:void 0};for(;i.pos>>3){case 1:s.message={$case:"join",join:Tt.decode(i,i.uint32())};break;case 2:s.message={$case:"answer",answer:Rt.decode(i,i.uint32())};break;case 3:s.message={$case:"offer",offer:Rt.decode(i,i.uint32())};break;case 4:s.message={$case:"trickle",trickle:yt.decode(i,i.uint32())};break;case 5:s.message={$case:"update",update:Ot.decode(i,i.uint32())};break;case 6:s.message={$case:"trackPublished",trackPublished:Pt.decode(i,i.uint32())};break;case 8:s.message={$case:"leave",leave:Dt.decode(i,i.uint32())};break;case 9:s.message={$case:"mute",mute:wt.decode(i,i.uint32())};break;case 10:s.message={$case:"speakersChanged",speakersChanged:Lt.decode(i,i.uint32())};break;case 11:s.message={$case:"roomUpdate",roomUpdate:Ut.decode(i,i.uint32())};break;case 12:s.message={$case:"connectionQuality",connectionQuality:Mt.decode(i,i.uint32())};break;case 13:s.message={$case:"streamStateUpdate",streamStateUpdate:Bt.decode(i,i.uint32())};break;case 14:s.message={$case:"subscribedQualityUpdate",subscribedQualityUpdate:Vt.decode(i,i.uint32())};break;case 15:s.message={$case:"subscriptionPermissionUpdate",subscriptionPermissionUpdate:qt.decode(i,i.uint32())};break;case 16:s.message={$case:"refreshToken",refreshToken:i.string()};break;case 17:s.message={$case:"trackUnpublished",trackUnpublished:Et.decode(i,i.uint32())};break;case 18:s.message={$case:"pong",pong:longToNumber(i.int64())};break;case 19:s.message={$case:"reconnect",reconnect:Ct.decode(i,i.uint32())};break;default:i.skipType(7&e)}}return s},fromJSON:e=>({message:isSet(e.join)?{$case:"join",join:Tt.fromJSON(e.join)}:isSet(e.answer)?{$case:"answer",answer:Rt.fromJSON(e.answer)}:isSet(e.offer)?{$case:"offer",offer:Rt.fromJSON(e.offer)}:isSet(e.trickle)?{$case:"trickle",trickle:yt.fromJSON(e.trickle)}:isSet(e.update)?{$case:"update",update:Ot.fromJSON(e.update)}:isSet(e.trackPublished)?{$case:"trackPublished",trackPublished:Pt.fromJSON(e.trackPublished)}:isSet(e.leave)?{$case:"leave",leave:Dt.fromJSON(e.leave)}:isSet(e.mute)?{$case:"mute",mute:wt.fromJSON(e.mute)}:isSet(e.speakersChanged)?{$case:"speakersChanged",speakersChanged:Lt.fromJSON(e.speakersChanged)}:isSet(e.roomUpdate)?{$case:"roomUpdate",roomUpdate:Ut.fromJSON(e.roomUpdate)}:isSet(e.connectionQuality)?{$case:"connectionQuality",connectionQuality:Mt.fromJSON(e.connectionQuality)}:isSet(e.streamStateUpdate)?{$case:"streamStateUpdate",streamStateUpdate:Bt.fromJSON(e.streamStateUpdate)}:isSet(e.subscribedQualityUpdate)?{$case:"subscribedQualityUpdate",subscribedQualityUpdate:Vt.fromJSON(e.subscribedQualityUpdate)}:isSet(e.subscriptionPermissionUpdate)?{$case:"subscriptionPermissionUpdate",subscriptionPermissionUpdate:qt.fromJSON(e.subscriptionPermissionUpdate)}:isSet(e.refreshToken)?{$case:"refreshToken",refreshToken:String(e.refreshToken)}:isSet(e.trackUnpublished)?{$case:"trackUnpublished",trackUnpublished:Et.fromJSON(e.trackUnpublished)}:isSet(e.pong)?{$case:"pong",pong:Number(e.pong)}:isSet(e.reconnect)?{$case:"reconnect",reconnect:Ct.fromJSON(e.reconnect)}:void 0}),toJSON(e){var t,i,n,s,o,a,c,u,l,h,p,m,v,g,b,S,k,y,w,T,C,P,E,R,O,N,I,D,_,A,L,U,x,M,$,B,F,J,V,j,W,q,G,Q,z,H,Z,K,Y,X,ee,te;const ie={};return"join"===(null===(t=e.message)||void 0===t?void 0:t.$case)&&(ie.join=(null===(i=e.message)||void 0===i?void 0:i.join)?Tt.toJSON(null===(n=e.message)||void 0===n?void 0:n.join):void 0),"answer"===(null===(s=e.message)||void 0===s?void 0:s.$case)&&(ie.answer=(null===(o=e.message)||void 0===o?void 0:o.answer)?Rt.toJSON(null===(a=e.message)||void 0===a?void 0:a.answer):void 0),"offer"===(null===(c=e.message)||void 0===c?void 0:c.$case)&&(ie.offer=(null===(u=e.message)||void 0===u?void 0:u.offer)?Rt.toJSON(null===(l=e.message)||void 0===l?void 0:l.offer):void 0),"trickle"===(null===(h=e.message)||void 0===h?void 0:h.$case)&&(ie.trickle=(null===(p=e.message)||void 0===p?void 0:p.trickle)?yt.toJSON(null===(m=e.message)||void 0===m?void 0:m.trickle):void 0),"update"===(null===(v=e.message)||void 0===v?void 0:v.$case)&&(ie.update=(null===(g=e.message)||void 0===g?void 0:g.update)?Ot.toJSON(null===(b=e.message)||void 0===b?void 0:b.update):void 0),"trackPublished"===(null===(S=e.message)||void 0===S?void 0:S.$case)&&(ie.trackPublished=(null===(k=e.message)||void 0===k?void 0:k.trackPublished)?Pt.toJSON(null===(y=e.message)||void 0===y?void 0:y.trackPublished):void 0),"leave"===(null===(w=e.message)||void 0===w?void 0:w.$case)&&(ie.leave=(null===(T=e.message)||void 0===T?void 0:T.leave)?Dt.toJSON(null===(C=e.message)||void 0===C?void 0:C.leave):void 0),"mute"===(null===(P=e.message)||void 0===P?void 0:P.$case)&&(ie.mute=(null===(E=e.message)||void 0===E?void 0:E.mute)?wt.toJSON(null===(R=e.message)||void 0===R?void 0:R.mute):void 0),"speakersChanged"===(null===(O=e.message)||void 0===O?void 0:O.$case)&&(ie.speakersChanged=(null===(N=e.message)||void 0===N?void 0:N.speakersChanged)?Lt.toJSON(null===(I=e.message)||void 0===I?void 0:I.speakersChanged):void 0),"roomUpdate"===(null===(D=e.message)||void 0===D?void 0:D.$case)&&(ie.roomUpdate=(null===(_=e.message)||void 0===_?void 0:_.roomUpdate)?Ut.toJSON(null===(A=e.message)||void 0===A?void 0:A.roomUpdate):void 0),"connectionQuality"===(null===(L=e.message)||void 0===L?void 0:L.$case)&&(ie.connectionQuality=(null===(U=e.message)||void 0===U?void 0:U.connectionQuality)?Mt.toJSON(null===(x=e.message)||void 0===x?void 0:x.connectionQuality):void 0),"streamStateUpdate"===(null===(M=e.message)||void 0===M?void 0:M.$case)&&(ie.streamStateUpdate=(null===($=e.message)||void 0===$?void 0:$.streamStateUpdate)?Bt.toJSON(null===(B=e.message)||void 0===B?void 0:B.streamStateUpdate):void 0),"subscribedQualityUpdate"===(null===(F=e.message)||void 0===F?void 0:F.$case)&&(ie.subscribedQualityUpdate=(null===(J=e.message)||void 0===J?void 0:J.subscribedQualityUpdate)?Vt.toJSON(null===(V=e.message)||void 0===V?void 0:V.subscribedQualityUpdate):void 0),"subscriptionPermissionUpdate"===(null===(j=e.message)||void 0===j?void 0:j.$case)&&(ie.subscriptionPermissionUpdate=(null===(W=e.message)||void 0===W?void 0:W.subscriptionPermissionUpdate)?qt.toJSON(null===(q=e.message)||void 0===q?void 0:q.subscriptionPermissionUpdate):void 0),"refreshToken"===(null===(G=e.message)||void 0===G?void 0:G.$case)&&(ie.refreshToken=null===(Q=e.message)||void 0===Q?void 0:Q.refreshToken),"trackUnpublished"===(null===(z=e.message)||void 0===z?void 0:z.$case)&&(ie.trackUnpublished=(null===(H=e.message)||void 0===H?void 0:H.trackUnpublished)?Et.toJSON(null===(Z=e.message)||void 0===Z?void 0:Z.trackUnpublished):void 0),"pong"===(null===(K=e.message)||void 0===K?void 0:K.$case)&&(ie.pong=Math.round(null===(Y=e.message)||void 0===Y?void 0:Y.pong)),"reconnect"===(null===(X=e.message)||void 0===X?void 0:X.$case)&&(ie.reconnect=(null===(ee=e.message)||void 0===ee?void 0:ee.reconnect)?Ct.toJSON(null===(te=e.message)||void 0===te?void 0:te.reconnect):void 0),ie},fromPartial(e){var t,i,n,s,o,a,c,u,l,h,p,m,v,g,b,S,k,y,w,T,C,P,E,R,O,N,I,D,_,A,L,U,x,M,$,B,F,J,V,j,W,q,G,Q,z,H,Z,K,Y,X,ee,te,ie,ne;const re={message:void 0};return"join"===(null===(t=e.message)||void 0===t?void 0:t.$case)&&void 0!==(null===(i=e.message)||void 0===i?void 0:i.join)&&null!==(null===(n=e.message)||void 0===n?void 0:n.join)&&(re.message={$case:"join",join:Tt.fromPartial(e.message.join)}),"answer"===(null===(s=e.message)||void 0===s?void 0:s.$case)&&void 0!==(null===(o=e.message)||void 0===o?void 0:o.answer)&&null!==(null===(a=e.message)||void 0===a?void 0:a.answer)&&(re.message={$case:"answer",answer:Rt.fromPartial(e.message.answer)}),"offer"===(null===(c=e.message)||void 0===c?void 0:c.$case)&&void 0!==(null===(u=e.message)||void 0===u?void 0:u.offer)&&null!==(null===(l=e.message)||void 0===l?void 0:l.offer)&&(re.message={$case:"offer",offer:Rt.fromPartial(e.message.offer)}),"trickle"===(null===(h=e.message)||void 0===h?void 0:h.$case)&&void 0!==(null===(p=e.message)||void 0===p?void 0:p.trickle)&&null!==(null===(m=e.message)||void 0===m?void 0:m.trickle)&&(re.message={$case:"trickle",trickle:yt.fromPartial(e.message.trickle)}),"update"===(null===(v=e.message)||void 0===v?void 0:v.$case)&&void 0!==(null===(g=e.message)||void 0===g?void 0:g.update)&&null!==(null===(b=e.message)||void 0===b?void 0:b.update)&&(re.message={$case:"update",update:Ot.fromPartial(e.message.update)}),"trackPublished"===(null===(S=e.message)||void 0===S?void 0:S.$case)&&void 0!==(null===(k=e.message)||void 0===k?void 0:k.trackPublished)&&null!==(null===(y=e.message)||void 0===y?void 0:y.trackPublished)&&(re.message={$case:"trackPublished",trackPublished:Pt.fromPartial(e.message.trackPublished)}),"leave"===(null===(w=e.message)||void 0===w?void 0:w.$case)&&void 0!==(null===(T=e.message)||void 0===T?void 0:T.leave)&&null!==(null===(C=e.message)||void 0===C?void 0:C.leave)&&(re.message={$case:"leave",leave:Dt.fromPartial(e.message.leave)}),"mute"===(null===(P=e.message)||void 0===P?void 0:P.$case)&&void 0!==(null===(E=e.message)||void 0===E?void 0:E.mute)&&null!==(null===(R=e.message)||void 0===R?void 0:R.mute)&&(re.message={$case:"mute",mute:wt.fromPartial(e.message.mute)}),"speakersChanged"===(null===(O=e.message)||void 0===O?void 0:O.$case)&&void 0!==(null===(N=e.message)||void 0===N?void 0:N.speakersChanged)&&null!==(null===(I=e.message)||void 0===I?void 0:I.speakersChanged)&&(re.message={$case:"speakersChanged",speakersChanged:Lt.fromPartial(e.message.speakersChanged)}),"roomUpdate"===(null===(D=e.message)||void 0===D?void 0:D.$case)&&void 0!==(null===(_=e.message)||void 0===_?void 0:_.roomUpdate)&&null!==(null===(A=e.message)||void 0===A?void 0:A.roomUpdate)&&(re.message={$case:"roomUpdate",roomUpdate:Ut.fromPartial(e.message.roomUpdate)}),"connectionQuality"===(null===(L=e.message)||void 0===L?void 0:L.$case)&&void 0!==(null===(U=e.message)||void 0===U?void 0:U.connectionQuality)&&null!==(null===(x=e.message)||void 0===x?void 0:x.connectionQuality)&&(re.message={$case:"connectionQuality",connectionQuality:Mt.fromPartial(e.message.connectionQuality)}),"streamStateUpdate"===(null===(M=e.message)||void 0===M?void 0:M.$case)&&void 0!==(null===($=e.message)||void 0===$?void 0:$.streamStateUpdate)&&null!==(null===(B=e.message)||void 0===B?void 0:B.streamStateUpdate)&&(re.message={$case:"streamStateUpdate",streamStateUpdate:Bt.fromPartial(e.message.streamStateUpdate)}),"subscribedQualityUpdate"===(null===(F=e.message)||void 0===F?void 0:F.$case)&&void 0!==(null===(J=e.message)||void 0===J?void 0:J.subscribedQualityUpdate)&&null!==(null===(V=e.message)||void 0===V?void 0:V.subscribedQualityUpdate)&&(re.message={$case:"subscribedQualityUpdate",subscribedQualityUpdate:Vt.fromPartial(e.message.subscribedQualityUpdate)}),"subscriptionPermissionUpdate"===(null===(j=e.message)||void 0===j?void 0:j.$case)&&void 0!==(null===(W=e.message)||void 0===W?void 0:W.subscriptionPermissionUpdate)&&null!==(null===(q=e.message)||void 0===q?void 0:q.subscriptionPermissionUpdate)&&(re.message={$case:"subscriptionPermissionUpdate",subscriptionPermissionUpdate:qt.fromPartial(e.message.subscriptionPermissionUpdate)}),"refreshToken"===(null===(G=e.message)||void 0===G?void 0:G.$case)&&void 0!==(null===(Q=e.message)||void 0===Q?void 0:Q.refreshToken)&&null!==(null===(z=e.message)||void 0===z?void 0:z.refreshToken)&&(re.message={$case:"refreshToken",refreshToken:e.message.refreshToken}),"trackUnpublished"===(null===(H=e.message)||void 0===H?void 0:H.$case)&&void 0!==(null===(Z=e.message)||void 0===Z?void 0:Z.trackUnpublished)&&null!==(null===(K=e.message)||void 0===K?void 0:K.trackUnpublished)&&(re.message={$case:"trackUnpublished",trackUnpublished:Et.fromPartial(e.message.trackUnpublished)}),"pong"===(null===(Y=e.message)||void 0===Y?void 0:Y.$case)&&void 0!==(null===(X=e.message)||void 0===X?void 0:X.pong)&&null!==(null===(ee=e.message)||void 0===ee?void 0:ee.pong)&&(re.message={$case:"pong",pong:e.message.pong}),"reconnect"===(null===(te=e.message)||void 0===te?void 0:te.$case)&&void 0!==(null===(ie=e.message)||void 0===ie?void 0:ie.reconnect)&&null!==(null===(ne=e.message)||void 0===ne?void 0:ne.reconnect)&&(re.message={$case:"reconnect",reconnect:Ct.fromPartial(e.message.reconnect)}),re}};const St={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xe.Writer.create();return""!==e.codec&&t.uint32(10).string(e.codec),""!==e.cid&&t.uint32(18).string(e.cid),!0===e.enableSimulcastLayers&&t.uint32(24).bool(e.enableSimulcastLayers),t},decode(e,t){const i=e instanceof xe.Reader?e:new xe.Reader(e);let n=void 0===t?i.len:i.pos+t;const s={codec:"",cid:"",enableSimulcastLayers:!1};for(;i.pos>>3){case 1:s.codec=i.string();break;case 2:s.cid=i.string();break;case 3:s.enableSimulcastLayers=i.bool();break;default:i.skipType(7&e)}}return s},fromJSON:e=>({codec:isSet(e.codec)?String(e.codec):"",cid:isSet(e.cid)?String(e.cid):"",enableSimulcastLayers:!!isSet(e.enableSimulcastLayers)&&Boolean(e.enableSimulcastLayers)}),toJSON(e){const t={};return void 0!==e.codec&&(t.codec=e.codec),void 0!==e.cid&&(t.cid=e.cid),void 0!==e.enableSimulcastLayers&&(t.enableSimulcastLayers=e.enableSimulcastLayers),t},fromPartial(e){var t,i,n;const s={codec:"",cid:"",enableSimulcastLayers:!1};return s.codec=null!==(t=e.codec)&&void 0!==t?t:"",s.cid=null!==(i=e.cid)&&void 0!==i?i:"",s.enableSimulcastLayers=null!==(n=e.enableSimulcastLayers)&&void 0!==n&&n,s}};const kt={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xe.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)We.encode(i,t.uint32(74).fork()).ldelim();for(const i of e.simulcastCodecs)St.encode(i,t.uint32(82).fork()).ldelim();return""!==e.sid&&t.uint32(90).string(e.sid),!0===e.stereo&&t.uint32(96).bool(e.stereo),!0===e.disableRed&&t.uint32(104).bool(e.disableRed),0!==e.encryption&&t.uint32(112).int32(e.encryption),t},decode(e,t){const i=e instanceof xe.Reader?e:new xe.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:[],simulcastCodecs:[],sid:"",stereo:!1,disableRed:!1,encryption:0};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(We.decode(i,i.uint32()));break;case 10:s.simulcastCodecs.push(St.decode(i,i.uint32()));break;case 11:s.sid=i.string();break;case 12:s.stereo=i.bool();break;case 13:s.disableRed=i.bool();break;case 14:s.encryption=i.int32();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=>We.fromJSON(e))):[],simulcastCodecs:Array.isArray(null==e?void 0:e.simulcastCodecs)?e.simulcastCodecs.map((e=>St.fromJSON(e))):[],sid:isSet(e.sid)?String(e.sid):"",stereo:!!isSet(e.stereo)&&Boolean(e.stereo),disableRed:!!isSet(e.disableRed)&&Boolean(e.disableRed),encryption:isSet(e.encryption)?encryption_TypeFromJSON(e.encryption):0}),toJSON(e){const t={};return void 0!==e.cid&&(t.cid=e.cid),void 0!==e.name&&(t.name=e.name),void 0!==e.type&&(t.type=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?We.toJSON(e):void 0)):t.layers=[],e.simulcastCodecs?t.simulcastCodecs=e.simulcastCodecs.map((e=>e?St.toJSON(e):void 0)):t.simulcastCodecs=[],void 0!==e.sid&&(t.sid=e.sid),void 0!==e.stereo&&(t.stereo=e.stereo),void 0!==e.disableRed&&(t.disableRed=e.disableRed),void 0!==e.encryption&&(t.encryption=encryption_TypeToJSON(e.encryption)),t},fromPartial(e){var t,i,n,s,o,a,c,u,l,h,p,m,v,g;const b={cid:"",name:"",type:0,width:0,height:0,muted:!1,disableDtx:!1,source:0,layers:[],simulcastCodecs:[],sid:"",stereo:!1,disableRed:!1,encryption:0};return b.cid=null!==(t=e.cid)&&void 0!==t?t:"",b.name=null!==(i=e.name)&&void 0!==i?i:"",b.type=null!==(n=e.type)&&void 0!==n?n:0,b.width=null!==(s=e.width)&&void 0!==s?s:0,b.height=null!==(o=e.height)&&void 0!==o?o:0,b.muted=null!==(a=e.muted)&&void 0!==a&&a,b.disableDtx=null!==(c=e.disableDtx)&&void 0!==c&&c,b.source=null!==(u=e.source)&&void 0!==u?u:0,b.layers=(null===(l=e.layers)||void 0===l?void 0:l.map((e=>We.fromPartial(e))))||[],b.simulcastCodecs=(null===(h=e.simulcastCodecs)||void 0===h?void 0:h.map((e=>St.fromPartial(e))))||[],b.sid=null!==(p=e.sid)&&void 0!==p?p:"",b.stereo=null!==(m=e.stereo)&&void 0!==m&&m,b.disableRed=null!==(v=e.disableRed)&&void 0!==v&&v,b.encryption=null!==(g=e.encryption)&&void 0!==g?g:0,b}};const yt={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xe.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 xe.Reader?e:new xe.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 wt={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xe.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 xe.Reader?e:new xe.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 Tt={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xe.Writer.create();void 0!==e.room&&$e.encode(e.room,t.uint32(10).fork()).ldelim(),void 0!==e.participant&&Je.encode(e.participant,t.uint32(18).fork()).ldelim();for(const i of e.otherParticipants)Je.encode(i,t.uint32(26).fork()).ldelim();""!==e.serverVersion&&t.uint32(34).string(e.serverVersion);for(const i of e.iceServers)At.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&&Ye.encode(e.clientConfiguration,t.uint32(66).fork()).ldelim(),""!==e.serverRegion&&t.uint32(74).string(e.serverRegion),0!==e.pingTimeout&&t.uint32(80).int32(e.pingTimeout),0!==e.pingInterval&&t.uint32(88).int32(e.pingInterval),void 0!==e.serverInfo&&Ze.encode(e.serverInfo,t.uint32(98).fork()).ldelim(),t},decode(e,t){const i=e instanceof xe.Reader?e:new xe.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:"",pingTimeout:0,pingInterval:0,serverInfo:void 0};for(;i.pos>>3){case 1:s.room=$e.decode(i,i.uint32());break;case 2:s.participant=Je.decode(i,i.uint32());break;case 3:s.otherParticipants.push(Je.decode(i,i.uint32()));break;case 4:s.serverVersion=i.string();break;case 5:s.iceServers.push(At.decode(i,i.uint32()));break;case 6:s.subscriberPrimary=i.bool();break;case 7:s.alternativeUrl=i.string();break;case 8:s.clientConfiguration=Ye.decode(i,i.uint32());break;case 9:s.serverRegion=i.string();break;case 10:s.pingTimeout=i.int32();break;case 11:s.pingInterval=i.int32();break;case 12:s.serverInfo=Ze.decode(i,i.uint32());break;default:i.skipType(7&e)}}return s},fromJSON:e=>({room:isSet(e.room)?$e.fromJSON(e.room):void 0,participant:isSet(e.participant)?Je.fromJSON(e.participant):void 0,otherParticipants:Array.isArray(null==e?void 0:e.otherParticipants)?e.otherParticipants.map((e=>Je.fromJSON(e))):[],serverVersion:isSet(e.serverVersion)?String(e.serverVersion):"",iceServers:Array.isArray(null==e?void 0:e.iceServers)?e.iceServers.map((e=>At.fromJSON(e))):[],subscriberPrimary:!!isSet(e.subscriberPrimary)&&Boolean(e.subscriberPrimary),alternativeUrl:isSet(e.alternativeUrl)?String(e.alternativeUrl):"",clientConfiguration:isSet(e.clientConfiguration)?Ye.fromJSON(e.clientConfiguration):void 0,serverRegion:isSet(e.serverRegion)?String(e.serverRegion):"",pingTimeout:isSet(e.pingTimeout)?Number(e.pingTimeout):0,pingInterval:isSet(e.pingInterval)?Number(e.pingInterval):0,serverInfo:isSet(e.serverInfo)?Ze.fromJSON(e.serverInfo):void 0}),toJSON(e){const t={};return void 0!==e.room&&(t.room=e.room?$e.toJSON(e.room):void 0),void 0!==e.participant&&(t.participant=e.participant?Je.toJSON(e.participant):void 0),e.otherParticipants?t.otherParticipants=e.otherParticipants.map((e=>e?Je.toJSON(e):void 0)):t.otherParticipants=[],void 0!==e.serverVersion&&(t.serverVersion=e.serverVersion),e.iceServers?t.iceServers=e.iceServers.map((e=>e?At.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?Ye.toJSON(e.clientConfiguration):void 0),void 0!==e.serverRegion&&(t.serverRegion=e.serverRegion),void 0!==e.pingTimeout&&(t.pingTimeout=Math.round(e.pingTimeout)),void 0!==e.pingInterval&&(t.pingInterval=Math.round(e.pingInterval)),void 0!==e.serverInfo&&(t.serverInfo=e.serverInfo?Ze.toJSON(e.serverInfo):void 0),t},fromPartial(e){var t,i,n,s,o,a,c,u;const l={room:void 0,participant:void 0,otherParticipants:[],serverVersion:"",iceServers:[],subscriberPrimary:!1,alternativeUrl:"",clientConfiguration:void 0,serverRegion:"",pingTimeout:0,pingInterval:0,serverInfo:void 0};return l.room=void 0!==e.room&&null!==e.room?$e.fromPartial(e.room):void 0,l.participant=void 0!==e.participant&&null!==e.participant?Je.fromPartial(e.participant):void 0,l.otherParticipants=(null===(t=e.otherParticipants)||void 0===t?void 0:t.map((e=>Je.fromPartial(e))))||[],l.serverVersion=null!==(i=e.serverVersion)&&void 0!==i?i:"",l.iceServers=(null===(n=e.iceServers)||void 0===n?void 0:n.map((e=>At.fromPartial(e))))||[],l.subscriberPrimary=null!==(s=e.subscriberPrimary)&&void 0!==s&&s,l.alternativeUrl=null!==(o=e.alternativeUrl)&&void 0!==o?o:"",l.clientConfiguration=void 0!==e.clientConfiguration&&null!==e.clientConfiguration?Ye.fromPartial(e.clientConfiguration):void 0,l.serverRegion=null!==(a=e.serverRegion)&&void 0!==a?a:"",l.pingTimeout=null!==(c=e.pingTimeout)&&void 0!==c?c:0,l.pingInterval=null!==(u=e.pingInterval)&&void 0!==u?u:0,l.serverInfo=void 0!==e.serverInfo&&null!==e.serverInfo?Ze.fromPartial(e.serverInfo):void 0,l}};const Ct={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xe.Writer.create();for(const i of e.iceServers)At.encode(i,t.uint32(10).fork()).ldelim();return void 0!==e.clientConfiguration&&Ye.encode(e.clientConfiguration,t.uint32(18).fork()).ldelim(),t},decode(e,t){const i=e instanceof xe.Reader?e:new xe.Reader(e);let n=void 0===t?i.len:i.pos+t;const s={iceServers:[],clientConfiguration:void 0};for(;i.pos>>3){case 1:s.iceServers.push(At.decode(i,i.uint32()));break;case 2:s.clientConfiguration=Ye.decode(i,i.uint32());break;default:i.skipType(7&e)}}return s},fromJSON:e=>({iceServers:Array.isArray(null==e?void 0:e.iceServers)?e.iceServers.map((e=>At.fromJSON(e))):[],clientConfiguration:isSet(e.clientConfiguration)?Ye.fromJSON(e.clientConfiguration):void 0}),toJSON(e){const t={};return e.iceServers?t.iceServers=e.iceServers.map((e=>e?At.toJSON(e):void 0)):t.iceServers=[],void 0!==e.clientConfiguration&&(t.clientConfiguration=e.clientConfiguration?Ye.toJSON(e.clientConfiguration):void 0),t},fromPartial(e){var t;const i={iceServers:[],clientConfiguration:void 0};return i.iceServers=(null===(t=e.iceServers)||void 0===t?void 0:t.map((e=>At.fromPartial(e))))||[],i.clientConfiguration=void 0!==e.clientConfiguration&&null!==e.clientConfiguration?Ye.fromPartial(e.clientConfiguration):void 0,i}};const Pt={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xe.Writer.create();return""!==e.cid&&t.uint32(10).string(e.cid),void 0!==e.track&&je.encode(e.track,t.uint32(18).fork()).ldelim(),t},decode(e,t){const i=e instanceof xe.Reader?e:new xe.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=je.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)?je.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?je.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?je.fromPartial(e.track):void 0,i}};const Et={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xe.Writer.create();return""!==e.trackSid&&t.uint32(10).string(e.trackSid),t},decode(e,t){const i=e instanceof xe.Reader?e:new xe.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 Rt={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xe.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 xe.Reader?e:new xe.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 Ot={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xe.Writer.create();for(const i of e.participants)Je.encode(i,t.uint32(10).fork()).ldelim();return t},decode(e,t){const i=e instanceof xe.Reader?e:new xe.Reader(e);let n=void 0===t?i.len:i.pos+t;const s={participants:[]};for(;i.pos>>3==1)s.participants.push(Je.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=>Je.fromJSON(e))):[]}),toJSON(e){const t={};return e.participants?t.participants=e.participants.map((e=>e?Je.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=>Je.fromPartial(e))))||[],i}};const Nt={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xe.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)He.encode(i,t.uint32(26).fork()).ldelim();return t},decode(e,t){const i=e instanceof xe.Reader?e:new xe.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(He.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=>He.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?He.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=>He.fromPartial(e))))||[],s}};const It={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xe.Writer.create();for(const i of e.trackSids)t.uint32(10).string(i);return!0===e.disabled&&t.uint32(24).bool(e.disabled),0!==e.quality&&t.uint32(32).int32(e.quality),0!==e.width&&t.uint32(40).uint32(e.width),0!==e.height&&t.uint32(48).uint32(e.height),0!==e.fps&&t.uint32(56).uint32(e.fps),t},decode(e,t){const i=e instanceof xe.Reader?e:new xe.Reader(e);let n=void 0===t?i.len:i.pos+t;const s={trackSids:[],disabled:!1,quality:0,width:0,height:0,fps: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;case 7:s.fps=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,fps:isSet(e.fps)?Number(e.fps):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)),void 0!==e.fps&&(t.fps=Math.round(e.fps)),t},fromPartial(e){var t,i,n,s,o,a;const c={trackSids:[],disabled:!1,quality:0,width:0,height:0,fps:0};return c.trackSids=(null===(t=e.trackSids)||void 0===t?void 0:t.map((e=>e)))||[],c.disabled=null!==(i=e.disabled)&&void 0!==i&&i,c.quality=null!==(n=e.quality)&&void 0!==n?n:0,c.width=null!==(s=e.width)&&void 0!==s?s:0,c.height=null!==(o=e.height)&&void 0!==o?o:0,c.fps=null!==(a=e.fps)&&void 0!==a?a:0,c}};const Dt={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xe.Writer.create();return!0===e.canReconnect&&t.uint32(8).bool(e.canReconnect),0!==e.reason&&t.uint32(16).int32(e.reason),t},decode(e,t){const i=e instanceof xe.Reader?e:new xe.Reader(e);let n=void 0===t?i.len:i.pos+t;const s={canReconnect:!1,reason:0};for(;i.pos>>3){case 1:s.canReconnect=i.bool();break;case 2:s.reason=i.int32();break;default:i.skipType(7&e)}}return s},fromJSON:e=>({canReconnect:!!isSet(e.canReconnect)&&Boolean(e.canReconnect),reason:isSet(e.reason)?disconnectReasonFromJSON(e.reason):0}),toJSON(e){const t={};return void 0!==e.canReconnect&&(t.canReconnect=e.canReconnect),void 0!==e.reason&&(t.reason=function disconnectReasonToJSON(e){switch(e){case Ie.UNKNOWN_REASON:return"UNKNOWN_REASON";case Ie.CLIENT_INITIATED:return"CLIENT_INITIATED";case Ie.DUPLICATE_IDENTITY:return"DUPLICATE_IDENTITY";case Ie.SERVER_SHUTDOWN:return"SERVER_SHUTDOWN";case Ie.PARTICIPANT_REMOVED:return"PARTICIPANT_REMOVED";case Ie.ROOM_DELETED:return"ROOM_DELETED";case Ie.STATE_MISMATCH:return"STATE_MISMATCH";case Ie.JOIN_FAILURE:return"JOIN_FAILURE";case Ie.UNRECOGNIZED:default:return"UNRECOGNIZED"}}(e.reason)),t},fromPartial(e){var t,i;const n={canReconnect:!1,reason:0};return n.canReconnect=null!==(t=e.canReconnect)&&void 0!==t&&t,n.reason=null!==(i=e.reason)&&void 0!==i?i:0,n}};const _t={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xe.Writer.create();""!==e.trackSid&&t.uint32(10).string(e.trackSid);for(const i of e.layers)We.encode(i,t.uint32(18).fork()).ldelim();return t},decode(e,t){const i=e instanceof xe.Reader?e:new xe.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(We.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=>We.fromJSON(e))):[]}),toJSON(e){const t={};return void 0!==e.trackSid&&(t.trackSid=e.trackSid),e.layers?t.layers=e.layers.map((e=>e?We.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=>We.fromPartial(e))))||[],n}};const At={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xe.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 xe.Reader?e:new xe.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 Lt={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xe.Writer.create();for(const i of e.speakers)Qe.encode(i,t.uint32(10).fork()).ldelim();return t},decode(e,t){const i=e instanceof xe.Reader?e:new xe.Reader(e);let n=void 0===t?i.len:i.pos+t;const s={speakers:[]};for(;i.pos>>3==1)s.speakers.push(Qe.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=>Qe.fromJSON(e))):[]}),toJSON(e){const t={};return e.speakers?t.speakers=e.speakers.map((e=>e?Qe.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=>Qe.fromPartial(e))))||[],i}};const Ut={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xe.Writer.create();return void 0!==e.room&&$e.encode(e.room,t.uint32(10).fork()).ldelim(),t},decode(e,t){const i=e instanceof xe.Reader?e:new xe.Reader(e);let n=void 0===t?i.len:i.pos+t;const s={room:void 0};for(;i.pos>>3==1)s.room=$e.decode(i,i.uint32());else i.skipType(7&e)}return s},fromJSON:e=>({room:isSet(e.room)?$e.fromJSON(e.room):void 0}),toJSON(e){const t={};return void 0!==e.room&&(t.room=e.room?$e.toJSON(e.room):void 0),t},fromPartial(e){const t={room:void 0};return t.room=void 0!==e.room&&null!==e.room?$e.fromPartial(e.room):void 0,t}};const xt={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xe.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 xe.Reader?e:new xe.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 Oe.POOR:return"POOR";case Oe.GOOD:return"GOOD";case Oe.EXCELLENT:return"EXCELLENT";case Oe.UNRECOGNIZED:default:return"UNRECOGNIZED"}}(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 Mt={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xe.Writer.create();for(const i of e.updates)xt.encode(i,t.uint32(10).fork()).ldelim();return t},decode(e,t){const i=e instanceof xe.Reader?e:new xe.Reader(e);let n=void 0===t?i.len:i.pos+t;const s={updates:[]};for(;i.pos>>3==1)s.updates.push(xt.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=>xt.fromJSON(e))):[]}),toJSON(e){const t={};return e.updates?t.updates=e.updates.map((e=>e?xt.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=>xt.fromPartial(e))))||[],i}};const $t={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xe.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 xe.Reader?e:new xe.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 mt.ACTIVE:return"ACTIVE";case mt.PAUSED:return"PAUSED";case mt.UNRECOGNIZED:default:return"UNRECOGNIZED"}}(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 Bt={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xe.Writer.create();for(const i of e.streamStates)$t.encode(i,t.uint32(10).fork()).ldelim();return t},decode(e,t){const i=e instanceof xe.Reader?e:new xe.Reader(e);let n=void 0===t?i.len:i.pos+t;const s={streamStates:[]};for(;i.pos>>3==1)s.streamStates.push($t.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=>$t.fromJSON(e))):[]}),toJSON(e){const t={};return e.streamStates?t.streamStates=e.streamStates.map((e=>e?$t.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=>$t.fromPartial(e))))||[],i}};const Ft={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xe.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 xe.Reader?e:new xe.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 Jt={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xe.Writer.create();""!==e.codec&&t.uint32(10).string(e.codec);for(const i of e.qualities)Ft.encode(i,t.uint32(18).fork()).ldelim();return t},decode(e,t){const i=e instanceof xe.Reader?e:new xe.Reader(e);let n=void 0===t?i.len:i.pos+t;const s={codec:"",qualities:[]};for(;i.pos>>3){case 1:s.codec=i.string();break;case 2:s.qualities.push(Ft.decode(i,i.uint32()));break;default:i.skipType(7&e)}}return s},fromJSON:e=>({codec:isSet(e.codec)?String(e.codec):"",qualities:Array.isArray(null==e?void 0:e.qualities)?e.qualities.map((e=>Ft.fromJSON(e))):[]}),toJSON(e){const t={};return void 0!==e.codec&&(t.codec=e.codec),e.qualities?t.qualities=e.qualities.map((e=>e?Ft.toJSON(e):void 0)):t.qualities=[],t},fromPartial(e){var t,i;const n={codec:"",qualities:[]};return n.codec=null!==(t=e.codec)&&void 0!==t?t:"",n.qualities=(null===(i=e.qualities)||void 0===i?void 0:i.map((e=>Ft.fromPartial(e))))||[],n}};const Vt={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xe.Writer.create();""!==e.trackSid&&t.uint32(10).string(e.trackSid);for(const i of e.subscribedQualities)Ft.encode(i,t.uint32(18).fork()).ldelim();for(const i of e.subscribedCodecs)Jt.encode(i,t.uint32(26).fork()).ldelim();return t},decode(e,t){const i=e instanceof xe.Reader?e:new xe.Reader(e);let n=void 0===t?i.len:i.pos+t;const s={trackSid:"",subscribedQualities:[],subscribedCodecs:[]};for(;i.pos>>3){case 1:s.trackSid=i.string();break;case 2:s.subscribedQualities.push(Ft.decode(i,i.uint32()));break;case 3:s.subscribedCodecs.push(Jt.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=>Ft.fromJSON(e))):[],subscribedCodecs:Array.isArray(null==e?void 0:e.subscribedCodecs)?e.subscribedCodecs.map((e=>Jt.fromJSON(e))):[]}),toJSON(e){const t={};return void 0!==e.trackSid&&(t.trackSid=e.trackSid),e.subscribedQualities?t.subscribedQualities=e.subscribedQualities.map((e=>e?Ft.toJSON(e):void 0)):t.subscribedQualities=[],e.subscribedCodecs?t.subscribedCodecs=e.subscribedCodecs.map((e=>e?Jt.toJSON(e):void 0)):t.subscribedCodecs=[],t},fromPartial(e){var t,i,n;const s={trackSid:"",subscribedQualities:[],subscribedCodecs:[]};return s.trackSid=null!==(t=e.trackSid)&&void 0!==t?t:"",s.subscribedQualities=(null===(i=e.subscribedQualities)||void 0===i?void 0:i.map((e=>Ft.fromPartial(e))))||[],s.subscribedCodecs=(null===(n=e.subscribedCodecs)||void 0===n?void 0:n.map((e=>Jt.fromPartial(e))))||[],s}};const jt={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xe.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 xe.Reader?e:new xe.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 o={participantSid:"",allTracks:!1,trackSids:[],participantIdentity:""};return o.participantSid=null!==(t=e.participantSid)&&void 0!==t?t:"",o.allTracks=null!==(i=e.allTracks)&&void 0!==i&&i,o.trackSids=(null===(n=e.trackSids)||void 0===n?void 0:n.map((e=>e)))||[],o.participantIdentity=null!==(s=e.participantIdentity)&&void 0!==s?s:"",o}};const Wt={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xe.Writer.create();!0===e.allParticipants&&t.uint32(8).bool(e.allParticipants);for(const i of e.trackPermissions)jt.encode(i,t.uint32(18).fork()).ldelim();return t},decode(e,t){const i=e instanceof xe.Reader?e:new xe.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(jt.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=>jt.fromJSON(e))):[]}),toJSON(e){const t={};return void 0!==e.allParticipants&&(t.allParticipants=e.allParticipants),e.trackPermissions?t.trackPermissions=e.trackPermissions.map((e=>e?jt.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=>jt.fromPartial(e))))||[],n}};const qt={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xe.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 xe.Reader?e:new xe.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 Gt={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xe.Writer.create();void 0!==e.answer&&Rt.encode(e.answer,t.uint32(10).fork()).ldelim(),void 0!==e.subscription&&Nt.encode(e.subscription,t.uint32(18).fork()).ldelim();for(const i of e.publishTracks)Pt.encode(i,t.uint32(26).fork()).ldelim();for(const i of e.dataChannels)Qt.encode(i,t.uint32(34).fork()).ldelim();return void 0!==e.offer&&Rt.encode(e.offer,t.uint32(42).fork()).ldelim(),t},decode(e,t){const i=e instanceof xe.Reader?e:new xe.Reader(e);let n=void 0===t?i.len:i.pos+t;const s={answer:void 0,subscription:void 0,publishTracks:[],dataChannels:[],offer:void 0};for(;i.pos>>3){case 1:s.answer=Rt.decode(i,i.uint32());break;case 2:s.subscription=Nt.decode(i,i.uint32());break;case 3:s.publishTracks.push(Pt.decode(i,i.uint32()));break;case 4:s.dataChannels.push(Qt.decode(i,i.uint32()));break;case 5:s.offer=Rt.decode(i,i.uint32());break;default:i.skipType(7&e)}}return s},fromJSON:e=>({answer:isSet(e.answer)?Rt.fromJSON(e.answer):void 0,subscription:isSet(e.subscription)?Nt.fromJSON(e.subscription):void 0,publishTracks:Array.isArray(null==e?void 0:e.publishTracks)?e.publishTracks.map((e=>Pt.fromJSON(e))):[],dataChannels:Array.isArray(null==e?void 0:e.dataChannels)?e.dataChannels.map((e=>Qt.fromJSON(e))):[],offer:isSet(e.offer)?Rt.fromJSON(e.offer):void 0}),toJSON(e){const t={};return void 0!==e.answer&&(t.answer=e.answer?Rt.toJSON(e.answer):void 0),void 0!==e.subscription&&(t.subscription=e.subscription?Nt.toJSON(e.subscription):void 0),e.publishTracks?t.publishTracks=e.publishTracks.map((e=>e?Pt.toJSON(e):void 0)):t.publishTracks=[],e.dataChannels?t.dataChannels=e.dataChannels.map((e=>e?Qt.toJSON(e):void 0)):t.dataChannels=[],void 0!==e.offer&&(t.offer=e.offer?Rt.toJSON(e.offer):void 0),t},fromPartial(e){var t,i;const n={answer:void 0,subscription:void 0,publishTracks:[],dataChannels:[],offer:void 0};return n.answer=void 0!==e.answer&&null!==e.answer?Rt.fromPartial(e.answer):void 0,n.subscription=void 0!==e.subscription&&null!==e.subscription?Nt.fromPartial(e.subscription):void 0,n.publishTracks=(null===(t=e.publishTracks)||void 0===t?void 0:t.map((e=>Pt.fromPartial(e))))||[],n.dataChannels=(null===(i=e.dataChannels)||void 0===i?void 0:i.map((e=>Qt.fromPartial(e))))||[],n.offer=void 0!==e.offer&&null!==e.offer?Rt.fromPartial(e.offer):void 0,n}};const Qt={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xe.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 xe.Reader?e:new xe.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 zt={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xe.Writer.create();var i,n,s,o,a;return"speakerUpdate"===(null===(i=e.scenario)||void 0===i?void 0:i.$case)&&t.uint32(8).int32(e.scenario.speakerUpdate),"nodeFailure"===(null===(n=e.scenario)||void 0===n?void 0:n.$case)&&t.uint32(16).bool(e.scenario.nodeFailure),"migration"===(null===(s=e.scenario)||void 0===s?void 0:s.$case)&&t.uint32(24).bool(e.scenario.migration),"serverLeave"===(null===(o=e.scenario)||void 0===o?void 0:o.$case)&&t.uint32(32).bool(e.scenario.serverLeave),"switchCandidateProtocol"===(null===(a=e.scenario)||void 0===a?void 0:a.$case)&&t.uint32(40).int32(e.scenario.switchCandidateProtocol),t},decode(e,t){const i=e instanceof xe.Reader?e:new xe.Reader(e);let n=void 0===t?i.len:i.pos+t;const s={scenario:void 0};for(;i.pos>>3){case 1:s.scenario={$case:"speakerUpdate",speakerUpdate:i.int32()};break;case 2:s.scenario={$case:"nodeFailure",nodeFailure:i.bool()};break;case 3:s.scenario={$case:"migration",migration:i.bool()};break;case 4:s.scenario={$case:"serverLeave",serverLeave:i.bool()};break;case 5:s.scenario={$case:"switchCandidateProtocol",switchCandidateProtocol:i.int32()};break;default:i.skipType(7&e)}}return s},fromJSON:e=>({scenario:isSet(e.speakerUpdate)?{$case:"speakerUpdate",speakerUpdate:Number(e.speakerUpdate)}:isSet(e.nodeFailure)?{$case:"nodeFailure",nodeFailure:Boolean(e.nodeFailure)}:isSet(e.migration)?{$case:"migration",migration:Boolean(e.migration)}:isSet(e.serverLeave)?{$case:"serverLeave",serverLeave:Boolean(e.serverLeave)}:isSet(e.switchCandidateProtocol)?{$case:"switchCandidateProtocol",switchCandidateProtocol:candidateProtocolFromJSON(e.switchCandidateProtocol)}:void 0}),toJSON(e){var t,i,n,s,o,a,c,u,l,h,p;const m={};return"speakerUpdate"===(null===(t=e.scenario)||void 0===t?void 0:t.$case)&&(m.speakerUpdate=Math.round(null===(i=e.scenario)||void 0===i?void 0:i.speakerUpdate)),"nodeFailure"===(null===(n=e.scenario)||void 0===n?void 0:n.$case)&&(m.nodeFailure=null===(s=e.scenario)||void 0===s?void 0:s.nodeFailure),"migration"===(null===(o=e.scenario)||void 0===o?void 0:o.$case)&&(m.migration=null===(a=e.scenario)||void 0===a?void 0:a.migration),"serverLeave"===(null===(c=e.scenario)||void 0===c?void 0:c.$case)&&(m.serverLeave=null===(u=e.scenario)||void 0===u?void 0:u.serverLeave),"switchCandidateProtocol"===(null===(l=e.scenario)||void 0===l?void 0:l.$case)&&(m.switchCandidateProtocol=void 0!==(null===(h=e.scenario)||void 0===h?void 0:h.switchCandidateProtocol)?function candidateProtocolToJSON(e){switch(e){case ft.UDP:return"UDP";case ft.TCP:return"TCP";case ft.TLS:return"TLS";case ft.UNRECOGNIZED:default:return"UNRECOGNIZED"}}(null===(p=e.scenario)||void 0===p?void 0:p.switchCandidateProtocol):void 0),m},fromPartial(e){var t,i,n,s,o,a,c,u,l,h,p,m,v,g,b;const S={scenario:void 0};return"speakerUpdate"===(null===(t=e.scenario)||void 0===t?void 0:t.$case)&&void 0!==(null===(i=e.scenario)||void 0===i?void 0:i.speakerUpdate)&&null!==(null===(n=e.scenario)||void 0===n?void 0:n.speakerUpdate)&&(S.scenario={$case:"speakerUpdate",speakerUpdate:e.scenario.speakerUpdate}),"nodeFailure"===(null===(s=e.scenario)||void 0===s?void 0:s.$case)&&void 0!==(null===(o=e.scenario)||void 0===o?void 0:o.nodeFailure)&&null!==(null===(a=e.scenario)||void 0===a?void 0:a.nodeFailure)&&(S.scenario={$case:"nodeFailure",nodeFailure:e.scenario.nodeFailure}),"migration"===(null===(c=e.scenario)||void 0===c?void 0:c.$case)&&void 0!==(null===(u=e.scenario)||void 0===u?void 0:u.migration)&&null!==(null===(l=e.scenario)||void 0===l?void 0:l.migration)&&(S.scenario={$case:"migration",migration:e.scenario.migration}),"serverLeave"===(null===(h=e.scenario)||void 0===h?void 0:h.$case)&&void 0!==(null===(p=e.scenario)||void 0===p?void 0:p.serverLeave)&&null!==(null===(m=e.scenario)||void 0===m?void 0:m.serverLeave)&&(S.scenario={$case:"serverLeave",serverLeave:e.scenario.serverLeave}),"switchCandidateProtocol"===(null===(v=e.scenario)||void 0===v?void 0:v.$case)&&void 0!==(null===(g=e.scenario)||void 0===g?void 0:g.switchCandidateProtocol)&&null!==(null===(b=e.scenario)||void 0===b?void 0:b.switchCandidateProtocol)&&(S.scenario={$case:"switchCandidateProtocol",switchCandidateProtocol:e.scenario.switchCandidateProtocol}),S}};var Ht,Zt,Kt,Yt,Xt,ei=(()=>{if(void 0!==ei)return ei;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 longToNumber(e){if(e.gt(Number.MAX_SAFE_INTEGER))throw new ei.Error("Value is larger than Number.MAX_SAFE_INTEGER");return e.toNumber()}function isSet(e){return null!=e}xe.util.Long!==p&&(xe.util.Long=p,xe.configure());class LivekitError extends Error{constructor(e,t){super(t||"an error has occured"),this.code=e}}class ConnectionError extends LivekitError{constructor(e,t,i){super(1,e),this.status=i,this.reason=t}}class TrackInvalidError extends LivekitError{constructor(e){super(20,null!=e?e:"track is invalid")}}class UnsupportedServer extends LivekitError{constructor(e){super(10,null!=e?e:"unsupported server")}}class UnexpectedConnectionState extends LivekitError{constructor(e){super(12,null!=e?e:"unexpected connection state")}}class NegotiationError extends LivekitError{constructor(e){super(13,null!=e?e:"unable to negotiate")}}class PublishDataError extends LivekitError{constructor(e){super(13,null!=e?e:"unable to publish data")}}!function(e){e.PermissionDenied="PermissionDenied",e.NotFound="NotFound",e.DeviceInUse="DeviceInUse",e.Other="Other"}(Ht||(Ht={})),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}}(Ht||(Ht={})),function(e){e.Connected="connected",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.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",e.AudioPlaybackStatusChanged="audioPlaybackChanged",e.MediaDevicesError="mediaDevicesError",e.ParticipantPermissionsChanged="participantPermissionsChanged",e.SignalConnected="signalConnected",e.RecordingStatusChanged="recordingStatusChanged"}(Zt||(Zt={})),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.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",e.MediaDevicesError="mediaDevicesError",e.ParticipantPermissionsChanged="participantPermissionsChanged"}(Kt||(Kt={})),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.Closing="closing",e.MediaTrackAdded="mediaTrackAdded",e.ActiveSpeakersUpdate="activeSpeakersUpdate",e.DataPacketReceived="dataPacketReceived"}(Yt||(Yt={})),function(e){e.Message="message",e.Muted="muted",e.Unmuted="unmuted",e.Restarted="restarted",e.Ended="ended",e.Subscribed="subscribed",e.Unsubscribed="unsubscribed",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",e.SubscriptionPermissionChanged="subscriptionPermissionChanged",e.SubscriptionStatusChanged="subscriptionStatusChanged"}(Xt||(Xt={}));const ti=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)}var ii={};!function(e,t){!function(i,n){var s="function",o="undefined",a="object",c="string",u="model",l="name",h="type",p="vendor",m="version",v="architecture",g="console",b="mobile",S="tablet",k="smarttv",y="wearable",w="embedded",T="Amazon",C="Apple",P="ASUS",E="BlackBerry",R="Firefox",O="Google",N="Huawei",I="LG",D="Microsoft",_="Motorola",A="Opera",L="Samsung",U="Sharp",x="Sony",M="Xiaomi",$="Zebra",B="Facebook",enumerize=function(e){for(var t={},i=0;i0?2===u.length?typeof u[1]==s?this[u[0]]=u[1].call(this,h):this[u[0]]=u[1]:3===u.length?typeof u[1]!==s||u[1].exec&&u[1].test?this[u[0]]=h?h.replace(u[1],u[2]):n:this[u[0]]=h?u[1].call(this,h,u[2]):n:4===u.length&&(this[u[0]]=h?u[3].call(this,h.replace(u[1],u[2])):n):this[u]=h||n;p+=2}},strMapper=function(e,t){for(var i in t)if(typeof t[i]===a&&t[i].length>0){for(var s=0;s350?trim(e,350):e,this},this.setUA(s),this};UAParser.VERSION="1.0.33",UAParser.BROWSER=enumerize([l,m,"major"]),UAParser.CPU=enumerize([v]),UAParser.DEVICE=enumerize([u,p,h,g,b,k,S,y,w]),UAParser.ENGINE=UAParser.OS=enumerize([l,m]),e.exports&&(t=e.exports=UAParser),t.UAParser=UAParser;var V=typeof i!==o&&(i.jQuery||i.Zepto);if(V&&!V.ua){var j=new UAParser;V.ua=j.getResult(),V.ua.get=function(){return j.getUA()},V.ua.set=function(e){j.setUA(e);var t=j.getResult();for(var i in t)V.ua[i]=t[i]}}}("object"==typeof window?window:s)}({get exports(){return ii},set exports(e){ii=e}},ii);var ni=ii;const ri="1.6.3",si=8;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({latencyHint:"interactive"})}async function sleep(e){return new Promise((t=>setTimeout(t,e)))}function supportsTransceiver(){return"addTransceiver"in RTCPeerConnection.prototype}function supportsAddTrack(){return"addTrack"in RTCPeerConnection.prototype}function supportsAdaptiveStream(){return void 0!==typeof ResizeObserver&&void 0!==typeof IntersectionObserver}function supportsDynacast(){return supportsTransceiver()}function supportsAV1(){const e=RTCRtpReceiver.getCapabilities("video");let t=!1,i=!1;if(e){for(const i of e.codecs)if("video/AV1"===i.mimeType){t=!0;break}for(const t of e.headerExtensions)if("https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension"===t.uri){i=!0;break}}return t&&i}function supportsSetSinkId(e){return!!document&&(e||(e=document.createElement("audio")),"setSinkId"in e)}const oi={Chrome:"100",Chromium:"100",Safari:"15",Firefox:"100",Edge:"100",Brave:"1.40"};function supportsSetCodecPreferences(e){if(!isWeb())return!1;if(!("setCodecPreferences"in e))return!1;const t=ni();if(!t.browser.name||!t.browser.version)return!1;const i=oi[t.browser.name];return!!i&&function compareVersions(e,t){const i=e.split("."),n=t.split("."),s=Math.min(e.length,t.length);for(let e=0;es)return 1;if(t=0}function isBrowserSupported(){return supportsTransceiver()||supportsAddTrack()}function isFireFox(){return!!isWeb()&&-1!==navigator.userAgent.indexOf("Firefox")}function isSafari(){return!!isWeb()&&/^((?!chrome|android).)*safari/i.test(navigator.userAgent)}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 ai=null;const getResizeObserver=()=>(ai||(ai=new ResizeObserver(roDispatchCallback)),ai);let ci=null;const getIntersectionObserver=()=>(ci||(ci=new IntersectionObserver(ioDispatchCallback,{root:document,rootMargin:"0px"})),ci);let di,ui;function getEmptyVideoStreamTrack(){return di||(di=createDummyVideoStreamTrack()),di}function createDummyVideoStreamTrack(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:16,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:16,i=arguments.length>2&&void 0!==arguments[2]&&arguments[2],n=arguments.length>3&&void 0!==arguments[3]&&arguments[3];const s=document.createElement("canvas");s.width=e,s.height=t;const o=s.getContext("2d");null==o||o.fillRect(0,0,s.width,s.height),n&&o&&(o.beginPath(),o.arc(e/2,t/2,50,0,2*Math.PI,!0),o.closePath(),o.fillStyle="grey",o.fill());const a=s.captureStream(),[c]=a.getTracks();if(!c)throw Error("Could not get empty media stream video track");return c.enabled=i,c}function getEmptyAudioStreamTrack(){if(!ui){const e=new AudioContext,t=e.createOscillator(),i=e.createMediaStreamDestination();if(t.connect(i),t.start(),[ui]=i.stream.getAudioTracks(),!ui)throw Error("Could not get empty media stream audio track");ui.enabled=!1}return ui}class Future{constructor(e,t){this.onFinally=t,this.promise=new Promise((async(t,i)=>{this.resolve=t,this.reject=i,e&&await e(t,i)})).finally((()=>{var e;return null===(e=this.onFinally)||void 0===e?void 0:e.call(this)}))}}function createAudioAnalyser(e,t){const i=_objectSpread2({cloneTrack:!1,fftSize:2048,smoothingTimeConstant:.8,minDecibels:-100,maxDecibels:-80},t),n=getNewAudioContext();if(!n)throw new Error("Audio Context not supported on this browser");const s=i.cloneTrack?e.mediaStreamTrack.clone():e.mediaStreamTrack,o=n.createMediaStreamSource(new MediaStream([s])),a=n.createAnalyser();a.minDecibels=i.minDecibels,a.maxDecibels=i.maxDecibels,a.fftSize=i.fftSize,a.smoothingTimeConstant=i.smoothingTimeConstant,o.connect(a);const c=new Uint8Array(a.frequencyBinCount);return{calculateVolume:()=>{a.getByteFrequencyData(c);let e=0;for(const t of c)e+=Math.pow(t/255,2);return Math.sqrt(e/c.length)},analyser:a,cleanup:()=>{n.close(),i.cloneTrack&&s.stop()}}}class Mutex{constructor(){this._locking=Promise.resolve(),this._locks=0}isLocked(){return this._locks>0}lock(){let e;this._locks+=1;const t=new Promise((t=>e=()=>{this._locks-=1,t()})),i=this._locking.then((()=>e));return this._locking=this._locking.then((()=>t)),i}}class Queue{constructor(e,t){this.maxConcurrent=e||1,this.minCycle=t||0,this.queueRunning=[],this.queueWaiting={},this.lastRun=0}dequeue(e){const t=this.queueRunning,i=t.findIndex((t=>t.hash===e));if(-1==i)throw"queue desync";const n=t[i];return t.splice(i,1),n}getFirstWaiting(){for(let e of Object.keys(this.queueWaiting).sort(((e,t)=>e-t)))if(void 0!==this.queueWaiting[e]&&this.queueWaiting[e].length>0)return this.queueWaiting[e]}end(e){this.dequeue(e).resolve();const t=this.getFirstWaiting();if(void 0!==t){t.shift().resolve()}}async wait(e,t){const i=void 0===t?0:t;let n={hash:e,priority:i};for(null==this.queueWaiting[i]&&(this.queueWaiting[i]=[]),this.queueRunning.length>=this.maxConcurrent&&(n.promise=new Promise((e=>{n.resolve=e})),this.queueWaiting[i].push(n),await n.promise),this.queueRunning.push(n),n.promise=new Promise((e=>{n.resolve=e}));Date.now()-this.lastRunsetTimeout(e,this.minCycle-Date.now()+this.lastRun)));this.lastRun=Date.now()}run(e,t){const i=void 0===t?0:t,n=Symbol();return this.wait(n,i).then((()=>e())).finally((()=>{this.end(n)}))}stat(){return{running:this.queueRunning.length,waiting:Object.keys(this.queueWaiting).reduce(((e,t)=>e+this.queueWaiting[t].length),0),last:this.lastRun}}async flush(){for(;this.stat().waiting>0;)for(let e of Object.keys(this.queueWaiting).sort(((e,t)=>t-e))){const t=this.queueWaiting[e];void 0!==t&&t.length>0&&await t[t.length-1].promise}for(;this.queueRunning.length>0;)await Promise.allSettled(this.queueRunning.map((e=>e.promise)))}}const li="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];var i;if((null===(i=DeviceManager.userMediaPromiseMap)||void 0===i?void 0:i.size)>0){h.debug("awaiting getUserMedia promise");try{e?await DeviceManager.userMediaPromiseMap.get(e):await Promise.all(DeviceManager.userMediaPromiseMap.values())}catch(e){h.warn("error waiting for media permissons")}}let n=await navigator.mediaDevices.enumerateDevices();if(t&&e&&(!DeviceManager.userMediaPromiseMap.get(e)||!isSafari())){if(0===n.length||n.some((t=>{const i=""===t.label,n=!e||t.kind===e;return i&&n}))){const t={video:"audioinput"!==e&&"audiooutput"!==e,audio:"videoinput"!==e},i=await navigator.mediaDevices.getUserMedia(t);n=await navigator.mediaDevices.enumerateDevices(),i.getTracks().forEach((e=>{e.stop()}))}}return e&&(n=n.filter((t=>t.kind===e))),n}async normalizeDeviceId(e,t,i){if(t!==li)return t;const n=(await this.getDevices(e)).find((e=>e.groupId===i&&e.deviceId!==li));return null==n?void 0:n.deviceId}}DeviceManager.mediaDeviceKinds=["audioinput","audiooutput","videoinput"],DeviceManager.userMediaPromiseMap=new Map;var hi,pi={},mi={get exports(){return pi},set exports(e){pi=e}},fi="object"==typeof Reflect?Reflect:null,vi=fi&&"function"==typeof fi.apply?fi.apply:function ReflectApply(e,t,i){return Function.prototype.apply.call(e,t,i)};hi=fi&&"function"==typeof fi.ownKeys?fi.ownKeys:Object.getOwnPropertySymbols?function ReflectOwnKeys(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function ReflectOwnKeys(e){return Object.getOwnPropertyNames(e)};var gi=Number.isNaN||function NumberIsNaN(e){return e!=e};function EventEmitter(){EventEmitter.init.call(this)}mi.exports=EventEmitter,pi.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 bi=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,o,a;if(checkListener(i),void 0===(o=e._events)?(o=e._events=Object.create(null),e._eventsCount=0):(void 0!==o.newListener&&(e.emit("newListener",t,i.listener?i.listener:i),o=e._events),a=o[t]),void 0===a)a=o[t]=i,++e._eventsCount;else if("function"==typeof a?a=o[t]=n?[i,a]:[a,i]:n?a.unshift(i):a.push(i),(s=_getMaxListeners(e))>0&&a.length>s&&!a.warned){a.warned=!0;var c=new Error("Possible EventEmitter memory leak detected. "+a.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");c.name="MaxListenersExceededWarning",c.emitter=e,c.type=t,c.count=a.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&&(o=t[0]),o instanceof Error)throw o;var a=new Error("Unhandled error."+(o?" ("+o.message+")":""));throw a.context=o,a}var c=s[e];if(void 0===c)return!1;if("function"==typeof c)vi(c,this,t);else{var u=c.length,l=arrayClone(c,u);for(i=0;i=0;o--)if(i[o]===t||i[o].listener===t){a=i[o].listener,s=o;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?hi(this._events):[]};const Si=[];class Track extends pi.EventEmitter{constructor(e,t){super(),this.attachedElements=[],this.isMuted=!1,this.streamState=Track.StreamState.Active,this._currentBitrate=0,this.appVisibilityChangedListener=()=>{this.backgroundTimeout&&clearTimeout(this.backgroundTimeout),"hidden"===document.visibilityState?this.backgroundTimeout=setTimeout((()=>this.handleAppVisibilityChanged()),5e3):this.handleAppVisibilityChanged()},this.setMaxListeners(100),this.kind=t,this._mediaStreamTrack=e,this._mediaStreamID=e.id,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}get mediaStreamID(){return this._mediaStreamID}attach(e){let t="audio";this.kind===Track.Kind.Video&&(t="video"),e||("audio"===t&&(Si.forEach((t=>{null!==t.parentElement||e||(e=t)})),e&&Si.splice(Si.indexOf(e),1)),e||(e=document.createElement(t))),this.attachedElements.includes(e)||this.attachedElements.push(e),attachToElement(this._mediaStreamTrack,e);const i=e.srcObject.getTracks();return i.some((e=>"audio"===e.kind))&&e.play().then((()=>{this.emit(Xt.AudioPlaybackStarted)})).catch((t=>{this.emit(Xt.AudioPlaybackFailed,t),e&&i.some((e=>"video"===e.kind))&&"NotAllowedError"===t.name&&(e.muted=!0,e.play().catch((()=>{})))})),this.emit(Xt.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(Xt.ElementDetached,e)),e}const t=[];return this.attachedElements.forEach((e=>{detachTrack(this._mediaStreamTrack,e),t.push(e),this.recycleElement(e),this.emit(Xt.ElementDetached,e)})),this.attachedElements=[],t}stop(){this.stopMonitor(),this._mediaStreamTrack.stop(),isWeb()&&document.removeEventListener("visibilitychange",this.appVisibilityChangedListener)}enable(){this._mediaStreamTrack.enabled=!0}disable(){this._mediaStreamTrack.enabled=!1}stopMonitor(){this.monitorInterval&&clearInterval(this.monitorInterval)}recycleElement(e){if(e instanceof HTMLAudioElement){let t=!0;e.pause(),Si.forEach((e=>{e.parentElement||(t=!1)})),t&&Si.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.autoplay=!0,t.muted=0===i.getAudioTracks().length,t instanceof HTMLVideoElement&&(t.playsInline=!0),t.srcObject!==i&&(t.srcObject=i,(isSafari()||isFireFox())&&t instanceof HTMLVideoElement&&setTimeout((()=>{t.srcObject=i,t.play().catch((()=>{}))}),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 Pe.AUDIO;case t.Video:return Pe.VIDEO;default:return Pe.UNRECOGNIZED}},e.kindFromProto=function kindFromProto(e){switch(e){case Pe.AUDIO:return t.Audio;case Pe.VIDEO:return t.Video;default:return t.Unknown}},e.sourceToProto=function sourceToProto(e){switch(e){case i.Camera:return Ee.CAMERA;case i.Microphone:return Ee.MICROPHONE;case i.ScreenShare:return Ee.SCREEN_SHARE;case i.ScreenShareAudio:return Ee.SCREEN_SHARE_AUDIO;default:return Ee.UNRECOGNIZED}},e.sourceFromProto=function sourceFromProto(e){switch(e){case Ee.CAMERA:return i.Camera;case Ee.MICROPHONE:return i.Microphone;case Ee.SCREEN_SHARE:return i.ScreenShare;case Ee.SCREEN_SHARE_AUDIO:return i.ScreenShareAudio;default:return i.Unknown}},e.streamStateFromProto=function streamStateFromProto(e){switch(e){case mt.ACTIVE:return n.Active;case mt.PAUSED:return n.Paused;default:return n.Unknown}}}(Track||(Track={}));class LocalTrack extends Track{constructor(e,t,i){let n=arguments.length>3&&void 0!==arguments[3]&&arguments[3];super(e,t),this._isUpstreamPaused=!1,this.handleEnded=()=>{this.isInBackground&&(this.reacquireTrack=!0),this.emit(Xt.Ended,this)},this._mediaStreamTrack.addEventListener("ended",this.handleEnded),this.constraints=null!=i?i:e.getConstraints(),this.reacquireTrack=!1,this.providedByUser=n,this.muteQueue=new Queue}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}get isUserProvided(){return this.providedByUser}async waitForDimensions(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:2e3;if(this.kind===Track.Kind.Audio)throw new Error("cannot get dimensions for audio tracks");const t=Date.now();for(;Date.now()-t1&&void 0!==arguments[1])||arguments[1];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.providedByUser||this._mediaStreamTrack.stop(),e.addEventListener("ended",this.handleEnded),h.debug("replace MediaStreamTrack"),this.sender&&await this.sender.replaceTrack(e),this._mediaStreamTrack=e,this._mediaStreamTrack.enabled=!this.isMuted,await this.resumeUpstream(),this.attachedElements.forEach((t=>{attachToElement(e,t)})),this.mediaStream=new MediaStream([e]),this.providedByUser=t,this}async restart(e){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"),this.sender&&await this.sender.replaceTrack(n),this._mediaStreamTrack=n,await this.resumeUpstream(),this.attachedElements.forEach((e=>{attachToElement(n,e)})),this.mediaStream=i,this.constraints=e,this.emit(Xt.Restarted,this),this}setTrackMuted(e){h.debug("setting ".concat(this.kind," track ").concat(e?"muted":"unmuted")),this.isMuted===e&&this._mediaStreamTrack.enabled!==e||(this.isMuted=e,this._mediaStreamTrack.enabled=!e,this.emit(e?Xt.Muted:Xt.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||this.isUserProvided||this.isMuted||(h.debug("track needs to be reaquired, restarting ".concat(this.source)),await this.restart(),this.reacquireTrack=!1))}async pauseUpstream(){this.muteQueue.run((async()=>{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(Xt.UpstreamPaused,this);const e=this.kind===Track.Kind.Audio?getEmptyAudioStreamTrack():getEmptyVideoStreamTrack();await this.sender.replaceTrack(e)}))}async resumeUpstream(){this.muteQueue.run((async()=>{!1!==this._isUpstreamPaused&&(this.sender?(this._isUpstreamPaused=!1,this.emit(Xt.UpstreamResumed,this),await this.sender.replaceTrack(this._mediaStreamTrack)):h.warn("unable to resume upstream for an unpublished track"))}))}}class LocalAudioTrack extends LocalTrack{constructor(e,t){let i=!(arguments.length>2&&void 0!==arguments[2])||arguments[2];super(e,Track.Kind.Audio,t,i),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},this.checkForSilence()}async setDeviceId(e){this.constraints.deviceId!==e&&(this.constraints.deviceId=e,this.isMuted||await this.restartTrack())}async mute(){return await this.muteQueue.run((async()=>{this.source===Track.Source.Microphone&&this.stopOnMute&&!this.isUserProvided&&(h.debug("stopping mic track"),this._mediaStreamTrack.stop()),await super.mute()})),this}async unmute(){return await this.muteQueue.run((async()=>{this.source===Track.Source.Microphone&&this.stopOnMute&&!this.isUserProvided&&(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(){isWeb()&&(this.monitorInterval||(this.monitorInterval=setInterval((()=>{this.monitorSender()}),ti)))}async getSenderStats(){var e;if(!(null===(e=this.sender)||void 0===e?void 0:e.getStats))return;let t;return(await this.sender.getStats()).forEach((e=>{"outbound-rtp"===e.type&&(t={type:"audio",streamId:e.id,packetsSent:e.packetsSent,packetsLost:e.packetsLost,bytesSent:e.bytesSent,timestamp:e.timestamp,roundTripTime:e.roundTripTime,jitter:e.jitter})})),t}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,o=new Uint8Array(s);i.createMediaStreamSource(new MediaStream([e.mediaStreamTrack])).connect(n),await sleep(t),n.getByteTimeDomainData(o);const a=o.some((e=>128!==e&&0!==e));return i.close(),!a}return!1}(this);e&&(this.isMuted||h.warn("silence detected on local audio track"),this.emit(Xt.AudioSilenceDetected))}}class LocalVideoTrack extends LocalTrack{constructor(e,t){let i=!(arguments.length>2&&void 0!==arguments[2])||arguments[2];super(e,Track.Kind.Video,t,i),this.simulcastCodecs=new Map,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}}get isSimulcast(){return!!(this.sender&&this.sender.getParameters().encodings.length>1)}startMonitor(e){var t;if(this.signalClient=e,!isWeb())return;const i=null===(t=this.sender)||void 0===t?void 0:t.getParameters();i&&(this.encodings=i.encodings),this.monitorInterval||(this.monitorInterval=setInterval((()=>{this.monitorSender()}),ti))}stop(){this._mediaStreamTrack.getConstraints(),this.simulcastCodecs.forEach((e=>{e.mediaStreamTrack.stop()})),super.stop()}async mute(){return await this.muteQueue.run((async()=>{this.source!==Track.Source.Camera||this.isUserProvided||(h.debug("stopping camera track"),this._mediaStreamTrack.stop()),await super.mute()})),this}async unmute(){return await this.muteQueue.run((async()=>{this.source!==Track.Source.Camera||this.isUserProvided||(h.debug("reacquiring camera track"),await this.restartTrack()),await super.unmute()})),this}async getSenderStats(){var e;if(!(null===(e=this.sender)||void 0===e?void 0:e.getStats))return[];const t=[],i=await this.sender.getStats();return i.forEach((e=>{var n;if("outbound-rtp"===e.type){const s={type:"video",streamId:e.id,frameHeight:e.frameHeight,frameWidth:e.frameWidth,firCount:e.firCount,pliCount:e.pliCount,nackCount:e.nackCount,packetsSent:e.packetsSent,bytesSent:e.bytesSent,framesSent:e.framesSent,timestamp:e.timestamp,rid:null!==(n=e.rid)&&void 0!==n?n:e.id,retransmittedPacketsSent:e.retransmittedPacketsSent,qualityLimitationReason:e.qualityLimitationReason,qualityLimitationResolutionChanges:e.qualityLimitationResolutionChanges},o=i.get(e.remoteId);o&&(s.jitter=o.jitter,s.packetsLost=o.packetsLost,s.roundTripTime=o.roundTripTime),t.push(s)}})),t}setPublishingQuality(e){const t=[];for(let i=Re.LOW;i<=Re.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)}addSimulcastTrack(e,t){if(this.simulcastCodecs.has(e))throw new Error("".concat(e," already added"));const i={codec:e,mediaStreamTrack:this.mediaStreamTrack.clone(),sender:void 0,encodings:t};return this.simulcastCodecs.set(e,i),i}setSimulcastTrackSender(e,t){const i=this.simulcastCodecs.get(e);i&&(i.sender=t,setTimeout((()=>{this.subscribedCodecs&&this.setPublishingCodecs(this.subscribedCodecs)}),5e3))}async setPublishingCodecs(e){if(h.debug("setting publishing codecs",{codecs:e,currentCodec:this.codec}),!this.codec&&e.length>0)return await this.setPublishingLayers(e[0].qualities),[];this.subscribedCodecs=e;const t=[];var i,n=!1,s=!1;try{for(var o,a=_asyncIterator(e);n=!(o=await a.next()).done;n=!1){const e=o.value;if(this.codec&&this.codec!==e.codec){const i=this.simulcastCodecs.get(e.codec);if(h.debug("try setPublishingCodec for ".concat(e.codec),i),i&&i.sender)i.encodings&&(h.debug("try setPublishingLayersForSender ".concat(e.codec)),await setPublishingLayersForSender(i.sender,i.encodings,e.qualities));else for(const i of e.qualities)if(i.enabled){t.push(e.codec);break}}else await this.setPublishingLayers(e.qualities)}}catch(e){s=!0,i=e}finally{try{n&&null!=a.return&&await a.return()}finally{if(s)throw i}}return t}async setPublishingLayers(e){h.debug("setting publishing layers",e),this.sender&&this.encodings&&await setPublishingLayersForSender(this.sender,this.encodings,e)}async handleAppVisibilityChanged(){await super.handleAppVisibilityChanged(),isMobile()&&this.isInBackground&&this.source===Track.Source.Camera&&(this._mediaStreamTrack.enabled=!1)}}async function setPublishingLayersForSender(e,t,i){h.debug("setPublishingLayersForSender",{sender:e,qualities:i,senderEncodings:t});const n=e.getParameters(),{encodings:s}=n;if(!s)return;if(s.length!==t.length)return void h.warn("cannot set publishing layers, encodings mismatch");let o=!1;s.forEach(((e,n)=>{var s;let a=null!==(s=e.rid)&&void 0!==s?s:"";""===a&&(a="q");const c=videoQualityForRid(a),u=i.find((e=>e.quality===c));u&&e.active!==u.enabled&&(o=!0,e.active=u.enabled,h.debug("setting layer ".concat(u.quality," to ").concat(e.active?"enabled":"disabled")),isFireFox()&&(u.enabled?(e.scaleResolutionDownBy=t[n].scaleResolutionDownBy,e.maxBitrate=t[n].maxBitrate,e.maxFrameRate=t[n].maxFrameRate):(e.scaleResolutionDownBy=4,e.maxBitrate=10,e.maxFrameRate=2)))})),o&&(n.encodings=s,await e.setParameters(n))}function videoQualityForRid(e){switch(e){case"f":return Re.HIGH;case"h":return Re.MEDIUM;case"q":return Re.LOW;default:return Re.UNRECOGNIZED}}function videoLayersFromEncodings(e,t,i){return i?i.map((n=>{var s,o,a;const c=null!==(s=n.scaleResolutionDownBy)&&void 0!==s?s:1;let u=videoQualityForRid(null!==(o=n.rid)&&void 0!==o?o:"");return u===Re.UNRECOGNIZED&&1===i.length&&(u=Re.HIGH),{quality:u,width:e/c,height:t/c,bitrate:null!==(a=n.maxBitrate)&&void 0!==a?a:0,ssrc:0}})):[{quality:Re.HIGH,width:e,height:t,bitrate:0,ssrc:0}]}class RemoteTrack extends Track{constructor(e,t,i,n){super(e,i),this.sid=t,this.receiver=n}setMuted(e){this.isMuted!==e&&(this.isMuted=e,this._mediaStreamTrack.enabled=!e,this.emit(e?Xt.Muted:Xt.Unmuted,this))}setMediaStream(e){this.mediaStream=e,e.onremovetrack=()=>{this.receiver=void 0,this._currentBitrate=0,this.emit(Xt.Ended,this)}}start(){this.startMonitor(),super.enable()}stop(){this.stopMonitor(),super.disable()}startMonitor(){this.monitorInterval||(this.monitorInterval=setInterval((()=>this.monitorReceiver()),ti))}}class RemoteAudioTrack extends RemoteTrack{constructor(e,t,i,n,s){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},this.audioContext=n,this.webAudioPluginNodes=[],s&&(this.sinkId=s.deviceId)}setVolume(e){var t;for(const i of this.attachedElements)this.audioContext?null===(t=this.gainNode)||void 0===t||t.gain.setTargetAtTime(e,0,.1):i.volume=e;this.elementVolume=e}getVolume(){if(this.elementVolume)return this.elementVolume;let e=0;return this.attachedElements.forEach((t=>{t.volume>e&&(e=t.volume)})),e}async setSinkId(e){this.sinkId=e,await Promise.all(this.attachedElements.map((t=>{if(supportsSetSinkId(t))return t.setSinkId(e)})))}attach(e){const t=0===this.attachedElements.length;return e?super.attach(e):e=super.attach(),this.elementVolume&&(e.volume=this.elementVolume),this.sinkId&&supportsSetSinkId(e)&&e.setSinkId(this.sinkId),this.audioContext&&t&&(h.debug("using audio context mapping"),this.connectWebAudio(this.audioContext,e),e.volume=0,e.muted=!0),e}detach(e){let t;return e?(t=super.detach(e),this.audioContext&&(this.attachedElements.length>0?this.connectWebAudio(this.audioContext,this.attachedElements[0]):this.disconnectWebAudio())):(t=super.detach(),this.disconnectWebAudio()),t}setAudioContext(e){this.audioContext=e,e&&this.attachedElements.length>0?this.connectWebAudio(e,this.attachedElements[0]):e||this.disconnectWebAudio()}setWebAudioPlugins(e){this.webAudioPluginNodes=e,this.attachedElements.length>0&&this.audioContext&&this.connectWebAudio(this.audioContext,this.attachedElements[0])}connectWebAudio(e,t){this.disconnectWebAudio(),this.sourceNode=e.createMediaStreamSource(t.srcObject);let i=this.sourceNode;this.webAudioPluginNodes.forEach((e=>{i.connect(e),i=e})),this.gainNode=e.createGain(),i.connect(this.gainNode),this.gainNode.connect(e.destination),this.elementVolume&&this.gainNode.gain.setTargetAtTime(this.elementVolume,0,.1),"running"!==e.state&&e.resume().then((()=>{"running"!==e.state&&this.emit(Xt.AudioPlaybackFailed,new Error("Audio Context couldn't be started automatically"))})).catch((e=>{this.emit(Xt.AudioPlaybackFailed,e)}))}disconnectWebAudio(){var e,t;null===(e=this.gainNode)||void 0===e||e.disconnect(),null===(t=this.sourceNode)||void 0===t||t.disconnect(),this.gainNode=void 0,this.sourceNode=void 0}async getReceiverStats(){if(!this.receiver||!this.receiver.getStats)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,o;void 0===t&&(t=50),void 0===i&&(i={});var a=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=a&&void 0===o;if(void 0!==o&&clearTimeout(o),o=setTimeout((function(){if(o=void 0,l=Date.now(),!a){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!==o&&clearTimeout(o),h.forEach((function(t){return(0,t.reject)(e)})),h=[]},d}class CriticalTimers{}CriticalTimers.setTimeout=function(){return setTimeout(...arguments)},CriticalTimers.setInterval=function(){return setInterval(...arguments)},CriticalTimers.clearTimeout=function(){return clearTimeout(...arguments)},CriticalTimers.clearInterval=function(){return clearInterval(...arguments)};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},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){if(e?super.attach(e):e=super.attach(),this.adaptiveStreamSettings&&void 0===this.elementInfos.find((t=>t.element===e))){const t=new HTMLElementInfo(e);this.observeElementInfo(t)}return this.hasUsedAttach=!0,e}observeElementInfo(e){this.adaptiveStreamSettings&&void 0===this.elementInfos.find((t=>t===e))?(e.handleResize=()=>{this.debouncedHandleResize()},e.handleVisibilityChanged=()=>{this.updateVisibility()},this.elementInfos.push(e),e.observe(),this.debouncedHandleResize(),this.updateVisibility()):h.warn("visibility resize observer not triggered")}stopObservingElementInfo(e){if(!this.isAdaptiveStream)return void h.warn("stopObservingElementInfo ignored");const t=this.elementInfos.filter((t=>t===e));for(const e of t)e.stopObserving();this.elementInfos=this.elementInfos.filter((t=>t!==e)),this.updateVisibility()}detach(e){let t=[];if(e)return this.stopObservingElement(e),super.detach(e);t=super.detach();for(const e of t)this.stopObservingElement(e);return t}getDecoderImplementation(){var e;return null===(e=this.prevStats)||void 0===e?void 0:e.decoderImplementation}async getReceiverStats(){if(!this.receiver||!this.receiver.getStats)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,decoderImplementation:t.decoderImplementation})})),e}stopObservingElement(e){const t=this.elementInfos.filter((t=>t.element===e));for(const e of t)e.stopObserving();this.elementInfos=this.elementInfos.filter((t=>t.element!==e))}async handleAppVisibilityChanged(){await super.handleAppVisibilityChanged(),this.isAdaptiveStream&&this.updateVisibility()}updateVisibility(){var e,t;const i=this.elementInfos.reduce(((e,t)=>Math.max(e,t.visibilityChangedAt||0)),0),n=!(null!==(t=null===(e=this.adaptiveStreamSettings)||void 0===e?void 0:e.pauseVideoInBackground)&&void 0!==t&&!t)&&this.isInBackground,s=this.elementInfos.some((e=>e.visible))&&!n;this.lastVisible!==s&&(!s&&Date.now()-i<100?CriticalTimers.setTimeout((()=>{this.updateVisibility()}),100):(this.lastVisible=s,this.emit(Xt.VisibilityChanged,s,this)))}updateDimensions(){var e,t,i,n;let s=0,o=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,a="screen"===n?window.devicePixelRatio:n,c=i.width()*a,u=i.height()*a;c+u>s+o&&(s=c,o=u)}(null===(i=this.lastDimensions)||void 0===i?void 0:i.width)===s&&(null===(n=this.lastDimensions)||void 0===n?void 0:n.height)===o||(this.lastDimensions={width:s,height:o},this.emit(Xt.VideoDimensionsChanged,this.lastDimensions,this))}}class HTMLElementInfo{constructor(e,t){this.onVisibilityChanged=e=>{var t;const{target:i,isIntersecting:n}=e;i===this.element&&(this.visible=n,this.visibilityChangedAt=Date.now(),null===(t=this.handleVisibilityChanged)||void 0===t||t.call(this))},this.element=e,this.visible=null!=t?t:function isElementInViewport(e){let t=e.offsetTop,i=e.offsetLeft;const n=e.offsetWidth,s=e.offsetHeight,{hidden:o}=e,{opacity:a,display:c}=getComputedStyle(e);for(;e.offsetParent;)t+=(e=e.offsetParent).offsetTop,i+=e.offsetLeft;return twindow.pageYOffset&&i+n>window.pageXOffset&&!o&&(""===a||parseFloat(a)>0)&&"none"!==c}(e),this.visibilityChangedAt=0}width(){return this.element.clientWidth}height(){return this.element.clientHeight}observe(){this.element.handleResize=()=>{var e;null===(e=this.handleResize)||void 0===e||e.call(this)},this.element.handleVisibilityChanged=this.onVisibilityChanged,getIntersectionObserver().observe(this.element),getResizeObserver().observe(this.element)}stopObserving(){var e,t;null===(e=getIntersectionObserver())||void 0===e||e.unobserve(this.element),null===(t=getResizeObserver())||void 0===t||t.unobserve(this.element)}}class TrackPublication extends pi.EventEmitter{constructor(e,t,i){super(),this.metadataMuted=!1,this.handleMuted=()=>{this.emit(Xt.Muted)},this.handleUnmuted=()=>{this.emit(Xt.Unmuted)},this.setMaxListeners(100),this.kind=e,this.trackSid=t,this.trackName=i,this.source=Track.Source.Unknown}setTrack(e){this.track&&(this.track.off(Xt.Muted,this.handleMuted),this.track.off(Xt.Unmuted,this.handleUnmuted)),this.track=e,e&&(e.on(Xt.Muted,this.handleMuted),e.on(Xt.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,h.trace("update publication info",{info:e})}}!function(e){var t,i;(t=e.SubscriptionStatus||(e.SubscriptionStatus={})).Desired="desired",t.Subscribed="subscribed",t.Unsubscribed="unsubscribed",(i=e.PermissionStatus||(e.PermissionStatus={})).Allowed="allowed",i.NotAllowed="not_allowed"}(TrackPublication||(TrackPublication={}));class LocalTrackPublication extends TrackPublication{get isUpstreamPaused(){var e;return null===(e=this.track)||void 0===e?void 0:e.isUpstreamPaused}constructor(e,t,i){super(e,t.sid,t.name),this.track=void 0,this.handleTrackEnded=()=>{this.emit(Xt.Ended)},this.updateInfo(t),this.setTrack(i)}setTrack(e){this.track&&this.track.off(Xt.Ended,this.handleTrackEnded),super.setTrack(e),e&&e.on(Xt.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}}}const ki=["vp8","h264"];function isBackupCodec(e){return!!ki.find((t=>t===e))}var yi;!function(e){e.telephone={maxBitrate:12e3},e.speech={maxBitrate:2e4},e.music={maxBitrate:32e3},e.musicStereo={maxBitrate:48e3},e.musicHighQuality={maxBitrate:64e3},e.musicHighQualityStereo={maxBitrate:96e3}}(yi||(yi={}));const wi={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)},Ti={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)},Ci={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 Pi;!function(e){e.Excellent="excellent",e.Good="good",e.Poor="poor",e.Unknown="unknown"}(Pi||(Pi={}));class Participant extends pi.EventEmitter{constructor(e,t,i,n){super(),this.audioLevel=0,this.isSpeaking=!1,this._connectionQuality=Pi.Unknown,this.setMaxListeners(100),this.sid=e,this.identity=t,this.name=i,this.metadata=n,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}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 isLocal(){return!1}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,h.trace("update participant info",{info:e})}setMetadata(e){const t=this.metadata!==e,i=this.metadata;this.metadata=e,t&&this.emit(Kt.ParticipantMetadataChanged,i)}setPermissions(e){var t,i,n,s,o;const a=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===(o=this.permissions)||void 0===o?void 0:o.recorder);return this.permissions=e,a}setIsSpeaking(e){e!==this.isSpeaking&&(this.isSpeaking=e,e&&(this.lastSpokeAt=new Date),this.emit(Kt.IsSpeakingChanged,e))}setConnectionQuality(e){const t=this._connectionQuality;this._connectionQuality=function qualityFromProto(e){switch(e){case Oe.EXCELLENT:return Pi.Excellent;case Oe.GOOD:return Pi.Good;case Oe.POOR:return Pi.Poor;default:return Pi.Unknown}}(e),t!==this._connectionQuality&&this.emit(Kt.ConnectionQualityChanged,this._connectionQuality)}addTrackPublication(e){e.on(Xt.Muted,(()=>{this.emit(Kt.TrackMuted,e)})),e.on(Xt.Unmuted,(()=>{this.emit(Kt.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,!1);case"video":return new LocalVideoTrack(e,t,!1);default:throw new TrackInvalidError("unsupported track type: ".concat(e.kind))}}const Ei=Object.values(wi),Ri=Object.values(Ti),Oi=Object.values(Ci),Ni=[wi.h180,wi.h360],Ii=[Ti.h180,Ti.h360],Di=["q","h","f"];function computeVideoEncodings(e,t,i,n){var s,o;let a=null==n?void 0:n.videoEncoding;e&&(a=null==n?void 0:n.screenShareEncoding);const c=null==n?void 0:n.simulcast,u=null==n?void 0:n.scalabilityMode,l=null==n?void 0:n.videoCodec;if(!a&&!c&&!u||!t||!i)return[{}];a||(a=function determineAppropriateEncoding(e,t,i,n){const s=function presetsForResolution(e,t,i){if(e)return Oi;const n=t>i?t/i:i/t;if(Math.abs(n-16/9)=a)break}if(n&&"av1"===n)o.maxBitrate=.7*o.maxBitrate;return o}(e,t,i,l),h.debug("using video encoding",a));const p=new VideoPreset(t,i,a.maxBitrate,a.maxFramerate);if(u&&"av1"===l){h.debug("using svc with scalabilityMode ".concat(u));const e=[];if("L3T3"===u){for(let t=0;t<3;t+=1)e.push({rid:Di[2-t],scaleResolutionDownBy:2**t,maxBitrate:a.maxBitrate/3**t,maxFramerate:p.encoding.maxFramerate,scalabilityMode:"L3T3"});return h.debug("encodings",e),e}throw new Error("unsupported scalabilityMode: ".concat(u))}if(!c)return[a];let m,v=[];if(v=e?null!==(s=sortPresets(null==n?void 0:n.screenShareSimulcastLayers))&&void 0!==s?s:defaultSimulcastLayers(e,p):null!==(o=sortPresets(null==n?void 0:n.videoSimulcastLayers))&&void 0!==o?o:defaultSimulcastLayers(e,p),v.length>0){const e=v[0];v.length>1&&([,m]=v);const n=Math.max(t,i);if(n>=960&&m)return encodingsFromPresets(t,i,[e,m,p]);if(n>=480)return encodingsFromPresets(t,i,[e,p])}return encodingsFromPresets(t,i,[p])}function computeTrackBackupEncodings(e,t,i){var n,s,o,a;if(!i.backupCodec||i.backupCodec.codec===i.videoCodec)return;t!==i.backupCodec.codec&&h.warn("requested a different codec than specified as backup",{serverRequested:t,backup:i.backupCodec.codec}),i.videoCodec=t,i.videoEncoding=i.backupCodec.encoding;const c=e.mediaStreamTrack.getSettings(),u=null!==(n=c.width)&&void 0!==n?n:null===(s=e.dimensions)||void 0===s?void 0:s.width,l=null!==(o=c.height)&&void 0!==o?o:null===(a=e.dimensions)||void 0===a?void 0:a.height;return computeVideoEncodings(e.source===Track.Source.ScreenShare,u,l,i)}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,o=n>s?n/s:s/n;return Math.abs(o-16/9){if(s>=Di.length)return;const o=Math.min(e,t),a=Di[s];n.push({rid:a,scaleResolutionDownBy:Math.max(1,o/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(e,t,i,n){super(e,t,i),this.track=void 0,this.allowed=!0,this.disabled=!1,this.currentVideoQuality=Re.HIGH,this.handleEnded=e=>{this.setTrack(void 0),this.emit(Xt.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()},this.subscribed=n}setSubscribed(e){const t=this.subscriptionStatus,i=this.permissionStatus;this.subscribed=e,e&&(this.allowed=!0);const n={trackSids:[this.trackSid],subscribe:this.subscribed,participantTracks:[{participantSid:"",trackSids:[this.trackSid]}]};this.emit(Xt.UpdateSubscription,n),this.emitSubscriptionUpdateIfChanged(t),this.emitPermissionUpdateIfChanged(i)}get subscriptionStatus(){return!1===this.subscribed?TrackPublication.SubscriptionStatus.Unsubscribed:super.isSubscribed?TrackPublication.SubscriptionStatus.Subscribed:TrackPublication.SubscriptionStatus.Desired}get permissionStatus(){return this.allowed?TrackPublication.PermissionStatus.Allowed:TrackPublication.PermissionStatus.NotAllowed}get isSubscribed(){return!1!==this.subscribed&&super.isSubscribed}get isDesired(){return!1!==this.subscribed}get isEnabled(){return!this.disabled}setEnabled(e){this.isManualOperationAllowed()&&this.disabled!==!e&&(this.disabled=!e,this.emitTrackUpdate())}setVideoQuality(e){this.isManualOperationAllowed()&&this.currentVideoQuality!==e&&(this.currentVideoQuality=e,this.videoDimensions=void 0,this.emitTrackUpdate())}setVideoDimensions(e){var t,i;this.isManualOperationAllowed()&&((null===(t=this.videoDimensions)||void 0===t?void 0:t.width)===e.width&&(null===(i=this.videoDimensions)||void 0===i?void 0:i.height)===e.height||(this.track instanceof RemoteVideoTrack&&(this.videoDimensions=e),this.currentVideoQuality=void 0,this.emitTrackUpdate()))}setVideoFPS(e){this.isManualOperationAllowed()&&this.track instanceof RemoteVideoTrack&&this.fps!==e&&(this.fps=e,this.emitTrackUpdate())}get videoQuality(){return this.currentVideoQuality}setTrack(e){const t=this.subscriptionStatus,i=this.permissionStatus,n=this.track;n!==e&&(n&&(n.off(Xt.VideoDimensionsChanged,this.handleVideoDimensionsChange),n.off(Xt.VisibilityChanged,this.handleVisibilityChange),n.off(Xt.Ended,this.handleEnded),n.detach(),this.emit(Xt.Unsubscribed,n)),super.setTrack(e),e&&(e.sid=this.trackSid,e.on(Xt.VideoDimensionsChanged,this.handleVideoDimensionsChange),e.on(Xt.VisibilityChanged,this.handleVisibilityChange),e.on(Xt.Ended,this.handleEnded),this.emit(Xt.Subscribed,e)),this.emitPermissionUpdateIfChanged(i),this.emitSubscriptionUpdateIfChanged(t))}setAllowed(e){const t=this.subscriptionStatus,i=this.permissionStatus;this.allowed=e,this.emitPermissionUpdateIfChanged(i),this.emitSubscriptionUpdateIfChanged(t)}updateInfo(e){var t;super.updateInfo(e),this.metadataMuted=e.muted,null===(t=this.track)||void 0===t||t.setMuted(e.muted)}emitSubscriptionUpdateIfChanged(e){const t=this.subscriptionStatus;e!==t&&this.emit(Xt.SubscriptionStatusChanged,t,e)}emitPermissionUpdateIfChanged(e){this.permissionStatus!==e&&this.emit(Xt.SubscriptionPermissionChanged,this.permissionStatus,e)}isManualOperationAllowed(){return this.isAdaptiveStream?(h.warn("adaptive stream is enabled, cannot change track settings",{trackSid:this.trackSid}),!1):!!this.isDesired||(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=It.fromPartial({trackSids:[this.trackSid],disabled:this.disabled,fps:this.fps});this.videoDimensions?(e.width=this.videoDimensions.width,e.height=this.videoDimensions.height):void 0!==this.currentVideoQuality?e.quality=this.currentVideoQuality:e.quality=Re.HIGH,this.emit(Xt.UpdateSettings,e)}}class RemoteParticipant extends Participant{static fromParticipantInfo(e,t){return new RemoteParticipant(e,t.sid,t.identity,t.name,t.metadata)}constructor(e,t,i,n,s){super(t,i||"",n,s),this.signalClient=e,this.tracks=new Map,this.audioTracks=new Map,this.videoTracks=new Map}addTrackPublication(e){super.addTrackPublication(e),e.on(Xt.UpdateSettings,(e=>{h.debug("send update settings",e),this.signalClient.sendUpdateTrackSettings(e)})),e.on(Xt.UpdateSubscription,(e=>{e.participantTracks.forEach((e=>{e.participantSid=this.sid})),this.signalClient.sendUpdateSubscription(e)})),e.on(Xt.SubscriptionPermissionChanged,(t=>{this.emit(Kt.TrackSubscriptionPermissionChanged,e,t)})),e.on(Xt.SubscriptionStatusChanged,(t=>{this.emit(Kt.TrackSubscriptionStatusChanged,e,t)})),e.on(Xt.Subscribed,(t=>{this.emit(Kt.TrackSubscribed,t,e)})),e.on(Xt.Unsubscribed,(t=>{this.emit(Kt.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,o){let a=this.getTrackPublication(t);if(a||t.startsWith("TR")||this.tracks.forEach((t=>{a||e.kind!==t.kind.toString()||(a=t)})),!a)return 0===o?(h.error("could not find published track",{participant:this.sid,trackSid:t}),void this.emit(Kt.TrackSubscriptionFailed,t)):(void 0===o&&(o=20),void setTimeout((()=>{this.addSubscribedMediaTrack(e,t,i,n,s,o-1)}),150));if("ended"===e.readyState)return h.error("unable to subscribe because MediaStreamTrack is ended. Do not call MediaStreamTrack.stop()",{participant:this.sid,trackSid:t}),void this.emit(Kt.TrackSubscriptionFailed,t);let c;return c="video"===e.kind?new RemoteVideoTrack(e,t,n,s):new RemoteAudioTrack(e,t,n,this.audioContext,this.audioOutput),c.source=a.source,c.isMuted=a.isMuted,c.setMediaStream(i),c.start(),a.setTrack(c),void 0!==this.volume&&c instanceof RemoteAudioTrack&&c.source===Track.Source.Microphone&&c.setVolume(this.volume),a}get hasMetadata(){return!!this.participantInfo}getTrackPublication(e){return this.tracks.get(e)}updateInfo(e){super.updateInfo(e);const t=new Map,i=new Map;e.tracks.forEach((n=>{var s;let o=this.getTrackPublication(n.sid);if(o)o.updateInfo(n);else{const t=Track.kindFromProto(n.type);if(!t)return;o=new RemoteTrackPublication(t,n.sid,n.name,null===(s=this.signalClient.connectOptions)||void 0===s?void 0:s.autoSubscribe),o.updateInfo(n),i.set(n.sid,o);const a=Array.from(this.tracks.values()).find((e=>e.source===(null==o?void 0:o.source)));a&&o.source!==Track.Source.Unknown&&h.warn("received a second track publication for ".concat(this.identity," with the same source: ").concat(o.source),{oldTrack:a,newTrack:o,participant:this,participantInfo:e}),this.addTrackPublication(o)}t.set(n.sid,o)})),this.tracks.forEach((e=>{t.has(e.trackSid)||(h.trace("detected removed track on remote participant, unpublishing",{publication:e,participantSid:this.sid}),this.unpublishTrack(e.trackSid,!0))})),i.forEach((e=>{this.emit(Kt.TrackPublished,e)}))}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;n&&(n.stop(),i.setTrack(void 0)),t&&this.emit(Kt.TrackUnpublished,i)}setAudioContext(e){this.audioContext=e,this.audioTracks.forEach((t=>t.track instanceof RemoteAudioTrack&&t.track.setAudioContext(e)))}async setAudioOutput(e){this.audioOutput=e;const t=[];this.audioTracks.forEach((i=>{var n;i.track instanceof RemoteAudioTrack&&t.push(i.track.setSinkId(null!==(n=e.deviceId)&&void 0!==n?n:"default"))})),await Promise.all(t)}emit(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),n=1;n{h.debug("updating track subscription permissions",{allParticipantsAllowed:this.allParticipantsAllowedToSubscribe,participantTrackPermissions:this.participantTrackPermissions}),this.engine.client.sendUpdateSubscriptionPermissions(this.allParticipantsAllowedToSubscribe,this.participantTrackPermissions.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))))},this.onTrackUnmuted=e=>{this.onTrackMuted(e,e.isUpstreamPaused)},this.onTrackMuted=(e,t)=>{void 0===t&&(t=!0),e.sid?this.engine.updateMuteStatus(e.sid,t):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=async e=>{var t,i;if(!(null===(t=this.roomOptions)||void 0===t?void 0:t.dynacast))return;const n=this.videoTracks.get(e.trackSid);if(n)if(e.subscribedCodecs.length>0){if(!n.videoTrack)return;const t=await n.videoTrack.setPublishingCodecs(e.subscribedCodecs);var s,o=!1,a=!1;try{for(var c,u=_asyncIterator(t);o=!(c=await u.next()).done;o=!1){const e=c.value;isBackupCodec(e)&&(h.debug("publish ".concat(e," for ").concat(n.videoTrack.sid)),await this.publishAdditionalCodecForTrack(n.videoTrack,e,n.options))}}catch(e){a=!0,s=e}finally{try{o&&null!=u.return&&await u.return()}finally{if(a)throw s}}}else e.subscribedQualities.length>0&&(null===(i=n.videoTrack)||void 0===i||i.setPublishingLayers(e.subscribedQualities));else 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.handleTrackEnded=async e=>{if(e.source===Track.Source.ScreenShare||e.source===Track.Source.ScreenShareAudio)h.debug("unpublishing local track due to TrackEnded",{track:e.sid}),this.unpublishTrack(e);else if(e.isUserProvided)await e.mute();else if(e instanceof LocalAudioTrack||e instanceof LocalVideoTrack)try{if(isWeb())try{const t=await(null===navigator||void 0===navigator?void 0:navigator.permissions.query({name:e.source===Track.Source.Camera?"camera":"microphone"}));if(t&&"denied"===t.state)throw h.warn("user has revoked access to ".concat(e.source)),t.onchange=()=>{"denied"!==t.state&&(e.restartTrack(),t.onchange=null)},new Error("GetUserMedia Permission denied")}catch(e){}h.debug("track ended, attempting to use a different device"),await e.restartTrack()}catch(t){h.warn("could not restart track, muting instead"),await e.mute()}},this.audioTracks=new Map,this.videoTracks=new Map,this.tracks=new Map,this.engine=i,this.roomOptions=n,this.setupEngine(i)}get lastCameraError(){return this.cameraError}get lastMicrophoneError(){return this.microphoneError}getTrack(e){const t=super.getTrack(e);if(t)return t}getTrackByName(e){const t=super.getTrackByName(e);if(t)return t}setupEngine(e){this.engine=e,this.engine.client.onRemoteMuteChanged=(e,t)=>{const i=this.tracks.get(e);i&&i.track&&(t?i.mute():i.unmute())},this.engine.client.onSubscribedQualityUpdate=this.handleSubscribedQualityUpdate,this.engine.client.onLocalTrackUnpublished=this.handleLocalTrackUnpublished,this.engine.on(Yt.Connected,this.updateTrackSubscriptionPermissions).on(Yt.Restarted,this.updateTrackSubscriptionPermissions).on(Yt.Resumed,this.updateTrackSubscriptionPermissions)}setCameraEnabled(e,t,i){return this.setTrackEnabled(Track.Source.Camera,e,t,i)}setMicrophoneEnabled(e,t,i){return this.setTrackEnabled(Track.Source.Microphone,e,t,i)}setScreenShareEnabled(e,t,i){return this.setTrackEnabled(Track.Source.ScreenShare,e,t,i)}setPermissions(e){const t=this.permissions,i=super.setPermissions(e);return i&&t&&this.emit(Kt.ParticipantPermissionsChanged,t),i}async setTrackEnabled(e,t,i,n){var s,o;h.debug("setTrackEnabled",{source:e,enabled:t});let a=this.getTrack(e);if(t)if(a)await a.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:null===(s=i)||void 0===s||s});break;case Track.Source.Microphone:t=await this.createTracks({audio:null===(o=i)||void 0===o||o});break;case Track.Source.ScreenShare:t=await this.createScreenTracks(_objectSpread2({},i));break;default:throw new TrackInvalidError(e)}const c=[];for(const e of t)h.info("publishing track",{localTrack:e}),c.push(this.publishTrack(e,n));const u=await Promise.all(c);[a]=u}catch(e){throw e instanceof Error&&!(e instanceof TrackInvalidError)&&this.emit(Kt.MediaDevicesError,e),e}finally{this.pendingPublishing.delete(e)}}else if(a&&a.track)if(e===Track.Source.ScreenShare){a=await this.unpublishTrack(a.track);const e=this.getTrack(Track.Source.ScreenShareAudio);e&&e.track&&this.unpublishTrack(e.track)}else await a.mute();return a}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 o;i?e.audio:e.video;const a=i?n.audio:n.video;"boolean"!=typeof a&&(o=a);const c=mediaTrackToLocalTrack(t,o);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=Ci.h1080fps15.resolution);let i=!0;e.resolution&&(i=isSafari()?{width:{max:e.resolution.width},height:{max:e.resolution.height},frameRate:e.resolution.frameRate}:{width:{ideal:e.resolution.width},height:{ideal:e.resolution.height},frameRate:e.resolution.frameRate});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 o=new LocalVideoTrack(s[0],void 0,!1);o.source=Track.Source.ScreenShare;const a=[o];if(n.getAudioTracks().length>0){const e=new LocalAudioTrack(n.getAudioTracks()[0],void 0,!1);e.source=Track.Source.ScreenShareAudio,a.push(e)}return a}async publishTrack(e,t){var i,n,s,o,a;if(e instanceof MediaStreamTrack)switch(e.kind){case"audio":e=new LocalAudioTrack(e,void 0,!0);break;case"video":e=new LocalVideoTrack(e,void 0,!0);break;default:throw new TrackInvalidError("unsupported MediaStreamTrack kind ".concat(e.kind))}const c=(null==t?void 0:t.forceStereo)||"channelCount"in e.mediaStreamTrack.getSettings()&&2===e.mediaStreamTrack.getSettings().channelCount||2===e.mediaStreamTrack.getConstraints().channelCount;c&&(t||(t={}),void 0===t.dtx&&h.info("Opus DTX will be disabled for stereo tracks by default. Enable them explicitly to make it work."),null!==(i=t.dtx)&&void 0!==i||(t.dtx=!1));const u=_objectSpread2(_objectSpread2({},this.roomOptions.publishDefaults),t);let l;if(this.tracks.forEach((t=>{t.track&&t.track===e&&(l=t)})),l)return l;u.source&&(e.source=u.source);const p=Array.from(this.tracks.values()).find((t=>e instanceof LocalTrack&&t.source===e.source));if(p&&e.source!==Track.Source.Unknown)try{throw Error("publishing a second track with the same source: ".concat(e.source))}catch(t){t instanceof Error&&h.warn(t.message,{oldTrack:p,newTrack:e,trace:t.stack})}u.stopMicTrackOnMute&&e instanceof LocalAudioTrack&&(e.stopOnMute=!0),e.source===Track.Source.ScreenShare&&isFireFox()&&(u.simulcast=!1),"av1"!==u.videoCodec||supportsAV1()||(u.videoCodec=void 0),e.on(Xt.Muted,this.onTrackMuted),e.on(Xt.Unmuted,this.onTrackUnmuted),e.on(Xt.Ended,this.handleTrackEnded),e.on(Xt.UpstreamPaused,this.onTrackUpstreamPaused),e.on(Xt.UpstreamResumed,this.onTrackUpstreamResumed);const m=kt.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=u.dtx)||void 0===n||n),stereo:c,disableRed:!(null===(s=u.red)||void 0===s||s)});let v,g;if(e.kind===Track.Kind.Video){let t={width:0,height:0};try{t=await e.waitForDimensions()}catch(e){h.error("could not determine track dimensions")}if(m.width=t.width,m.height=t.height,e instanceof LocalVideoTrack&&("av1"===(null==u?void 0:u.videoCodec)&&(u.scalabilityMode=null!==(o=u.scalabilityMode)&&void 0!==o?o:"L3T3"),u.videoCodec&&u.backupCodec&&u.videoCodec!==u.backupCodec.codec)){const t=_objectSpread2({},u);t.simulcast=!0,g=computeTrackBackupEncodings(e,u.backupCodec.codec,t),m.simulcastCodecs=[{codec:u.videoCodec,cid:e.mediaStreamTrack.id,enableSimulcastLayers:!0},{codec:u.backupCodec.codec,cid:"",enableSimulcastLayers:!0}]}v=computeVideoEncodings(e.source===Track.Source.ScreenShare,t.width,t.height,u),m.layers=videoLayersFromEncodings(m.width,m.height,null!=g?g:v)}else e.kind===Track.Kind.Audio&&u.audioBitrate&&(v=[{maxBitrate:u.audioBitrate}]);if(!this.engine||this.engine.isClosed)throw new UnexpectedConnectionState("cannot publish track when not connected");const b=await this.engine.addTrack(m),S=new LocalTrackPublication(e.kind,b,e);if(S.options=u,e.sid=b.sid,!this.engine.publisher)throw new UnexpectedConnectionState("publisher is closed");return h.debug("publishing ".concat(e.kind," with encodings"),{encodings:v,trackInfo:b}),e.sender=await this.engine.createSender(e,u,v),"av1"===e.codec&&v&&(null===(a=v[0])||void 0===a?void 0:a.maxBitrate)&&this.engine.publisher.setTrackCodecBitrate(m.cid,e.codec,v[0].maxBitrate/1e3),this.engine.negotiate(),e instanceof LocalVideoTrack?e.startMonitor(this.engine.client):e instanceof LocalAudioTrack&&e.startMonitor(),this.addTrackPublication(S),this.emit(Kt.LocalTrackPublished,S),S}get isLocal(){return!0}async publishAdditionalCodecForTrack(e,t,i){var n;let s;if(this.tracks.forEach((t=>{t.track&&t.track===e&&(s=t)})),!s)throw new TrackInvalidError("track is not published");if(!(e instanceof LocalVideoTrack))throw new TrackInvalidError("track is not a video track");const o=_objectSpread2(_objectSpread2({},null===(n=this.roomOptions)||void 0===n?void 0:n.publishDefaults),i),a=computeTrackBackupEncodings(e,t,o);if(!a)return void h.info("backup codec has been disabled, ignoring request to add additional codec for track");const c=e.addSimulcastTrack(t,a),u=kt.fromPartial({cid:c.mediaStreamTrack.id,type:Track.kindToProto(e.kind),muted:e.isMuted,source:Track.sourceToProto(e.source),sid:e.sid,simulcastCodecs:[{codec:o.videoCodec,cid:c.mediaStreamTrack.id,enableSimulcastLayers:o.simulcast}]});if(u.layers=videoLayersFromEncodings(u.width,u.height,a),!this.engine||this.engine.isClosed)throw new UnexpectedConnectionState("cannot publish track when not connected");const l=await this.engine.addTrack(u);await this.engine.createSimulcastSender(e,c,o,a),this.engine.negotiate(),h.debug("published ".concat(t," for track ").concat(e.sid),{encodings:a,trackInfo:l})}async unpublishTrack(e,t){var i,n;const s=this.getPublicationForTrack(e);if(h.debug("unpublishing track",{track:e,method:"unpublishTrack"}),s&&s.track){if((e=s.track).off(Xt.Muted,this.onTrackMuted),e.off(Xt.Unmuted,this.onTrackUnmuted),e.off(Xt.Ended,this.handleTrackEnded),e.off(Xt.UpstreamPaused,this.onTrackUpstreamPaused),e.off(Xt.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(),this.engine.publisher&&"closed"!==this.engine.publisher.pc.connectionState&&e.sender)try{if(this.engine.removeTrack(e.sender),e instanceof LocalVideoTrack){for(const[,t]of e.simulcastCodecs)t.sender&&(this.engine.removeTrack(t.sender),t.sender=void 0);e.simulcastCodecs.clear()}}catch(e){h.warn("failed to unpublish track",{error:e,method:"unpublishTrack"})}finally{await this.engine.negotiate()}switch(e.sender=void 0,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(Kt.LocalTrackUnpublished,s),s.setTrack(void 0),s}h.warn("track was not unpublished because no publication was found",{track:e,method:"unpublishTrack"})}async unpublishTracks(e){return(await Promise.all(e.map((e=>this.unpublishTrack(e))))).filter((e=>e instanceof LocalTrackPublication))}async republishAllTracks(e){const t=[];this.tracks.forEach((i=>{i.track&&(e&&(i.options=_objectSpread2(_objectSpread2({},i.options),e)),t.push(i))})),await Promise.all(t.map((async e=>{const t=e.track;await this.unpublishTrack(t,!1),await this.publishTrack(t,e.options)})))}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,value:{$case:"user",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.participantTrackPermissions=t,this.allParticipantsAllowedToSubscribe=e,this.engine.client.isConnected&&this.updateTrackSubscriptionPermissions()}updateInfo(e){super.updateInfo(e),e.tracks.forEach((e=>{var t,i;const n=this.tracks.get(e.sid);if(n){const s=n.isMuted||null!==(i=null===(t=n.track)||void 0===t?void 0:t.isUpstreamPaused)&&void 0!==i&&i;s!==e.muted&&(h.debug("updating server mute state after reconcile",{sid:e.sid,muted:s}),this.engine.client.sendMuteTrack(e.sid,s))}}))}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}publishedTracksInfo(){const e=[];return this.tracks.forEach((t=>{void 0!==t.track&&e.push({cid:t.track.mediaStreamID,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(Ae.LOSSY),pt.PUBLISHER),getInfo(this.engine.dataChannelForKind(Ae.RELIABLE),pt.PUBLISHER),getInfo(this.engine.dataChannelForKind(Ae.LOSSY,!0),pt.SUBSCRIBER),getInfo(this.engine.dataChannelForKind(Ae.RELIABLE,!0),pt.SUBSCRIBER),e}}const _i=["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,this.queuedRequests=[],this.closingLock=new Mutex}async join(e,t,i,n){this.isConnected=!1,this.options=i;return await this.connect(e,t,i,n)}async reconnect(e,t,i){if(!this.options)return void h.warn("attempted to reconnect without signal options being set, ignoring");this.isReconnecting=!0,this.clearPingInterval();return await this.connect(e,t,_objectSpread2(_objectSpread2({},this.options),{},{reconnect:!0,sid:i}))}connect(e,t,i,n){this.connectOptions=i,e.startsWith("http")&&(e=e.replace("http","ws")),e=e.replace(/\/$/,""),e+="/rtc";const s=function createConnectionParams(e,t,i){var n;const s=new URLSearchParams;s.set("access_token",e),i.reconnect&&(s.set("reconnect","1"),i.sid&&s.set("sid",i.sid));s.set("auto_subscribe",i.autoSubscribe?"1":"0"),s.set("sdk","js"),s.set("version",t.version),s.set("protocol",t.protocol.toString()),t.deviceModel&&s.set("device_model",t.deviceModel);t.os&&s.set("os",t.os);t.osVersion&&s.set("os_version",t.osVersion);t.browser&&s.set("browser",t.browser);t.browserVersion&&s.set("browser_version",t.browserVersion);void 0!==i.publishOnly&&s.set("publish",i.publishOnly);i.adaptiveStream&&s.set("adaptive_stream","1");(null===(n=navigator.connection)||void 0===n?void 0:n.type)&&s.set("network",navigator.connection.type);return"?".concat(s.toString())}(t,function getClientInfo(){return Ke.fromPartial({sdk:Ue.JS,protocol:si,version:ri})}(),i);return new Promise((async(t,o)=>{const abortHandler=async()=>{await this.close(),o(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&&await this.close(),this.ws=new WebSocket(e+s),this.ws.binaryType="arraybuffer",this.ws.onerror=async t=>{if(this.isConnected)this.handleWSError(t);else try{const t=await fetch("http".concat(e.substring(2),"/validate").concat(s));if(t.ok)o(new ConnectionError("Internal error",2,t.status));else{const e=await t.text();o(new ConnectionError(e,0,t.status))}}catch(e){o(new ConnectionError("server was not reachable",1))}},this.ws.onmessage=async e=>{var s,a,c,u;let l;if("string"==typeof e.data){const t=JSON.parse(e.data);l=bt.fromJSON(t)}else{if(!(e.data instanceof ArrayBuffer))return void h.error("could not decode websocket message: ".concat(typeof e.data));l=bt.decode(new Uint8Array(e.data))}if(!this.isConnected){let e=!1;if("join"===(null===(s=l.message)||void 0===s?void 0:s.$case)?(this.isConnected=!0,null==n||n.removeEventListener("abort",abortHandler),this.pingTimeoutDuration=l.message.join.pingTimeout,this.pingIntervalDuration=l.message.join.pingInterval,this.pingTimeoutDuration&&this.pingTimeoutDuration>0&&(h.debug("ping config",{timeout:this.pingTimeoutDuration,interval:this.pingIntervalDuration}),this.startPingInterval()),t(l.message.join)):i.reconnect?(this.isConnected=!0,null==n||n.removeEventListener("abort",abortHandler),this.startPingInterval(),"reconnect"===(null===(a=l.message)||void 0===a?void 0:a.$case)?t(null===(c=l.message)||void 0===c?void 0:c.reconnect):(t(),e=!0)):i.reconnect||o(new ConnectionError("did not receive join response, got ".concat(null===(u=l.message)||void 0===u?void 0:u.$case," instead"))),!e)return}this.signalLatency&&await sleep(this.signalLatency),this.handleSignalResponse(l)},this.ws.onclose=e=>{this.isConnected&&(h.debug("websocket connection closed: ".concat(e.reason)),this.isConnected=!1,this.onClose&&this.onClose(e.reason),this.ws=void 0)}}))}async close(){const e=await this.closingLock.lock();try{if(this.isConnected=!1,this.ws){this.ws.onclose=null,this.ws.onmessage=null,this.ws.onopen=null;const e=new Promise((e=>{this.ws?this.ws.onclose=e:e(!0)}));this.ws.close(),await Promise.race([e,sleep(250)])}this.ws=void 0,this.clearPingInterval()}finally{e()}}sendOffer(e){h.debug("sending offer",e),this.sendRequest({$case:"offer",offer:toProtoSessionDescription(e)})}sendAnswer(e){h.debug("sending answer"),this.sendRequest({$case:"answer",answer:toProtoSessionDescription(e)})}sendIceCandidate(e,t){h.trace("sending ice candidate",e),this.sendRequest({$case:"trickle",trickle:{candidateInit:JSON.stringify(e),target:t}})}sendMuteTrack(e,t){this.sendRequest({$case:"mute",mute:{sid:e,muted:t}})}sendAddTrack(e){this.sendRequest({$case:"addTrack",addTrack:kt.fromPartial(e)})}sendUpdateTrackSettings(e){this.sendRequest({$case:"trackSetting",trackSetting:e})}sendUpdateSubscription(e){this.sendRequest({$case:"subscription",subscription:e})}sendSyncState(e){this.sendRequest({$case:"syncState",syncState:e})}sendUpdateVideoLayers(e,t){this.sendRequest({$case:"updateLayers",updateLayers:{trackSid:e,layers:t}})}sendUpdateSubscriptionPermissions(e,t){this.sendRequest({$case:"subscriptionPermission",subscriptionPermission:{allParticipants:e,trackPermissions:t}})}sendSimulateScenario(e){this.sendRequest({$case:"simulate",simulate:e})}sendPing(){this.sendRequest({$case:"ping",ping:Date.now()})}async sendLeave(){await this.sendRequest({$case:"leave",leave:{canReconnect:!1,reason:Ie.CLIENT_INITIATED}})}async sendRequest(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];const i=!t&&!function canPassThroughQueue(e){const t=_i.includes(e.$case);return h.trace("request allowed to bypass queue:",{canPass:t,req:e}),t}(e);if(i&&this.isReconnecting)return void this.queuedRequests.push((async()=>{await this.sendRequest(e,!0)}));if(t||await this.requestQueue.flush(),this.signalLatency&&await sleep(this.signalLatency),!this.ws||this.ws.readyState!==this.ws.OPEN)return void h.error("cannot send signal request before connected, type: ".concat(null==e?void 0:e.$case));const n={message:e};try{this.useJSON?this.ws.send(JSON.stringify(gt.toJSON(n))):this.ws.send(gt.encode(n).finish())}catch(e){h.error("error sending signal message",{error:e})}}handleSignalResponse(e){var t,i;const n=e.message;if("answer"===n.$case){const e=fromProtoSessionDescription(n.answer);this.onAnswer&&this.onAnswer(e)}else if("offer"===n.$case){const e=fromProtoSessionDescription(n.offer);this.onOffer&&this.onOffer(e)}else if("trickle"===n.$case){const e=JSON.parse(n.trickle.candidateInit);this.onTrickle&&this.onTrickle(e,n.trickle.target)}else"update"===n.$case?this.onParticipantUpdate&&this.onParticipantUpdate(null!==(t=n.update.participants)&&void 0!==t?t:[]):"trackPublished"===n.$case?this.onLocalTrackPublished&&this.onLocalTrackPublished(n.trackPublished):"speakersChanged"===n.$case?this.onSpeakersChanged&&this.onSpeakersChanged(null!==(i=n.speakersChanged.speakers)&&void 0!==i?i:[]):"leave"===n.$case?this.onLeave&&this.onLeave(n.leave):"mute"===n.$case?this.onRemoteMuteChanged&&this.onRemoteMuteChanged(n.mute.sid,n.mute.muted):"roomUpdate"===n.$case?this.onRoomUpdate&&n.roomUpdate.room&&this.onRoomUpdate(n.roomUpdate.room):"connectionQuality"===n.$case?this.onConnectionQuality&&this.onConnectionQuality(n.connectionQuality):"streamStateUpdate"===n.$case?this.onStreamStateUpdate&&this.onStreamStateUpdate(n.streamStateUpdate):"subscribedQualityUpdate"===n.$case?this.onSubscribedQualityUpdate&&this.onSubscribedQualityUpdate(n.subscribedQualityUpdate):"subscriptionPermissionUpdate"===n.$case?this.onSubscriptionPermissionUpdate&&this.onSubscriptionPermissionUpdate(n.subscriptionPermissionUpdate):"refreshToken"===n.$case?this.onTokenRefresh&&this.onTokenRefresh(n.refreshToken):"trackUnpublished"===n.$case?this.onLocalTrackUnpublished&&this.onLocalTrackUnpublished(n.trackUnpublished):"pong"===n.$case?this.resetPingTimeout():h.debug("unsupported message",n)}setReconnected(){for(;this.queuedRequests.length>0;){const e=this.queuedRequests.shift();e&&this.requestQueue.run(e)}this.isReconnecting=!1}handleWSError(e){h.error("websocket error",e)}resetPingTimeout(){this.clearPingTimeout(),this.pingTimeoutDuration?this.pingTimeout=CriticalTimers.setTimeout((()=>{h.warn("ping timeout triggered. last pong received at: ".concat(new Date(Date.now()-1e3*this.pingTimeoutDuration).toUTCString())),this.onClose&&this.onClose("ping timeout")}),1e3*this.pingTimeoutDuration):h.warn("ping timeout duration not set")}clearPingTimeout(){this.pingTimeout&&CriticalTimers.clearTimeout(this.pingTimeout)}startPingInterval(){this.clearPingInterval(),this.resetPingTimeout(),this.pingIntervalDuration?(h.debug("start ping interval"),this.pingInterval=CriticalTimers.setInterval((()=>{this.sendPing()}),1e3*this.pingIntervalDuration)):h.warn("ping interval duration not set")}clearPingInterval(){h.debug("clearing ping interval"),this.clearPingTimeout(),this.pingInterval&&CriticalTimers.clearInterval(this.pingInterval)}}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}}const Ai={audioBitrate:yi.music.maxBitrate,dtx:!0,red:!0,forceStereo:!1,simulcast:!0,screenShareEncoding:Ci.h1080fps15.encoding,stopMicTrackOnMute:!1,videoCodec:"vp8",backupCodec:{codec:"vp8",encoding:wi.h540.encoding}},Li={autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0},Ui={resolution:wi.h720.resolution},xi={adaptiveStream:!1,dynacast:!1,stopLocalTrackOnUnpublish:!0,reconnectPolicy:new DefaultReconnectPolicy,expWebAudioMix:!1},Mi={autoSubscribe:!0,maxRetries:1,peerConnectionTimeout:15e3};var $i={},Bi={},Fi={get exports(){return Bi},set exports(e){Bi=e}}.exports={v:[{name:"version",reg:/^(\d*)$/}],o:[{name:"origin",reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:["username","sessionId","sessionVersion","netType","ipVer","address"],format:"%s %s %d %s IP%d %s"}],s:[{name:"name"}],i:[{name:"description"}],u:[{name:"uri"}],e:[{name:"email"}],p:[{name:"phone"}],z:[{name:"timezones"}],r:[{name:"repeats"}],t:[{name:"timing",reg:/^(\d*) (\d*)/,names:["start","stop"],format:"%d %d"}],c:[{name:"connection",reg:/^IN IP(\d) (\S*)/,names:["version","ip"],format:"IN IP%d %s"}],b:[{push:"bandwidth",reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:["type","limit"],format:"%s:%s"}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:["type","port","protocol","payloads"],format:"%s %d %s %s"}],a:[{push:"rtp",reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:["payload","codec","rate","encoding"],format:function(e){return e.encoding?"rtpmap:%d %s/%s/%s":e.rate?"rtpmap:%d %s/%s":"rtpmap:%d %s"}},{push:"fmtp",reg:/^fmtp:(\d*) ([\S| ]*)/,names:["payload","config"],format:"fmtp:%d %s"},{name:"control",reg:/^control:(.*)/,format:"control:%s"},{name:"rtcp",reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:["port","netType","ipVer","address"],format:function(e){return null!=e.address?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%s trr-int %d"},{push:"rtcpFb",reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:["payload","type","subtype"],format:function(e){return null!=e.subtype?"rtcp-fb:%s %s %s":"rtcp-fb:%s %s"}},{push:"ext",reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:["value","direction","encrypt-uri","uri","config"],format:function(e){return"extmap:%d"+(e.direction?"/%s":"%v")+(e["encrypt-uri"]?" %s":"%v")+" %s"+(e.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(e){return null!=e.sessionConfig?"crypto:%d %s %s %s":"crypto:%d %s %s"}},{name:"setup",reg:/^setup:(\w*)/,format:"setup:%s"},{name:"connectionType",reg:/^connection:(new|existing)/,format:"connection:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{name:"msid",reg:/^msid:(.*)/,format:"msid:%s"},{name:"ptime",reg:/^ptime:(\d*(?:\.\d*)*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\d*(?:\.\d*)*)/,format:"maxptime:%d"},{name:"direction",reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:"icelite",reg:/^(ice-lite)/},{name:"iceUfrag",reg:/^ice-ufrag:(\S*)/,format:"ice-ufrag:%s"},{name:"icePwd",reg:/^ice-pwd:(\S*)/,format:"ice-pwd:%s"},{name:"fingerprint",reg:/^fingerprint:(\S*) (\S*)/,names:["type","hash"],format:"fingerprint:%s %s"},{push:"candidates",reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation","network-id","network-cost"],format:function(e){var t="candidate:%s %d %s %d %s %d typ %s";return t+=null!=e.raddr?" raddr %s rport %d":"%v%v",t+=null!=e.tcptype?" tcptype %s":"%v",null!=e.generation&&(t+=" generation %d"),t+=null!=e["network-id"]?" network-id %d":"%v",t+=null!=e["network-cost"]?" network-cost %d":"%v"}},{name:"endOfCandidates",reg:/^(end-of-candidates)/},{name:"remoteCandidates",reg:/^remote-candidates:(.*)/,format:"remote-candidates:%s"},{name:"iceOptions",reg:/^ice-options:(\S*)/,format:"ice-options:%s"},{push:"ssrcs",reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:["id","attribute","value"],format:function(e){var t="ssrc:%d";return null!=e.attribute&&(t+=" %s",null!=e.value&&(t+=":%s")),t}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","maxMessageSize"],format:function(e){return null!=e.maxMessageSize?"sctpmap:%s %s %s":"sctpmap:%s %s"}},{name:"xGoogleFlag",reg:/^x-google-flag:([^\s]*)/,format:"x-google-flag:%s"},{push:"rids",reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:["id","direction","params"],format:function(e){return e.params?"rid:%s %s %s":"rid:%s %s"}},{push:"imageattrs",reg:new RegExp("^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?"),names:["pt","dir1","attrs1","dir2","attrs2"],format:function(e){return"imageattr:%s %s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast",reg:new RegExp("^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$"),names:["dir1","list1","dir2","list2"],format:function(e){return"simulcast:%s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast_03",reg:/^simulcast:[\s\t]+([\S+\s\t]+)$/,names:["value"],format:"simulcast: %s"},{name:"framerate",reg:/^framerate:(\d+(?:$|\.\d+))/,format:"framerate:%s"},{name:"sourceFilter",reg:/^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,names:["filterMode","netType","addressTypes","destAddress","srcList"],format:"source-filter: %s %s %s %s %s"},{name:"bundleOnly",reg:/^(bundle-only)/},{name:"label",reg:/^label:(.+)/,format:"label:%s"},{name:"sctpPort",reg:/^sctp-port:(\d+)$/,format:"sctp-port:%s"},{name:"maxMessageSize",reg:/^max-message-size:(\d+)$/,format:"max-message-size:%s"},{push:"tsRefClocks",reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:["clksrc","clksrcExt"],format:function(e){return"ts-refclk:%s"+(null!=e.clksrcExt?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(e){var t="mediaclk:";return t+=null!=e.id?"id=%s %s":"%v%s",t+=null!=e.mediaClockValue?"=%s":"",t+=null!=e.rateNumerator?" rate=%s":"",t+=null!=e.rateDenominator?"/%s":""}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{push:"invalid",names:["value"]}]};Object.keys(Fi).forEach((function(e){Fi[e].forEach((function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")}))})),function(e){var toIntIfInt=function(e){return String(Number(e))===e?Number(e):e},parseReg=function(e,t,i){var n=e.name&&e.names;e.push&&!t[e.push]?t[e.push]=[]:n&&!t[e.name]&&(t[e.name]={});var s=e.push?{}:n?t[e.name]:t;!function(e,t,i,n){if(n&&!i)t[n]=toIntIfInt(e[1]);else for(var s=0;s1&&(e[i[0]]=void 0),e};e.parseParams=function(e){return e.split(/;\s?/).reduce(paramReducer,{})},e.parseFmtpConfig=e.parseParams,e.parsePayloads=function(e){return e.toString().split(" ").map(Number)},e.parseRemoteCandidates=function(e){for(var t=[],i=e.split(" ").map(toIntIfInt),n=0;n=n)return e;var s=i[t];switch(t+=1,e){case"%%":return"%";case"%s":return String(s);case"%d":return Number(s);case"%v":return""}}))},makeLine=function(e,t,i){var n=[e+"="+(t.format instanceof Function?t.format(t.push?i:i[t.name]):t.format)];if(t.names)for(var s=0;s{this.emit(zi);try{this.createAndSendOffer()}catch(t){if(!e)throw t;e(t)}}),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){if("offer"===e.type){let{stereoMids:t,nackMids:i}=function extractStereoAndNackAudioFromOffer(e){var t;const i=[],n=[],s=Qi(null!==(t=e.sdp)&&void 0!==t?t:"");let o=0;return s.media.forEach((e=>{var t;"audio"===e.type&&(e.rtp.some((e=>"opus"===e.codec&&(o=e.payload,!0))),(null===(t=e.rtcpFb)||void 0===t?void 0:t.some((e=>e.payload===o&&"nack"===e.type)))&&n.push(e.mid),e.fmtp.some((t=>t.payload===o&&(t.config.includes("sprop-stereo=1")&&i.push(e.mid),!0))))})),{stereoMids:i,nackMids:n}}(e);this.remoteStereoMids=t,this.remoteNackMids=i}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()):"answer"===e.type&&this.emit(Hi)}async createAndSendOffer(e){var t;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 i=await this.pc.createOffer(e),n=Qi(null!==(t=i.sdp)&&void 0!==t?t:"");n.media.forEach((e=>{"audio"===e.type?ensureAudioNackAndStereo(e,[],[]):"video"===e.type&&this.trackBitrates.some((t=>{if(!e.msid||!e.msid.includes(t.sid))return!1;let i=0;return e.rtp.some((e=>e.codec.toUpperCase()===t.codec.toUpperCase()&&(i=e.payload,!0))),i>0&&(e.fmtp.some((e=>e.payload===i&&(e.config.includes("x-google-max-bitrate")||(e.config+=";x-google-max-bitrate=".concat(t.maxbr)),!0)))||e.fmtp.push({payload:i,config:"x-google-max-bitrate=".concat(t.maxbr)})),!0}))})),this.trackBitrates=[],await this.setMungedLocalDescription(i,Gi(n)),this.onOffer(i)}async createAndSetAnswer(){var e;const t=await this.pc.createAnswer(),i=Qi(null!==(e=t.sdp)&&void 0!==e?e:"");return i.media.forEach((e=>{"audio"===e.type&&ensureAudioNackAndStereo(e,this.remoteStereoMids,this.remoteNackMids)})),await this.setMungedLocalDescription(t,Gi(i)),t}setTrackCodecBitrate(e,t,i){this.trackBitrates.push({sid:e,codec:t,maxbr:i})}close(){this.pc.close()}async setMungedLocalDescription(e,t){const i=e.sdp;e.sdp=t;try{return h.debug("setting munged local description"),void await this.pc.setLocalDescription(e)}catch(t){h.warn("not able to set ".concat(e.type,", falling back to unmodified sdp"),{error:t}),e.sdp=i}try{await this.pc.setLocalDescription(e)}catch(e){let t="unknown error";throw e instanceof Error?t=e.message:"string"==typeof e&&(t=e),new NegotiationError(t)}}}function ensureAudioNackAndStereo(e,t,i){let n=0;e.rtp.some((e=>"opus"===e.codec&&(n=e.payload,!0))),n>0&&(e.rtcpFb||(e.rtcpFb=[]),i.includes(e.mid)&&!e.rtcpFb.some((e=>e.payload===n&&"nack"===e.type))&&e.rtcpFb.push({payload:n,type:"nack"}),t.includes(e.mid)&&e.fmtp.some((e=>e.payload===n&&(e.config.includes("stereo=1")||(e.config+=";stereo=1"),!0))))}const Zi="_lossy",Ki="_reliable",Yi="leave-reconnect";var Xi,en;!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"}(Xi||(Xi={}));class RTCEngine extends pi.EventEmitter{get isClosed(){return this._isClosed}constructor(e){var t;super(),t=this,this.options=e,this.rtcConfig={},this.peerConnectionTimeout=Mi.peerConnectionTimeout,this.subscriberPrimary=!1,this.pcState=Xi.New,this._isClosed=!0,this.pendingTrackResolvers={},this.hasPublished=!1,this.reconnectAttempts=0,this.reconnectStart=0,this.fullReconnectOnNext=!1,this.attemptingReconnect=!1,this.joinAttempts=0,this.maxJoinAttempts=1,this.handleDataChannel=async e=>{let{channel:t}=e;if(t){if(t.label===Ki)this.reliableDCSub=t;else{if(t.label!==Zi)return;this.lossyDCSub=t}h.debug("on data channel ".concat(t.id,", ").concat(t.label)),t.onmessage=this.handleDataMessage}},this.handleDataMessage=async e=>{var t,i;let n;if(e.data instanceof ArrayBuffer)n=e.data;else{if(!(e.data instanceof Blob))return void h.error("unsupported data type",e.data);n=await e.data.arrayBuffer()}const s=qe.decode(new Uint8Array(n));"speaker"===(null===(t=s.value)||void 0===t?void 0:t.$case)?this.emit(Yt.ActiveSpeakersUpdate,s.value.speaker.speakers):"user"===(null===(i=s.value)||void 0===i?void 0:i.$case)&&this.emit(Yt.DataPacketReceived,s.value.user,s.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=function(e){let i=arguments.length>1&&void 0!==arguments[1]&&arguments[1];if(t._isClosed)return;h.debug("".concat(e," disconnected")),0===t.reconnectAttempts&&(t.reconnectStart=Date.now());const disconnect=e=>{h.info("could not recover connection after ".concat(t.reconnectAttempts," attempts, ").concat(e,"ms. giving up")),t.emit(Yt.Disconnected),t.close()},n=Date.now()-t.reconnectStart;let s=t.getNextRetryDelay({elapsedMs:n,retryCount:t.reconnectAttempts});null!==s?(e===Yi&&(s=0),h.debug("reconnecting in ".concat(s,"ms")),t.clearReconnectTimeout(),t.reconnectTimeout=CriticalTimers.setTimeout((()=>t.attemptReconnect(i)),s)):disconnect(n)},this.handleBrowserOnLine=()=>{this.client.isReconnecting&&(this.clearReconnectTimeout(),this.attemptReconnect(!0))},this.client=new SignalClient,this.client.signalLatency=this.options.expSignalLatency,this.reconnectPolicy=this.options.reconnectPolicy,this.registerOnLineListener(),this.closingLock=new Mutex}async join(e,t,i,n){this.url=e,this.token=t,this.signalOpts=i;try{this.joinAttempts+=1;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}catch(s){if(s instanceof ConnectionError&&1===s.reason&&(h.warn("Couldn't connect to server, attempt ".concat(this.joinAttempts," of ").concat(this.maxJoinAttempts)),this.joinAttempts{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),await this.client.close()}finally{e()}}addTrack(e){if(this.pendingTrackResolvers[e.cid])throw new TrackInvalidError("a track with the same ID has already been published");return new Promise(((t,i)=>{const n=setTimeout((()=>{delete this.pendingTrackResolvers[e.cid],i(new ConnectionError("publication of local track timed out, no response from server"))}),1e4);this.pendingTrackResolvers[e.cid]={resolve:e=>{clearTimeout(n),t(e)},reject:()=>{clearTimeout(n),i(new Error("Cancelled publication by calling unpublish"))}},this.client.sendAddTrack(e)}))}removeTrack(e){var t;if(e.track&&this.pendingTrackResolvers[e.track.id]){const{reject:t}=this.pendingTrackResolvers[e.track.id];t&&t(),delete this.pendingTrackResolvers[e.track.id]}try{null===(t=this.publisher)||void 0===t||t.pc.removeTrack(e)}catch(e){h.warn("failed to remove track",{error:e,method:"removeTrack"})}}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){var t;if(this.publisher||this.subscriber)return;this.participantSid=null===(t=e.participant)||void 0===t?void 0:t.sid;const i=this.makeRTCConfiguration(e);this.publisher=new PCTransport(i),this.subscriber=new PCTransport(i),this.emit(Yt.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,pt.PUBLISHER))},this.subscriber.pc.onicecandidate=e=>{e.candidate&&this.client.sendIceCandidate(e.candidate,pt.SUBSCRIBER)},this.publisher.onOffer=e=>{this.client.sendOffer(e)};let n=this.publisher.pc,s=this.subscriber.pc;e.subscriberPrimary&&(n=this.subscriber.pc,s=this.publisher.pc,this.subscriber.pc.ondatachannel=this.handleDataChannel),this.primaryPC=n,n.onconnectionstatechange=async()=>{if(h.debug("primary PC state changed ".concat(n.connectionState)),"connected"===n.connectionState){try{this.connectedServerAddr=await getConnectedAddress(n)}catch(e){h.warn("could not get connected server address",{error:e})}const t=this.pcState===Xi.New;this.pcState=Xi.Connected,t&&this.emit(Yt.Connected,e)}else"failed"===n.connectionState&&this.pcState===Xi.Connected&&(this.pcState=Xi.Disconnected,this.handleDisconnect("primary peerconnection"))},s.onconnectionstatechange=async()=>{h.debug("secondary PC state changed ".concat(s.connectionState)),"failed"===s.connectionState&&this.handleDisconnect("secondary peerconnection")},this.subscriber.pc.ontrack=e=>{this.emit(Yt.MediaTrackAdded,e.track,e.streams[0],e.receiver)},this.createDataChannels(),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===pt.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.createAndSetAnswer();this.client.sendAnswer(t)},this.client.onLocalTrackPublished=e=>{h.debug("received trackPublishedResponse",e);const{resolve: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.handleDisconnect(Yi)):(this.emit(Yt.Disconnected,null==e?void 0:e.reason),this.close()),h.trace("leave request",{leave:e})}}makeRTCConfiguration(e){const t=_objectSpread2({},this.rtcConfig);if(e.iceServers&&!t.iceServers){const i=[];e.iceServers.forEach((e=>{const t={urls:e.urls};e.username&&(t.username=e.username),e.credential&&(t.credential=e.credential),i.push(t)})),t.iceServers=i}return e.clientConfiguration&&e.clientConfiguration.forceRelay===Ne.ENABLED&&(t.iceTransportPolicy="relay"),t.sdpSemantics="unified-plan",t.continualGatheringPolicy="gather_continually",t}createDataChannels(){this.publisher&&(this.lossyDC&&(this.lossyDC.onmessage=null,this.lossyDC.onerror=null),this.reliableDC&&(this.reliableDC.onmessage=null,this.reliableDC.onerror=null),this.lossyDC=this.publisher.pc.createDataChannel(Zi,{ordered:!0,maxRetransmits:0}),this.reliableDC=this.publisher.pc.createDataChannel(Ki,{ordered:!0}),this.lossyDC.onmessage=this.handleDataMessage,this.reliableDC.onmessage=this.handleDataMessage,this.lossyDC.onerror=this.handleDataError,this.reliableDC.onerror=this.handleDataError)}setPreferredCodec(e,t,i){if(!("getCapabilities"in RTCRtpSender))return;const n=RTCRtpSender.getCapabilities(t);if(!n)return;h.debug("get capabilities",n);const s=[],o=[],a=[];n.codecs.forEach((e=>{const t=e.mimeType.toLowerCase();if("audio/opus"===t)return void s.push(e);t==="video/".concat(i)?"h264"!==i||e.sdpFmtpLine&&e.sdpFmtpLine.includes("profile-level-id=42e01f")?s.push(e):o.push(e):a.push(e)})),supportsSetCodecPreferences(e)&&e.setCodecPreferences(s.concat(o,a))}async createSender(e,t,i){if(supportsTransceiver())return this.createTransceiverRTCRtpSender(e,t,i);if(supportsAddTrack())return h.debug("using add-track fallback"),this.createRTCRtpSender(e.mediaStreamTrack);throw new UnexpectedConnectionState("Required webRTC APIs not supported on this device")}async createSimulcastSender(e,t,i,n){if(supportsTransceiver())return this.createSimulcastTransceiverSender(e,t,i,n);if(supportsAddTrack())return h.debug("using add-track fallback"),this.createRTCRtpSender(e.mediaStreamTrack);throw new UnexpectedConnectionState("Cannot stream on this device")}async createTransceiverRTCRtpSender(e,t,i){if(!this.publisher)throw new UnexpectedConnectionState("publisher is closed");const n={direction:"sendonly"};i&&(n.sendEncodings=i);const s=await this.publisher.pc.addTransceiver(e.mediaStreamTrack,n);return e.kind===Track.Kind.Video&&t.videoCodec&&(this.setPreferredCodec(s,e.kind,t.videoCodec),e.codec=t.videoCodec),s.sender}async createSimulcastTransceiverSender(e,t,i,n){if(!this.publisher)throw new UnexpectedConnectionState("publisher is closed");const s={direction:"sendonly"};n&&(s.sendEncodings=n);const o=await this.publisher.pc.addTransceiver(t.mediaStreamTrack,s);if(i.videoCodec)return this.setPreferredCodec(o,e.kind,i.videoCodec),e.setSimulcastTrackSender(i.videoCodec,o.sender),o.sender}async createRTCRtpSender(e){if(!this.publisher)throw new UnexpectedConnectionState("publisher is closed");return this.publisher.pc.addTrack(e)}async attemptReconnect(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];var t,i,n;if(!this._isClosed&&!this.attemptingReconnect){(null===(t=this.clientConfiguration)||void 0===t?void 0:t.resumeConnection)!==Ne.DISABLED&&"closed"!==(null!==(n=null===(i=this.primaryPC)||void 0===i?void 0:i.signalingState)&&void 0!==n?n:"closed")||(this.fullReconnectOnNext=!0);try{this.attemptingReconnect=!0,this.fullReconnectOnNext?await this.restartConnection(e):await this.resumeConnection(e),this.clearPendingReconnect(),this.fullReconnectOnNext=!1}catch(e){this.reconnectAttempts+=1;let t=!1,i=!0,n=!1;e instanceof UnexpectedConnectionState?(h.debug("received unrecoverable error",{error:e}),i=!1):e instanceof SignalReconnectError||(t=!0),t&&!this.fullReconnectOnNext&&(this.fullReconnectOnNext=!0,n=!0),i?this.handleDisconnect("reconnect",n):(h.info("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(Date.now()-this.reconnectStart,"ms. giving up")),this.emit(Yt.Disconnected),this.close())}finally{this.attemptingReconnect=!1}}}getNextRetryDelay(e){try{return this.reconnectPolicy.nextRetryDelayInMs(e)}catch(e){h.warn("encountered error in reconnect policy",{error:e})}return null}async restartConnection(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];var t,i;if(!this.url||!this.token)throw new UnexpectedConnectionState("could not reconnect, url or token not saved");let n;h.info("reconnecting, attempt: ".concat(this.reconnectAttempts)),(e||0===this.reconnectAttempts)&&this.emit(Yt.Restarting),this.client.isConnected&&await this.client.sendLeave(),await this.client.close(),this.primaryPC=void 0,null===(t=this.publisher)||void 0===t||t.close(),this.publisher=void 0,null===(i=this.subscriber)||void 0===i||i.close(),this.subscriber=void 0;try{if(!this.signalOpts)throw h.warn("attempted connection restart, without signal options present"),new SignalReconnectError;n=await this.join(this.url,this.token,this.signalOpts)}catch(e){throw new SignalReconnectError}await this.waitForPCConnected(),this.client.setReconnected(),this.emit(Yt.Restarted,n)}async resumeConnection(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];var t;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)),(e||0===this.reconnectAttempts)&&this.emit(Yt.Resuming);try{const e=await this.client.reconnect(this.url,this.token,this.participantSid);if(e){const t=this.makeRTCConfiguration(e);this.publisher.pc.setConfiguration(t),this.subscriber.pc.setConfiguration(t)}}catch(e){let t="";throw e instanceof Error&&(t=e.message),new SignalReconnectError(t)}this.emit(Yt.SignalResumed),this.subscriber.restartingIce=!0,this.hasPublished&&await this.publisher.createAndSendOffer({iceRestart:!0}),await this.waitForPCConnected(),this.client.setReconnected(),"open"===(null===(t=this.reliableDC)||void 0===t?void 0:t.readyState)&&null===this.reliableDC.id&&this.createDataChannels(),this.emit(Yt.Resumed)}async waitForPCConnected(){var e;const t=Date.now();let i=t;for(this.pcState=Xi.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=Xi.Connected;try{this.connectedServerAddr=await getConnectedAddress(this.primaryPC)}catch(e){h.warn("could not get connected server address",{error:e})}}if(this.pcState===Xi.Connected)return;await sleep(100),i=Date.now()}throw new ConnectionError("could not establish PC connection")}async sendDataPacket(e,t){const i=qe.encode(e).finish();await this.ensurePublisherConnected(t),t===Ae.LOSSY&&this.lossyDC?this.lossyDC.send(i):t===Ae.RELIABLE&&this.reliableDC&&this.reliableDC.send(i)}async ensureDataTransportConnected(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.subscriberPrimary;var i,n,s;const o=t?this.subscriber:this.publisher,a=t?"Subscriber":"Publisher";if(!o)throw new ConnectionError("".concat(a," connection not set"));t||(null===(i=this.publisher)||void 0===i?void 0:i.isICEConnected)||"checking"===(null===(n=this.publisher)||void 0===n?void 0:n.pc.iceConnectionState)||this.negotiate();const c=this.dataChannelForKind(e,t);if("open"===(null==c?void 0:c.readyState))return;const u=(new Date).getTime()+this.peerConnectionTimeout;for(;(new Date).getTime(){if(!this.publisher)return void t(new NegotiationError("publisher is not defined"));this.hasPublished=!0;const handleClosed=()=>{h.debug("engine disconnected while negotiation was ongoing"),cleanup(),e()};this.on(Yt.Closing,handleClosed);const i=setTimeout((()=>{t("negotiation timed out"),this.handleDisconnect("negotiation")}),this.peerConnectionTimeout),cleanup=()=>{clearTimeout(i),this.off(Yt.Closing,handleClosed)};this.publisher.once(zi,(()=>{var t;null===(t=this.publisher)||void 0===t||t.once(Hi,(()=>{cleanup(),e()}))})),this.publisher.negotiate((e=>{cleanup(),t(e),e instanceof NegotiationError&&(this.fullReconnectOnNext=!0),this.handleDisconnect("negotiation")}))}))}dataChannelForKind(e,t){if(t){if(e===Ae.LOSSY)return this.lossyDCSub;if(e===Ae.RELIABLE)return this.reliableDCSub}else{if(e===Ae.LOSSY)return this.lossyDC;if(e===Ae.RELIABLE)return this.reliableDC}}clearReconnectTimeout(){this.reconnectTimeout&&CriticalTimers.clearTimeout(this.reconnectTimeout)}clearPendingReconnect(){this.clearReconnectTimeout(),this.reconnectAttempts=0}registerOnLineListener(){isWeb()&&window.addEventListener("online",this.handleBrowserOnLine)}deregisterOnLineListener(){isWeb()&&window.removeEventListener("online",this.handleBrowserOnLine)}}async function getConnectedAddress(e){var t;let i="";const n=new Map,s=new Map;if((await e.getStats()).forEach((e=>{switch(e.type){case"transport":i=e.selectedCandidatePairId;break;case"candidate-pair":""===i&&e.selected&&(i=e.id),n.set(e.id,e);break;case"remote-candidate":s.set(e.id,"".concat(e.address,":").concat(e.port))}})),""===i)return;const o=null===(t=n.get(i))||void 0===t?void 0:t.remoteCandidateId;return void 0!==o?s.get(o):void 0}class SignalReconnectError extends Error{}!function(e){e.Disconnected="disconnected",e.Connecting="connecting",e.Connected="connected",e.Reconnecting="reconnecting"}(en||(en={}));const tn=en;class Room extends pi.EventEmitter{constructor(e){var t;super(),t=this,this.state=en.Disconnected,this.activeSpeakers=[],this.sid="",this.name="",this.metadata=void 0,this._isRecording=!1,this.audioEnabled=!0,this.connect=async(e,t,i)=>{const n=await this.disconnectLock.lock();if(this.state===en.Connected)return h.info("already connected to room ".concat(this.name)),n(),Promise.resolve();if(this.connectFuture)return n(),this.connectFuture.promise;this.setAndEmitConnectionState(en.Connecting);return this.connectFuture=new Future((async(s,o)=>{var a,c;this.abortController&&!this.abortController.signal.aborted||(this.abortController=new AbortController),n(),this.state===en.Reconnecting?(h.info("Reconnection attempt replaced by new connection attempt"),this.recreateEngine()):this.maybeCreateEngine(),this.acquireAudioContext(),this.connOptions=_objectSpread2(_objectSpread2({},Mi),i),this.connOptions.rtcConfig&&(this.engine.rtcConfig=this.connOptions.rtcConfig),this.connOptions.peerConnectionTimeout&&(this.engine.peerConnectionTimeout=this.connOptions.peerConnectionTimeout);try{const i=await this.engine.join(e,t,{autoSubscribe:this.connOptions.autoSubscribe,publishOnly:this.connOptions.publishOnly,adaptiveStream:"object"==typeof this.options.adaptiveStream||this.options.adaptiveStream,maxRetries:this.connOptions.maxRetries},this.abortController.signal);let n=i.serverInfo;if(n||(n={version:i.serverVersion,region:i.serverRegion}),h.debug("connected to Livekit Server ".concat(Object.entries(n).map((e=>{let[t,i]=e;return"".concat(t,": ").concat(i)})).join(", "))),!i.serverVersion)throw new UnsupportedServer("unknown server version");"0.15.1"===i.serverVersion&&this.options.dynacast&&(h.debug("disabling dynacast due to server version"),this.options.dynacast=!1);const s=i.participant;this.localParticipant.sid=s.sid,this.localParticipant.identity=s.identity,this.localParticipant.updateInfo(s),this.setupLocalParticipantEvents(),i.otherParticipants.forEach((e=>{e.sid!==this.localParticipant.sid&&e.identity!==this.localParticipant.identity?this.getOrCreateParticipant(e.sid,e):h.warn("received info to create local participant as remote participant",{info:e,localParticipant:this.localParticipant})})),this.name=i.room.name,this.sid=i.room.sid,this.metadata=i.room.metadata,this._isRecording!==i.room.activeRecording&&(this._isRecording=i.room.activeRecording,this.emit(Zt.RecordingStatusChanged,i.room.activeRecording)),this.emit(Zt.SignalConnected)}catch(e){this.recreateEngine(),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish);let t="";return e instanceof Error&&(t=e.message,h.debug("error trying to establish signal connection",{error:e})),void o(new ConnectionError("could not establish signal connection: ".concat(t)))}const u=CriticalTimers.setTimeout((()=>{this.recreateEngine(),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),o(new ConnectionError("could not connect PeerConnection after timeout"))}),this.connOptions.peerConnectionTimeout),abortHandler=()=>{h.warn("closing engine"),CriticalTimers.clearTimeout(u),this.recreateEngine(),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),o(new ConnectionError("room connection has been cancelled"))};(null===(a=this.abortController)||void 0===a?void 0:a.signal.aborted)&&abortHandler(),null===(c=this.abortController)||void 0===c||c.signal.addEventListener("abort",abortHandler),this.engine.once(Yt.Connected,(()=>{var e,t;CriticalTimers.clearTimeout(u),null===(e=this.abortController)||void 0===e||e.signal.removeEventListener("abort",abortHandler),isWeb()&&(window.addEventListener("beforeunload",this.onBeforeUnload),null===(t=navigator.mediaDevices)||void 0===t||t.addEventListener("devicechange",this.handleDeviceChange)),this.setAndEmitConnectionState(en.Connected),this.emit(Zt.Connected),s()}))}),(()=>{this.clearConnectionFutures()})),this.connectFuture.promise},this.disconnect=async function(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];var i,n,s,o;const a=await t.disconnectLock.lock();try{if(t.state===en.Disconnected)return void h.debug("already disconnected");h.info("disconnect from room",{identity:t.localParticipant.identity}),t.state!==en.Connecting&&t.state!==en.Reconnecting||(h.warn("abort connection attempt"),null===(i=t.abortController)||void 0===i||i.abort(),null===(s=null===(n=t.connectFuture)||void 0===n?void 0:n.reject)||void 0===s||s.call(n,new ConnectionError("Client initiated disconnect")),t.connectFuture=void 0),(null===(o=t.engine)||void 0===o?void 0:o.client.isConnected)&&await t.engine.client.sendLeave(),t.engine&&await t.engine.close(),t.handleDisconnect(e,Ie.CLIENT_INITIATED),t.engine=void 0}finally{a()}},this.onBeforeUnload=async()=>{await this.disconnect()},this.handleRestarting=()=>{for(const e of this.participants.values())this.handleParticipantDisconnected(e.sid,e);this.setAndEmitConnectionState(en.Reconnecting)&&this.emit(Zt.Reconnecting)},this.handleRestarted=async e=>{h.debug("reconnected to server",{region:e.serverRegion}),this.setAndEmitConnectionState(en.Connected),this.emit(Zt.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),t.isMuted||((t instanceof LocalAudioTrack||t instanceof LocalVideoTrack)&&!t.isUserProvided&&(h.debug("restarting existing track",{track:e.trackSid}),await t.restartTrack()),await 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);const t=this.identityToSid.get(e.identity);t&&t!==e.sid&&this.handleParticipantDisconnected(t,this.participants.get(t));let i=this.participants.get(e.sid);const n=!i;i=this.getOrCreateParticipant(e.sid,e),e.state===De.DISCONNECTED?this.handleParticipantDisconnected(e.sid,i):n||i.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.emitWhenConnected(Zt.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.emitWhenConnected(Zt.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(Kt.TrackStreamStateChanged,i,i.track.streamState),this.emitWhenConnected(Zt.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.setAllowed(e.allowed)},this.handleDataPacket=(e,t)=>{const i=this.participants.get(e.participantSid);this.emit(Zt.DataReceived,e.payload,i,t),null==i||i.emit(Kt.DataReceived,e.payload,t)},this.handleAudioPlaybackStarted=()=>{this.canPlaybackAudio||(this.audioEnabled=!0,this.emit(Zt.AudioPlaybackStatusChanged,!0))},this.handleAudioPlaybackFailed=e=>{h.warn("could not playback audio",e),this.canPlaybackAudio&&(this.audioEnabled=!1,this.emit(Zt.AudioPlaybackStatusChanged,!1))},this.handleDeviceChange=async()=>{this.emit(Zt.MediaDevicesChanged)},this.handleRoomUpdate=e=>{this._isRecording!==e.activeRecording&&(this._isRecording=e.activeRecording,this.emit(Zt.RecordingStatusChanged,e.activeRecording)),this.metadata!==e.metadata&&(this.metadata=e.metadata,this.emitWhenConnected(Zt.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.onLocalParticipantMetadataChanged=e=>{this.emit(Zt.ParticipantMetadataChanged,e,this.localParticipant)},this.onLocalTrackMuted=e=>{this.emit(Zt.TrackMuted,e,this.localParticipant)},this.onLocalTrackUnmuted=e=>{this.emit(Zt.TrackUnmuted,e,this.localParticipant)},this.onLocalTrackPublished=e=>{this.emit(Zt.LocalTrackPublished,e,this.localParticipant)},this.onLocalTrackUnpublished=e=>{this.emit(Zt.LocalTrackUnpublished,e,this.localParticipant)},this.onLocalConnectionQualityChanged=e=>{this.emit(Zt.ConnectionQualityChanged,e,this.localParticipant)},this.onMediaDevicesError=e=>{this.emit(Zt.MediaDevicesError,e)},this.onLocalParticipantPermissionsChanged=e=>{this.emit(Zt.ParticipantPermissionsChanged,e,this.localParticipant)},this.setMaxListeners(100),this.participants=new Map,this.identityToSid=new Map,this.options=_objectSpread2(_objectSpread2({},xi),e),this.options.audioCaptureDefaults=_objectSpread2(_objectSpread2({},Li),null==e?void 0:e.audioCaptureDefaults),this.options.videoCaptureDefaults=_objectSpread2(_objectSpread2({},Ui),null==e?void 0:e.videoCaptureDefaults),this.options.publishDefaults=_objectSpread2(_objectSpread2({},Ai),null==e?void 0:e.publishDefaults),this.maybeCreateEngine(),this.disconnectLock=new Mutex,this.localParticipant=new LocalParticipant("","",this.engine,this.options)}maybeCreateEngine(){this.engine||(this.engine=new RTCEngine(this.options),this.engine.client.onParticipantUpdate=this.handleParticipantUpdates,this.engine.client.onRoomUpdate=this.handleRoomUpdate,this.engine.client.onSpeakersChanged=this.handleSpeakersChanged,this.engine.client.onStreamStateUpdate=this.handleStreamStateUpdate,this.engine.client.onSubscriptionPermissionUpdate=this.handleSubscriptionPermissionUpdate,this.engine.client.onConnectionQuality=this.handleConnectionQualityUpdate,this.engine.on(Yt.MediaTrackAdded,((e,t,i)=>{this.onTrackAdded(e,t,i)})).on(Yt.Disconnected,(e=>{this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e)})).on(Yt.ActiveSpeakersUpdate,this.handleActiveSpeakersUpdate).on(Yt.DataPacketReceived,this.handleDataPacket).on(Yt.Resuming,(()=>{this.setAndEmitConnectionState(en.Reconnecting)&&this.emit(Zt.Reconnecting)})).on(Yt.Resumed,(()=>{this.setAndEmitConnectionState(en.Connected),this.emit(Zt.Reconnected),this.updateSubscriptions()})).on(Yt.SignalResumed,(()=>{this.state===en.Reconnecting&&this.sendSyncState()})).on(Yt.Restarting,this.handleRestarting).on(Yt.Restarted,this.handleRestarted),this.localParticipant&&this.localParticipant.setupEngine(this.engine))}static getLocalDevices(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return DeviceManager.getInstance().getDevices(e,t)}async prepareConnection(e){await fetch("http".concat(e.substring(2)),{method:"HEAD"})}getParticipantByIdentity(e){if(this.localParticipant.identity===e)return this.localParticipant;const t=this.identityToSid.get(e);return t?this.participants.get(t):void 0}clearConnectionFutures(){this.connectFuture=void 0}get isRecording(){return this._isRecording}async simulateScenario(e){let t,postAction=()=>{};switch(e){case"signal-reconnect":await this.engine.client.close(),this.engine.client.onClose&&this.engine.client.onClose("simulate disconnect");break;case"speaker":t=zt.fromPartial({scenario:{$case:"speakerUpdate",speakerUpdate:3}});break;case"node-failure":t=zt.fromPartial({scenario:{$case:"nodeFailure",nodeFailure:!0}});break;case"server-leave":t=zt.fromPartial({scenario:{$case:"serverLeave",serverLeave:!0}});break;case"migration":t=zt.fromPartial({scenario:{$case:"migration",migration:!0}});break;case"force-tcp":case"force-tls":t=zt.fromPartial({scenario:{$case:"switchCandidateProtocol",switchCandidateProtocol:"force-tls"===e?2:1}}),postAction=async()=>{const e=this.engine.client.onLeave;e&&e({reason:Ie.CLIENT_INITIATED,canReconnect:!0})}}t&&(this.engine.client.sendSimulateScenario(t),postAction())}async startAudio(){await 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.muted=!1,e.play())))),this.handleAudioPlaybackStarted()}catch(e){throw this.handleAudioPlaybackFailed(e),e}}get canPlaybackAudio(){return this.audioEnabled}getActiveAudioOutputDevice(){var e,t;return null!==(t=null===(e=this.options.audioOutput)||void 0===e?void 0:e.deviceId)&&void 0!==t?t:""}async switchActiveDevice(e,t){var i,n;if("audioinput"===e){const e=this.options.audioCaptureDefaults.deviceId;this.options.audioCaptureDefaults.deviceId=t;const i=Array.from(this.localParticipant.audioTracks.values()).filter((e=>e.source===Track.Source.Microphone));try{await Promise.all(i.map((e=>{var i;return null===(i=e.audioTrack)||void 0===i?void 0:i.setDeviceId(t)})))}catch(t){throw this.options.audioCaptureDefaults.deviceId=e,t}}else if("videoinput"===e){const e=this.options.videoCaptureDefaults.deviceId;this.options.videoCaptureDefaults.deviceId=t;const i=Array.from(this.localParticipant.videoTracks.values()).filter((e=>e.source===Track.Source.Camera));try{await Promise.all(i.map((e=>{var i;return null===(i=e.videoTrack)||void 0===i?void 0:i.setDeviceId(t)})))}catch(t){throw this.options.videoCaptureDefaults.deviceId=e,t}}else if("audiooutput"===e){if(!supportsSetSinkId())throw new Error("cannot switch audio output, setSinkId not supported");null!==(i=(n=this.options).audioOutput)&&void 0!==i||(n.audioOutput={});const e=this.options.audioOutput.deviceId;this.options.audioOutput.deviceId=t;try{await Promise.all(Array.from(this.participants.values()).map((e=>e.setAudioOutput({deviceId:t}))))}catch(t){throw this.options.audioOutput.deviceId=e,t}}}setupLocalParticipantEvents(){this.localParticipant.on(Kt.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).on(Kt.TrackMuted,this.onLocalTrackMuted).on(Kt.TrackUnmuted,this.onLocalTrackUnmuted).on(Kt.LocalTrackPublished,this.onLocalTrackPublished).on(Kt.LocalTrackUnpublished,this.onLocalTrackUnpublished).on(Kt.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).on(Kt.MediaDevicesError,this.onMediaDevicesError).on(Kt.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged)}recreateEngine(){var e;null===(e=this.engine)||void 0===e||e.close(),this.engine=void 0,this.participants.clear(),this.maybeCreateEngine()}onTrackAdded(e,t,i){if(this.state===en.Connecting||this.state===en.Reconnecting){const reconnectedHandler=()=>{this.onTrackAdded(e,t,i),cleanup()},cleanup=()=>{this.off(Zt.Reconnected,reconnectedHandler),this.off(Zt.Connected,reconnectedHandler),this.off(Zt.Disconnected,cleanup)};return this.once(Zt.Reconnected,reconnectedHandler),this.once(Zt.Connected,reconnectedHandler),void this.once(Zt.Disconnected,cleanup)}if(this.state===en.Disconnected)return void h.warn("skipping incoming track after Room disconnected");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 o=n[1];if(o&&""!==o||(o=e.id),s===this.localParticipant.sid)return void h.warn("tried to create RemoteParticipant for local participant");const a=this.getOrCreateParticipant(s);let c;this.options.adaptiveStream&&(c="object"==typeof this.options.adaptiveStream?this.options.adaptiveStream:{}),a.addSubscribedMediaTrack(e,o,t,i,c)}handleDisconnect(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0],t=arguments.length>1?arguments[1]:void 0;var i;this.state!==en.Disconnected&&(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),e&&(null===(i=t.track)||void 0===i||i.detach(),null===(n=t.track)||void 0===n||n.stop())})),this.localParticipant.off(Kt.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).off(Kt.TrackMuted,this.onLocalTrackMuted).off(Kt.TrackUnmuted,this.onLocalTrackUnmuted).off(Kt.LocalTrackPublished,this.onLocalTrackPublished).off(Kt.LocalTrackUnpublished,this.onLocalTrackUnpublished).off(Kt.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).off(Kt.MediaDevicesError,this.onMediaDevicesError).off(Kt.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged),this.localParticipant.tracks.clear(),this.localParticipant.videoTracks.clear(),this.localParticipant.audioTracks.clear(),this.participants.clear(),this.activeSpeakers=[],this.audioContext&&"boolean"==typeof this.options.expWebAudioMix&&(this.audioContext.close(),this.audioContext=void 0),isWeb()&&(window.removeEventListener("beforeunload",this.onBeforeUnload),null===(i=navigator.mediaDevices)||void 0===i||i.removeEventListener("devicechange",this.handleDeviceChange)),this.setAndEmitConnectionState(en.Disconnected),this.emit(Zt.Disconnected,t))}handleParticipantDisconnected(e,t){this.participants.delete(e),t&&(this.identityToSid.delete(t.identity),t.tracks.forEach((e=>{t.unpublishTrack(e.trackSid,!0)})),this.emitWhenConnected(Zt.ParticipantDisconnected,t))}async acquireAudioContext(){var e,t;"boolean"!=typeof this.options.expWebAudioMix&&this.options.expWebAudioMix.audioContext?(this.audioContext=this.options.expWebAudioMix.audioContext,await this.audioContext.resume()):this.audioContext=null!==(e=getNewAudioContext())&&void 0!==e?e:void 0,this.options.expWebAudioMix&&this.participants.forEach((e=>e.setAudioContext(this.audioContext)));const i="running"===(null===(t=this.audioContext)||void 0===t?void 0:t.state);i!==this.canPlaybackAudio&&(this.audioEnabled=i,this.emit(Zt.AudioPlaybackStatusChanged,i))}createParticipant(e,t){let i;return i=t?RemoteParticipant.fromParticipantInfo(this.engine.client,t):new RemoteParticipant(this.engine.client,e,"",void 0,void 0),this.options.expWebAudioMix&&i.setAudioContext(this.audioContext),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),t&&(this.identityToSid.set(t.identity,t.sid),this.emitWhenConnected(Zt.ParticipantConnected,i)),i.on(Kt.TrackPublished,(e=>{this.emitWhenConnected(Zt.TrackPublished,e,i)})).on(Kt.TrackSubscribed,((e,t)=>{e.kind===Track.Kind.Audio&&(e.on(Xt.AudioPlaybackStarted,this.handleAudioPlaybackStarted),e.on(Xt.AudioPlaybackFailed,this.handleAudioPlaybackFailed)),this.emit(Zt.TrackSubscribed,e,t,i)})).on(Kt.TrackUnpublished,(e=>{this.emitWhenConnected(Zt.TrackUnpublished,e,i)})).on(Kt.TrackUnsubscribed,((e,t)=>{this.emit(Zt.TrackUnsubscribed,e,t,i)})).on(Kt.TrackSubscriptionFailed,(e=>{this.emit(Zt.TrackSubscriptionFailed,e,i)})).on(Kt.TrackMuted,(e=>{this.emitWhenConnected(Zt.TrackMuted,e,i)})).on(Kt.TrackUnmuted,(e=>{this.emitWhenConnected(Zt.TrackUnmuted,e,i)})).on(Kt.ParticipantMetadataChanged,(e=>{this.emitWhenConnected(Zt.ParticipantMetadataChanged,e,i)})).on(Kt.ConnectionQualityChanged,(e=>{this.emitWhenConnected(Zt.ConnectionQualityChanged,e,i)})).on(Kt.ParticipantPermissionsChanged,(e=>{this.emitWhenConnected(Zt.ParticipantPermissionsChanged,e,i)})).on(Kt.TrackSubscriptionStatusChanged,((e,t)=>{this.emitWhenConnected(Zt.TrackSubscriptionStatusChanged,e,t,i)})).on(Kt.TrackSubscriptionPermissionChanged,((e,t)=>{this.emitWhenConnected(Zt.TrackSubscriptionPermissionChanged,e,t,i)})),t&&i.updateInfo(t),i}sendSyncState(){var e,t;if(void 0===this.engine.subscriber||null===this.engine.subscriber.pc.localDescription)return;const i=this.engine.subscriber.pc.localDescription,n=this.engine.subscriber.pc.remoteDescription,s=null===(t=null===(e=this.connOptions)||void 0===e?void 0:e.autoSubscribe)||void 0===t||t,o=new Array;this.participants.forEach((e=>{e.tracks.forEach((e=>{e.isDesired!==s&&o.push(e.trackSid)}))})),this.engine.client.sendSyncState({answer:toProtoSessionDescription({sdp:i.sdp,type:i.type}),offer:n?toProtoSessionDescription({sdp:n.sdp,type:n.type}):void 0,subscription:{trackSids:o,subscribe:!s,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){return e!==this.state&&(this.state=e,this.emit(Zt.ConnectionStateChanged,this.state),!0)}emitWhenConnected(e){if(this.state===en.Connected){for(var t=arguments.length,i=new Array(t>1?t-1:0),n=1;n1?t-1:0),n=1;nDeviceManager.userMediaPromiseMap.delete("audioinput")))),e.video&&(DeviceManager.userMediaPromiseMap.set("videoinput",s),s.catch((()=>DeviceManager.userMediaPromiseMap.delete("videoinput"))));const o=await s;return o.getTracks().map((t=>{const i="audio"===t.kind;let s;i?e.audio:e.video;const a=i?n.audio:n.video;"boolean"!=typeof a&&(s=a);const c=mediaTrackToLocalTrack(t,s);return c.kind===Track.Kind.Video?c.source=Track.Source.Camera:c.kind===Track.Kind.Audio&&(c.source=Track.Source.Microphone),c.mediaStream=o,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=wi.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 o=new LocalVideoTrack(s[0],void 0,!1);o.source=Track.Source.ScreenShare;const a=[o];if(n.getAudioTracks().length>0){const e=new LocalAudioTrack(n.getAudioTracks()[0],void 0,!1);e.source=Track.Source.ScreenShareAudio,a.push(e)}return a}var nn;!function(e){e[e.IDLE=0]="IDLE",e[e.RUNNING=1]="RUNNING",e[e.SKIPPED=2]="SKIPPED",e[e.SUCCESS=3]="SUCCESS",e[e.FAILED=4]="FAILED"}(nn||(nn={}));class Checker extends pi.EventEmitter{constructor(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};super(),this.status=nn.IDLE,this.logs=[],this.errorsAsWarnings=!1,this.url=e,this.token=t,this.name=this.constructor.name,this.room=new Room(i.roomOptions),this.connectOptions=i.connectOptions,i.errorsAsWarnings&&(this.errorsAsWarnings=i.errorsAsWarnings)}async run(e){if(this.status!==nn.IDLE)throw Error("check is running already");this.setStatus(nn.RUNNING),this.appendMessage("".concat(this.name," started."));try{await this.perform()}catch(e){e instanceof Error&&(this.errorsAsWarnings?this.appendWarning(e.message):this.appendError(e.message))}return await this.disconnect(),await new Promise((e=>setTimeout(e,500))),this.status!==nn.SKIPPED&&this.setStatus(this.isSuccess()?nn.SUCCESS:nn.FAILED),e&&e(),this.getInfo()}isSuccess(){return!this.logs.some((e=>"error"===e.level))}async connect(){return this.room.state===en.Connected||await this.room.connect(this.url,this.token),this.room}async disconnect(){this.room&&this.room.state!==en.Disconnected&&(await this.room.disconnect(),await new Promise((e=>setTimeout(e,500))))}skip(){this.setStatus(nn.SKIPPED)}appendMessage(e){this.logs.push({level:"info",message:e}),this.emit("update",this.getInfo())}appendWarning(e){this.logs.push({level:"warning",message:e}),this.emit("update",this.getInfo())}appendError(e){this.logs.push({level:"error",message:e}),this.emit("update",this.getInfo())}setStatus(e){this.status=e,this.emit("update",this.getInfo())}get engine(){var e;return null===(e=this.room)||void 0===e?void 0:e.engine}getInfo(){return{logs:this.logs,name:this.name,status:this.status,description:this.description}}}class PublishAudioCheck extends Checker{get description(){return"Can publish audio"}async perform(){var e;const t=await this.connect(),i=await createLocalAudioTrack();t.localParticipant.publishTrack(i),await new Promise((e=>setTimeout(e,3e3)));const n=await(null===(e=i.sender)||void 0===e?void 0:e.getStats());if(!n)throw new Error("Could not get RTCStats");let s=0;if(n.forEach((e=>{"outbound-rtp"===e.type&&"audio"===e.mediaType&&(s=e.packetsSent)})),0===s)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(s," audio packets"))}}class PublishVideoCheck extends Checker{get description(){return"Can publish video"}async perform(){var e;const t=await this.connect(),i=await createLocalVideoTrack();t.localParticipant.publishTrack(i),await new Promise((e=>setTimeout(e,3e3)));const n=await(null===(e=i.sender)||void 0===e?void 0:e.getStats());if(!n)throw new Error("Could not get RTCStats");let s=0;if(n.forEach((e=>{"outbound-rtp"===e.type&&"video"===e.mediaType&&(s=e.packetsSent)})),0===s)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(s," video packets"))}}class ReconnectCheck extends Checker{get description(){return"Resuming connection after interruption"}async perform(){var e;const t=await this.connect();let i,n=!1,s=!1;const o=new Promise((e=>{setTimeout(e,5e3),i=e}));t.on(Zt.Reconnecting,(()=>{n=!0})).on(Zt.Reconnected,(()=>{s=!0,i(!0)})),null===(e=t.engine.client.ws)||void 0===e||e.close();const a=t.engine.client.onClose;if(a&&a(""),await o,!n)throw new Error("Did not attempt to reconnect");if(!s||t.state!==en.Connected)throw this.appendWarning("reconnection is only possible in Redis-based configurations"),new Error("Not able to reconnect")}}class TURNCheck extends Checker{get description(){return"Can connect via TURN"}async perform(){var e,t;const i=new SignalClient,n=await i.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0});let s=!1,o=!1,a=!1;for(let e of n.iceServers)for(let t of e.urls)t.startsWith("turn:")?(o=!0,a=!0):t.startsWith("turns:")&&(o=!0,a=!0,s=!0),t.startsWith("stun:")&&(a=!0);a?o&&!s&&this.appendWarning("TURN is configured server side, but TURN/TLS is unavailable."):this.appendWarning("No STUN servers configured on server side."),await i.close(),(null===(t=null===(e=this.connectOptions)||void 0===e?void 0:e.rtcConfig)||void 0===t?void 0:t.iceServers)||o?await this.room.connect(this.url,this.token,{rtcConfig:{iceTransportPolicy:"relay"}}):(this.appendWarning("No TURN servers configured."),this.skip(),await new Promise((e=>setTimeout(e,0))))}}class WebRTCCheck extends Checker{get description(){return"Establishing WebRTC connection"}async perform(){try{console.log("initiating room connection"),this.room=await this.connect(),console.log("now the room is connected")}catch(e){throw this.appendWarning("ports need to be open on firewall in order to connect."),e}}}class WebSocketCheck extends Checker{get description(){return"Connecting to signal connection via WebSocket"}async perform(){(this.url.startsWith("ws:")||this.url.startsWith("http:"))&&this.appendWarning("Server is insecure, clients may block connections to it");let e=new SignalClient;const t=await e.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0});this.appendMessage("Connected to server, version ".concat(t.serverVersion,".")),await e.close()}}class ConnectionCheck extends pi{constructor(e,t){super(),this.checkResults=new Map,this.url=e,this.token=t}getNextCheckId(){const e=this.checkResults.size;return this.checkResults.set(e,{logs:[],status:nn.IDLE,name:"",description:""}),e}updateCheck(e,t){this.checkResults.set(e,t),this.emit("checkUpdate",e,t)}isSuccess(){return Array.from(this.checkResults.values()).every((e=>e.status!==nn.FAILED))}getResults(){return Array.from(this.checkResults.values())}async createAndRunCheck(e){const t=this.getNextCheckId(),i=new e(this.url,this.token),handleUpdate=e=>{this.updateCheck(t,e)};i.on("update",handleUpdate);const n=await i.run();return i.off("update",handleUpdate),n}async checkWebsocket(){return this.createAndRunCheck(WebSocketCheck)}async checkWebRTC(){return this.createAndRunCheck(WebRTCCheck)}async checkTURN(){return this.createAndRunCheck(TURNCheck)}async checkReconnect(){return this.createAndRunCheck(ReconnectCheck)}async checkPublishAudio(){return this.createAndRunCheck(PublishAudioCheck)}async checkPublishVideo(){return this.createAndRunCheck(PublishVideoCheck)}}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);uCi,ConnectionCheck:()=>ConnectionCheck,ConnectionError:()=>ConnectionError,ConnectionQuality:()=>Oi,ConnectionState:()=>rr,CriticalTimers:()=>CriticalTimers,DataPacket_Kind:()=>Ae,DefaultReconnectPolicy:()=>DefaultReconnectPolicy,DeviceUnsupportedError:()=>DeviceUnsupportedError,DisconnectReason:()=>Ie,EngineEvent:()=>ti,LivekitError:()=>LivekitError,LocalAudioTrack:()=>LocalAudioTrack,LocalParticipant:()=>LocalParticipant,LocalTrack:()=>LocalTrack,LocalTrackPublication:()=>LocalTrackPublication,LocalVideoTrack:()=>LocalVideoTrack,LogLevel:()=>u,MediaDeviceFailure:()=>Yt,NegotiationError:()=>NegotiationError,Participant:()=>Participant,ParticipantEvent:()=>ei,PublishDataError:()=>PublishDataError,RemoteAudioTrack:()=>RemoteAudioTrack,RemoteParticipant:()=>RemoteParticipant,RemoteTrack:()=>RemoteTrack,RemoteTrackPublication:()=>RemoteTrackPublication,RemoteVideoTrack:()=>RemoteVideoTrack,Room:()=>Room,RoomEvent:()=>Xt,RoomState:()=>nr,ScreenSharePresets:()=>Ri,Track:()=>Track,TrackEvent:()=>ii,TrackInvalidError:()=>TrackInvalidError,TrackPublication:()=>TrackPublication,UnexpectedConnectionState:()=>UnexpectedConnectionState,UnsupportedServer:()=>UnsupportedServer,VideoPreset:()=>VideoPreset,VideoPresets:()=>Pi,VideoPresets43:()=>Ei,VideoQuality:()=>Re,attachToElement:()=>attachToElement,createAudioAnalyser:()=>createAudioAnalyser,createLocalAudioTrack:()=>createLocalAudioTrack,createLocalScreenTracks:()=>createLocalScreenTracks,createLocalTracks:()=>createLocalTracks,createLocalVideoTrack:()=>createLocalVideoTrack,detachTrack:()=>detachTrack,getEmptyAudioStreamTrack:()=>getEmptyAudioStreamTrack,getEmptyVideoStreamTrack:()=>getEmptyVideoStreamTrack,isBackupCodec:()=>isBackupCodec,isBrowserSupported:()=>isBrowserSupported,protocolVersion:()=>ci,setLogExtension:()=>setLogExtension,setLogLevel:()=>setLogLevel,supportsAV1:()=>supportsAV1,supportsAdaptiveStream:()=>supportsAdaptiveStream,supportsDynacast:()=>supportsDynacast,version:()=>oi});var s="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function getDefaultExportFromCjs(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var a,o,c,u,l={};o=s,c=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(),c=n>=o&&n{i?a(t,i):a(t),c&&e(n,t,i)}},h.setLevel(h.getLevel())}h.setLevel(u.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:T;if(t){if(e<0)return C;if(e>=k)return N}else{if(e<=-y)return I;if(e+1>=y)return O}return e<0?fromNumber(-e,t).neg():fromBits(e%S|0,e/S|0,t)}function fromBits(e,t,i){return new Long(e,t,i)}Long.fromInt=fromInt,Long.fromNumber=fromNumber,Long.fromBits=fromBits;var b=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 T;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(b(i,8)),a=T,o=0;o>>0:this.low},D.toNumber=function toNumber(){return this.unsigned?(this.high>>>0)*S+(this.low>>>0):this.high*S+(this.low>>>0)},D.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}},D.getHighBits=function getHighBits(){return this.high},D.getHighBitsUnsigned=function getHighBitsUnsigned(){return this.high>>>0},D.getLowBits=function getLowBits(){return this.low},D.getLowBitsUnsigned=function getLowBitsUnsigned(){return this.low>>>0},D.getNumBitsAbs=function getNumBitsAbs(){if(this.isNegative())return this.eq(I)?64:this.neg().getNumBitsAbs();for(var e=0!=this.high?this.high:this.low,t=31;t>0&&0==(e&1<=0},D.isOdd=function isOdd(){return 1==(1&this.low)},D.isEven=function isEven(){return 0==(1&this.low)},D.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)},D.eq=D.equals,D.notEquals=function notEquals(e){return!this.eq(e)},D.neq=D.notEquals,D.ne=D.notEquals,D.lessThan=function lessThan(e){return this.comp(e)<0},D.lt=D.lessThan,D.lessThanOrEqual=function lessThanOrEqual(e){return this.comp(e)<=0},D.lte=D.lessThanOrEqual,D.le=D.lessThanOrEqual,D.greaterThan=function greaterThan(e){return this.comp(e)>0},D.gt=D.greaterThan,D.greaterThanOrEqual=function greaterThanOrEqual(e){return this.comp(e)>=0},D.gte=D.greaterThanOrEqual,D.ge=D.greaterThanOrEqual,D.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},D.comp=D.compare,D.negate=function negate(){return!this.unsigned&&this.eq(I)?I:this.not().add(P)},D.neg=D.negate,D.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)},D.subtract=function subtract(e){return isLong(e)||(e=fromValue(e)),this.add(e.neg())},D.sub=D.subtract,D.multiply=function multiply(e){if(this.isZero())return T;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 T;if(this.eq(I))return e.isOdd()?I:T;if(e.eq(I))return this.isOdd()?I:T;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(w)&&e.lt(w))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)},D.mul=D.multiply,D.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:T;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(I))return e.eq(P)||e.eq(R)?I:e.eq(I)?P:(t=this.shr(1).div(e).shl(1)).eq(T)?e.isNegative()?P:R:(i=this.sub(e.mul(t)),n=t.add(i.div(e)));if(e.eq(I))return this.unsigned?C:T;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=T}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:b(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},D.div=D.divide,D.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))},D.mod=D.modulo,D.rem=D.modulo,D.not=function not(){return fromBits(~this.low,~this.high,this.unsigned)},D.and=function and(e){return isLong(e)||(e=fromValue(e)),fromBits(this.low&e.low,this.high&e.high,this.unsigned)},D.or=function or(e){return isLong(e)||(e=fromValue(e)),fromBits(this.low|e.low,this.high|e.high,this.unsigned)},D.xor=function xor(e){return isLong(e)||(e=fromValue(e)),fromBits(this.low^e.low,this.high^e.high,this.unsigned)},D.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)},D.shr=D.shiftRight,D.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)},D.shru=D.shiftRightUnsigned,D.shr_u=D.shiftRightUnsigned,D.toSigned=function toSigned(){return this.unsigned?fromBits(this.low,this.high,!1):this},D.toUnsigned=function toUnsigned(){return this.unsigned?this:fromBits(this.low,this.high,!0)},D.toBytes=function toBytes(e){return e?this.toBytesLE():this.toBytesBE()},D.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]},D.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 _,L,A={},U={get exports(){return A},set exports(e){A=e}},M={},x={};var $,B,F,J,V,j,W,q={};var G,Q,z,H,Z,K,Y={};function requireMinimal(){return K||(K=1,function(e){var t=e;function merge(e,t,i){for(var n=Object.keys(t),s=0;se,set:void 0,enumerable:!1,configurable:!0},toString:{value(){return this.name+": "+this.message},writable:!0,enumerable:!1,configurable:!0}}),CustomError}t.asPromise=function requireAspromise(){return L||(L=1,_=function asPromise(e,t){for(var i=new Array(arguments.length-1),n=0,s=2,a=!0;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)}}(q)),q}(),t.EventEmitter=function requireEventemitter(){if(F)return B;function EventEmitter(){this._listeners={}}return F=1,B=EventEmitter,EventEmitter.prototype.on=function on(e,t,i){return(this._listeners[e]||(this._listeners[e]=[])).push({fn:t,ctx:i||this}),this},EventEmitter.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}return V=1,J=factory(factory)}(),t.inquire=function requireInquire(){return W?j:(W=1,j=function inquire(e){try{}catch(e){}return null})}(),t.utf8=function requireUtf8(){return G||(G=1,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}}(Y)),Y}(),t.pool=function requirePool(){return z?Q:(z=1,Q=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}})}(),t.LongBits=function requireLongbits(){if(Z)return H;Z=1,H=LongBits;var e=requireMinimal();function LongBits(e,t){this.lo=e>>>0,this.hi=t>>>0}var t=LongBits.zero=new LongBits(0,0);t.toNumber=function(){return 0},t.zzEncode=t.zzDecode=function(){return this},t.length=function(){return 1};var i=LongBits.zeroHash="\0\0\0\0\0\0\0\0";LongBits.fromNumber=function fromNumber(e){if(0===e)return t;var i=e<0;i&&(e=-e);var n=e>>>0,s=(e-n)/4294967296>>>0;return i&&(s=~s>>>0,n=~n>>>0,++n>4294967295&&(n=0,++s>4294967295&&(s=0))),new LongBits(n,s)},LongBits.from=function from(i){if("number"==typeof i)return LongBits.fromNumber(i);if(e.isString(i)){if(!e.Long)return LongBits.fromNumber(parseInt(i,10));i=e.Long.fromString(i)}return i.low||i.high?new LongBits(i.low>>>0,i.high>>>0):t},LongBits.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.prototype.toLong=function toLong(t){return e.Long?new e.Long(0|this.lo,0|this.hi,Boolean(t)):{low:0|this.lo,high:0|this.hi,unsigned:Boolean(t)}};var n=String.prototype.charCodeAt;return LongBits.fromHash=function fromHash(e){return e===i?t:new LongBits((n.call(e,0)|n.call(e,1)<<8|n.call(e,2)<<16|n.call(e,3)<<24)>>>0,(n.call(e,4)|n.call(e,5)<<8|n.call(e,6)<<16|n.call(e,7)<<24)>>>0)},LongBits.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.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.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.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},H}(),t.isNode=Boolean(void 0!==s&&s&&s.process&&s.process.versions&&s.process.versions.node),t.global=t.isNode&&s||"undefined"!=typeof window&&window||"undefined"!=typeof self&&self||s,t.emptyArray=Object.freeze?Object.freeze([]):[],t.emptyObject=Object.freeze?Object.freeze({}):{},t.isInteger=Number.isInteger||function isInteger(e){return"number"==typeof e&&isFinite(e)&&Math.floor(e)===e},t.isString=function isString(e){return"string"==typeof e||e instanceof String},t.isObject=function isObject(e){return e&&"object"==typeof e},t.isset=t.isSet=function isSet(e,t){var i=e[t];return!(null==i||!e.hasOwnProperty(t))&&("object"!=typeof i||(Array.isArray(i)?i.length:Object.keys(i).length)>0)},t.Buffer=function(){try{var e=t.inquire("buffer").Buffer;return e.prototype.utf8Write?e:null}catch(e){return null}}(),t._Buffer_from=null,t._Buffer_allocUnsafe=null,t.newBuffer=function 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=se(),Writer$1.alloc=function alloc(e){return new te.Array(e)},te.Array!==Array&&(Writer$1.alloc=te.pool(Writer$1.alloc,te.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,ie.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=ie.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=ie.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=ie.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(te.float.writeFloatLE,4,e)},Writer$1.prototype.double=function write_double(e){return this._push(te.float.writeDoubleLE,8,e)};var ae=te.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(te.isString(e)){var i=Writer$1.alloc(t=re.length(e));re.decode(e,i,0),e=i}return this.uint32(t)._push(ae,t,e)},Writer$1.prototype.string=function write_string(e){var t=ne.length(e);return t?this.uint32(t)._push(ne.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){X=e,Writer$1.create=se(),X._configure()};var oe=BufferWriter,ce=ee;(BufferWriter.prototype=Object.create(ce.prototype)).constructor=BufferWriter;var de=requireMinimal();function BufferWriter(){ce.call(this)}function writeStringBuffer(e,t,i){e.length<40?de.utf8.write(e,t,i):t.utf8Write?t.utf8Write(e,i):t.write(e,i)}BufferWriter._configure=function(){BufferWriter.alloc=de._Buffer_allocUnsafe,BufferWriter.writeBytesBuffer=de.Buffer&&de.Buffer.prototype instanceof Uint8Array&&"set"===de.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=de.Buffer.byteLength(e);return this.uint32(t),t&&this._push(writeStringBuffer,t,e),this},BufferWriter._configure();var ue,le=Reader$1,he=requireMinimal(),pe=he.LongBits,me=he.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 fe="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")},ve=function create(){return he.Buffer?function create_buffer_setup(e){return(Reader$1.create=function create_buffer(e){return he.Buffer.isBuffer(e)?new ue(e):fe(e)})(e)}:fe};function readLongVarint(){var e=new pe(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 pe(readFixed32_end(this.buf,this.pos+=4),readFixed32_end(this.buf,this.pos+=4))}Reader$1.create=ve(),Reader$1.prototype._slice=he.Array.prototype.subarray||he.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=he.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=he.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 me.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){ue=e,Reader$1.create=ve(),ue._configure();var t=he.Long?"toLong":"toNumber";he.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 ge=BufferReader,be=le;(BufferReader.prototype=Object.create(be.prototype)).constructor=BufferReader;var Se=requireMinimal();function BufferReader(e){be.call(this,e)}BufferReader._configure=function(){Se.Buffer&&(BufferReader.prototype._slice=Se.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 ke,ye={},we=Service,Te=requireMinimal();function Service(e,t,i){if("function"!=typeof e)throw TypeError("rpcImpl must be a function");Te.EventEmitter.call(this),this.rpcImpl=e,this.requestDelimited=Boolean(t),this.responseDelimited=Boolean(i)}(Service.prototype=Object.create(Te.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 Te.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},ke=ye,ke.Service=we;var Ce={};!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=ee,t.BufferWriter=oe,t.Reader=le,t.BufferReader=ge,t.util=requireMinimal(),t.rpc=ye,t.roots=Ce,t.configure=configure,configure()}(M),function(e){e.exports=M}(U);var Pe,Ee,Re,Oe,Ne,Ie,De,_e,Le,Ae,Ue,Me,xe=getDefaultExportFromCjs(A);function trackTypeFromJSON(e){switch(e){case 0:case"AUDIO":return Pe.AUDIO;case 1:case"VIDEO":return Pe.VIDEO;case 2:case"DATA":return Pe.DATA;default:return Pe.UNRECOGNIZED}}function trackTypeToJSON(e){switch(e){case Pe.AUDIO:return"AUDIO";case Pe.VIDEO:return"VIDEO";case Pe.DATA:return"DATA";case Pe.UNRECOGNIZED:default:return"UNRECOGNIZED"}}function trackSourceFromJSON(e){switch(e){case 0:case"UNKNOWN":return Ee.UNKNOWN;case 1:case"CAMERA":return Ee.CAMERA;case 2:case"MICROPHONE":return Ee.MICROPHONE;case 3:case"SCREEN_SHARE":return Ee.SCREEN_SHARE;case 4:case"SCREEN_SHARE_AUDIO":return Ee.SCREEN_SHARE_AUDIO;default:return Ee.UNRECOGNIZED}}function trackSourceToJSON(e){switch(e){case Ee.UNKNOWN:return"UNKNOWN";case Ee.CAMERA:return"CAMERA";case Ee.MICROPHONE:return"MICROPHONE";case Ee.SCREEN_SHARE:return"SCREEN_SHARE";case Ee.SCREEN_SHARE_AUDIO:return"SCREEN_SHARE_AUDIO";case Ee.UNRECOGNIZED:default:return"UNRECOGNIZED"}}function videoQualityFromJSON(e){switch(e){case 0:case"LOW":return Re.LOW;case 1:case"MEDIUM":return Re.MEDIUM;case 2:case"HIGH":return Re.HIGH;case 3:case"OFF":return Re.OFF;default:return Re.UNRECOGNIZED}}function videoQualityToJSON(e){switch(e){case Re.LOW:return"LOW";case Re.MEDIUM:return"MEDIUM";case Re.HIGH:return"HIGH";case Re.OFF:return"OFF";case Re.UNRECOGNIZED:default:return"UNRECOGNIZED"}}function connectionQualityFromJSON(e){switch(e){case 0:case"POOR":return Oe.POOR;case 1:case"GOOD":return Oe.GOOD;case 2:case"EXCELLENT":return Oe.EXCELLENT;default:return Oe.UNRECOGNIZED}}function clientConfigSettingFromJSON(e){switch(e){case 0:case"UNSET":return Ne.UNSET;case 1:case"DISABLED":return Ne.DISABLED;case 2:case"ENABLED":return Ne.ENABLED;default:return Ne.UNRECOGNIZED}}function clientConfigSettingToJSON(e){switch(e){case Ne.UNSET:return"UNSET";case Ne.DISABLED:return"DISABLED";case Ne.ENABLED:return"ENABLED";case Ne.UNRECOGNIZED:default:return"UNRECOGNIZED"}}function disconnectReasonFromJSON(e){switch(e){case 0:case"UNKNOWN_REASON":return Ie.UNKNOWN_REASON;case 1:case"CLIENT_INITIATED":return Ie.CLIENT_INITIATED;case 2:case"DUPLICATE_IDENTITY":return Ie.DUPLICATE_IDENTITY;case 3:case"SERVER_SHUTDOWN":return Ie.SERVER_SHUTDOWN;case 4:case"PARTICIPANT_REMOVED":return Ie.PARTICIPANT_REMOVED;case 5:case"ROOM_DELETED":return Ie.ROOM_DELETED;case 6:case"STATE_MISMATCH":return Ie.STATE_MISMATCH;case 7:case"JOIN_FAILURE":return Ie.JOIN_FAILURE;default:return Ie.UNRECOGNIZED}}function participantInfo_StateFromJSON(e){switch(e){case 0:case"JOINING":return _e.JOINING;case 1:case"JOINED":return _e.JOINED;case 2:case"ACTIVE":return _e.ACTIVE;case 3:case"DISCONNECTED":return _e.DISCONNECTED;default:return _e.UNRECOGNIZED}}function encryption_TypeFromJSON(e){switch(e){case 0:case"NONE":return Le.NONE;case 1:case"GCM":return Le.GCM;case 2:case"CUSTOM":return Le.CUSTOM;default:return Le.UNRECOGNIZED}}function encryption_TypeToJSON(e){switch(e){case Le.NONE:return"NONE";case Le.GCM:return"GCM";case Le.CUSTOM:return"CUSTOM";case Le.UNRECOGNIZED:default:return"UNRECOGNIZED"}}function dataPacket_KindFromJSON(e){switch(e){case 0:case"RELIABLE":return Ae.RELIABLE;case 1:case"LOSSY":return Ae.LOSSY;default:return Ae.UNRECOGNIZED}}function serverInfo_EditionFromJSON(e){switch(e){case 0:case"Standard":return Ue.Standard;case 1:case"Cloud":return Ue.Cloud;default:return Ue.UNRECOGNIZED}}function clientInfo_SDKFromJSON(e){switch(e){case 0:case"UNKNOWN":return Me.UNKNOWN;case 1:case"JS":return Me.JS;case 2:case"SWIFT":return Me.SWIFT;case 3:case"ANDROID":return Me.ANDROID;case 4:case"FLUTTER":return Me.FLUTTER;case 5:case"GO":return Me.GO;case 6:case"UNITY":return Me.UNITY;default:return Me.UNRECOGNIZED}}(()=>{if("undefined"!=typeof globalThis)return globalThis;if("undefined"!=typeof self)return self;if("undefined"!=typeof window)return window;if("undefined"!=typeof global)return global;throw"Unable to locate global object"})(),xe.util.Long!==p&&(xe.util.Long=p,xe.configure()),function(e){e[e.AUDIO=0]="AUDIO",e[e.VIDEO=1]="VIDEO",e[e.DATA=2]="DATA",e[e.UNRECOGNIZED=-1]="UNRECOGNIZED"}(Pe||(Pe={})),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"}(Ee||(Ee={})),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"}(Re||(Re={})),function(e){e[e.POOR=0]="POOR",e[e.GOOD=1]="GOOD",e[e.EXCELLENT=2]="EXCELLENT",e[e.UNRECOGNIZED=-1]="UNRECOGNIZED"}(Oe||(Oe={})),function(e){e[e.UNSET=0]="UNSET",e[e.DISABLED=1]="DISABLED",e[e.ENABLED=2]="ENABLED",e[e.UNRECOGNIZED=-1]="UNRECOGNIZED"}(Ne||(Ne={})),function(e){e[e.UNKNOWN_REASON=0]="UNKNOWN_REASON",e[e.CLIENT_INITIATED=1]="CLIENT_INITIATED",e[e.DUPLICATE_IDENTITY=2]="DUPLICATE_IDENTITY",e[e.SERVER_SHUTDOWN=3]="SERVER_SHUTDOWN",e[e.PARTICIPANT_REMOVED=4]="PARTICIPANT_REMOVED",e[e.ROOM_DELETED=5]="ROOM_DELETED",e[e.STATE_MISMATCH=6]="STATE_MISMATCH",e[e.JOIN_FAILURE=7]="JOIN_FAILURE",e[e.UNRECOGNIZED=-1]="UNRECOGNIZED"}(Ie||(Ie={})),function(e){e[e.RR_UNKOWN=0]="RR_UNKOWN",e[e.RR_SIGNAL_DISCONNECTED=1]="RR_SIGNAL_DISCONNECTED",e[e.RR_PUBLISHER_FAILED=2]="RR_PUBLISHER_FAILED",e[e.RR_SUBSCRIBER_FAILED=3]="RR_SUBSCRIBER_FAILED",e[e.RR_SWITCH_CANDIDATE=4]="RR_SWITCH_CANDIDATE",e[e.UNRECOGNIZED=-1]="UNRECOGNIZED"}(De||(De={})),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"}(_e||(_e={})),function(e){e[e.NONE=0]="NONE",e[e.GCM=1]="GCM",e[e.CUSTOM=2]="CUSTOM",e[e.UNRECOGNIZED=-1]="UNRECOGNIZED"}(Le||(Le={})),function(e){e[e.RELIABLE=0]="RELIABLE",e[e.LOSSY=1]="LOSSY",e[e.UNRECOGNIZED=-1]="UNRECOGNIZED"}(Ae||(Ae={})),function(e){e[e.Standard=0]="Standard",e[e.Cloud=1]="Cloud",e[e.UNRECOGNIZED=-1]="UNRECOGNIZED"}(Ue||(Ue={})),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"}(Me||(Me={}));const $e={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xe.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)Be.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 xe.Reader?e:new xe.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$1(i.int64());break;case 6:s.turnPassword=i.string();break;case 7:s.enabledCodecs.push(Be.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=>Be.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?Be.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},create:e=>$e.fromPartial(null!=e?e:{}),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=>Be.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 Be={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xe.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 xe.Reader?e:new xe.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},create:e=>Be.fromPartial(null!=e?e:{}),fromPartial(e){var t,i;const n={mime:"",fmtpLine:""};return n.mime=null!==(t=e.mime)&&void 0!==t?t:"",n.fmtpLine=null!==(i=e.fmtpLine)&&void 0!==i?i:"",n}};const Fe={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xe.Writer.create();!0===e.canSubscribe&&t.uint32(8).bool(e.canSubscribe),!0===e.canPublish&&t.uint32(16).bool(e.canPublish),!0===e.canPublishData&&t.uint32(24).bool(e.canPublishData),t.uint32(74).fork();for(const i of e.canPublishSources)t.int32(i);return t.ldelim(),!0===e.hidden&&t.uint32(56).bool(e.hidden),!0===e.recorder&&t.uint32(64).bool(e.recorder),t},decode(e,t){const i=e instanceof xe.Reader?e:new xe.Reader(e);let n=void 0===t?i.len:i.pos+t;const s={canSubscribe:!1,canPublish:!1,canPublishData:!1,canPublishSources:[],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 9:if(2==(7&e)){const e=i.uint32()+i.pos;for(;i.pos({canSubscribe:!!isSet$1(e.canSubscribe)&&Boolean(e.canSubscribe),canPublish:!!isSet$1(e.canPublish)&&Boolean(e.canPublish),canPublishData:!!isSet$1(e.canPublishData)&&Boolean(e.canPublishData),canPublishSources:Array.isArray(null==e?void 0:e.canPublishSources)?e.canPublishSources.map((e=>trackSourceFromJSON(e))):[],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),e.canPublishSources?t.canPublishSources=e.canPublishSources.map((e=>trackSourceToJSON(e))):t.canPublishSources=[],void 0!==e.hidden&&(t.hidden=e.hidden),void 0!==e.recorder&&(t.recorder=e.recorder),t},create:e=>Fe.fromPartial(null!=e?e:{}),fromPartial(e){var t,i,n,s,a,o;const c={canSubscribe:!1,canPublish:!1,canPublishData:!1,canPublishSources:[],hidden:!1,recorder:!1};return c.canSubscribe=null!==(t=e.canSubscribe)&&void 0!==t&&t,c.canPublish=null!==(i=e.canPublish)&&void 0!==i&&i,c.canPublishData=null!==(n=e.canPublishData)&&void 0!==n&&n,c.canPublishSources=(null===(s=e.canPublishSources)||void 0===s?void 0:s.map((e=>e)))||[],c.hidden=null!==(a=e.hidden)&&void 0!==a&&a,c.recorder=null!==(o=e.recorder)&&void 0!==o&&o,c}};const Je={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xe.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)je.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&&Fe.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 xe.Reader?e:new xe.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(je.decode(i,i.uint32()));break;case 5:s.metadata=i.string();break;case 6:s.joinedAt=longToNumber$1(i.int64());break;case 9:s.name=i.string();break;case 10:s.version=i.uint32();break;case 11:s.permission=Fe.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=>je.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)?Fe.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 _e.JOINING:return"JOINING";case _e.JOINED:return"JOINED";case _e.ACTIVE:return"ACTIVE";case _e.DISCONNECTED:return"DISCONNECTED";case _e.UNRECOGNIZED:default:return"UNRECOGNIZED"}}(e.state)),e.tracks?t.tracks=e.tracks.map((e=>e?je.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?Fe.toJSON(e.permission):void 0),void 0!==e.region&&(t.region=e.region),void 0!==e.isPublisher&&(t.isPublisher=e.isPublisher),t},create:e=>Je.fromPartial(null!=e?e:{}),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=>je.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?Fe.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 Ve={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xe.Writer.create();""!==e.mimeType&&t.uint32(10).string(e.mimeType),""!==e.mid&&t.uint32(18).string(e.mid),""!==e.cid&&t.uint32(26).string(e.cid);for(const i of e.layers)We.encode(i,t.uint32(34).fork()).ldelim();return t},decode(e,t){const i=e instanceof xe.Reader?e:new xe.Reader(e);let n=void 0===t?i.len:i.pos+t;const s={mimeType:"",mid:"",cid:"",layers:[]};for(;i.pos>>3){case 1:s.mimeType=i.string();break;case 2:s.mid=i.string();break;case 3:s.cid=i.string();break;case 4:s.layers.push(We.decode(i,i.uint32()));break;default:i.skipType(7&e)}}return s},fromJSON:e=>({mimeType:isSet$1(e.mimeType)?String(e.mimeType):"",mid:isSet$1(e.mid)?String(e.mid):"",cid:isSet$1(e.cid)?String(e.cid):"",layers:Array.isArray(null==e?void 0:e.layers)?e.layers.map((e=>We.fromJSON(e))):[]}),toJSON(e){const t={};return void 0!==e.mimeType&&(t.mimeType=e.mimeType),void 0!==e.mid&&(t.mid=e.mid),void 0!==e.cid&&(t.cid=e.cid),e.layers?t.layers=e.layers.map((e=>e?We.toJSON(e):void 0)):t.layers=[],t},create:e=>Ve.fromPartial(null!=e?e:{}),fromPartial(e){var t,i,n,s;const a={mimeType:"",mid:"",cid:"",layers:[]};return a.mimeType=null!==(t=e.mimeType)&&void 0!==t?t:"",a.mid=null!==(i=e.mid)&&void 0!==i?i:"",a.cid=null!==(n=e.cid)&&void 0!==n?n:"",a.layers=(null===(s=e.layers)||void 0===s?void 0:s.map((e=>We.fromPartial(e))))||[],a}};const je={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xe.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)We.encode(i,t.uint32(82).fork()).ldelim();""!==e.mimeType&&t.uint32(90).string(e.mimeType),""!==e.mid&&t.uint32(98).string(e.mid);for(const i of e.codecs)Ve.encode(i,t.uint32(106).fork()).ldelim();return!0===e.stereo&&t.uint32(112).bool(e.stereo),!0===e.disableRed&&t.uint32(120).bool(e.disableRed),0!==e.encryption&&t.uint32(128).int32(e.encryption),t},decode(e,t){const i=e instanceof xe.Reader?e:new xe.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:"",codecs:[],stereo:!1,disableRed:!1,encryption:0};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(We.decode(i,i.uint32()));break;case 11:s.mimeType=i.string();break;case 12:s.mid=i.string();break;case 13:s.codecs.push(Ve.decode(i,i.uint32()));break;case 14:s.stereo=i.bool();break;case 15:s.disableRed=i.bool();break;case 16:s.encryption=i.int32();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=>We.fromJSON(e))):[],mimeType:isSet$1(e.mimeType)?String(e.mimeType):"",mid:isSet$1(e.mid)?String(e.mid):"",codecs:Array.isArray(null==e?void 0:e.codecs)?e.codecs.map((e=>Ve.fromJSON(e))):[],stereo:!!isSet$1(e.stereo)&&Boolean(e.stereo),disableRed:!!isSet$1(e.disableRed)&&Boolean(e.disableRed),encryption:isSet$1(e.encryption)?encryption_TypeFromJSON(e.encryption):0}),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?We.toJSON(e):void 0)):t.layers=[],void 0!==e.mimeType&&(t.mimeType=e.mimeType),void 0!==e.mid&&(t.mid=e.mid),e.codecs?t.codecs=e.codecs.map((e=>e?Ve.toJSON(e):void 0)):t.codecs=[],void 0!==e.stereo&&(t.stereo=e.stereo),void 0!==e.disableRed&&(t.disableRed=e.disableRed),void 0!==e.encryption&&(t.encryption=encryption_TypeToJSON(e.encryption)),t},create:e=>je.fromPartial(null!=e?e:{}),fromPartial(e){var t,i,n,s,a,o,c,u,l,h,p,m,v,g,b,S;const k={sid:"",type:0,name:"",muted:!1,width:0,height:0,simulcast:!1,disableDtx:!1,source:0,layers:[],mimeType:"",mid:"",codecs:[],stereo:!1,disableRed:!1,encryption:0};return k.sid=null!==(t=e.sid)&&void 0!==t?t:"",k.type=null!==(i=e.type)&&void 0!==i?i:0,k.name=null!==(n=e.name)&&void 0!==n?n:"",k.muted=null!==(s=e.muted)&&void 0!==s&&s,k.width=null!==(a=e.width)&&void 0!==a?a:0,k.height=null!==(o=e.height)&&void 0!==o?o:0,k.simulcast=null!==(c=e.simulcast)&&void 0!==c&&c,k.disableDtx=null!==(u=e.disableDtx)&&void 0!==u&&u,k.source=null!==(l=e.source)&&void 0!==l?l:0,k.layers=(null===(h=e.layers)||void 0===h?void 0:h.map((e=>We.fromPartial(e))))||[],k.mimeType=null!==(p=e.mimeType)&&void 0!==p?p:"",k.mid=null!==(m=e.mid)&&void 0!==m?m:"",k.codecs=(null===(v=e.codecs)||void 0===v?void 0:v.map((e=>Ve.fromPartial(e))))||[],k.stereo=null!==(g=e.stereo)&&void 0!==g&&g,k.disableRed=null!==(b=e.disableRed)&&void 0!==b&&b,k.encryption=null!==(S=e.encryption)&&void 0!==S?S:0,k}};const We={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xe.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 xe.Reader?e:new xe.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},create:e=>We.fromPartial(null!=e?e:{}),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 qe={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xe.Writer.create();var i;switch(0!==e.kind&&t.uint32(8).int32(e.kind),null===(i=e.value)||void 0===i?void 0:i.$case){case"user":ze.encode(e.value.user,t.uint32(18).fork()).ldelim();break;case"speaker":Ge.encode(e.value.speaker,t.uint32(26).fork()).ldelim()}return t},decode(e,t){const i=e instanceof xe.Reader?e:new xe.Reader(e);let n=void 0===t?i.len:i.pos+t;const s={kind:0,value:void 0};for(;i.pos>>3){case 1:s.kind=i.int32();break;case 2:s.value={$case:"user",user:ze.decode(i,i.uint32())};break;case 3:s.value={$case:"speaker",speaker:Ge.decode(i,i.uint32())};break;default:i.skipType(7&e)}}return s},fromJSON:e=>({kind:isSet$1(e.kind)?dataPacket_KindFromJSON(e.kind):0,value:isSet$1(e.user)?{$case:"user",user:ze.fromJSON(e.user)}:isSet$1(e.speaker)?{$case:"speaker",speaker:Ge.fromJSON(e.speaker)}:void 0}),toJSON(e){var t,i,n,s,a,o;const c={};return void 0!==e.kind&&(c.kind=function dataPacket_KindToJSON(e){switch(e){case Ae.RELIABLE:return"RELIABLE";case Ae.LOSSY:return"LOSSY";case Ae.UNRECOGNIZED:default:return"UNRECOGNIZED"}}(e.kind)),"user"===(null===(t=e.value)||void 0===t?void 0:t.$case)&&(c.user=(null===(i=e.value)||void 0===i?void 0:i.user)?ze.toJSON(null===(n=e.value)||void 0===n?void 0:n.user):void 0),"speaker"===(null===(s=e.value)||void 0===s?void 0:s.$case)&&(c.speaker=(null===(a=e.value)||void 0===a?void 0:a.speaker)?Ge.toJSON(null===(o=e.value)||void 0===o?void 0:o.speaker):void 0),c},create:e=>qe.fromPartial(null!=e?e:{}),fromPartial(e){var t,i,n,s,a,o,c;const u={kind:0,value:void 0};return u.kind=null!==(t=e.kind)&&void 0!==t?t:0,"user"===(null===(i=e.value)||void 0===i?void 0:i.$case)&&void 0!==(null===(n=e.value)||void 0===n?void 0:n.user)&&null!==(null===(s=e.value)||void 0===s?void 0:s.user)&&(u.value={$case:"user",user:ze.fromPartial(e.value.user)}),"speaker"===(null===(a=e.value)||void 0===a?void 0:a.$case)&&void 0!==(null===(o=e.value)||void 0===o?void 0:o.speaker)&&null!==(null===(c=e.value)||void 0===c?void 0:c.speaker)&&(u.value={$case:"speaker",speaker:Ge.fromPartial(e.value.speaker)}),u}};const Ge={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xe.Writer.create();for(const i of e.speakers)Qe.encode(i,t.uint32(10).fork()).ldelim();return t},decode(e,t){const i=e instanceof xe.Reader?e:new xe.Reader(e);let n=void 0===t?i.len:i.pos+t;const s={speakers:[]};for(;i.pos>>3==1)s.speakers.push(Qe.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=>Qe.fromJSON(e))):[]}),toJSON(e){const t={};return e.speakers?t.speakers=e.speakers.map((e=>e?Qe.toJSON(e):void 0)):t.speakers=[],t},create:e=>Ge.fromPartial(null!=e?e:{}),fromPartial(e){var t;const i={speakers:[]};return i.speakers=(null===(t=e.speakers)||void 0===t?void 0:t.map((e=>Qe.fromPartial(e))))||[],i}};const Qe={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xe.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 xe.Reader?e:new xe.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},create:e=>Qe.fromPartial(null!=e?e:{}),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:[],topic:void 0}}const ze={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xe.Writer.create();""!==e.participantSid&&t.uint32(10).string(e.participantSid),0!==e.payload.length&&t.uint32(18).bytes(e.payload);for(const i of e.destinationSids)t.uint32(26).string(i);return void 0!==e.topic&&t.uint32(34).string(e.topic),t},decode(e,t){const i=e instanceof xe.Reader?e:new xe.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;case 4:s.topic=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))):[],topic:isSet$1(e.topic)?String(e.topic):void 0}),toJSON(e){const t={};return void 0!==e.participantSid&&(t.participantSid=e.participantSid),void 0!==e.payload&&(t.payload=function base64FromBytes(e){if(tt.Buffer)return tt.Buffer.from(e).toString("base64");{const t=[];return e.forEach((e=>{t.push(String.fromCharCode(e))})),tt.btoa(t.join(""))}}(void 0!==e.payload?e.payload:new Uint8Array)),e.destinationSids?t.destinationSids=e.destinationSids.map((e=>e)):t.destinationSids=[],void 0!==e.topic&&(t.topic=e.topic),t},create:e=>ze.fromPartial(null!=e?e:{}),fromPartial(e){var t,i,n,s;const a=createBaseUserPacket();return a.participantSid=null!==(t=e.participantSid)&&void 0!==t?t:"",a.payload=null!==(i=e.payload)&&void 0!==i?i:new Uint8Array,a.destinationSids=(null===(n=e.destinationSids)||void 0===n?void 0:n.map((e=>e)))||[],a.topic=null!==(s=e.topic)&&void 0!==s?s:void 0,a}};const He={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xe.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 xe.Reader?e:new xe.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},create:e=>He.fromPartial(null!=e?e:{}),fromPartial(e){var t,i;const n={participantSid:"",trackSids:[]};return n.participantSid=null!==(t=e.participantSid)&&void 0!==t?t:"",n.trackSids=(null===(i=e.trackSids)||void 0===i?void 0:i.map((e=>e)))||[],n}};const Ze={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xe.Writer.create();return 0!==e.edition&&t.uint32(8).int32(e.edition),""!==e.version&&t.uint32(18).string(e.version),0!==e.protocol&&t.uint32(24).int32(e.protocol),""!==e.region&&t.uint32(34).string(e.region),""!==e.nodeId&&t.uint32(42).string(e.nodeId),""!==e.debugInfo&&t.uint32(50).string(e.debugInfo),t},decode(e,t){const i=e instanceof xe.Reader?e:new xe.Reader(e);let n=void 0===t?i.len:i.pos+t;const s={edition:0,version:"",protocol:0,region:"",nodeId:"",debugInfo:""};for(;i.pos>>3){case 1:s.edition=i.int32();break;case 2:s.version=i.string();break;case 3:s.protocol=i.int32();break;case 4:s.region=i.string();break;case 5:s.nodeId=i.string();break;case 6:s.debugInfo=i.string();break;default:i.skipType(7&e)}}return s},fromJSON:e=>({edition:isSet$1(e.edition)?serverInfo_EditionFromJSON(e.edition):0,version:isSet$1(e.version)?String(e.version):"",protocol:isSet$1(e.protocol)?Number(e.protocol):0,region:isSet$1(e.region)?String(e.region):"",nodeId:isSet$1(e.nodeId)?String(e.nodeId):"",debugInfo:isSet$1(e.debugInfo)?String(e.debugInfo):""}),toJSON(e){const t={};return void 0!==e.edition&&(t.edition=function serverInfo_EditionToJSON(e){switch(e){case Ue.Standard:return"Standard";case Ue.Cloud:return"Cloud";case Ue.UNRECOGNIZED:default:return"UNRECOGNIZED"}}(e.edition)),void 0!==e.version&&(t.version=e.version),void 0!==e.protocol&&(t.protocol=Math.round(e.protocol)),void 0!==e.region&&(t.region=e.region),void 0!==e.nodeId&&(t.nodeId=e.nodeId),void 0!==e.debugInfo&&(t.debugInfo=e.debugInfo),t},create:e=>Ze.fromPartial(null!=e?e:{}),fromPartial(e){var t,i,n,s,a,o;const c={edition:0,version:"",protocol:0,region:"",nodeId:"",debugInfo:""};return c.edition=null!==(t=e.edition)&&void 0!==t?t:0,c.version=null!==(i=e.version)&&void 0!==i?i:"",c.protocol=null!==(n=e.protocol)&&void 0!==n?n:0,c.region=null!==(s=e.region)&&void 0!==s?s:"",c.nodeId=null!==(a=e.nodeId)&&void 0!==a?a:"",c.debugInfo=null!==(o=e.debugInfo)&&void 0!==o?o:"",c}};const Ke={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xe.Writer.create();return 0!==e.sdk&&t.uint32(8).int32(e.sdk),""!==e.version&&t.uint32(18).string(e.version),0!==e.protocol&&t.uint32(24).int32(e.protocol),""!==e.os&&t.uint32(34).string(e.os),""!==e.osVersion&&t.uint32(42).string(e.osVersion),""!==e.deviceModel&&t.uint32(50).string(e.deviceModel),""!==e.browser&&t.uint32(58).string(e.browser),""!==e.browserVersion&&t.uint32(66).string(e.browserVersion),""!==e.address&&t.uint32(74).string(e.address),""!==e.network&&t.uint32(82).string(e.network),t},decode(e,t){const i=e instanceof xe.Reader?e:new xe.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:"",network:""};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;case 10:s.network=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):"",network:isSet$1(e.network)?String(e.network):""}),toJSON(e){const t={};return void 0!==e.sdk&&(t.sdk=function clientInfo_SDKToJSON(e){switch(e){case Me.UNKNOWN:return"UNKNOWN";case Me.JS:return"JS";case Me.SWIFT:return"SWIFT";case Me.ANDROID:return"ANDROID";case Me.FLUTTER:return"FLUTTER";case Me.GO:return"GO";case Me.UNITY:return"UNITY";case Me.UNRECOGNIZED:default:return"UNRECOGNIZED"}}(e.sdk)),void 0!==e.version&&(t.version=e.version),void 0!==e.protocol&&(t.protocol=Math.round(e.protocol)),void 0!==e.os&&(t.os=e.os),void 0!==e.osVersion&&(t.osVersion=e.osVersion),void 0!==e.deviceModel&&(t.deviceModel=e.deviceModel),void 0!==e.browser&&(t.browser=e.browser),void 0!==e.browserVersion&&(t.browserVersion=e.browserVersion),void 0!==e.address&&(t.address=e.address),void 0!==e.network&&(t.network=e.network),t},create:e=>Ke.fromPartial(null!=e?e:{}),fromPartial(e){var t,i,n,s,a,o,c,u,l,h;const p={sdk:0,version:"",protocol:0,os:"",osVersion:"",deviceModel:"",browser:"",browserVersion:"",address:"",network:""};return p.sdk=null!==(t=e.sdk)&&void 0!==t?t:0,p.version=null!==(i=e.version)&&void 0!==i?i:"",p.protocol=null!==(n=e.protocol)&&void 0!==n?n:0,p.os=null!==(s=e.os)&&void 0!==s?s:"",p.osVersion=null!==(a=e.osVersion)&&void 0!==a?a:"",p.deviceModel=null!==(o=e.deviceModel)&&void 0!==o?o:"",p.browser=null!==(c=e.browser)&&void 0!==c?c:"",p.browserVersion=null!==(u=e.browserVersion)&&void 0!==u?u:"",p.address=null!==(l=e.address)&&void 0!==l?l:"",p.network=null!==(h=e.network)&&void 0!==h?h:"",p}};const Ye={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xe.Writer.create();return void 0!==e.video&&Xe.encode(e.video,t.uint32(10).fork()).ldelim(),void 0!==e.screen&&Xe.encode(e.screen,t.uint32(18).fork()).ldelim(),0!==e.resumeConnection&&t.uint32(24).int32(e.resumeConnection),void 0!==e.disabledCodecs&&et.encode(e.disabledCodecs,t.uint32(34).fork()).ldelim(),0!==e.forceRelay&&t.uint32(40).int32(e.forceRelay),t},decode(e,t){const i=e instanceof xe.Reader?e:new xe.Reader(e);let n=void 0===t?i.len:i.pos+t;const s={video:void 0,screen:void 0,resumeConnection:0,disabledCodecs:void 0,forceRelay:0};for(;i.pos>>3){case 1:s.video=Xe.decode(i,i.uint32());break;case 2:s.screen=Xe.decode(i,i.uint32());break;case 3:s.resumeConnection=i.int32();break;case 4:s.disabledCodecs=et.decode(i,i.uint32());break;case 5:s.forceRelay=i.int32();break;default:i.skipType(7&e)}}return s},fromJSON:e=>({video:isSet$1(e.video)?Xe.fromJSON(e.video):void 0,screen:isSet$1(e.screen)?Xe.fromJSON(e.screen):void 0,resumeConnection:isSet$1(e.resumeConnection)?clientConfigSettingFromJSON(e.resumeConnection):0,disabledCodecs:isSet$1(e.disabledCodecs)?et.fromJSON(e.disabledCodecs):void 0,forceRelay:isSet$1(e.forceRelay)?clientConfigSettingFromJSON(e.forceRelay):0}),toJSON(e){const t={};return void 0!==e.video&&(t.video=e.video?Xe.toJSON(e.video):void 0),void 0!==e.screen&&(t.screen=e.screen?Xe.toJSON(e.screen):void 0),void 0!==e.resumeConnection&&(t.resumeConnection=clientConfigSettingToJSON(e.resumeConnection)),void 0!==e.disabledCodecs&&(t.disabledCodecs=e.disabledCodecs?et.toJSON(e.disabledCodecs):void 0),void 0!==e.forceRelay&&(t.forceRelay=clientConfigSettingToJSON(e.forceRelay)),t},create:e=>Ye.fromPartial(null!=e?e:{}),fromPartial(e){var t,i;const n={video:void 0,screen:void 0,resumeConnection:0,disabledCodecs:void 0,forceRelay:0};return n.video=void 0!==e.video&&null!==e.video?Xe.fromPartial(e.video):void 0,n.screen=void 0!==e.screen&&null!==e.screen?Xe.fromPartial(e.screen):void 0,n.resumeConnection=null!==(t=e.resumeConnection)&&void 0!==t?t:0,n.disabledCodecs=void 0!==e.disabledCodecs&&null!==e.disabledCodecs?et.fromPartial(e.disabledCodecs):void 0,n.forceRelay=null!==(i=e.forceRelay)&&void 0!==i?i:0,n}};const Xe={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xe.Writer.create();return 0!==e.hardwareEncoder&&t.uint32(8).int32(e.hardwareEncoder),t},decode(e,t){const i=e instanceof xe.Reader?e:new xe.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},create:e=>Xe.fromPartial(null!=e?e:{}),fromPartial(e){var t;const i={hardwareEncoder:0};return i.hardwareEncoder=null!==(t=e.hardwareEncoder)&&void 0!==t?t:0,i}};const et={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xe.Writer.create();for(const i of e.codecs)Be.encode(i,t.uint32(10).fork()).ldelim();return t},decode(e,t){const i=e instanceof xe.Reader?e:new xe.Reader(e);let n=void 0===t?i.len:i.pos+t;const s={codecs:[]};for(;i.pos>>3==1)s.codecs.push(Be.decode(i,i.uint32()));else i.skipType(7&e)}return s},fromJSON:e=>({codecs:Array.isArray(null==e?void 0:e.codecs)?e.codecs.map((e=>Be.fromJSON(e))):[]}),toJSON(e){const t={};return e.codecs?t.codecs=e.codecs.map((e=>e?Be.toJSON(e):void 0)):t.codecs=[],t},create:e=>et.fromPartial(null!=e?e:{}),fromPartial(e){var t;const i={codecs:[]};return i.codecs=(null===(t=e.codecs)||void 0===t?void 0:t.map((e=>Be.fromPartial(e))))||[],i}};var tt=(()=>{if("undefined"!=typeof globalThis)return globalThis;if("undefined"!=typeof self)return self;if("undefined"!=typeof window)return window;if("undefined"!=typeof global)return global;throw"Unable to locate global object"})();function bytesFromBase64(e){if(tt.Buffer)return Uint8Array.from(tt.Buffer.from(e,"base64"));{const t=tt.atob(e),i=new Uint8Array(t.length);for(let e=0;e=this._retryDelays.length)return null;const t=this._retryDelays[e.retryCount];return e.retryCount<=1?t:t+1e3*Math.random()}}function _asyncIterator(e){var t,i,n,s=2;for("undefined"!=typeof Symbol&&(i=Symbol.asyncIterator,n=Symbol.iterator);s--;){if(i&&null!=(t=e[i]))return t.call(e);if(n&&null!=(t=e[n]))return new AsyncFromSyncIterator(t.call(e));i="@@asyncIterator",n="@@iterator"}throw new TypeError("Object is not async iterable")}function AsyncFromSyncIterator(e){function AsyncFromSyncIteratorContinuation(e){if(Object(e)!==e)return Promise.reject(new TypeError(e+" is not an object."));var t=e.done;return Promise.resolve(e.value).then((function(e){return{value:e,done:t}}))}return AsyncFromSyncIterator=function(e){this.s=e,this.n=e.next},AsyncFromSyncIterator.prototype={s:null,n:null,next:function(){return AsyncFromSyncIteratorContinuation(this.n.apply(this.s,arguments))},return:function(e){var t=this.s.return;return void 0===t?Promise.resolve({value:e,done:!0}):AsyncFromSyncIteratorContinuation(t.apply(this.s,arguments))},throw:function(e){var t=this.s.return;return void 0===t?Promise.reject(e):AsyncFromSyncIteratorContinuation(t.apply(this.s,arguments))}},new AsyncFromSyncIterator(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;t=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."):(nt=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."):(st=!e,"adapter.js deprecation warnings "+(e?"disabled":"enabled"))}function log(){if("object"==typeof window){if(nt)return;"undefined"!=typeof console&&"function"==typeof console.log&&console.log.apply(console,arguments)}}function deprecated(e,t){st&&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 at=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),at("chrome: "+JSON.stringify(e)),n(e)}))}e.video=constraintsToChrome_(e.video)}return at("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 ot=Object.freeze({__proto__:null,fixNegotiationNeeded,shimAddTrackRemoveTrack,shimAddTrackRemoveTrackWithNative,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"))},shimGetSendersWithDtmf,shimGetStats,shimGetUserMedia:shimGetUserMedia$2,shimMediaStream,shimOnTrack:shimOnTrack$1,shimPeerConnection:shimPeerConnection$1,shimSenderReceiverGetStats});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 ct=Object.freeze({__proto__:null,shimAddTransceiver,shimCreateAnswer,shimCreateOffer,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)})},shimGetParameters,shimGetUserMedia:shimGetUserMedia$1,shimOnTrack,shimPeerConnection,shimRTCDataChannel,shimReceiverGetStats,shimRemoveStream,shimSenderGetStats});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 dt=Object.freeze({__proto__:null,shimAudioContext,shimCallbacksAPI,shimConstraints,shimCreateOfferLegacy,shimGetUserMedia,shimLocalStreamsAPI,shimRTCIceServerUrls,shimRemoteStreamsAPI,shimTrackEventTransceiver}),ut={};!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=lt.splitSections(e.sdp);return t.shift(),t.some((e=>{const t=lt.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=lt.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 pt,mt,ft,vt=Object.freeze({__proto__:null,removeExtmapAllowMixed,shimAddIceCandidateNullOrEmpty,shimConnectionState,shimMaxMessageSize,shimParameterlessSetLocalDescription,shimRTCIceCandidate,shimSendThrowTypeError});function signalTargetFromJSON(e){switch(e){case 0:case"PUBLISHER":return pt.PUBLISHER;case 1:case"SUBSCRIBER":return pt.SUBSCRIBER;default:return pt.UNRECOGNIZED}}function signalTargetToJSON(e){switch(e){case pt.PUBLISHER:return"PUBLISHER";case pt.SUBSCRIBER:return"SUBSCRIBER";case pt.UNRECOGNIZED:default:return"UNRECOGNIZED"}}function streamStateFromJSON(e){switch(e){case 0:case"ACTIVE":return mt.ACTIVE;case 1:case"PAUSED":return mt.PAUSED;default:return mt.UNRECOGNIZED}}function candidateProtocolFromJSON(e){switch(e){case 0:case"UDP":return ft.UDP;case 1:case"TCP":return ft.TCP;case 2:case"TLS":return ft.TLS;default:return ft.UNRECOGNIZED}}!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:vt,extractVersion,disableLog,disableWarnings,sdp:ht};switch(n.browser){case"chrome":if(!ot||!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=ot,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(!ct||!shimPeerConnection||!t.shimFirefox)return i("Firefox shim is not included in this adapter release."),s;i("adapter.js shimming firefox."),s.browserShim=ct,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(!dt||!t.shimSafari)return i("Safari shim is not included in this adapter release."),s;i("adapter.js shimming safari."),s.browserShim=dt,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}),function(e){e[e.PUBLISHER=0]="PUBLISHER",e[e.SUBSCRIBER=1]="SUBSCRIBER",e[e.UNRECOGNIZED=-1]="UNRECOGNIZED"}(pt||(pt={})),function(e){e[e.ACTIVE=0]="ACTIVE",e[e.PAUSED=1]="PAUSED",e[e.UNRECOGNIZED=-1]="UNRECOGNIZED"}(mt||(mt={})),function(e){e[e.UDP=0]="UDP",e[e.TCP=1]="TCP",e[e.TLS=2]="TLS",e[e.UNRECOGNIZED=-1]="UNRECOGNIZED"}(ft||(ft={}));const gt={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xe.Writer.create();var i;switch(null===(i=e.message)||void 0===i?void 0:i.$case){case"offer":Rt.encode(e.message.offer,t.uint32(10).fork()).ldelim();break;case"answer":Rt.encode(e.message.answer,t.uint32(18).fork()).ldelim();break;case"trickle":yt.encode(e.message.trickle,t.uint32(26).fork()).ldelim();break;case"addTrack":kt.encode(e.message.addTrack,t.uint32(34).fork()).ldelim();break;case"mute":wt.encode(e.message.mute,t.uint32(42).fork()).ldelim();break;case"subscription":Nt.encode(e.message.subscription,t.uint32(50).fork()).ldelim();break;case"trackSetting":It.encode(e.message.trackSetting,t.uint32(58).fork()).ldelim();break;case"leave":Dt.encode(e.message.leave,t.uint32(66).fork()).ldelim();break;case"updateLayers":_t.encode(e.message.updateLayers,t.uint32(82).fork()).ldelim();break;case"subscriptionPermission":qt.encode(e.message.subscriptionPermission,t.uint32(90).fork()).ldelim();break;case"syncState":Qt.encode(e.message.syncState,t.uint32(98).fork()).ldelim();break;case"simulate":Ht.encode(e.message.simulate,t.uint32(106).fork()).ldelim();break;case"ping":t.uint32(112).int64(e.message.ping);break;case"updateMetadata":Lt.encode(e.message.updateMetadata,t.uint32(122).fork()).ldelim();break;case"pingReq":Zt.encode(e.message.pingReq,t.uint32(130).fork()).ldelim()}return t},decode(e,t){const i=e instanceof xe.Reader?e:new xe.Reader(e);let n=void 0===t?i.len:i.pos+t;const s={message:void 0};for(;i.pos>>3){case 1:s.message={$case:"offer",offer:Rt.decode(i,i.uint32())};break;case 2:s.message={$case:"answer",answer:Rt.decode(i,i.uint32())};break;case 3:s.message={$case:"trickle",trickle:yt.decode(i,i.uint32())};break;case 4:s.message={$case:"addTrack",addTrack:kt.decode(i,i.uint32())};break;case 5:s.message={$case:"mute",mute:wt.decode(i,i.uint32())};break;case 6:s.message={$case:"subscription",subscription:Nt.decode(i,i.uint32())};break;case 7:s.message={$case:"trackSetting",trackSetting:It.decode(i,i.uint32())};break;case 8:s.message={$case:"leave",leave:Dt.decode(i,i.uint32())};break;case 10:s.message={$case:"updateLayers",updateLayers:_t.decode(i,i.uint32())};break;case 11:s.message={$case:"subscriptionPermission",subscriptionPermission:qt.decode(i,i.uint32())};break;case 12:s.message={$case:"syncState",syncState:Qt.decode(i,i.uint32())};break;case 13:s.message={$case:"simulate",simulate:Ht.decode(i,i.uint32())};break;case 14:s.message={$case:"ping",ping:longToNumber(i.int64())};break;case 15:s.message={$case:"updateMetadata",updateMetadata:Lt.decode(i,i.uint32())};break;case 16:s.message={$case:"pingReq",pingReq:Zt.decode(i,i.uint32())};break;default:i.skipType(7&e)}}return s},fromJSON:e=>({message:isSet(e.offer)?{$case:"offer",offer:Rt.fromJSON(e.offer)}:isSet(e.answer)?{$case:"answer",answer:Rt.fromJSON(e.answer)}:isSet(e.trickle)?{$case:"trickle",trickle:yt.fromJSON(e.trickle)}:isSet(e.addTrack)?{$case:"addTrack",addTrack:kt.fromJSON(e.addTrack)}:isSet(e.mute)?{$case:"mute",mute:wt.fromJSON(e.mute)}:isSet(e.subscription)?{$case:"subscription",subscription:Nt.fromJSON(e.subscription)}:isSet(e.trackSetting)?{$case:"trackSetting",trackSetting:It.fromJSON(e.trackSetting)}:isSet(e.leave)?{$case:"leave",leave:Dt.fromJSON(e.leave)}:isSet(e.updateLayers)?{$case:"updateLayers",updateLayers:_t.fromJSON(e.updateLayers)}:isSet(e.subscriptionPermission)?{$case:"subscriptionPermission",subscriptionPermission:qt.fromJSON(e.subscriptionPermission)}:isSet(e.syncState)?{$case:"syncState",syncState:Qt.fromJSON(e.syncState)}:isSet(e.simulate)?{$case:"simulate",simulate:Ht.fromJSON(e.simulate)}:isSet(e.ping)?{$case:"ping",ping:Number(e.ping)}:isSet(e.updateMetadata)?{$case:"updateMetadata",updateMetadata:Lt.fromJSON(e.updateMetadata)}:isSet(e.pingReq)?{$case:"pingReq",pingReq:Zt.fromJSON(e.pingReq)}:void 0}),toJSON(e){var t,i,n,s,a,o,c,u,l,h,p,m,v,g,b,S,k,y,w,T,C,P,E,R,O,N,I,D,_,L,A,U,M,x,$,B,F,J,V,j,W,q,G,Q;const z={};return"offer"===(null===(t=e.message)||void 0===t?void 0:t.$case)&&(z.offer=(null===(i=e.message)||void 0===i?void 0:i.offer)?Rt.toJSON(null===(n=e.message)||void 0===n?void 0:n.offer):void 0),"answer"===(null===(s=e.message)||void 0===s?void 0:s.$case)&&(z.answer=(null===(a=e.message)||void 0===a?void 0:a.answer)?Rt.toJSON(null===(o=e.message)||void 0===o?void 0:o.answer):void 0),"trickle"===(null===(c=e.message)||void 0===c?void 0:c.$case)&&(z.trickle=(null===(u=e.message)||void 0===u?void 0:u.trickle)?yt.toJSON(null===(l=e.message)||void 0===l?void 0:l.trickle):void 0),"addTrack"===(null===(h=e.message)||void 0===h?void 0:h.$case)&&(z.addTrack=(null===(p=e.message)||void 0===p?void 0:p.addTrack)?kt.toJSON(null===(m=e.message)||void 0===m?void 0:m.addTrack):void 0),"mute"===(null===(v=e.message)||void 0===v?void 0:v.$case)&&(z.mute=(null===(g=e.message)||void 0===g?void 0:g.mute)?wt.toJSON(null===(b=e.message)||void 0===b?void 0:b.mute):void 0),"subscription"===(null===(S=e.message)||void 0===S?void 0:S.$case)&&(z.subscription=(null===(k=e.message)||void 0===k?void 0:k.subscription)?Nt.toJSON(null===(y=e.message)||void 0===y?void 0:y.subscription):void 0),"trackSetting"===(null===(w=e.message)||void 0===w?void 0:w.$case)&&(z.trackSetting=(null===(T=e.message)||void 0===T?void 0:T.trackSetting)?It.toJSON(null===(C=e.message)||void 0===C?void 0:C.trackSetting):void 0),"leave"===(null===(P=e.message)||void 0===P?void 0:P.$case)&&(z.leave=(null===(E=e.message)||void 0===E?void 0:E.leave)?Dt.toJSON(null===(R=e.message)||void 0===R?void 0:R.leave):void 0),"updateLayers"===(null===(O=e.message)||void 0===O?void 0:O.$case)&&(z.updateLayers=(null===(N=e.message)||void 0===N?void 0:N.updateLayers)?_t.toJSON(null===(I=e.message)||void 0===I?void 0:I.updateLayers):void 0),"subscriptionPermission"===(null===(D=e.message)||void 0===D?void 0:D.$case)&&(z.subscriptionPermission=(null===(_=e.message)||void 0===_?void 0:_.subscriptionPermission)?qt.toJSON(null===(L=e.message)||void 0===L?void 0:L.subscriptionPermission):void 0),"syncState"===(null===(A=e.message)||void 0===A?void 0:A.$case)&&(z.syncState=(null===(U=e.message)||void 0===U?void 0:U.syncState)?Qt.toJSON(null===(M=e.message)||void 0===M?void 0:M.syncState):void 0),"simulate"===(null===(x=e.message)||void 0===x?void 0:x.$case)&&(z.simulate=(null===($=e.message)||void 0===$?void 0:$.simulate)?Ht.toJSON(null===(B=e.message)||void 0===B?void 0:B.simulate):void 0),"ping"===(null===(F=e.message)||void 0===F?void 0:F.$case)&&(z.ping=Math.round(null===(J=e.message)||void 0===J?void 0:J.ping)),"updateMetadata"===(null===(V=e.message)||void 0===V?void 0:V.$case)&&(z.updateMetadata=(null===(j=e.message)||void 0===j?void 0:j.updateMetadata)?Lt.toJSON(null===(W=e.message)||void 0===W?void 0:W.updateMetadata):void 0),"pingReq"===(null===(q=e.message)||void 0===q?void 0:q.$case)&&(z.pingReq=(null===(G=e.message)||void 0===G?void 0:G.pingReq)?Zt.toJSON(null===(Q=e.message)||void 0===Q?void 0:Q.pingReq):void 0),z},create:e=>gt.fromPartial(null!=e?e:{}),fromPartial(e){var t,i,n,s,a,o,c,u,l,h,p,m,v,g,b,S,k,y,w,T,C,P,E,R,O,N,I,D,_,L,A,U,M,x,$,B,F,J,V,j,W,q,G,Q,z;const H={message:void 0};return"offer"===(null===(t=e.message)||void 0===t?void 0:t.$case)&&void 0!==(null===(i=e.message)||void 0===i?void 0:i.offer)&&null!==(null===(n=e.message)||void 0===n?void 0:n.offer)&&(H.message={$case:"offer",offer:Rt.fromPartial(e.message.offer)}),"answer"===(null===(s=e.message)||void 0===s?void 0:s.$case)&&void 0!==(null===(a=e.message)||void 0===a?void 0:a.answer)&&null!==(null===(o=e.message)||void 0===o?void 0:o.answer)&&(H.message={$case:"answer",answer:Rt.fromPartial(e.message.answer)}),"trickle"===(null===(c=e.message)||void 0===c?void 0:c.$case)&&void 0!==(null===(u=e.message)||void 0===u?void 0:u.trickle)&&null!==(null===(l=e.message)||void 0===l?void 0:l.trickle)&&(H.message={$case:"trickle",trickle:yt.fromPartial(e.message.trickle)}),"addTrack"===(null===(h=e.message)||void 0===h?void 0:h.$case)&&void 0!==(null===(p=e.message)||void 0===p?void 0:p.addTrack)&&null!==(null===(m=e.message)||void 0===m?void 0:m.addTrack)&&(H.message={$case:"addTrack",addTrack:kt.fromPartial(e.message.addTrack)}),"mute"===(null===(v=e.message)||void 0===v?void 0:v.$case)&&void 0!==(null===(g=e.message)||void 0===g?void 0:g.mute)&&null!==(null===(b=e.message)||void 0===b?void 0:b.mute)&&(H.message={$case:"mute",mute:wt.fromPartial(e.message.mute)}),"subscription"===(null===(S=e.message)||void 0===S?void 0:S.$case)&&void 0!==(null===(k=e.message)||void 0===k?void 0:k.subscription)&&null!==(null===(y=e.message)||void 0===y?void 0:y.subscription)&&(H.message={$case:"subscription",subscription:Nt.fromPartial(e.message.subscription)}),"trackSetting"===(null===(w=e.message)||void 0===w?void 0:w.$case)&&void 0!==(null===(T=e.message)||void 0===T?void 0:T.trackSetting)&&null!==(null===(C=e.message)||void 0===C?void 0:C.trackSetting)&&(H.message={$case:"trackSetting",trackSetting:It.fromPartial(e.message.trackSetting)}),"leave"===(null===(P=e.message)||void 0===P?void 0:P.$case)&&void 0!==(null===(E=e.message)||void 0===E?void 0:E.leave)&&null!==(null===(R=e.message)||void 0===R?void 0:R.leave)&&(H.message={$case:"leave",leave:Dt.fromPartial(e.message.leave)}),"updateLayers"===(null===(O=e.message)||void 0===O?void 0:O.$case)&&void 0!==(null===(N=e.message)||void 0===N?void 0:N.updateLayers)&&null!==(null===(I=e.message)||void 0===I?void 0:I.updateLayers)&&(H.message={$case:"updateLayers",updateLayers:_t.fromPartial(e.message.updateLayers)}),"subscriptionPermission"===(null===(D=e.message)||void 0===D?void 0:D.$case)&&void 0!==(null===(_=e.message)||void 0===_?void 0:_.subscriptionPermission)&&null!==(null===(L=e.message)||void 0===L?void 0:L.subscriptionPermission)&&(H.message={$case:"subscriptionPermission",subscriptionPermission:qt.fromPartial(e.message.subscriptionPermission)}),"syncState"===(null===(A=e.message)||void 0===A?void 0:A.$case)&&void 0!==(null===(U=e.message)||void 0===U?void 0:U.syncState)&&null!==(null===(M=e.message)||void 0===M?void 0:M.syncState)&&(H.message={$case:"syncState",syncState:Qt.fromPartial(e.message.syncState)}),"simulate"===(null===(x=e.message)||void 0===x?void 0:x.$case)&&void 0!==(null===($=e.message)||void 0===$?void 0:$.simulate)&&null!==(null===(B=e.message)||void 0===B?void 0:B.simulate)&&(H.message={$case:"simulate",simulate:Ht.fromPartial(e.message.simulate)}),"ping"===(null===(F=e.message)||void 0===F?void 0:F.$case)&&void 0!==(null===(J=e.message)||void 0===J?void 0:J.ping)&&null!==(null===(V=e.message)||void 0===V?void 0:V.ping)&&(H.message={$case:"ping",ping:e.message.ping}),"updateMetadata"===(null===(j=e.message)||void 0===j?void 0:j.$case)&&void 0!==(null===(W=e.message)||void 0===W?void 0:W.updateMetadata)&&null!==(null===(q=e.message)||void 0===q?void 0:q.updateMetadata)&&(H.message={$case:"updateMetadata",updateMetadata:Lt.fromPartial(e.message.updateMetadata)}),"pingReq"===(null===(G=e.message)||void 0===G?void 0:G.$case)&&void 0!==(null===(Q=e.message)||void 0===Q?void 0:Q.pingReq)&&null!==(null===(z=e.message)||void 0===z?void 0:z.pingReq)&&(H.message={$case:"pingReq",pingReq:Zt.fromPartial(e.message.pingReq)}),H}};const bt={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xe.Writer.create();var i;switch(null===(i=e.message)||void 0===i?void 0:i.$case){case"join":Tt.encode(e.message.join,t.uint32(10).fork()).ldelim();break;case"answer":Rt.encode(e.message.answer,t.uint32(18).fork()).ldelim();break;case"offer":Rt.encode(e.message.offer,t.uint32(26).fork()).ldelim();break;case"trickle":yt.encode(e.message.trickle,t.uint32(34).fork()).ldelim();break;case"update":Ot.encode(e.message.update,t.uint32(42).fork()).ldelim();break;case"trackPublished":Pt.encode(e.message.trackPublished,t.uint32(50).fork()).ldelim();break;case"leave":Dt.encode(e.message.leave,t.uint32(66).fork()).ldelim();break;case"mute":wt.encode(e.message.mute,t.uint32(74).fork()).ldelim();break;case"speakersChanged":Ut.encode(e.message.speakersChanged,t.uint32(82).fork()).ldelim();break;case"roomUpdate":Mt.encode(e.message.roomUpdate,t.uint32(90).fork()).ldelim();break;case"connectionQuality":$t.encode(e.message.connectionQuality,t.uint32(98).fork()).ldelim();break;case"streamStateUpdate":Ft.encode(e.message.streamStateUpdate,t.uint32(106).fork()).ldelim();break;case"subscribedQualityUpdate":jt.encode(e.message.subscribedQualityUpdate,t.uint32(114).fork()).ldelim();break;case"subscriptionPermissionUpdate":Gt.encode(e.message.subscriptionPermissionUpdate,t.uint32(122).fork()).ldelim();break;case"refreshToken":t.uint32(130).string(e.message.refreshToken);break;case"trackUnpublished":Et.encode(e.message.trackUnpublished,t.uint32(138).fork()).ldelim();break;case"pong":t.uint32(144).int64(e.message.pong);break;case"reconnect":Ct.encode(e.message.reconnect,t.uint32(154).fork()).ldelim();break;case"pongResp":Kt.encode(e.message.pongResp,t.uint32(162).fork()).ldelim()}return t},decode(e,t){const i=e instanceof xe.Reader?e:new xe.Reader(e);let n=void 0===t?i.len:i.pos+t;const s={message:void 0};for(;i.pos>>3){case 1:s.message={$case:"join",join:Tt.decode(i,i.uint32())};break;case 2:s.message={$case:"answer",answer:Rt.decode(i,i.uint32())};break;case 3:s.message={$case:"offer",offer:Rt.decode(i,i.uint32())};break;case 4:s.message={$case:"trickle",trickle:yt.decode(i,i.uint32())};break;case 5:s.message={$case:"update",update:Ot.decode(i,i.uint32())};break;case 6:s.message={$case:"trackPublished",trackPublished:Pt.decode(i,i.uint32())};break;case 8:s.message={$case:"leave",leave:Dt.decode(i,i.uint32())};break;case 9:s.message={$case:"mute",mute:wt.decode(i,i.uint32())};break;case 10:s.message={$case:"speakersChanged",speakersChanged:Ut.decode(i,i.uint32())};break;case 11:s.message={$case:"roomUpdate",roomUpdate:Mt.decode(i,i.uint32())};break;case 12:s.message={$case:"connectionQuality",connectionQuality:$t.decode(i,i.uint32())};break;case 13:s.message={$case:"streamStateUpdate",streamStateUpdate:Ft.decode(i,i.uint32())};break;case 14:s.message={$case:"subscribedQualityUpdate",subscribedQualityUpdate:jt.decode(i,i.uint32())};break;case 15:s.message={$case:"subscriptionPermissionUpdate",subscriptionPermissionUpdate:Gt.decode(i,i.uint32())};break;case 16:s.message={$case:"refreshToken",refreshToken:i.string()};break;case 17:s.message={$case:"trackUnpublished",trackUnpublished:Et.decode(i,i.uint32())};break;case 18:s.message={$case:"pong",pong:longToNumber(i.int64())};break;case 19:s.message={$case:"reconnect",reconnect:Ct.decode(i,i.uint32())};break;case 20:s.message={$case:"pongResp",pongResp:Kt.decode(i,i.uint32())};break;default:i.skipType(7&e)}}return s},fromJSON:e=>({message:isSet(e.join)?{$case:"join",join:Tt.fromJSON(e.join)}:isSet(e.answer)?{$case:"answer",answer:Rt.fromJSON(e.answer)}:isSet(e.offer)?{$case:"offer",offer:Rt.fromJSON(e.offer)}:isSet(e.trickle)?{$case:"trickle",trickle:yt.fromJSON(e.trickle)}:isSet(e.update)?{$case:"update",update:Ot.fromJSON(e.update)}:isSet(e.trackPublished)?{$case:"trackPublished",trackPublished:Pt.fromJSON(e.trackPublished)}:isSet(e.leave)?{$case:"leave",leave:Dt.fromJSON(e.leave)}:isSet(e.mute)?{$case:"mute",mute:wt.fromJSON(e.mute)}:isSet(e.speakersChanged)?{$case:"speakersChanged",speakersChanged:Ut.fromJSON(e.speakersChanged)}:isSet(e.roomUpdate)?{$case:"roomUpdate",roomUpdate:Mt.fromJSON(e.roomUpdate)}:isSet(e.connectionQuality)?{$case:"connectionQuality",connectionQuality:$t.fromJSON(e.connectionQuality)}:isSet(e.streamStateUpdate)?{$case:"streamStateUpdate",streamStateUpdate:Ft.fromJSON(e.streamStateUpdate)}:isSet(e.subscribedQualityUpdate)?{$case:"subscribedQualityUpdate",subscribedQualityUpdate:jt.fromJSON(e.subscribedQualityUpdate)}:isSet(e.subscriptionPermissionUpdate)?{$case:"subscriptionPermissionUpdate",subscriptionPermissionUpdate:Gt.fromJSON(e.subscriptionPermissionUpdate)}:isSet(e.refreshToken)?{$case:"refreshToken",refreshToken:String(e.refreshToken)}:isSet(e.trackUnpublished)?{$case:"trackUnpublished",trackUnpublished:Et.fromJSON(e.trackUnpublished)}:isSet(e.pong)?{$case:"pong",pong:Number(e.pong)}:isSet(e.reconnect)?{$case:"reconnect",reconnect:Ct.fromJSON(e.reconnect)}:isSet(e.pongResp)?{$case:"pongResp",pongResp:Kt.fromJSON(e.pongResp)}:void 0}),toJSON(e){var t,i,n,s,a,o,c,u,l,h,p,m,v,g,b,S,k,y,w,T,C,P,E,R,O,N,I,D,_,L,A,U,M,x,$,B,F,J,V,j,W,q,G,Q,z,H,Z,K,Y,X,ee,te,ie,re,ne;const se={};return"join"===(null===(t=e.message)||void 0===t?void 0:t.$case)&&(se.join=(null===(i=e.message)||void 0===i?void 0:i.join)?Tt.toJSON(null===(n=e.message)||void 0===n?void 0:n.join):void 0),"answer"===(null===(s=e.message)||void 0===s?void 0:s.$case)&&(se.answer=(null===(a=e.message)||void 0===a?void 0:a.answer)?Rt.toJSON(null===(o=e.message)||void 0===o?void 0:o.answer):void 0),"offer"===(null===(c=e.message)||void 0===c?void 0:c.$case)&&(se.offer=(null===(u=e.message)||void 0===u?void 0:u.offer)?Rt.toJSON(null===(l=e.message)||void 0===l?void 0:l.offer):void 0),"trickle"===(null===(h=e.message)||void 0===h?void 0:h.$case)&&(se.trickle=(null===(p=e.message)||void 0===p?void 0:p.trickle)?yt.toJSON(null===(m=e.message)||void 0===m?void 0:m.trickle):void 0),"update"===(null===(v=e.message)||void 0===v?void 0:v.$case)&&(se.update=(null===(g=e.message)||void 0===g?void 0:g.update)?Ot.toJSON(null===(b=e.message)||void 0===b?void 0:b.update):void 0),"trackPublished"===(null===(S=e.message)||void 0===S?void 0:S.$case)&&(se.trackPublished=(null===(k=e.message)||void 0===k?void 0:k.trackPublished)?Pt.toJSON(null===(y=e.message)||void 0===y?void 0:y.trackPublished):void 0),"leave"===(null===(w=e.message)||void 0===w?void 0:w.$case)&&(se.leave=(null===(T=e.message)||void 0===T?void 0:T.leave)?Dt.toJSON(null===(C=e.message)||void 0===C?void 0:C.leave):void 0),"mute"===(null===(P=e.message)||void 0===P?void 0:P.$case)&&(se.mute=(null===(E=e.message)||void 0===E?void 0:E.mute)?wt.toJSON(null===(R=e.message)||void 0===R?void 0:R.mute):void 0),"speakersChanged"===(null===(O=e.message)||void 0===O?void 0:O.$case)&&(se.speakersChanged=(null===(N=e.message)||void 0===N?void 0:N.speakersChanged)?Ut.toJSON(null===(I=e.message)||void 0===I?void 0:I.speakersChanged):void 0),"roomUpdate"===(null===(D=e.message)||void 0===D?void 0:D.$case)&&(se.roomUpdate=(null===(_=e.message)||void 0===_?void 0:_.roomUpdate)?Mt.toJSON(null===(L=e.message)||void 0===L?void 0:L.roomUpdate):void 0),"connectionQuality"===(null===(A=e.message)||void 0===A?void 0:A.$case)&&(se.connectionQuality=(null===(U=e.message)||void 0===U?void 0:U.connectionQuality)?$t.toJSON(null===(M=e.message)||void 0===M?void 0:M.connectionQuality):void 0),"streamStateUpdate"===(null===(x=e.message)||void 0===x?void 0:x.$case)&&(se.streamStateUpdate=(null===($=e.message)||void 0===$?void 0:$.streamStateUpdate)?Ft.toJSON(null===(B=e.message)||void 0===B?void 0:B.streamStateUpdate):void 0),"subscribedQualityUpdate"===(null===(F=e.message)||void 0===F?void 0:F.$case)&&(se.subscribedQualityUpdate=(null===(J=e.message)||void 0===J?void 0:J.subscribedQualityUpdate)?jt.toJSON(null===(V=e.message)||void 0===V?void 0:V.subscribedQualityUpdate):void 0),"subscriptionPermissionUpdate"===(null===(j=e.message)||void 0===j?void 0:j.$case)&&(se.subscriptionPermissionUpdate=(null===(W=e.message)||void 0===W?void 0:W.subscriptionPermissionUpdate)?Gt.toJSON(null===(q=e.message)||void 0===q?void 0:q.subscriptionPermissionUpdate):void 0),"refreshToken"===(null===(G=e.message)||void 0===G?void 0:G.$case)&&(se.refreshToken=null===(Q=e.message)||void 0===Q?void 0:Q.refreshToken),"trackUnpublished"===(null===(z=e.message)||void 0===z?void 0:z.$case)&&(se.trackUnpublished=(null===(H=e.message)||void 0===H?void 0:H.trackUnpublished)?Et.toJSON(null===(Z=e.message)||void 0===Z?void 0:Z.trackUnpublished):void 0),"pong"===(null===(K=e.message)||void 0===K?void 0:K.$case)&&(se.pong=Math.round(null===(Y=e.message)||void 0===Y?void 0:Y.pong)),"reconnect"===(null===(X=e.message)||void 0===X?void 0:X.$case)&&(se.reconnect=(null===(ee=e.message)||void 0===ee?void 0:ee.reconnect)?Ct.toJSON(null===(te=e.message)||void 0===te?void 0:te.reconnect):void 0),"pongResp"===(null===(ie=e.message)||void 0===ie?void 0:ie.$case)&&(se.pongResp=(null===(re=e.message)||void 0===re?void 0:re.pongResp)?Kt.toJSON(null===(ne=e.message)||void 0===ne?void 0:ne.pongResp):void 0),se},create:e=>bt.fromPartial(null!=e?e:{}),fromPartial(e){var t,i,n,s,a,o,c,u,l,h,p,m,v,g,b,S,k,y,w,T,C,P,E,R,O,N,I,D,_,L,A,U,M,x,$,B,F,J,V,j,W,q,G,Q,z,H,Z,K,Y,X,ee,te,ie,re,ne,se,ae;const oe={message:void 0};return"join"===(null===(t=e.message)||void 0===t?void 0:t.$case)&&void 0!==(null===(i=e.message)||void 0===i?void 0:i.join)&&null!==(null===(n=e.message)||void 0===n?void 0:n.join)&&(oe.message={$case:"join",join:Tt.fromPartial(e.message.join)}),"answer"===(null===(s=e.message)||void 0===s?void 0:s.$case)&&void 0!==(null===(a=e.message)||void 0===a?void 0:a.answer)&&null!==(null===(o=e.message)||void 0===o?void 0:o.answer)&&(oe.message={$case:"answer",answer:Rt.fromPartial(e.message.answer)}),"offer"===(null===(c=e.message)||void 0===c?void 0:c.$case)&&void 0!==(null===(u=e.message)||void 0===u?void 0:u.offer)&&null!==(null===(l=e.message)||void 0===l?void 0:l.offer)&&(oe.message={$case:"offer",offer:Rt.fromPartial(e.message.offer)}),"trickle"===(null===(h=e.message)||void 0===h?void 0:h.$case)&&void 0!==(null===(p=e.message)||void 0===p?void 0:p.trickle)&&null!==(null===(m=e.message)||void 0===m?void 0:m.trickle)&&(oe.message={$case:"trickle",trickle:yt.fromPartial(e.message.trickle)}),"update"===(null===(v=e.message)||void 0===v?void 0:v.$case)&&void 0!==(null===(g=e.message)||void 0===g?void 0:g.update)&&null!==(null===(b=e.message)||void 0===b?void 0:b.update)&&(oe.message={$case:"update",update:Ot.fromPartial(e.message.update)}),"trackPublished"===(null===(S=e.message)||void 0===S?void 0:S.$case)&&void 0!==(null===(k=e.message)||void 0===k?void 0:k.trackPublished)&&null!==(null===(y=e.message)||void 0===y?void 0:y.trackPublished)&&(oe.message={$case:"trackPublished",trackPublished:Pt.fromPartial(e.message.trackPublished)}),"leave"===(null===(w=e.message)||void 0===w?void 0:w.$case)&&void 0!==(null===(T=e.message)||void 0===T?void 0:T.leave)&&null!==(null===(C=e.message)||void 0===C?void 0:C.leave)&&(oe.message={$case:"leave",leave:Dt.fromPartial(e.message.leave)}),"mute"===(null===(P=e.message)||void 0===P?void 0:P.$case)&&void 0!==(null===(E=e.message)||void 0===E?void 0:E.mute)&&null!==(null===(R=e.message)||void 0===R?void 0:R.mute)&&(oe.message={$case:"mute",mute:wt.fromPartial(e.message.mute)}),"speakersChanged"===(null===(O=e.message)||void 0===O?void 0:O.$case)&&void 0!==(null===(N=e.message)||void 0===N?void 0:N.speakersChanged)&&null!==(null===(I=e.message)||void 0===I?void 0:I.speakersChanged)&&(oe.message={$case:"speakersChanged",speakersChanged:Ut.fromPartial(e.message.speakersChanged)}),"roomUpdate"===(null===(D=e.message)||void 0===D?void 0:D.$case)&&void 0!==(null===(_=e.message)||void 0===_?void 0:_.roomUpdate)&&null!==(null===(L=e.message)||void 0===L?void 0:L.roomUpdate)&&(oe.message={$case:"roomUpdate",roomUpdate:Mt.fromPartial(e.message.roomUpdate)}),"connectionQuality"===(null===(A=e.message)||void 0===A?void 0:A.$case)&&void 0!==(null===(U=e.message)||void 0===U?void 0:U.connectionQuality)&&null!==(null===(M=e.message)||void 0===M?void 0:M.connectionQuality)&&(oe.message={$case:"connectionQuality",connectionQuality:$t.fromPartial(e.message.connectionQuality)}),"streamStateUpdate"===(null===(x=e.message)||void 0===x?void 0:x.$case)&&void 0!==(null===($=e.message)||void 0===$?void 0:$.streamStateUpdate)&&null!==(null===(B=e.message)||void 0===B?void 0:B.streamStateUpdate)&&(oe.message={$case:"streamStateUpdate",streamStateUpdate:Ft.fromPartial(e.message.streamStateUpdate)}),"subscribedQualityUpdate"===(null===(F=e.message)||void 0===F?void 0:F.$case)&&void 0!==(null===(J=e.message)||void 0===J?void 0:J.subscribedQualityUpdate)&&null!==(null===(V=e.message)||void 0===V?void 0:V.subscribedQualityUpdate)&&(oe.message={$case:"subscribedQualityUpdate",subscribedQualityUpdate:jt.fromPartial(e.message.subscribedQualityUpdate)}),"subscriptionPermissionUpdate"===(null===(j=e.message)||void 0===j?void 0:j.$case)&&void 0!==(null===(W=e.message)||void 0===W?void 0:W.subscriptionPermissionUpdate)&&null!==(null===(q=e.message)||void 0===q?void 0:q.subscriptionPermissionUpdate)&&(oe.message={$case:"subscriptionPermissionUpdate",subscriptionPermissionUpdate:Gt.fromPartial(e.message.subscriptionPermissionUpdate)}),"refreshToken"===(null===(G=e.message)||void 0===G?void 0:G.$case)&&void 0!==(null===(Q=e.message)||void 0===Q?void 0:Q.refreshToken)&&null!==(null===(z=e.message)||void 0===z?void 0:z.refreshToken)&&(oe.message={$case:"refreshToken",refreshToken:e.message.refreshToken}),"trackUnpublished"===(null===(H=e.message)||void 0===H?void 0:H.$case)&&void 0!==(null===(Z=e.message)||void 0===Z?void 0:Z.trackUnpublished)&&null!==(null===(K=e.message)||void 0===K?void 0:K.trackUnpublished)&&(oe.message={$case:"trackUnpublished",trackUnpublished:Et.fromPartial(e.message.trackUnpublished)}),"pong"===(null===(Y=e.message)||void 0===Y?void 0:Y.$case)&&void 0!==(null===(X=e.message)||void 0===X?void 0:X.pong)&&null!==(null===(ee=e.message)||void 0===ee?void 0:ee.pong)&&(oe.message={$case:"pong",pong:e.message.pong}),"reconnect"===(null===(te=e.message)||void 0===te?void 0:te.$case)&&void 0!==(null===(ie=e.message)||void 0===ie?void 0:ie.reconnect)&&null!==(null===(re=e.message)||void 0===re?void 0:re.reconnect)&&(oe.message={$case:"reconnect",reconnect:Ct.fromPartial(e.message.reconnect)}),"pongResp"===(null===(ne=e.message)||void 0===ne?void 0:ne.$case)&&void 0!==(null===(se=e.message)||void 0===se?void 0:se.pongResp)&&null!==(null===(ae=e.message)||void 0===ae?void 0:ae.pongResp)&&(oe.message={$case:"pongResp",pongResp:Kt.fromPartial(e.message.pongResp)}),oe}};const St={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xe.Writer.create();return""!==e.codec&&t.uint32(10).string(e.codec),""!==e.cid&&t.uint32(18).string(e.cid),!0===e.enableSimulcastLayers&&t.uint32(24).bool(e.enableSimulcastLayers),t},decode(e,t){const i=e instanceof xe.Reader?e:new xe.Reader(e);let n=void 0===t?i.len:i.pos+t;const s={codec:"",cid:"",enableSimulcastLayers:!1};for(;i.pos>>3){case 1:s.codec=i.string();break;case 2:s.cid=i.string();break;case 3:s.enableSimulcastLayers=i.bool();break;default:i.skipType(7&e)}}return s},fromJSON:e=>({codec:isSet(e.codec)?String(e.codec):"",cid:isSet(e.cid)?String(e.cid):"",enableSimulcastLayers:!!isSet(e.enableSimulcastLayers)&&Boolean(e.enableSimulcastLayers)}),toJSON(e){const t={};return void 0!==e.codec&&(t.codec=e.codec),void 0!==e.cid&&(t.cid=e.cid),void 0!==e.enableSimulcastLayers&&(t.enableSimulcastLayers=e.enableSimulcastLayers),t},create:e=>St.fromPartial(null!=e?e:{}),fromPartial(e){var t,i,n;const s={codec:"",cid:"",enableSimulcastLayers:!1};return s.codec=null!==(t=e.codec)&&void 0!==t?t:"",s.cid=null!==(i=e.cid)&&void 0!==i?i:"",s.enableSimulcastLayers=null!==(n=e.enableSimulcastLayers)&&void 0!==n&&n,s}};const kt={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xe.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)We.encode(i,t.uint32(74).fork()).ldelim();for(const i of e.simulcastCodecs)St.encode(i,t.uint32(82).fork()).ldelim();return""!==e.sid&&t.uint32(90).string(e.sid),!0===e.stereo&&t.uint32(96).bool(e.stereo),!0===e.disableRed&&t.uint32(104).bool(e.disableRed),0!==e.encryption&&t.uint32(112).int32(e.encryption),t},decode(e,t){const i=e instanceof xe.Reader?e:new xe.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:[],simulcastCodecs:[],sid:"",stereo:!1,disableRed:!1,encryption:0};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(We.decode(i,i.uint32()));break;case 10:s.simulcastCodecs.push(St.decode(i,i.uint32()));break;case 11:s.sid=i.string();break;case 12:s.stereo=i.bool();break;case 13:s.disableRed=i.bool();break;case 14:s.encryption=i.int32();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=>We.fromJSON(e))):[],simulcastCodecs:Array.isArray(null==e?void 0:e.simulcastCodecs)?e.simulcastCodecs.map((e=>St.fromJSON(e))):[],sid:isSet(e.sid)?String(e.sid):"",stereo:!!isSet(e.stereo)&&Boolean(e.stereo),disableRed:!!isSet(e.disableRed)&&Boolean(e.disableRed),encryption:isSet(e.encryption)?encryption_TypeFromJSON(e.encryption):0}),toJSON(e){const t={};return void 0!==e.cid&&(t.cid=e.cid),void 0!==e.name&&(t.name=e.name),void 0!==e.type&&(t.type=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?We.toJSON(e):void 0)):t.layers=[],e.simulcastCodecs?t.simulcastCodecs=e.simulcastCodecs.map((e=>e?St.toJSON(e):void 0)):t.simulcastCodecs=[],void 0!==e.sid&&(t.sid=e.sid),void 0!==e.stereo&&(t.stereo=e.stereo),void 0!==e.disableRed&&(t.disableRed=e.disableRed),void 0!==e.encryption&&(t.encryption=encryption_TypeToJSON(e.encryption)),t},create:e=>kt.fromPartial(null!=e?e:{}),fromPartial(e){var t,i,n,s,a,o,c,u,l,h,p,m,v,g;const b={cid:"",name:"",type:0,width:0,height:0,muted:!1,disableDtx:!1,source:0,layers:[],simulcastCodecs:[],sid:"",stereo:!1,disableRed:!1,encryption:0};return b.cid=null!==(t=e.cid)&&void 0!==t?t:"",b.name=null!==(i=e.name)&&void 0!==i?i:"",b.type=null!==(n=e.type)&&void 0!==n?n:0,b.width=null!==(s=e.width)&&void 0!==s?s:0,b.height=null!==(a=e.height)&&void 0!==a?a:0,b.muted=null!==(o=e.muted)&&void 0!==o&&o,b.disableDtx=null!==(c=e.disableDtx)&&void 0!==c&&c,b.source=null!==(u=e.source)&&void 0!==u?u:0,b.layers=(null===(l=e.layers)||void 0===l?void 0:l.map((e=>We.fromPartial(e))))||[],b.simulcastCodecs=(null===(h=e.simulcastCodecs)||void 0===h?void 0:h.map((e=>St.fromPartial(e))))||[],b.sid=null!==(p=e.sid)&&void 0!==p?p:"",b.stereo=null!==(m=e.stereo)&&void 0!==m&&m,b.disableRed=null!==(v=e.disableRed)&&void 0!==v&&v,b.encryption=null!==(g=e.encryption)&&void 0!==g?g:0,b}};const yt={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xe.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 xe.Reader?e:new xe.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},create:e=>yt.fromPartial(null!=e?e:{}),fromPartial(e){var t,i;const n={candidateInit:"",target:0};return n.candidateInit=null!==(t=e.candidateInit)&&void 0!==t?t:"",n.target=null!==(i=e.target)&&void 0!==i?i:0,n}};const wt={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xe.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 xe.Reader?e:new xe.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},create:e=>wt.fromPartial(null!=e?e:{}),fromPartial(e){var t,i;const n={sid:"",muted:!1};return n.sid=null!==(t=e.sid)&&void 0!==t?t:"",n.muted=null!==(i=e.muted)&&void 0!==i&&i,n}};const Tt={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xe.Writer.create();void 0!==e.room&&$e.encode(e.room,t.uint32(10).fork()).ldelim(),void 0!==e.participant&&Je.encode(e.participant,t.uint32(18).fork()).ldelim();for(const i of e.otherParticipants)Je.encode(i,t.uint32(26).fork()).ldelim();""!==e.serverVersion&&t.uint32(34).string(e.serverVersion);for(const i of e.iceServers)At.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&&Ye.encode(e.clientConfiguration,t.uint32(66).fork()).ldelim(),""!==e.serverRegion&&t.uint32(74).string(e.serverRegion),0!==e.pingTimeout&&t.uint32(80).int32(e.pingTimeout),0!==e.pingInterval&&t.uint32(88).int32(e.pingInterval),void 0!==e.serverInfo&&Ze.encode(e.serverInfo,t.uint32(98).fork()).ldelim(),t},decode(e,t){const i=e instanceof xe.Reader?e:new xe.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:"",pingTimeout:0,pingInterval:0,serverInfo:void 0};for(;i.pos>>3){case 1:s.room=$e.decode(i,i.uint32());break;case 2:s.participant=Je.decode(i,i.uint32());break;case 3:s.otherParticipants.push(Je.decode(i,i.uint32()));break;case 4:s.serverVersion=i.string();break;case 5:s.iceServers.push(At.decode(i,i.uint32()));break;case 6:s.subscriberPrimary=i.bool();break;case 7:s.alternativeUrl=i.string();break;case 8:s.clientConfiguration=Ye.decode(i,i.uint32());break;case 9:s.serverRegion=i.string();break;case 10:s.pingTimeout=i.int32();break;case 11:s.pingInterval=i.int32();break;case 12:s.serverInfo=Ze.decode(i,i.uint32());break;default:i.skipType(7&e)}}return s},fromJSON:e=>({room:isSet(e.room)?$e.fromJSON(e.room):void 0,participant:isSet(e.participant)?Je.fromJSON(e.participant):void 0,otherParticipants:Array.isArray(null==e?void 0:e.otherParticipants)?e.otherParticipants.map((e=>Je.fromJSON(e))):[],serverVersion:isSet(e.serverVersion)?String(e.serverVersion):"",iceServers:Array.isArray(null==e?void 0:e.iceServers)?e.iceServers.map((e=>At.fromJSON(e))):[],subscriberPrimary:!!isSet(e.subscriberPrimary)&&Boolean(e.subscriberPrimary),alternativeUrl:isSet(e.alternativeUrl)?String(e.alternativeUrl):"",clientConfiguration:isSet(e.clientConfiguration)?Ye.fromJSON(e.clientConfiguration):void 0,serverRegion:isSet(e.serverRegion)?String(e.serverRegion):"",pingTimeout:isSet(e.pingTimeout)?Number(e.pingTimeout):0,pingInterval:isSet(e.pingInterval)?Number(e.pingInterval):0,serverInfo:isSet(e.serverInfo)?Ze.fromJSON(e.serverInfo):void 0}),toJSON(e){const t={};return void 0!==e.room&&(t.room=e.room?$e.toJSON(e.room):void 0),void 0!==e.participant&&(t.participant=e.participant?Je.toJSON(e.participant):void 0),e.otherParticipants?t.otherParticipants=e.otherParticipants.map((e=>e?Je.toJSON(e):void 0)):t.otherParticipants=[],void 0!==e.serverVersion&&(t.serverVersion=e.serverVersion),e.iceServers?t.iceServers=e.iceServers.map((e=>e?At.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?Ye.toJSON(e.clientConfiguration):void 0),void 0!==e.serverRegion&&(t.serverRegion=e.serverRegion),void 0!==e.pingTimeout&&(t.pingTimeout=Math.round(e.pingTimeout)),void 0!==e.pingInterval&&(t.pingInterval=Math.round(e.pingInterval)),void 0!==e.serverInfo&&(t.serverInfo=e.serverInfo?Ze.toJSON(e.serverInfo):void 0),t},create:e=>Tt.fromPartial(null!=e?e:{}),fromPartial(e){var t,i,n,s,a,o,c,u;const l={room:void 0,participant:void 0,otherParticipants:[],serverVersion:"",iceServers:[],subscriberPrimary:!1,alternativeUrl:"",clientConfiguration:void 0,serverRegion:"",pingTimeout:0,pingInterval:0,serverInfo:void 0};return l.room=void 0!==e.room&&null!==e.room?$e.fromPartial(e.room):void 0,l.participant=void 0!==e.participant&&null!==e.participant?Je.fromPartial(e.participant):void 0,l.otherParticipants=(null===(t=e.otherParticipants)||void 0===t?void 0:t.map((e=>Je.fromPartial(e))))||[],l.serverVersion=null!==(i=e.serverVersion)&&void 0!==i?i:"",l.iceServers=(null===(n=e.iceServers)||void 0===n?void 0:n.map((e=>At.fromPartial(e))))||[],l.subscriberPrimary=null!==(s=e.subscriberPrimary)&&void 0!==s&&s,l.alternativeUrl=null!==(a=e.alternativeUrl)&&void 0!==a?a:"",l.clientConfiguration=void 0!==e.clientConfiguration&&null!==e.clientConfiguration?Ye.fromPartial(e.clientConfiguration):void 0,l.serverRegion=null!==(o=e.serverRegion)&&void 0!==o?o:"",l.pingTimeout=null!==(c=e.pingTimeout)&&void 0!==c?c:0,l.pingInterval=null!==(u=e.pingInterval)&&void 0!==u?u:0,l.serverInfo=void 0!==e.serverInfo&&null!==e.serverInfo?Ze.fromPartial(e.serverInfo):void 0,l}};const Ct={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xe.Writer.create();for(const i of e.iceServers)At.encode(i,t.uint32(10).fork()).ldelim();return void 0!==e.clientConfiguration&&Ye.encode(e.clientConfiguration,t.uint32(18).fork()).ldelim(),t},decode(e,t){const i=e instanceof xe.Reader?e:new xe.Reader(e);let n=void 0===t?i.len:i.pos+t;const s={iceServers:[],clientConfiguration:void 0};for(;i.pos>>3){case 1:s.iceServers.push(At.decode(i,i.uint32()));break;case 2:s.clientConfiguration=Ye.decode(i,i.uint32());break;default:i.skipType(7&e)}}return s},fromJSON:e=>({iceServers:Array.isArray(null==e?void 0:e.iceServers)?e.iceServers.map((e=>At.fromJSON(e))):[],clientConfiguration:isSet(e.clientConfiguration)?Ye.fromJSON(e.clientConfiguration):void 0}),toJSON(e){const t={};return e.iceServers?t.iceServers=e.iceServers.map((e=>e?At.toJSON(e):void 0)):t.iceServers=[],void 0!==e.clientConfiguration&&(t.clientConfiguration=e.clientConfiguration?Ye.toJSON(e.clientConfiguration):void 0),t},create:e=>Ct.fromPartial(null!=e?e:{}),fromPartial(e){var t;const i={iceServers:[],clientConfiguration:void 0};return i.iceServers=(null===(t=e.iceServers)||void 0===t?void 0:t.map((e=>At.fromPartial(e))))||[],i.clientConfiguration=void 0!==e.clientConfiguration&&null!==e.clientConfiguration?Ye.fromPartial(e.clientConfiguration):void 0,i}};const Pt={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xe.Writer.create();return""!==e.cid&&t.uint32(10).string(e.cid),void 0!==e.track&&je.encode(e.track,t.uint32(18).fork()).ldelim(),t},decode(e,t){const i=e instanceof xe.Reader?e:new xe.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=je.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)?je.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?je.toJSON(e.track):void 0),t},create:e=>Pt.fromPartial(null!=e?e:{}),fromPartial(e){var t;const i={cid:"",track:void 0};return i.cid=null!==(t=e.cid)&&void 0!==t?t:"",i.track=void 0!==e.track&&null!==e.track?je.fromPartial(e.track):void 0,i}};const Et={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xe.Writer.create();return""!==e.trackSid&&t.uint32(10).string(e.trackSid),t},decode(e,t){const i=e instanceof xe.Reader?e:new xe.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},create:e=>Et.fromPartial(null!=e?e:{}),fromPartial(e){var t;const i={trackSid:""};return i.trackSid=null!==(t=e.trackSid)&&void 0!==t?t:"",i}};const Rt={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xe.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 xe.Reader?e:new xe.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},create:e=>Rt.fromPartial(null!=e?e:{}),fromPartial(e){var t,i;const n={type:"",sdp:""};return n.type=null!==(t=e.type)&&void 0!==t?t:"",n.sdp=null!==(i=e.sdp)&&void 0!==i?i:"",n}};const Ot={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xe.Writer.create();for(const i of e.participants)Je.encode(i,t.uint32(10).fork()).ldelim();return t},decode(e,t){const i=e instanceof xe.Reader?e:new xe.Reader(e);let n=void 0===t?i.len:i.pos+t;const s={participants:[]};for(;i.pos>>3==1)s.participants.push(Je.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=>Je.fromJSON(e))):[]}),toJSON(e){const t={};return e.participants?t.participants=e.participants.map((e=>e?Je.toJSON(e):void 0)):t.participants=[],t},create:e=>Ot.fromPartial(null!=e?e:{}),fromPartial(e){var t;const i={participants:[]};return i.participants=(null===(t=e.participants)||void 0===t?void 0:t.map((e=>Je.fromPartial(e))))||[],i}};const Nt={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xe.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)He.encode(i,t.uint32(26).fork()).ldelim();return t},decode(e,t){const i=e instanceof xe.Reader?e:new xe.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(He.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=>He.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?He.toJSON(e):void 0)):t.participantTracks=[],t},create:e=>Nt.fromPartial(null!=e?e:{}),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=>He.fromPartial(e))))||[],s}};const It={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xe.Writer.create();for(const i of e.trackSids)t.uint32(10).string(i);return!0===e.disabled&&t.uint32(24).bool(e.disabled),0!==e.quality&&t.uint32(32).int32(e.quality),0!==e.width&&t.uint32(40).uint32(e.width),0!==e.height&&t.uint32(48).uint32(e.height),0!==e.fps&&t.uint32(56).uint32(e.fps),0!==e.priority&&t.uint32(64).uint32(e.priority),t},decode(e,t){const i=e instanceof xe.Reader?e:new xe.Reader(e);let n=void 0===t?i.len:i.pos+t;const s={trackSids:[],disabled:!1,quality:0,width:0,height:0,fps:0,priority: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;case 7:s.fps=i.uint32();break;case 8:s.priority=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,fps:isSet(e.fps)?Number(e.fps):0,priority:isSet(e.priority)?Number(e.priority):0}),toJSON(e){const t={};return e.trackSids?t.trackSids=e.trackSids.map((e=>e)):t.trackSids=[],void 0!==e.disabled&&(t.disabled=e.disabled),void 0!==e.quality&&(t.quality=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.fps&&(t.fps=Math.round(e.fps)),void 0!==e.priority&&(t.priority=Math.round(e.priority)),t},create:e=>It.fromPartial(null!=e?e:{}),fromPartial(e){var t,i,n,s,a,o,c;const u={trackSids:[],disabled:!1,quality:0,width:0,height:0,fps:0,priority:0};return u.trackSids=(null===(t=e.trackSids)||void 0===t?void 0:t.map((e=>e)))||[],u.disabled=null!==(i=e.disabled)&&void 0!==i&&i,u.quality=null!==(n=e.quality)&&void 0!==n?n:0,u.width=null!==(s=e.width)&&void 0!==s?s:0,u.height=null!==(a=e.height)&&void 0!==a?a:0,u.fps=null!==(o=e.fps)&&void 0!==o?o:0,u.priority=null!==(c=e.priority)&&void 0!==c?c:0,u}};const Dt={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xe.Writer.create();return!0===e.canReconnect&&t.uint32(8).bool(e.canReconnect),0!==e.reason&&t.uint32(16).int32(e.reason),t},decode(e,t){const i=e instanceof xe.Reader?e:new xe.Reader(e);let n=void 0===t?i.len:i.pos+t;const s={canReconnect:!1,reason:0};for(;i.pos>>3){case 1:s.canReconnect=i.bool();break;case 2:s.reason=i.int32();break;default:i.skipType(7&e)}}return s},fromJSON:e=>({canReconnect:!!isSet(e.canReconnect)&&Boolean(e.canReconnect),reason:isSet(e.reason)?disconnectReasonFromJSON(e.reason):0}),toJSON(e){const t={};return void 0!==e.canReconnect&&(t.canReconnect=e.canReconnect),void 0!==e.reason&&(t.reason=function disconnectReasonToJSON(e){switch(e){case Ie.UNKNOWN_REASON:return"UNKNOWN_REASON";case Ie.CLIENT_INITIATED:return"CLIENT_INITIATED";case Ie.DUPLICATE_IDENTITY:return"DUPLICATE_IDENTITY";case Ie.SERVER_SHUTDOWN:return"SERVER_SHUTDOWN";case Ie.PARTICIPANT_REMOVED:return"PARTICIPANT_REMOVED";case Ie.ROOM_DELETED:return"ROOM_DELETED";case Ie.STATE_MISMATCH:return"STATE_MISMATCH";case Ie.JOIN_FAILURE:return"JOIN_FAILURE";case Ie.UNRECOGNIZED:default:return"UNRECOGNIZED"}}(e.reason)),t},create:e=>Dt.fromPartial(null!=e?e:{}),fromPartial(e){var t,i;const n={canReconnect:!1,reason:0};return n.canReconnect=null!==(t=e.canReconnect)&&void 0!==t&&t,n.reason=null!==(i=e.reason)&&void 0!==i?i:0,n}};const _t={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xe.Writer.create();""!==e.trackSid&&t.uint32(10).string(e.trackSid);for(const i of e.layers)We.encode(i,t.uint32(18).fork()).ldelim();return t},decode(e,t){const i=e instanceof xe.Reader?e:new xe.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(We.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=>We.fromJSON(e))):[]}),toJSON(e){const t={};return void 0!==e.trackSid&&(t.trackSid=e.trackSid),e.layers?t.layers=e.layers.map((e=>e?We.toJSON(e):void 0)):t.layers=[],t},create:e=>_t.fromPartial(null!=e?e:{}),fromPartial(e){var t,i;const n={trackSid:"",layers:[]};return n.trackSid=null!==(t=e.trackSid)&&void 0!==t?t:"",n.layers=(null===(i=e.layers)||void 0===i?void 0:i.map((e=>We.fromPartial(e))))||[],n}};const Lt={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xe.Writer.create();return""!==e.metadata&&t.uint32(10).string(e.metadata),t},decode(e,t){const i=e instanceof xe.Reader?e:new xe.Reader(e);let n=void 0===t?i.len:i.pos+t;const s={metadata:""};for(;i.pos>>3==1)s.metadata=i.string();else i.skipType(7&e)}return s},fromJSON:e=>({metadata:isSet(e.metadata)?String(e.metadata):""}),toJSON(e){const t={};return void 0!==e.metadata&&(t.metadata=e.metadata),t},create:e=>Lt.fromPartial(null!=e?e:{}),fromPartial(e){var t;const i={metadata:""};return i.metadata=null!==(t=e.metadata)&&void 0!==t?t:"",i}};const At={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xe.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 xe.Reader?e:new xe.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},create:e=>At.fromPartial(null!=e?e:{}),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 Ut={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xe.Writer.create();for(const i of e.speakers)Qe.encode(i,t.uint32(10).fork()).ldelim();return t},decode(e,t){const i=e instanceof xe.Reader?e:new xe.Reader(e);let n=void 0===t?i.len:i.pos+t;const s={speakers:[]};for(;i.pos>>3==1)s.speakers.push(Qe.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=>Qe.fromJSON(e))):[]}),toJSON(e){const t={};return e.speakers?t.speakers=e.speakers.map((e=>e?Qe.toJSON(e):void 0)):t.speakers=[],t},create:e=>Ut.fromPartial(null!=e?e:{}),fromPartial(e){var t;const i={speakers:[]};return i.speakers=(null===(t=e.speakers)||void 0===t?void 0:t.map((e=>Qe.fromPartial(e))))||[],i}};const Mt={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xe.Writer.create();return void 0!==e.room&&$e.encode(e.room,t.uint32(10).fork()).ldelim(),t},decode(e,t){const i=e instanceof xe.Reader?e:new xe.Reader(e);let n=void 0===t?i.len:i.pos+t;const s={room:void 0};for(;i.pos>>3==1)s.room=$e.decode(i,i.uint32());else i.skipType(7&e)}return s},fromJSON:e=>({room:isSet(e.room)?$e.fromJSON(e.room):void 0}),toJSON(e){const t={};return void 0!==e.room&&(t.room=e.room?$e.toJSON(e.room):void 0),t},create:e=>Mt.fromPartial(null!=e?e:{}),fromPartial(e){const t={room:void 0};return t.room=void 0!==e.room&&null!==e.room?$e.fromPartial(e.room):void 0,t}};const xt={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xe.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 xe.Reader?e:new xe.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 Oe.POOR:return"POOR";case Oe.GOOD:return"GOOD";case Oe.EXCELLENT:return"EXCELLENT";case Oe.UNRECOGNIZED:default:return"UNRECOGNIZED"}}(e.quality)),void 0!==e.score&&(t.score=e.score),t},create:e=>xt.fromPartial(null!=e?e:{}),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 $t={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xe.Writer.create();for(const i of e.updates)xt.encode(i,t.uint32(10).fork()).ldelim();return t},decode(e,t){const i=e instanceof xe.Reader?e:new xe.Reader(e);let n=void 0===t?i.len:i.pos+t;const s={updates:[]};for(;i.pos>>3==1)s.updates.push(xt.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=>xt.fromJSON(e))):[]}),toJSON(e){const t={};return e.updates?t.updates=e.updates.map((e=>e?xt.toJSON(e):void 0)):t.updates=[],t},create:e=>$t.fromPartial(null!=e?e:{}),fromPartial(e){var t;const i={updates:[]};return i.updates=(null===(t=e.updates)||void 0===t?void 0:t.map((e=>xt.fromPartial(e))))||[],i}};const Bt={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xe.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 xe.Reader?e:new xe.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 mt.ACTIVE:return"ACTIVE";case mt.PAUSED:return"PAUSED";case mt.UNRECOGNIZED:default:return"UNRECOGNIZED"}}(e.state)),t},create:e=>Bt.fromPartial(null!=e?e:{}),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 Ft={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xe.Writer.create();for(const i of e.streamStates)Bt.encode(i,t.uint32(10).fork()).ldelim();return t},decode(e,t){const i=e instanceof xe.Reader?e:new xe.Reader(e);let n=void 0===t?i.len:i.pos+t;const s={streamStates:[]};for(;i.pos>>3==1)s.streamStates.push(Bt.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=>Bt.fromJSON(e))):[]}),toJSON(e){const t={};return e.streamStates?t.streamStates=e.streamStates.map((e=>e?Bt.toJSON(e):void 0)):t.streamStates=[],t},create:e=>Ft.fromPartial(null!=e?e:{}),fromPartial(e){var t;const i={streamStates:[]};return i.streamStates=(null===(t=e.streamStates)||void 0===t?void 0:t.map((e=>Bt.fromPartial(e))))||[],i}};const Jt={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xe.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 xe.Reader?e:new xe.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},create:e=>Jt.fromPartial(null!=e?e:{}),fromPartial(e){var t,i;const n={quality:0,enabled:!1};return n.quality=null!==(t=e.quality)&&void 0!==t?t:0,n.enabled=null!==(i=e.enabled)&&void 0!==i&&i,n}};const Vt={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xe.Writer.create();""!==e.codec&&t.uint32(10).string(e.codec);for(const i of e.qualities)Jt.encode(i,t.uint32(18).fork()).ldelim();return t},decode(e,t){const i=e instanceof xe.Reader?e:new xe.Reader(e);let n=void 0===t?i.len:i.pos+t;const s={codec:"",qualities:[]};for(;i.pos>>3){case 1:s.codec=i.string();break;case 2:s.qualities.push(Jt.decode(i,i.uint32()));break;default:i.skipType(7&e)}}return s},fromJSON:e=>({codec:isSet(e.codec)?String(e.codec):"",qualities:Array.isArray(null==e?void 0:e.qualities)?e.qualities.map((e=>Jt.fromJSON(e))):[]}),toJSON(e){const t={};return void 0!==e.codec&&(t.codec=e.codec),e.qualities?t.qualities=e.qualities.map((e=>e?Jt.toJSON(e):void 0)):t.qualities=[],t},create:e=>Vt.fromPartial(null!=e?e:{}),fromPartial(e){var t,i;const n={codec:"",qualities:[]};return n.codec=null!==(t=e.codec)&&void 0!==t?t:"",n.qualities=(null===(i=e.qualities)||void 0===i?void 0:i.map((e=>Jt.fromPartial(e))))||[],n}};const jt={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xe.Writer.create();""!==e.trackSid&&t.uint32(10).string(e.trackSid);for(const i of e.subscribedQualities)Jt.encode(i,t.uint32(18).fork()).ldelim();for(const i of e.subscribedCodecs)Vt.encode(i,t.uint32(26).fork()).ldelim();return t},decode(e,t){const i=e instanceof xe.Reader?e:new xe.Reader(e);let n=void 0===t?i.len:i.pos+t;const s={trackSid:"",subscribedQualities:[],subscribedCodecs:[]};for(;i.pos>>3){case 1:s.trackSid=i.string();break;case 2:s.subscribedQualities.push(Jt.decode(i,i.uint32()));break;case 3:s.subscribedCodecs.push(Vt.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=>Jt.fromJSON(e))):[],subscribedCodecs:Array.isArray(null==e?void 0:e.subscribedCodecs)?e.subscribedCodecs.map((e=>Vt.fromJSON(e))):[]}),toJSON(e){const t={};return void 0!==e.trackSid&&(t.trackSid=e.trackSid),e.subscribedQualities?t.subscribedQualities=e.subscribedQualities.map((e=>e?Jt.toJSON(e):void 0)):t.subscribedQualities=[],e.subscribedCodecs?t.subscribedCodecs=e.subscribedCodecs.map((e=>e?Vt.toJSON(e):void 0)):t.subscribedCodecs=[],t},create:e=>jt.fromPartial(null!=e?e:{}),fromPartial(e){var t,i,n;const s={trackSid:"",subscribedQualities:[],subscribedCodecs:[]};return s.trackSid=null!==(t=e.trackSid)&&void 0!==t?t:"",s.subscribedQualities=(null===(i=e.subscribedQualities)||void 0===i?void 0:i.map((e=>Jt.fromPartial(e))))||[],s.subscribedCodecs=(null===(n=e.subscribedCodecs)||void 0===n?void 0:n.map((e=>Vt.fromPartial(e))))||[],s}};const Wt={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xe.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 xe.Reader?e:new xe.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},create:e=>Wt.fromPartial(null!=e?e:{}),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 qt={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xe.Writer.create();!0===e.allParticipants&&t.uint32(8).bool(e.allParticipants);for(const i of e.trackPermissions)Wt.encode(i,t.uint32(18).fork()).ldelim();return t},decode(e,t){const i=e instanceof xe.Reader?e:new xe.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(Wt.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=>Wt.fromJSON(e))):[]}),toJSON(e){const t={};return void 0!==e.allParticipants&&(t.allParticipants=e.allParticipants),e.trackPermissions?t.trackPermissions=e.trackPermissions.map((e=>e?Wt.toJSON(e):void 0)):t.trackPermissions=[],t},create:e=>qt.fromPartial(null!=e?e:{}),fromPartial(e){var t,i;const n={allParticipants:!1,trackPermissions:[]};return n.allParticipants=null!==(t=e.allParticipants)&&void 0!==t&&t,n.trackPermissions=(null===(i=e.trackPermissions)||void 0===i?void 0:i.map((e=>Wt.fromPartial(e))))||[],n}};const Gt={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xe.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 xe.Reader?e:new xe.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},create:e=>Gt.fromPartial(null!=e?e:{}),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 Qt={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xe.Writer.create();void 0!==e.answer&&Rt.encode(e.answer,t.uint32(10).fork()).ldelim(),void 0!==e.subscription&&Nt.encode(e.subscription,t.uint32(18).fork()).ldelim();for(const i of e.publishTracks)Pt.encode(i,t.uint32(26).fork()).ldelim();for(const i of e.dataChannels)zt.encode(i,t.uint32(34).fork()).ldelim();return void 0!==e.offer&&Rt.encode(e.offer,t.uint32(42).fork()).ldelim(),t},decode(e,t){const i=e instanceof xe.Reader?e:new xe.Reader(e);let n=void 0===t?i.len:i.pos+t;const s={answer:void 0,subscription:void 0,publishTracks:[],dataChannels:[],offer:void 0};for(;i.pos>>3){case 1:s.answer=Rt.decode(i,i.uint32());break;case 2:s.subscription=Nt.decode(i,i.uint32());break;case 3:s.publishTracks.push(Pt.decode(i,i.uint32()));break;case 4:s.dataChannels.push(zt.decode(i,i.uint32()));break;case 5:s.offer=Rt.decode(i,i.uint32());break;default:i.skipType(7&e)}}return s},fromJSON:e=>({answer:isSet(e.answer)?Rt.fromJSON(e.answer):void 0,subscription:isSet(e.subscription)?Nt.fromJSON(e.subscription):void 0,publishTracks:Array.isArray(null==e?void 0:e.publishTracks)?e.publishTracks.map((e=>Pt.fromJSON(e))):[],dataChannels:Array.isArray(null==e?void 0:e.dataChannels)?e.dataChannels.map((e=>zt.fromJSON(e))):[],offer:isSet(e.offer)?Rt.fromJSON(e.offer):void 0}),toJSON(e){const t={};return void 0!==e.answer&&(t.answer=e.answer?Rt.toJSON(e.answer):void 0),void 0!==e.subscription&&(t.subscription=e.subscription?Nt.toJSON(e.subscription):void 0),e.publishTracks?t.publishTracks=e.publishTracks.map((e=>e?Pt.toJSON(e):void 0)):t.publishTracks=[],e.dataChannels?t.dataChannels=e.dataChannels.map((e=>e?zt.toJSON(e):void 0)):t.dataChannels=[],void 0!==e.offer&&(t.offer=e.offer?Rt.toJSON(e.offer):void 0),t},create:e=>Qt.fromPartial(null!=e?e:{}),fromPartial(e){var t,i;const n={answer:void 0,subscription:void 0,publishTracks:[],dataChannels:[],offer:void 0};return n.answer=void 0!==e.answer&&null!==e.answer?Rt.fromPartial(e.answer):void 0,n.subscription=void 0!==e.subscription&&null!==e.subscription?Nt.fromPartial(e.subscription):void 0,n.publishTracks=(null===(t=e.publishTracks)||void 0===t?void 0:t.map((e=>Pt.fromPartial(e))))||[],n.dataChannels=(null===(i=e.dataChannels)||void 0===i?void 0:i.map((e=>zt.fromPartial(e))))||[],n.offer=void 0!==e.offer&&null!==e.offer?Rt.fromPartial(e.offer):void 0,n}};const zt={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xe.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 xe.Reader?e:new xe.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},create:e=>zt.fromPartial(null!=e?e:{}),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 Ht={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xe.Writer.create();var i;switch(null===(i=e.scenario)||void 0===i?void 0:i.$case){case"speakerUpdate":t.uint32(8).int32(e.scenario.speakerUpdate);break;case"nodeFailure":t.uint32(16).bool(e.scenario.nodeFailure);break;case"migration":t.uint32(24).bool(e.scenario.migration);break;case"serverLeave":t.uint32(32).bool(e.scenario.serverLeave);break;case"switchCandidateProtocol":t.uint32(40).int32(e.scenario.switchCandidateProtocol)}return t},decode(e,t){const i=e instanceof xe.Reader?e:new xe.Reader(e);let n=void 0===t?i.len:i.pos+t;const s={scenario:void 0};for(;i.pos>>3){case 1:s.scenario={$case:"speakerUpdate",speakerUpdate:i.int32()};break;case 2:s.scenario={$case:"nodeFailure",nodeFailure:i.bool()};break;case 3:s.scenario={$case:"migration",migration:i.bool()};break;case 4:s.scenario={$case:"serverLeave",serverLeave:i.bool()};break;case 5:s.scenario={$case:"switchCandidateProtocol",switchCandidateProtocol:i.int32()};break;default:i.skipType(7&e)}}return s},fromJSON:e=>({scenario:isSet(e.speakerUpdate)?{$case:"speakerUpdate",speakerUpdate:Number(e.speakerUpdate)}:isSet(e.nodeFailure)?{$case:"nodeFailure",nodeFailure:Boolean(e.nodeFailure)}:isSet(e.migration)?{$case:"migration",migration:Boolean(e.migration)}:isSet(e.serverLeave)?{$case:"serverLeave",serverLeave:Boolean(e.serverLeave)}:isSet(e.switchCandidateProtocol)?{$case:"switchCandidateProtocol",switchCandidateProtocol:candidateProtocolFromJSON(e.switchCandidateProtocol)}:void 0}),toJSON(e){var t,i,n,s,a,o,c,u,l,h,p;const m={};return"speakerUpdate"===(null===(t=e.scenario)||void 0===t?void 0:t.$case)&&(m.speakerUpdate=Math.round(null===(i=e.scenario)||void 0===i?void 0:i.speakerUpdate)),"nodeFailure"===(null===(n=e.scenario)||void 0===n?void 0:n.$case)&&(m.nodeFailure=null===(s=e.scenario)||void 0===s?void 0:s.nodeFailure),"migration"===(null===(a=e.scenario)||void 0===a?void 0:a.$case)&&(m.migration=null===(o=e.scenario)||void 0===o?void 0:o.migration),"serverLeave"===(null===(c=e.scenario)||void 0===c?void 0:c.$case)&&(m.serverLeave=null===(u=e.scenario)||void 0===u?void 0:u.serverLeave),"switchCandidateProtocol"===(null===(l=e.scenario)||void 0===l?void 0:l.$case)&&(m.switchCandidateProtocol=void 0!==(null===(h=e.scenario)||void 0===h?void 0:h.switchCandidateProtocol)?function candidateProtocolToJSON(e){switch(e){case ft.UDP:return"UDP";case ft.TCP:return"TCP";case ft.TLS:return"TLS";case ft.UNRECOGNIZED:default:return"UNRECOGNIZED"}}(null===(p=e.scenario)||void 0===p?void 0:p.switchCandidateProtocol):void 0),m},create:e=>Ht.fromPartial(null!=e?e:{}),fromPartial(e){var t,i,n,s,a,o,c,u,l,h,p,m,v,g,b;const S={scenario:void 0};return"speakerUpdate"===(null===(t=e.scenario)||void 0===t?void 0:t.$case)&&void 0!==(null===(i=e.scenario)||void 0===i?void 0:i.speakerUpdate)&&null!==(null===(n=e.scenario)||void 0===n?void 0:n.speakerUpdate)&&(S.scenario={$case:"speakerUpdate",speakerUpdate:e.scenario.speakerUpdate}),"nodeFailure"===(null===(s=e.scenario)||void 0===s?void 0:s.$case)&&void 0!==(null===(a=e.scenario)||void 0===a?void 0:a.nodeFailure)&&null!==(null===(o=e.scenario)||void 0===o?void 0:o.nodeFailure)&&(S.scenario={$case:"nodeFailure",nodeFailure:e.scenario.nodeFailure}),"migration"===(null===(c=e.scenario)||void 0===c?void 0:c.$case)&&void 0!==(null===(u=e.scenario)||void 0===u?void 0:u.migration)&&null!==(null===(l=e.scenario)||void 0===l?void 0:l.migration)&&(S.scenario={$case:"migration",migration:e.scenario.migration}),"serverLeave"===(null===(h=e.scenario)||void 0===h?void 0:h.$case)&&void 0!==(null===(p=e.scenario)||void 0===p?void 0:p.serverLeave)&&null!==(null===(m=e.scenario)||void 0===m?void 0:m.serverLeave)&&(S.scenario={$case:"serverLeave",serverLeave:e.scenario.serverLeave}),"switchCandidateProtocol"===(null===(v=e.scenario)||void 0===v?void 0:v.$case)&&void 0!==(null===(g=e.scenario)||void 0===g?void 0:g.switchCandidateProtocol)&&null!==(null===(b=e.scenario)||void 0===b?void 0:b.switchCandidateProtocol)&&(S.scenario={$case:"switchCandidateProtocol",switchCandidateProtocol:e.scenario.switchCandidateProtocol}),S}};const Zt={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xe.Writer.create();return 0!==e.timestamp&&t.uint32(8).int64(e.timestamp),0!==e.rtt&&t.uint32(16).int64(e.rtt),t},decode(e,t){const i=e instanceof xe.Reader?e:new xe.Reader(e);let n=void 0===t?i.len:i.pos+t;const s={timestamp:0,rtt:0};for(;i.pos>>3){case 1:s.timestamp=longToNumber(i.int64());break;case 2:s.rtt=longToNumber(i.int64());break;default:i.skipType(7&e)}}return s},fromJSON:e=>({timestamp:isSet(e.timestamp)?Number(e.timestamp):0,rtt:isSet(e.rtt)?Number(e.rtt):0}),toJSON(e){const t={};return void 0!==e.timestamp&&(t.timestamp=Math.round(e.timestamp)),void 0!==e.rtt&&(t.rtt=Math.round(e.rtt)),t},create:e=>Zt.fromPartial(null!=e?e:{}),fromPartial(e){var t,i;const n={timestamp:0,rtt:0};return n.timestamp=null!==(t=e.timestamp)&&void 0!==t?t:0,n.rtt=null!==(i=e.rtt)&&void 0!==i?i:0,n}};const Kt={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xe.Writer.create();return 0!==e.lastPingTimestamp&&t.uint32(8).int64(e.lastPingTimestamp),0!==e.timestamp&&t.uint32(16).int64(e.timestamp),t},decode(e,t){const i=e instanceof xe.Reader?e:new xe.Reader(e);let n=void 0===t?i.len:i.pos+t;const s={lastPingTimestamp:0,timestamp:0};for(;i.pos>>3){case 1:s.lastPingTimestamp=longToNumber(i.int64());break;case 2:s.timestamp=longToNumber(i.int64());break;default:i.skipType(7&e)}}return s},fromJSON:e=>({lastPingTimestamp:isSet(e.lastPingTimestamp)?Number(e.lastPingTimestamp):0,timestamp:isSet(e.timestamp)?Number(e.timestamp):0}),toJSON(e){const t={};return void 0!==e.lastPingTimestamp&&(t.lastPingTimestamp=Math.round(e.lastPingTimestamp)),void 0!==e.timestamp&&(t.timestamp=Math.round(e.timestamp)),t},create:e=>Kt.fromPartial(null!=e?e:{}),fromPartial(e){var t,i;const n={lastPingTimestamp:0,timestamp:0};return n.lastPingTimestamp=null!==(t=e.lastPingTimestamp)&&void 0!==t?t:0,n.timestamp=null!==(i=e.timestamp)&&void 0!==i?i:0,n}};var Yt,Xt,ei,ti,ii,ri=(()=>{if("undefined"!=typeof globalThis)return globalThis;if("undefined"!=typeof self)return self;if("undefined"!=typeof window)return window;if("undefined"!=typeof global)return global;throw"Unable to locate global object"})();function longToNumber(e){if(e.gt(Number.MAX_SAFE_INTEGER))throw new ri.Error("Value is larger than Number.MAX_SAFE_INTEGER");return e.toNumber()}function isSet(e){return null!=e}xe.util.Long!==p&&(xe.util.Long=p,xe.configure());class LivekitError extends Error{constructor(e,t){super(t||"an error has occured"),this.code=e}}class ConnectionError extends LivekitError{constructor(e,t,i){super(1,e),this.status=i,this.reason=t}}class DeviceUnsupportedError extends LivekitError{constructor(e){super(21,null!=e?e:"device is unsupported")}}class TrackInvalidError extends LivekitError{constructor(e){super(20,null!=e?e:"track is invalid")}}class UnsupportedServer extends LivekitError{constructor(e){super(10,null!=e?e:"unsupported server")}}class UnexpectedConnectionState extends LivekitError{constructor(e){super(12,null!=e?e:"unexpected connection state")}}class NegotiationError extends LivekitError{constructor(e){super(13,null!=e?e:"unable to negotiate")}}class PublishDataError extends LivekitError{constructor(e){super(13,null!=e?e:"unable to publish data")}}!function(e){e.PermissionDenied="PermissionDenied",e.NotFound="NotFound",e.DeviceInUse="DeviceInUse",e.Other="Other"}(Yt||(Yt={})),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}}(Yt||(Yt={})),function(e){e.Connected="connected",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.LocalAudioSilenceDetected="localAudioSilenceDetected",e.ActiveSpeakersChanged="activeSpeakersChanged",e.ParticipantMetadataChanged="participantMetadataChanged",e.RoomMetadataChanged="roomMetadataChanged",e.DataReceived="dataReceived",e.ConnectionQualityChanged="connectionQualityChanged",e.TrackStreamStateChanged="trackStreamStateChanged",e.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",e.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",e.AudioPlaybackStatusChanged="audioPlaybackChanged",e.MediaDevicesError="mediaDevicesError",e.ParticipantPermissionsChanged="participantPermissionsChanged",e.SignalConnected="signalConnected",e.RecordingStatusChanged="recordingStatusChanged"}(Xt||(Xt={})),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.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",e.MediaDevicesError="mediaDevicesError",e.ParticipantPermissionsChanged="participantPermissionsChanged"}(ei||(ei={})),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.Closing="closing",e.MediaTrackAdded="mediaTrackAdded",e.ActiveSpeakersUpdate="activeSpeakersUpdate",e.DataPacketReceived="dataPacketReceived"}(ti||(ti={})),function(e){e.Message="message",e.Muted="muted",e.Unmuted="unmuted",e.Restarted="restarted",e.Ended="ended",e.Subscribed="subscribed",e.Unsubscribed="unsubscribed",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",e.SubscriptionPermissionChanged="subscriptionPermissionChanged",e.SubscriptionStatusChanged="subscriptionStatusChanged"}(ii||(ii={}));const ni=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)}var si={};!function(e,t){!function(i,n){var s="function",a="undefined",o="object",c="string",u="model",l="name",h="type",p="vendor",m="version",v="architecture",g="console",b="mobile",S="tablet",k="smarttv",y="wearable",w="embedded",T="Amazon",C="Apple",P="ASUS",E="BlackBerry",R="Firefox",O="Google",N="Huawei",I="LG",D="Microsoft",_="Motorola",L="Opera",A="Samsung",U="Sharp",M="Sony",x="Xiaomi",$="Zebra",B="Facebook",enumerize=function(e){for(var t={},i=0;i0?2===u.length?typeof u[1]==s?this[u[0]]=u[1].call(this,h):this[u[0]]=u[1]:3===u.length?typeof u[1]!==s||u[1].exec&&u[1].test?this[u[0]]=h?h.replace(u[1],u[2]):n:this[u[0]]=h?u[1].call(this,h,u[2]):n:4===u.length&&(this[u[0]]=h?u[3].call(this,h.replace(u[1],u[2])):n):this[u]=h||n;p+=2}},strMapper=function(e,t){for(var i in t)if(typeof t[i]===o&&t[i].length>0){for(var s=0;s350?trim(e,350):e,this},this.setUA(s),this};UAParser.VERSION="1.0.33",UAParser.BROWSER=enumerize([l,m,"major"]),UAParser.CPU=enumerize([v]),UAParser.DEVICE=enumerize([u,p,h,g,b,k,S,y,w]),UAParser.ENGINE=UAParser.OS=enumerize([l,m]),e.exports&&(t=e.exports=UAParser),t.UAParser=UAParser;var V=typeof i!==a&&(i.jQuery||i.Zepto);if(V&&!V.ua){var j=new UAParser;V.ua=j.getResult(),V.ua.get=function(){return j.getUA()},V.ua.set=function(e){j.setUA(e);var t=j.getResult();for(var i in t)V.ua[i]=t[i]}}}("object"==typeof window?window:s)}({get exports(){return si},set exports(e){si=e}},si);var ai=si;const oi="1.7.1",ci=9;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="undefined"!=typeof window&&(window.AudioContext||window.webkitAudioContext);if(e)return new e({latencyHint:"interactive"})}async function sleep(e){return new Promise((t=>setTimeout(t,e)))}function supportsTransceiver(){return"addTransceiver"in RTCPeerConnection.prototype}function supportsAddTrack(){return"addTrack"in RTCPeerConnection.prototype}function supportsAdaptiveStream(){return void 0!==typeof ResizeObserver&&void 0!==typeof IntersectionObserver}function supportsDynacast(){return supportsTransceiver()}function supportsAV1(){const e=RTCRtpReceiver.getCapabilities("video");let t=!1,i=!1;if(e){for(const i of e.codecs)if("video/AV1"===i.mimeType){t=!0;break}for(const t of e.headerExtensions)if("https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension"===t.uri){i=!0;break}}return t&&i}function supportsSetSinkId(e){return!!document&&(e||(e=document.createElement("audio")),"setSinkId"in e)}const di={Chrome:"100",Chromium:"100",Safari:"15",Firefox:"100",Edge:"100",Brave:"1.40"};function supportsSetCodecPreferences(e){if(!isWeb())return!1;if(!("setCodecPreferences"in e))return!1;const t=ai();if(!t.browser.name||!t.browser.version)return!1;const i=di[t.browser.name];return!!i&&function compareVersions(e,t){const i=e.split("."),n=t.split("."),s=Math.min(e.length,t.length);for(let e=0;es)return 1;if(t=0}function isBrowserSupported(){return supportsTransceiver()||supportsAddTrack()}function isFireFox(){return!!isWeb()&&-1!==navigator.userAgent.indexOf("Firefox")}function isSafari(){return!!isWeb()&&/^((?!chrome|android).)*safari/i.test(navigator.userAgent)}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 ui=null;const getResizeObserver=()=>(ui||(ui=new ResizeObserver(roDispatchCallback)),ui);let li=null;const getIntersectionObserver=()=>(li||(li=new IntersectionObserver(ioDispatchCallback,{root:document,rootMargin:"0px"})),li);let hi,pi;function getEmptyVideoStreamTrack(){return hi||(hi=createDummyVideoStreamTrack()),hi}function createDummyVideoStreamTrack(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:16,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:16,i=arguments.length>2&&void 0!==arguments[2]&&arguments[2],n=arguments.length>3&&void 0!==arguments[3]&&arguments[3];const s=document.createElement("canvas");s.width=e,s.height=t;const a=s.getContext("2d");null==a||a.fillRect(0,0,s.width,s.height),n&&a&&(a.beginPath(),a.arc(e/2,t/2,50,0,2*Math.PI,!0),a.closePath(),a.fillStyle="grey",a.fill());const o=s.captureStream(),[c]=o.getTracks();if(!c)throw Error("Could not get empty media stream video track");return c.enabled=i,c}function getEmptyAudioStreamTrack(){if(!pi){const e=new AudioContext,t=e.createOscillator(),i=e.createMediaStreamDestination();if(t.connect(i),t.start(),[pi]=i.stream.getAudioTracks(),!pi)throw Error("Could not get empty media stream audio track");pi.enabled=!1}return pi}class Future{constructor(e,t){this.onFinally=t,this.promise=new Promise((async(t,i)=>{this.resolve=t,this.reject=i,e&&await e(t,i)})).finally((()=>{var e;return null===(e=this.onFinally)||void 0===e?void 0:e.call(this)}))}}function createAudioAnalyser(e,t){const i=_objectSpread2({cloneTrack:!1,fftSize:2048,smoothingTimeConstant:.8,minDecibels:-100,maxDecibels:-80},t),n=getNewAudioContext();if(!n)throw new Error("Audio Context not supported on this browser");const s=i.cloneTrack?e.mediaStreamTrack.clone():e.mediaStreamTrack,a=n.createMediaStreamSource(new MediaStream([s])),o=n.createAnalyser();o.minDecibels=i.minDecibels,o.maxDecibels=i.maxDecibels,o.fftSize=i.fftSize,o.smoothingTimeConstant=i.smoothingTimeConstant,a.connect(o);const c=new Uint8Array(o.frequencyBinCount);return{calculateVolume:()=>{o.getByteFrequencyData(c);let e=0;for(const t of c)e+=Math.pow(t/255,2);return Math.sqrt(e/c.length)},analyser:o,cleanup:()=>{n.close(),i.cloneTrack&&s.stop()}}}class Mutex{constructor(){this._locking=Promise.resolve(),this._locks=0}isLocked(){return this._locks>0}lock(){let e;this._locks+=1;const t=new Promise((t=>e=()=>{this._locks-=1,t()})),i=this._locking.then((()=>e));return this._locking=this._locking.then((()=>t)),i}}class Queue{constructor(e,t){this.maxConcurrent=e||1,this.minCycle=t||0,this.queueRunning=[],this.queueWaiting={},this.lastRun=0}dequeue(e){const t=this.queueRunning,i=t.findIndex((t=>t.hash===e));if(-1==i)throw"queue desync";const n=t[i];return t.splice(i,1),n}getFirstWaiting(){for(let e of Object.keys(this.queueWaiting).sort(((e,t)=>e-t)))if(void 0!==this.queueWaiting[e]&&this.queueWaiting[e].length>0)return this.queueWaiting[e]}end(e){this.dequeue(e).resolve();const t=this.getFirstWaiting();if(void 0!==t){t.shift().resolve()}}async wait(e,t){const i=void 0===t?0:t;let n={hash:e,priority:i};for(null==this.queueWaiting[i]&&(this.queueWaiting[i]=[]),this.queueRunning.length>=this.maxConcurrent&&(n.promise=new Promise((e=>{n.resolve=e})),this.queueWaiting[i].push(n),await n.promise),this.queueRunning.push(n),n.promise=new Promise((e=>{n.resolve=e}));Date.now()-this.lastRunsetTimeout(e,this.minCycle-Date.now()+this.lastRun)));this.lastRun=Date.now()}run(e,t){const i=void 0===t?0:t,n=Symbol();return this.wait(n,i).then((()=>e())).finally((()=>{this.end(n)}))}stat(){return{running:this.queueRunning.length,waiting:Object.keys(this.queueWaiting).reduce(((e,t)=>e+this.queueWaiting[t].length),0),last:this.lastRun}}async flush(){for(;this.stat().waiting>0;)for(let e of Object.keys(this.queueWaiting).sort(((e,t)=>t-e))){const t=this.queueWaiting[e];void 0!==t&&t.length>0&&await t[t.length-1].promise}for(;this.queueRunning.length>0;)await Promise.allSettled(this.queueRunning.map((e=>e.promise)))}}const mi="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];var i;if((null===(i=DeviceManager.userMediaPromiseMap)||void 0===i?void 0:i.size)>0){h.debug("awaiting getUserMedia promise");try{e?await DeviceManager.userMediaPromiseMap.get(e):await Promise.all(DeviceManager.userMediaPromiseMap.values())}catch(e){h.warn("error waiting for media permissons")}}let n=await navigator.mediaDevices.enumerateDevices();if(t&&e&&(!DeviceManager.userMediaPromiseMap.get(e)||!isSafari())){if(0===n.length||n.some((t=>{const i=""===t.label,n=!e||t.kind===e;return i&&n}))){const t={video:"audioinput"!==e&&"audiooutput"!==e,audio:"videoinput"!==e},i=await navigator.mediaDevices.getUserMedia(t);n=await navigator.mediaDevices.enumerateDevices(),i.getTracks().forEach((e=>{e.stop()}))}}return e&&(n=n.filter((t=>t.kind===e))),n}async normalizeDeviceId(e,t,i){if(t!==mi)return t;const n=(await this.getDevices(e)).find((e=>e.groupId===i&&e.deviceId!==mi));return null==n?void 0:n.deviceId}}DeviceManager.mediaDeviceKinds=["audioinput","audiooutput","videoinput"],DeviceManager.userMediaPromiseMap=new Map;var fi,vi={},gi={get exports(){return vi},set exports(e){vi=e}},bi="object"==typeof Reflect?Reflect:null,Si=bi&&"function"==typeof bi.apply?bi.apply:function ReflectApply(e,t,i){return Function.prototype.apply.call(e,t,i)};fi=bi&&"function"==typeof bi.ownKeys?bi.ownKeys:Object.getOwnPropertySymbols?function ReflectOwnKeys(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function ReflectOwnKeys(e){return Object.getOwnPropertyNames(e)};var ki=Number.isNaN||function NumberIsNaN(e){return e!=e};function EventEmitter(){EventEmitter.init.call(this)}gi.exports=EventEmitter,vi.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 yi=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)Si(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?fi(this._events):[]};const wi=[];class Track extends vi.EventEmitter{constructor(e,t){super(),this.attachedElements=[],this.isMuted=!1,this.streamState=Track.StreamState.Active,this._currentBitrate=0,this.appVisibilityChangedListener=()=>{this.backgroundTimeout&&clearTimeout(this.backgroundTimeout),"hidden"===document.visibilityState?this.backgroundTimeout=setTimeout((()=>this.handleAppVisibilityChanged()),5e3):this.handleAppVisibilityChanged()},this.setMaxListeners(100),this.kind=t,this._mediaStreamTrack=e,this._mediaStreamID=e.id,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}get mediaStreamID(){return this._mediaStreamID}attach(e){let t="audio";this.kind===Track.Kind.Video&&(t="video"),e||("audio"===t&&(wi.forEach((t=>{null!==t.parentElement||e||(e=t)})),e&&wi.splice(wi.indexOf(e),1)),e||(e=document.createElement(t))),this.attachedElements.includes(e)||this.attachedElements.push(e),attachToElement(this._mediaStreamTrack,e);const i=e.srcObject.getTracks();return i.some((e=>"audio"===e.kind))&&e.play().then((()=>{this.emit(ii.AudioPlaybackStarted)})).catch((t=>{"NotAllowedError"===t.name?this.emit(ii.AudioPlaybackFailed,t):h.warn("could not playback audio",t),e&&i.some((e=>"video"===e.kind))&&"NotAllowedError"===t.name&&(e.muted=!0,e.play().catch((()=>{})))})),this.emit(ii.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(ii.ElementDetached,e)),e}const t=[];return this.attachedElements.forEach((e=>{detachTrack(this._mediaStreamTrack,e),t.push(e),this.recycleElement(e),this.emit(ii.ElementDetached,e)})),this.attachedElements=[],t}stop(){this.stopMonitor(),this._mediaStreamTrack.stop(),isWeb()&&document.removeEventListener("visibilitychange",this.appVisibilityChangedListener)}enable(){this._mediaStreamTrack.enabled=!0}disable(){this._mediaStreamTrack.enabled=!1}stopMonitor(){this.monitorInterval&&clearInterval(this.monitorInterval)}recycleElement(e){if(e instanceof HTMLAudioElement){let t=!0;e.pause(),wi.forEach((e=>{e.parentElement||(t=!1)})),t&&wi.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.autoplay=!0,t.muted=0===i.getAudioTracks().length,t instanceof HTMLVideoElement&&(t.playsInline=!0),t.srcObject!==i&&(t.srcObject=i,(isSafari()||isFireFox())&&t instanceof HTMLVideoElement&&setTimeout((()=>{t.srcObject=i,t.play().catch((()=>{}))}),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 Pe.AUDIO;case t.Video:return Pe.VIDEO;default:return Pe.UNRECOGNIZED}},e.kindFromProto=function kindFromProto(e){switch(e){case Pe.AUDIO:return t.Audio;case Pe.VIDEO:return t.Video;default:return t.Unknown}},e.sourceToProto=function sourceToProto(e){switch(e){case i.Camera:return Ee.CAMERA;case i.Microphone:return Ee.MICROPHONE;case i.ScreenShare:return Ee.SCREEN_SHARE;case i.ScreenShareAudio:return Ee.SCREEN_SHARE_AUDIO;default:return Ee.UNRECOGNIZED}},e.sourceFromProto=function sourceFromProto(e){switch(e){case Ee.CAMERA:return i.Camera;case Ee.MICROPHONE:return i.Microphone;case Ee.SCREEN_SHARE:return i.ScreenShare;case Ee.SCREEN_SHARE_AUDIO:return i.ScreenShareAudio;default:return i.Unknown}},e.streamStateFromProto=function streamStateFromProto(e){switch(e){case mt.ACTIVE:return n.Active;case mt.PAUSED:return n.Paused;default:return n.Unknown}}}(Track||(Track={}));class LocalTrack extends Track{constructor(e,t,i){let n=arguments.length>3&&void 0!==arguments[3]&&arguments[3];super(e,t),this._isUpstreamPaused=!1,this.handleEnded=()=>{this.isInBackground&&(this.reacquireTrack=!0),this.emit(ii.Ended,this)},this._mediaStreamTrack.addEventListener("ended",this.handleEnded),this.constraints=null!=i?i:e.getConstraints(),this.reacquireTrack=!1,this.providedByUser=n,this.muteQueue=new Queue}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}get isUserProvided(){return this.providedByUser}async waitForDimensions(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:2e3;if(this.kind===Track.Kind.Audio)throw new Error("cannot get dimensions for audio tracks");const t=Date.now();for(;Date.now()-t1&&void 0!==arguments[1])||arguments[1];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.providedByUser||this._mediaStreamTrack.stop(),e.addEventListener("ended",this.handleEnded),h.debug("replace MediaStreamTrack"),this.sender&&await this.sender.replaceTrack(e),this._mediaStreamTrack=e,this._mediaStreamTrack.enabled=!this.isMuted,await this.resumeUpstream(),this.attachedElements.forEach((t=>{attachToElement(e,t)})),this.mediaStream=new MediaStream([e]),this.providedByUser=t,this}async restart(e){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"),this.sender&&await this.sender.replaceTrack(n),this._mediaStreamTrack=n,await this.resumeUpstream(),this.attachedElements.forEach((e=>{attachToElement(n,e)})),this.mediaStream=i,this.constraints=e,this.emit(ii.Restarted,this),this}setTrackMuted(e){h.debug("setting ".concat(this.kind," track ").concat(e?"muted":"unmuted")),this.isMuted===e&&this._mediaStreamTrack.enabled!==e||(this.isMuted=e,this._mediaStreamTrack.enabled=!e,this.emit(e?ii.Muted:ii.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||this.isUserProvided||this.isMuted||(h.debug("track needs to be reaquired, restarting ".concat(this.source)),await this.restart(),this.reacquireTrack=!1))}async pauseUpstream(){this.muteQueue.run((async()=>{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(ii.UpstreamPaused,this);const e=this.kind===Track.Kind.Audio?getEmptyAudioStreamTrack():getEmptyVideoStreamTrack();await this.sender.replaceTrack(e)}))}async resumeUpstream(){this.muteQueue.run((async()=>{!1!==this._isUpstreamPaused&&(this.sender?(this._isUpstreamPaused=!1,this.emit(ii.UpstreamResumed,this),await this.sender.replaceTrack(this._mediaStreamTrack)):h.warn("unable to resume upstream for an unpublished track"))}))}}class LocalAudioTrack extends LocalTrack{constructor(e,t){let i=!(arguments.length>2&&void 0!==arguments[2])||arguments[2];super(e,Track.Kind.Audio,t,i),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},this.checkForSilence()}async setDeviceId(e){this.constraints.deviceId!==e&&(this.constraints.deviceId=e,this.isMuted||await this.restartTrack())}async mute(){return await this.muteQueue.run((async()=>{this.source===Track.Source.Microphone&&this.stopOnMute&&!this.isUserProvided&&(h.debug("stopping mic track"),this._mediaStreamTrack.stop()),await super.mute()})),this}async unmute(){return await this.muteQueue.run((async()=>{this.source!==Track.Source.Microphone||!this.stopOnMute&&"ended"!==this._mediaStreamTrack.readyState||this.isUserProvided||(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(){isWeb()&&(this.monitorInterval||(this.monitorInterval=setInterval((()=>{this.monitorSender()}),ni)))}async getSenderStats(){var e;if(!(null===(e=this.sender)||void 0===e?void 0:e.getStats))return;let t;return(await this.sender.getStats()).forEach((e=>{"outbound-rtp"===e.type&&(t={type:"audio",streamId:e.id,packetsSent:e.packetsSent,packetsLost:e.packetsLost,bytesSent:e.bytesSent,timestamp:e.timestamp,roundTripTime:e.roundTripTime,jitter:e.jitter})})),t}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);return e&&(this.isMuted||h.warn("silence detected on local audio track"),this.emit(ii.AudioSilenceDetected)),e}}class LocalVideoTrack extends LocalTrack{constructor(e,t){let i=!(arguments.length>2&&void 0!==arguments[2])||arguments[2];super(e,Track.Kind.Video,t,i),this.simulcastCodecs=new Map,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},this.senderLock=new Mutex}get isSimulcast(){return!!(this.sender&&this.sender.getParameters().encodings.length>1)}startMonitor(e){var t;if(this.signalClient=e,!isWeb())return;const i=null===(t=this.sender)||void 0===t?void 0:t.getParameters();i&&(this.encodings=i.encodings),this.monitorInterval||(this.monitorInterval=setInterval((()=>{this.monitorSender()}),ni))}stop(){this._mediaStreamTrack.getConstraints(),this.simulcastCodecs.forEach((e=>{e.mediaStreamTrack.stop()})),super.stop()}async mute(){return await this.muteQueue.run((async()=>{this.source!==Track.Source.Camera||this.isUserProvided||(h.debug("stopping camera track"),this._mediaStreamTrack.stop()),await super.mute()})),this}async unmute(){return await this.muteQueue.run((async()=>{this.source!==Track.Source.Camera||this.isUserProvided||(h.debug("reacquiring camera track"),await this.restartTrack()),await super.unmute()})),this}async getSenderStats(){var e;if(!(null===(e=this.sender)||void 0===e?void 0:e.getStats))return[];const t=[],i=await this.sender.getStats();return i.forEach((e=>{var n;if("outbound-rtp"===e.type){const s={type:"video",streamId:e.id,frameHeight:e.frameHeight,frameWidth:e.frameWidth,firCount:e.firCount,pliCount:e.pliCount,nackCount:e.nackCount,packetsSent:e.packetsSent,bytesSent:e.bytesSent,framesSent:e.framesSent,timestamp:e.timestamp,rid:null!==(n=e.rid)&&void 0!==n?n:e.id,retransmittedPacketsSent:e.retransmittedPacketsSent,qualityLimitationReason:e.qualityLimitationReason,qualityLimitationResolutionChanges:e.qualityLimitationResolutionChanges},a=i.get(e.remoteId);a&&(s.jitter=a.jitter,s.packetsLost=a.packetsLost,s.roundTripTime=a.roundTripTime),t.push(s)}})),t}setPublishingQuality(e){const t=[];for(let i=Re.LOW;i<=Re.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)}addSimulcastTrack(e,t){if(this.simulcastCodecs.has(e))throw new Error("".concat(e," already added"));const i={codec:e,mediaStreamTrack:this.mediaStreamTrack.clone(),sender:void 0,encodings:t};return this.simulcastCodecs.set(e,i),i}setSimulcastTrackSender(e,t){const i=this.simulcastCodecs.get(e);i&&(i.sender=t,setTimeout((()=>{this.subscribedCodecs&&this.setPublishingCodecs(this.subscribedCodecs)}),5e3))}async setPublishingCodecs(e){if(h.debug("setting publishing codecs",{codecs:e,currentCodec:this.codec}),!this.codec&&e.length>0)return await this.setPublishingLayers(e[0].qualities),[];this.subscribedCodecs=e;const t=[];var i,n=!1,s=!1;try{for(var a,o=_asyncIterator(e);n=!(a=await o.next()).done;n=!1){const e=a.value;if(this.codec&&this.codec!==e.codec){const i=this.simulcastCodecs.get(e.codec);if(h.debug("try setPublishingCodec for ".concat(e.codec),i),i&&i.sender)i.encodings&&(h.debug("try setPublishingLayersForSender ".concat(e.codec)),await setPublishingLayersForSender(i.sender,i.encodings,e.qualities,this.senderLock));else for(const i of e.qualities)if(i.enabled){t.push(e.codec);break}}else await this.setPublishingLayers(e.qualities)}}catch(e){s=!0,i=e}finally{try{n&&null!=o.return&&await o.return()}finally{if(s)throw i}}return t}async setPublishingLayers(e){h.debug("setting publishing layers",e),this.sender&&this.encodings&&await setPublishingLayersForSender(this.sender,this.encodings,e,this.senderLock)}async handleAppVisibilityChanged(){await super.handleAppVisibilityChanged(),isMobile()&&this.isInBackground&&this.source===Track.Source.Camera&&(this._mediaStreamTrack.enabled=!1)}}async function setPublishingLayersForSender(e,t,i,n){const s=await n.lock();h.debug("setPublishingLayersForSender",{sender:e,qualities:i,senderEncodings:t});try{const n=e.getParameters(),{encodings:a}=n;if(!a)return;if(a.length!==t.length)return void h.warn("cannot set publishing layers, encodings mismatch");let o=!1;a.forEach(((e,n)=>{var s;let a=null!==(s=e.rid)&&void 0!==s?s:"";""===a&&(a="q");const c=videoQualityForRid(a),u=i.find((e=>e.quality===c));u&&e.active!==u.enabled&&(o=!0,e.active=u.enabled,h.debug("setting layer ".concat(u.quality," to ").concat(e.active?"enabled":"disabled")),isFireFox()&&(u.enabled?(e.scaleResolutionDownBy=t[n].scaleResolutionDownBy,e.maxBitrate=t[n].maxBitrate,e.maxFrameRate=t[n].maxFrameRate):(e.scaleResolutionDownBy=4,e.maxBitrate=10,e.maxFrameRate=2)))})),o&&(n.encodings=a,await e.setParameters(n))}finally{s()}}function videoQualityForRid(e){switch(e){case"f":return Re.HIGH;case"h":return Re.MEDIUM;case"q":return Re.LOW;default:return Re.UNRECOGNIZED}}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===Re.UNRECOGNIZED&&1===i.length&&(u=Re.HIGH),{quality:u,width:e/c,height:t/c,bitrate:null!==(o=n.maxBitrate)&&void 0!==o?o:0,ssrc:0}})):[{quality:Re.HIGH,width:e,height:t,bitrate:0,ssrc:0}]}class RemoteTrack extends Track{constructor(e,t,i,n){super(e,i),this.sid=t,this.receiver=n}setMuted(e){this.isMuted!==e&&(this.isMuted=e,this._mediaStreamTrack.enabled=!e,this.emit(e?ii.Muted:ii.Unmuted,this))}setMediaStream(e){this.mediaStream=e,e.onremovetrack=()=>{this.receiver=void 0,this._currentBitrate=0,this.emit(ii.Ended,this)}}start(){this.startMonitor(),super.enable()}stop(){this.stopMonitor(),super.disable()}startMonitor(){this.monitorInterval||(this.monitorInterval=setInterval((()=>this.monitorReceiver()),ni))}}class RemoteAudioTrack extends RemoteTrack{constructor(e,t,i,n,s){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},this.audioContext=n,this.webAudioPluginNodes=[],s&&(this.sinkId=s.deviceId)}setVolume(e){var t;for(const i of this.attachedElements)this.audioContext?null===(t=this.gainNode)||void 0===t||t.gain.setTargetAtTime(e,0,.1):i.volume=e;this.elementVolume=e}getVolume(){if(this.elementVolume)return this.elementVolume;let e=0;return this.attachedElements.forEach((t=>{t.volume>e&&(e=t.volume)})),e}async setSinkId(e){this.sinkId=e,await Promise.all(this.attachedElements.map((t=>{if(supportsSetSinkId(t))return t.setSinkId(e)})))}attach(e){const t=0===this.attachedElements.length;return e?super.attach(e):e=super.attach(),this.elementVolume&&(e.volume=this.elementVolume),this.sinkId&&supportsSetSinkId(e)&&e.setSinkId(this.sinkId),this.audioContext&&t&&(h.debug("using audio context mapping"),this.connectWebAudio(this.audioContext,e),e.volume=0,e.muted=!0),e}detach(e){let t;return e?(t=super.detach(e),this.audioContext&&(this.attachedElements.length>0?this.connectWebAudio(this.audioContext,this.attachedElements[0]):this.disconnectWebAudio())):(t=super.detach(),this.disconnectWebAudio()),t}setAudioContext(e){this.audioContext=e,e&&this.attachedElements.length>0?this.connectWebAudio(e,this.attachedElements[0]):e||this.disconnectWebAudio()}setWebAudioPlugins(e){this.webAudioPluginNodes=e,this.attachedElements.length>0&&this.audioContext&&this.connectWebAudio(this.audioContext,this.attachedElements[0])}connectWebAudio(e,t){this.disconnectWebAudio(),this.sourceNode=e.createMediaStreamSource(t.srcObject);let i=this.sourceNode;this.webAudioPluginNodes.forEach((e=>{i.connect(e),i=e})),this.gainNode=e.createGain(),i.connect(this.gainNode),this.gainNode.connect(e.destination),this.elementVolume&&this.gainNode.gain.setTargetAtTime(this.elementVolume,0,.1),"running"!==e.state&&e.resume().then((()=>{"running"!==e.state&&this.emit(ii.AudioPlaybackFailed,new Error("Audio Context couldn't be started automatically"))})).catch((e=>{this.emit(ii.AudioPlaybackFailed,e)}))}disconnectWebAudio(){var e,t;null===(e=this.gainNode)||void 0===e||e.disconnect(),null===(t=this.sourceNode)||void 0===t||t.disconnect(),this.gainNode=void 0,this.sourceNode=void 0}async getReceiverStats(){if(!this.receiver||!this.receiver.getStats)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 CriticalTimers{}CriticalTimers.setTimeout=function(){return setTimeout(...arguments)},CriticalTimers.setInterval=function(){return setInterval(...arguments)},CriticalTimers.clearTimeout=function(){return clearTimeout(...arguments)},CriticalTimers.clearInterval=function(){return clearInterval(...arguments)};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},this.debouncedHandleResize=r((()=>{this.updateDimensions()}),100),this.adaptiveStreamSettings=n}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){if(e?super.attach(e):e=super.attach(),this.adaptiveStreamSettings&&void 0===this.elementInfos.find((t=>t.element===e))){const t=new HTMLElementInfo(e);this.observeElementInfo(t)}return this.hasUsedAttach=!0,e}observeElementInfo(e){this.adaptiveStreamSettings&&void 0===this.elementInfos.find((t=>t===e))?(e.handleResize=()=>{this.debouncedHandleResize()},e.handleVisibilityChanged=()=>{this.updateVisibility()},this.elementInfos.push(e),e.observe(),this.debouncedHandleResize(),this.updateVisibility()):h.warn("visibility resize observer not triggered")}stopObservingElementInfo(e){if(!this.isAdaptiveStream)return void h.warn("stopObservingElementInfo ignored");const t=this.elementInfos.filter((t=>t===e));for(const e of t)e.stopObserving();this.elementInfos=this.elementInfos.filter((t=>t!==e)),this.updateVisibility()}detach(e){let t=[];if(e)return this.stopObservingElement(e),super.detach(e);t=super.detach();for(const e of t)this.stopObservingElement(e);return t}getDecoderImplementation(){var e;return null===(e=this.prevStats)||void 0===e?void 0:e.decoderImplementation}async getReceiverStats(){if(!this.receiver||!this.receiver.getStats)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,decoderImplementation:t.decoderImplementation})})),e}stopObservingElement(e){const t=this.elementInfos.filter((t=>t.element===e));for(const e of t)e.stopObserving();this.elementInfos=this.elementInfos.filter((t=>t.element!==e))}async handleAppVisibilityChanged(){await super.handleAppVisibilityChanged(),this.isAdaptiveStream&&this.updateVisibility()}updateVisibility(){var e,t;const i=this.elementInfos.reduce(((e,t)=>Math.max(e,t.visibilityChangedAt||0)),0),n=!(null!==(t=null===(e=this.adaptiveStreamSettings)||void 0===e?void 0:e.pauseVideoInBackground)&&void 0!==t&&!t)&&this.isInBackground,s=this.elementInfos.some((e=>e.pictureInPicture)),a=this.elementInfos.some((e=>e.visible))&&!n||s;this.lastVisible!==a&&(!a&&Date.now()-i<100?CriticalTimers.setTimeout((()=>{this.updateVisibility()}),100):(this.lastVisible=a,this.emit(ii.VisibilityChanged,a,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.width()*o,u=i.height()*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(ii.VideoDimensionsChanged,this.lastDimensions,this))}}class HTMLElementInfo{get visible(){return this.isPiP||this.isIntersecting}get pictureInPicture(){return this.isPiP}constructor(e,t){this.onVisibilityChanged=e=>{var t;const{target:i,isIntersecting:n}=e;i===this.element&&(this.isIntersecting=n,this.visibilityChangedAt=Date.now(),null===(t=this.handleVisibilityChanged)||void 0===t||t.call(this))},this.onEnterPiP=()=>{var e;this.isPiP=!0,null===(e=this.handleVisibilityChanged)||void 0===e||e.call(this)},this.onLeavePiP=()=>{var e;this.isPiP=!1,null===(e=this.handleVisibilityChanged)||void 0===e||e.call(this)},this.element=e,this.isIntersecting=null!=t?t:isElementInViewport(e),this.isPiP=isWeb()&&document.pictureInPictureElement===e,this.visibilityChangedAt=0}width(){return this.element.clientWidth}height(){return this.element.clientHeight}observe(){this.isIntersecting=isElementInViewport(this.element),this.isPiP=document.pictureInPictureElement===this.element,this.element.handleResize=()=>{var e;null===(e=this.handleResize)||void 0===e||e.call(this)},this.element.handleVisibilityChanged=this.onVisibilityChanged,getIntersectionObserver().observe(this.element),getResizeObserver().observe(this.element),this.element.addEventListener("enterpictureinpicture",this.onEnterPiP),this.element.addEventListener("leavepictureinpicture",this.onLeavePiP)}stopObserving(){var e,t;null===(e=getIntersectionObserver())||void 0===e||e.unobserve(this.element),null===(t=getResizeObserver())||void 0===t||t.unobserve(this.element),this.element.removeEventListener("enterpictureinpicture",this.onEnterPiP),this.element.removeEventListener("leavepictureinpicture",this.onLeavePiP)}}function isElementInViewport(e){let t=e.offsetTop,i=e.offsetLeft;const n=e.offsetWidth,s=e.offsetHeight,{hidden:a}=e,{opacity:o,display:c}=getComputedStyle(e);for(;e.offsetParent;)t+=(e=e.offsetParent).offsetTop,i+=e.offsetLeft;return twindow.pageYOffset&&i+n>window.pageXOffset&&!a&&(""===o||parseFloat(o)>0)&&"none"!==c}class TrackPublication extends vi.EventEmitter{constructor(e,t,i){super(),this.metadataMuted=!1,this.handleMuted=()=>{this.emit(ii.Muted)},this.handleUnmuted=()=>{this.emit(ii.Unmuted)},this.setMaxListeners(100),this.kind=e,this.trackSid=t,this.trackName=i,this.source=Track.Source.Unknown}setTrack(e){this.track&&(this.track.off(ii.Muted,this.handleMuted),this.track.off(ii.Unmuted,this.handleUnmuted)),this.track=e,e&&(e.on(ii.Muted,this.handleMuted),e.on(ii.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,h.trace("update publication info",{info:e})}}!function(e){var t,i;(t=e.SubscriptionStatus||(e.SubscriptionStatus={})).Desired="desired",t.Subscribed="subscribed",t.Unsubscribed="unsubscribed",(i=e.PermissionStatus||(e.PermissionStatus={})).Allowed="allowed",i.NotAllowed="not_allowed"}(TrackPublication||(TrackPublication={}));class LocalTrackPublication extends TrackPublication{get isUpstreamPaused(){var e;return null===(e=this.track)||void 0===e?void 0:e.isUpstreamPaused}constructor(e,t,i){super(e,t.sid,t.name),this.track=void 0,this.handleTrackEnded=()=>{this.emit(ii.Ended)},this.updateInfo(t),this.setTrack(i)}setTrack(e){this.track&&this.track.off(ii.Ended,this.handleTrackEnded),super.setTrack(e),e&&e.on(ii.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}}}const Ti=["vp8","h264"];function isBackupCodec(e){return!!Ti.find((t=>t===e))}var Ci;!function(e){e.telephone={maxBitrate:12e3},e.speech={maxBitrate:2e4},e.music={maxBitrate:32e3},e.musicStereo={maxBitrate:48e3},e.musicHighQuality={maxBitrate:64e3},e.musicHighQualityStereo={maxBitrate:96e3}}(Ci||(Ci={}));const Pi={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)},Ei={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)},Ri={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 Oi;!function(e){e.Excellent="excellent",e.Good="good",e.Poor="poor",e.Unknown="unknown"}(Oi||(Oi={}));class Participant extends vi.EventEmitter{constructor(e,t,i,n){super(),this.audioLevel=0,this.isSpeaking=!1,this._connectionQuality=Oi.Unknown,this.setMaxListeners(100),this.sid=e,this.identity=t,this.name=i,this.metadata=n,this.audioTracks=new Map,this.videoTracks=new Map,this.tracks=new Map}getTracks(){return Array.from(this.tracks.values())}getTrack(e){for(const[,t]of this.tracks)if(t.source===e)return t}getTrackByName(e){for(const[,t]of this.tracks)if(t.trackName===e)return t}get connectionQuality(){return this._connectionQuality}get isCameraEnabled(){var e;const t=this.getTrack(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 isLocal(){return!1}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,h.trace("update participant info",{info:e})}setMetadata(e){const t=this.metadata!==e,i=this.metadata;this.metadata=e,t&&this.emit(ei.ParticipantMetadataChanged,i)}setPermissions(e){var t,i,n,s,a;const o=this.permissions,c=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)||e.canPublishSources.length!==this.permissions.canPublishSources.length||e.canPublishSources.some(((e,t)=>{var i;return e!==(null===(i=this.permissions)||void 0===i?void 0:i.canPublishSources[t])}));return this.permissions=e,c&&this.emit(ei.ParticipantPermissionsChanged,o),c}setIsSpeaking(e){e!==this.isSpeaking&&(this.isSpeaking=e,e&&(this.lastSpokeAt=new Date),this.emit(ei.IsSpeakingChanged,e))}setConnectionQuality(e){const t=this._connectionQuality;this._connectionQuality=function qualityFromProto(e){switch(e){case Oe.EXCELLENT:return Oi.Excellent;case Oe.GOOD:return Oi.Good;case Oe.POOR:return Oi.Poor;default:return Oi.Unknown}}(e),t!==this._connectionQuality&&this.emit(ei.ConnectionQualityChanged,this._connectionQuality)}addTrackPublication(e){e.on(ii.Muted,(()=>{this.emit(ei.TrackMuted,e)})),e.on(ii.Unmuted,(()=>{this.emit(ei.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,!1);case"video":return new LocalVideoTrack(e,t,!1);default:throw new TrackInvalidError("unsupported track type: ".concat(e.kind))}}const Ni=Object.values(Pi),Ii=Object.values(Ei),Di=Object.values(Ri),_i=[Pi.h180,Pi.h360],Li=[Ei.h180,Ei.h360],Ai=["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,l=null==n?void 0:n.videoCodec;if(!o&&!c&&!u||!t||!i)return[{}];o||(o=function determineAppropriateEncoding(e,t,i,n){const s=function presetsForResolution(e,t,i){if(e)return Di;const n=t>i?t/i:i/t;if(Math.abs(n-16/9)=o)break}if(n&&"av1"===n)a.maxBitrate=.7*a.maxBitrate;return a}(e,t,i,l),h.debug("using video encoding",o));const p=new VideoPreset(t,i,o.maxBitrate,o.maxFramerate);if(u&&"av1"===l){h.debug("using svc with scalabilityMode ".concat(u));const e=[];if("L3T3"===u){for(let t=0;t<3;t+=1)e.push({rid:Ai[2-t],scaleResolutionDownBy:2**t,maxBitrate:o.maxBitrate/3**t,maxFramerate:p.encoding.maxFramerate,scalabilityMode:"L3T3"});return h.debug("encodings",e),e}throw new Error("unsupported scalabilityMode: ".concat(u))}if(!c)return[o];let m,v=[];if(v=e?null!==(s=sortPresets(null==n?void 0:n.screenShareSimulcastLayers))&&void 0!==s?s:defaultSimulcastLayers(e,p):null!==(a=sortPresets(null==n?void 0:n.videoSimulcastLayers))&&void 0!==a?a:defaultSimulcastLayers(e,p),v.length>0){const e=v[0];v.length>1&&([,m]=v);const n=Math.max(t,i);if(n>=960&&m)return encodingsFromPresets(t,i,[e,m,p]);if(n>=480)return encodingsFromPresets(t,i,[e,p])}return encodingsFromPresets(t,i,[p])}function computeTrackBackupEncodings(e,t,i){var n,s,a,o;if(!i.backupCodec||i.backupCodec.codec===i.videoCodec)return;t!==i.backupCodec.codec&&h.warn("requested a different codec than specified as backup",{serverRequested:t,backup:i.backupCodec.codec}),i.videoCodec=t,i.videoEncoding=i.backupCodec.encoding;const c=e.mediaStreamTrack.getSettings(),u=null!==(n=c.width)&&void 0!==n?n:null===(s=e.dimensions)||void 0===s?void 0:s.width,l=null!==(a=c.height)&&void 0!==a?a:null===(o=e.dimensions)||void 0===o?void 0:o.height;return computeVideoEncodings(e.source===Track.Source.ScreenShare,u,l,i)}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>=Ai.length)return;const a=Math.min(e,t),o=Ai[s];n.push({rid:o,scaleResolutionDownBy:Math.max(1,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(e,t,i){super(e,t.sid,t.name),this.track=void 0,this.allowed=!0,this.disabled=!1,this.currentVideoQuality=Re.HIGH,this.handleEnded=e=>{this.setTrack(void 0),this.emit(ii.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()},this.subscribed=i,this.updateInfo(t)}setSubscribed(e){const t=this.subscriptionStatus,i=this.permissionStatus;this.subscribed=e,e&&(this.allowed=!0);const n={trackSids:[this.trackSid],subscribe:this.subscribed,participantTracks:[{participantSid:"",trackSids:[this.trackSid]}]};this.emit(ii.UpdateSubscription,n),this.emitSubscriptionUpdateIfChanged(t),this.emitPermissionUpdateIfChanged(i)}get subscriptionStatus(){return!1===this.subscribed?TrackPublication.SubscriptionStatus.Unsubscribed:super.isSubscribed?TrackPublication.SubscriptionStatus.Subscribed:TrackPublication.SubscriptionStatus.Desired}get permissionStatus(){return this.allowed?TrackPublication.PermissionStatus.Allowed:TrackPublication.PermissionStatus.NotAllowed}get isSubscribed(){return!1!==this.subscribed&&super.isSubscribed}get isDesired(){return!1!==this.subscribed}get isEnabled(){return!this.disabled}setEnabled(e){this.isManualOperationAllowed()&&this.disabled!==!e&&(this.disabled=!e,this.emitTrackUpdate())}setVideoQuality(e){this.isManualOperationAllowed()&&this.currentVideoQuality!==e&&(this.currentVideoQuality=e,this.videoDimensions=void 0,this.emitTrackUpdate())}setVideoDimensions(e){var t,i;this.isManualOperationAllowed()&&((null===(t=this.videoDimensions)||void 0===t?void 0:t.width)===e.width&&(null===(i=this.videoDimensions)||void 0===i?void 0:i.height)===e.height||(this.track instanceof RemoteVideoTrack&&(this.videoDimensions=e),this.currentVideoQuality=void 0,this.emitTrackUpdate()))}setVideoFPS(e){this.isManualOperationAllowed()&&this.track instanceof RemoteVideoTrack&&this.fps!==e&&(this.fps=e,this.emitTrackUpdate())}get videoQuality(){return this.currentVideoQuality}setTrack(e){const t=this.subscriptionStatus,i=this.permissionStatus,n=this.track;n!==e&&(n&&(n.off(ii.VideoDimensionsChanged,this.handleVideoDimensionsChange),n.off(ii.VisibilityChanged,this.handleVisibilityChange),n.off(ii.Ended,this.handleEnded),n.detach(),this.emit(ii.Unsubscribed,n)),super.setTrack(e),e&&(e.sid=this.trackSid,e.on(ii.VideoDimensionsChanged,this.handleVideoDimensionsChange),e.on(ii.VisibilityChanged,this.handleVisibilityChange),e.on(ii.Ended,this.handleEnded),this.emit(ii.Subscribed,e)),this.emitPermissionUpdateIfChanged(i),this.emitSubscriptionUpdateIfChanged(t))}setAllowed(e){const t=this.subscriptionStatus,i=this.permissionStatus;this.allowed=e,this.emitPermissionUpdateIfChanged(i),this.emitSubscriptionUpdateIfChanged(t)}updateInfo(e){super.updateInfo(e);const t=this.metadataMuted;this.metadataMuted=e.muted,this.track?this.track.setMuted(e.muted):t!==e.muted&&this.emit(e.muted?ii.Muted:ii.Unmuted)}emitSubscriptionUpdateIfChanged(e){const t=this.subscriptionStatus;e!==t&&this.emit(ii.SubscriptionStatusChanged,t,e)}emitPermissionUpdateIfChanged(e){this.permissionStatus!==e&&this.emit(ii.SubscriptionPermissionChanged,this.permissionStatus,e)}isManualOperationAllowed(){return this.isAdaptiveStream?(h.warn("adaptive stream is enabled, cannot change track settings",{trackSid:this.trackSid}),!1):!!this.isDesired||(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=It.fromPartial({trackSids:[this.trackSid],disabled:this.disabled,fps:this.fps});this.videoDimensions?(e.width=this.videoDimensions.width,e.height=this.videoDimensions.height):void 0!==this.currentVideoQuality?e.quality=this.currentVideoQuality:e.quality=Re.HIGH,this.emit(ii.UpdateSettings,e)}}class RemoteParticipant extends Participant{static fromParticipantInfo(e,t){return new RemoteParticipant(e,t.sid,t.identity,t.name,t.metadata)}constructor(e,t,i,n,s){super(t,i||"",n,s),this.signalClient=e,this.tracks=new Map,this.audioTracks=new Map,this.videoTracks=new Map}addTrackPublication(e){super.addTrackPublication(e),e.on(ii.UpdateSettings,(e=>{h.debug("send update settings",e),this.signalClient.sendUpdateTrackSettings(e)})),e.on(ii.UpdateSubscription,(e=>{e.participantTracks.forEach((e=>{e.participantSid=this.sid})),this.signalClient.sendUpdateSubscription(e)})),e.on(ii.SubscriptionPermissionChanged,(t=>{this.emit(ei.TrackSubscriptionPermissionChanged,e,t)})),e.on(ii.SubscriptionStatusChanged,(t=>{this.emit(ei.TrackSubscriptionStatusChanged,e,t)})),e.on(ii.Subscribed,(t=>{this.emit(ei.TrackSubscribed,t,e)})),e.on(ii.Unsubscribed,(t=>{this.emit(ei.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(ei.TrackSubscriptionFailed,t)):(void 0===a&&(a=20),void setTimeout((()=>{this.addSubscribedMediaTrack(e,t,i,n,s,a-1)}),150));if("ended"===e.readyState)return h.error("unable to subscribe because MediaStreamTrack is ended. Do not call MediaStreamTrack.stop()",{participant:this.sid,trackSid:t}),void this.emit(ei.TrackSubscriptionFailed,t);let c;return c="video"===e.kind?new RemoteVideoTrack(e,t,n,s):new RemoteAudioTrack(e,t,n,this.audioContext,this.audioOutput),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),o}get hasMetadata(){return!!this.participantInfo}getTrackPublication(e){return this.tracks.get(e)}updateInfo(e){super.updateInfo(e);const t=new Map,i=new Map;e.tracks.forEach((n=>{var s;let a=this.getTrackPublication(n.sid);if(a)a.updateInfo(n);else{const t=Track.kindFromProto(n.type);if(!t)return;a=new RemoteTrackPublication(t,n,null===(s=this.signalClient.connectOptions)||void 0===s?void 0:s.autoSubscribe),a.updateInfo(n),i.set(n.sid,a);const o=Array.from(this.tracks.values()).find((e=>e.source===(null==a?void 0:a.source)));o&&a.source!==Track.Source.Unknown&&h.debug("received a second track publication for ".concat(this.identity," with the same source: ").concat(a.source),{oldTrack:o,newTrack:a,participant:this,participantInfo:e}),this.addTrackPublication(a)}t.set(n.sid,a)})),this.tracks.forEach((e=>{t.has(e.trackSid)||(h.trace("detected removed track on remote participant, unpublishing",{publication:e,participantSid:this.sid}),this.unpublishTrack(e.trackSid,!0))})),i.forEach((e=>{this.emit(ei.TrackPublished,e)}))}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;n&&(n.stop(),i.setTrack(void 0)),t&&this.emit(ei.TrackUnpublished,i)}setAudioContext(e){this.audioContext=e,this.audioTracks.forEach((t=>t.track instanceof RemoteAudioTrack&&t.track.setAudioContext(e)))}async setAudioOutput(e){this.audioOutput=e;const t=[];this.audioTracks.forEach((i=>{var n;i.track instanceof RemoteAudioTrack&&t.push(i.track.setSinkId(null!==(n=e.deviceId)&&void 0!==n?n:"default"))})),await Promise.all(t)}emit(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),n=1;n{this.reconnectFuture||(this.reconnectFuture=new Future)},this.handleReconnected=()=>{var e,t;null===(t=null===(e=this.reconnectFuture)||void 0===e?void 0:e.resolve)||void 0===t||t.call(e),this.reconnectFuture=void 0,this.updateTrackSubscriptionPermissions()},this.handleDisconnected=()=>{var e,t;null===(t=null===(e=this.reconnectFuture)||void 0===e?void 0:e.reject)||void 0===t||t.call(e,"Got disconnected during publishing attempt"),this.reconnectFuture=void 0},this.updateTrackSubscriptionPermissions=()=>{h.debug("updating track subscription permissions",{allParticipantsAllowed:this.allParticipantsAllowedToSubscribe,participantTrackPermissions:this.participantTrackPermissions}),this.engine.client.sendUpdateSubscriptionPermissions(this.allParticipantsAllowedToSubscribe,this.participantTrackPermissions.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))))},this.onTrackUnmuted=e=>{this.onTrackMuted(e,e.isUpstreamPaused)},this.onTrackMuted=(e,t)=>{void 0===t&&(t=!0),e.sid?this.engine.updateMuteStatus(e.sid,t):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=async e=>{var t,i;if(!(null===(t=this.roomOptions)||void 0===t?void 0:t.dynacast))return;const n=this.videoTracks.get(e.trackSid);if(n)if(e.subscribedCodecs.length>0){if(!n.videoTrack)return;const t=await n.videoTrack.setPublishingCodecs(e.subscribedCodecs);var s,a=!1,o=!1;try{for(var c,u=_asyncIterator(t);a=!(c=await u.next()).done;a=!1){const e=c.value;isBackupCodec(e)&&(h.debug("publish ".concat(e," for ").concat(n.videoTrack.sid)),await this.publishAdditionalCodecForTrack(n.videoTrack,e,n.options))}}catch(e){o=!0,s=e}finally{try{a&&null!=u.return&&await u.return()}finally{if(o)throw s}}}else e.subscribedQualities.length>0&&await(null===(i=n.videoTrack)||void 0===i?void 0:i.setPublishingLayers(e.subscribedQualities));else 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.handleTrackEnded=async e=>{if(e.source===Track.Source.ScreenShare||e.source===Track.Source.ScreenShareAudio)h.debug("unpublishing local track due to TrackEnded",{track:e.sid}),this.unpublishTrack(e);else if(e.isUserProvided)await e.mute();else if(e instanceof LocalAudioTrack||e instanceof LocalVideoTrack)try{if(isWeb())try{const t=await(null===navigator||void 0===navigator?void 0:navigator.permissions.query({name:e.source===Track.Source.Camera?"camera":"microphone"}));if(t&&"denied"===t.state)throw h.warn("user has revoked access to ".concat(e.source)),t.onchange=()=>{"denied"!==t.state&&(e.isMuted||e.restartTrack(),t.onchange=null)},new Error("GetUserMedia Permission denied")}catch(e){}e.isMuted||(h.debug("track ended, attempting to use a different device"),await e.restartTrack())}catch(t){h.warn("could not restart track, muting instead"),await e.mute()}},this.audioTracks=new Map,this.videoTracks=new Map,this.tracks=new Map,this.engine=i,this.roomOptions=n,this.setupEngine(i)}get lastCameraError(){return this.cameraError}get lastMicrophoneError(){return this.microphoneError}getTrack(e){const t=super.getTrack(e);if(t)return t}getTrackByName(e){const t=super.getTrackByName(e);if(t)return t}setupEngine(e){this.engine=e,this.engine.client.onRemoteMuteChanged=(e,t)=>{const i=this.tracks.get(e);i&&i.track&&(t?i.mute():i.unmute())},this.engine.client.onSubscribedQualityUpdate=this.handleSubscribedQualityUpdate,this.engine.client.onLocalTrackUnpublished=this.handleLocalTrackUnpublished,this.engine.on(ti.Connected,this.handleReconnected).on(ti.Restarted,this.handleReconnected).on(ti.Resumed,this.handleReconnected).on(ti.Restarting,this.handleReconnecting).on(ti.Resuming,this.handleReconnecting).on(ti.Disconnected,this.handleDisconnected)}setCameraEnabled(e,t,i){return this.setTrackEnabled(Track.Source.Camera,e,t,i)}setMicrophoneEnabled(e,t,i){return this.setTrackEnabled(Track.Source.Microphone,e,t,i)}setScreenShareEnabled(e,t,i){return this.setTrackEnabled(Track.Source.ScreenShare,e,t,i)}async setTrackEnabled(e,t,i,n){var s,a;h.debug("setTrackEnabled",{source:e,enabled:t});let o=this.getTrack(e);if(t)if(o)await o.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:null===(s=i)||void 0===s||s});break;case Track.Source.Microphone:t=await this.createTracks({audio:null===(a=i)||void 0===a||a});break;case Track.Source.ScreenShare:t=await this.createScreenTracks(_objectSpread2({},i));break;default:throw new TrackInvalidError(e)}const c=[];for(const e of t)h.info("publishing track",{localTrack:e}),c.push(this.publishTrack(e,n));const u=await Promise.all(c);[o]=u}catch(e){throw e instanceof Error&&!(e instanceof TrackInvalidError)&&this.emit(ei.MediaDevicesError,e),e}finally{this.pendingPublishing.delete(e)}}else if(o&&o.track)if(e===Track.Source.ScreenShare){o=await this.unpublishTrack(o.track);const e=this.getTrack(Track.Source.ScreenShareAudio);e&&e.track&&this.unpublishTrack(e.track)}else await o.mute();return o}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=Ri.h1080fps15.resolution);let i=!0;if(e.resolution&&(i=isSafari()?{width:{max:e.resolution.width},height:{max:e.resolution.height},frameRate:e.resolution.frameRate}:{width:{ideal:e.resolution.width},height:{ideal:e.resolution.height},frameRate:e.resolution.frameRate}),void 0===navigator.mediaDevices.getDisplayMedia)throw new DeviceUnsupportedError("getDisplayMedia not supported");const n=await navigator.mediaDevices.getDisplayMedia({audio:null!==(t=e.audio)&&void 0!==t&&t,video:i,controller:e.controller,selfBrowserSurface:e.selfBrowserSurface,surfaceSwitching:e.surfaceSwitching,systemAudio:e.systemAudio}),s=n.getVideoTracks();if(0===s.length)throw new TrackInvalidError("no video track found");const a=new LocalVideoTrack(s[0],void 0,!1);a.source=Track.Source.ScreenShare;const o=[a];if(n.getAudioTracks().length>0){const e=new LocalAudioTrack(n.getAudioTracks()[0],void 0,!1);e.source=Track.Source.ScreenShareAudio,o.push(e)}return o}async publishTrack(e,t){var i,n,s;if(await(null===(i=this.reconnectFuture)||void 0===i?void 0:i.promise),e instanceof LocalTrack&&this.pendingPublishPromises.has(e)&&await this.pendingPublishPromises.get(e),e instanceof MediaStreamTrack)switch(e.kind){case"audio":e=new LocalAudioTrack(e,void 0,!0);break;case"video":e=new LocalVideoTrack(e,void 0,!0);break;default:throw new TrackInvalidError("unsupported MediaStreamTrack kind ".concat(e.kind))}let a;if(this.tracks.forEach((t=>{t.track&&t.track===e&&(a=t)})),a)return h.warn("track has already been published, skipping"),a;const o=(null==t?void 0:t.forceStereo)||"channelCount"in e.mediaStreamTrack.getSettings()&&2===e.mediaStreamTrack.getSettings().channelCount||2===e.mediaStreamTrack.getConstraints().channelCount;o&&(t||(t={}),void 0===t.dtx&&h.info("Opus DTX will be disabled for stereo tracks by default. Enable them explicitly to make it work."),void 0===t.red&&h.info("Opus RED will be disabled for stereo tracks by default. Enable them explicitly to make it work."),null!==(n=t.dtx)&&void 0!==n||(t.dtx=!1),null!==(s=t.red)&&void 0!==s||(t.red=!1));const c=_objectSpread2(_objectSpread2({},this.roomOptions.publishDefaults),t);c.source&&(e.source=c.source);const u=this.publish(e,c,t,o);this.pendingPublishPromises.set(e,u);try{return await u}catch(e){throw e}finally{this.pendingPublishPromises.delete(e)}}async publish(e,t,i,n){var s,a,o,c;const u=Array.from(this.tracks.values()).find((t=>e instanceof LocalTrack&&t.source===e.source));if(u&&e.source!==Track.Source.Unknown)try{throw Error("publishing a second track with the same source: ".concat(e.source))}catch(t){t instanceof Error&&h.warn(t.message,{oldTrack:u,newTrack:e,trace:t.stack})}t.stopMicTrackOnMute&&e instanceof LocalAudioTrack&&(e.stopOnMute=!0),e.source===Track.Source.ScreenShare&&isFireFox()&&(t.simulcast=!1),"av1"!==t.videoCodec||supportsAV1()||(t.videoCodec=void 0),e.on(ii.Muted,this.onTrackMuted),e.on(ii.Unmuted,this.onTrackUnmuted),e.on(ii.Ended,this.handleTrackEnded),e.on(ii.UpstreamPaused,this.onTrackUpstreamPaused),e.on(ii.UpstreamResumed,this.onTrackUpstreamResumed);const l=kt.fromPartial({cid:e.mediaStreamTrack.id,name:null==i?void 0:i.name,type:Track.kindToProto(e.kind),muted:e.isMuted,source:Track.sourceToProto(e.source),disableDtx:!(null===(s=t.dtx)||void 0===s||s),stereo:n,disableRed:!(null===(a=t.red)||void 0===a||a)});let p,m;if(e.kind===Track.Kind.Video){let i={width:0,height:0};try{i=await e.waitForDimensions()}catch(e){h.error("could not determine track dimensions")}if(l.width=i.width,l.height=i.height,e instanceof LocalVideoTrack&&("av1"===(null==t?void 0:t.videoCodec)&&(t.scalabilityMode=null!==(o=t.scalabilityMode)&&void 0!==o?o:"L3T3"),t.videoCodec&&t.backupCodec&&t.videoCodec!==t.backupCodec.codec)){const i=_objectSpread2({},t);i.simulcast=!0,m=computeTrackBackupEncodings(e,t.backupCodec.codec,i),l.simulcastCodecs=[{codec:t.videoCodec,cid:e.mediaStreamTrack.id,enableSimulcastLayers:!0},{codec:t.backupCodec.codec,cid:"",enableSimulcastLayers:!0}]}p=computeVideoEncodings(e.source===Track.Source.ScreenShare,i.width,i.height,t),l.layers=videoLayersFromEncodings(l.width,l.height,null!=m?m:p)}else e.kind===Track.Kind.Audio&&t.audioBitrate&&(p=[{maxBitrate:t.audioBitrate}]);if(!this.engine||this.engine.isClosed)throw new UnexpectedConnectionState("cannot publish track when not connected");const v=await this.engine.addTrack(l),g=new LocalTrackPublication(e.kind,v,e);if(g.options=t,e.sid=v.sid,!this.engine.publisher)throw new UnexpectedConnectionState("publisher is closed");return h.debug("publishing ".concat(e.kind," with encodings"),{encodings:p,trackInfo:v}),e.sender=await this.engine.createSender(e,t,p),"av1"===e.codec&&p&&(null===(c=p[0])||void 0===c?void 0:c.maxBitrate)&&this.engine.publisher.setTrackCodecBitrate(l.cid,e.codec,p[0].maxBitrate/1e3),this.engine.negotiate(),e instanceof LocalVideoTrack?e.startMonitor(this.engine.client):e instanceof LocalAudioTrack&&e.startMonitor(),this.addTrackPublication(g),this.emit(ei.LocalTrackPublished,g),g}get isLocal(){return!0}async publishAdditionalCodecForTrack(e,t,i){var n;let s;if(this.tracks.forEach((t=>{t.track&&t.track===e&&(s=t)})),!s)throw new TrackInvalidError("track is not published");if(!(e instanceof LocalVideoTrack))throw new TrackInvalidError("track is not a video track");const a=_objectSpread2(_objectSpread2({},null===(n=this.roomOptions)||void 0===n?void 0:n.publishDefaults),i),o=computeTrackBackupEncodings(e,t,a);if(!o)return void h.info("backup codec has been disabled, ignoring request to add additional codec for track");const c=e.addSimulcastTrack(t,o),u=kt.fromPartial({cid:c.mediaStreamTrack.id,type:Track.kindToProto(e.kind),muted:e.isMuted,source:Track.sourceToProto(e.source),sid:e.sid,simulcastCodecs:[{codec:a.videoCodec,cid:c.mediaStreamTrack.id,enableSimulcastLayers:a.simulcast}]});if(u.layers=videoLayersFromEncodings(u.width,u.height,o),!this.engine||this.engine.isClosed)throw new UnexpectedConnectionState("cannot publish track when not connected");const l=await this.engine.addTrack(u);await this.engine.createSimulcastSender(e,c,a,o),this.engine.negotiate(),h.debug("published ".concat(t," for track ").concat(e.sid),{encodings:o,trackInfo:l})}async 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(ii.Muted,this.onTrackMuted),e.off(ii.Unmuted,this.onTrackUnmuted),e.off(ii.Ended,this.handleTrackEnded),e.off(ii.UpstreamPaused,this.onTrackUpstreamPaused),e.off(ii.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();let a=!1;const o=e.sender;if(e.sender=void 0,this.engine.publisher&&"closed"!==this.engine.publisher.pc.connectionState&&o)try{if(this.engine.removeTrack(o)&&(a=!0),e instanceof LocalVideoTrack){for(const[,t]of e.simulcastCodecs)t.sender&&(this.engine.removeTrack(t.sender)&&(a=!0),t.sender=void 0);e.simulcastCodecs.clear()}}catch(e){h.warn("failed to unpublish 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(ei.LocalTrackUnpublished,s),s.setTrack(void 0),a&&await this.engine.negotiate(),s}async unpublishTracks(e){return(await Promise.all(e.map((e=>this.unpublishTrack(e))))).filter((e=>e instanceof LocalTrackPublication))}async republishAllTracks(e){const t=[];this.tracks.forEach((i=>{i.track&&(e&&(i.options=_objectSpread2(_objectSpread2({},i.options),e)),t.push(i))})),await Promise.all(t.map((async e=>{const t=e.track;await this.unpublishTrack(t,!1),await this.publishTrack(t,e.options)})))}async publishData(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};const n=Array.isArray(i)?i:null==i?void 0:i.destination,s=[],a=Array.isArray(i)?void 0:i.topic;void 0!==n&&n.forEach((e=>{e instanceof RemoteParticipant?s.push(e.sid):s.push(e)}));const o={kind:t,value:{$case:"user",user:{participantSid:this.sid,payload:e,destinationSids:s,topic:a}}};await this.engine.sendDataPacket(o,t)}setTrackSubscriptionPermissions(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[];this.participantTrackPermissions=t,this.allParticipantsAllowedToSubscribe=e,this.engine.client.isConnected&&this.updateTrackSubscriptionPermissions()}updateInfo(e){e.sid===this.sid&&(super.updateInfo(e),e.tracks.forEach((e=>{var t,i;const n=this.tracks.get(e.sid);if(n){const s=n.isMuted||null!==(i=null===(t=n.track)||void 0===t?void 0:t.isUpstreamPaused)&&void 0!==i&&i;s!==e.muted&&(h.debug("updating server mute state after reconcile",{sid:e.sid,muted:s}),this.engine.client.sendMuteTrack(e.sid,s))}})))}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}publishedTracksInfo(){const e=[];return this.tracks.forEach((t=>{void 0!==t.track&&e.push({cid:t.track.mediaStreamID,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(Ae.LOSSY),pt.PUBLISHER),getInfo(this.engine.dataChannelForKind(Ae.RELIABLE),pt.PUBLISHER),getInfo(this.engine.dataChannelForKind(Ae.LOSSY,!0),pt.SUBSCRIBER),getInfo(this.engine.dataChannelForKind(Ae.RELIABLE,!0),pt.SUBSCRIBER),e}}const Ui=["syncState","trickle","offer","answer","simulate","leave"];class SignalClient{constructor(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];this.rtt=0,this.isConnected=!1,this.isReconnecting=!1,this.useJSON=e,this.requestQueue=new Queue,this.queuedRequests=[],this.closingLock=new Mutex}async join(e,t,i,n){this.isConnected=!1,this.options=i;return await this.connect(e,t,i,n)}async reconnect(e,t,i,n){if(!this.options)return void h.warn("attempted to reconnect without signal options being set, ignoring");this.isReconnecting=!0,this.clearPingInterval();return await this.connect(e,t,_objectSpread2(_objectSpread2({},this.options),{},{reconnect:!0,sid:i,reconnectReason:n}))}connect(e,t,i,n){this.connectOptions=i,e.startsWith("http")&&(e=e.replace("http","ws")),e=e.replace(/\/$/,""),e+="/rtc";const s=function createConnectionParams(e,t,i){var n;const s=new URLSearchParams;s.set("access_token",e),i.reconnect&&(s.set("reconnect","1"),i.sid&&s.set("sid",i.sid));s.set("auto_subscribe",i.autoSubscribe?"1":"0"),s.set("sdk","js"),s.set("version",t.version),s.set("protocol",t.protocol.toString()),t.deviceModel&&s.set("device_model",t.deviceModel);t.os&&s.set("os",t.os);t.osVersion&&s.set("os_version",t.osVersion);t.browser&&s.set("browser",t.browser);t.browserVersion&&s.set("browser_version",t.browserVersion);void 0!==i.publishOnly&&s.set("publish",i.publishOnly);i.adaptiveStream&&s.set("adaptive_stream","1");i.reconnectReason&&s.set("reconnect_reason",i.reconnectReason.toString());(null===(n=navigator.connection)||void 0===n?void 0:n.type)&&s.set("network",navigator.connection.type);return"?".concat(s.toString())}(t,function getClientInfo(){return Ke.fromPartial({sdk:Me.JS,protocol:ci,version:oi})}(),i);return new Promise((async(t,a)=>{const abortHandler=async()=>{await 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&&await this.close(),this.ws=new WebSocket(e+s),this.ws.binaryType="arraybuffer",this.ws.onerror=async t=>{if(this.isConnected)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",2,t.status));else{const e=await t.text();a(new ConnectionError(e,0,t.status))}}catch(e){a(new ConnectionError("server was not reachable",1))}},this.ws.onmessage=async e=>{var s,o,c,u;let l;if("string"==typeof e.data){const t=JSON.parse(e.data);l=bt.fromJSON(t)}else{if(!(e.data instanceof ArrayBuffer))return void h.error("could not decode websocket message: ".concat(typeof e.data));l=bt.decode(new Uint8Array(e.data))}if(!this.isConnected){let e=!1;if("join"===(null===(s=l.message)||void 0===s?void 0:s.$case)?(this.isConnected=!0,null==n||n.removeEventListener("abort",abortHandler),this.pingTimeoutDuration=l.message.join.pingTimeout,this.pingIntervalDuration=l.message.join.pingInterval,this.pingTimeoutDuration&&this.pingTimeoutDuration>0&&(h.debug("ping config",{timeout:this.pingTimeoutDuration,interval:this.pingIntervalDuration}),this.startPingInterval()),t(l.message.join)):i.reconnect?(this.isConnected=!0,null==n||n.removeEventListener("abort",abortHandler),this.startPingInterval(),"reconnect"===(null===(o=l.message)||void 0===o?void 0:o.$case)?t(null===(c=l.message)||void 0===c?void 0:c.reconnect):(t(),e=!0)):i.reconnect||a(new ConnectionError("did not receive join response, got ".concat(null===(u=l.message)||void 0===u?void 0:u.$case," instead"))),!e)return}this.signalLatency&&await sleep(this.signalLatency),this.handleSignalResponse(l)},this.ws.onclose=e=>{this.isConnected&&(h.debug("websocket connection closed: ".concat(e.reason)),this.isConnected=!1,this.onClose&&this.onClose(e.reason),this.ws=void 0)}}))}async close(){const e=await this.closingLock.lock();try{if(this.isConnected=!1,this.ws){this.ws.onclose=null,this.ws.onmessage=null,this.ws.onopen=null;const e=new Promise((e=>{this.ws?this.ws.onclose=e:e(!0)}));this.ws.close(),await Promise.race([e,sleep(250)])}this.ws=void 0,this.clearPingInterval()}finally{e()}}sendOffer(e){h.debug("sending offer",e),this.sendRequest({$case:"offer",offer:toProtoSessionDescription(e)})}sendAnswer(e){h.debug("sending answer"),this.sendRequest({$case:"answer",answer:toProtoSessionDescription(e)})}sendIceCandidate(e,t){h.trace("sending ice candidate",e),this.sendRequest({$case:"trickle",trickle:{candidateInit:JSON.stringify(e),target:t}})}sendMuteTrack(e,t){this.sendRequest({$case:"mute",mute:{sid:e,muted:t}})}sendAddTrack(e){this.sendRequest({$case:"addTrack",addTrack:kt.fromPartial(e)})}sendUpdateTrackSettings(e){this.sendRequest({$case:"trackSetting",trackSetting:e})}sendUpdateSubscription(e){this.sendRequest({$case:"subscription",subscription:e})}sendSyncState(e){this.sendRequest({$case:"syncState",syncState:e})}sendUpdateVideoLayers(e,t){this.sendRequest({$case:"updateLayers",updateLayers:{trackSid:e,layers:t}})}sendUpdateSubscriptionPermissions(e,t){this.sendRequest({$case:"subscriptionPermission",subscriptionPermission:{allParticipants:e,trackPermissions:t}})}sendSimulateScenario(e){this.sendRequest({$case:"simulate",simulate:e})}sendPing(){this.sendRequest({$case:"ping",ping:Date.now()}),this.sendRequest({$case:"pingReq",pingReq:{timestamp:Date.now(),rtt:this.rtt}})}async sendLeave(){await this.sendRequest({$case:"leave",leave:{canReconnect:!1,reason:Ie.CLIENT_INITIATED}})}async sendRequest(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];const i=!t&&!function canPassThroughQueue(e){const t=Ui.includes(e.$case);return h.trace("request allowed to bypass queue:",{canPass:t,req:e}),t}(e);if(i&&this.isReconnecting)return void this.queuedRequests.push((async()=>{await this.sendRequest(e,!0)}));if(t||await this.requestQueue.flush(),this.signalLatency&&await sleep(this.signalLatency),!this.ws||this.ws.readyState!==this.ws.OPEN)return void h.error("cannot send signal request before connected, type: ".concat(null==e?void 0:e.$case));const n={message:e};try{this.useJSON?this.ws.send(JSON.stringify(gt.toJSON(n))):this.ws.send(gt.encode(n).finish())}catch(e){h.error("error sending signal message",{error:e})}}handleSignalResponse(e){var t,i;const n=e.message;if(null!=n)if("answer"===n.$case){const e=fromProtoSessionDescription(n.answer);this.onAnswer&&this.onAnswer(e)}else if("offer"===n.$case){const e=fromProtoSessionDescription(n.offer);this.onOffer&&this.onOffer(e)}else if("trickle"===n.$case){const e=JSON.parse(n.trickle.candidateInit);this.onTrickle&&this.onTrickle(e,n.trickle.target)}else"update"===n.$case?this.onParticipantUpdate&&this.onParticipantUpdate(null!==(t=n.update.participants)&&void 0!==t?t:[]):"trackPublished"===n.$case?this.onLocalTrackPublished&&this.onLocalTrackPublished(n.trackPublished):"speakersChanged"===n.$case?this.onSpeakersChanged&&this.onSpeakersChanged(null!==(i=n.speakersChanged.speakers)&&void 0!==i?i:[]):"leave"===n.$case?this.onLeave&&this.onLeave(n.leave):"mute"===n.$case?this.onRemoteMuteChanged&&this.onRemoteMuteChanged(n.mute.sid,n.mute.muted):"roomUpdate"===n.$case?this.onRoomUpdate&&n.roomUpdate.room&&this.onRoomUpdate(n.roomUpdate.room):"connectionQuality"===n.$case?this.onConnectionQuality&&this.onConnectionQuality(n.connectionQuality):"streamStateUpdate"===n.$case?this.onStreamStateUpdate&&this.onStreamStateUpdate(n.streamStateUpdate):"subscribedQualityUpdate"===n.$case?this.onSubscribedQualityUpdate&&this.onSubscribedQualityUpdate(n.subscribedQualityUpdate):"subscriptionPermissionUpdate"===n.$case?this.onSubscriptionPermissionUpdate&&this.onSubscriptionPermissionUpdate(n.subscriptionPermissionUpdate):"refreshToken"===n.$case?this.onTokenRefresh&&this.onTokenRefresh(n.refreshToken):"trackUnpublished"===n.$case?this.onLocalTrackUnpublished&&this.onLocalTrackUnpublished(n.trackUnpublished):"pong"===n.$case?this.resetPingTimeout():"pongResp"===n.$case?(this.rtt=Date.now()-n.pongResp.lastPingTimestamp,this.resetPingTimeout()):h.debug("unsupported message",n);else h.debug("received unsupported message")}setReconnected(){for(;this.queuedRequests.length>0;){const e=this.queuedRequests.shift();e&&this.requestQueue.run(e)}this.isReconnecting=!1}handleWSError(e){h.error("websocket error",e)}resetPingTimeout(){this.clearPingTimeout(),this.pingTimeoutDuration?this.pingTimeout=CriticalTimers.setTimeout((()=>{h.warn("ping timeout triggered. last pong received at: ".concat(new Date(Date.now()-1e3*this.pingTimeoutDuration).toUTCString())),this.onClose&&this.onClose("ping timeout")}),1e3*this.pingTimeoutDuration):h.warn("ping timeout duration not set")}clearPingTimeout(){this.pingTimeout&&CriticalTimers.clearTimeout(this.pingTimeout)}startPingInterval(){this.clearPingInterval(),this.resetPingTimeout(),this.pingIntervalDuration?(h.debug("start ping interval"),this.pingInterval=CriticalTimers.setInterval((()=>{this.sendPing()}),1e3*this.pingIntervalDuration)):h.warn("ping interval duration not set")}clearPingInterval(){h.debug("clearing ping interval"),this.clearPingTimeout(),this.pingInterval&&CriticalTimers.clearInterval(this.pingInterval)}}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}}const Mi={audioBitrate:Ci.music.maxBitrate,dtx:!0,red:!0,forceStereo:!1,simulcast:!0,screenShareEncoding:Ri.h1080fps15.encoding,stopMicTrackOnMute:!1,videoCodec:"vp8",backupCodec:{codec:"vp8",encoding:Pi.h540.encoding}},xi={autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0},$i={resolution:Pi.h720.resolution},Bi={adaptiveStream:!1,dynacast:!1,stopLocalTrackOnUnpublish:!0,reconnectPolicy:new DefaultReconnectPolicy,disconnectOnPageLeave:!0,expWebAudioMix:!1},Fi={autoSubscribe:!0,maxRetries:1,peerConnectionTimeout:15e3};var Ji={},Vi={},ji={get exports(){return Vi},set exports(e){Vi=e}}.exports={v:[{name:"version",reg:/^(\d*)$/}],o:[{name:"origin",reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:["username","sessionId","sessionVersion","netType","ipVer","address"],format:"%s %s %d %s IP%d %s"}],s:[{name:"name"}],i:[{name:"description"}],u:[{name:"uri"}],e:[{name:"email"}],p:[{name:"phone"}],z:[{name:"timezones"}],r:[{name:"repeats"}],t:[{name:"timing",reg:/^(\d*) (\d*)/,names:["start","stop"],format:"%d %d"}],c:[{name:"connection",reg:/^IN IP(\d) (\S*)/,names:["version","ip"],format:"IN IP%d %s"}],b:[{push:"bandwidth",reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:["type","limit"],format:"%s:%s"}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:["type","port","protocol","payloads"],format:"%s %d %s %s"}],a:[{push:"rtp",reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:["payload","codec","rate","encoding"],format:function(e){return e.encoding?"rtpmap:%d %s/%s/%s":e.rate?"rtpmap:%d %s/%s":"rtpmap:%d %s"}},{push:"fmtp",reg:/^fmtp:(\d*) ([\S| ]*)/,names:["payload","config"],format:"fmtp:%d %s"},{name:"control",reg:/^control:(.*)/,format:"control:%s"},{name:"rtcp",reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:["port","netType","ipVer","address"],format:function(e){return null!=e.address?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%s trr-int %d"},{push:"rtcpFb",reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:["payload","type","subtype"],format:function(e){return null!=e.subtype?"rtcp-fb:%s %s %s":"rtcp-fb:%s %s"}},{push:"ext",reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:["value","direction","encrypt-uri","uri","config"],format:function(e){return"extmap:%d"+(e.direction?"/%s":"%v")+(e["encrypt-uri"]?" %s":"%v")+" %s"+(e.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(e){return null!=e.sessionConfig?"crypto:%d %s %s %s":"crypto:%d %s %s"}},{name:"setup",reg:/^setup:(\w*)/,format:"setup:%s"},{name:"connectionType",reg:/^connection:(new|existing)/,format:"connection:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{name:"msid",reg:/^msid:(.*)/,format:"msid:%s"},{name:"ptime",reg:/^ptime:(\d*(?:\.\d*)*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\d*(?:\.\d*)*)/,format:"maxptime:%d"},{name:"direction",reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:"icelite",reg:/^(ice-lite)/},{name:"iceUfrag",reg:/^ice-ufrag:(\S*)/,format:"ice-ufrag:%s"},{name:"icePwd",reg:/^ice-pwd:(\S*)/,format:"ice-pwd:%s"},{name:"fingerprint",reg:/^fingerprint:(\S*) (\S*)/,names:["type","hash"],format:"fingerprint:%s %s"},{push:"candidates",reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation","network-id","network-cost"],format:function(e){var t="candidate:%s %d %s %d %s %d typ %s";return t+=null!=e.raddr?" raddr %s rport %d":"%v%v",t+=null!=e.tcptype?" tcptype %s":"%v",null!=e.generation&&(t+=" generation %d"),t+=null!=e["network-id"]?" network-id %d":"%v",t+=null!=e["network-cost"]?" network-cost %d":"%v"}},{name:"endOfCandidates",reg:/^(end-of-candidates)/},{name:"remoteCandidates",reg:/^remote-candidates:(.*)/,format:"remote-candidates:%s"},{name:"iceOptions",reg:/^ice-options:(\S*)/,format:"ice-options:%s"},{push:"ssrcs",reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:["id","attribute","value"],format:function(e){var t="ssrc:%d";return null!=e.attribute&&(t+=" %s",null!=e.value&&(t+=":%s")),t}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","maxMessageSize"],format:function(e){return null!=e.maxMessageSize?"sctpmap:%s %s %s":"sctpmap:%s %s"}},{name:"xGoogleFlag",reg:/^x-google-flag:([^\s]*)/,format:"x-google-flag:%s"},{push:"rids",reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:["id","direction","params"],format:function(e){return e.params?"rid:%s %s %s":"rid:%s %s"}},{push:"imageattrs",reg:new RegExp("^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?"),names:["pt","dir1","attrs1","dir2","attrs2"],format:function(e){return"imageattr:%s %s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast",reg:new RegExp("^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$"),names:["dir1","list1","dir2","list2"],format:function(e){return"simulcast:%s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast_03",reg:/^simulcast:[\s\t]+([\S+\s\t]+)$/,names:["value"],format:"simulcast: %s"},{name:"framerate",reg:/^framerate:(\d+(?:$|\.\d+))/,format:"framerate:%s"},{name:"sourceFilter",reg:/^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,names:["filterMode","netType","addressTypes","destAddress","srcList"],format:"source-filter: %s %s %s %s %s"},{name:"bundleOnly",reg:/^(bundle-only)/},{name:"label",reg:/^label:(.+)/,format:"label:%s"},{name:"sctpPort",reg:/^sctp-port:(\d+)$/,format:"sctp-port:%s"},{name:"maxMessageSize",reg:/^max-message-size:(\d+)$/,format:"max-message-size:%s"},{push:"tsRefClocks",reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:["clksrc","clksrcExt"],format:function(e){return"ts-refclk:%s"+(null!=e.clksrcExt?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(e){var t="mediaclk:";return t+=null!=e.id?"id=%s %s":"%v%s",t+=null!=e.mediaClockValue?"=%s":"",t+=null!=e.rateNumerator?" rate=%s":"",t+=null!=e.rateDenominator?"/%s":""}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{push:"invalid",names:["value"]}]};Object.keys(ji).forEach((function(e){ji[e].forEach((function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")}))})),function(e){var toIntIfInt=function(e){return String(Number(e))===e?Number(e):e},parseReg=function(e,t,i){var n=e.name&&e.names;e.push&&!t[e.push]?t[e.push]=[]:n&&!t[e.name]&&(t[e.name]={});var s=e.push?{}:n?t[e.name]:t;!function(e,t,i,n){if(n&&!i)t[n]=toIntIfInt(e[1]);else for(var s=0;s1&&(e[i[0]]=void 0),e};e.parseParams=function(e){return e.split(/;\s?/).reduce(paramReducer,{})},e.parseFmtpConfig=e.parseParams,e.parsePayloads=function(e){return e.toString().split(" ").map(Number)},e.parseRemoteCandidates=function(e){for(var t=[],i=e.split(" ").map(toIntIfInt),n=0;n=n)return e;var s=i[t];switch(t+=1,e){case"%%":return"%";case"%s":return String(s);case"%d":return Number(s);case"%v":return""}}))},makeLine=function(e,t,i){var n=[e+"="+(t.format instanceof Function?t.format(t.push?i:i[t.name]):t.format)];if(t.names)for(var s=0;s{this.emit(Ki);try{this.createAndSendOffer()}catch(t){if(!e)throw t;e(t)}}),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){if("offer"===e.type){let{stereoMids:t,nackMids:i}=function extractStereoAndNackAudioFromOffer(e){var t;const i=[],n=[],s=Zi(null!==(t=e.sdp)&&void 0!==t?t:"");let a=0;return s.media.forEach((e=>{var t;"audio"===e.type&&(e.rtp.some((e=>"opus"===e.codec&&(a=e.payload,!0))),(null===(t=e.rtcpFb)||void 0===t?void 0:t.some((e=>e.payload===a&&"nack"===e.type)))&&n.push(e.mid),e.fmtp.some((t=>t.payload===a&&(t.config.includes("sprop-stereo=1")&&i.push(e.mid),!0))))})),{stereoMids:i,nackMids:n}}(e);this.remoteStereoMids=t,this.remoteNackMids=i}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()):"answer"===e.type&&this.emit(Yi)}async createAndSendOffer(e){var t;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 i=await this.pc.createOffer(e),n=Zi(null!==(t=i.sdp)&&void 0!==t?t:"");n.media.forEach((e=>{"audio"===e.type?ensureAudioNackAndStereo(e,[],[]):"video"===e.type&&this.trackBitrates.some((t=>{if(!e.msid||!e.msid.includes(t.sid))return!1;let i=0;return e.rtp.some((e=>e.codec.toUpperCase()===t.codec.toUpperCase()&&(i=e.payload,!0))),i>0&&(e.fmtp.some((e=>e.payload===i&&(e.config.includes("x-google-max-bitrate")||(e.config+=";x-google-max-bitrate=".concat(t.maxbr)),!0)))||e.fmtp.push({payload:i,config:"x-google-max-bitrate=".concat(t.maxbr)})),!0}))})),this.trackBitrates=[],await this.setMungedLocalDescription(i,Hi(n)),this.onOffer(i)}async createAndSetAnswer(){var e;const t=await this.pc.createAnswer(),i=Zi(null!==(e=t.sdp)&&void 0!==e?e:"");return i.media.forEach((e=>{"audio"===e.type&&ensureAudioNackAndStereo(e,this.remoteStereoMids,this.remoteNackMids)})),await this.setMungedLocalDescription(t,Hi(i)),t}setTrackCodecBitrate(e,t,i){this.trackBitrates.push({sid:e,codec:t,maxbr:i})}close(){this.pc.onconnectionstatechange=null,this.pc.oniceconnectionstatechange=null,this.pc.close()}async setMungedLocalDescription(e,t){const i=e.sdp;e.sdp=t;try{return h.debug("setting munged local description"),void await this.pc.setLocalDescription(e)}catch(t){h.warn("not able to set ".concat(e.type,", falling back to unmodified sdp"),{error:t}),e.sdp=i}try{await this.pc.setLocalDescription(e)}catch(e){let t="unknown error";throw e instanceof Error?t=e.message:"string"==typeof e&&(t=e),new NegotiationError(t)}}}function ensureAudioNackAndStereo(e,t,i){let n=0;e.rtp.some((e=>"opus"===e.codec&&(n=e.payload,!0))),n>0&&(e.rtcpFb||(e.rtcpFb=[]),i.includes(e.mid)&&!e.rtcpFb.some((e=>e.payload===n&&"nack"===e.type))&&e.rtcpFb.push({payload:n,type:"nack"}),t.includes(e.mid)&&e.fmtp.some((e=>e.payload===n&&(e.config.includes("stereo=1")||(e.config+=";stereo=1"),!0))))}const Xi="_lossy",er="_reliable",tr="leave-reconnect";var ir,rr;!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"}(ir||(ir={}));class RTCEngine extends vi.EventEmitter{get isClosed(){return this._isClosed}constructor(e){super(),this.options=e,this.rtcConfig={},this.peerConnectionTimeout=Fi.peerConnectionTimeout,this.subscriberPrimary=!1,this.pcState=ir.New,this._isClosed=!0,this.pendingTrackResolvers={},this.hasPublished=!1,this.reconnectAttempts=0,this.reconnectStart=0,this.fullReconnectOnNext=!1,this.attemptingReconnect=!1,this.joinAttempts=0,this.maxJoinAttempts=1,this.shouldFailNext=!1,this.handleDataChannel=async e=>{let{channel:t}=e;if(t){if(t.label===er)this.reliableDCSub=t;else{if(t.label!==Xi)return;this.lossyDCSub=t}h.debug("on data channel ".concat(t.id,", ").concat(t.label)),t.onmessage=this.handleDataMessage}},this.handleDataMessage=async e=>{var t,i;const n=await this.dataProcessLock.lock();try{let s;if(e.data instanceof ArrayBuffer)s=e.data;else{if(!(e.data instanceof Blob))return void h.error("unsupported data type",e.data);s=await e.data.arrayBuffer()}const a=qe.decode(new Uint8Array(s));"speaker"===(null===(t=a.value)||void 0===t?void 0:t.$case)?this.emit(ti.ActiveSpeakersUpdate,a.value.speaker.speakers):"user"===(null===(i=a.value)||void 0===i?void 0:i.$case)&&this.emit(ti.DataPacketReceived,a.value.user,a.kind)}finally{n()}},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,t)=>{if(this._isClosed)return;h.warn("".concat(e," disconnected")),0===this.reconnectAttempts&&(this.reconnectStart=Date.now());const disconnect=e=>{h.warn("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(e,"ms. giving up")),this.emit(ti.Disconnected),this.close()},i=Date.now()-this.reconnectStart;let n=this.getNextRetryDelay({elapsedMs:i,retryCount:this.reconnectAttempts});null!==n?(e===tr&&(n=0),h.debug("reconnecting in ".concat(n,"ms")),this.clearReconnectTimeout(),this.reconnectTimeout=CriticalTimers.setTimeout((()=>this.attemptReconnect(t)),n)):disconnect(i)},this.handleBrowserOnLine=()=>{this.client.isReconnecting&&(this.clearReconnectTimeout(),this.attemptReconnect(De.RR_SIGNAL_DISCONNECTED))},this.client=new SignalClient,this.client.signalLatency=this.options.expSignalLatency,this.reconnectPolicy=this.options.reconnectPolicy,this.registerOnLineListener(),this.closingLock=new Mutex,this.dataProcessLock=new Mutex}async join(e,t,i,n){this.url=e,this.token=t,this.signalOpts=i;try{this.joinAttempts+=1;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}catch(s){if(s instanceof ConnectionError&&1===s.reason&&(h.warn("Couldn't connect to server, attempt ".concat(this.joinAttempts," of ").concat(this.maxJoinAttempts)),this.joinAttempts{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),await this.client.close()}finally{e()}}addTrack(e){if(this.pendingTrackResolvers[e.cid])throw new TrackInvalidError("a track with the same ID has already been published");return new Promise(((t,i)=>{const n=setTimeout((()=>{delete this.pendingTrackResolvers[e.cid],i(new ConnectionError("publication of local track timed out, no response from server"))}),1e4);this.pendingTrackResolvers[e.cid]={resolve:e=>{clearTimeout(n),t(e)},reject:()=>{clearTimeout(n),i(new Error("Cancelled publication by calling unpublish"))}},this.client.sendAddTrack(e)}))}removeTrack(e){var t;if(e.track&&this.pendingTrackResolvers[e.track.id]){const{reject:t}=this.pendingTrackResolvers[e.track.id];t&&t(),delete this.pendingTrackResolvers[e.track.id]}try{return null===(t=this.publisher)||void 0===t||t.pc.removeTrack(e),!0}catch(e){h.warn("failed to remove track",{error:e,method:"removeTrack"})}return!1}updateMuteStatus(e,t){this.client.sendMuteTrack(e,t)}get dataSubscriberReadyState(){var e;return null===(e=this.reliableDCSub)||void 0===e?void 0:e.readyState}async getConnectedServerAddress(){if(void 0!==this.primaryPC)return async function getConnectedAddress(e){var t;let i="";const n=new Map,s=new Map;if((await e.getStats()).forEach((e=>{switch(e.type){case"transport":i=e.selectedCandidatePairId;break;case"candidate-pair":""===i&&e.selected&&(i=e.id),n.set(e.id,e);break;case"remote-candidate":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;if(void 0===a)return;return s.get(a)}(this.primaryPC)}configure(e){var t;if(this.publisher||this.subscriber)return;this.participantSid=null===(t=e.participant)||void 0===t?void 0:t.sid;const i=this.makeRTCConfiguration(e);this.publisher=new PCTransport(i),this.subscriber=new PCTransport(i),this.emit(ti.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,pt.PUBLISHER))},this.subscriber.pc.onicecandidate=e=>{e.candidate&&this.client.sendIceCandidate(e.candidate,pt.SUBSCRIBER)},this.publisher.onOffer=e=>{this.client.sendOffer(e)};let n=this.publisher.pc,s=this.subscriber.pc,a=e.subscriberPrimary;a&&(n=this.subscriber.pc,s=this.publisher.pc,this.subscriber.pc.ondatachannel=this.handleDataChannel),this.primaryPC=n,n.onconnectionstatechange=async()=>{if(h.debug("primary PC state changed ".concat(n.connectionState)),"connected"===n.connectionState){const t=this.pcState===ir.New;this.pcState=ir.Connected,t&&this.emit(ti.Connected,e)}else"failed"===n.connectionState&&this.pcState===ir.Connected&&(this.pcState=ir.Disconnected,this.handleDisconnect("primary peerconnection",a?De.RR_SUBSCRIBER_FAILED:De.RR_PUBLISHER_FAILED))},s.onconnectionstatechange=async()=>{h.debug("secondary PC state changed ".concat(s.connectionState)),"failed"===s.connectionState&&this.handleDisconnect("secondary peerconnection",a?De.RR_PUBLISHER_FAILED:De.RR_SUBSCRIBER_FAILED)},this.subscriber.pc.ontrack=e=>{this.emit(ti.MediaTrackAdded,e.track,e.streams[0],e.receiver)},this.createDataChannels(),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===pt.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.createAndSetAnswer();this.client.sendAnswer(t)},this.client.onLocalTrackPublished=e=>{h.debug("received trackPublishedResponse",e);const{resolve: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",De.RR_SIGNAL_DISCONNECTED)},this.client.onLeave=e=>{(null==e?void 0:e.canReconnect)?(this.fullReconnectOnNext=!0,this.primaryPC=void 0,this.handleDisconnect(tr)):(this.emit(ti.Disconnected,null==e?void 0:e.reason),this.close()),h.trace("leave request",{leave:e})}}makeRTCConfiguration(e){const t=_objectSpread2({},this.rtcConfig);if(e.iceServers&&!t.iceServers){const i=[];e.iceServers.forEach((e=>{const t={urls:e.urls};e.username&&(t.username=e.username),e.credential&&(t.credential=e.credential),i.push(t)})),t.iceServers=i}return e.clientConfiguration&&e.clientConfiguration.forceRelay===Ne.ENABLED&&(t.iceTransportPolicy="relay"),t.sdpSemantics="unified-plan",t.continualGatheringPolicy="gather_continually",t}createDataChannels(){this.publisher&&(this.lossyDC&&(this.lossyDC.onmessage=null,this.lossyDC.onerror=null),this.reliableDC&&(this.reliableDC.onmessage=null,this.reliableDC.onerror=null),this.lossyDC=this.publisher.pc.createDataChannel(Xi,{ordered:!0,maxRetransmits:0}),this.reliableDC=this.publisher.pc.createDataChannel(er,{ordered:!0}),this.lossyDC.onmessage=this.handleDataMessage,this.reliableDC.onmessage=this.handleDataMessage,this.lossyDC.onerror=this.handleDataError,this.reliableDC.onerror=this.handleDataError)}setPreferredCodec(e,t,i){if(!("getCapabilities"in RTCRtpSender))return;const n=RTCRtpSender.getCapabilities(t);if(!n)return;h.debug("get capabilities",n);const s=[],a=[],o=[];n.codecs.forEach((e=>{const t=e.mimeType.toLowerCase();if("audio/opus"===t)return void s.push(e);t==="video/".concat(i)?"h264"!==i||e.sdpFmtpLine&&e.sdpFmtpLine.includes("profile-level-id=42e01f")?s.push(e):a.push(e):o.push(e)})),supportsSetCodecPreferences(e)&&e.setCodecPreferences(s.concat(a,o))}async createSender(e,t,i){if(supportsTransceiver())return this.createTransceiverRTCRtpSender(e,t,i);if(supportsAddTrack())return h.debug("using add-track fallback"),this.createRTCRtpSender(e.mediaStreamTrack);throw new UnexpectedConnectionState("Required webRTC APIs not supported on this device")}async createSimulcastSender(e,t,i,n){if(supportsTransceiver())return this.createSimulcastTransceiverSender(e,t,i,n);if(supportsAddTrack())return h.debug("using add-track fallback"),this.createRTCRtpSender(e.mediaStreamTrack);throw new UnexpectedConnectionState("Cannot stream on this device")}async createTransceiverRTCRtpSender(e,t,i){if(!this.publisher)throw new UnexpectedConnectionState("publisher is closed");const n={direction:"sendonly"};i&&(n.sendEncodings=i);const s=await this.publisher.pc.addTransceiver(e.mediaStreamTrack,n);return e.kind===Track.Kind.Video&&t.videoCodec&&(this.setPreferredCodec(s,e.kind,t.videoCodec),e.codec=t.videoCodec),s.sender}async createSimulcastTransceiverSender(e,t,i,n){if(!this.publisher)throw new UnexpectedConnectionState("publisher is closed");const s={direction:"sendonly"};n&&(s.sendEncodings=n);const a=await this.publisher.pc.addTransceiver(t.mediaStreamTrack,s);if(i.videoCodec)return this.setPreferredCodec(a,e.kind,i.videoCodec),e.setSimulcastTrackSender(i.videoCodec,a.sender),a.sender}async createRTCRtpSender(e){if(!this.publisher)throw new UnexpectedConnectionState("publisher is closed");return this.publisher.pc.addTrack(e)}async attemptReconnect(e){var t,i,n;if(!this._isClosed&&!this.attemptingReconnect){(null===(t=this.clientConfiguration)||void 0===t?void 0:t.resumeConnection)!==Ne.DISABLED&&"closed"!==(null!==(n=null===(i=this.primaryPC)||void 0===i?void 0:i.signalingState)&&void 0!==n?n:"closed")||(this.fullReconnectOnNext=!0);try{this.attemptingReconnect=!0,this.fullReconnectOnNext?await this.restartConnection():await this.resumeConnection(e),this.clearPendingReconnect(),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),t?this.handleDisconnect("reconnect",De.RR_UNKOWN):(h.info("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(Date.now()-this.reconnectStart,"ms. giving up")),this.emit(ti.Disconnected),this.close())}finally{this.attemptingReconnect=!1}}}getNextRetryDelay(e){try{return this.reconnectPolicy.nextRetryDelayInMs(e)}catch(e){h.warn("encountered error in reconnect policy",{error:e})}return null}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)),this.emit(ti.Restarting),this.client.isConnected&&await this.client.sendLeave(),await this.client.close(),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{if(!this.signalOpts)throw h.warn("attempted connection restart, without signal options present"),new SignalReconnectError;i=await this.join(this.url,this.token,this.signalOpts)}catch(e){throw new SignalReconnectError}if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");await this.waitForPCConnected(),this.client.setReconnected(),this.emit(ti.Restarted,i)}async resumeConnection(e){var t;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)),this.emit(ti.Resuming);try{const t=await this.client.reconnect(this.url,this.token,this.participantSid,e);if(t){const e=this.makeRTCConfiguration(t);this.publisher.pc.setConfiguration(e),this.subscriber.pc.setConfiguration(e)}}catch(e){let t="";throw e instanceof Error&&(t=e.message),new SignalReconnectError(t)}if(this.emit(ti.SignalResumed),this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");this.subscriber.restartingIce=!0,this.hasPublished&&await this.publisher.createAndSendOffer({iceRestart:!0}),await this.waitForPCConnected(),this.client.setReconnected(),"open"===(null===(t=this.reliableDC)||void 0===t?void 0:t.readyState)&&null===this.reliableDC.id&&this.createDataChannels(),this.emit(ti.Resumed)}async waitForPCConnected(){var e;const t=Date.now();let i=t;for(this.pcState=ir.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=ir.Connected),this.pcState===ir.Connected)return;await sleep(100),i=Date.now()}throw new ConnectionError("could not establish PC connection")}async sendDataPacket(e,t){const i=qe.encode(e).finish();await this.ensurePublisherConnected(t),t===Ae.LOSSY&&this.lossyDC?this.lossyDC.send(i):t===Ae.RELIABLE&&this.reliableDC&&this.reliableDC.send(i)}async ensureDataTransportConnected(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.subscriberPrimary;var i,n,s;const a=t?this.subscriber:this.publisher,o=t?"Subscriber":"Publisher";if(!a)throw new ConnectionError("".concat(o," connection not set"));t||(null===(i=this.publisher)||void 0===i?void 0:i.isICEConnected)||"checking"===(null===(n=this.publisher)||void 0===n?void 0:n.pc.iceConnectionState)||this.negotiate();const c=this.dataChannelForKind(e,t);if("open"===(null==c?void 0:c.readyState))return;const u=(new Date).getTime()+this.peerConnectionTimeout;for(;(new Date).getTime(){if(!this.publisher)return void t(new NegotiationError("publisher is not defined"));this.hasPublished=!0;const handleClosed=()=>{h.debug("engine disconnected while negotiation was ongoing"),cleanup(),e()};this.on(ti.Closing,handleClosed);const i=setTimeout((()=>{t("negotiation timed out"),this.handleDisconnect("negotiation",De.RR_SIGNAL_DISCONNECTED)}),this.peerConnectionTimeout),cleanup=()=>{clearTimeout(i),this.off(ti.Closing,handleClosed)};this.publisher.once(Ki,(()=>{var t;null===(t=this.publisher)||void 0===t||t.once(Yi,(()=>{cleanup(),e()}))})),this.publisher.negotiate((e=>{cleanup(),t(e),e instanceof NegotiationError&&(this.fullReconnectOnNext=!0),this.handleDisconnect("negotiation",De.RR_UNKOWN)}))}))}dataChannelForKind(e,t){if(t){if(e===Ae.LOSSY)return this.lossyDCSub;if(e===Ae.RELIABLE)return this.reliableDCSub}else{if(e===Ae.LOSSY)return this.lossyDC;if(e===Ae.RELIABLE)return this.reliableDC}}failNext(){this.shouldFailNext=!0}clearReconnectTimeout(){this.reconnectTimeout&&CriticalTimers.clearTimeout(this.reconnectTimeout)}clearPendingReconnect(){this.clearReconnectTimeout(),this.reconnectAttempts=0}registerOnLineListener(){isWeb()&&window.addEventListener("online",this.handleBrowserOnLine)}deregisterOnLineListener(){isWeb()&&window.removeEventListener("online",this.handleBrowserOnLine)}}class SignalReconnectError extends Error{}!function(e){e.Disconnected="disconnected",e.Connecting="connecting",e.Connected="connected",e.Reconnecting="reconnecting"}(rr||(rr={}));const nr=rr;class Room extends vi.EventEmitter{constructor(e){var t;super(),t=this,this.state=rr.Disconnected,this.activeSpeakers=[],this.sid="",this.name="",this.metadata=void 0,this._isRecording=!1,this.audioEnabled=!0,this.connect=async(e,t,i)=>{const n=await this.disconnectLock.lock();if(this.state===rr.Connected)return h.info("already connected to room ".concat(this.name)),n(),Promise.resolve();if(this.connectFuture)return n(),this.connectFuture.promise;this.setAndEmitConnectionState(rr.Connecting);return this.connectFuture=new Future((async(s,a)=>{var o,c;this.abortController&&!this.abortController.signal.aborted||(this.abortController=new AbortController),n(),this.state===rr.Reconnecting?(h.info("Reconnection attempt replaced by new connection attempt"),this.recreateEngine()):this.maybeCreateEngine(),this.acquireAudioContext(),this.connOptions=_objectSpread2(_objectSpread2({},Fi),i),this.connOptions.rtcConfig&&(this.engine.rtcConfig=this.connOptions.rtcConfig),this.connOptions.peerConnectionTimeout&&(this.engine.peerConnectionTimeout=this.connOptions.peerConnectionTimeout);try{const i=await this.engine.join(e,t,{autoSubscribe:this.connOptions.autoSubscribe,publishOnly:this.connOptions.publishOnly,adaptiveStream:"object"==typeof this.options.adaptiveStream||this.options.adaptiveStream,maxRetries:this.connOptions.maxRetries},this.abortController.signal);let n=i.serverInfo;if(n||(n={version:i.serverVersion,region:i.serverRegion}),h.debug("connected to Livekit Server ".concat(Object.entries(n).map((e=>{let[t,i]=e;return"".concat(t,": ").concat(i)})).join(", "))),!i.serverVersion)throw new UnsupportedServer("unknown server version");"0.15.1"===i.serverVersion&&this.options.dynacast&&(h.debug("disabling dynacast due to server version"),this.options.dynacast=!1);const s=i.participant;this.localParticipant.sid=s.sid,this.localParticipant.identity=s.identity,this.localParticipant.updateInfo(s),this.setupLocalParticipantEvents(),i.otherParticipants.forEach((e=>{e.sid!==this.localParticipant.sid&&e.identity!==this.localParticipant.identity?this.getOrCreateParticipant(e.sid,e):h.warn("received info to create local participant as remote participant",{info:e,localParticipant:this.localParticipant})})),this.name=i.room.name,this.sid=i.room.sid,this.metadata=i.room.metadata,this._isRecording!==i.room.activeRecording&&(this._isRecording=i.room.activeRecording,this.emit(Xt.RecordingStatusChanged,i.room.activeRecording)),this.emit(Xt.SignalConnected)}catch(e){this.recreateEngine(),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish);const t=new ConnectionError("could not establish signal connection");return e instanceof Error&&(t.message="".concat(t.message,": ").concat(e.message)),e instanceof ConnectionError&&(t.reason=e.reason,t.status=e.status),h.debug("error trying to establish signal connection",{error:e}),void a(t)}const u=CriticalTimers.setTimeout((()=>{this.recreateEngine(),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),a(new ConnectionError("could not connect PeerConnection after timeout"))}),this.connOptions.peerConnectionTimeout),abortHandler=()=>{h.warn("closing engine"),CriticalTimers.clearTimeout(u),this.recreateEngine(),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),a(new ConnectionError("room connection has been cancelled"))};(null===(o=this.abortController)||void 0===o?void 0:o.signal.aborted)&&abortHandler(),null===(c=this.abortController)||void 0===c||c.signal.addEventListener("abort",abortHandler),this.engine.once(ti.Connected,(()=>{var e,t;CriticalTimers.clearTimeout(u),null===(e=this.abortController)||void 0===e||e.signal.removeEventListener("abort",abortHandler),isWeb()&&this.options.disconnectOnPageLeave&&(window.addEventListener("pagehide",this.onPageLeave),window.addEventListener("beforeunload",this.onPageLeave),null===(t=navigator.mediaDevices)||void 0===t||t.addEventListener("devicechange",this.handleDeviceChange)),this.setAndEmitConnectionState(rr.Connected),this.emit(Xt.Connected),s()}))}),(()=>{this.clearConnectionFutures()})),this.connectFuture.promise},this.disconnect=async function(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];var i,n,s,a;const o=await t.disconnectLock.lock();try{if(t.state===rr.Disconnected)return void h.debug("already disconnected");h.info("disconnect from room",{identity:t.localParticipant.identity}),t.state!==rr.Connecting&&t.state!==rr.Reconnecting||(h.warn("abort connection attempt"),null===(i=t.abortController)||void 0===i||i.abort(),null===(s=null===(n=t.connectFuture)||void 0===n?void 0:n.reject)||void 0===s||s.call(n,new ConnectionError("Client initiated disconnect")),t.connectFuture=void 0),(null===(a=t.engine)||void 0===a?void 0:a.client.isConnected)&&await t.engine.client.sendLeave(),t.engine&&await t.engine.close(),t.handleDisconnect(e,Ie.CLIENT_INITIATED),t.engine=void 0}finally{o()}},this.onPageLeave=async()=>{await this.disconnect()},this.handleRestarting=()=>{for(const e of this.participants.values())this.handleParticipantDisconnected(e.sid,e);this.setAndEmitConnectionState(rr.Reconnecting)&&this.emit(Xt.Reconnecting)},this.handleRestarted=async e=>{h.debug("reconnected to server",{region:e.serverRegion});try{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),t.isMuted||((t instanceof LocalAudioTrack||t instanceof LocalVideoTrack)&&!t.isUserProvided&&(h.debug("restarting existing track",{track:e.trackSid}),await t.restartTrack()),h.debug("publishing new track",{track:e.trackSid}),await this.localParticipant.publishTrack(t,e.options))})))}catch(e){h.error("error trying to re-publish tracks after reconnection",{error:e})}finally{this.setAndEmitConnectionState(rr.Connected),this.emit(Xt.Reconnected)}},this.handleParticipantUpdates=e=>{e.forEach((e=>{if(e.identity===this.localParticipant.identity)return void this.localParticipant.updateInfo(e);const t=this.identityToSid.get(e.identity);t&&t!==e.sid&&this.handleParticipantDisconnected(t,this.participants.get(t));let i=this.participants.get(e.sid);const n=!i;e.state===_e.DISCONNECTED?this.handleParticipantDisconnected(e.sid,i):(i=this.getOrCreateParticipant(e.sid,e),n||i.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.emitWhenConnected(Xt.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.emitWhenConnected(Xt.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(ei.TrackStreamStateChanged,i,i.track.streamState),this.emitWhenConnected(Xt.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.setAllowed(e.allowed)},this.handleDataPacket=(e,t)=>{const i=this.participants.get(e.participantSid);this.emit(Xt.DataReceived,e.payload,i,t,e.topic),null==i||i.emit(ei.DataReceived,e.payload,t)},this.handleAudioPlaybackStarted=()=>{this.canPlaybackAudio||(this.audioEnabled=!0,this.emit(Xt.AudioPlaybackStatusChanged,!0))},this.handleAudioPlaybackFailed=e=>{h.warn("could not playback audio",e),this.canPlaybackAudio&&(this.audioEnabled=!1,this.emit(Xt.AudioPlaybackStatusChanged,!1))},this.handleDeviceChange=async()=>{this.emit(Xt.MediaDevicesChanged)},this.handleRoomUpdate=e=>{this._isRecording!==e.activeRecording&&(this._isRecording=e.activeRecording,this.emit(Xt.RecordingStatusChanged,e.activeRecording)),this.metadata!==e.metadata&&(this.metadata=e.metadata,this.emitWhenConnected(Xt.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.onLocalParticipantMetadataChanged=e=>{this.emit(Xt.ParticipantMetadataChanged,e,this.localParticipant)},this.onLocalTrackMuted=e=>{this.emit(Xt.TrackMuted,e,this.localParticipant)},this.onLocalTrackUnmuted=e=>{this.emit(Xt.TrackUnmuted,e,this.localParticipant)},this.onLocalTrackPublished=async e=>{if(this.emit(Xt.LocalTrackPublished,e,this.localParticipant),e.track instanceof LocalAudioTrack){await e.track.checkForSilence()&&this.emit(Xt.LocalAudioSilenceDetected,e)}},this.onLocalTrackUnpublished=e=>{this.emit(Xt.LocalTrackUnpublished,e,this.localParticipant)},this.onLocalConnectionQualityChanged=e=>{this.emit(Xt.ConnectionQualityChanged,e,this.localParticipant)},this.onMediaDevicesError=e=>{this.emit(Xt.MediaDevicesError,e)},this.onLocalParticipantPermissionsChanged=e=>{this.emit(Xt.ParticipantPermissionsChanged,e,this.localParticipant)},this.setMaxListeners(100),this.participants=new Map,this.identityToSid=new Map,this.options=_objectSpread2(_objectSpread2({},Bi),e),this.options.audioCaptureDefaults=_objectSpread2(_objectSpread2({},xi),null==e?void 0:e.audioCaptureDefaults),this.options.videoCaptureDefaults=_objectSpread2(_objectSpread2({},$i),null==e?void 0:e.videoCaptureDefaults),this.options.publishDefaults=_objectSpread2(_objectSpread2({},Mi),null==e?void 0:e.publishDefaults),this.maybeCreateEngine(),this.disconnectLock=new Mutex,this.localParticipant=new LocalParticipant("","",this.engine,this.options)}maybeCreateEngine(){this.engine||(this.engine=new RTCEngine(this.options),this.engine.client.onParticipantUpdate=this.handleParticipantUpdates,this.engine.client.onRoomUpdate=this.handleRoomUpdate,this.engine.client.onSpeakersChanged=this.handleSpeakersChanged,this.engine.client.onStreamStateUpdate=this.handleStreamStateUpdate,this.engine.client.onSubscriptionPermissionUpdate=this.handleSubscriptionPermissionUpdate,this.engine.client.onConnectionQuality=this.handleConnectionQualityUpdate,this.engine.on(ti.MediaTrackAdded,((e,t,i)=>{this.onTrackAdded(e,t,i)})).on(ti.Disconnected,(e=>{this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e)})).on(ti.ActiveSpeakersUpdate,this.handleActiveSpeakersUpdate).on(ti.DataPacketReceived,this.handleDataPacket).on(ti.Resuming,(()=>{this.setAndEmitConnectionState(rr.Reconnecting)&&this.emit(Xt.Reconnecting)})).on(ti.Resumed,(()=>{this.setAndEmitConnectionState(rr.Connected),this.emit(Xt.Reconnected),this.updateSubscriptions()})).on(ti.SignalResumed,(()=>{this.state===rr.Reconnecting&&this.sendSyncState()})).on(ti.Restarting,this.handleRestarting).on(ti.Restarted,this.handleRestarted),this.localParticipant&&this.localParticipant.setupEngine(this.engine))}static getLocalDevices(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return DeviceManager.getInstance().getDevices(e,t)}async prepareConnection(e){await fetch("http".concat(e.substring(2)),{method:"HEAD"})}getParticipantByIdentity(e){if(this.localParticipant.identity===e)return this.localParticipant;const t=this.identityToSid.get(e);return t?this.participants.get(t):void 0}clearConnectionFutures(){this.connectFuture=void 0}get isRecording(){return this._isRecording}async simulateScenario(e){let t,postAction=()=>{};switch(e){case"signal-reconnect":await this.engine.client.close(),this.engine.client.onClose&&this.engine.client.onClose("simulate disconnect");break;case"speaker":t=Ht.fromPartial({scenario:{$case:"speakerUpdate",speakerUpdate:3}});break;case"node-failure":t=Ht.fromPartial({scenario:{$case:"nodeFailure",nodeFailure:!0}});break;case"server-leave":t=Ht.fromPartial({scenario:{$case:"serverLeave",serverLeave:!0}});break;case"migration":t=Ht.fromPartial({scenario:{$case:"migration",migration:!0}});break;case"resume-reconnect":this.engine.failNext(),await this.engine.client.close(),this.engine.client.onClose&&this.engine.client.onClose("simulate resume-reconnect");break;case"force-tcp":case"force-tls":t=Ht.fromPartial({scenario:{$case:"switchCandidateProtocol",switchCandidateProtocol:"force-tls"===e?2:1}}),postAction=async()=>{const e=this.engine.client.onLeave;e&&e({reason:Ie.CLIENT_INITIATED,canReconnect:!0})}}t&&(this.engine.client.sendSimulateScenario(t),postAction())}async startAudio(){await 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.muted=!1,e.play())))),this.handleAudioPlaybackStarted()}catch(e){throw this.handleAudioPlaybackFailed(e),e}}get canPlaybackAudio(){return this.audioEnabled}getActiveAudioOutputDevice(){var e,t;return null!==(t=null===(e=this.options.audioOutput)||void 0===e?void 0:e.deviceId)&&void 0!==t?t:""}async switchActiveDevice(e,t){var i,n;const s=arguments.length>2&&void 0!==arguments[2]&&arguments[2]?{exact:t}:t;if("audioinput"===e){const e=this.options.audioCaptureDefaults.deviceId;this.options.audioCaptureDefaults.deviceId=s;const t=Array.from(this.localParticipant.audioTracks.values()).filter((e=>e.source===Track.Source.Microphone));try{await Promise.all(t.map((e=>{var t;return null===(t=e.audioTrack)||void 0===t?void 0:t.setDeviceId(s)})))}catch(t){throw this.options.audioCaptureDefaults.deviceId=e,t}}else if("videoinput"===e){const e=this.options.videoCaptureDefaults.deviceId;this.options.videoCaptureDefaults.deviceId=s;const t=Array.from(this.localParticipant.videoTracks.values()).filter((e=>e.source===Track.Source.Camera));try{await Promise.all(t.map((e=>{var t;return null===(t=e.videoTrack)||void 0===t?void 0:t.setDeviceId(s)})))}catch(t){throw this.options.videoCaptureDefaults.deviceId=e,t}}else if("audiooutput"===e){if(!supportsSetSinkId())throw new Error("cannot switch audio output, setSinkId not supported");null!==(i=(n=this.options).audioOutput)&&void 0!==i||(n.audioOutput={});const e=this.options.audioOutput.deviceId;this.options.audioOutput.deviceId=t;try{await Promise.all(Array.from(this.participants.values()).map((e=>e.setAudioOutput({deviceId:t}))))}catch(t){throw this.options.audioOutput.deviceId=e,t}}}setupLocalParticipantEvents(){this.localParticipant.on(ei.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).on(ei.TrackMuted,this.onLocalTrackMuted).on(ei.TrackUnmuted,this.onLocalTrackUnmuted).on(ei.LocalTrackPublished,this.onLocalTrackPublished).on(ei.LocalTrackUnpublished,this.onLocalTrackUnpublished).on(ei.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).on(ei.MediaDevicesError,this.onMediaDevicesError).on(ei.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged)}recreateEngine(){var e;null===(e=this.engine)||void 0===e||e.close(),this.engine=void 0,this.participants.clear(),this.maybeCreateEngine()}onTrackAdded(e,t,i){if(this.state===rr.Connecting||this.state===rr.Reconnecting){const reconnectedHandler=()=>{this.onTrackAdded(e,t,i),cleanup()},cleanup=()=>{this.off(Xt.Reconnected,reconnectedHandler),this.off(Xt.Connected,reconnectedHandler),this.off(Xt.Disconnected,cleanup)};return this.once(Xt.Reconnected,reconnectedHandler),this.once(Xt.Connected,reconnectedHandler),void this.once(Xt.Disconnected,cleanup)}if(this.state===rr.Disconnected)return void h.warn("skipping incoming track after Room disconnected");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];if(a&&""!==a||(a=e.id),s===this.localParticipant.sid)return void h.warn("tried to create RemoteParticipant for local participant");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],t=arguments.length>1?arguments[1]:void 0;var i;this.state!==rr.Disconnected&&(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),e&&(null===(i=t.track)||void 0===i||i.detach(),null===(n=t.track)||void 0===n||n.stop())})),this.localParticipant.off(ei.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).off(ei.TrackMuted,this.onLocalTrackMuted).off(ei.TrackUnmuted,this.onLocalTrackUnmuted).off(ei.LocalTrackPublished,this.onLocalTrackPublished).off(ei.LocalTrackUnpublished,this.onLocalTrackUnpublished).off(ei.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).off(ei.MediaDevicesError,this.onMediaDevicesError).off(ei.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged),this.localParticipant.tracks.clear(),this.localParticipant.videoTracks.clear(),this.localParticipant.audioTracks.clear(),this.participants.clear(),this.activeSpeakers=[],this.audioContext&&"boolean"==typeof this.options.expWebAudioMix&&(this.audioContext.close(),this.audioContext=void 0),isWeb()&&(window.removeEventListener("beforeunload",this.onPageLeave),window.removeEventListener("pagehide",this.onPageLeave),null===(i=navigator.mediaDevices)||void 0===i||i.removeEventListener("devicechange",this.handleDeviceChange)),this.setAndEmitConnectionState(rr.Disconnected),this.emit(Xt.Disconnected,t))}handleParticipantDisconnected(e,t){this.participants.delete(e),t&&(this.identityToSid.delete(t.identity),t.tracks.forEach((e=>{t.unpublishTrack(e.trackSid,!0)})),this.emit(Xt.ParticipantDisconnected,t))}async acquireAudioContext(){var e,t;"boolean"!=typeof this.options.expWebAudioMix&&this.options.expWebAudioMix.audioContext?(this.audioContext=this.options.expWebAudioMix.audioContext,await this.audioContext.resume()):this.audioContext=null!==(e=getNewAudioContext())&&void 0!==e?e:void 0,this.options.expWebAudioMix&&this.participants.forEach((e=>e.setAudioContext(this.audioContext)));const i="running"===(null===(t=this.audioContext)||void 0===t?void 0:t.state);i!==this.canPlaybackAudio&&(this.audioEnabled=i,this.emit(Xt.AudioPlaybackStatusChanged,i))}createParticipant(e,t){let i;return i=t?RemoteParticipant.fromParticipantInfo(this.engine.client,t):new RemoteParticipant(this.engine.client,e,"",void 0,void 0),this.options.expWebAudioMix&&i.setAudioContext(this.audioContext),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),t&&(this.identityToSid.set(t.identity,t.sid),this.emitWhenConnected(Xt.ParticipantConnected,i)),i.on(ei.TrackPublished,(e=>{this.emitWhenConnected(Xt.TrackPublished,e,i)})).on(ei.TrackSubscribed,((e,t)=>{e.kind===Track.Kind.Audio&&(e.on(ii.AudioPlaybackStarted,this.handleAudioPlaybackStarted),e.on(ii.AudioPlaybackFailed,this.handleAudioPlaybackFailed)),this.emit(Xt.TrackSubscribed,e,t,i)})).on(ei.TrackUnpublished,(e=>{this.emit(Xt.TrackUnpublished,e,i)})).on(ei.TrackUnsubscribed,((e,t)=>{this.emit(Xt.TrackUnsubscribed,e,t,i)})).on(ei.TrackSubscriptionFailed,(e=>{this.emit(Xt.TrackSubscriptionFailed,e,i)})).on(ei.TrackMuted,(e=>{this.emitWhenConnected(Xt.TrackMuted,e,i)})).on(ei.TrackUnmuted,(e=>{this.emitWhenConnected(Xt.TrackUnmuted,e,i)})).on(ei.ParticipantMetadataChanged,(e=>{this.emitWhenConnected(Xt.ParticipantMetadataChanged,e,i)})).on(ei.ConnectionQualityChanged,(e=>{this.emitWhenConnected(Xt.ConnectionQualityChanged,e,i)})).on(ei.ParticipantPermissionsChanged,(e=>{this.emitWhenConnected(Xt.ParticipantPermissionsChanged,e,i)})).on(ei.TrackSubscriptionStatusChanged,((e,t)=>{this.emitWhenConnected(Xt.TrackSubscriptionStatusChanged,e,t,i)})).on(ei.TrackSubscriptionPermissionChanged,((e,t)=>{this.emitWhenConnected(Xt.TrackSubscriptionPermissionChanged,e,t,i)})),t&&i.updateInfo(t),i}sendSyncState(){var e,t;if(void 0===this.engine.subscriber||null===this.engine.subscriber.pc.localDescription)return;const i=this.engine.subscriber.pc.localDescription,n=this.engine.subscriber.pc.remoteDescription,s=null===(t=null===(e=this.connOptions)||void 0===e?void 0:e.autoSubscribe)||void 0===t||t,a=new Array;this.participants.forEach((e=>{e.tracks.forEach((e=>{e.isDesired!==s&&a.push(e.trackSid)}))})),this.engine.client.sendSyncState({answer:toProtoSessionDescription({sdp:i.sdp,type:i.type}),offer:n?toProtoSessionDescription({sdp:n.sdp,type:n.type}):void 0,subscription:{trackSids:a,subscribe:!s,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){return e!==this.state&&(this.state=e,this.emit(Xt.ConnectionStateChanged,this.state),!0)}emitWhenConnected(e){if(this.state===rr.Connected){for(var t=arguments.length,i=new Array(t>1?t-1:0),n=1;n1?t-1:0),n=1;nDeviceManager.userMediaPromiseMap.delete("audioinput")))),e.video&&(DeviceManager.userMediaPromiseMap.set("videoinput",s),s.catch((()=>DeviceManager.userMediaPromiseMap.delete("videoinput"))));const a=await s;return a.getTracks().map((t=>{const i="audio"===t.kind;let s;i?e.audio:e.video;const o=i?n.audio:n.video;"boolean"!=typeof o&&(s=o);const c=mediaTrackToLocalTrack(t,s);return c.kind===Track.Kind.Video?c.source=Track.Source.Camera:c.kind===Track.Kind.Audio&&(c.source=Track.Source.Microphone),c.mediaStream=a,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=Pi.h1080.resolution);let i=!0;if(e.resolution&&(i={width:e.resolution.width,height:e.resolution.height}),void 0===navigator.mediaDevices.getDisplayMedia)throw new DeviceUnsupportedError("getDisplayMedia not supported");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],void 0,!1);a.source=Track.Source.ScreenShare;const o=[a];if(n.getAudioTracks().length>0){const e=new LocalAudioTrack(n.getAudioTracks()[0],void 0,!1);e.source=Track.Source.ScreenShareAudio,o.push(e)}return o}var sr;!function(e){e[e.IDLE=0]="IDLE",e[e.RUNNING=1]="RUNNING",e[e.SKIPPED=2]="SKIPPED",e[e.SUCCESS=3]="SUCCESS",e[e.FAILED=4]="FAILED"}(sr||(sr={}));class Checker extends vi.EventEmitter{constructor(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};super(),this.status=sr.IDLE,this.logs=[],this.errorsAsWarnings=!1,this.url=e,this.token=t,this.name=this.constructor.name,this.room=new Room(i.roomOptions),this.connectOptions=i.connectOptions,i.errorsAsWarnings&&(this.errorsAsWarnings=i.errorsAsWarnings)}async run(e){if(this.status!==sr.IDLE)throw Error("check is running already");this.setStatus(sr.RUNNING),this.appendMessage("".concat(this.name," started."));try{await this.perform()}catch(e){e instanceof Error&&(this.errorsAsWarnings?this.appendWarning(e.message):this.appendError(e.message))}return await this.disconnect(),await new Promise((e=>setTimeout(e,500))),this.status!==sr.SKIPPED&&this.setStatus(this.isSuccess()?sr.SUCCESS:sr.FAILED),e&&e(),this.getInfo()}isSuccess(){return!this.logs.some((e=>"error"===e.level))}async connect(){return this.room.state===rr.Connected||await this.room.connect(this.url,this.token),this.room}async disconnect(){this.room&&this.room.state!==rr.Disconnected&&(await this.room.disconnect(),await new Promise((e=>setTimeout(e,500))))}skip(){this.setStatus(sr.SKIPPED)}appendMessage(e){this.logs.push({level:"info",message:e}),this.emit("update",this.getInfo())}appendWarning(e){this.logs.push({level:"warning",message:e}),this.emit("update",this.getInfo())}appendError(e){this.logs.push({level:"error",message:e}),this.emit("update",this.getInfo())}setStatus(e){this.status=e,this.emit("update",this.getInfo())}get engine(){var e;return null===(e=this.room)||void 0===e?void 0:e.engine}getInfo(){return{logs:this.logs,name:this.name,status:this.status,description:this.description}}}class PublishAudioCheck extends Checker{get description(){return"Can publish audio"}async perform(){var e;const t=await this.connect(),i=await createLocalAudioTrack();t.localParticipant.publishTrack(i),await new Promise((e=>setTimeout(e,3e3)));const n=await(null===(e=i.sender)||void 0===e?void 0:e.getStats());if(!n)throw new Error("Could not get RTCStats");let s=0;if(n.forEach((e=>{"outbound-rtp"===e.type&&"audio"===e.mediaType&&(s=e.packetsSent)})),0===s)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(s," audio packets"))}}class PublishVideoCheck extends Checker{get description(){return"Can publish video"}async perform(){var e;const t=await this.connect(),i=await createLocalVideoTrack();t.localParticipant.publishTrack(i),await new Promise((e=>setTimeout(e,3e3)));const n=await(null===(e=i.sender)||void 0===e?void 0:e.getStats());if(!n)throw new Error("Could not get RTCStats");let s=0;if(n.forEach((e=>{"outbound-rtp"===e.type&&"video"===e.mediaType&&(s=e.packetsSent)})),0===s)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(s," video packets"))}}class ReconnectCheck extends Checker{get description(){return"Resuming connection after interruption"}async perform(){var e;const t=await this.connect();let i,n=!1,s=!1;const a=new Promise((e=>{setTimeout(e,5e3),i=e}));t.on(Xt.Reconnecting,(()=>{n=!0})).on(Xt.Reconnected,(()=>{s=!0,i(!0)})),null===(e=t.engine.client.ws)||void 0===e||e.close();const o=t.engine.client.onClose;if(o&&o(""),await a,!n)throw new Error("Did not attempt to reconnect");if(!s||t.state!==rr.Connected)throw this.appendWarning("reconnection is only possible in Redis-based configurations"),new Error("Not able to reconnect")}}class TURNCheck extends Checker{get description(){return"Can connect via TURN"}async perform(){var e,t;const i=new SignalClient,n=await i.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0});let s=!1,a=!1,o=!1;for(let e of n.iceServers)for(let t of e.urls)t.startsWith("turn:")?(a=!0,o=!0):t.startsWith("turns:")&&(a=!0,o=!0,s=!0),t.startsWith("stun:")&&(o=!0);o?a&&!s&&this.appendWarning("TURN is configured server side, but TURN/TLS is unavailable."):this.appendWarning("No STUN servers configured on server side."),await i.close(),(null===(t=null===(e=this.connectOptions)||void 0===e?void 0:e.rtcConfig)||void 0===t?void 0:t.iceServers)||a?await this.room.connect(this.url,this.token,{rtcConfig:{iceTransportPolicy:"relay"}}):(this.appendWarning("No TURN servers configured."),this.skip(),await new Promise((e=>setTimeout(e,0))))}}class WebRTCCheck extends Checker{get description(){return"Establishing WebRTC connection"}async perform(){try{console.log("initiating room connection"),this.room=await this.connect(),console.log("now the room is connected")}catch(e){throw this.appendWarning("ports need to be open on firewall in order to connect."),e}}}class WebSocketCheck extends Checker{get description(){return"Connecting to signal connection via WebSocket"}async perform(){(this.url.startsWith("ws:")||this.url.startsWith("http:"))&&this.appendWarning("Server is insecure, clients may block connections to it");let e=new SignalClient;const t=await e.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0});this.appendMessage("Connected to server, version ".concat(t.serverVersion,".")),await e.close()}}class ConnectionCheck extends vi{constructor(e,t){super(),this.checkResults=new Map,this.url=e,this.token=t}getNextCheckId(){const e=this.checkResults.size;return this.checkResults.set(e,{logs:[],status:sr.IDLE,name:"",description:""}),e}updateCheck(e,t){this.checkResults.set(e,t),this.emit("checkUpdate",e,t)}isSuccess(){return Array.from(this.checkResults.values()).every((e=>e.status!==sr.FAILED))}getResults(){return Array.from(this.checkResults.values())}async createAndRunCheck(e){const t=this.getNextCheckId(),i=new e(this.url,this.token),handleUpdate=e=>{this.updateCheck(t,e)};i.on("update",handleUpdate);const n=await i.run();return i.off("update",handleUpdate),n}async checkWebsocket(){return this.createAndRunCheck(WebSocketCheck)}async checkWebRTC(){return this.createAndRunCheck(WebRTCCheck)}async checkTURN(){return this.createAndRunCheck(TURNCheck)}async checkReconnect(){return this.createAndRunCheck(ReconnectCheck)}async checkPublishAudio(){return this.createAndRunCheck(PublishAudioCheck)}async checkPublishVideo(){return this.createAndRunCheck(PublishVideoCheck)}}n=__webpack_require__.O(n),window.livekit=n})(); \ No newline at end of file