livekit-client 2.0.6 → 2.0.8
Sign up to get free protection for your applications and to get access to all the features.
- package/dist/livekit-client.e2ee.worker.js +1 -1
- package/dist/livekit-client.e2ee.worker.js.map +1 -1
- package/dist/livekit-client.e2ee.worker.mjs +27 -3
- package/dist/livekit-client.e2ee.worker.mjs.map +1 -1
- package/dist/livekit-client.esm.mjs +74 -35
- package/dist/livekit-client.esm.mjs.map +1 -1
- package/dist/livekit-client.umd.js +1 -1
- package/dist/livekit-client.umd.js.map +1 -1
- package/dist/src/e2ee/worker/FrameCryptor.d.ts.map +1 -1
- package/dist/src/index.d.ts +7 -6
- package/dist/src/index.d.ts.map +1 -1
- package/dist/src/room/PCTransport.d.ts.map +1 -1
- package/dist/src/room/Room.d.ts.map +1 -1
- package/dist/src/room/participant/LocalParticipant.d.ts.map +1 -1
- package/dist/src/room/participant/publishUtils.d.ts.map +1 -1
- package/dist/src/room/track/LocalTrack.d.ts.map +1 -1
- package/dist/src/room/track/RemoteAudioTrack.d.ts.map +1 -1
- package/dist/src/room/track/options.d.ts +6 -0
- package/dist/src/room/track/options.d.ts.map +1 -1
- package/dist/src/room/track/utils.d.ts.map +1 -1
- package/dist/ts4.2/src/index.d.ts +7 -6
- package/dist/ts4.2/src/room/track/options.d.ts +6 -0
- package/package.json +1 -1
- package/src/e2ee/worker/FrameCryptor.ts +12 -0
- package/src/e2ee/worker/e2ee.worker.ts +24 -3
- package/src/index.ts +32 -29
- package/src/room/PCTransport.ts +6 -18
- package/src/room/Room.ts +1 -0
- package/src/room/participant/LocalParticipant.ts +31 -3
- package/src/room/participant/publishUtils.ts +38 -11
- package/src/room/track/LocalTrack.ts +11 -9
- package/src/room/track/RemoteAudioTrack.ts +1 -1
- package/src/room/track/options.ts +7 -0
- package/src/room/track/utils.ts +1 -0
@@ -1,2 +1,2 @@
|
|
1
|
-
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).LivekitClient={})}(this,(function(e){"use strict";function t(e,t){return t.forEach((function(t){t&&"string"!=typeof t&&!Array.isArray(t)&&Object.keys(t).forEach((function(n){if("default"!==n&&!(n in e)){var i=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(e,n,i.get?i:{enumerable:!0,get:function(){return t[n]}})}}))})),Object.freeze(e)}function n(e,t){if(!e)throw new Error(t)}const i=34028234663852886e22,s=-34028234663852886e22,o=4294967295,a=2147483647,r=-2147483648;function c(e){if("number"!=typeof e)throw new Error("invalid int 32: "+typeof e);if(!Number.isInteger(e)||e>a||e<r)throw new Error("invalid int 32: "+e)}function d(e){if("number"!=typeof e)throw new Error("invalid uint 32: "+typeof e);if(!Number.isInteger(e)||e>o||e<0)throw new Error("invalid uint 32: "+e)}function l(e){if("number"!=typeof e)throw new Error("invalid float 32: "+typeof e);if(Number.isFinite(e)&&(e>i||e<s))throw new Error("invalid float 32: "+e)}const u=Symbol("@bufbuild/protobuf/enum-type");function h(e){const t=e[u];return n(t,"missing enum type on enum object"),t}function m(e,t,n,i){e[u]=p(t,n.map((t=>({no:t.no,name:t.name,localName:e[t.no]}))))}function p(e,t,n){const i=Object.create(null),s=Object.create(null),o=[];for(const e of t){const t=f(e);o.push(t),i[e.name]=t,s[e.no]=t}return{typeName:e,values:o,findName:e=>i[e],findNumber:e=>s[e]}}function g(e,t,n){const i={};for(const e of t){const t=f(e);i[t.localName]=t.no,i[t.no]=t.localName}return m(i,e,t),i}function f(e){return"localName"in e?e:Object.assign(Object.assign({},e),{localName:e.name})}class v{equals(e){return this.getType().runtime.util.equals(this.getType(),this,e)}clone(){return this.getType().runtime.util.clone(this)}fromBinary(e,t){const n=this.getType().runtime.bin,i=n.makeReadOptions(t);return n.readMessage(this,i.readerFactory(e),e.byteLength,i),this}fromJson(e,t){const n=this.getType(),i=n.runtime.json,s=i.makeReadOptions(t);return i.readMessage(n,e,s,this),this}fromJsonString(e,t){let n;try{n=JSON.parse(e)}catch(e){throw new Error("cannot decode ".concat(this.getType().typeName," from JSON: ").concat(e instanceof Error?e.message:String(e)))}return this.fromJson(n,t)}toBinary(e){const t=this.getType().runtime.bin,n=t.makeWriteOptions(e),i=n.writerFactory();return t.writeMessage(this,i,n),i.finish()}toJson(e){const t=this.getType().runtime.json,n=t.makeWriteOptions(e);return t.writeMessage(this,n)}toJsonString(e){var t;const n=this.toJson(e);return JSON.stringify(n,null,null!==(t=null==e?void 0:e.prettySpaces)&&void 0!==t?t:0)}toJSON(){return this.toJson({emitDefaultValues:!0})}getType(){return Object.getPrototypeOf(this).constructor}}var k,T;function y(){let e=0,t=0;for(let n=0;n<28;n+=7){let i=this.buf[this.pos++];if(e|=(127&i)<<n,0==(128&i))return this.assertBounds(),[e,t]}let n=this.buf[this.pos++];if(e|=(15&n)<<28,t=(112&n)>>4,0==(128&n))return this.assertBounds(),[e,t];for(let n=3;n<=31;n+=7){let i=this.buf[this.pos++];if(t|=(127&i)<<n,0==(128&i))return this.assertBounds(),[e,t]}throw new Error("invalid varint")}function b(e,t,n){for(let i=0;i<28;i+=7){const s=e>>>i,o=!(s>>>7==0&&0==t),a=255&(o?128|s:s);if(n.push(a),!o)return}const i=e>>>28&15|(7&t)<<4,s=!(t>>3==0);if(n.push(255&(s?128|i:i)),s){for(let e=3;e<31;e+=7){const i=t>>>e,s=!(i>>>7==0),o=255&(s?128|i:i);if(n.push(o),!s)return}n.push(t>>>31&1)}}!function(e){e[e.DOUBLE=1]="DOUBLE",e[e.FLOAT=2]="FLOAT",e[e.INT64=3]="INT64",e[e.UINT64=4]="UINT64",e[e.INT32=5]="INT32",e[e.FIXED64=6]="FIXED64",e[e.FIXED32=7]="FIXED32",e[e.BOOL=8]="BOOL",e[e.STRING=9]="STRING",e[e.BYTES=12]="BYTES",e[e.UINT32=13]="UINT32",e[e.SFIXED32=15]="SFIXED32",e[e.SFIXED64=16]="SFIXED64",e[e.SINT32=17]="SINT32",e[e.SINT64=18]="SINT64"}(k||(k={})),function(e){e[e.BIGINT=0]="BIGINT",e[e.STRING=1]="STRING"}(T||(T={}));const C=4294967296;function S(e){const t="-"===e[0];t&&(e=e.slice(1));const n=1e6;let i=0,s=0;function o(t,o){const a=Number(e.slice(t,o));s*=n,i=i*n+a,i>=C&&(s+=i/C|0,i%=C)}return o(-24,-18),o(-18,-12),o(-12,-6),o(-6),t?P(i,s):w(i,s)}function E(e,t){if(({lo:e,hi:t}=function(e,t){return{lo:e>>>0,hi:t>>>0}}(e,t)),t<=2097151)return String(C*t+e);const n=16777215&(e>>>24|t<<8),i=t>>16&65535;let s=(16777215&e)+6777216*n+6710656*i,o=n+8147497*i,a=2*i;const r=1e7;return s>=r&&(o+=Math.floor(s/r),s%=r),o>=r&&(a+=Math.floor(o/r),o%=r),a.toString()+R(o)+R(s)}function w(e,t){return{lo:0|e,hi:0|t}}function P(e,t){return t=~t,e?e=1+~e:t+=1,w(e,t)}const R=e=>{const t=String(e);return"0000000".slice(t.length)+t};function _(e,t){if(e>=0){for(;e>127;)t.push(127&e|128),e>>>=7;t.push(e)}else{for(let n=0;n<9;n++)t.push(127&e|128),e>>=7;t.push(1)}}function I(){let e=this.buf[this.pos++],t=127&e;if(0==(128&e))return this.assertBounds(),t;if(e=this.buf[this.pos++],t|=(127&e)<<7,0==(128&e))return this.assertBounds(),t;if(e=this.buf[this.pos++],t|=(127&e)<<14,0==(128&e))return this.assertBounds(),t;if(e=this.buf[this.pos++],t|=(127&e)<<21,0==(128&e))return this.assertBounds(),t;e=this.buf[this.pos++],t|=(15&e)<<28;for(let t=5;0!=(128&e)&&t<10;t++)e=this.buf[this.pos++];if(0!=(128&e))throw new Error("invalid varint");return this.assertBounds(),t>>>0}const O=function(){const e=new DataView(new ArrayBuffer(8));if("function"==typeof BigInt&&"function"==typeof e.getBigInt64&&"function"==typeof e.getBigUint64&&"function"==typeof e.setBigInt64&&"function"==typeof e.setBigUint64&&("object"!=typeof process||"object"!=typeof process.env||"1"!==process.env.BUF_BIGINT_DISABLE)){const t=BigInt("-9223372036854775808"),n=BigInt("9223372036854775807"),i=BigInt("0"),s=BigInt("18446744073709551615");return{zero:BigInt(0),supported:!0,parse(e){const i="bigint"==typeof e?e:BigInt(e);if(i>n||i<t)throw new Error("int64 invalid: ".concat(e));return i},uParse(e){const t="bigint"==typeof e?e:BigInt(e);if(t>s||t<i)throw new Error("uint64 invalid: ".concat(e));return t},enc(t){return e.setBigInt64(0,this.parse(t),!0),{lo:e.getInt32(0,!0),hi:e.getInt32(4,!0)}},uEnc(t){return e.setBigInt64(0,this.uParse(t),!0),{lo:e.getInt32(0,!0),hi:e.getInt32(4,!0)}},dec:(t,n)=>(e.setInt32(0,t,!0),e.setInt32(4,n,!0),e.getBigInt64(0,!0)),uDec:(t,n)=>(e.setInt32(0,t,!0),e.setInt32(4,n,!0),e.getBigUint64(0,!0))}}const t=e=>n(/^-?[0-9]+$/.test(e),"int64 invalid: ".concat(e)),i=e=>n(/^[0-9]+$/.test(e),"uint64 invalid: ".concat(e));return{zero:"0",supported:!1,parse:e=>("string"!=typeof e&&(e=e.toString()),t(e),e),uParse:e=>("string"!=typeof e&&(e=e.toString()),i(e),e),enc:e=>("string"!=typeof e&&(e=e.toString()),t(e),S(e)),uEnc:e=>("string"!=typeof e&&(e=e.toString()),i(e),S(e)),dec:(e,t)=>function(e,t){let n=w(e,t);const i=2147483648&n.hi;i&&(n=P(n.lo,n.hi));const s=E(n.lo,n.hi);return i?"-"+s:s}(e,t),uDec:(e,t)=>E(e,t)}}();var M;!function(e){e[e.Varint=0]="Varint",e[e.Bit64=1]="Bit64",e[e.LengthDelimited=2]="LengthDelimited",e[e.StartGroup=3]="StartGroup",e[e.EndGroup=4]="EndGroup",e[e.Bit32=5]="Bit32"}(M||(M={}));class x{constructor(e){this.stack=[],this.textEncoder=null!=e?e:new TextEncoder,this.chunks=[],this.buf=[]}finish(){this.chunks.push(new Uint8Array(this.buf));let e=0;for(let t=0;t<this.chunks.length;t++)e+=this.chunks[t].length;let t=new Uint8Array(e),n=0;for(let e=0;e<this.chunks.length;e++)t.set(this.chunks[e],n),n+=this.chunks[e].length;return this.chunks=[],t}fork(){return this.stack.push({chunks:this.chunks,buf:this.buf}),this.chunks=[],this.buf=[],this}join(){let e=this.finish(),t=this.stack.pop();if(!t)throw new Error("invalid state, fork stack empty");return this.chunks=t.chunks,this.buf=t.buf,this.uint32(e.byteLength),this.raw(e)}tag(e,t){return this.uint32((e<<3|t)>>>0)}raw(e){return this.buf.length&&(this.chunks.push(new Uint8Array(this.buf)),this.buf=[]),this.chunks.push(e),this}uint32(e){for(d(e);e>127;)this.buf.push(127&e|128),e>>>=7;return this.buf.push(e),this}int32(e){return c(e),_(e,this.buf),this}bool(e){return this.buf.push(e?1:0),this}bytes(e){return this.uint32(e.byteLength),this.raw(e)}string(e){let t=this.textEncoder.encode(e);return this.uint32(t.byteLength),this.raw(t)}float(e){l(e);let t=new Uint8Array(4);return new DataView(t.buffer).setFloat32(0,e,!0),this.raw(t)}double(e){let t=new Uint8Array(8);return new DataView(t.buffer).setFloat64(0,e,!0),this.raw(t)}fixed32(e){d(e);let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!0),this.raw(t)}sfixed32(e){c(e);let t=new Uint8Array(4);return new DataView(t.buffer).setInt32(0,e,!0),this.raw(t)}sint32(e){return c(e),_(e=(e<<1^e>>31)>>>0,this.buf),this}sfixed64(e){let t=new Uint8Array(8),n=new DataView(t.buffer),i=O.enc(e);return n.setInt32(0,i.lo,!0),n.setInt32(4,i.hi,!0),this.raw(t)}fixed64(e){let t=new Uint8Array(8),n=new DataView(t.buffer),i=O.uEnc(e);return n.setInt32(0,i.lo,!0),n.setInt32(4,i.hi,!0),this.raw(t)}int64(e){let t=O.enc(e);return b(t.lo,t.hi,this.buf),this}sint64(e){let t=O.enc(e),n=t.hi>>31;return b(t.lo<<1^n,(t.hi<<1|t.lo>>>31)^n,this.buf),this}uint64(e){let t=O.uEnc(e);return b(t.lo,t.hi,this.buf),this}}class D{constructor(e,t){this.varint64=y,this.uint32=I,this.buf=e,this.len=e.length,this.pos=0,this.view=new DataView(e.buffer,e.byteOffset,e.byteLength),this.textDecoder=null!=t?t:new TextDecoder}tag(){let e=this.uint32(),t=e>>>3,n=7&e;if(t<=0||n<0||n>5)throw new Error("illegal tag: field no "+t+" wire type "+n);return[t,n]}skip(e){let t=this.pos;switch(e){case M.Varint:for(;128&this.buf[this.pos++];);break;case M.Bit64:this.pos+=4;case M.Bit32:this.pos+=4;break;case M.LengthDelimited:let t=this.uint32();this.pos+=t;break;case M.StartGroup:let n;for(;(n=this.tag()[1])!==M.EndGroup;)this.skip(n);break;default:throw new Error("cant skip wire type "+e)}return this.assertBounds(),this.buf.subarray(t,this.pos)}assertBounds(){if(this.pos>this.len)throw new RangeError("premature EOF")}int32(){return 0|this.uint32()}sint32(){let e=this.uint32();return e>>>1^-(1&e)}int64(){return O.dec(...this.varint64())}uint64(){return O.uDec(...this.varint64())}sint64(){let[e,t]=this.varint64(),n=-(1&e);return e=(e>>>1|(1&t)<<31)^n,t=t>>>1^n,O.dec(e,t)}bool(){let[e,t]=this.varint64();return 0!==e||0!==t}fixed32(){return this.view.getUint32((this.pos+=4)-4,!0)}sfixed32(){return this.view.getInt32((this.pos+=4)-4,!0)}fixed64(){return O.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return O.dec(this.sfixed32(),this.sfixed32())}float(){return this.view.getFloat32((this.pos+=4)-4,!0)}double(){return this.view.getFloat64((this.pos+=8)-8,!0)}bytes(){let e=this.uint32(),t=this.pos;return this.pos+=e,this.assertBounds(),this.buf.subarray(t,t+e)}string(){return this.textDecoder.decode(this.bytes())}}function N(e,t,n){if(t===n)return!0;if(e==k.BYTES){if(!(t instanceof Uint8Array&&n instanceof Uint8Array))return!1;if(t.length!==n.length)return!1;for(let e=0;e<t.length;e++)if(t[e]!==n[e])return!1;return!0}switch(e){case k.UINT64:case k.FIXED64:case k.INT64:case k.SFIXED64:case k.SINT64:return t==n}return!1}function L(e,t){switch(e){case k.BOOL:return!1;case k.UINT64:case k.FIXED64:case k.INT64:case k.SFIXED64:case k.SINT64:return 0==t?O.zero:"0";case k.DOUBLE:case k.FLOAT:return 0;case k.BYTES:return new Uint8Array(0);case k.STRING:return"";default:return 0}}function A(e,t){const n=void 0===t;let i=M.Varint,s=0===t;switch(e){case k.STRING:s=n||!t.length,i=M.LengthDelimited;break;case k.BOOL:s=!1===t;break;case k.DOUBLE:i=M.Bit64;break;case k.FLOAT:i=M.Bit32;break;case k.INT64:case k.UINT64:s=n||0==t;break;case k.FIXED64:s=n||0==t,i=M.Bit64;break;case k.BYTES:s=n||!t.byteLength,i=M.LengthDelimited;break;case k.FIXED32:case k.SFIXED32:i=M.Bit32;break;case k.SFIXED64:s=n||0==t,i=M.Bit64;break;case k.SINT64:s=n||0==t}return[i,k[e].toLowerCase(),n||s]}function U(e){const t=e.field.localName,n=Object.create(null);return n[t]=function(e){const t=e.field;if(t.repeated)return[];if(void 0!==t.default)return t.default;switch(t.kind){case"enum":return t.T.values[0].no;case"scalar":return L(t.T,t.L);case"message":const e=t.T,n=new e;return e.fieldWrapper?e.fieldWrapper.unwrapField(n):n;case"map":throw"map fields are not allowed to be extensions"}}(e),[n,()=>n[t]]}function j(e,t){return t instanceof v||!e.fieldWrapper?t:e.fieldWrapper.wrapField(t)}k.DOUBLE,k.FLOAT,k.INT64,k.UINT64,k.INT32,k.UINT32,k.BOOL,k.STRING,k.BYTES;const F=Symbol("@bufbuild/protobuf/unknown-fields"),B={readUnknownFields:!0,readerFactory:e=>new D(e)},V={writeUnknownFields:!0,writerFactory:()=>new x};function q(e){return e?Object.assign(Object.assign({},B),e):B}function K(e){return e?Object.assign(Object.assign({},V),e):V}function G(e,t,n,i,s){let{repeated:o,localName:a}=n;switch(n.oneof&&((e=e[n.oneof.localName]).case!=a&&delete e.value,e.case=a,a="value"),n.kind){case"scalar":case"enum":const r="enum"==n.kind?k.INT32:n.T;let c=J;if("scalar"==n.kind&&n.L>0&&(c=H),o){let n=e[a];if(i==M.LengthDelimited&&r!=k.STRING&&r!=k.BYTES){let e=t.uint32()+t.pos;for(;t.pos<e;)n.push(c(t,r))}else n.push(c(t,r))}else e[a]=c(t,r);break;case"message":const d=n.T;o?e[a].push(W(t,new d,s,n)):e[a]instanceof v?W(t,e[a],s,n):(e[a]=W(t,new d,s,n),!d.fieldWrapper||n.oneof||n.repeated||(e[a]=d.fieldWrapper.unwrapField(e[a])));break;case"map":let[l,u]=function(e,t,n){const i=t.uint32(),s=t.pos+i;let o,a;for(;t.pos<s;){let[i]=t.tag();switch(i){case 1:o=J(t,e.K);break;case 2:switch(e.V.kind){case"scalar":a=J(t,e.V.T);break;case"enum":a=t.int32();break;case"message":a=W(t,new e.V.T,n,void 0)}}}if(void 0===o){let t=L(e.K,T.BIGINT);o=e.K==k.BOOL?t.toString():t}"string"!=typeof o&&"number"!=typeof o&&(o=o.toString());if(void 0===a)switch(e.V.kind){case"scalar":a=L(e.V.T,T.BIGINT);break;case"enum":a=0;break;case"message":a=new e.V.T}return[o,a]}(n,t,s);e[a][l]=u}}function W(e,t,n,i){const s=t.getType().runtime.bin,o=null==i?void 0:i.delimited;return s.readMessage(t,e,o?null==i?void 0:i.no:e.uint32(),n,o),t}function H(e,t){const n=J(e,t);return"bigint"==typeof n?n.toString():n}function J(e,t){switch(t){case k.STRING:return e.string();case k.BOOL:return e.bool();case k.DOUBLE:return e.double();case k.FLOAT:return e.float();case k.INT32:return e.int32();case k.INT64:return e.int64();case k.UINT64:return e.uint64();case k.FIXED64:return e.fixed64();case k.BYTES:return e.bytes();case k.FIXED32:return e.fixed32();case k.SFIXED32:return e.sfixed32();case k.SFIXED64:return e.sfixed64();case k.SINT64:return e.sint64();case k.UINT32:return e.uint32();case k.SINT32:return e.sint32()}}function z(e,t,i,s,o){e.tag(i.no,M.LengthDelimited),e.fork();let a=s;switch(i.K){case k.INT32:case k.FIXED32:case k.UINT32:case k.SFIXED32:case k.SINT32:a=Number.parseInt(s);break;case k.BOOL:n("true"==s||"false"==s),a="true"==s}switch(Y(e,i.K,1,a,!0),i.V.kind){case"scalar":Y(e,i.V.T,2,o,!0);break;case"enum":Y(e,k.INT32,2,o,!0);break;case"message":e.tag(2,M.LengthDelimited).bytes(o.toBinary(t))}e.join()}function Q(e,t,n,i){const s=j(n.T,i);(null==n?void 0:n.delimited)?e.tag(n.no,M.StartGroup).raw(s.toBinary(t)).tag(n.no,M.EndGroup):e.tag(n.no,M.LengthDelimited).bytes(s.toBinary(t))}function Y(e,t,n,i,s){let[o,a,r]=A(t,i);r&&!s||e.tag(n,o)[a](i)}function X(e,t,n,i){const s=e.repeated;switch(e.kind){case"scalar":case"enum":let o="enum"==e.kind?k.INT32:e.T;if(s)if(e.packed)!function(e,t,n,i){if(!i.length)return;e.tag(n,M.LengthDelimited).fork();let[,s]=A(t);for(let t=0;t<i.length;t++)e[s](i[t]);e.join()}(n,o,e.no,t);else for(const i of t)Y(n,o,e.no,i,!0);else void 0!==t&&Y(n,o,e.no,t,!!e.oneof||e.opt);break;case"message":if(s)for(const s of t)Q(n,i,e,s);else void 0!==t&&Q(n,i,e,t);break;case"map":for(const[s,o]of Object.entries(t))z(n,i,e,s,o)}}let Z="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),$=[];for(let e=0;e<Z.length;e++)$[Z[e].charCodeAt(0)]=e;$["-".charCodeAt(0)]=Z.indexOf("+"),$["_".charCodeAt(0)]=Z.indexOf("/");const ee={dec(e){let t=3*e.length/4;"="==e[e.length-2]?t-=2:"="==e[e.length-1]&&(t-=1);let n,i=new Uint8Array(t),s=0,o=0,a=0;for(let t=0;t<e.length;t++){if(n=$[e.charCodeAt(t)],void 0===n)switch(e[t]){case"=":o=0;case"\n":case"\r":case"\t":case" ":continue;default:throw Error("invalid base64 string.")}switch(o){case 0:a=n,o=1;break;case 1:i[s++]=a<<2|(48&n)>>4,a=n,o=2;break;case 2:i[s++]=(15&a)<<4|(60&n)>>2,a=n,o=3;break;case 3:i[s++]=(3&a)<<6|n,o=0}}if(1==o)throw Error("invalid base64 string.");return i.subarray(0,s)},enc(e){let t,n="",i=0,s=0;for(let o=0;o<e.length;o++)switch(t=e[o],i){case 0:n+=Z[t>>2],s=(3&t)<<4,i=1;break;case 1:n+=Z[s|t>>4],s=(15&t)<<2,i=2;break;case 2:n+=Z[s|t>>6],n+=Z[63&t],i=0}return i&&(n+=Z[s],n+="=",1==i&&(n+="=")),n}};function te(e,t,n){se(t,e);const i=t.runtime.bin.makeReadOptions(n),s=function(e,t){if(!t.repeated&&("enum"==t.kind||"scalar"==t.kind)){for(let n=e.length-1;n>=0;--n)if(e[n].no==t.no)return[e[n]];return[]}return e.filter((e=>e.no===t.no))}(e.getType().runtime.bin.listUnknownFields(e),t.field),[o,a]=U(t);for(const e of s)t.runtime.bin.readField(o,i.readerFactory(e.data),t.field,e.wireType,i);return a()}function ne(e,t,n,i){se(t,e);const s=t.runtime.bin.makeReadOptions(i),o=t.runtime.bin.makeWriteOptions(i);if(ie(e,t)){const n=e.getType().runtime.bin.listUnknownFields(e).filter((e=>e.no!=t.field.no));e.getType().runtime.bin.discardUnknownFields(e);for(const t of n)e.getType().runtime.bin.onUnknownField(e,t.no,t.wireType,t.data)}const a=o.writerFactory();let r=t.field;r.opt||r.repeated||"enum"!=r.kind&&"scalar"!=r.kind||(r=Object.assign(Object.assign({},t.field),{opt:!0})),t.runtime.bin.writeField(r,n,a,o);const c=s.readerFactory(a.finish());for(;c.pos<c.len;){const[t,n]=c.tag(),i=c.skip(n);e.getType().runtime.bin.onUnknownField(e,t,n,i)}}function ie(e,t){const n=e.getType();return t.extendee.typeName===n.typeName&&!!n.runtime.bin.listUnknownFields(e).find((e=>e.no==t.field.no))}function se(e,t){n(e.extendee.typeName==t.getType().typeName,"extension ".concat(e.typeName," can only be applied to message ").concat(e.extendee.typeName))}const oe={ignoreUnknownFields:!1},ae={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0};function re(e){return e?Object.assign(Object.assign({},oe),e):oe}function ce(e){return e?Object.assign(Object.assign({},ae),e):ae}function de(e){if(null===e)return"null";switch(typeof e){case"object":return Array.isArray(e)?"array":"object";case"string":return e.length>100?"string":'"'.concat(e.split('"').join('\\"'),'"');default:return String(e)}}function le(e,t,n,i,s,o){let a=n.localName;if(n.oneof){if(null===t&&"scalar"==n.kind)return;e=e[n.oneof.localName]={case:a},a="value"}if(n.repeated){if(null===t)return;if(!Array.isArray(t))throw new Error("cannot decode field ".concat(s.typeName,".").concat(n.name," from JSON: ").concat(de(t)));const o=e[a];for(const e of t){if(null===e)throw new Error("cannot decode field ".concat(s.typeName,".").concat(n.name," from JSON: ").concat(de(e)));let t;switch(n.kind){case"message":t=n.T.fromJson(e,i);break;case"enum":if(t=he(n.T,e,i.ignoreUnknownFields,!0),void 0===t)continue;break;case"scalar":try{t=ue(n.T,e,n.L,!0)}catch(t){let i="cannot decode field ".concat(s.typeName,".").concat(n.name," from JSON: ").concat(de(e));throw t instanceof Error&&t.message.length>0&&(i+=": ".concat(t.message)),new Error(i)}}o.push(t)}}else if("map"==n.kind){if(null===t)return;if("object"!=typeof t||Array.isArray(t))throw new Error("cannot decode field ".concat(s.typeName,".").concat(n.name," from JSON: ").concat(de(t)));const o=e[a];for(const[e,a]of Object.entries(t)){if(null===a)throw new Error("cannot decode field ".concat(s.typeName,".").concat(n.name," from JSON: map value null"));let r;switch(n.V.kind){case"message":r=n.V.T.fromJson(a,i);break;case"enum":if(r=he(n.V.T,a,i.ignoreUnknownFields,!0),void 0===r)continue;break;case"scalar":try{r=ue(n.V.T,a,T.BIGINT,!0)}catch(e){let i="cannot decode map value for field ".concat(s.typeName,".").concat(n.name," from JSON: ").concat(de(t));throw e instanceof Error&&e.message.length>0&&(i+=": ".concat(e.message)),new Error(i)}}try{o[ue(n.K,n.K==k.BOOL?"true"==e||"false"!=e&&e:e,T.BIGINT,!0).toString()]=r}catch(e){let i="cannot decode map key for field ".concat(s.typeName,".").concat(n.name," from JSON: ").concat(de(t));throw e instanceof Error&&e.message.length>0&&(i+=": ".concat(e.message)),new Error(i)}}}else switch(n.kind){case"message":const r=n.T;if(null===t&&"google.protobuf.Value"!=r.typeName){if(n.oneof)throw new Error("cannot decode field ".concat(s.typeName,".").concat(n.name," from JSON: null is invalid for oneof field"));return}e[a]instanceof v?e[a].fromJson(t,i):(e[a]=r.fromJson(t,i),r.fieldWrapper&&!n.oneof&&(e[a]=r.fieldWrapper.unwrapField(e[a])));break;case"enum":const c=he(n.T,t,i.ignoreUnknownFields,o);void 0!==c&&(e[a]=c);break;case"scalar":try{e[a]=ue(n.T,t,n.L,o)}catch(e){let i="cannot decode field ".concat(s.typeName,".").concat(n.name," from JSON: ").concat(de(t));throw e instanceof Error&&e.message.length>0&&(i+=": ".concat(e.message)),new Error(i)}}}function ue(e,t,n,i){switch(e){case k.DOUBLE:case k.FLOAT:if(null===t)return i?0:void 0;if("NaN"===t)return Number.NaN;if("Infinity"===t)return Number.POSITIVE_INFINITY;if("-Infinity"===t)return Number.NEGATIVE_INFINITY;if(""===t)break;if("string"==typeof t&&t.trim().length!==t.length)break;if("string"!=typeof t&&"number"!=typeof t)break;const s=Number(t);if(Number.isNaN(s))break;if(!Number.isFinite(s))break;return e==k.FLOAT&&l(s),s;case k.INT32:case k.FIXED32:case k.SFIXED32:case k.SINT32:case k.UINT32:if(null===t)return i?0:void 0;let o;if("number"==typeof t?o=t:"string"==typeof t&&t.length>0&&t.trim().length===t.length&&(o=Number(t)),void 0===o)break;return e==k.UINT32?d(o):c(o),o;case k.INT64:case k.SFIXED64:case k.SINT64:if(null===t)return i?O.zero:void 0;if("number"!=typeof t&&"string"!=typeof t)break;const a=O.parse(t);return n?a.toString():a;case k.FIXED64:case k.UINT64:if(null===t)return i?O.zero:void 0;if("number"!=typeof t&&"string"!=typeof t)break;const r=O.uParse(t);return n?r.toString():r;case k.BOOL:if(null===t)return!i&&void 0;if("boolean"!=typeof t)break;return t;case k.STRING:if(null===t)return i?"":void 0;if("string"!=typeof t)break;try{encodeURIComponent(t)}catch(e){throw new Error("invalid UTF8")}return t;case k.BYTES:if(null===t)return i?new Uint8Array(0):void 0;if(""===t)return new Uint8Array(0);if("string"!=typeof t)break;return ee.dec(t)}throw new Error}function he(e,t,n,i){if(null===t)return i?e.values[0].no:void 0;switch(typeof t){case"number":if(Number.isInteger(t))return t;break;case"string":const i=e.findName(t);if(i||n)return null==i?void 0:i.no}throw new Error("cannot decode enum ".concat(e.typeName," from JSON: ").concat(de(t)))}function me(e,t,n,i){var s;if(void 0===t)return t;if(!n&&e.values[0].no===t)return;if(i)return t;if("google.protobuf.NullValue"==e.typeName)return null;const o=e.findNumber(t);return null!==(s=null==o?void 0:o.name)&&void 0!==s?s:t}function pe(e,t,i){if(void 0!==t)switch(e){case k.INT32:case k.SFIXED32:case k.SINT32:case k.FIXED32:case k.UINT32:return n("number"==typeof t),0!=t||i?t:void 0;case k.FLOAT:case k.DOUBLE:return n("number"==typeof t),Number.isNaN(t)?"NaN":t===Number.POSITIVE_INFINITY?"Infinity":t===Number.NEGATIVE_INFINITY?"-Infinity":0!==t||i?t:void 0;case k.STRING:return n("string"==typeof t),t.length>0||i?t:void 0;case k.BOOL:return n("boolean"==typeof t),t||i?t:void 0;case k.UINT64:case k.FIXED64:case k.INT64:case k.SFIXED64:case k.SINT64:return n("bigint"==typeof t||"string"==typeof t||"number"==typeof t),i||0!=t?t.toString(10):void 0;case k.BYTES:return n(t instanceof Uint8Array),i||t.byteLength>0?ee.enc(t):void 0}}function ge(e){if(void 0===e)return e;if(e instanceof v)return e.clone();if(e instanceof Uint8Array){const t=new Uint8Array(e.byteLength);return t.set(e),t}return e}function fe(e){return e instanceof Uint8Array?e:new Uint8Array(e)}class ve{constructor(e,t){this._fields=e,this._normalizer=t}findJsonName(e){if(!this.jsonNames){const e={};for(const t of this.list())e[t.jsonName]=e[t.name]=t;this.jsonNames=e}return this.jsonNames[e]}find(e){if(!this.numbers){const e={};for(const t of this.list())e[t.no]=t;this.numbers=e}return this.numbers[e]}list(){return this.all||(this.all=this._normalizer(this._fields)),this.all}byNumber(){return this.numbersAsc||(this.numbersAsc=this.list().concat().sort(((e,t)=>e.no-t.no))),this.numbersAsc}byMember(){if(!this.members){this.members=[];const e=this.members;let t;for(const n of this.list())n.oneof?n.oneof!==t&&(t=n.oneof,e.push(t)):e.push(n)}return this.members}}function ke(e,t){const n=ye(e);return t?n:we(Ee(n))}const Te=ye;function ye(e){let t=!1;const n=[];for(let i=0;i<e.length;i++){let s=e.charAt(i);switch(s){case"_":t=!0;break;case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":n.push(s),t=!1;break;default:t&&(t=!1,s=s.toUpperCase()),n.push(s)}}return n.join("")}const be=new Set(["constructor","toString","toJSON","valueOf"]),Ce=new Set(["getType","clone","equals","fromBinary","fromJson","fromJsonString","toBinary","toJson","toJsonString","toObject"]),Se=e=>"".concat(e,"$"),Ee=e=>Ce.has(e)?Se(e):e,we=e=>be.has(e)?Se(e):e;class Pe{constructor(e){this.kind="oneof",this.repeated=!1,this.packed=!1,this.opt=!1,this.default=void 0,this.fields=[],this.name=e,this.localName=ke(e,!1)}addField(e){n(e.oneof===this,"field ".concat(e.name," not one of ").concat(this.name)),this.fields.push(e)}findField(e){if(!this._lookup){this._lookup=Object.create(null);for(let e=0;e<this.fields.length;e++)this._lookup[this.fields[e].localName]=this.fields[e]}return this._lookup[e]}}const Re=(_e="proto3",Ie=function(e,t){const n=t(me,pe);return{makeReadOptions:re,makeWriteOptions:ce,readMessage(t,n,i,s){if(null==n||Array.isArray(n)||"object"!=typeof n)throw new Error("cannot decode message ".concat(t.typeName," from JSON: ").concat(de(n)));s=null!=s?s:new t;const o=new Map,a=i.typeRegistry;for(const[r,c]of Object.entries(n)){const n=t.fields.findJsonName(r);if(n){if(n.oneof){if(null===c&&"scalar"==n.kind)continue;const e=o.get(n.oneof);if(void 0!==e)throw new Error("cannot decode message ".concat(t.typeName,' from JSON: multiple keys for oneof "').concat(n.oneof.name,'" present: "').concat(e,'", "').concat(r,'"'));o.set(n.oneof,r)}le(s,c,n,i,t,e)}else{let e=!1;if((null==a?void 0:a.findExtension)&&r.startsWith("[")&&r.endsWith("]")){const n=a.findExtension(r.substring(1,r.length-1));if(n&&n.extendee.typeName==t.typeName){e=!0;const[t,o]=U(n);le(t,c,n.field,i,n,!0),ne(s,n,o(),i)}}if(!e&&!i.ignoreUnknownFields)throw new Error("cannot decode message ".concat(t.typeName,' from JSON: key "').concat(r,'" is unknown'))}}return s},writeMessage(e,t){const i=e.getType(),s={};let o;try{for(const a of i.fields.byMember()){let i;if("oneof"==a.kind){const s=e[a.localName];if(void 0===s.value)continue;if(o=a.findField(s.case),!o)throw"oneof case not found: "+s.case;i=n(o,s.value,t)}else o=a,i=n(o,e[o.localName],t);void 0!==i&&(s[t.useProtoFieldName?o.name:o.jsonName]=i)}const a=t.typeRegistry;if(null==a?void 0:a.findExtensionFor)for(const o of i.runtime.bin.listUnknownFields(e)){const r=a.findExtensionFor(i.typeName,o.no);if(r&&ie(e,r)){const i=te(e,r,t),o=n(r.field,i,t);void 0!==o&&(s[r.field.jsonName]=o)}}}catch(e){const t=o?"cannot encode field ".concat(i.typeName,".").concat(o.name," to JSON"):"cannot encode message ".concat(i.typeName," to JSON"),n=e instanceof Error?e.message:String(e);throw new Error(t+(n.length>0?": ".concat(n):""))}return s},readScalar:(t,n,i)=>ue(t,n,i,e),writeScalar:pe,debug:de}}(!0,((e,t)=>function(i,s,o){if("map"==i.kind){const a={};switch(i.V.kind){case"scalar":for(const[e,o]of Object.entries(s)){const s=t(i.V.T,o,!0);n(void 0!==s),a[e.toString()]=s}break;case"message":for(const[e,t]of Object.entries(s))a[e.toString()]=t.toJson(o);break;case"enum":const r=i.V.T;for(const[t,i]of Object.entries(s)){n(void 0===i||"number"==typeof i);const s=e(r,i,!0,o.enumAsInteger);n(void 0!==s),a[t.toString()]=s}}return o.emitDefaultValues||Object.keys(a).length>0?a:void 0}if(i.repeated){const n=[];switch(i.kind){case"scalar":for(let e=0;e<s.length;e++)n.push(t(i.T,s[e],!0));break;case"enum":for(let t=0;t<s.length;t++)n.push(e(i.T,s[t],!0,o.enumAsInteger));break;case"message":for(let e=0;e<s.length;e++)n.push(s[e].toJson(o))}return o.emitDefaultValues||n.length>0?n:void 0}if(void 0!==s)switch(i.kind){case"scalar":return t(i.T,s,!!i.oneof||i.opt||o.emitDefaultValues);case"enum":return e(i.T,s,!!i.oneof||i.opt||o.emitDefaultValues,o.enumAsInteger);case"message":return j(i.T,s).toJson(o)}})),Oe=Object.assign(Object.assign({},{makeReadOptions:q,makeWriteOptions:K,listUnknownFields(e){var t;return null!==(t=e[F])&&void 0!==t?t:[]},discardUnknownFields(e){delete e[F]},writeUnknownFields(e,t){const n=e[F];if(n)for(const e of n)t.tag(e.no,e.wireType).raw(e.data)},onUnknownField(e,t,n,i){const s=e;Array.isArray(s[F])||(s[F]=[]),s[F].push({no:t,wireType:n,data:i})},readMessage(e,t,n,i,s){const o=e.getType(),a=s?t.len:t.pos+n;let r,c;for(;t.pos<a&&([r,c]=t.tag(),c!=M.EndGroup);){const n=o.fields.find(r);if(n)G(e,t,n,c,i);else{const n=t.skip(c);i.readUnknownFields&&this.onUnknownField(e,r,c,n)}}if(s&&(c!=M.EndGroup||r!==n))throw new Error("invalid end group tag")},readField:G}),{writeField:X,writeMessage(e,t,n){const i=e.getType();for(const s of i.fields.byNumber()){let i,o=s.localName;if(s.oneof){const t=e[s.oneof.localName];if(t.case!==o)continue;i=t.value}else i=e[o];X(s,i,t,n)}return n.writeUnknownFields&&this.writeUnknownFields(e,t),t}}),Me=Object.assign(Object.assign({},{setEnumType:m,initPartial(e,t){if(void 0===e)return;const n=t.getType();for(const i of n.fields.byMember()){const n=i.localName,s=t,o=e;if(void 0!==o[n])switch(i.kind){case"oneof":const e=o[n].case;if(void 0===e)continue;const t=i.findField(e);let a=o[n].value;!t||"message"!=t.kind||a instanceof t.T?t&&"scalar"===t.kind&&t.T===k.BYTES&&(a=fe(a)):a=new t.T(a),s[n]={case:e,value:a};break;case"scalar":case"enum":let r=o[n];i.T===k.BYTES&&(r=i.repeated?r.map(fe):fe(r)),s[n]=r;break;case"map":switch(i.V.kind){case"scalar":case"enum":if(i.V.T===k.BYTES)for(const[e,t]of Object.entries(o[n]))s[n][e]=fe(t);else Object.assign(s[n],o[n]);break;case"message":const e=i.V.T;for(const t of Object.keys(o[n])){let i=o[n][t];e.fieldWrapper||(i=new e(i)),s[n][t]=i}}break;case"message":const c=i.T;if(i.repeated)s[n]=o[n].map((e=>e instanceof c?e:new c(e)));else if(void 0!==o[n]){const e=o[n];c.fieldWrapper?"google.protobuf.BytesValue"===c.typeName?s[n]=fe(e):s[n]=e:s[n]=e instanceof c?e:new c(e)}}}},equals:(e,t,n)=>t===n||!(!t||!n)&&e.fields.byMember().every((e=>{const i=t[e.localName],s=n[e.localName];if(e.repeated){if(i.length!==s.length)return!1;switch(e.kind){case"message":return i.every(((t,n)=>e.T.equals(t,s[n])));case"scalar":return i.every(((t,n)=>N(e.T,t,s[n])));case"enum":return i.every(((e,t)=>N(k.INT32,e,s[t])))}throw new Error("repeated cannot contain ".concat(e.kind))}switch(e.kind){case"message":return e.T.equals(i,s);case"enum":return N(k.INT32,i,s);case"scalar":return N(e.T,i,s);case"oneof":if(i.case!==s.case)return!1;const t=e.findField(i.case);if(void 0===t)return!0;switch(t.kind){case"message":return t.T.equals(i.value,s.value);case"enum":return N(k.INT32,i.value,s.value);case"scalar":return N(t.T,i.value,s.value)}throw new Error("oneof cannot contain ".concat(t.kind));case"map":const n=Object.keys(i).concat(Object.keys(s));switch(e.V.kind){case"message":const t=e.V.T;return n.every((e=>t.equals(i[e],s[e])));case"enum":return n.every((e=>N(k.INT32,i[e],s[e])));case"scalar":const o=e.V.T;return n.every((e=>N(o,i[e],s[e])))}}})),clone(e){const t=e.getType(),n=new t,i=n;for(const n of t.fields.byMember()){const t=e[n.localName];let s;if(n.repeated)s=t.map(ge);else if("map"==n.kind){s=i[n.localName];for(const[e,n]of Object.entries(t))s[e]=ge(n)}else s="oneof"==n.kind?n.findField(t.case)?{case:t.case,value:ge(t.value)}:{case:void 0}:ge(t);i[n.localName]=s}return n}}),{newFieldList:e=>new ve(e,xe),initFields(e){for(const t of e.getType().fields.byMember()){if(t.opt)continue;const n=t.localName,i=e;if(t.repeated)i[n]=[];else switch(t.kind){case"oneof":i[n]={case:void 0};break;case"enum":i[n]=0;break;case"map":i[n]={};break;case"scalar":i[n]=L(t.T,t.L)}}}}),{syntax:_e,json:Ie,bin:Oe,util:Me,makeMessageType(e,t,n){return function(e,t,n,i){var s;const o=null!==(s=null==i?void 0:i.localName)&&void 0!==s?s:t.substring(t.lastIndexOf(".")+1),a={[o]:function(t){e.util.initFields(this),e.util.initPartial(t,this)}}[o];return Object.setPrototypeOf(a.prototype,new v),Object.assign(a,{runtime:e,typeName:t,fields:e.util.newFieldList(n),fromBinary:(e,t)=>(new a).fromBinary(e,t),fromJson:(e,t)=>(new a).fromJson(e,t),fromJsonString:(e,t)=>(new a).fromJsonString(e,t),equals:(t,n)=>e.util.equals(a,t,n)}),a}(this,e,t,n)},makeEnum:g,makeEnumType:p,getEnumType:h,makeExtension(e,t,n){return function(e,t,n,i){let s;return{typeName:t,extendee:n,get field(){if(!s){const n="function"==typeof i?i():i;n.name=t.split(".").pop(),n.jsonName="[".concat(t,"]"),s=e.util.newFieldList([n]).list()[0]}return s},runtime:e}}(this,e,t,n)}});var _e,Ie,Oe,Me;function xe(e){var t,n,i,s;const o=[];let a;for(const r of"function"==typeof e?e():e){const e=r;if(e.localName=ke(r.name,void 0!==r.oneof),e.jsonName=null!==(t=r.jsonName)&&void 0!==t?t:Te(r.name),e.repeated=null!==(n=r.repeated)&&void 0!==n&&n,"scalar"==r.kind&&(e.L=null!==(i=r.L)&&void 0!==i?i:T.BIGINT),void 0!==r.oneof){const t="string"==typeof r.oneof?r.oneof:r.oneof.name;a&&a.name==t||(a=new Pe(t)),e.oneof=a,a.addField(e)}"message"==r.kind&&(e.delimited=!1),e.packed=null!==(s=r.packed)&&void 0!==s?s:"enum"==r.kind||"scalar"==r.kind&&r.T!=k.BYTES&&r.T!=k.STRING,o.push(e)}return o}class De extends v{constructor(e){super(),this.seconds=O.zero,this.nanos=0,Re.util.initPartial(e,this)}fromJson(e,t){if("string"!=typeof e)throw new Error("cannot decode google.protobuf.Timestamp from JSON: ".concat(Re.json.debug(e)));const n=e.match(/^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})(?:Z|\.([0-9]{3,9})Z|([+-][0-9][0-9]:[0-9][0-9]))$/);if(!n)throw new Error("cannot decode google.protobuf.Timestamp from JSON: invalid RFC 3339 string");const i=Date.parse(n[1]+"-"+n[2]+"-"+n[3]+"T"+n[4]+":"+n[5]+":"+n[6]+(n[8]?n[8]:"Z"));if(Number.isNaN(i))throw new Error("cannot decode google.protobuf.Timestamp from JSON: invalid RFC 3339 string");if(i<Date.parse("0001-01-01T00:00:00Z")||i>Date.parse("9999-12-31T23:59:59Z"))throw new Error("cannot decode message google.protobuf.Timestamp from JSON: must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive");return this.seconds=O.parse(i/1e3),this.nanos=0,n[7]&&(this.nanos=parseInt("1"+n[7]+"0".repeat(9-n[7].length))-1e9),this}toJson(e){const t=1e3*Number(this.seconds);if(t<Date.parse("0001-01-01T00:00:00Z")||t>Date.parse("9999-12-31T23:59:59Z"))throw new Error("cannot encode google.protobuf.Timestamp to JSON: must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive");if(this.nanos<0)throw new Error("cannot encode google.protobuf.Timestamp to JSON: nanos must not be negative");let n="Z";if(this.nanos>0){const e=(this.nanos+1e9).toString().substring(1);n="000000"===e.substring(3)?"."+e.substring(0,3)+"Z":"000"===e.substring(6)?"."+e.substring(0,6)+"Z":"."+e+"Z"}return new Date(t).toISOString().replace(".000Z",n)}toDate(){return new Date(1e3*Number(this.seconds)+Math.ceil(this.nanos/1e6))}static now(){return De.fromDate(new Date)}static fromDate(e){const t=e.getTime();return new De({seconds:O.parse(Math.floor(t/1e3)),nanos:t%1e3*1e6})}static fromBinary(e,t){return(new De).fromBinary(e,t)}static fromJson(e,t){return(new De).fromJson(e,t)}static fromJsonString(e,t){return(new De).fromJsonString(e,t)}static equals(e,t){return Re.util.equals(De,e,t)}}De.runtime=Re,De.typeName="google.protobuf.Timestamp",De.fields=Re.util.newFieldList((()=>[{no:1,name:"seconds",kind:"scalar",T:3},{no:2,name:"nanos",kind:"scalar",T:5}]));const Ne=Re.makeEnum("livekit.AudioCodec",[{no:0,name:"DEFAULT_AC"},{no:1,name:"OPUS"},{no:2,name:"AAC"}]),Le=Re.makeEnum("livekit.VideoCodec",[{no:0,name:"DEFAULT_VC"},{no:1,name:"H264_BASELINE"},{no:2,name:"H264_MAIN"},{no:3,name:"H264_HIGH"},{no:4,name:"VP8"}]),Ae=Re.makeEnum("livekit.ImageCodec",[{no:0,name:"IC_DEFAULT"},{no:1,name:"IC_JPEG"}]),Ue=Re.makeEnum("livekit.TrackType",[{no:0,name:"AUDIO"},{no:1,name:"VIDEO"},{no:2,name:"DATA"}]),je=Re.makeEnum("livekit.TrackSource",[{no:0,name:"UNKNOWN"},{no:1,name:"CAMERA"},{no:2,name:"MICROPHONE"},{no:3,name:"SCREEN_SHARE"},{no:4,name:"SCREEN_SHARE_AUDIO"}]),Fe=Re.makeEnum("livekit.VideoQuality",[{no:0,name:"LOW"},{no:1,name:"MEDIUM"},{no:2,name:"HIGH"},{no:3,name:"OFF"}]),Be=Re.makeEnum("livekit.ConnectionQuality",[{no:0,name:"POOR"},{no:1,name:"GOOD"},{no:2,name:"EXCELLENT"},{no:3,name:"LOST"}]),Ve=Re.makeEnum("livekit.ClientConfigSetting",[{no:0,name:"UNSET"},{no:1,name:"DISABLED"},{no:2,name:"ENABLED"}]),qe=Re.makeEnum("livekit.DisconnectReason",[{no:0,name:"UNKNOWN_REASON"},{no:1,name:"CLIENT_INITIATED"},{no:2,name:"DUPLICATE_IDENTITY"},{no:3,name:"SERVER_SHUTDOWN"},{no:4,name:"PARTICIPANT_REMOVED"},{no:5,name:"ROOM_DELETED"},{no:6,name:"STATE_MISMATCH"},{no:7,name:"JOIN_FAILURE"},{no:8,name:"MIGRATION"},{no:9,name:"SIGNAL_CLOSE"}]),Ke=Re.makeEnum("livekit.ReconnectReason",[{no:0,name:"RR_UNKNOWN"},{no:1,name:"RR_SIGNAL_DISCONNECTED"},{no:2,name:"RR_PUBLISHER_FAILED"},{no:3,name:"RR_SUBSCRIBER_FAILED"},{no:4,name:"RR_SWITCH_CANDIDATE"}]),Ge=Re.makeEnum("livekit.SubscriptionError",[{no:0,name:"SE_UNKNOWN"},{no:1,name:"SE_CODEC_UNSUPPORTED"},{no:2,name:"SE_TRACK_NOTFOUND"}]),We=Re.makeMessageType("livekit.Room",(()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",T:9},{no:3,name:"empty_timeout",kind:"scalar",T:13},{no:14,name:"departure_timeout",kind:"scalar",T:13},{no:4,name:"max_participants",kind:"scalar",T:13},{no:5,name:"creation_time",kind:"scalar",T:3},{no:6,name:"turn_password",kind:"scalar",T:9},{no:7,name:"enabled_codecs",kind:"message",T:He,repeated:!0},{no:8,name:"metadata",kind:"scalar",T:9},{no:9,name:"num_participants",kind:"scalar",T:13},{no:11,name:"num_publishers",kind:"scalar",T:13},{no:10,name:"active_recording",kind:"scalar",T:8},{no:13,name:"version",kind:"message",T:ft}])),He=Re.makeMessageType("livekit.Codec",(()=>[{no:1,name:"mime",kind:"scalar",T:9},{no:2,name:"fmtp_line",kind:"scalar",T:9}]));Re.makeMessageType("livekit.PlayoutDelay",(()=>[{no:1,name:"enabled",kind:"scalar",T:8},{no:2,name:"min",kind:"scalar",T:13},{no:3,name:"max",kind:"scalar",T:13}]));const Je=Re.makeMessageType("livekit.ParticipantPermission",(()=>[{no:1,name:"can_subscribe",kind:"scalar",T:8},{no:2,name:"can_publish",kind:"scalar",T:8},{no:3,name:"can_publish_data",kind:"scalar",T:8},{no:9,name:"can_publish_sources",kind:"enum",T:Re.getEnumType(je),repeated:!0},{no:7,name:"hidden",kind:"scalar",T:8},{no:8,name:"recorder",kind:"scalar",T:8},{no:10,name:"can_update_metadata",kind:"scalar",T:8},{no:11,name:"agent",kind:"scalar",T:8}])),ze=Re.makeMessageType("livekit.ParticipantInfo",(()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"identity",kind:"scalar",T:9},{no:3,name:"state",kind:"enum",T:Re.getEnumType(Qe)},{no:4,name:"tracks",kind:"message",T:$e,repeated:!0},{no:5,name:"metadata",kind:"scalar",T:9},{no:6,name:"joined_at",kind:"scalar",T:3},{no:9,name:"name",kind:"scalar",T:9},{no:10,name:"version",kind:"scalar",T:13},{no:11,name:"permission",kind:"message",T:Je},{no:12,name:"region",kind:"scalar",T:9},{no:13,name:"is_publisher",kind:"scalar",T:8},{no:14,name:"kind",kind:"enum",T:Re.getEnumType(Ye)}])),Qe=Re.makeEnum("livekit.ParticipantInfo.State",[{no:0,name:"JOINING"},{no:1,name:"JOINED"},{no:2,name:"ACTIVE"},{no:3,name:"DISCONNECTED"}]),Ye=Re.makeEnum("livekit.ParticipantInfo.Kind",[{no:0,name:"STANDARD"},{no:1,name:"INGRESS"},{no:2,name:"EGRESS"},{no:3,name:"SIP"},{no:4,name:"AGENT"}]);Re.makeMessageType("livekit.Encryption",[]);const Xe=Re.makeEnum("livekit.Encryption.Type",[{no:0,name:"NONE"},{no:1,name:"GCM"},{no:2,name:"CUSTOM"}]),Ze=Re.makeMessageType("livekit.SimulcastCodecInfo",(()=>[{no:1,name:"mime_type",kind:"scalar",T:9},{no:2,name:"mid",kind:"scalar",T:9},{no:3,name:"cid",kind:"scalar",T:9},{no:4,name:"layers",kind:"message",T:et,repeated:!0}])),$e=Re.makeMessageType("livekit.TrackInfo",(()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"type",kind:"enum",T:Re.getEnumType(Ue)},{no:3,name:"name",kind:"scalar",T:9},{no:4,name:"muted",kind:"scalar",T:8},{no:5,name:"width",kind:"scalar",T:13},{no:6,name:"height",kind:"scalar",T:13},{no:7,name:"simulcast",kind:"scalar",T:8},{no:8,name:"disable_dtx",kind:"scalar",T:8},{no:9,name:"source",kind:"enum",T:Re.getEnumType(je)},{no:10,name:"layers",kind:"message",T:et,repeated:!0},{no:11,name:"mime_type",kind:"scalar",T:9},{no:12,name:"mid",kind:"scalar",T:9},{no:13,name:"codecs",kind:"message",T:Ze,repeated:!0},{no:14,name:"stereo",kind:"scalar",T:8},{no:15,name:"disable_red",kind:"scalar",T:8},{no:16,name:"encryption",kind:"enum",T:Re.getEnumType(Xe)},{no:17,name:"stream",kind:"scalar",T:9},{no:18,name:"version",kind:"message",T:ft}])),et=Re.makeMessageType("livekit.VideoLayer",(()=>[{no:1,name:"quality",kind:"enum",T:Re.getEnumType(Fe)},{no:2,name:"width",kind:"scalar",T:13},{no:3,name:"height",kind:"scalar",T:13},{no:4,name:"bitrate",kind:"scalar",T:13},{no:5,name:"ssrc",kind:"scalar",T:13}])),tt=Re.makeMessageType("livekit.DataPacket",(()=>[{no:1,name:"kind",kind:"enum",T:Re.getEnumType(nt)},{no:4,name:"participant_identity",kind:"scalar",T:9},{no:5,name:"destination_identities",kind:"scalar",T:9,repeated:!0},{no:2,name:"user",kind:"message",T:ot,oneof:"value"},{no:3,name:"speaker",kind:"message",T:it,oneof:"value"},{no:6,name:"sip_dtmf",kind:"message",T:at,oneof:"value"}])),nt=Re.makeEnum("livekit.DataPacket.Kind",[{no:0,name:"RELIABLE"},{no:1,name:"LOSSY"}]),it=Re.makeMessageType("livekit.ActiveSpeakerUpdate",(()=>[{no:1,name:"speakers",kind:"message",T:st,repeated:!0}])),st=Re.makeMessageType("livekit.SpeakerInfo",(()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"level",kind:"scalar",T:2},{no:3,name:"active",kind:"scalar",T:8}])),ot=Re.makeMessageType("livekit.UserPacket",(()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:5,name:"participant_identity",kind:"scalar",T:9},{no:2,name:"payload",kind:"scalar",T:12},{no:3,name:"destination_sids",kind:"scalar",T:9,repeated:!0},{no:6,name:"destination_identities",kind:"scalar",T:9,repeated:!0},{no:4,name:"topic",kind:"scalar",T:9,opt:!0}])),at=Re.makeMessageType("livekit.SipDTMF",(()=>[{no:3,name:"code",kind:"scalar",T:13},{no:4,name:"digit",kind:"scalar",T:9}])),rt=Re.makeMessageType("livekit.ParticipantTracks",(()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"track_sids",kind:"scalar",T:9,repeated:!0}])),ct=Re.makeMessageType("livekit.ServerInfo",(()=>[{no:1,name:"edition",kind:"enum",T:Re.getEnumType(dt)},{no:2,name:"version",kind:"scalar",T:9},{no:3,name:"protocol",kind:"scalar",T:5},{no:4,name:"region",kind:"scalar",T:9},{no:5,name:"node_id",kind:"scalar",T:9},{no:6,name:"debug_info",kind:"scalar",T:9}])),dt=Re.makeEnum("livekit.ServerInfo.Edition",[{no:0,name:"Standard"},{no:1,name:"Cloud"}]),lt=Re.makeMessageType("livekit.ClientInfo",(()=>[{no:1,name:"sdk",kind:"enum",T:Re.getEnumType(ut)},{no:2,name:"version",kind:"scalar",T:9},{no:3,name:"protocol",kind:"scalar",T:5},{no:4,name:"os",kind:"scalar",T:9},{no:5,name:"os_version",kind:"scalar",T:9},{no:6,name:"device_model",kind:"scalar",T:9},{no:7,name:"browser",kind:"scalar",T:9},{no:8,name:"browser_version",kind:"scalar",T:9},{no:9,name:"address",kind:"scalar",T:9},{no:10,name:"network",kind:"scalar",T:9}])),ut=Re.makeEnum("livekit.ClientInfo.SDK",[{no:0,name:"UNKNOWN"},{no:1,name:"JS"},{no:2,name:"SWIFT"},{no:3,name:"ANDROID"},{no:4,name:"FLUTTER"},{no:5,name:"GO"},{no:6,name:"UNITY"},{no:7,name:"REACT_NATIVE"},{no:8,name:"RUST"},{no:9,name:"PYTHON"},{no:10,name:"CPP"}]),ht=Re.makeMessageType("livekit.ClientConfiguration",(()=>[{no:1,name:"video",kind:"message",T:mt},{no:2,name:"screen",kind:"message",T:mt},{no:3,name:"resume_connection",kind:"enum",T:Re.getEnumType(Ve)},{no:4,name:"disabled_codecs",kind:"message",T:pt},{no:5,name:"force_relay",kind:"enum",T:Re.getEnumType(Ve)}])),mt=Re.makeMessageType("livekit.VideoConfiguration",(()=>[{no:1,name:"hardware_encoder",kind:"enum",T:Re.getEnumType(Ve)}])),pt=Re.makeMessageType("livekit.DisabledCodecs",(()=>[{no:1,name:"codecs",kind:"message",T:He,repeated:!0},{no:2,name:"publish",kind:"message",T:He,repeated:!0}])),gt=Re.makeMessageType("livekit.RTPDrift",(()=>[{no:1,name:"start_time",kind:"message",T:De},{no:2,name:"end_time",kind:"message",T:De},{no:3,name:"duration",kind:"scalar",T:1},{no:4,name:"start_timestamp",kind:"scalar",T:4},{no:5,name:"end_timestamp",kind:"scalar",T:4},{no:6,name:"rtp_clock_ticks",kind:"scalar",T:4},{no:7,name:"drift_samples",kind:"scalar",T:3},{no:8,name:"drift_ms",kind:"scalar",T:1},{no:9,name:"clock_rate",kind:"scalar",T:1}]));Re.makeMessageType("livekit.RTPStats",(()=>[{no:1,name:"start_time",kind:"message",T:De},{no:2,name:"end_time",kind:"message",T:De},{no:3,name:"duration",kind:"scalar",T:1},{no:4,name:"packets",kind:"scalar",T:13},{no:5,name:"packet_rate",kind:"scalar",T:1},{no:6,name:"bytes",kind:"scalar",T:4},{no:39,name:"header_bytes",kind:"scalar",T:4},{no:7,name:"bitrate",kind:"scalar",T:1},{no:8,name:"packets_lost",kind:"scalar",T:13},{no:9,name:"packet_loss_rate",kind:"scalar",T:1},{no:10,name:"packet_loss_percentage",kind:"scalar",T:2},{no:11,name:"packets_duplicate",kind:"scalar",T:13},{no:12,name:"packet_duplicate_rate",kind:"scalar",T:1},{no:13,name:"bytes_duplicate",kind:"scalar",T:4},{no:40,name:"header_bytes_duplicate",kind:"scalar",T:4},{no:14,name:"bitrate_duplicate",kind:"scalar",T:1},{no:15,name:"packets_padding",kind:"scalar",T:13},{no:16,name:"packet_padding_rate",kind:"scalar",T:1},{no:17,name:"bytes_padding",kind:"scalar",T:4},{no:41,name:"header_bytes_padding",kind:"scalar",T:4},{no:18,name:"bitrate_padding",kind:"scalar",T:1},{no:19,name:"packets_out_of_order",kind:"scalar",T:13},{no:20,name:"frames",kind:"scalar",T:13},{no:21,name:"frame_rate",kind:"scalar",T:1},{no:22,name:"jitter_current",kind:"scalar",T:1},{no:23,name:"jitter_max",kind:"scalar",T:1},{no:24,name:"gap_histogram",kind:"map",K:5,V:{kind:"scalar",T:13}},{no:25,name:"nacks",kind:"scalar",T:13},{no:37,name:"nack_acks",kind:"scalar",T:13},{no:26,name:"nack_misses",kind:"scalar",T:13},{no:38,name:"nack_repeated",kind:"scalar",T:13},{no:27,name:"plis",kind:"scalar",T:13},{no:28,name:"last_pli",kind:"message",T:De},{no:29,name:"firs",kind:"scalar",T:13},{no:30,name:"last_fir",kind:"message",T:De},{no:31,name:"rtt_current",kind:"scalar",T:13},{no:32,name:"rtt_max",kind:"scalar",T:13},{no:33,name:"key_frames",kind:"scalar",T:13},{no:34,name:"last_key_frame",kind:"message",T:De},{no:35,name:"layer_lock_plis",kind:"scalar",T:13},{no:36,name:"last_layer_lock_pli",kind:"message",T:De},{no:44,name:"packet_drift",kind:"message",T:gt},{no:45,name:"report_drift",kind:"message",T:gt}]));const ft=Re.makeMessageType("livekit.TimedVersion",(()=>[{no:1,name:"unix_micro",kind:"scalar",T:3},{no:2,name:"ticks",kind:"scalar",T:5}])),vt=Re.makeEnum("livekit.EncodedFileType",[{no:0,name:"DEFAULT_FILETYPE"},{no:1,name:"MP4"},{no:2,name:"OGG"}]),kt=Re.makeEnum("livekit.SegmentedFileProtocol",[{no:0,name:"DEFAULT_SEGMENTED_FILE_PROTOCOL"},{no:1,name:"HLS_PROTOCOL"}]),Tt=Re.makeEnum("livekit.SegmentedFileSuffix",[{no:0,name:"INDEX"},{no:1,name:"TIMESTAMP"}]),yt=Re.makeEnum("livekit.ImageFileSuffix",[{no:0,name:"IMAGE_SUFFIX_INDEX"},{no:1,name:"IMAGE_SUFFIX_TIMESTAMP"}]),bt=Re.makeEnum("livekit.StreamProtocol",[{no:0,name:"DEFAULT_PROTOCOL"},{no:1,name:"RTMP"}]),Ct=Re.makeEnum("livekit.EncodingOptionsPreset",[{no:0,name:"H264_720P_30"},{no:1,name:"H264_720P_60"},{no:2,name:"H264_1080P_30"},{no:3,name:"H264_1080P_60"},{no:4,name:"PORTRAIT_H264_720P_30"},{no:5,name:"PORTRAIT_H264_720P_60"},{no:6,name:"PORTRAIT_H264_1080P_30"},{no:7,name:"PORTRAIT_H264_1080P_60"}]),St=Re.makeEnum("livekit.EgressStatus",[{no:0,name:"EGRESS_STARTING"},{no:1,name:"EGRESS_ACTIVE"},{no:2,name:"EGRESS_ENDING"},{no:3,name:"EGRESS_COMPLETE"},{no:4,name:"EGRESS_FAILED"},{no:5,name:"EGRESS_ABORTED"},{no:6,name:"EGRESS_LIMIT_REACHED"}]),Et=Re.makeMessageType("livekit.RoomCompositeEgressRequest",(()=>[{no:1,name:"room_name",kind:"scalar",T:9},{no:2,name:"layout",kind:"scalar",T:9},{no:3,name:"audio_only",kind:"scalar",T:8},{no:4,name:"video_only",kind:"scalar",T:8},{no:5,name:"custom_base_url",kind:"scalar",T:9},{no:6,name:"file",kind:"message",T:It,oneof:"output"},{no:7,name:"stream",kind:"message",T:Ut,oneof:"output"},{no:10,name:"segments",kind:"message",T:Ot,oneof:"output"},{no:8,name:"preset",kind:"enum",T:Re.getEnumType(Ct),oneof:"options"},{no:9,name:"advanced",kind:"message",T:jt,oneof:"options"},{no:11,name:"file_outputs",kind:"message",T:It,repeated:!0},{no:12,name:"stream_outputs",kind:"message",T:Ut,repeated:!0},{no:13,name:"segment_outputs",kind:"message",T:Ot,repeated:!0},{no:14,name:"image_outputs",kind:"message",T:xt,repeated:!0}])),wt=Re.makeMessageType("livekit.WebEgressRequest",(()=>[{no:1,name:"url",kind:"scalar",T:9},{no:2,name:"audio_only",kind:"scalar",T:8},{no:3,name:"video_only",kind:"scalar",T:8},{no:12,name:"await_start_signal",kind:"scalar",T:8},{no:4,name:"file",kind:"message",T:It,oneof:"output"},{no:5,name:"stream",kind:"message",T:Ut,oneof:"output"},{no:6,name:"segments",kind:"message",T:Ot,oneof:"output"},{no:7,name:"preset",kind:"enum",T:Re.getEnumType(Ct),oneof:"options"},{no:8,name:"advanced",kind:"message",T:jt,oneof:"options"},{no:9,name:"file_outputs",kind:"message",T:It,repeated:!0},{no:10,name:"stream_outputs",kind:"message",T:Ut,repeated:!0},{no:11,name:"segment_outputs",kind:"message",T:Ot,repeated:!0},{no:13,name:"image_outputs",kind:"message",T:xt,repeated:!0}])),Pt=Re.makeMessageType("livekit.ParticipantEgressRequest",(()=>[{no:1,name:"room_name",kind:"scalar",T:9},{no:2,name:"identity",kind:"scalar",T:9},{no:3,name:"screen_share",kind:"scalar",T:8},{no:4,name:"preset",kind:"enum",T:Re.getEnumType(Ct),oneof:"options"},{no:5,name:"advanced",kind:"message",T:jt,oneof:"options"},{no:6,name:"file_outputs",kind:"message",T:It,repeated:!0},{no:7,name:"stream_outputs",kind:"message",T:Ut,repeated:!0},{no:8,name:"segment_outputs",kind:"message",T:Ot,repeated:!0},{no:9,name:"image_outputs",kind:"message",T:xt,repeated:!0}])),Rt=Re.makeMessageType("livekit.TrackCompositeEgressRequest",(()=>[{no:1,name:"room_name",kind:"scalar",T:9},{no:2,name:"audio_track_id",kind:"scalar",T:9},{no:3,name:"video_track_id",kind:"scalar",T:9},{no:4,name:"file",kind:"message",T:It,oneof:"output"},{no:5,name:"stream",kind:"message",T:Ut,oneof:"output"},{no:8,name:"segments",kind:"message",T:Ot,oneof:"output"},{no:6,name:"preset",kind:"enum",T:Re.getEnumType(Ct),oneof:"options"},{no:7,name:"advanced",kind:"message",T:jt,oneof:"options"},{no:11,name:"file_outputs",kind:"message",T:It,repeated:!0},{no:12,name:"stream_outputs",kind:"message",T:Ut,repeated:!0},{no:13,name:"segment_outputs",kind:"message",T:Ot,repeated:!0},{no:14,name:"image_outputs",kind:"message",T:xt,repeated:!0}])),_t=Re.makeMessageType("livekit.TrackEgressRequest",(()=>[{no:1,name:"room_name",kind:"scalar",T:9},{no:2,name:"track_id",kind:"scalar",T:9},{no:3,name:"file",kind:"message",T:Mt,oneof:"output"},{no:4,name:"websocket_url",kind:"scalar",T:9,oneof:"output"}])),It=Re.makeMessageType("livekit.EncodedFileOutput",(()=>[{no:1,name:"file_type",kind:"enum",T:Re.getEnumType(vt)},{no:2,name:"filepath",kind:"scalar",T:9},{no:6,name:"disable_manifest",kind:"scalar",T:8},{no:3,name:"s3",kind:"message",T:Dt,oneof:"output"},{no:4,name:"gcp",kind:"message",T:Nt,oneof:"output"},{no:5,name:"azure",kind:"message",T:Lt,oneof:"output"},{no:7,name:"aliOSS",kind:"message",T:At,oneof:"output"}])),Ot=Re.makeMessageType("livekit.SegmentedFileOutput",(()=>[{no:1,name:"protocol",kind:"enum",T:Re.getEnumType(kt)},{no:2,name:"filename_prefix",kind:"scalar",T:9},{no:3,name:"playlist_name",kind:"scalar",T:9},{no:11,name:"live_playlist_name",kind:"scalar",T:9},{no:4,name:"segment_duration",kind:"scalar",T:13},{no:10,name:"filename_suffix",kind:"enum",T:Re.getEnumType(Tt)},{no:8,name:"disable_manifest",kind:"scalar",T:8},{no:5,name:"s3",kind:"message",T:Dt,oneof:"output"},{no:6,name:"gcp",kind:"message",T:Nt,oneof:"output"},{no:7,name:"azure",kind:"message",T:Lt,oneof:"output"},{no:9,name:"aliOSS",kind:"message",T:At,oneof:"output"}])),Mt=Re.makeMessageType("livekit.DirectFileOutput",(()=>[{no:1,name:"filepath",kind:"scalar",T:9},{no:5,name:"disable_manifest",kind:"scalar",T:8},{no:2,name:"s3",kind:"message",T:Dt,oneof:"output"},{no:3,name:"gcp",kind:"message",T:Nt,oneof:"output"},{no:4,name:"azure",kind:"message",T:Lt,oneof:"output"},{no:6,name:"aliOSS",kind:"message",T:At,oneof:"output"}])),xt=Re.makeMessageType("livekit.ImageOutput",(()=>[{no:1,name:"capture_interval",kind:"scalar",T:13},{no:2,name:"width",kind:"scalar",T:5},{no:3,name:"height",kind:"scalar",T:5},{no:4,name:"filename_prefix",kind:"scalar",T:9},{no:5,name:"filename_suffix",kind:"enum",T:Re.getEnumType(yt)},{no:6,name:"image_codec",kind:"enum",T:Re.getEnumType(Ae)},{no:7,name:"disable_manifest",kind:"scalar",T:8},{no:8,name:"s3",kind:"message",T:Dt,oneof:"output"},{no:9,name:"gcp",kind:"message",T:Nt,oneof:"output"},{no:10,name:"azure",kind:"message",T:Lt,oneof:"output"},{no:11,name:"aliOSS",kind:"message",T:At,oneof:"output"}])),Dt=Re.makeMessageType("livekit.S3Upload",(()=>[{no:1,name:"access_key",kind:"scalar",T:9},{no:2,name:"secret",kind:"scalar",T:9},{no:3,name:"region",kind:"scalar",T:9},{no:4,name:"endpoint",kind:"scalar",T:9},{no:5,name:"bucket",kind:"scalar",T:9},{no:6,name:"force_path_style",kind:"scalar",T:8},{no:7,name:"metadata",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:8,name:"tagging",kind:"scalar",T:9},{no:9,name:"content_disposition",kind:"scalar",T:9}])),Nt=Re.makeMessageType("livekit.GCPUpload",(()=>[{no:1,name:"credentials",kind:"scalar",T:9},{no:2,name:"bucket",kind:"scalar",T:9},{no:3,name:"endpoint",kind:"scalar",T:9}])),Lt=Re.makeMessageType("livekit.AzureBlobUpload",(()=>[{no:1,name:"account_name",kind:"scalar",T:9},{no:2,name:"account_key",kind:"scalar",T:9},{no:3,name:"container_name",kind:"scalar",T:9}])),At=Re.makeMessageType("livekit.AliOSSUpload",(()=>[{no:1,name:"access_key",kind:"scalar",T:9},{no:2,name:"secret",kind:"scalar",T:9},{no:3,name:"region",kind:"scalar",T:9},{no:4,name:"endpoint",kind:"scalar",T:9},{no:5,name:"bucket",kind:"scalar",T:9}])),Ut=Re.makeMessageType("livekit.StreamOutput",(()=>[{no:1,name:"protocol",kind:"enum",T:Re.getEnumType(bt)},{no:2,name:"urls",kind:"scalar",T:9,repeated:!0}])),jt=Re.makeMessageType("livekit.EncodingOptions",(()=>[{no:1,name:"width",kind:"scalar",T:5},{no:2,name:"height",kind:"scalar",T:5},{no:3,name:"depth",kind:"scalar",T:5},{no:4,name:"framerate",kind:"scalar",T:5},{no:5,name:"audio_codec",kind:"enum",T:Re.getEnumType(Ne)},{no:6,name:"audio_bitrate",kind:"scalar",T:5},{no:11,name:"audio_quality",kind:"scalar",T:5},{no:7,name:"audio_frequency",kind:"scalar",T:5},{no:8,name:"video_codec",kind:"enum",T:Re.getEnumType(Le)},{no:9,name:"video_bitrate",kind:"scalar",T:5},{no:12,name:"video_quality",kind:"scalar",T:5},{no:10,name:"key_frame_interval",kind:"scalar",T:1}]));Re.makeMessageType("livekit.UpdateLayoutRequest",(()=>[{no:1,name:"egress_id",kind:"scalar",T:9},{no:2,name:"layout",kind:"scalar",T:9}])),Re.makeMessageType("livekit.UpdateStreamRequest",(()=>[{no:1,name:"egress_id",kind:"scalar",T:9},{no:2,name:"add_output_urls",kind:"scalar",T:9,repeated:!0},{no:3,name:"remove_output_urls",kind:"scalar",T:9,repeated:!0}])),Re.makeMessageType("livekit.ListEgressRequest",(()=>[{no:1,name:"room_name",kind:"scalar",T:9},{no:2,name:"egress_id",kind:"scalar",T:9},{no:3,name:"active",kind:"scalar",T:8}])),Re.makeMessageType("livekit.ListEgressResponse",(()=>[{no:1,name:"items",kind:"message",T:Ft,repeated:!0}])),Re.makeMessageType("livekit.StopEgressRequest",(()=>[{no:1,name:"egress_id",kind:"scalar",T:9}]));const Ft=Re.makeMessageType("livekit.EgressInfo",(()=>[{no:1,name:"egress_id",kind:"scalar",T:9},{no:2,name:"room_id",kind:"scalar",T:9},{no:13,name:"room_name",kind:"scalar",T:9},{no:3,name:"status",kind:"enum",T:Re.getEnumType(St)},{no:10,name:"started_at",kind:"scalar",T:3},{no:11,name:"ended_at",kind:"scalar",T:3},{no:18,name:"updated_at",kind:"scalar",T:3},{no:21,name:"details",kind:"scalar",T:9},{no:9,name:"error",kind:"scalar",T:9},{no:4,name:"room_composite",kind:"message",T:Et,oneof:"request"},{no:14,name:"web",kind:"message",T:wt,oneof:"request"},{no:19,name:"participant",kind:"message",T:Pt,oneof:"request"},{no:5,name:"track_composite",kind:"message",T:Rt,oneof:"request"},{no:6,name:"track",kind:"message",T:_t,oneof:"request"},{no:7,name:"stream",kind:"message",T:Bt,oneof:"result"},{no:8,name:"file",kind:"message",T:Kt,oneof:"result"},{no:12,name:"segments",kind:"message",T:Gt,oneof:"result"},{no:15,name:"stream_results",kind:"message",T:Vt,repeated:!0},{no:16,name:"file_results",kind:"message",T:Kt,repeated:!0},{no:17,name:"segment_results",kind:"message",T:Gt,repeated:!0},{no:20,name:"image_results",kind:"message",T:Wt,repeated:!0}])),Bt=Re.makeMessageType("livekit.StreamInfoList",(()=>[{no:1,name:"info",kind:"message",T:Vt,repeated:!0}])),Vt=Re.makeMessageType("livekit.StreamInfo",(()=>[{no:1,name:"url",kind:"scalar",T:9},{no:2,name:"started_at",kind:"scalar",T:3},{no:3,name:"ended_at",kind:"scalar",T:3},{no:4,name:"duration",kind:"scalar",T:3},{no:5,name:"status",kind:"enum",T:Re.getEnumType(qt)},{no:6,name:"error",kind:"scalar",T:9}])),qt=Re.makeEnum("livekit.StreamInfo.Status",[{no:0,name:"ACTIVE"},{no:1,name:"FINISHED"},{no:2,name:"FAILED"}]),Kt=Re.makeMessageType("livekit.FileInfo",(()=>[{no:1,name:"filename",kind:"scalar",T:9},{no:2,name:"started_at",kind:"scalar",T:3},{no:3,name:"ended_at",kind:"scalar",T:3},{no:6,name:"duration",kind:"scalar",T:3},{no:4,name:"size",kind:"scalar",T:3},{no:5,name:"location",kind:"scalar",T:9}])),Gt=Re.makeMessageType("livekit.SegmentsInfo",(()=>[{no:1,name:"playlist_name",kind:"scalar",T:9},{no:8,name:"live_playlist_name",kind:"scalar",T:9},{no:2,name:"duration",kind:"scalar",T:3},{no:3,name:"size",kind:"scalar",T:3},{no:4,name:"playlist_location",kind:"scalar",T:9},{no:9,name:"live_playlist_location",kind:"scalar",T:9},{no:5,name:"segment_count",kind:"scalar",T:3},{no:6,name:"started_at",kind:"scalar",T:3},{no:7,name:"ended_at",kind:"scalar",T:3}])),Wt=Re.makeMessageType("livekit.ImagesInfo",(()=>[{no:1,name:"image_count",kind:"scalar",T:3},{no:2,name:"started_at",kind:"scalar",T:3},{no:3,name:"ended_at",kind:"scalar",T:3}])),Ht=Re.makeMessageType("livekit.AutoParticipantEgress",(()=>[{no:1,name:"preset",kind:"enum",T:Re.getEnumType(Ct),oneof:"options"},{no:2,name:"advanced",kind:"message",T:jt,oneof:"options"},{no:3,name:"file_outputs",kind:"message",T:It,repeated:!0},{no:4,name:"segment_outputs",kind:"message",T:Ot,repeated:!0}])),Jt=Re.makeMessageType("livekit.AutoTrackEgress",(()=>[{no:1,name:"filepath",kind:"scalar",T:9},{no:5,name:"disable_manifest",kind:"scalar",T:8},{no:2,name:"s3",kind:"message",T:Dt,oneof:"output"},{no:3,name:"gcp",kind:"message",T:Nt,oneof:"output"},{no:4,name:"azure",kind:"message",T:Lt,oneof:"output"}]));Re.makeMessageType("livekit.CreateRoomRequest",(()=>[{no:1,name:"name",kind:"scalar",T:9},{no:2,name:"empty_timeout",kind:"scalar",T:13},{no:10,name:"departure_timeout",kind:"scalar",T:13},{no:3,name:"max_participants",kind:"scalar",T:13},{no:4,name:"node_id",kind:"scalar",T:9},{no:5,name:"metadata",kind:"scalar",T:9},{no:6,name:"egress",kind:"message",T:zt},{no:7,name:"min_playout_delay",kind:"scalar",T:13},{no:8,name:"max_playout_delay",kind:"scalar",T:13},{no:9,name:"sync_streams",kind:"scalar",T:8}]));const zt=Re.makeMessageType("livekit.RoomEgress",(()=>[{no:1,name:"room",kind:"message",T:Et},{no:3,name:"participant",kind:"message",T:Ht},{no:2,name:"tracks",kind:"message",T:Jt}]));Re.makeMessageType("livekit.ListRoomsRequest",(()=>[{no:1,name:"names",kind:"scalar",T:9,repeated:!0}])),Re.makeMessageType("livekit.ListRoomsResponse",(()=>[{no:1,name:"rooms",kind:"message",T:We,repeated:!0}])),Re.makeMessageType("livekit.DeleteRoomRequest",(()=>[{no:1,name:"room",kind:"scalar",T:9}])),Re.makeMessageType("livekit.DeleteRoomResponse",[]),Re.makeMessageType("livekit.ListParticipantsRequest",(()=>[{no:1,name:"room",kind:"scalar",T:9}])),Re.makeMessageType("livekit.ListParticipantsResponse",(()=>[{no:1,name:"participants",kind:"message",T:ze,repeated:!0}])),Re.makeMessageType("livekit.RoomParticipantIdentity",(()=>[{no:1,name:"room",kind:"scalar",T:9},{no:2,name:"identity",kind:"scalar",T:9}])),Re.makeMessageType("livekit.RemoveParticipantResponse",[]),Re.makeMessageType("livekit.MuteRoomTrackRequest",(()=>[{no:1,name:"room",kind:"scalar",T:9},{no:2,name:"identity",kind:"scalar",T:9},{no:3,name:"track_sid",kind:"scalar",T:9},{no:4,name:"muted",kind:"scalar",T:8}])),Re.makeMessageType("livekit.MuteRoomTrackResponse",(()=>[{no:1,name:"track",kind:"message",T:$e}])),Re.makeMessageType("livekit.UpdateParticipantRequest",(()=>[{no:1,name:"room",kind:"scalar",T:9},{no:2,name:"identity",kind:"scalar",T:9},{no:3,name:"metadata",kind:"scalar",T:9},{no:4,name:"permission",kind:"message",T:Je},{no:5,name:"name",kind:"scalar",T:9}])),Re.makeMessageType("livekit.UpdateSubscriptionsRequest",(()=>[{no:1,name:"room",kind:"scalar",T:9},{no:2,name:"identity",kind:"scalar",T:9},{no:3,name:"track_sids",kind:"scalar",T:9,repeated:!0},{no:4,name:"subscribe",kind:"scalar",T:8},{no:5,name:"participant_tracks",kind:"message",T:rt,repeated:!0}])),Re.makeMessageType("livekit.UpdateSubscriptionsResponse",[]),Re.makeMessageType("livekit.SendDataRequest",(()=>[{no:1,name:"room",kind:"scalar",T:9},{no:2,name:"data",kind:"scalar",T:12},{no:3,name:"kind",kind:"enum",T:Re.getEnumType(nt)},{no:4,name:"destination_sids",kind:"scalar",T:9,repeated:!0},{no:6,name:"destination_identities",kind:"scalar",T:9,repeated:!0},{no:5,name:"topic",kind:"scalar",T:9,opt:!0}])),Re.makeMessageType("livekit.SendDataResponse",[]),Re.makeMessageType("livekit.UpdateRoomMetadataRequest",(()=>[{no:1,name:"room",kind:"scalar",T:9},{no:2,name:"metadata",kind:"scalar",T:9}]));const Qt=Re.makeEnum("livekit.JobType",[{no:0,name:"JT_ROOM"},{no:1,name:"JT_PUBLISHER"}]),Yt=Re.makeEnum("livekit.WorkerStatus",[{no:0,name:"WS_AVAILABLE"},{no:1,name:"WS_FULL"}]),Xt=Re.makeEnum("livekit.JobStatus",[{no:0,name:"JS_UNKNOWN"},{no:1,name:"JS_SUCCESS"},{no:2,name:"JS_FAILED"}]);Re.makeMessageType("livekit.AgentInfo",(()=>[{no:1,name:"id",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",T:9},{no:3,name:"version",kind:"scalar",T:9}]));const Zt=Re.makeMessageType("livekit.Job",(()=>[{no:1,name:"id",kind:"scalar",T:9},{no:2,name:"type",kind:"enum",T:Re.getEnumType(Qt)},{no:3,name:"room",kind:"message",T:We},{no:4,name:"participant",kind:"message",T:ze,opt:!0}]));Re.makeMessageType("livekit.WorkerMessage",(()=>[{no:1,name:"register",kind:"message",T:$t,oneof:"message"},{no:2,name:"availability",kind:"message",T:nn,oneof:"message"},{no:3,name:"status",kind:"message",T:an,oneof:"message"},{no:4,name:"job_update",kind:"message",T:sn,oneof:"message"}])),Re.makeMessageType("livekit.ServerMessage",(()=>[{no:1,name:"register",kind:"message",T:en,oneof:"message"},{no:2,name:"availability",kind:"message",T:tn,oneof:"message"},{no:3,name:"assignment",kind:"message",T:on,oneof:"message"}]));const $t=Re.makeMessageType("livekit.RegisterWorkerRequest",(()=>[{no:1,name:"type",kind:"enum",T:Re.getEnumType(Qt)},{no:2,name:"worker_id",kind:"scalar",T:9},{no:3,name:"version",kind:"scalar",T:9},{no:4,name:"name",kind:"scalar",T:9}])),en=Re.makeMessageType("livekit.RegisterWorkerResponse",(()=>[{no:1,name:"worker_id",kind:"scalar",T:9},{no:2,name:"server_version",kind:"scalar",T:9}])),tn=Re.makeMessageType("livekit.AvailabilityRequest",(()=>[{no:1,name:"job",kind:"message",T:Zt}])),nn=Re.makeMessageType("livekit.AvailabilityResponse",(()=>[{no:1,name:"job_id",kind:"scalar",T:9},{no:2,name:"available",kind:"scalar",T:8}])),sn=Re.makeMessageType("livekit.JobStatusUpdate",(()=>[{no:1,name:"job_id",kind:"scalar",T:9},{no:2,name:"status",kind:"enum",T:Re.getEnumType(Xt)},{no:3,name:"error",kind:"scalar",T:9},{no:4,name:"user_data",kind:"scalar",T:9}])),on=Re.makeMessageType("livekit.JobAssignment",(()=>[{no:1,name:"job",kind:"message",T:Zt}])),an=Re.makeMessageType("livekit.UpdateWorkerStatus",(()=>[{no:1,name:"status",kind:"enum",T:Re.getEnumType(Yt)}])),rn=Re.makeEnum("livekit.SignalTarget",[{no:0,name:"PUBLISHER"},{no:1,name:"SUBSCRIBER"}]),cn=Re.makeEnum("livekit.StreamState",[{no:0,name:"ACTIVE"},{no:1,name:"PAUSED"}]),dn=Re.makeEnum("livekit.CandidateProtocol",[{no:0,name:"UDP"},{no:1,name:"TCP"},{no:2,name:"TLS"}]),ln=Re.makeMessageType("livekit.SignalRequest",(()=>[{no:1,name:"offer",kind:"message",T:yn,oneof:"message"},{no:2,name:"answer",kind:"message",T:yn,oneof:"message"},{no:3,name:"trickle",kind:"message",T:pn,oneof:"message"},{no:4,name:"add_track",kind:"message",T:mn,oneof:"message"},{no:5,name:"mute",kind:"message",T:gn,oneof:"message"},{no:6,name:"subscription",kind:"message",T:Cn,oneof:"message"},{no:7,name:"track_setting",kind:"message",T:Sn,oneof:"message"},{no:8,name:"leave",kind:"message",T:En,oneof:"message"},{no:10,name:"update_layers",kind:"message",T:Pn,oneof:"message"},{no:11,name:"subscription_permission",kind:"message",T:Fn,oneof:"message"},{no:12,name:"sync_state",kind:"message",T:Vn,oneof:"message"},{no:13,name:"simulate",kind:"message",T:Kn,oneof:"message"},{no:14,name:"ping",kind:"scalar",T:3,oneof:"message"},{no:15,name:"update_metadata",kind:"message",T:Rn,oneof:"message"},{no:16,name:"ping_req",kind:"message",T:Gn,oneof:"message"}])),un=Re.makeMessageType("livekit.SignalResponse",(()=>[{no:1,name:"join",kind:"message",T:fn,oneof:"message"},{no:2,name:"answer",kind:"message",T:yn,oneof:"message"},{no:3,name:"offer",kind:"message",T:yn,oneof:"message"},{no:4,name:"trickle",kind:"message",T:pn,oneof:"message"},{no:5,name:"update",kind:"message",T:bn,oneof:"message"},{no:6,name:"track_published",kind:"message",T:kn,oneof:"message"},{no:8,name:"leave",kind:"message",T:En,oneof:"message"},{no:9,name:"mute",kind:"message",T:gn,oneof:"message"},{no:10,name:"speakers_changed",kind:"message",T:In,oneof:"message"},{no:11,name:"room_update",kind:"message",T:On,oneof:"message"},{no:12,name:"connection_quality",kind:"message",T:xn,oneof:"message"},{no:13,name:"stream_state_update",kind:"message",T:Nn,oneof:"message"},{no:14,name:"subscribed_quality_update",kind:"message",T:Un,oneof:"message"},{no:15,name:"subscription_permission_update",kind:"message",T:Bn,oneof:"message"},{no:16,name:"refresh_token",kind:"scalar",T:9,oneof:"message"},{no:17,name:"track_unpublished",kind:"message",T:Tn,oneof:"message"},{no:18,name:"pong",kind:"scalar",T:3,oneof:"message"},{no:19,name:"reconnect",kind:"message",T:vn,oneof:"message"},{no:20,name:"pong_resp",kind:"message",T:Wn,oneof:"message"},{no:21,name:"subscription_response",kind:"message",T:zn,oneof:"message"}])),hn=Re.makeMessageType("livekit.SimulcastCodec",(()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"cid",kind:"scalar",T:9}])),mn=Re.makeMessageType("livekit.AddTrackRequest",(()=>[{no:1,name:"cid",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",T:9},{no:3,name:"type",kind:"enum",T:Re.getEnumType(Ue)},{no:4,name:"width",kind:"scalar",T:13},{no:5,name:"height",kind:"scalar",T:13},{no:6,name:"muted",kind:"scalar",T:8},{no:7,name:"disable_dtx",kind:"scalar",T:8},{no:8,name:"source",kind:"enum",T:Re.getEnumType(je)},{no:9,name:"layers",kind:"message",T:et,repeated:!0},{no:10,name:"simulcast_codecs",kind:"message",T:hn,repeated:!0},{no:11,name:"sid",kind:"scalar",T:9},{no:12,name:"stereo",kind:"scalar",T:8},{no:13,name:"disable_red",kind:"scalar",T:8},{no:14,name:"encryption",kind:"enum",T:Re.getEnumType(Xe)},{no:15,name:"stream",kind:"scalar",T:9}])),pn=Re.makeMessageType("livekit.TrickleRequest",(()=>[{no:1,name:"candidateInit",kind:"scalar",T:9},{no:2,name:"target",kind:"enum",T:Re.getEnumType(rn)}])),gn=Re.makeMessageType("livekit.MuteTrackRequest",(()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"muted",kind:"scalar",T:8}])),fn=Re.makeMessageType("livekit.JoinResponse",(()=>[{no:1,name:"room",kind:"message",T:We},{no:2,name:"participant",kind:"message",T:ze},{no:3,name:"other_participants",kind:"message",T:ze,repeated:!0},{no:4,name:"server_version",kind:"scalar",T:9},{no:5,name:"ice_servers",kind:"message",T:_n,repeated:!0},{no:6,name:"subscriber_primary",kind:"scalar",T:8},{no:7,name:"alternative_url",kind:"scalar",T:9},{no:8,name:"client_configuration",kind:"message",T:ht},{no:9,name:"server_region",kind:"scalar",T:9},{no:10,name:"ping_timeout",kind:"scalar",T:5},{no:11,name:"ping_interval",kind:"scalar",T:5},{no:12,name:"server_info",kind:"message",T:ct},{no:13,name:"sif_trailer",kind:"scalar",T:12}])),vn=Re.makeMessageType("livekit.ReconnectResponse",(()=>[{no:1,name:"ice_servers",kind:"message",T:_n,repeated:!0},{no:2,name:"client_configuration",kind:"message",T:ht}])),kn=Re.makeMessageType("livekit.TrackPublishedResponse",(()=>[{no:1,name:"cid",kind:"scalar",T:9},{no:2,name:"track",kind:"message",T:$e}])),Tn=Re.makeMessageType("livekit.TrackUnpublishedResponse",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9}])),yn=Re.makeMessageType("livekit.SessionDescription",(()=>[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"sdp",kind:"scalar",T:9}])),bn=Re.makeMessageType("livekit.ParticipantUpdate",(()=>[{no:1,name:"participants",kind:"message",T:ze,repeated:!0}])),Cn=Re.makeMessageType("livekit.UpdateSubscription",(()=>[{no:1,name:"track_sids",kind:"scalar",T:9,repeated:!0},{no:2,name:"subscribe",kind:"scalar",T:8},{no:3,name:"participant_tracks",kind:"message",T:rt,repeated:!0}])),Sn=Re.makeMessageType("livekit.UpdateTrackSettings",(()=>[{no:1,name:"track_sids",kind:"scalar",T:9,repeated:!0},{no:3,name:"disabled",kind:"scalar",T:8},{no:4,name:"quality",kind:"enum",T:Re.getEnumType(Fe)},{no:5,name:"width",kind:"scalar",T:13},{no:6,name:"height",kind:"scalar",T:13},{no:7,name:"fps",kind:"scalar",T:13},{no:8,name:"priority",kind:"scalar",T:13}])),En=Re.makeMessageType("livekit.LeaveRequest",(()=>[{no:1,name:"can_reconnect",kind:"scalar",T:8},{no:2,name:"reason",kind:"enum",T:Re.getEnumType(qe)},{no:3,name:"action",kind:"enum",T:Re.getEnumType(wn)},{no:4,name:"regions",kind:"message",T:Hn}])),wn=Re.makeEnum("livekit.LeaveRequest.Action",[{no:0,name:"DISCONNECT"},{no:1,name:"RESUME"},{no:2,name:"RECONNECT"}]),Pn=Re.makeMessageType("livekit.UpdateVideoLayers",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"layers",kind:"message",T:et,repeated:!0}])),Rn=Re.makeMessageType("livekit.UpdateParticipantMetadata",(()=>[{no:1,name:"metadata",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",T:9}])),_n=Re.makeMessageType("livekit.ICEServer",(()=>[{no:1,name:"urls",kind:"scalar",T:9,repeated:!0},{no:2,name:"username",kind:"scalar",T:9},{no:3,name:"credential",kind:"scalar",T:9}])),In=Re.makeMessageType("livekit.SpeakersChanged",(()=>[{no:1,name:"speakers",kind:"message",T:st,repeated:!0}])),On=Re.makeMessageType("livekit.RoomUpdate",(()=>[{no:1,name:"room",kind:"message",T:We}])),Mn=Re.makeMessageType("livekit.ConnectionQualityInfo",(()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"quality",kind:"enum",T:Re.getEnumType(Be)},{no:3,name:"score",kind:"scalar",T:2}])),xn=Re.makeMessageType("livekit.ConnectionQualityUpdate",(()=>[{no:1,name:"updates",kind:"message",T:Mn,repeated:!0}])),Dn=Re.makeMessageType("livekit.StreamStateInfo",(()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"track_sid",kind:"scalar",T:9},{no:3,name:"state",kind:"enum",T:Re.getEnumType(cn)}])),Nn=Re.makeMessageType("livekit.StreamStateUpdate",(()=>[{no:1,name:"stream_states",kind:"message",T:Dn,repeated:!0}])),Ln=Re.makeMessageType("livekit.SubscribedQuality",(()=>[{no:1,name:"quality",kind:"enum",T:Re.getEnumType(Fe)},{no:2,name:"enabled",kind:"scalar",T:8}])),An=Re.makeMessageType("livekit.SubscribedCodec",(()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"qualities",kind:"message",T:Ln,repeated:!0}])),Un=Re.makeMessageType("livekit.SubscribedQualityUpdate",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribed_qualities",kind:"message",T:Ln,repeated:!0},{no:3,name:"subscribed_codecs",kind:"message",T:An,repeated:!0}])),jn=Re.makeMessageType("livekit.TrackPermission",(()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"all_tracks",kind:"scalar",T:8},{no:3,name:"track_sids",kind:"scalar",T:9,repeated:!0},{no:4,name:"participant_identity",kind:"scalar",T:9}])),Fn=Re.makeMessageType("livekit.SubscriptionPermission",(()=>[{no:1,name:"all_participants",kind:"scalar",T:8},{no:2,name:"track_permissions",kind:"message",T:jn,repeated:!0}])),Bn=Re.makeMessageType("livekit.SubscriptionPermissionUpdate",(()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"track_sid",kind:"scalar",T:9},{no:3,name:"allowed",kind:"scalar",T:8}])),Vn=Re.makeMessageType("livekit.SyncState",(()=>[{no:1,name:"answer",kind:"message",T:yn},{no:2,name:"subscription",kind:"message",T:Cn},{no:3,name:"publish_tracks",kind:"message",T:kn,repeated:!0},{no:4,name:"data_channels",kind:"message",T:qn,repeated:!0},{no:5,name:"offer",kind:"message",T:yn},{no:6,name:"track_sids_disabled",kind:"scalar",T:9,repeated:!0}])),qn=Re.makeMessageType("livekit.DataChannelInfo",(()=>[{no:1,name:"label",kind:"scalar",T:9},{no:2,name:"id",kind:"scalar",T:13},{no:3,name:"target",kind:"enum",T:Re.getEnumType(rn)}])),Kn=Re.makeMessageType("livekit.SimulateScenario",(()=>[{no:1,name:"speaker_update",kind:"scalar",T:5,oneof:"scenario"},{no:2,name:"node_failure",kind:"scalar",T:8,oneof:"scenario"},{no:3,name:"migration",kind:"scalar",T:8,oneof:"scenario"},{no:4,name:"server_leave",kind:"scalar",T:8,oneof:"scenario"},{no:5,name:"switch_candidate_protocol",kind:"enum",T:Re.getEnumType(dn),oneof:"scenario"},{no:6,name:"subscriber_bandwidth",kind:"scalar",T:3,oneof:"scenario"},{no:7,name:"disconnect_signal_on_resume",kind:"scalar",T:8,oneof:"scenario"},{no:8,name:"disconnect_signal_on_resume_no_messages",kind:"scalar",T:8,oneof:"scenario"}])),Gn=Re.makeMessageType("livekit.Ping",(()=>[{no:1,name:"timestamp",kind:"scalar",T:3},{no:2,name:"rtt",kind:"scalar",T:3}])),Wn=Re.makeMessageType("livekit.Pong",(()=>[{no:1,name:"last_ping_timestamp",kind:"scalar",T:3},{no:2,name:"timestamp",kind:"scalar",T:3}])),Hn=Re.makeMessageType("livekit.RegionSettings",(()=>[{no:1,name:"regions",kind:"message",T:Jn,repeated:!0}])),Jn=Re.makeMessageType("livekit.RegionInfo",(()=>[{no:1,name:"region",kind:"scalar",T:9},{no:2,name:"url",kind:"scalar",T:9},{no:3,name:"distance",kind:"scalar",T:3}])),zn=Re.makeMessageType("livekit.SubscriptionResponse",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"err",kind:"enum",T:Re.getEnumType(Ge)}])),Qn=Re.makeEnum("livekit.IngressInput",[{no:0,name:"RTMP_INPUT"},{no:1,name:"WHIP_INPUT"},{no:2,name:"URL_INPUT"}]),Yn=Re.makeEnum("livekit.IngressAudioEncodingPreset",[{no:0,name:"OPUS_STEREO_96KBPS"},{no:1,name:"OPUS_MONO_64KBS"}]),Xn=Re.makeEnum("livekit.IngressVideoEncodingPreset",[{no:0,name:"H264_720P_30FPS_3_LAYERS"},{no:1,name:"H264_1080P_30FPS_3_LAYERS"},{no:2,name:"H264_540P_25FPS_2_LAYERS"},{no:3,name:"H264_720P_30FPS_1_LAYER"},{no:4,name:"H264_1080P_30FPS_1_LAYER"},{no:5,name:"H264_720P_30FPS_3_LAYERS_HIGH_MOTION"},{no:6,name:"H264_1080P_30FPS_3_LAYERS_HIGH_MOTION"},{no:7,name:"H264_540P_25FPS_2_LAYERS_HIGH_MOTION"},{no:8,name:"H264_720P_30FPS_1_LAYER_HIGH_MOTION"},{no:9,name:"H264_1080P_30FPS_1_LAYER_HIGH_MOTION"}]);Re.makeMessageType("livekit.CreateIngressRequest",(()=>[{no:1,name:"input_type",kind:"enum",T:Re.getEnumType(Qn)},{no:9,name:"url",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",T:9},{no:3,name:"room_name",kind:"scalar",T:9},{no:4,name:"participant_identity",kind:"scalar",T:9},{no:5,name:"participant_name",kind:"scalar",T:9},{no:10,name:"participant_metadata",kind:"scalar",T:9},{no:8,name:"bypass_transcoding",kind:"scalar",T:8},{no:6,name:"audio",kind:"message",T:Zn},{no:7,name:"video",kind:"message",T:$n}]));const Zn=Re.makeMessageType("livekit.IngressAudioOptions",(()=>[{no:1,name:"name",kind:"scalar",T:9},{no:2,name:"source",kind:"enum",T:Re.getEnumType(je)},{no:3,name:"preset",kind:"enum",T:Re.getEnumType(Yn),oneof:"encoding_options"},{no:4,name:"options",kind:"message",T:ei,oneof:"encoding_options"}])),$n=Re.makeMessageType("livekit.IngressVideoOptions",(()=>[{no:1,name:"name",kind:"scalar",T:9},{no:2,name:"source",kind:"enum",T:Re.getEnumType(je)},{no:3,name:"preset",kind:"enum",T:Re.getEnumType(Xn),oneof:"encoding_options"},{no:4,name:"options",kind:"message",T:ti,oneof:"encoding_options"}])),ei=Re.makeMessageType("livekit.IngressAudioEncodingOptions",(()=>[{no:1,name:"audio_codec",kind:"enum",T:Re.getEnumType(Ne)},{no:2,name:"bitrate",kind:"scalar",T:13},{no:3,name:"disable_dtx",kind:"scalar",T:8},{no:4,name:"channels",kind:"scalar",T:13}])),ti=Re.makeMessageType("livekit.IngressVideoEncodingOptions",(()=>[{no:1,name:"video_codec",kind:"enum",T:Re.getEnumType(Le)},{no:2,name:"frame_rate",kind:"scalar",T:1},{no:3,name:"layers",kind:"message",T:et,repeated:!0}])),ni=Re.makeMessageType("livekit.IngressInfo",(()=>[{no:1,name:"ingress_id",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",T:9},{no:3,name:"stream_key",kind:"scalar",T:9},{no:4,name:"url",kind:"scalar",T:9},{no:5,name:"input_type",kind:"enum",T:Re.getEnumType(Qn)},{no:13,name:"bypass_transcoding",kind:"scalar",T:8},{no:6,name:"audio",kind:"message",T:Zn},{no:7,name:"video",kind:"message",T:$n},{no:8,name:"room_name",kind:"scalar",T:9},{no:9,name:"participant_identity",kind:"scalar",T:9},{no:10,name:"participant_name",kind:"scalar",T:9},{no:14,name:"participant_metadata",kind:"scalar",T:9},{no:11,name:"reusable",kind:"scalar",T:8},{no:12,name:"state",kind:"message",T:ii}])),ii=Re.makeMessageType("livekit.IngressState",(()=>[{no:1,name:"status",kind:"enum",T:Re.getEnumType(si)},{no:2,name:"error",kind:"scalar",T:9},{no:3,name:"video",kind:"message",T:oi},{no:4,name:"audio",kind:"message",T:ai},{no:5,name:"room_id",kind:"scalar",T:9},{no:7,name:"started_at",kind:"scalar",T:3},{no:8,name:"ended_at",kind:"scalar",T:3},{no:9,name:"resource_id",kind:"scalar",T:9},{no:6,name:"tracks",kind:"message",T:$e,repeated:!0}])),si=Re.makeEnum("livekit.IngressState.Status",[{no:0,name:"ENDPOINT_INACTIVE"},{no:1,name:"ENDPOINT_BUFFERING"},{no:2,name:"ENDPOINT_PUBLISHING"},{no:3,name:"ENDPOINT_ERROR"},{no:4,name:"ENDPOINT_COMPLETE"}]),oi=Re.makeMessageType("livekit.InputVideoState",(()=>[{no:1,name:"mime_type",kind:"scalar",T:9},{no:2,name:"average_bitrate",kind:"scalar",T:13},{no:3,name:"width",kind:"scalar",T:13},{no:4,name:"height",kind:"scalar",T:13},{no:5,name:"framerate",kind:"scalar",T:1}])),ai=Re.makeMessageType("livekit.InputAudioState",(()=>[{no:1,name:"mime_type",kind:"scalar",T:9},{no:2,name:"average_bitrate",kind:"scalar",T:13},{no:3,name:"channels",kind:"scalar",T:13},{no:4,name:"sample_rate",kind:"scalar",T:13}]));Re.makeMessageType("livekit.UpdateIngressRequest",(()=>[{no:1,name:"ingress_id",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",T:9},{no:3,name:"room_name",kind:"scalar",T:9},{no:4,name:"participant_identity",kind:"scalar",T:9},{no:5,name:"participant_name",kind:"scalar",T:9},{no:9,name:"participant_metadata",kind:"scalar",T:9},{no:8,name:"bypass_transcoding",kind:"scalar",T:8,opt:!0},{no:6,name:"audio",kind:"message",T:Zn},{no:7,name:"video",kind:"message",T:$n}])),Re.makeMessageType("livekit.ListIngressRequest",(()=>[{no:1,name:"room_name",kind:"scalar",T:9},{no:2,name:"ingress_id",kind:"scalar",T:9}])),Re.makeMessageType("livekit.ListIngressResponse",(()=>[{no:1,name:"items",kind:"message",T:ni,repeated:!0}])),Re.makeMessageType("livekit.DeleteIngressRequest",(()=>[{no:1,name:"ingress_id",kind:"scalar",T:9}])),Re.makeMessageType("livekit.WebhookEvent",(()=>[{no:1,name:"event",kind:"scalar",T:9},{no:2,name:"room",kind:"message",T:We},{no:3,name:"participant",kind:"message",T:ze},{no:9,name:"egress_info",kind:"message",T:Ft},{no:10,name:"ingress_info",kind:"message",T:ni},{no:8,name:"track",kind:"message",T:$e},{no:6,name:"id",kind:"scalar",T:9},{no:7,name:"created_at",kind:"scalar",T:3},{no:11,name:"num_dropped",kind:"scalar",T:5}])),Re.makeMessageType("livekit.CreateSIPTrunkRequest",(()=>[{no:1,name:"inbound_addresses",kind:"scalar",T:9,repeated:!0},{no:2,name:"outbound_address",kind:"scalar",T:9},{no:3,name:"outbound_number",kind:"scalar",T:9},{no:4,name:"inbound_numbers_regex",kind:"scalar",T:9,repeated:!0},{no:9,name:"inbound_numbers",kind:"scalar",T:9,repeated:!0},{no:5,name:"inbound_username",kind:"scalar",T:9},{no:6,name:"inbound_password",kind:"scalar",T:9},{no:7,name:"outbound_username",kind:"scalar",T:9},{no:8,name:"outbound_password",kind:"scalar",T:9}]));const ri=Re.makeMessageType("livekit.SIPTrunkInfo",(()=>[{no:1,name:"sip_trunk_id",kind:"scalar",T:9},{no:2,name:"inbound_addresses",kind:"scalar",T:9,repeated:!0},{no:3,name:"outbound_address",kind:"scalar",T:9},{no:4,name:"outbound_number",kind:"scalar",T:9},{no:5,name:"inbound_numbers_regex",kind:"scalar",T:9,repeated:!0},{no:10,name:"inbound_numbers",kind:"scalar",T:9,repeated:!0},{no:6,name:"inbound_username",kind:"scalar",T:9},{no:7,name:"inbound_password",kind:"scalar",T:9},{no:8,name:"outbound_username",kind:"scalar",T:9},{no:9,name:"outbound_password",kind:"scalar",T:9}]));Re.makeMessageType("livekit.ListSIPTrunkRequest",[]),Re.makeMessageType("livekit.ListSIPTrunkResponse",(()=>[{no:1,name:"items",kind:"message",T:ri,repeated:!0}])),Re.makeMessageType("livekit.DeleteSIPTrunkRequest",(()=>[{no:1,name:"sip_trunk_id",kind:"scalar",T:9}]));const ci=Re.makeMessageType("livekit.SIPDispatchRuleDirect",(()=>[{no:1,name:"room_name",kind:"scalar",T:9},{no:2,name:"pin",kind:"scalar",T:9}])),di=Re.makeMessageType("livekit.SIPDispatchRuleIndividual",(()=>[{no:1,name:"room_prefix",kind:"scalar",T:9},{no:2,name:"pin",kind:"scalar",T:9}])),li=Re.makeMessageType("livekit.SIPDispatchRule",(()=>[{no:1,name:"dispatch_rule_direct",kind:"message",T:ci,oneof:"rule"},{no:2,name:"dispatch_rule_individual",kind:"message",T:di,oneof:"rule"}]));Re.makeMessageType("livekit.CreateSIPDispatchRuleRequest",(()=>[{no:1,name:"rule",kind:"message",T:li},{no:2,name:"trunk_ids",kind:"scalar",T:9,repeated:!0},{no:3,name:"hide_phone_number",kind:"scalar",T:8}]));const ui=Re.makeMessageType("livekit.SIPDispatchRuleInfo",(()=>[{no:1,name:"sip_dispatch_rule_id",kind:"scalar",T:9},{no:2,name:"rule",kind:"message",T:li},{no:3,name:"trunk_ids",kind:"scalar",T:9,repeated:!0},{no:4,name:"hide_phone_number",kind:"scalar",T:8}]));Re.makeMessageType("livekit.ListSIPDispatchRuleRequest",[]),Re.makeMessageType("livekit.ListSIPDispatchRuleResponse",(()=>[{no:1,name:"items",kind:"message",T:ui,repeated:!0}])),Re.makeMessageType("livekit.DeleteSIPDispatchRuleRequest",(()=>[{no:1,name:"sip_dispatch_rule_id",kind:"scalar",T:9}])),Re.makeMessageType("livekit.CreateSIPParticipantRequest",(()=>[{no:1,name:"sip_trunk_id",kind:"scalar",T:9},{no:2,name:"sip_call_to",kind:"scalar",T:9},{no:3,name:"room_name",kind:"scalar",T:9},{no:4,name:"participant_identity",kind:"scalar",T:9}])),Re.makeMessageType("livekit.SIPParticipantInfo",(()=>[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"participant_identity",kind:"scalar",T:9},{no:3,name:"room_name",kind:"scalar",T:9}]));var hi="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function mi(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var pi={exports:{}};!function(e){var t,n;t=hi,n=function(){var e=function(){},t="undefined",n=typeof window!==t&&typeof window.navigator!==t&&/Trident\/|MSIE /.test(window.navigator.userAgent),i=["trace","debug","info","warn","error"];function s(e,t){var n=e[t];if("function"==typeof n.bind)return n.bind(e);try{return Function.prototype.bind.call(n,e)}catch(t){return function(){return Function.prototype.apply.apply(n,[e,arguments])}}}function o(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function a(t,n){for(var s=0;s<i.length;s++){var o=i[s];this[o]=s<t?e:this.methodFactory(o,t,n)}this.log=this.debug}function r(e,n,i){return function(){typeof console!==t&&(a.call(this,n,i),this[e].apply(this,arguments))}}function c(i,a,c){return function(i){return"debug"===i&&(i="log"),typeof console!==t&&("trace"===i&&n?o:void 0!==console[i]?s(console,i):void 0!==console.log?s(console,"log"):e)}(i)||r.apply(this,arguments)}function d(e,n,s){var o,r=this;n=null==n?"WARN":n;var d="loglevel";function l(){var e;if(typeof window!==t&&d){try{e=window.localStorage[d]}catch(e){}if(typeof e===t)try{var n=window.document.cookie,i=n.indexOf(encodeURIComponent(d)+"=");-1!==i&&(e=/^([^;]+)/.exec(n.slice(i))[1])}catch(e){}return void 0===r.levels[e]&&(e=void 0),e}}"string"==typeof e?d+=":"+e:"symbol"==typeof e&&(d=void 0),r.name=e,r.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},r.methodFactory=s||c,r.getLevel=function(){return o},r.setLevel=function(n,s){if("string"==typeof n&&void 0!==r.levels[n.toUpperCase()]&&(n=r.levels[n.toUpperCase()]),!("number"==typeof n&&n>=0&&n<=r.levels.SILENT))throw"log.setLevel() called with invalid level: "+n;if(o=n,!1!==s&&function(e){var n=(i[e]||"silent").toUpperCase();if(typeof window!==t&&d){try{return void(window.localStorage[d]=n)}catch(e){}try{window.document.cookie=encodeURIComponent(d)+"="+n+";"}catch(e){}}}(n),a.call(r,n,e),typeof console===t&&n<r.levels.SILENT)return"No console available for logging"},r.setDefaultLevel=function(e){n=e,l()||r.setLevel(e,!1)},r.resetLevel=function(){r.setLevel(n,!1),function(){if(typeof window!==t&&d){try{return void window.localStorage.removeItem(d)}catch(e){}try{window.document.cookie=encodeURIComponent(d)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch(e){}}}()},r.enableAll=function(e){r.setLevel(r.levels.TRACE,e)},r.disableAll=function(e){r.setLevel(r.levels.SILENT,e)};var u=l();null==u&&(u=n),r.setLevel(u,!1)}var l=new d,u={};l.getLogger=function(e){if("symbol"!=typeof e&&"string"!=typeof e||""===e)throw new TypeError("You must supply a name when creating a logger.");var t=u[e];return t||(t=u[e]=new d(e,l.getLevel(),l.methodFactory)),t};var h=typeof window!==t?window.log:void 0;return l.noConflict=function(){return typeof window!==t&&window.log===l&&(window.log=h),l},l.getLoggers=function(){return u},l.default=l,l},e.exports?e.exports=n():t.log=n()}(pi);var gi,fi,vi=pi.exports;e.LogLevel=void 0,(gi=e.LogLevel||(e.LogLevel={}))[gi.trace=0]="trace",gi[gi.debug=1]="debug",gi[gi.info=2]="info",gi[gi.warn=3]="warn",gi[gi.error=4]="error",gi[gi.silent=5]="silent",e.LoggerNames=void 0,(fi=e.LoggerNames||(e.LoggerNames={})).Default="livekit",fi.Room="livekit-room",fi.Participant="livekit-participant",fi.Track="livekit-track",fi.Publication="livekit-track-publication",fi.Engine="livekit-engine",fi.Signal="livekit-signal",fi.PCManager="livekit-pc-manager",fi.PCTransport="livekit-pc-transport",fi.E2EE="lk-e2ee";let ki=vi.getLogger("livekit");const Ti=Object.values(e.LoggerNames).map((e=>vi.getLogger(e)));function yi(e){const t=vi.getLogger(e);return t.setDefaultLevel(ki.getLevel()),t}ki.setDefaultLevel(e.LogLevel.info);const bi=vi.getLogger("lk-e2ee"),Ci=7e3,Si=[0,300,1200,2700,4800,Ci,Ci,Ci,Ci,Ci];class Ei{constructor(e){this._retryDelays=void 0!==e?[...e]:Si}nextRetryDelayInMs(e){if(e.retryCount>=this._retryDelays.length)return null;const t=this._retryDelays[e.retryCount];return e.retryCount<=1?t:t+1e3*Math.random()}}function wi(e,t,n,i){return new(n||(n=Promise))((function(s,o){function a(e){try{c(i.next(e))}catch(e){o(e)}}function r(e){try{c(i.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?s(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(a,r)}c((i=i.apply(e,t||[])).next())}))}function Pi(e){var t="function"==typeof Symbol&&Symbol.iterator,n=t&&e[t],i=0;if(n)return n.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&i>=e.length&&(e=void 0),{value:e&&e[i++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function Ri(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t,n=e[Symbol.asyncIterator];return n?n.call(e):(e=Pi(e),t={},i("next"),i("throw"),i("return"),t[Symbol.asyncIterator]=function(){return this},t);function i(n){t[n]=e[n]&&function(t){return new Promise((function(i,s){(function(e,t,n,i){Promise.resolve(i).then((function(t){e({value:t,done:n})}),t)})(i,s,(t=e[n](t)).done,t.value)}))}}}"function"==typeof SuppressedError&&SuppressedError;var _i,Ii={exports:{}},Oi="object"==typeof Reflect?Reflect:null,Mi=Oi&&"function"==typeof Oi.apply?Oi.apply:function(e,t,n){return Function.prototype.apply.call(e,t,n)};_i=Oi&&"function"==typeof Oi.ownKeys?Oi.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var xi=Number.isNaN||function(e){return e!=e};function Di(){Di.init.call(this)}Ii.exports=Di,Ii.exports.once=function(e,t){return new Promise((function(n,i){function s(n){e.removeListener(t,o),i(n)}function o(){"function"==typeof e.removeListener&&e.removeListener("error",s),n([].slice.call(arguments))}Ki(e,t,o,{once:!0}),"error"!==t&&function(e,t,n){"function"==typeof e.on&&Ki(e,"error",t,n)}(e,s,{once:!0})}))},Di.EventEmitter=Di,Di.prototype._events=void 0,Di.prototype._eventsCount=0,Di.prototype._maxListeners=void 0;var Ni=10;function Li(e){if("function"!=typeof e)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function Ai(e){return void 0===e._maxListeners?Di.defaultMaxListeners:e._maxListeners}function Ui(e,t,n,i){var s,o,a,r;if(Li(n),void 0===(o=e._events)?(o=e._events=Object.create(null),e._eventsCount=0):(void 0!==o.newListener&&(e.emit("newListener",t,n.listener?n.listener:n),o=e._events),a=o[t]),void 0===a)a=o[t]=n,++e._eventsCount;else if("function"==typeof a?a=o[t]=i?[n,a]:[a,n]:i?a.unshift(n):a.push(n),(s=Ai(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,r=c,console&&console.warn&&console.warn(r)}return e}function ji(){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 Fi(e,t,n){var i={fired:!1,wrapFn:void 0,target:e,type:t,listener:n},s=ji.bind(i);return s.listener=n,i.wrapFn=s,s}function Bi(e,t,n){var i=e._events;if(void 0===i)return[];var s=i[t];return void 0===s?[]:"function"==typeof s?n?[s.listener||s]:[s]:n?function(e){for(var t=new Array(e.length),n=0;n<t.length;++n)t[n]=e[n].listener||e[n];return t}(s):qi(s,s.length)}function Vi(e){var t=this._events;if(void 0!==t){var n=t[e];if("function"==typeof n)return 1;if(void 0!==n)return n.length}return 0}function qi(e,t){for(var n=new Array(t),i=0;i<t;++i)n[i]=e[i];return n}function Ki(e,t,n,i){if("function"==typeof e.on)i.once?e.once(t,n):e.on(t,n);else{if("function"!=typeof e.addEventListener)throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof e);e.addEventListener(t,(function s(o){i.once&&e.removeEventListener(t,s),n(o)}))}}Object.defineProperty(Di,"defaultMaxListeners",{enumerable:!0,get:function(){return Ni},set:function(e){if("number"!=typeof e||e<0||xi(e))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+e+".");Ni=e}}),Di.init=function(){void 0!==this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},Di.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||xi(e))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this},Di.prototype.getMaxListeners=function(){return Ai(this)},Di.prototype.emit=function(e){for(var t=[],n=1;n<arguments.length;n++)t.push(arguments[n]);var i="error"===e,s=this._events;if(void 0!==s)i=i&&void 0===s.error;else if(!i)return!1;if(i){var o;if(t.length>0&&(o=t[0]),o instanceof Error)throw o;var a=new Error("Unhandled error."+(o?" ("+o.message+")":""));throw a.context=o,a}var r=s[e];if(void 0===r)return!1;if("function"==typeof r)Mi(r,this,t);else{var c=r.length,d=qi(r,c);for(n=0;n<c;++n)Mi(d[n],this,t)}return!0},Di.prototype.addListener=function(e,t){return Ui(this,e,t,!1)},Di.prototype.on=Di.prototype.addListener,Di.prototype.prependListener=function(e,t){return Ui(this,e,t,!0)},Di.prototype.once=function(e,t){return Li(t),this.on(e,Fi(this,e,t)),this},Di.prototype.prependOnceListener=function(e,t){return Li(t),this.prependListener(e,Fi(this,e,t)),this},Di.prototype.removeListener=function(e,t){var n,i,s,o,a;if(Li(t),void 0===(i=this._events))return this;if(void 0===(n=i[e]))return this;if(n===t||n.listener===t)0==--this._eventsCount?this._events=Object.create(null):(delete i[e],i.removeListener&&this.emit("removeListener",e,n.listener||t));else if("function"!=typeof n){for(s=-1,o=n.length-1;o>=0;o--)if(n[o]===t||n[o].listener===t){a=n[o].listener,s=o;break}if(s<0)return this;0===s?n.shift():function(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}(n,s),1===n.length&&(i[e]=n[0]),void 0!==i.removeListener&&this.emit("removeListener",e,a||t)}return this},Di.prototype.off=Di.prototype.removeListener,Di.prototype.removeAllListeners=function(e){var t,n,i;if(void 0===(n=this._events))return this;if(void 0===n.removeListener)return 0===arguments.length?(this._events=Object.create(null),this._eventsCount=0):void 0!==n[e]&&(0==--this._eventsCount?this._events=Object.create(null):delete n[e]),this;if(0===arguments.length){var s,o=Object.keys(n);for(i=0;i<o.length;++i)"removeListener"!==(s=o[i])&&this.removeAllListeners(s);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if("function"==typeof(t=n[e]))this.removeListener(e,t);else if(void 0!==t)for(i=t.length-1;i>=0;i--)this.removeListener(e,t[i]);return this},Di.prototype.listeners=function(e){return Bi(this,e,!0)},Di.prototype.rawListeners=function(e){return Bi(this,e,!1)},Di.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):Vi.call(e,t)},Di.prototype.listenerCount=Vi,Di.prototype.eventNames=function(){return this._eventsCount>0?_i(this._events):[]};var Gi=Ii.exports;let Wi=!0,Hi=!0;function Ji(e,t,n){const i=e.match(t);return i&&i.length>=n&&parseInt(i[n],10)}function zi(e,t,n){if(!e.RTCPeerConnection)return;const i=e.RTCPeerConnection.prototype,s=i.addEventListener;i.addEventListener=function(e,i){if(e!==t)return s.apply(this,arguments);const o=e=>{const t=n(e);t&&(i.handleEvent?i.handleEvent(t):i(t))};return this._eventMap=this._eventMap||{},this._eventMap[t]||(this._eventMap[t]=new Map),this._eventMap[t].set(i,o),s.apply(this,[e,o])};const o=i.removeEventListener;i.removeEventListener=function(e,n){if(e!==t||!this._eventMap||!this._eventMap[t])return o.apply(this,arguments);if(!this._eventMap[t].has(n))return o.apply(this,arguments);const i=this._eventMap[t].get(n);return this._eventMap[t].delete(n),0===this._eventMap[t].size&&delete this._eventMap[t],0===Object.keys(this._eventMap).length&&delete this._eventMap,o.apply(this,[e,i])},Object.defineProperty(i,"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 Qi(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(Wi=e,e?"adapter.js logging disabled":"adapter.js logging enabled")}function Yi(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(Hi=!e,"adapter.js deprecation warnings "+(e?"disabled":"enabled"))}function Xi(){if("object"==typeof window){if(Wi)return;"undefined"!=typeof console&&"function"==typeof console.log&&console.log.apply(console,arguments)}}function Zi(e,t){Hi&&console.warn(e+" is deprecated, please use "+t+" instead.")}function $i(e){return"[object Object]"===Object.prototype.toString.call(e)}function es(e){return $i(e)?Object.keys(e).reduce((function(t,n){const i=$i(e[n]),s=i?es(e[n]):e[n],o=i&&!Object.keys(s).length;return void 0===s||o?t:Object.assign(t,{[n]:s})}),{}):e}function ts(e,t,n){t&&!n.has(t.id)&&(n.set(t.id,t),Object.keys(t).forEach((i=>{i.endsWith("Id")?ts(e,e.get(t[i]),n):i.endsWith("Ids")&&t[i].forEach((t=>{ts(e,e.get(t),n)}))})))}function ns(e,t,n){const i=n?"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((n=>{n.type===i&&n.trackId===t.id&&ts(e,n,s)}))})),s}const is=Xi;function ss(e,t){const n=e&&e.navigator;if(!n.mediaDevices)return;const i=function(e){if("object"!=typeof e||e.mandatory||e.optional)return e;const t={};return Object.keys(e).forEach((n=>{if("require"===n||"advanced"===n||"mediaSource"===n)return;const i="object"==typeof e[n]?e[n]:{ideal:e[n]};void 0!==i.exact&&"number"==typeof i.exact&&(i.min=i.max=i.exact);const s=function(e,t){return e?e+t.charAt(0).toUpperCase()+t.slice(1):"deviceId"===t?"sourceId":t};if(void 0!==i.ideal){t.optional=t.optional||[];let e={};"number"==typeof i.ideal?(e[s("min",n)]=i.ideal,t.optional.push(e),e={},e[s("max",n)]=i.ideal,t.optional.push(e)):(e[s("",n)]=i.ideal,t.optional.push(e))}void 0!==i.exact&&"number"!=typeof i.exact?(t.mandatory=t.mandatory||{},t.mandatory[s("",n)]=i.exact):["min","max"].forEach((e=>{void 0!==i[e]&&(t.mandatory=t.mandatory||{},t.mandatory[s(e,n)]=i[e])}))})),e.advanced&&(t.optional=(t.optional||[]).concat(e.advanced)),t},s=function(e,s){if(t.version>=61)return s(e);if((e=JSON.parse(JSON.stringify(e)))&&"object"==typeof e.audio){const t=function(e,t,n){t in e&&!(n in e)&&(e[n]=e[t],delete e[t])};t((e=JSON.parse(JSON.stringify(e))).audio,"autoGainControl","googAutoGainControl"),t(e.audio,"noiseSuppression","googNoiseSuppression"),e.audio=i(e.audio)}if(e&&"object"==typeof e.video){let o=e.video.facingMode;o=o&&("object"==typeof o?o:{ideal:o});const a=t.version<66;if(o&&("user"===o.exact||"environment"===o.exact||"user"===o.ideal||"environment"===o.ideal)&&(!n.mediaDevices.getSupportedConstraints||!n.mediaDevices.getSupportedConstraints().facingMode||a)){let t;if(delete e.video.facingMode,"environment"===o.exact||"environment"===o.ideal?t=["back","rear"]:"user"!==o.exact&&"user"!==o.ideal||(t=["front"]),t)return n.mediaDevices.enumerateDevices().then((n=>{let a=(n=n.filter((e=>"videoinput"===e.kind))).find((e=>t.some((t=>e.label.toLowerCase().includes(t)))));return!a&&n.length&&t.includes("back")&&(a=n[n.length-1]),a&&(e.video.deviceId=o.exact?{exact:a.deviceId}:{ideal:a.deviceId}),e.video=i(e.video),is("chrome: "+JSON.stringify(e)),s(e)}))}e.video=i(e.video)}return is("chrome: "+JSON.stringify(e)),s(e)},o=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(n.getUserMedia=function(e,t,i){s(e,(e=>{n.webkitGetUserMedia(e,t,(e=>{i&&i(o(e))}))}))}.bind(n),n.mediaDevices.getUserMedia){const e=n.mediaDevices.getUserMedia.bind(n.mediaDevices);n.mediaDevices.getUserMedia=function(t){return s(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(o(e))))))}}}function os(e){e.MediaStream=e.MediaStream||e.webkitMediaStream}function as(e){if("object"==typeof e&&e.RTCPeerConnection&&!("ontrack"in e.RTCPeerConnection.prototype)){Object.defineProperty(e.RTCPeerConnection.prototype,"ontrack",{get(){return this._ontrack},set(e){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=e)},enumerable:!0,configurable:!0});const t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=t=>{t.stream.addEventListener("addtrack",(n=>{let i;i=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find((e=>e.track&&e.track.id===n.track.id)):{track:n.track};const s=new Event("track");s.track=n.track,s.receiver=i,s.transceiver={receiver:i},s.streams=[t.stream],this.dispatchEvent(s)})),t.stream.getTracks().forEach((n=>{let i;i=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find((e=>e.track&&e.track.id===n.id)):{track:n};const s=new Event("track");s.track=n,s.receiver=i,s.transceiver={receiver:i},s.streams=[t.stream],this.dispatchEvent(s)}))},this.addEventListener("addstream",this._ontrackpoly)),t.apply(this,arguments)}}else zi(e,"track",(e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e)))}function rs(e){if("object"==typeof e&&e.RTCPeerConnection&&!("getSenders"in e.RTCPeerConnection.prototype)&&"createDTMFSender"in e.RTCPeerConnection.prototype){const t=function(e,t){return{track:t,get dtmf(){return void 0===this._dtmf&&("audio"===t.kind?this._dtmf=e.createDTMFSender(t):this._dtmf=null),this._dtmf},_pc:e}};if(!e.RTCPeerConnection.prototype.getSenders){e.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};const n=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,i){let s=n.apply(this,arguments);return s||(s=t(this,e),this._senders.push(s)),s};const i=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){i.apply(this,arguments);const t=this._senders.indexOf(e);-1!==t&&this._senders.splice(t,1)}}const n=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._senders=this._senders||[],n.apply(this,[e]),e.getTracks().forEach((e=>{this._senders.push(t(this,e))}))};const i=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(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(){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 cs(e){if(!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){const[e,n,i]=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 s=function(e){const t={};return e.result().forEach((e=>{const n={id:e.id,timestamp:e.timestamp,type:{localcandidate:"local-candidate",remotecandidate:"remote-candidate"}[e.type]||e.type};e.names().forEach((t=>{n[t]=e.stat(t)})),t[n.id]=n})),t},o=function(e){return new Map(Object.keys(e).map((t=>[t,e[t]])))};if(arguments.length>=2){const i=function(e){n(o(s(e)))};return t.apply(this,[i,e])}return new Promise(((e,n)=>{t.apply(this,[function(t){e(o(s(t)))},n])})).then(n,i)}}function ds(e){if(!("object"==typeof e&&e.RTCPeerConnection&&e.RTCRtpSender&&e.RTCRtpReceiver))return;if(!("getStats"in e.RTCRtpSender.prototype)){const t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e});const n=e.RTCPeerConnection.prototype.addTrack;n&&(e.RTCPeerConnection.prototype.addTrack=function(){const e=n.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){const e=this;return this._pc.getStats().then((t=>ns(t,e.track,!0)))}}if(!("getStats"in e.RTCRtpReceiver.prototype)){const t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e}),zi(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){const e=this;return this._pc.getStats().then((t=>ns(t,e.track,!1)))}}if(!("getStats"in e.RTCRtpSender.prototype)||!("getStats"in e.RTCRtpReceiver.prototype))return;const t=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof e.MediaStreamTrack){const e=arguments[0];let t,n,i;return this.getSenders().forEach((n=>{n.track===e&&(t?i=!0:t=n)})),this.getReceivers().forEach((t=>(t.track===e&&(n?i=!0:n=t),t.track===e))),i||t&&n?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):t?t.getStats():n?n.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return t.apply(this,arguments)}}function ls(e){e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map((e=>this._shimmedLocalStreams[e][0]))};const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,n){if(!n)return t.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};const i=t.apply(this,arguments);return this._shimmedLocalStreams[n.id]?-1===this._shimmedLocalStreams[n.id].indexOf(i)&&this._shimmedLocalStreams[n.id].push(i):this._shimmedLocalStreams[n.id]=[n,i],i};const n=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._shimmedLocalStreams=this._shimmedLocalStreams||{},e.getTracks().forEach((e=>{if(this.getSenders().find((t=>t.track===e)))throw new DOMException("Track already exists.","InvalidAccessError")}));const t=this.getSenders();n.apply(this,arguments);const i=this.getSenders().filter((e=>-1===t.indexOf(e)));this._shimmedLocalStreams[e.id]=[e].concat(i)};const i=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[e.id],i.apply(this,arguments)};const s=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},e&&Object.keys(this._shimmedLocalStreams).forEach((t=>{const n=this._shimmedLocalStreams[t].indexOf(e);-1!==n&&this._shimmedLocalStreams[t].splice(n,1),1===this._shimmedLocalStreams[t].length&&delete this._shimmedLocalStreams[t]})),s.apply(this,arguments)}}function us(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return ls(e);const n=e.RTCPeerConnection.prototype.getLocalStreams;e.RTCPeerConnection.prototype.getLocalStreams=function(){const e=n.apply(this);return this._reverseStreams=this._reverseStreams||{},e.map((e=>this._reverseStreams[e.id]))};const i=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(t){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},t.getTracks().forEach((e=>{if(this.getSenders().find((t=>t.track===e)))throw new DOMException("Track already exists.","InvalidAccessError")})),!this._reverseStreams[t.id]){const n=new e.MediaStream(t.getTracks());this._streams[t.id]=n,this._reverseStreams[n.id]=t,t=n}i.apply(this,[t])};const s=e.RTCPeerConnection.prototype.removeStream;function o(e,t){let n=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((t=>{const i=e._reverseStreams[t],s=e._streams[i.id];n=n.replace(new RegExp(s.id,"g"),i.id)})),new RTCSessionDescription({type:t.type,sdp:n})}e.RTCPeerConnection.prototype.removeStream=function(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(t,n){if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");const i=[].slice.call(arguments,1);if(1!==i.length||!i[0].getTracks().find((e=>e===t)))throw new DOMException("The adapter.js addTrack polyfill only supports a single stream which is associated with the specified track.","NotSupportedError");if(this.getSenders().find((e=>e.track===t)))throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};const s=this._streams[n.id];if(s)s.addTrack(t),Promise.resolve().then((()=>{this.dispatchEvent(new Event("negotiationneeded"))}));else{const i=new e.MediaStream([t]);this._streams[n.id]=i,this._reverseStreams[i.id]=n,this.addStream(i)}return this.getSenders().find((e=>e.track===t))},["createOffer","createAnswer"].forEach((function(t){const n=e.RTCPeerConnection.prototype[t],i={[t](){const e=arguments;return arguments.length&&"function"==typeof arguments[0]?n.apply(this,[t=>{const n=o(this,t);e[0].apply(null,[n])},t=>{e[1]&&e[1].apply(null,t)},arguments[2]]):n.apply(this,arguments).then((e=>o(this,e)))}};e.RTCPeerConnection.prototype[t]=i[t]}));const a=e.RTCPeerConnection.prototype.setLocalDescription;e.RTCPeerConnection.prototype.setLocalDescription=function(){return arguments.length&&arguments[0].type?(arguments[0]=function(e,t){let n=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((t=>{const i=e._reverseStreams[t],s=e._streams[i.id];n=n.replace(new RegExp(i.id,"g"),s.id)})),new RTCSessionDescription({type:t.type,sdp:n})}(this,arguments[0]),a.apply(this,arguments)):a.apply(this,arguments)};const r=Object.getOwnPropertyDescriptor(e.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(e.RTCPeerConnection.prototype,"localDescription",{get(){const e=r.get.apply(this);return""===e.type?e:o(this,e)}}),e.RTCPeerConnection.prototype.removeTrack=function(e){if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!e._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(!(e._pc===this))throw new DOMException("Sender was not created by this connection.","InvalidAccessError");let t;this._streams=this._streams||{},Object.keys(this._streams).forEach((n=>{this._streams[n].getTracks().find((t=>e.track===t))&&(t=this._streams[n])})),t&&(1===t.getTracks().length?this.removeStream(this._reverseStreams[t.id]):t.removeTrack(e.track),this.dispatchEvent(new Event("negotiationneeded")))}}function hs(e,t){!e.RTCPeerConnection&&e.webkitRTCPeerConnection&&(e.RTCPeerConnection=e.webkitRTCPeerConnection),e.RTCPeerConnection&&t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach((function(t){const n=e.RTCPeerConnection.prototype[t],i={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),n.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=i[t]}))}function ms(e,t){zi(e,"negotiationneeded",(e=>{const n=e.target;if(!(t.version<72||n.getConfiguration&&"plan-b"===n.getConfiguration().sdpSemantics)||"stable"===n.signalingState)return e}))}var ps=Object.freeze({__proto__:null,fixNegotiationNeeded:ms,shimAddTrackRemoveTrack:us,shimAddTrackRemoveTrackWithNative:ls,shimGetDisplayMedia:function(e,t){e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||e.navigator.mediaDevices&&("function"==typeof t?e.navigator.mediaDevices.getDisplayMedia=function(n){return t(n).then((t=>{const i=n.video&&n.video.width,s=n.video&&n.video.height,o=n.video&&n.video.frameRate;return n.video={mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:t,maxFrameRate:o||3}},i&&(n.video.mandatory.maxWidth=i),s&&(n.video.mandatory.maxHeight=s),e.navigator.mediaDevices.getUserMedia(n)}))}:console.error("shimGetDisplayMedia: getSourceId argument is not a function"))},shimGetSendersWithDtmf:rs,shimGetStats:cs,shimGetUserMedia:ss,shimMediaStream:os,shimOnTrack:as,shimPeerConnection:hs,shimSenderReceiverGetStats:ds});function gs(e,t){const n=e&&e.navigator,i=e&&e.MediaStreamTrack;if(n.getUserMedia=function(e,t,i){Zi("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),n.mediaDevices.getUserMedia(e).then(t,i)},!(t.version>55&&"autoGainControl"in n.mediaDevices.getSupportedConstraints())){const e=function(e,t,n){t in e&&!(n in e)&&(e[n]=e[t],delete e[t])},t=n.mediaDevices.getUserMedia.bind(n.mediaDevices);if(n.mediaDevices.getUserMedia=function(n){return"object"==typeof n&&"object"==typeof n.audio&&(n=JSON.parse(JSON.stringify(n)),e(n.audio,"autoGainControl","mozAutoGainControl"),e(n.audio,"noiseSuppression","mozNoiseSuppression")),t(n)},i&&i.prototype.getSettings){const t=i.prototype.getSettings;i.prototype.getSettings=function(){const n=t.apply(this,arguments);return e(n,"mozAutoGainControl","autoGainControl"),e(n,"mozNoiseSuppression","noiseSuppression"),n}}if(i&&i.prototype.applyConstraints){const t=i.prototype.applyConstraints;i.prototype.applyConstraints=function(n){return"audio"===this.kind&&"object"==typeof n&&(n=JSON.parse(JSON.stringify(n)),e(n,"autoGainControl","mozAutoGainControl"),e(n,"noiseSuppression","mozNoiseSuppression")),t.apply(this,[n])}}}}function fs(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 vs(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 n=e.RTCPeerConnection.prototype[t],i={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),n.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=i[t]}));const n={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},i=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){const[e,s,o]=arguments;return i.apply(this,[e||null]).then((e=>{if(t.version<53&&!s)try{e.forEach((e=>{e.type=n[e.type]||e.type}))}catch(t){if("TypeError"!==t.name)throw t;e.forEach(((t,i)=>{e.set(i,Object.assign({},t,{type:n[t.type]||t.type}))}))}return e})).then(s,o)}}function ks(e){if("object"!=typeof e||!e.RTCPeerConnection||!e.RTCRtpSender)return;if(e.RTCRtpSender&&"getStats"in e.RTCRtpSender.prototype)return;const t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e});const n=e.RTCPeerConnection.prototype.addTrack;n&&(e.RTCPeerConnection.prototype.addTrack=function(){const e=n.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function Ts(e){if("object"!=typeof e||!e.RTCPeerConnection||!e.RTCRtpSender)return;if(e.RTCRtpSender&&"getStats"in e.RTCRtpReceiver.prototype)return;const t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e}),zi(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function ys(e){e.RTCPeerConnection&&!("removeStream"in e.RTCPeerConnection.prototype)&&(e.RTCPeerConnection.prototype.removeStream=function(e){Zi("removeStream","removeTrack"),this.getSenders().forEach((t=>{t.track&&e.getTracks().includes(t.track)&&this.removeTrack(t)}))})}function bs(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)}function Cs(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.addTransceiver;t&&(e.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let e=arguments[1]&&arguments[1].sendEncodings;void 0===e&&(e=[]),e=[...e];const n=e.length>0;n&&e.forEach((e=>{if("rid"in e){if(!/^[a-z0-9]{0,16}$/i.test(e.rid))throw new TypeError("Invalid RID value provided.")}if("scaleResolutionDownBy"in e&&!(parseFloat(e.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in e&&!(parseFloat(e.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")}));const i=t.apply(this,arguments);if(n){const{sender:t}=i,n=t.getParameters();(!("encodings"in n)||1===n.encodings.length&&0===Object.keys(n.encodings[0]).length)&&(n.encodings=e,t.sendEncodings=e,this.setParametersPromises.push(t.setParameters(n).then((()=>{delete t.sendEncodings})).catch((()=>{delete t.sendEncodings}))))}return i})}function Ss(e){if("object"!=typeof e||!e.RTCRtpSender)return;const t=e.RTCRtpSender.prototype.getParameters;t&&(e.RTCRtpSender.prototype.getParameters=function(){const e=t.apply(this,arguments);return"encodings"in e||(e.encodings=[].concat(this.sendEncodings||[{}])),e})}function Es(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then((()=>t.apply(this,arguments))).finally((()=>{this.setParametersPromises=[]})):t.apply(this,arguments)}}function ws(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.createAnswer;e.RTCPeerConnection.prototype.createAnswer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then((()=>t.apply(this,arguments))).finally((()=>{this.setParametersPromises=[]})):t.apply(this,arguments)}}var Ps=Object.freeze({__proto__:null,shimAddTransceiver:Cs,shimCreateAnswer:ws,shimCreateOffer:Es,shimGetDisplayMedia:function(e,t){e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||e.navigator.mediaDevices&&(e.navigator.mediaDevices.getDisplayMedia=function(n){if(!n||!n.video){const e=new DOMException("getDisplayMedia without video constraints is undefined");return e.name="NotFoundError",e.code=8,Promise.reject(e)}return!0===n.video?n.video={mediaSource:t}:n.video.mediaSource=t,e.navigator.mediaDevices.getUserMedia(n)})},shimGetParameters:Ss,shimGetUserMedia:gs,shimOnTrack:fs,shimPeerConnection:vs,shimRTCDataChannel:bs,shimReceiverGetStats:Ts,shimRemoveStream:ys,shimSenderGetStats:ks});function Rs(e){if("object"==typeof e&&e.RTCPeerConnection){if("getLocalStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in e.RTCPeerConnection.prototype)){const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addStream=function(e){this._localStreams||(this._localStreams=[]),this._localStreams.includes(e)||this._localStreams.push(e),e.getAudioTracks().forEach((n=>t.call(this,n,e))),e.getVideoTracks().forEach((n=>t.call(this,n,e)))},e.RTCPeerConnection.prototype.addTrack=function(e){for(var n=arguments.length,i=new Array(n>1?n-1:0),s=1;s<n;s++)i[s-1]=arguments[s];return i&&i.forEach((e=>{this._localStreams?this._localStreams.includes(e)||this._localStreams.push(e):this._localStreams=[e]})),t.apply(this,arguments)}}"removeStream"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.removeStream=function(e){this._localStreams||(this._localStreams=[]);const t=this._localStreams.indexOf(e);if(-1===t)return;this._localStreams.splice(t,1);const n=e.getTracks();this.getSenders().forEach((e=>{n.includes(e.track)&&this.removeTrack(e)}))})}}function _s(e){if("object"==typeof e&&e.RTCPeerConnection&&("getRemoteStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!("onaddstream"in e.RTCPeerConnection.prototype))){Object.defineProperty(e.RTCPeerConnection.prototype,"onaddstream",{get(){return this._onaddstream},set(e){this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=e),this.addEventListener("track",this._onaddstreampoly=e=>{e.streams.forEach((e=>{if(this._remoteStreams||(this._remoteStreams=[]),this._remoteStreams.includes(e))return;this._remoteStreams.push(e);const t=new Event("addstream");t.stream=e,this.dispatchEvent(t)}))})}});const t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){const e=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(t){t.streams.forEach((t=>{if(e._remoteStreams||(e._remoteStreams=[]),e._remoteStreams.indexOf(t)>=0)return;e._remoteStreams.push(t);const n=new Event("addstream");n.stream=t,e.dispatchEvent(n)}))}),t.apply(e,arguments)}}}function Is(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype,n=t.createOffer,i=t.createAnswer,s=t.setLocalDescription,o=t.setRemoteDescription,a=t.addIceCandidate;t.createOffer=function(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},t.createAnswer=function(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};let r=function(e,t,n){const i=s.apply(this,[e]);return n?(i.then(t,n),Promise.resolve()):i};t.setLocalDescription=r,r=function(e,t,n){const i=o.apply(this,[e]);return n?(i.then(t,n),Promise.resolve()):i},t.setRemoteDescription=r,r=function(e,t,n){const i=a.apply(this,[e]);return n?(i.then(t,n),Promise.resolve()):i},t.addIceCandidate=r}function Os(e){const t=e&&e.navigator;if(t.mediaDevices&&t.mediaDevices.getUserMedia){const e=t.mediaDevices,n=e.getUserMedia.bind(e);t.mediaDevices.getUserMedia=e=>n(Ms(e))}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=function(e,n,i){t.mediaDevices.getUserMedia(e).then(n,i)}.bind(t))}function Ms(e){return e&&void 0!==e.video?Object.assign({},e,{video:es(e.video)}):e}function xs(e){if(!e.RTCPeerConnection)return;const t=e.RTCPeerConnection;e.RTCPeerConnection=function(e,n){if(e&&e.iceServers){const t=[];for(let n=0;n<e.iceServers.length;n++){let i=e.iceServers[n];void 0===i.urls&&i.url?(Zi("RTCIceServer.url","RTCIceServer.urls"),i=JSON.parse(JSON.stringify(i)),i.urls=i.url,delete i.url,t.push(i)):t.push(e.iceServers[n])}e.iceServers=t}return new t(e,n)},e.RTCPeerConnection.prototype=t.prototype,"generateCertificate"in t&&Object.defineProperty(e.RTCPeerConnection,"generateCertificate",{get:()=>t.generateCertificate})}function Ds(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 Ns(e){const t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(e){if(e){void 0!==e.offerToReceiveAudio&&(e.offerToReceiveAudio=!!e.offerToReceiveAudio);const t=this.getTransceivers().find((e=>"audio"===e.receiver.track.kind));!1===e.offerToReceiveAudio&&t?"sendrecv"===t.direction?t.setDirection?t.setDirection("sendonly"):t.direction="sendonly":"recvonly"===t.direction&&(t.setDirection?t.setDirection("inactive"):t.direction="inactive"):!0!==e.offerToReceiveAudio||t||this.addTransceiver("audio",{direction:"recvonly"}),void 0!==e.offerToReceiveVideo&&(e.offerToReceiveVideo=!!e.offerToReceiveVideo);const n=this.getTransceivers().find((e=>"video"===e.receiver.track.kind));!1===e.offerToReceiveVideo&&n?"sendrecv"===n.direction?n.setDirection?n.setDirection("sendonly"):n.direction="sendonly":"recvonly"===n.direction&&(n.setDirection?n.setDirection("inactive"):n.direction="inactive"):!0!==e.offerToReceiveVideo||n||this.addTransceiver("video",{direction:"recvonly"})}return t.apply(this,arguments)}}function Ls(e){"object"!=typeof e||e.AudioContext||(e.AudioContext=e.webkitAudioContext)}var As=Object.freeze({__proto__:null,shimAudioContext:Ls,shimCallbacksAPI:Is,shimConstraints:Ms,shimCreateOfferLegacy:Ns,shimGetUserMedia:Os,shimLocalStreamsAPI:Rs,shimRTCIceServerUrls:xs,shimRemoteStreamsAPI:_s,shimTrackEventTransceiver:Ds}),Us={exports:{}};!function(e){const t={generateIdentifier:function(){return Math.random().toString(36).substring(2,12)}};t.localCName=t.generateIdentifier(),t.splitLines=function(e){return e.trim().split("\n").map((e=>e.trim()))},t.splitSections=function(e){return e.split("\nm=").map(((e,t)=>(t>0?"m="+e:e).trim()+"\r\n"))},t.getDescription=function(e){const n=t.splitSections(e);return n&&n[0]},t.getMediaSections=function(e){const n=t.splitSections(e);return n.shift(),n},t.matchPrefix=function(e,n){return t.splitLines(e).filter((e=>0===e.indexOf(n)))},t.parseCandidate=function(e){let t;t=0===e.indexOf("a=candidate:")?e.substring(12).split(" "):e.substring(10).split(" ");const n={foundation:t[0],component:{1:"rtp",2:"rtcp"}[t[1]]||t[1],protocol:t[2].toLowerCase(),priority:parseInt(t[3],10),ip:t[4],address:t[4],port:parseInt(t[5],10),type:t[7]};for(let e=8;e<t.length;e+=2)switch(t[e]){case"raddr":n.relatedAddress=t[e+1];break;case"rport":n.relatedPort=parseInt(t[e+1],10);break;case"tcptype":n.tcpType=t[e+1];break;case"ufrag":n.ufrag=t[e+1],n.usernameFragment=t[e+1];break;default:void 0===n[t[e]]&&(n[t[e]]=t[e+1])}return n},t.writeCandidate=function(e){const t=[];t.push(e.foundation);const n=e.component;"rtp"===n?t.push(1):"rtcp"===n?t.push(2):t.push(n),t.push(e.protocol.toUpperCase()),t.push(e.priority),t.push(e.address||e.ip),t.push(e.port);const i=e.type;return t.push("typ"),t.push(i),"host"!==i&&e.relatedAddress&&e.relatedPort&&(t.push("raddr"),t.push(e.relatedAddress),t.push("rport"),t.push(e.relatedPort)),e.tcpType&&"tcp"===e.protocol.toLowerCase()&&(t.push("tcptype"),t.push(e.tcpType)),(e.usernameFragment||e.ufrag)&&(t.push("ufrag"),t.push(e.usernameFragment||e.ufrag)),"candidate:"+t.join(" ")},t.parseIceOptions=function(e){return e.substring(14).split(" ")},t.parseRtpMap=function(e){let t=e.substring(9).split(" ");const n={payloadType:parseInt(t.shift(),10)};return t=t[0].split("/"),n.name=t[0],n.clockRate=parseInt(t[1],10),n.channels=3===t.length?parseInt(t[2],10):1,n.numChannels=n.channels,n},t.writeRtpMap=function(e){let t=e.payloadType;void 0!==e.preferredPayloadType&&(t=e.preferredPayloadType);const n=e.channels||e.numChannels||1;return"a=rtpmap:"+t+" "+e.name+"/"+e.clockRate+(1!==n?"/"+n:"")+"\r\n"},t.parseExtmap=function(e){const t=e.substring(9).split(" ");return{id:parseInt(t[0],10),direction:t[0].indexOf("/")>0?t[0].split("/")[1]:"sendrecv",uri:t[1],attributes:t.slice(2).join(" ")}},t.writeExtmap=function(e){return"a=extmap:"+(e.id||e.preferredId)+(e.direction&&"sendrecv"!==e.direction?"/"+e.direction:"")+" "+e.uri+(e.attributes?" "+e.attributes:"")+"\r\n"},t.parseFmtp=function(e){const t={};let n;const i=e.substring(e.indexOf(" ")+1).split(";");for(let e=0;e<i.length;e++)n=i[e].trim().split("="),t[n[0].trim()]=n[1];return t},t.writeFmtp=function(e){let t="",n=e.payloadType;if(void 0!==e.preferredPayloadType&&(n=e.preferredPayloadType),e.parameters&&Object.keys(e.parameters).length){const i=[];Object.keys(e.parameters).forEach((t=>{void 0!==e.parameters[t]?i.push(t+"="+e.parameters[t]):i.push(t)})),t+="a=fmtp:"+n+" "+i.join(";")+"\r\n"}return t},t.parseRtcpFb=function(e){const t=e.substring(e.indexOf(" ")+1).split(" ");return{type:t.shift(),parameter:t.join(" ")}},t.writeRtcpFb=function(e){let t="",n=e.payloadType;return void 0!==e.preferredPayloadType&&(n=e.preferredPayloadType),e.rtcpFeedback&&e.rtcpFeedback.length&&e.rtcpFeedback.forEach((e=>{t+="a=rtcp-fb:"+n+" "+e.type+(e.parameter&&e.parameter.length?" "+e.parameter:"")+"\r\n"})),t},t.parseSsrcMedia=function(e){const t=e.indexOf(" "),n={ssrc:parseInt(e.substring(7,t),10)},i=e.indexOf(":",t);return i>-1?(n.attribute=e.substring(t+1,i),n.value=e.substring(i+1)):n.attribute=e.substring(t+1),n},t.parseSsrcGroup=function(e){const t=e.substring(13).split(" ");return{semantics:t.shift(),ssrcs:t.map((e=>parseInt(e,10)))}},t.getMid=function(e){const n=t.matchPrefix(e,"a=mid:")[0];if(n)return n.substring(6)},t.parseFingerprint=function(e){const t=e.substring(14).split(" ");return{algorithm:t[0].toLowerCase(),value:t[1].toUpperCase()}},t.getDtlsParameters=function(e,n){return{role:"auto",fingerprints:t.matchPrefix(e+n,"a=fingerprint:").map(t.parseFingerprint)}},t.writeDtlsParameters=function(e,t){let n="a=setup:"+t+"\r\n";return e.fingerprints.forEach((e=>{n+="a=fingerprint:"+e.algorithm+" "+e.value+"\r\n"})),n},t.parseCryptoLine=function(e){const t=e.substring(9).split(" ");return{tag:parseInt(t[0],10),cryptoSuite:t[1],keyParams:t[2],sessionParams:t.slice(3)}},t.writeCryptoLine=function(e){return"a=crypto:"+e.tag+" "+e.cryptoSuite+" "+("object"==typeof e.keyParams?t.writeCryptoKeyParams(e.keyParams):e.keyParams)+(e.sessionParams?" "+e.sessionParams.join(" "):"")+"\r\n"},t.parseCryptoKeyParams=function(e){if(0!==e.indexOf("inline:"))return null;const t=e.substring(7).split("|");return{keyMethod:"inline",keySalt:t[0],lifeTime:t[1],mkiValue:t[2]?t[2].split(":")[0]:void 0,mkiLength:t[2]?t[2].split(":")[1]:void 0}},t.writeCryptoKeyParams=function(e){return e.keyMethod+":"+e.keySalt+(e.lifeTime?"|"+e.lifeTime:"")+(e.mkiValue&&e.mkiLength?"|"+e.mkiValue+":"+e.mkiLength:"")},t.getCryptoParameters=function(e,n){return t.matchPrefix(e+n,"a=crypto:").map(t.parseCryptoLine)},t.getIceParameters=function(e,n){const i=t.matchPrefix(e+n,"a=ice-ufrag:")[0],s=t.matchPrefix(e+n,"a=ice-pwd:")[0];return i&&s?{usernameFragment:i.substring(12),password:s.substring(10)}:null},t.writeIceParameters=function(e){let t="a=ice-ufrag:"+e.usernameFragment+"\r\na=ice-pwd:"+e.password+"\r\n";return e.iceLite&&(t+="a=ice-lite\r\n"),t},t.parseRtpParameters=function(e){const n={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},i=t.splitLines(e)[0].split(" ");n.profile=i[2];for(let s=3;s<i.length;s++){const o=i[s],a=t.matchPrefix(e,"a=rtpmap:"+o+" ")[0];if(a){const i=t.parseRtpMap(a),s=t.matchPrefix(e,"a=fmtp:"+o+" ");switch(i.parameters=s.length?t.parseFmtp(s[0]):{},i.rtcpFeedback=t.matchPrefix(e,"a=rtcp-fb:"+o+" ").map(t.parseRtcpFb),n.codecs.push(i),i.name.toUpperCase()){case"RED":case"ULPFEC":n.fecMechanisms.push(i.name.toUpperCase())}}}t.matchPrefix(e,"a=extmap:").forEach((e=>{n.headerExtensions.push(t.parseExtmap(e))}));const s=t.matchPrefix(e,"a=rtcp-fb:* ").map(t.parseRtcpFb);return n.codecs.forEach((e=>{s.forEach((t=>{e.rtcpFeedback.find((e=>e.type===t.type&&e.parameter===t.parameter))||e.rtcpFeedback.push(t)}))})),n},t.writeRtpDescription=function(e,n){let i="";i+="m="+e+" ",i+=n.codecs.length>0?"9":"0",i+=" "+(n.profile||"UDP/TLS/RTP/SAVPF")+" ",i+=n.codecs.map((e=>void 0!==e.preferredPayloadType?e.preferredPayloadType:e.payloadType)).join(" ")+"\r\n",i+="c=IN IP4 0.0.0.0\r\n",i+="a=rtcp:9 IN IP4 0.0.0.0\r\n",n.codecs.forEach((e=>{i+=t.writeRtpMap(e),i+=t.writeFmtp(e),i+=t.writeRtcpFb(e)}));let s=0;return n.codecs.forEach((e=>{e.maxptime>s&&(s=e.maxptime)})),s>0&&(i+="a=maxptime:"+s+"\r\n"),n.headerExtensions&&n.headerExtensions.forEach((e=>{i+=t.writeExtmap(e)})),i},t.parseRtpEncodingParameters=function(e){const n=[],i=t.parseRtpParameters(e),s=-1!==i.fecMechanisms.indexOf("RED"),o=-1!==i.fecMechanisms.indexOf("ULPFEC"),a=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"cname"===e.attribute)),r=a.length>0&&a[0].ssrc;let c;const d=t.matchPrefix(e,"a=ssrc-group:FID").map((e=>e.substring(17).split(" ").map((e=>parseInt(e,10)))));d.length>0&&d[0].length>1&&d[0][0]===r&&(c=d[0][1]),i.codecs.forEach((e=>{if("RTX"===e.name.toUpperCase()&&e.parameters.apt){let t={ssrc:r,codecPayloadType:parseInt(e.parameters.apt,10)};r&&c&&(t.rtx={ssrc:c}),n.push(t),s&&(t=JSON.parse(JSON.stringify(t)),t.fec={ssrc:r,mechanism:o?"red+ulpfec":"red"},n.push(t))}})),0===n.length&&r&&n.push({ssrc:r});let l=t.matchPrefix(e,"b=");return l.length&&(l=0===l[0].indexOf("b=TIAS:")?parseInt(l[0].substring(7),10):0===l[0].indexOf("b=AS:")?1e3*parseInt(l[0].substring(5),10)*.95-16e3:void 0,n.forEach((e=>{e.maxBitrate=l}))),n},t.parseRtcpParameters=function(e){const n={},i=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"cname"===e.attribute))[0];i&&(n.cname=i.value,n.ssrc=i.ssrc);const s=t.matchPrefix(e,"a=rtcp-rsize");n.reducedSize=s.length>0,n.compound=0===s.length;const o=t.matchPrefix(e,"a=rtcp-mux");return n.mux=o.length>0,n},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 n;const i=t.matchPrefix(e,"a=msid:");if(1===i.length)return n=i[0].substring(7).split(" "),{stream:n[0],track:n[1]};const s=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"msid"===e.attribute));return s.length>0?(n=s[0].value.split(" "),{stream:n[0],track:n[1]}):void 0},t.parseSctpDescription=function(e){const n=t.parseMLine(e),i=t.matchPrefix(e,"a=max-message-size:");let s;i.length>0&&(s=parseInt(i[0].substring(19),10)),isNaN(s)&&(s=65536);const o=t.matchPrefix(e,"a=sctp-port:");if(o.length>0)return{port:parseInt(o[0].substring(12),10),protocol:n.fmt,maxMessageSize:s};const a=t.matchPrefix(e,"a=sctpmap:");if(a.length>0){const e=a[0].substring(10).split(" ");return{port:parseInt(e[0],10),protocol:e[1],maxMessageSize:s}}},t.writeSctpDescription=function(e,t){let n=[];return n="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&&n.push("a=max-message-size:"+t.maxMessageSize+"\r\n"),n.join("")},t.generateSessionId=function(){return Math.random().toString().substr(2,22)},t.writeSessionBoilerplate=function(e,n,i){let s;const o=void 0!==n?n:2;s=e||t.generateSessionId();return"v=0\r\no="+(i||"thisisadapterortc")+" "+s+" "+o+" IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\n"},t.getDirection=function(e,n){const i=t.splitLines(e);for(let e=0;e<i.length;e++)switch(i[e]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return i[e].substring(2)}return n?t.getDirection(n):"sendrecv"},t.getKind=function(e){return t.splitLines(e)[0].split(" ")[0].substring(2)},t.isRejected=function(e){return"0"===e.split(" ",2)[1]},t.parseMLine=function(e){const n=t.splitLines(e)[0].substring(2).split(" ");return{kind:n[0],port:parseInt(n[1],10),protocol:n[2],fmt:n.slice(3).join(" ")}},t.parseOLine=function(e){const n=t.matchPrefix(e,"o=")[0].substring(2).split(" ");return{username:n[0],sessionId:n[1],sessionVersion:parseInt(n[2],10),netType:n[3],addressType:n[4],address:n[5]}},t.isValidSDP=function(e){if("string"!=typeof e||0===e.length)return!1;const n=t.splitLines(e);for(let e=0;e<n.length;e++)if(n[e].length<2||"="!==n[e].charAt(1))return!1;return!0},e.exports=t}(Us);var js=Us.exports,Fs=mi(js),Bs=t({__proto__:null,default:Fs},[js]);function Vs(e){if(!e.RTCIceCandidate||e.RTCIceCandidate&&"foundation"in e.RTCIceCandidate.prototype)return;const t=e.RTCIceCandidate;e.RTCIceCandidate=function(e){if("object"==typeof e&&e.candidate&&0===e.candidate.indexOf("a=")&&((e=JSON.parse(JSON.stringify(e))).candidate=e.candidate.substring(2)),e.candidate&&e.candidate.length){const n=new t(e),i=Fs.parseCandidate(e.candidate);for(const e in i)e in n||Object.defineProperty(n,e,{value:i[e]});return n.toJSON=function(){return{candidate:n.candidate,sdpMid:n.sdpMid,sdpMLineIndex:n.sdpMLineIndex,usernameFragment:n.usernameFragment}},n}return new t(e)},e.RTCIceCandidate.prototype=t.prototype,zi(e,"icecandidate",(t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new e.RTCIceCandidate(t.candidate),writable:"false"}),t)))}function qs(e){!e.RTCIceCandidate||e.RTCIceCandidate&&"relayProtocol"in e.RTCIceCandidate.prototype||zi(e,"icecandidate",(e=>{if(e.candidate){const t=Fs.parseCandidate(e.candidate.candidate);"relay"===t.type&&(e.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[t.priority>>24])}return e}))}function Ks(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 n=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,"chrome"===t.browser&&t.version>=76){const{sdpSemantics:e}=this.getConfiguration();"plan-b"===e&&Object.defineProperty(this,"sctp",{get(){return void 0===this._sctp?null:this._sctp},enumerable:!0,configurable:!0})}if(function(e){if(!e||!e.sdp)return!1;const t=Fs.splitSections(e.sdp);return t.shift(),t.some((e=>{const t=Fs.parseMLine(e);return t&&"application"===t.kind&&-1!==t.protocol.indexOf("SCTP")}))}(arguments[0])){const e=function(e){const t=e.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(null===t||t.length<2)return-1;const n=parseInt(t[1],10);return n!=n?-1:n}(arguments[0]),n=function(e){let n=65536;return"firefox"===t.browser&&(n=t.version<57?-1===e?16384:2147483637:t.version<60?57===t.version?65535:65536:2147483637),n}(e),i=function(e,n){let i=65536;"firefox"===t.browser&&57===t.version&&(i=65535);const s=Fs.matchPrefix(e.sdp,"a=max-message-size:");return s.length>0?i=parseInt(s[0].substring(19),10):"firefox"===t.browser&&-1!==n&&(i=2147483637),i}(arguments[0],e);let s;s=0===n&&0===i?Number.POSITIVE_INFINITY:0===n||0===i?Math.max(n,i):Math.min(n,i);const o={};Object.defineProperty(o,"maxMessageSize",{get:()=>s}),this._sctp=o}return n.apply(this,arguments)}}function Gs(e){if(!e.RTCPeerConnection||!("createDataChannel"in e.RTCPeerConnection.prototype))return;function t(e,t){const n=e.send;e.send=function(){const i=arguments[0],s=i.length||i.size||i.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 n.apply(e,arguments)}}const n=e.RTCPeerConnection.prototype.createDataChannel;e.RTCPeerConnection.prototype.createDataChannel=function(){const e=n.apply(this,arguments);return t(e,this),e},zi(e,"datachannel",(e=>(t(e.channel,e.target),e)))}function Ws(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 n=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 n=new Event("connectionstatechange",e);t.dispatchEvent(n)}return e},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),n.apply(this,arguments)}}))}function Hs(e,t){if(!e.RTCPeerConnection)return;if("chrome"===t.browser&&t.version>=71)return;if("safari"===t.browser&&t.version>=605)return;const n=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(t){if(t&&t.sdp&&-1!==t.sdp.indexOf("\na=extmap-allow-mixed")){const n=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:n}):t.sdp=n}return n.apply(this,arguments)}}function Js(e,t){if(!e.RTCPeerConnection||!e.RTCPeerConnection.prototype)return;const n=e.RTCPeerConnection.prototype.addIceCandidate;n&&0!==n.length&&(e.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?("chrome"===t.browser&&t.version<78||"firefox"===t.browser&&t.version<68||"safari"===t.browser)&&arguments[0]&&""===arguments[0].candidate?Promise.resolve():n.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}function zs(e,t){if(!e.RTCPeerConnection||!e.RTCPeerConnection.prototype)return;const n=e.RTCPeerConnection.prototype.setLocalDescription;n&&0!==n.length&&(e.RTCPeerConnection.prototype.setLocalDescription=function(){let e=arguments[0]||{};if("object"!=typeof e||e.type&&e.sdp)return n.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 n.apply(this,[e]);return("offer"===e.type?this.createOffer:this.createAnswer).apply(this).then((e=>n.apply(this,[e])))})}var Qs=Object.freeze({__proto__:null,removeExtmapAllowMixed:Hs,shimAddIceCandidateNullOrEmpty:Js,shimConnectionState:Ws,shimMaxMessageSize:Ks,shimParameterlessSetLocalDescription:zs,shimRTCIceCandidate:Vs,shimRTCIceCandidateRelayProtocol:qs,shimSendThrowTypeError:Gs});!function(){let{window:e}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{shimChrome:!0,shimFirefox:!0,shimSafari:!0};const n=Xi,i=function(e){const t={browser:null,version:null};if(void 0===e||!e.navigator||!e.navigator.userAgent)return t.browser="Not a browser.",t;const{navigator:n}=e;if(n.mozGetUserMedia)t.browser="firefox",t.version=Ji(n.userAgent,/Firefox\/(\d+)\./,1);else if(n.webkitGetUserMedia||!1===e.isSecureContext&&e.webkitRTCPeerConnection)t.browser="chrome",t.version=Ji(n.userAgent,/Chrom(e|ium)\/(\d+)\./,2);else{if(!e.RTCPeerConnection||!n.userAgent.match(/AppleWebKit\/(\d+)\./))return t.browser="Not a supported browser.",t;t.browser="safari",t.version=Ji(n.userAgent,/AppleWebKit\/(\d+)\./,1),t.supportsUnifiedPlan=e.RTCRtpTransceiver&&"currentDirection"in e.RTCRtpTransceiver.prototype}return t}(e),s={browserDetails:i,commonShim:Qs,extractVersion:Ji,disableLog:Qi,disableWarnings:Yi,sdp:Bs};switch(i.browser){case"chrome":if(!ps||!hs||!t.shimChrome)return n("Chrome shim is not included in this adapter release."),s;if(null===i.version)return n("Chrome shim can not determine version, not shimming."),s;n("adapter.js shimming chrome."),s.browserShim=ps,Js(e,i),zs(e),ss(e,i),os(e),hs(e,i),as(e),us(e,i),rs(e),cs(e),ds(e),ms(e,i),Vs(e),qs(e),Ws(e),Ks(e,i),Gs(e),Hs(e,i);break;case"firefox":if(!Ps||!vs||!t.shimFirefox)return n("Firefox shim is not included in this adapter release."),s;n("adapter.js shimming firefox."),s.browserShim=Ps,Js(e,i),zs(e),gs(e,i),vs(e,i),fs(e),ys(e),ks(e),Ts(e),bs(e),Cs(e),Ss(e),Es(e),ws(e),Vs(e),Ws(e),Ks(e,i),Gs(e);break;case"safari":if(!As||!t.shimSafari)return n("Safari shim is not included in this adapter release."),s;n("adapter.js shimming safari."),s.browserShim=As,Js(e,i),zs(e),xs(e),Ns(e),Is(e),Rs(e),_s(e),Ds(e),Os(e),Ls(e),Vs(e),qs(e),Ks(e,i),Gs(e),Hs(e,i);break;default:n("Unsupported browser!")}}({window:"undefined"==typeof window?void 0:window});const Ys="AES-GCM",Xs="lk_e2ee",Zs={sharedKey:!1,ratchetSalt:"LKFrameEncryptionKey",ratchetWindowSize:8,failureTolerance:10};var $s,eo;function to(){return io()||no()}function no(){return void 0!==window.RTCRtpScriptTransform}function io(){return void 0!==window.RTCRtpSender&&void 0!==window.RTCRtpSender.prototype.createEncodedStreams}function so(e){return wi(this,void 0,void 0,(function*(){let t=new TextEncoder;return yield crypto.subtle.importKey("raw",t.encode(e),{name:"PBKDF2"},!1,["deriveBits","deriveKey"])}))}function oo(e){return wi(this,void 0,void 0,(function*(){return yield crypto.subtle.importKey("raw",e,"HKDF",!1,["deriveBits","deriveKey"])}))}function ao(e,t){const n=(new TextEncoder).encode(t);switch(e){case"HKDF":return{name:"HKDF",salt:n,hash:"SHA-256",info:new ArrayBuffer(128)};case"PBKDF2":return{name:"PBKDF2",salt:n,hash:"SHA-256",iterations:1e5};default:throw new Error("algorithm ".concat(e," is currently unsupported"))}}e.KeyProviderEvent=void 0,($s=e.KeyProviderEvent||(e.KeyProviderEvent={})).SetKey="setKey",$s.RatchetRequest="ratchetRequest",$s.KeyRatcheted="keyRatcheted",e.KeyHandlerEvent=void 0,(e.KeyHandlerEvent||(e.KeyHandlerEvent={})).KeyRatcheted="keyRatcheted",e.EncryptionEvent=void 0,(eo=e.EncryptionEvent||(e.EncryptionEvent={})).ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",eo.EncryptionError="encryptionError",e.CryptorEvent=void 0,(e.CryptorEvent||(e.CryptorEvent={})).Error="cryptorError";class ro extends Gi.EventEmitter{constructor(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};super(),this.onKeyRatcheted=(e,t)=>{ki.debug("key ratcheted event received",{material:e,keyIndex:t})},this.keyInfoMap=new Map,this.options=Object.assign(Object.assign({},Zs),t),this.on(e.KeyProviderEvent.KeyRatcheted,this.onKeyRatcheted)}onSetEncryptionKey(t,n,i){const s={key:t,participantIdentity:n,keyIndex:i};if(!this.options.sharedKey&&!n)throw new Error("participant identity needs to be passed for encryption key if sharedKey option is false");this.keyInfoMap.set("".concat(null!=n?n:"shared","-").concat(null!=i?i:0),s),this.emit(e.KeyProviderEvent.SetKey,s)}getKeys(){return Array.from(this.keyInfoMap.values())}getOptions(){return this.options}ratchetKey(t,n){this.emit(e.KeyProviderEvent.RatchetRequest,t,n)}}class co extends Error{constructor(e,t){super(t||"an error has occured"),this.code=e}}class lo extends co{constructor(e,t,n){super(1,e),this.status=n,this.reason=t}}class uo extends co{constructor(e){super(21,null!=e?e:"device is unsupported")}}class ho extends co{constructor(e){super(20,null!=e?e:"track is invalid")}}class mo extends co{constructor(e){super(10,null!=e?e:"unsupported server")}}class po extends co{constructor(e){super(12,null!=e?e:"unexpected connection state")}}class go extends co{constructor(e){super(13,null!=e?e:"unable to negotiate")}}var fo,vo,ko,To,yo;function bo(e,t,n){var i,s,o;void 0===t&&(t=50),void 0===n&&(n={});var a=null!=(i=n.isImmediate)&&i,r=null!=(s=n.callback)&&s,c=n.maxWait,d=Date.now(),l=[];function u(){if(void 0!==c){var e=Date.now()-d;if(e+t>=c)return c-e}return t}var h=function(){var t=[].slice.call(arguments),n=this;return new Promise((function(i,s){var c=a&&void 0===o;if(void 0!==o&&clearTimeout(o),o=setTimeout((function(){if(o=void 0,d=Date.now(),!a){var i=e.apply(n,t);r&&r(i),l.forEach((function(e){return(0,e.resolve)(i)})),l=[]}}),u()),c){var h=e.apply(n,t);return r&&r(h),i(h)}l.push({resolve:i,reject:s})}))};return h.cancel=function(e){void 0!==o&&clearTimeout(o),l.forEach((function(t){return(0,t.reject)(e)})),l=[]},h}e.MediaDeviceFailure=void 0,(fo=e.MediaDeviceFailure||(e.MediaDeviceFailure={})).PermissionDenied="PermissionDenied",fo.NotFound="NotFound",fo.DeviceInUse="DeviceInUse",fo.Other="Other",function(e){e.getFailure=function(t){if(t&&"name"in t)return"NotFoundError"===t.name||"DevicesNotFoundError"===t.name?e.NotFound:"NotAllowedError"===t.name||"PermissionDeniedError"===t.name?e.PermissionDenied:"NotReadableError"===t.name||"TrackStartError"===t.name?e.DeviceInUse:e.Other}}(e.MediaDeviceFailure||(e.MediaDeviceFailure={})),e.RoomEvent=void 0,(vo=e.RoomEvent||(e.RoomEvent={})).Connected="connected",vo.Reconnecting="reconnecting",vo.Reconnected="reconnected",vo.Disconnected="disconnected",vo.ConnectionStateChanged="connectionStateChanged",vo.MediaDevicesChanged="mediaDevicesChanged",vo.ParticipantConnected="participantConnected",vo.ParticipantDisconnected="participantDisconnected",vo.TrackPublished="trackPublished",vo.TrackSubscribed="trackSubscribed",vo.TrackSubscriptionFailed="trackSubscriptionFailed",vo.TrackUnpublished="trackUnpublished",vo.TrackUnsubscribed="trackUnsubscribed",vo.TrackMuted="trackMuted",vo.TrackUnmuted="trackUnmuted",vo.LocalTrackPublished="localTrackPublished",vo.LocalTrackUnpublished="localTrackUnpublished",vo.LocalAudioSilenceDetected="localAudioSilenceDetected",vo.ActiveSpeakersChanged="activeSpeakersChanged",vo.ParticipantMetadataChanged="participantMetadataChanged",vo.ParticipantNameChanged="participantNameChanged",vo.RoomMetadataChanged="roomMetadataChanged",vo.DataReceived="dataReceived",vo.ConnectionQualityChanged="connectionQualityChanged",vo.TrackStreamStateChanged="trackStreamStateChanged",vo.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",vo.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",vo.AudioPlaybackStatusChanged="audioPlaybackChanged",vo.VideoPlaybackStatusChanged="videoPlaybackChanged",vo.MediaDevicesError="mediaDevicesError",vo.ParticipantPermissionsChanged="participantPermissionsChanged",vo.SignalConnected="signalConnected",vo.RecordingStatusChanged="recordingStatusChanged",vo.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",vo.EncryptionError="encryptionError",vo.DCBufferStatusChanged="dcBufferStatusChanged",vo.ActiveDeviceChanged="activeDeviceChanged",e.ParticipantEvent=void 0,(ko=e.ParticipantEvent||(e.ParticipantEvent={})).TrackPublished="trackPublished",ko.TrackSubscribed="trackSubscribed",ko.TrackSubscriptionFailed="trackSubscriptionFailed",ko.TrackUnpublished="trackUnpublished",ko.TrackUnsubscribed="trackUnsubscribed",ko.TrackMuted="trackMuted",ko.TrackUnmuted="trackUnmuted",ko.LocalTrackPublished="localTrackPublished",ko.LocalTrackUnpublished="localTrackUnpublished",ko.ParticipantMetadataChanged="participantMetadataChanged",ko.ParticipantNameChanged="participantNameChanged",ko.DataReceived="dataReceived",ko.IsSpeakingChanged="isSpeakingChanged",ko.ConnectionQualityChanged="connectionQualityChanged",ko.TrackStreamStateChanged="trackStreamStateChanged",ko.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",ko.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",ko.MediaDevicesError="mediaDevicesError",ko.AudioStreamAcquired="audioStreamAcquired",ko.ParticipantPermissionsChanged="participantPermissionsChanged",ko.PCTrackAdded="pcTrackAdded",e.EngineEvent=void 0,(To=e.EngineEvent||(e.EngineEvent={})).TransportsCreated="transportsCreated",To.Connected="connected",To.Disconnected="disconnected",To.Resuming="resuming",To.Resumed="resumed",To.Restarting="restarting",To.Restarted="restarted",To.SignalResumed="signalResumed",To.SignalRestarted="signalRestarted",To.Closing="closing",To.MediaTrackAdded="mediaTrackAdded",To.ActiveSpeakersUpdate="activeSpeakersUpdate",To.DataPacketReceived="dataPacketReceived",To.RTPVideoMapUpdate="rtpVideoMapUpdate",To.DCBufferStatusChanged="dcBufferStatusChanged",To.ParticipantUpdate="participantUpdate",To.RoomUpdate="roomUpdate",To.SpeakersChanged="speakersChanged",To.StreamStateChanged="streamStateChanged",To.ConnectionQualityUpdate="connectionQualityUpdate",To.SubscriptionError="subscriptionError",To.SubscriptionPermissionUpdate="subscriptionPermissionUpdate",To.RemoteMute="remoteMute",To.SubscribedQualityUpdate="subscribedQualityUpdate",To.LocalTrackUnpublished="localTrackUnpublished",To.Offline="offline",e.TrackEvent=void 0,(yo=e.TrackEvent||(e.TrackEvent={})).Message="message",yo.Muted="muted",yo.Unmuted="unmuted",yo.Restarted="restarted",yo.Ended="ended",yo.Subscribed="subscribed",yo.Unsubscribed="unsubscribed",yo.UpdateSettings="updateSettings",yo.UpdateSubscription="updateSubscription",yo.AudioPlaybackStarted="audioPlaybackStarted",yo.AudioPlaybackFailed="audioPlaybackFailed",yo.AudioSilenceDetected="audioSilenceDetected",yo.VisibilityChanged="visibilityChanged",yo.VideoDimensionsChanged="videoDimensionsChanged",yo.VideoPlaybackStarted="videoPlaybackStarted",yo.VideoPlaybackFailed="videoPlaybackFailed",yo.ElementAttached="elementAttached",yo.ElementDetached="elementDetached",yo.UpstreamPaused="upstreamPaused",yo.UpstreamResumed="upstreamResumed",yo.SubscriptionPermissionChanged="subscriptionPermissionChanged",yo.SubscriptionStatusChanged="subscriptionStatusChanged",yo.SubscriptionFailed="subscriptionFailed",yo.TrackProcessorUpdate="trackProcessorUpdate";const Co=/version\/(\d+(\.?_?\d+)+)/i;let So;function Eo(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(void 0===e&&"undefined"==typeof navigator)return;const n=(null!=e?e:navigator.userAgent).toLowerCase();if(void 0===So||t){const e=wo.find((e=>{let{test:t}=e;return t.test(n)}));So=null==e?void 0:e.describe(n)}return So}const wo=[{test:/firefox|iceweasel|fxios/i,describe:e=>({name:"Firefox",version:Po(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,e),os:e.toLowerCase().includes("fxios")?"iOS":void 0})},{test:/chrom|crios|crmo/i,describe:e=>({name:"Chrome",version:Po(/(?:chrome|chromium|crios|crmo)\/(\d+(\.?_?\d+)+)/i,e),os:e.toLowerCase().includes("crios")?"iOS":void 0})},{test:/safari|applewebkit/i,describe:e=>({name:"Safari",version:Po(Co,e),os:e.includes("mobile/")?"iOS":"macOS"})}];function Po(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1;const i=t.match(e);return i&&i.length>=n&&i[n]||""}const Ro="2.0.6";class _o{}_o.setTimeout=function(){return setTimeout(...arguments)},_o.setInterval=function(){return setInterval(...arguments)},_o.clearTimeout=function(){return clearTimeout(...arguments)},_o.clearInterval=function(){return clearInterval(...arguments)};class Io{constructor(e,t,n,i,s){if("object"==typeof e)this.width=e.width,this.height=e.height,this.aspectRatio=e.aspectRatio,this.encoding={maxBitrate:e.maxBitrate,maxFramerate:e.maxFramerate,priority:e.priority};else{if(void 0===t||void 0===n)throw new TypeError("Unsupported options: provide at least width, height and maxBitrate");this.width=e,this.height=t,this.aspectRatio=e/t,this.encoding={maxBitrate:n,maxFramerate:i,priority:s}}}get resolution(){return{width:this.width,height:this.height,frameRate:this.encoding.maxFramerate,aspectRatio:this.aspectRatio}}}const Oo=["vp8","h264"],Mo=["vp8","h264","vp9","av1"];function xo(e){return!!Oo.find((t=>t===e))}var Do;e.AudioPresets=void 0,(Do=e.AudioPresets||(e.AudioPresets={})).telephone={maxBitrate:12e3},Do.speech={maxBitrate:2e4},Do.music={maxBitrate:32e3},Do.musicStereo={maxBitrate:48e3},Do.musicHighQuality={maxBitrate:64e3},Do.musicHighQualityStereo={maxBitrate:96e3};const No={h90:new Io(160,90,9e4,20),h180:new Io(320,180,16e4,20),h216:new Io(384,216,18e4,20),h360:new Io(640,360,45e4,20),h540:new Io(960,540,8e5,25),h720:new Io(1280,720,17e5,30),h1080:new Io(1920,1080,3e6,30),h1440:new Io(2560,1440,5e6,30),h2160:new Io(3840,2160,8e6,30)},Lo={h120:new Io(160,120,7e4,20),h180:new Io(240,180,125e3,20),h240:new Io(320,240,14e4,20),h360:new Io(480,360,33e4,20),h480:new Io(640,480,5e5,20),h540:new Io(720,540,6e5,25),h720:new Io(960,720,13e5,30),h1080:new Io(1440,1080,23e5,30),h1440:new Io(1920,1440,38e5,30)},Ao={h360fps3:new Io(640,360,2e5,3,"medium"),h360fps15:new Io(640,360,4e5,15,"medium"),h720fps5:new Io(1280,720,8e5,5,"medium"),h720fps15:new Io(1280,720,15e5,15,"medium"),h720fps30:new Io(1280,720,2e6,30,"medium"),h1080fps15:new Io(1920,1080,25e5,15,"medium"),h1080fps30:new Io(1920,1080,5e6,30,"medium"),original:new Io(0,0,7e6,30,"medium")};const Uo=[];e.VideoQuality=void 0,function(e){e[e.LOW=0]="LOW",e[e.MEDIUM=1]="MEDIUM",e[e.HIGH=2]="HIGH"}(e.VideoQuality||(e.VideoQuality={}));class jo extends Gi.EventEmitter{constructor(t,n){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};var s;super(),this.attachedElements=[],this.isMuted=!1,this.streamState=jo.StreamState.Active,this.isInBackground=!1,this._currentBitrate=0,this.log=ki,this.appVisibilityChangedListener=()=>{this.backgroundTimeout&&clearTimeout(this.backgroundTimeout),"hidden"===document.visibilityState?this.backgroundTimeout=setTimeout((()=>this.handleAppVisibilityChanged()),5e3):this.handleAppVisibilityChanged()},this.log=yi(null!==(s=i.loggerName)&&void 0!==s?s:e.LoggerNames.Track),this.loggerContextCb=i.loggerContextCb,this.setMaxListeners(100),this.kind=n,this._mediaStreamTrack=t,this._mediaStreamID=t.id,this.source=jo.Source.Unknown}get logContext(){var e;return Object.assign(Object.assign({},null===(e=this.loggerContextCb)||void 0===e?void 0:e.call(this)),zo(this))}get currentBitrate(){return this._currentBitrate}get mediaStreamTrack(){return this._mediaStreamTrack}get mediaStreamID(){return this._mediaStreamID}attach(t){let n="audio";this.kind===jo.Kind.Video&&(n="video"),0===this.attachedElements.length&&jo.Kind.Video&&this.addAppVisibilityListener(),t||("audio"===n&&(Uo.forEach((e=>{null!==e.parentElement||t||(t=e)})),t&&Uo.splice(Uo.indexOf(t),1)),t||(t=document.createElement(n))),this.attachedElements.includes(t)||this.attachedElements.push(t),Fo(this.mediaStreamTrack,t);const i=t.srcObject.getTracks(),s=i.some((e=>"audio"===e.kind));return t.play().then((()=>{this.emit(s?e.TrackEvent.AudioPlaybackStarted:e.TrackEvent.VideoPlaybackStarted)})).catch((n=>{"NotAllowedError"===n.name?this.emit(s?e.TrackEvent.AudioPlaybackFailed:e.TrackEvent.VideoPlaybackFailed,n):"AbortError"===n.name?ki.debug("".concat(s?"audio":"video"," playback aborted, likely due to new play request")):ki.warn("could not playback ".concat(s?"audio":"video"),n),s&&t&&i.some((e=>"video"===e.kind))&&"NotAllowedError"===n.name&&(t.muted=!0,t.play().catch((()=>{})))})),this.emit(e.TrackEvent.ElementAttached,t),t}detach(t){try{if(t){Bo(this.mediaStreamTrack,t);const n=this.attachedElements.indexOf(t);return n>=0&&(this.attachedElements.splice(n,1),this.recycleElement(t),this.emit(e.TrackEvent.ElementDetached,t)),t}const n=[];return this.attachedElements.forEach((t=>{Bo(this.mediaStreamTrack,t),n.push(t),this.recycleElement(t),this.emit(e.TrackEvent.ElementDetached,t)})),this.attachedElements=[],n}finally{0===this.attachedElements.length&&this.removeAppVisibilityListener()}}stop(){this.stopMonitor(),this._mediaStreamTrack.stop()}enable(){this._mediaStreamTrack.enabled=!0}disable(){this._mediaStreamTrack.enabled=!1}stopMonitor(){this.monitorInterval&&clearInterval(this.monitorInterval)}updateLoggerOptions(e){e.loggerName&&(this.log=yi(e.loggerName)),e.loggerContextCb&&(this.loggerContextCb=e.loggerContextCb)}recycleElement(e){if(e instanceof HTMLAudioElement){let t=!0;e.pause(),Uo.forEach((e=>{e.parentElement||(t=!1)})),t&&Uo.push(e)}}handleAppVisibilityChanged(){return wi(this,void 0,void 0,(function*(){this.isInBackground="hidden"===document.visibilityState}))}addAppVisibilityListener(){da()?(this.isInBackground="hidden"===document.visibilityState,document.addEventListener("visibilitychange",this.appVisibilityChangedListener)):this.isInBackground=!1}removeAppVisibilityListener(){da()&&document.removeEventListener("visibilitychange",this.appVisibilityChangedListener)}}function Fo(e,t){let n,i;n=t.srcObject instanceof MediaStream?t.srcObject:new MediaStream,i="audio"===e.kind?n.getAudioTracks():n.getVideoTracks(),i.includes(e)||(i.forEach((e=>{n.removeTrack(e)})),n.addTrack(e)),aa()&&t instanceof HTMLVideoElement||(t.autoplay=!0),t.muted=0===n.getAudioTracks().length,t instanceof HTMLVideoElement&&(t.playsInline=!0),t.srcObject!==n&&(t.srcObject=n,(aa()||oa())&&t instanceof HTMLVideoElement&&setTimeout((()=>{t.srcObject=n,t.play().catch((()=>{}))}),0))}function Bo(e,t){if(t.srcObject instanceof MediaStream){const n=t.srcObject;n.removeTrack(e),n.getTracks().length>0?t.srcObject=n:t.srcObject=null}}function Vo(e,t,n){var i;const s=null!==(i=function(e){if(void 0!==e)return"function"==typeof structuredClone?structuredClone(e):JSON.parse(JSON.stringify(e))}(e))&&void 0!==i?i:{};return!0===s.audio&&(s.audio={}),!0===s.video&&(s.video={}),s.audio&&qo(s.audio,t),s.video&&qo(s.video,n),s}function qo(e,t){return Object.keys(t).forEach((n=>{void 0===e[n]&&(e[n]=t[n])})),e}function Ko(e){const t={};if(e.video)if("object"==typeof e.video){const n={},i=n,s=e.video;Object.keys(s).forEach((e=>{if("resolution"===e)qo(i,s.resolution);else i[e]=s[e]})),t.video=n}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 Go(){const e="undefined"!=typeof window&&(window.AudioContext||window.webkitAudioContext);if(e)return new e({latencyHint:"interactive"})}function Wo(e){var t,n;let i=null===(t=e.video)||void 0===t||t;return e.resolution&&e.resolution.width>0&&e.resolution.height>0&&(i="boolean"==typeof i?{}:i,i=aa()?Object.assign(Object.assign({},i),{width:{max:e.resolution.width},height:{max:e.resolution.height},frameRate:e.resolution.frameRate}):Object.assign(Object.assign({},i),{width:{ideal:e.resolution.width},height:{ideal:e.resolution.height},frameRate:e.resolution.frameRate})),{audio:null!==(n=e.audio)&&void 0!==n&&n,video:i,controller:e.controller,selfBrowserSurface:e.selfBrowserSurface,surfaceSwitching:e.surfaceSwitching,systemAudio:e.systemAudio}}function Ho(e){const t=e.split("/")[1].toLowerCase();if(!Mo.includes(t))throw Error("Video codec not supported: ".concat(t));return t}function Jo(e){const t=[];return e.forEach((e=>{void 0!==e.track&&t.push(new kn({cid:e.track.mediaStreamID,track:e.trackInfo}))})),t}function zo(e){return e instanceof jo?{trackID:e.sid,source:e.source,muted:e.isMuted,enabled:e.mediaStreamTrack.enabled,kind:e.kind,streamID:e.mediaStreamID,streamTrackID:e.mediaStreamTrack.id}:{trackID:e.trackSid,enabled:e.isEnabled,muted:e.isMuted,trackInfo:Object.assign({mimeType:e.mimeType,name:e.trackName,encrypted:e.isEncrypted,kind:e.kind,source:e.source},e.track?zo(e.track):{})}}!function(e){let t,n,i;!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"}(n=e.Source||(e.Source={})),function(e){e.Active="active",e.Paused="paused",e.Unknown="unknown"}(i=e.StreamState||(e.StreamState={})),e.kindToProto=function(e){switch(e){case t.Audio:return Ue.AUDIO;case t.Video:return Ue.VIDEO;default:return Ue.DATA}},e.kindFromProto=function(e){switch(e){case Ue.AUDIO:return t.Audio;case Ue.VIDEO:return t.Video;default:return t.Unknown}},e.sourceToProto=function(e){switch(e){case n.Camera:return je.CAMERA;case n.Microphone:return je.MICROPHONE;case n.ScreenShare:return je.SCREEN_SHARE;case n.ScreenShareAudio:return je.SCREEN_SHARE_AUDIO;default:return je.UNKNOWN}},e.sourceFromProto=function(e){switch(e){case je.CAMERA:return n.Camera;case je.MICROPHONE:return n.Microphone;case je.SCREEN_SHARE:return n.ScreenShare;case je.SCREEN_SHARE_AUDIO:return n.ScreenShareAudio;default:return n.Unknown}},e.streamStateFromProto=function(e){switch(e){case cn.ACTIVE:return i.Active;case cn.PAUSED:return i.Paused;default:return i.Unknown}}}(jo||(jo={}));const Qo="https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension";function Yo(e){return wi(this,void 0,void 0,(function*(){return new Promise((t=>_o.setTimeout(t,e)))}))}function Xo(){return"addTransceiver"in RTCPeerConnection.prototype}function Zo(){return"addTrack"in RTCPeerConnection.prototype}function $o(){if(!("getCapabilities"in RTCRtpSender))return!1;if(aa())return!1;const e=RTCRtpSender.getCapabilities("video");let t=!1;if(e)for(const n of e.codecs)if("video/AV1"===n.mimeType){t=!0;break}return t}function ea(){if(!("getCapabilities"in RTCRtpSender))return!1;if(oa())return!1;if(aa()){const e=Eo();if((null==e?void 0:e.version)&&ga(e.version,"16")<0)return!1}const e=RTCRtpSender.getCapabilities("video");let t=!1;if(e)for(const n of e.codecs)if("video/VP9"===n.mimeType){t=!0;break}return t}function ta(e){return"av1"===e||"vp9"===e}function na(e){return!!document&&(e||(e=document.createElement("audio")),"setSinkId"in e)}const ia={Chrome:"100",Safari:"15",Firefox:"100"};function sa(){return"undefined"!=typeof RTCPeerConnection&&(Xo()||Zo())}function oa(){var e;return"Firefox"===(null===(e=Eo())||void 0===e?void 0:e.name)}function aa(){var e;return"Safari"===(null===(e=Eo())||void 0===e?void 0:e.name)}function ra(){const e=Eo();return"Safari"===(null==e?void 0:e.name)&&e.version.startsWith("17.")}function ca(){return!!da()&&/Tablet|iPad|Mobile|Android|BlackBerry/.test(navigator.userAgent)}function da(){return"undefined"!=typeof document}function la(){return"ReactNative"==navigator.product}function ua(e){return e.hostname.endsWith(".livekit.cloud")||e.hostname.endsWith(".livekit.run")}function ha(){if(global&&global.LiveKitReactNativeGlobal)return global.LiveKitReactNativeGlobal}function ma(){if(!la())return;let e=ha();return e?e.platform:void 0}function pa(){if(da())return window.devicePixelRatio;if(la()){let e=ha();if(e)return e.devicePixelRatio}return 1}function ga(e,t){const n=e.split("."),i=t.split("."),s=Math.min(n.length,i.length);for(let e=0;e<s;++e){const t=parseInt(n[e],10),o=parseInt(i[e],10);if(t>o)return 1;if(t<o)return-1;if(e===s-1&&t===o)return 0}return""===e&&""!==t?-1:""===t?1:n.length==i.length?0:n.length<i.length?-1:1}function fa(e){for(const t of e)t.target.handleResize(t)}function va(e){for(const t of e)t.target.handleVisibilityChanged(t)}let ka=null;const Ta=()=>(ka||(ka=new ResizeObserver(fa)),ka);let ya=null;const ba=()=>(ya||(ya=new IntersectionObserver(va,{root:null,rootMargin:"0px"})),ya);let Ca,Sa;function Ea(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:16,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:16,n=arguments.length>2&&void 0!==arguments[2]&&arguments[2],i=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),i&&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(),[r]=a.getTracks();if(!r)throw Error("Could not get empty media stream video track");return r.enabled=n,r}function wa(){if(!Sa){const e=new AudioContext,t=e.createOscillator(),n=e.createGain();n.gain.setValueAtTime(0,0);const i=e.createMediaStreamDestination();if(t.connect(n),n.connect(i),t.start(),[Sa]=i.stream.getAudioTracks(),!Sa)throw Error("Could not get empty media stream audio track");Sa.enabled=!1}return Sa.clone()}class Pa{constructor(e,t){this.onFinally=t,this.promise=new Promise(((t,n)=>wi(this,void 0,void 0,(function*(){this.resolve=t,this.reject=n,e&&(yield e(t,n))})))).finally((()=>{var e;return null===(e=this.onFinally)||void 0===e?void 0:e.call(this)}))}}class Ra{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()})),n=this._locking.then((()=>e));return this._locking=this._locking.then((()=>t)),n}}function _a(e){if("string"==typeof e)return e;if(Array.isArray(e))return e[0];if(e.exact)return Array.isArray(e.exact)?e.exact[0]:e.exact;if(e.ideal)return Array.isArray(e.ideal)?e.ideal[0]:e.ideal;throw Error("could not unwrap constraint")}function Ia(e){return e.startsWith("ws")?e.replace(/^(ws)/,"http"):e}const Oa="default";class Ma{static getInstance(){return void 0===this.instance&&(this.instance=new Ma),this.instance}getDevices(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];var n;return wi(this,void 0,void 0,(function*(){if((null===(n=Ma.userMediaPromiseMap)||void 0===n?void 0:n.size)>0){ki.debug("awaiting getUserMedia promise");try{e?yield Ma.userMediaPromiseMap.get(e):yield Promise.all(Ma.userMediaPromiseMap.values())}catch(e){ki.warn("error waiting for media permissons")}}let i=yield navigator.mediaDevices.enumerateDevices();if(t&&(!aa()||!this.hasDeviceInUse(e))){if(0===i.length||i.some((t=>{const n=""===t.label,i=!e||t.kind===e;return n&&i}))){const t={video:"audioinput"!==e&&"audiooutput"!==e,audio:"videoinput"!==e},n=yield navigator.mediaDevices.getUserMedia(t);i=yield navigator.mediaDevices.enumerateDevices(),n.getTracks().forEach((e=>{e.stop()}))}}return e&&(i=i.filter((t=>t.kind===e))),i}))}normalizeDeviceId(e,t,n){return wi(this,void 0,void 0,(function*(){if(t!==Oa)return t;const i=yield this.getDevices(e),s=new Map(i.map((e=>[e.groupId,0])));i.forEach((e=>{var t;return s.set(e.groupId,(null!==(t=s.get(e.groupId))&&void 0!==t?t:0)+1)}));const o=i.find((e=>{var t;return(n===e.groupId||(null!==(t=s.get(e.groupId))&&void 0!==t?t:0)>1)&&e.deviceId!==Oa}));return null==o?void 0:o.deviceId}))}hasDeviceInUse(e){return e?Ma.userMediaPromiseMap.has(e):Ma.userMediaPromiseMap.size>0}}Ma.mediaDeviceKinds=["audioinput","audiooutput","videoinput"],Ma.userMediaPromiseMap=new Map;class xa extends jo{get constraints(){return this._constraints}constructor(t,n,i){let s=arguments.length>3&&void 0!==arguments[3]&&arguments[3];super(t,n,arguments.length>4?arguments[4]:void 0),this._isUpstreamPaused=!1,this.handleTrackMuteEvent=()=>this.debouncedTrackMuteHandler().catch((()=>this.log.debug("track mute bounce got cancelled by an unmute event",this.logContext))),this.debouncedTrackMuteHandler=bo((()=>wi(this,void 0,void 0,(function*(){yield this.pauseUpstream()}))),5e3),this.handleTrackUnmuteEvent=()=>wi(this,void 0,void 0,(function*(){this.debouncedTrackMuteHandler.cancel("unmute"),yield this.resumeUpstream()})),this.handleEnded=()=>{this.isInBackground&&(this.reacquireTrack=!0),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent),this.emit(e.TrackEvent.Ended,this)},this.reacquireTrack=!1,this.providedByUser=s,this.muteLock=new Ra,this.pauseUpstreamLock=new Ra,this.processorLock=new Ra,this.restartLock=new Ra,this.setMediaStreamTrack(t,!0),this._constraints=t.getConstraints(),i&&(this._constraints=i)}get id(){return this._mediaStreamTrack.id}get dimensions(){if(this.kind!==jo.Kind.Video)return;const{width:e,height:t}=this._mediaStreamTrack.getSettings();return e&&t?{width:e,height:t}:void 0}get isUpstreamPaused(){return this._isUpstreamPaused}get isUserProvided(){return this.providedByUser}get mediaStreamTrack(){var e,t;return null!==(t=null===(e=this.processor)||void 0===e?void 0:e.processedTrack)&&void 0!==t?t:this._mediaStreamTrack}setMediaStreamTrack(e,t){return wi(this,void 0,void 0,(function*(){if(e===this._mediaStreamTrack&&!t)return;let n;if(this._mediaStreamTrack&&(this.attachedElements.forEach((e=>{Bo(this._mediaStreamTrack,e)})),this.debouncedTrackMuteHandler.cancel("new-track"),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent)),this.mediaStream=new MediaStream([e]),e&&(e.addEventListener("ended",this.handleEnded),e.addEventListener("mute",this.handleTrackMuteEvent),e.addEventListener("unmute",this.handleTrackUnmuteEvent),this._constraints=e.getConstraints()),this.processor&&e){const t=yield this.processorLock.lock();try{if(this.log.debug("restarting processor",this.logContext),"unknown"===this.kind)throw TypeError("cannot set processor on track of unknown kind");this.processorElement&&(Fo(e,this.processorElement),this.processorElement.muted=!0),yield this.processor.restart({track:e,kind:this.kind,element:this.processorElement}),n=this.processor.processedTrack}finally{t()}}this.sender&&(yield this.sender.replaceTrack(null!=n?n:e)),this.providedByUser||this._mediaStreamTrack===e||this._mediaStreamTrack.stop(),this._mediaStreamTrack=e,e&&(this._mediaStreamTrack.enabled=!this.isMuted,yield this.resumeUpstream(),this.attachedElements.forEach((t=>{Fo(null!=n?n:e,t)})))}))}waitForDimensions(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1e3;var t;return wi(this,void 0,void 0,(function*(){if(this.kind===jo.Kind.Audio)throw new Error("cannot get dimensions for audio tracks");"iOS"===(null===(t=Eo())||void 0===t?void 0:t.os)&&(yield Yo(10));const n=Date.now();for(;Date.now()-n<e;){const e=this.dimensions;if(e)return e;yield Yo(50)}throw new ho("unable to get track dimensions after timeout")}))}getDeviceId(){return wi(this,void 0,void 0,(function*(){if(this.source===jo.Source.ScreenShare)return;const{deviceId:e,groupId:t}=this._mediaStreamTrack.getSettings(),n=this.kind===jo.Kind.Audio?"audioinput":"videoinput";return Ma.getInstance().normalizeDeviceId(n,e,t)}))}mute(){return wi(this,void 0,void 0,(function*(){return this.setTrackMuted(!0),this}))}unmute(){return wi(this,void 0,void 0,(function*(){return this.setTrackMuted(!1),this}))}replaceTrack(e,t){return wi(this,void 0,void 0,(function*(){if(!this.sender)throw new ho("unable to replace an unpublished track");let n,i;return"boolean"==typeof t?n=t:void 0!==t&&(n=t.userProvidedTrack,i=t.stopProcessor),this.providedByUser=null==n||n,this.log.debug("replace MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(e),i&&this.processor&&(yield this.stopProcessor()),this}))}restart(t){return wi(this,void 0,void 0,(function*(){const n=yield this.restartLock.lock();try{t||(t=this._constraints),this.log.debug("restarting track with constraints",Object.assign(Object.assign({},this.logContext),{constraints:t}));const n={audio:!1,video:!1};this.kind===jo.Kind.Video?n.video=t:n.audio=t,this.attachedElements.forEach((e=>{Bo(this.mediaStreamTrack,e)})),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.stop();const i=(yield navigator.mediaDevices.getUserMedia(n)).getTracks()[0];return i.addEventListener("ended",this.handleEnded),this.log.debug("re-acquired MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(i),this._constraints=t,this.emit(e.TrackEvent.Restarted,this),this}finally{n()}}))}setTrackMuted(t){this.log.debug("setting ".concat(this.kind," track ").concat(t?"muted":"unmuted"),this.logContext),this.isMuted===t&&this._mediaStreamTrack.enabled!==t||(this.isMuted=t,this._mediaStreamTrack.enabled=!t,this.emit(t?e.TrackEvent.Muted:e.TrackEvent.Unmuted,this))}get needsReAcquisition(){return"live"!==this._mediaStreamTrack.readyState||this._mediaStreamTrack.muted||!this._mediaStreamTrack.enabled||this.reacquireTrack}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return wi(this,void 0,void 0,(function*(){yield e.handleAppVisibilityChanged.call(this),ca()&&(this.log.debug("visibility changed, is in Background: ".concat(this.isInBackground),this.logContext),this.isInBackground||!this.needsReAcquisition||this.isUserProvided||this.isMuted||(this.log.debug("track needs to be reacquired, restarting ".concat(this.source),this.logContext),yield this.restart(),this.reacquireTrack=!1))}))}stop(){var e;super.stop(),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent),null===(e=this.processor)||void 0===e||e.destroy(),this.processor=void 0}pauseUpstream(){return wi(this,void 0,void 0,(function*(){const t=yield this.pauseUpstreamLock.lock();try{if(!0===this._isUpstreamPaused)return;if(!this.sender)return void this.log.warn("unable to pause upstream for an unpublished track",this.logContext);this._isUpstreamPaused=!0,this.emit(e.TrackEvent.UpstreamPaused,this);const t=Eo();if("Safari"===(null==t?void 0:t.name)&&ga(t.version,"12.0")<0)throw new uo("pauseUpstream is not supported on Safari < 12.");yield this.sender.replaceTrack(null)}finally{t()}}))}resumeUpstream(){return wi(this,void 0,void 0,(function*(){const t=yield this.pauseUpstreamLock.lock();try{if(!1===this._isUpstreamPaused)return;if(!this.sender)return void this.log.warn("unable to resume upstream for an unpublished track",this.logContext);this._isUpstreamPaused=!1,this.emit(e.TrackEvent.UpstreamResumed,this),yield this.sender.replaceTrack(this._mediaStreamTrack)}finally{t()}}))}getRTCStatsReport(){var e;return wi(this,void 0,void 0,(function*(){if(!(null===(e=this.sender)||void 0===e?void 0:e.getStats))return;return yield this.sender.getStats()}))}setProcessor(t){let n=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];var i,s;return wi(this,void 0,void 0,(function*(){const o=yield this.processorLock.lock();try{if(this.log.debug("setting up processor",this.logContext),this.processor&&(yield this.stopProcessor()),"unknown"===this.kind)throw TypeError("cannot set processor on track of unknown kind");this.processorElement=null!==(i=this.processorElement)&&void 0!==i?i:document.createElement(this.kind),Fo(this._mediaStreamTrack,this.processorElement),this.processorElement.muted=!0,this.processorElement.play().catch((e=>this.log.error("failed to play processor element",Object.assign(Object.assign({},this.logContext),{error:e}))));const o={kind:this.kind,track:this._mediaStreamTrack,element:this.processorElement,audioContext:this.audioContext};if(yield t.init(o),this.processor=t,this.processor.processedTrack){for(const e of this.attachedElements)e!==this.processorElement&&n&&(Bo(this._mediaStreamTrack,e),Fo(this.processor.processedTrack,e));yield null===(s=this.sender)||void 0===s?void 0:s.replaceTrack(this.processor.processedTrack)}this.emit(e.TrackEvent.TrackProcessorUpdate,this.processor)}finally{o()}}))}getProcessor(){return this.processor}stopProcessor(){var t,n;return wi(this,void 0,void 0,(function*(){this.processor&&(this.log.debug("stopping processor",this.logContext),null===(t=this.processor.processedTrack)||void 0===t||t.stop(),yield this.processor.destroy(),this.processor=void 0,null===(n=this.processorElement)||void 0===n||n.remove(),this.processorElement=void 0,yield this.restart(),this.emit(e.TrackEvent.TrackProcessorUpdate))}))}}class Da extends Gi.EventEmitter{constructor(t){super(),this.onWorkerMessage=t=>{var n,i;const{kind:s,data:o}=t.data;switch(s){case"error":ki.error(o.error.message),this.emit(e.EncryptionEvent.EncryptionError,o.error);break;case"initAck":o.enabled&&this.keyProvider.getKeys().forEach((e=>{this.postKey(e)}));break;case"enable":if(this.encryptionEnabled!==o.enabled&&o.participantIdentity===(null===(n=this.room)||void 0===n?void 0:n.localParticipant.identity))this.emit(e.EncryptionEvent.ParticipantEncryptionStatusChanged,o.enabled,this.room.localParticipant),this.encryptionEnabled=o.enabled;else if(o.participantIdentity){const t=null===(i=this.room)||void 0===i?void 0:i.getParticipantByIdentity(o.participantIdentity);if(!t)throw TypeError("couldn't set encryption status, participant not found".concat(o.participantIdentity));this.emit(e.EncryptionEvent.ParticipantEncryptionStatusChanged,o.enabled,t)}this.encryptionEnabled&&this.keyProvider.getKeys().forEach((e=>{this.postKey(e)}));break;case"ratchetKey":this.keyProvider.emit(e.KeyProviderEvent.KeyRatcheted,o.material,o.keyIndex)}},this.onWorkerError=t=>{ki.error("e2ee worker encountered an error:",{error:t.error}),this.emit(e.EncryptionEvent.EncryptionError,t.error)},this.keyProvider=t.keyProvider,this.worker=t.worker,this.encryptionEnabled=!1}setup(e){if(!to())throw new uo("tried to setup end-to-end encryption on an unsupported browser");if(ki.info("setting up e2ee"),e!==this.room){this.room=e,this.setupEventListeners(e,this.keyProvider);const t={kind:"init",data:{keyProviderOptions:this.keyProvider.getOptions(),loglevel:bi.getLevel()}};this.worker&&(ki.info("initializing worker",{worker:this.worker}),this.worker.onmessage=this.onWorkerMessage,this.worker.onerror=this.onWorkerError,this.worker.postMessage(t))}}setParticipantCryptorEnabled(e,t){ki.debug("set e2ee to ".concat(e," for participant ").concat(t)),this.postEnable(e,t)}setSifTrailer(e){e&&0!==e.length?this.postSifTrailer(e):ki.warn("ignoring server sent trailer as it's empty")}setupEngine(t){t.on(e.EngineEvent.RTPVideoMapUpdate,(e=>{this.postRTPMap(e)}))}setupEventListeners(t,n){t.on(e.RoomEvent.TrackPublished,((e,t)=>this.setParticipantCryptorEnabled(e.trackInfo.encryption!==Xe.NONE,t.identity))),t.on(e.RoomEvent.ConnectionStateChanged,(n=>{n===e.ConnectionState.Connected&&t.remoteParticipants.forEach((e=>{e.trackPublications.forEach((t=>{this.setParticipantCryptorEnabled(t.trackInfo.encryption!==Xe.NONE,e.identity)}))}))})).on(e.RoomEvent.TrackUnsubscribed,((e,t,n)=>{var i;const s={kind:"removeTransform",data:{participantIdentity:n.identity,trackId:e.mediaStreamID}};null===(i=this.worker)||void 0===i||i.postMessage(s)})).on(e.RoomEvent.TrackSubscribed,((e,t,n)=>{this.setupE2EEReceiver(e,n.identity,t.trackInfo)})).on(e.RoomEvent.SignalConnected,(()=>{if(!this.room)throw new TypeError("expected room to be present on signal connect");this.setParticipantCryptorEnabled(this.room.localParticipant.isE2EEEnabled,this.room.localParticipant.identity),n.getKeys().forEach((e=>{this.postKey(e)}))})),t.localParticipant.on(e.ParticipantEvent.LocalTrackPublished,(e=>wi(this,void 0,void 0,(function*(){this.setupE2EESender(e.track,e.track.sender)})))),n.on(e.KeyProviderEvent.SetKey,(e=>this.postKey(e))).on(e.KeyProviderEvent.RatchetRequest,((e,t)=>this.postRatchetRequest(e,t)))}postRatchetRequest(e,t){if(!this.worker)throw Error("could not ratchet key, worker is missing");const n={kind:"ratchetRequest",data:{participantIdentity:e,keyIndex:t}};this.worker.postMessage(n)}postKey(e){let{key:t,participantIdentity:n,keyIndex:i}=e;var s;if(!this.worker)throw Error("could not set key, worker is missing");const o={kind:"setKey",data:{participantIdentity:n,isPublisher:n===(null===(s=this.room)||void 0===s?void 0:s.localParticipant.identity),key:t,keyIndex:i}};this.worker.postMessage(o)}postEnable(e,t){if(!this.worker)throw new ReferenceError("failed to enable e2ee, worker is not ready");{const n={kind:"enable",data:{enabled:e,participantIdentity:t}};this.worker.postMessage(n)}}postRTPMap(e){var t;if(!this.worker)throw TypeError("could not post rtp map, worker is missing");if(!(null===(t=this.room)||void 0===t?void 0:t.localParticipant.identity))throw TypeError("could not post rtp map, local participant identity is missing");const n={kind:"setRTPMap",data:{map:e,participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(n)}postSifTrailer(e){if(!this.worker)throw Error("could not post SIF trailer, worker is missing");const t={kind:"setSifTrailer",data:{trailer:e}};this.worker.postMessage(t)}setupE2EEReceiver(e,t,n){if(e.receiver){if(!(null==n?void 0:n.mimeType)||""===n.mimeType)throw new TypeError("MimeType missing from trackInfo, cannot set up E2EE cryptor");this.handleReceiver(e.receiver,e.mediaStreamID,t,"video"===e.kind?Ho(n.mimeType):void 0)}}setupE2EESender(e,t){e instanceof xa&&t?this.handleSender(t,e.mediaStreamID,void 0):t||ki.warn("early return because sender is not ready")}handleReceiver(e,t,n,i){return wi(this,void 0,void 0,(function*(){if(this.worker){if(no()){const s={kind:"decode",participantIdentity:n,trackId:t,codec:i};e.transform=new RTCRtpScriptTransform(this.worker,s)}else{if(Xs in e&&i){const e={kind:"updateCodec",data:{trackId:t,codec:i,participantIdentity:n}};return void this.worker.postMessage(e)}let s=e.writableStream,o=e.readableStream;if(!s||!o){const t=e.createEncodedStreams();e.writableStream=t.writable,s=t.writable,e.readableStream=t.readable,o=t.readable}const a={kind:"decode",data:{readableStream:o,writableStream:s,trackId:t,codec:i,participantIdentity:n}};this.worker.postMessage(a,[o,s])}e[Xs]=!0}}))}handleSender(e,t,n){var i;if(!(Xs in e)&&this.worker){if(!(null===(i=this.room)||void 0===i?void 0:i.localParticipant.identity)||""===this.room.localParticipant.identity)throw TypeError("local identity needs to be known in order to set up encrypted sender");if(no()){ki.info("initialize script transform");const i={kind:"encode",participantIdentity:this.room.localParticipant.identity,trackId:t,codec:n};e.transform=new RTCRtpScriptTransform(this.worker,i)}else{ki.info("initialize encoded streams");const i=e.createEncodedStreams(),s={kind:"encode",data:{readableStream:i.readable,writableStream:i.writable,codec:n,trackId:t,participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(s,[i.readable,i.writable])}e[Xs]=!0}}}var Na;!function(e){e[e.WAITING=0]="WAITING",e[e.RUNNING=1]="RUNNING",e[e.COMPLETED=2]="COMPLETED"}(Na||(Na={}));class La{constructor(){this.pendingTasks=new Map,this.taskMutex=new Ra,this.nextTaskIndex=0}run(e){return wi(this,void 0,void 0,(function*(){const t={id:this.nextTaskIndex++,enqueuedAt:Date.now(),status:Na.WAITING};this.pendingTasks.set(t.id,t);const n=yield this.taskMutex.lock();try{return t.executedAt=Date.now(),t.status=Na.RUNNING,yield e()}finally{t.status=Na.COMPLETED,this.pendingTasks.delete(t.id),n()}}))}flush(){return wi(this,void 0,void 0,(function*(){return this.run((()=>wi(this,void 0,void 0,(function*(){}))))}))}snapshot(){return Array.from(this.pendingTasks.values())}}const Aa=["syncState","trickle","offer","answer","simulate","leave"];var Ua;!function(e){e[e.CONNECTING=0]="CONNECTING",e[e.CONNECTED=1]="CONNECTED",e[e.RECONNECTING=2]="RECONNECTING",e[e.DISCONNECTING=3]="DISCONNECTING",e[e.DISCONNECTED=4]="DISCONNECTED"}(Ua||(Ua={}));class ja{get currentState(){return this.state}get isDisconnected(){return this.state===Ua.DISCONNECTING||this.state===Ua.DISCONNECTED}get isEstablishingConnection(){return this.state===Ua.CONNECTING||this.state===Ua.RECONNECTING}constructor(){let t=arguments.length>0&&void 0!==arguments[0]&&arguments[0],n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};var i;this.rtt=0,this.state=Ua.DISCONNECTED,this.log=ki,this.resetCallbacks=()=>{this.onAnswer=void 0,this.onLeave=void 0,this.onLocalTrackPublished=void 0,this.onLocalTrackUnpublished=void 0,this.onNegotiateRequested=void 0,this.onOffer=void 0,this.onRemoteMuteChanged=void 0,this.onSubscribedQualityUpdate=void 0,this.onTokenRefresh=void 0,this.onTrickle=void 0,this.onClose=void 0},this.log=yi(null!==(i=n.loggerName)&&void 0!==i?i:e.LoggerNames.Signal),this.loggerContextCb=n.loggerContextCb,this.useJSON=t,this.requestQueue=new La,this.queuedRequests=[],this.closingLock=new Ra,this.connectionLock=new Ra,this.state=Ua.DISCONNECTED}get logContext(){var e,t;return null!==(t=null===(e=this.loggerContextCb)||void 0===e?void 0:e.call(this))&&void 0!==t?t:{}}join(e,t,n,i){return wi(this,void 0,void 0,(function*(){this.state=Ua.CONNECTING,this.options=n;return yield this.connect(e,t,n,i)}))}reconnect(e,t,n,i){return wi(this,void 0,void 0,(function*(){if(!this.options)return void this.log.warn("attempted to reconnect without signal options being set, ignoring",this.logContext);this.state=Ua.RECONNECTING,this.clearPingInterval();return yield this.connect(e,t,Object.assign(Object.assign({},this.options),{reconnect:!0,sid:n,reconnectReason:i}))}))}connect(e,t,n,i){this.connectOptions=n,e=(e=function(e){return e.startsWith("http")?e.replace(/^(http)/,"ws"):e}(e)).replace(/\/$/,""),e+="/rtc";const s=function(e,t,n){var i;const s=new URLSearchParams;s.set("access_token",e),n.reconnect&&(s.set("reconnect","1"),n.sid&&s.set("sid",n.sid));s.set("auto_subscribe",n.autoSubscribe?"1":"0"),s.set("sdk",la()?"reactnative":"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);n.adaptiveStream&&s.set("adaptive_stream","1");n.reconnectReason&&s.set("reconnect_reason",n.reconnectReason.toString());(null===(i=navigator.connection)||void 0===i?void 0:i.type)&&s.set("network",navigator.connection.type);return"?".concat(s.toString())}(t,function(){var e;const t=new lt({sdk:ut.JS,protocol:12,version:Ro});return la()&&(t.os=null!==(e=ma())&&void 0!==e?e:""),t}(),n);return new Promise(((t,o)=>wi(this,void 0,void 0,(function*(){const a=yield this.connectionLock.lock();try{const a=()=>wi(this,void 0,void 0,(function*(){this.close(),clearTimeout(r),o(new lo("room connection has been cancelled (signal)"))})),r=setTimeout((()=>{this.close(),o(new lo("room connection has timed out (signal)"))}),n.websocketTimeout);(null==i?void 0:i.aborted)&&a(),null==i||i.addEventListener("abort",a),this.log.debug("connecting to ".concat(e+s),this.logContext),this.ws&&(yield this.close(!1)),this.ws=new WebSocket(e+s),this.ws.binaryType="arraybuffer",this.ws.onopen=()=>{clearTimeout(r)},this.ws.onerror=t=>wi(this,void 0,void 0,(function*(){if(this.state===Ua.CONNECTED)this.handleWSError(t);else{this.state=Ua.DISCONNECTED,clearTimeout(r);try{const t=yield fetch("http".concat(e.substring(2),"/validate").concat(s));if(t.status.toFixed(0).startsWith("4")){const e=yield t.text();o(new lo(e,0,t.status))}else o(new lo("Internal error",2,t.status))}catch(e){o(new lo("server was not reachable",1))}}})),this.ws.onmessage=e=>wi(this,void 0,void 0,(function*(){var s,r,c;let d;if("string"==typeof e.data){const t=JSON.parse(e.data);d=un.fromJson(t,{ignoreUnknownFields:!0})}else{if(!(e.data instanceof ArrayBuffer))return void this.log.error("could not decode websocket message: ".concat(typeof e.data),this.logContext);d=un.fromBinary(new Uint8Array(e.data))}if(this.state!==Ua.CONNECTED){let e=!1;if("join"===(null===(s=d.message)||void 0===s?void 0:s.case)?(this.state=Ua.CONNECTED,null==i||i.removeEventListener("abort",a),this.pingTimeoutDuration=d.message.value.pingTimeout,this.pingIntervalDuration=d.message.value.pingInterval,this.pingTimeoutDuration&&this.pingTimeoutDuration>0&&(this.log.debug("ping config",Object.assign(Object.assign({},this.logContext),{timeout:this.pingTimeoutDuration,interval:this.pingIntervalDuration})),this.startPingInterval()),t(d.message.value)):this.state===Ua.RECONNECTING&&"leave"!==d.message.case?(this.state=Ua.CONNECTED,null==i||i.removeEventListener("abort",a),this.startPingInterval(),"reconnect"===(null===(r=d.message)||void 0===r?void 0:r.case)?t(d.message.value):(this.log.debug("declaring signal reconnected without reconnect response received",this.logContext),t(void 0),e=!0)):this.isEstablishingConnection&&"leave"===d.message.case?o(new lo("Received leave request while trying to (re)connect",4)):n.reconnect||o(new lo("did not receive join response, got ".concat(null===(c=d.message)||void 0===c?void 0:c.case," instead"))),!e)return}this.signalLatency&&(yield Yo(this.signalLatency)),this.handleSignalResponse(d)})),this.ws.onclose=e=>{this.isEstablishingConnection&&o(new lo("Websocket got closed during a (re)connection attempt")),this.log.warn("websocket closed",Object.assign(Object.assign({},this.logContext),{reason:e.reason,code:e.code,wasClean:e.wasClean,state:this.state})),this.handleOnClose(e.reason)}}finally{a()}}))))}close(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return wi(this,void 0,void 0,(function*(){const t=yield this.closingLock.lock();try{if(e&&(this.state=Ua.DISCONNECTING),this.ws){this.ws.onmessage=null,this.ws.onopen=null,this.ws.onclose=null;const e=new Promise((e=>{this.ws?this.ws.onclose=()=>{e()}:e()}));this.ws.readyState<this.ws.CLOSING&&(this.ws.close(),yield Promise.race([e,Yo(250)])),this.ws=void 0}}finally{e&&(this.state=Ua.DISCONNECTED),this.clearPingInterval(),t()}}))}sendOffer(e){this.log.debug("sending offer",Object.assign(Object.assign({},this.logContext),{offerSdp:e.sdp})),this.sendRequest({case:"offer",value:Ba(e)})}sendAnswer(e){return this.log.debug("sending answer",Object.assign(Object.assign({},this.logContext),{answerSdp:e.sdp})),this.sendRequest({case:"answer",value:Ba(e)})}sendIceCandidate(e,t){return this.log.trace("sending ice candidate",Object.assign(Object.assign({},this.logContext),{candidate:e})),this.sendRequest({case:"trickle",value:new pn({candidateInit:JSON.stringify(e),target:t})})}sendMuteTrack(e,t){return this.sendRequest({case:"mute",value:new gn({sid:e,muted:t})})}sendAddTrack(e){return this.sendRequest({case:"addTrack",value:e})}sendUpdateLocalMetadata(e,t){return this.sendRequest({case:"updateMetadata",value:new Rn({metadata:e,name:t})})}sendUpdateTrackSettings(e){this.sendRequest({case:"trackSetting",value:e})}sendUpdateSubscription(e){return this.sendRequest({case:"subscription",value:e})}sendSyncState(e){return this.sendRequest({case:"syncState",value:e})}sendUpdateVideoLayers(e,t){return this.sendRequest({case:"updateLayers",value:new Pn({trackSid:e,layers:t})})}sendUpdateSubscriptionPermissions(e,t){return this.sendRequest({case:"subscriptionPermission",value:new Fn({allParticipants:e,trackPermissions:t})})}sendSimulateScenario(e){return this.sendRequest({case:"simulate",value:e})}sendPing(){return Promise.all([this.sendRequest({case:"ping",value:O.parse(Date.now())}),this.sendRequest({case:"pingReq",value:new Gn({timestamp:O.parse(Date.now()),rtt:O.parse(this.rtt)})})])}sendLeave(){return this.sendRequest({case:"leave",value:new En({canReconnect:!1,reason:qe.CLIENT_INITIATED})})}sendRequest(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return wi(this,void 0,void 0,(function*(){const n=!t&&!function(e){const t=Aa.indexOf(e.case)>=0;return ki.trace("request allowed to bypass queue:",{canPass:t,req:e}),t}(e);if(n&&this.state===Ua.RECONNECTING)return void this.queuedRequests.push((()=>wi(this,void 0,void 0,(function*(){yield this.sendRequest(e,!0)}))));if(t||(yield this.requestQueue.flush()),this.signalLatency&&(yield Yo(this.signalLatency)),!this.ws||this.ws.readyState!==this.ws.OPEN)return void this.log.error("cannot send signal request before connected, type: ".concat(null==e?void 0:e.case),this.logContext);const i=new ln({message:e});try{this.useJSON?this.ws.send(i.toJsonString()):this.ws.send(i.toBinary())}catch(e){this.log.error("error sending signal message",Object.assign(Object.assign({},this.logContext),{error:e}))}}))}handleSignalResponse(e){var t,n;const i=e.message;if(null==i)return void this.log.debug("received unsupported message",this.logContext);let s=!1;if("answer"===i.case){const e=Fa(i.value);this.onAnswer&&this.onAnswer(e)}else if("offer"===i.case){const e=Fa(i.value);this.onOffer&&this.onOffer(e)}else if("trickle"===i.case){const e=JSON.parse(i.value.candidateInit);this.onTrickle&&this.onTrickle(e,i.value.target)}else"update"===i.case?this.onParticipantUpdate&&this.onParticipantUpdate(null!==(t=i.value.participants)&&void 0!==t?t:[]):"trackPublished"===i.case?this.onLocalTrackPublished&&this.onLocalTrackPublished(i.value):"speakersChanged"===i.case?this.onSpeakersChanged&&this.onSpeakersChanged(null!==(n=i.value.speakers)&&void 0!==n?n:[]):"leave"===i.case?this.onLeave&&this.onLeave(i.value):"mute"===i.case?this.onRemoteMuteChanged&&this.onRemoteMuteChanged(i.value.sid,i.value.muted):"roomUpdate"===i.case?this.onRoomUpdate&&i.value.room&&this.onRoomUpdate(i.value.room):"connectionQuality"===i.case?this.onConnectionQuality&&this.onConnectionQuality(i.value):"streamStateUpdate"===i.case?this.onStreamStateUpdate&&this.onStreamStateUpdate(i.value):"subscribedQualityUpdate"===i.case?this.onSubscribedQualityUpdate&&this.onSubscribedQualityUpdate(i.value):"subscriptionPermissionUpdate"===i.case?this.onSubscriptionPermissionUpdate&&this.onSubscriptionPermissionUpdate(i.value):"refreshToken"===i.case?this.onTokenRefresh&&this.onTokenRefresh(i.value):"trackUnpublished"===i.case?this.onLocalTrackUnpublished&&this.onLocalTrackUnpublished(i.value):"subscriptionResponse"===i.case?this.onSubscriptionError&&this.onSubscriptionError(i.value):"pong"===i.case||("pongResp"===i.case?(this.rtt=Date.now()-Number.parseInt(i.value.lastPingTimestamp.toString()),this.resetPingTimeout(),s=!0):this.log.debug("unsupported message",Object.assign(Object.assign({},this.logContext),{msgCase:i.case})));s||this.resetPingTimeout()}setReconnected(){for(;this.queuedRequests.length>0;){const e=this.queuedRequests.shift();e&&this.requestQueue.run(e)}}handleOnClose(e){return wi(this,void 0,void 0,(function*(){if(this.state===Ua.DISCONNECTED)return;const t=this.onClose;yield this.close(),this.log.debug("websocket connection closed: ".concat(e),Object.assign(Object.assign({},this.logContext),{reason:e})),t&&t(e)}))}handleWSError(e){this.log.error("websocket error",Object.assign(Object.assign({},this.logContext),{error:e}))}resetPingTimeout(){this.clearPingTimeout(),this.pingTimeoutDuration?this.pingTimeout=_o.setTimeout((()=>{this.log.warn("ping timeout triggered. last pong received at: ".concat(new Date(Date.now()-1e3*this.pingTimeoutDuration).toUTCString()),this.logContext),this.handleOnClose("ping timeout")}),1e3*this.pingTimeoutDuration):this.log.warn("ping timeout duration not set",this.logContext)}clearPingTimeout(){this.pingTimeout&&_o.clearTimeout(this.pingTimeout)}startPingInterval(){this.clearPingInterval(),this.resetPingTimeout(),this.pingIntervalDuration?(this.log.debug("start ping interval",this.logContext),this.pingInterval=_o.setInterval((()=>{this.sendPing()}),1e3*this.pingIntervalDuration)):this.log.warn("ping interval duration not set",this.logContext)}clearPingInterval(){this.log.debug("clearing ping interval",this.logContext),this.clearPingTimeout(),this.pingInterval&&_o.clearInterval(this.pingInterval)}}function Fa(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 Ba(e){return new yn({sdp:e.sdp,type:e.type})}var Va={},qa={exports:{}},Ka=qa.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(Ka).forEach((function(e){Ka[e].forEach((function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")}))}));var Ga=qa.exports;!function(e){var t=function(e){return String(Number(e))===e?Number(e):e},n=function(e,n,i){var s=e.name&&e.names;e.push&&!n[e.push]?n[e.push]=[]:s&&!n[e.name]&&(n[e.name]={});var o=e.push?{}:s?n[e.name]:n;!function(e,n,i,s){if(s&&!i)n[s]=t(e[1]);else for(var o=0;o<i.length;o+=1)null!=e[o+1]&&(n[i[o]]=t(e[o+1]))}(i.match(e.reg),o,e.names,e.name),e.push&&n[e.push].push(o)},i=Ga,s=RegExp.prototype.test.bind(/^([a-z])=(.*)/);e.parse=function(e){var t={},o=[],a=t;return e.split(/(\r\n|\r|\n)/).filter(s).forEach((function(e){var t=e[0],s=e.slice(2);"m"===t&&(o.push({rtp:[],fmtp:[]}),a=o[o.length-1]);for(var r=0;r<(i[t]||[]).length;r+=1){var c=i[t][r];if(c.reg.test(s))return n(c,a,s)}})),t.media=o,t};var o=function(e,n){var i=n.split(/=(.+)/,2);return 2===i.length?e[i[0]]=t(i[1]):1===i.length&&n.length>1&&(e[i[0]]=void 0),e};e.parseParams=function(e){return e.split(/;\s?/).reduce(o,{})},e.parseFmtpConfig=e.parseParams,e.parsePayloads=function(e){return e.toString().split(" ").map(Number)},e.parseRemoteCandidates=function(e){for(var n=[],i=e.split(" ").map(t),s=0;s<i.length;s+=3)n.push({component:i[s],ip:i[s+1],port:i[s+2]});return n},e.parseImageAttributes=function(e){return e.split(" ").map((function(e){return e.substring(1,e.length-1).split(",").reduce(o,{})}))},e.parseSimulcastStreamList=function(e){return e.split(";").map((function(e){return e.split(",").map((function(e){var n,i=!1;return"~"!==e[0]?n=t(e):(n=t(e.substring(1,e.length)),i=!0),{scid:n,paused:i}}))}))}}(Va);var Wa=Ga,Ha=/%[sdv%]/g,Ja=function(e){var t=1,n=arguments,i=n.length;return e.replace(Ha,(function(e){if(t>=i)return e;var s=n[t];switch(t+=1,e){case"%%":return"%";case"%s":return String(s);case"%d":return Number(s);case"%v":return""}}))},za=function(e,t,n){var i=[e+"="+(t.format instanceof Function?t.format(t.push?n:n[t.name]):t.format)];if(t.names)for(var s=0;s<t.names.length;s+=1){var o=t.names[s];t.name?i.push(n[t.name][o]):i.push(n[t.names[s]])}else i.push(n[t.name]);return Ja.apply(null,i)},Qa=["v","o","s","i","u","e","p","c","b","t","r","z","a"],Ya=["i","c","b","a"],Xa=Va,Za=function(e,t){t=t||{},null==e.version&&(e.version=0),null==e.name&&(e.name=" "),e.media.forEach((function(e){null==e.payloads&&(e.payloads="")}));var n=t.outerOrder||Qa,i=t.innerOrder||Ya,s=[];return n.forEach((function(t){Wa[t].forEach((function(n){n.name in e&&null!=e[n.name]?s.push(za(t,n,e)):n.push in e&&null!=e[n.push]&&e[n.push].forEach((function(e){s.push(za(t,n,e))}))}))})),e.media.forEach((function(e){s.push(za("m",Wa.m[0],e)),i.forEach((function(t){Wa[t].forEach((function(n){n.name in e&&null!=e[n.name]?s.push(za(t,n,e)):n.push in e&&null!=e[n.push]&&e[n.push].forEach((function(e){s.push(za(t,n,e))}))}))}))})),s.join("\r\n")+"\r\n"},$a=Za,er=Xa.parse;const tr="negotiationStarted",nr="negotiationComplete",ir="rtpVideoPayloadTypes";class sr extends Gi.EventEmitter{get pc(){return this._pc||(this._pc=this.createPC()),this._pc}constructor(t){let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};var i;super(),this.log=ki,this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate=!1,this.trackBitrates=[],this.remoteStereoMids=[],this.remoteNackMids=[],this.negotiate=bo((e=>wi(this,void 0,void 0,(function*(){this.emit(tr);try{yield this.createAndSendOffer()}catch(t){if(!e)throw t;e(t)}}))),100),this.close=()=>{this._pc&&(this._pc.close(),this._pc.onconnectionstatechange=null,this._pc.oniceconnectionstatechange=null,this._pc.onicegatheringstatechange=null,this._pc.ondatachannel=null,this._pc.onnegotiationneeded=null,this._pc.onsignalingstatechange=null,this._pc.onicecandidate=null,this._pc.ondatachannel=null,this._pc.ontrack=null,this._pc.onconnectionstatechange=null,this._pc.oniceconnectionstatechange=null,this._pc=null)},this.log=yi(null!==(i=n.loggerName)&&void 0!==i?i:e.LoggerNames.PCTransport),this.loggerOptions=n,this.config=t,this._pc=this.createPC()}createPC(){const e=new RTCPeerConnection(this.config);return e.onicecandidate=e=>{var t;e.candidate&&(null===(t=this.onIceCandidate)||void 0===t||t.call(this,e.candidate))},e.onicecandidateerror=e=>{var t;null===(t=this.onIceCandidateError)||void 0===t||t.call(this,e)},e.oniceconnectionstatechange=()=>{var t;null===(t=this.onIceConnectionStateChange)||void 0===t||t.call(this,e.iceConnectionState)},e.onsignalingstatechange=()=>{var t;null===(t=this.onSignalingStatechange)||void 0===t||t.call(this,e.signalingState)},e.onconnectionstatechange=()=>{var t;null===(t=this.onConnectionStateChange)||void 0===t||t.call(this,e.connectionState)},e.ondatachannel=e=>{var t;null===(t=this.onDataChannel)||void 0===t||t.call(this,e)},e.ontrack=e=>{var t;null===(t=this.onTrack)||void 0===t||t.call(this,e)},e}get logContext(){var e,t;return Object.assign({},null===(t=(e=this.loggerOptions).loggerContextCb)||void 0===t?void 0:t.call(e))}get isICEConnected(){return null!==this._pc&&("connected"===this.pc.iceConnectionState||"completed"===this.pc.iceConnectionState)}addIceCandidate(e){return wi(this,void 0,void 0,(function*(){if(this.pc.remoteDescription&&!this.restartingIce)return this.pc.addIceCandidate(e);this.pendingCandidates.push(e)}))}setRemoteDescription(e){var t;return wi(this,void 0,void 0,(function*(){let n;if("offer"===e.type){let{stereoMids:t,nackMids:n}=function(e){var t;const n=[],i=[],s=er(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)))&&i.push(e.mid),e.fmtp.some((t=>t.payload===o&&(t.config.includes("sprop-stereo=1")&&n.push(e.mid),!0))))})),{stereoMids:n,nackMids:i}}(e);this.remoteStereoMids=t,this.remoteNackMids=n}else if("answer"===e.type){const i=er(null!==(t=e.sdp)&&void 0!==t?t:"");i.media.forEach((e=>{"audio"===e.type&&this.trackBitrates.some((t=>{if(!t.transceiver||e.mid!=t.transceiver.mid)return!1;let n=0;if(e.rtp.some((e=>e.codec.toUpperCase()===t.codec.toUpperCase()&&(n=e.payload,!0))),0===n)return!0;let i=!1;for(const s of e.fmtp)if(s.payload===n){s.config=s.config.split(";").filter((e=>!e.includes("maxaveragebitrate"))).join(";"),t.maxbr>0&&(s.config+=";maxaveragebitrate=".concat(1e3*t.maxbr)),i=!0;break}return i||t.maxbr>0&&e.fmtp.push({payload:n,config:"maxaveragebitrate=".concat(1e3*t.maxbr)}),!0}))})),n=$a(i)}if(yield this.setMungedSDP(e,n,!0),this.pendingCandidates.forEach((e=>{this.pc.addIceCandidate(e)})),this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate)this.renegotiate=!1,yield this.createAndSendOffer();else if("answer"===e.type&&(this.emit(nr),e.sdp)){er(e.sdp).media.forEach((e=>{"video"===e.type&&this.emit(ir,e.rtp)}))}}))}createAndSendOffer(e){var t;return wi(this,void 0,void 0,(function*(){if(void 0===this.onOffer)return;if((null==e?void 0:e.iceRestart)&&(this.log.debug("restarting ICE",this.logContext),this.restartingIce=!0),this._pc&&"have-local-offer"===this._pc.signalingState){const t=this._pc.remoteDescription;if(!(null==e?void 0:e.iceRestart)||!t)return void(this.renegotiate=!0);yield this._pc.setRemoteDescription(t)}else if(!this._pc||"closed"===this._pc.signalingState)return void this.log.warn("could not createOffer with closed peer connection",this.logContext);this.log.debug("starting to negotiate",this.logContext);const n=yield this.pc.createOffer(e),i=er(null!==(t=n.sdp)&&void 0!==t?t:"");i.media.forEach((e=>{"audio"===e.type?or(e,[],[]):"video"===e.type&&(!function(e){var t,n,i,s;const o=null===(n=null===(t=e.rtp[0])||void 0===t?void 0:t.codec)||void 0===n?void 0:n.toLowerCase();if(!ta(o))return;let a=0;const r=null===(i=e.ext)||void 0===i?void 0:i.some((e=>e.uri===Qo||(e.value>a&&(a=e.value),!1)));r||null===(s=e.ext)||void 0===s||s.push({value:a+1,uri:Qo})}(e),this.trackBitrates.some((t=>{if(!e.msid||!t.cid||!e.msid.includes(t.cid))return!1;let n=0;if(e.rtp.some((e=>e.codec.toUpperCase()===t.codec.toUpperCase()&&(n=e.payload,!0))),0===n)return!0;let i=!1;for(const s of e.fmtp)if(s.payload===n){s.config.includes("x-google-start-bitrate")||(s.config+=";x-google-start-bitrate=".concat(Math.round(.7*t.maxbr))),s.config.includes("x-google-max-bitrate")||(s.config+=";x-google-max-bitrate=".concat(t.maxbr)),i=!0;break}return i||e.fmtp.push({payload:n,config:"x-google-start-bitrate=".concat(Math.round(.7*t.maxbr),";x-google-max-bitrate=").concat(t.maxbr)}),!0})))})),yield this.setMungedSDP(n,$a(i)),this.onOffer(n)}))}createAndSetAnswer(){var e;return wi(this,void 0,void 0,(function*(){const t=yield this.pc.createAnswer(),n=er(null!==(e=t.sdp)&&void 0!==e?e:"");return n.media.forEach((e=>{"audio"===e.type&&or(e,this.remoteStereoMids,this.remoteNackMids)})),yield this.setMungedSDP(t,$a(n)),t}))}createDataChannel(e,t){return this.pc.createDataChannel(e,t)}addTransceiver(e,t){return this.pc.addTransceiver(e,t)}addTrack(e){if(!this._pc)throw new po("PC closed, cannot add track");return this._pc.addTrack(e)}setTrackCodecBitrate(e){this.trackBitrates.push(e)}setConfiguration(e){var t;if(!this._pc)throw new po("PC closed, cannot configure");return null===(t=this._pc)||void 0===t?void 0:t.setConfiguration(e)}canRemoveTrack(){var e;return!!(null===(e=this._pc)||void 0===e?void 0:e.removeTrack)}removeTrack(e){var t;return null===(t=this._pc)||void 0===t?void 0:t.removeTrack(e)}getConnectionState(){var e,t;return null!==(t=null===(e=this._pc)||void 0===e?void 0:e.connectionState)&&void 0!==t?t:"closed"}getICEConnectionState(){var e,t;return null!==(t=null===(e=this._pc)||void 0===e?void 0:e.iceConnectionState)&&void 0!==t?t:"closed"}getSignallingState(){var e,t;return null!==(t=null===(e=this._pc)||void 0===e?void 0:e.signalingState)&&void 0!==t?t:"closed"}getTransceivers(){var e,t;return null!==(t=null===(e=this._pc)||void 0===e?void 0:e.getTransceivers())&&void 0!==t?t:[]}getSenders(){var e,t;return null!==(t=null===(e=this._pc)||void 0===e?void 0:e.getSenders())&&void 0!==t?t:[]}getLocalDescription(){var e;return null===(e=this._pc)||void 0===e?void 0:e.localDescription}getRemoteDescription(){var e;return null===(e=this.pc)||void 0===e?void 0:e.remoteDescription}getStats(){return this.pc.getStats()}getConnectedAddress(){var e;return wi(this,void 0,void 0,(function*(){if(!this._pc)return;let t="";const n=new Map,i=new Map;if((yield this._pc.getStats()).forEach((e=>{switch(e.type){case"transport":t=e.selectedCandidatePairId;break;case"candidate-pair":""===t&&e.selected&&(t=e.id),n.set(e.id,e);break;case"remote-candidate":i.set(e.id,"".concat(e.address,":").concat(e.port))}})),""===t)return;const s=null===(e=n.get(t))||void 0===e?void 0:e.remoteCandidateId;return void 0!==s?i.get(s):void 0}))}setMungedSDP(e,t,n){return wi(this,void 0,void 0,(function*(){if(t){const i=e.sdp;e.sdp=t;try{return this.log.debug("setting munged ".concat(n?"remote":"local"," description"),this.logContext),void(n?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e))}catch(n){this.log.warn("not able to set ".concat(e.type,", falling back to unmodified sdp"),Object.assign(Object.assign({},this.logContext),{error:n,sdp:t})),e.sdp=i}}try{n?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e)}catch(t){let i="unknown error";t instanceof Error?i=t.message:"string"==typeof t&&(i=t);const s={error:i,sdp:e.sdp};throw!n&&this.pc.remoteDescription&&(s.remoteSdp=this.pc.remoteDescription),this.log.error("unable to set ".concat(e.type),Object.assign(Object.assign({},this.logContext),{fields:s})),new go(i)}}))}}function or(e,t,n){let i=0;e.rtp.some((e=>"opus"===e.codec&&(i=e.payload,!0))),i>0&&(e.rtcpFb||(e.rtcpFb=[]),n.includes(e.mid)&&!e.rtcpFb.some((e=>e.payload===i&&"nack"===e.type))&&e.rtcpFb.push({payload:i,type:"nack"}),t.includes(e.mid)&&e.fmtp.some((e=>e.payload===i&&(e.config.includes("stereo=1")||(e.config+=";stereo=1"),!0))))}const ar="vp8",rr={audioPreset:e.AudioPresets.music,dtx:!0,red:!0,forceStereo:!1,simulcast:!0,screenShareEncoding:Ao.h1080fps15.encoding,stopMicTrackOnMute:!1,videoCodec:ar,backupCodec:!0},cr={autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0},dr={resolution:No.h720.resolution},lr={adaptiveStream:!1,dynacast:!1,stopLocalTrackOnUnpublish:!0,reconnectPolicy:new Ei,disconnectOnPageLeave:!0,webAudioMix:!0},ur={autoSubscribe:!0,maxRetries:1,peerConnectionTimeout:15e3,websocketTimeout:15e3};var hr;!function(e){e[e.NEW=0]="NEW",e[e.CONNECTING=1]="CONNECTING",e[e.CONNECTED=2]="CONNECTED",e[e.FAILED=3]="FAILED",e[e.CLOSING=4]="CLOSING",e[e.CLOSED=5]="CLOSED"}(hr||(hr={}));class mr{get needsPublisher(){return this.isPublisherConnectionRequired}get needsSubscriber(){return this.isSubscriberConnectionRequired}get currentState(){return this.state}constructor(t,n,i){var s;this.peerConnectionTimeout=ur.peerConnectionTimeout,this.log=ki,this.updateState=()=>{var e;const t=this.state,n=this.requiredTransports.map((e=>e.getConnectionState()));n.every((e=>"connected"===e))?this.state=hr.CONNECTED:n.some((e=>"failed"===e))?this.state=hr.FAILED:n.some((e=>"connecting"===e))?this.state=hr.CONNECTING:n.every((e=>"closed"===e))?this.state=hr.CLOSED:n.some((e=>"closed"===e))?this.state=hr.CLOSING:n.every((e=>"new"===e))&&(this.state=hr.NEW),t!==this.state&&(this.log.debug("pc state change: from ".concat(hr[t]," to ").concat(hr[this.state]),this.logContext),null===(e=this.onStateChange)||void 0===e||e.call(this,this.state,this.publisher.getConnectionState(),this.subscriber.getConnectionState()))},this.log=yi(null!==(s=i.loggerName)&&void 0!==s?s:e.LoggerNames.PCManager),this.loggerOptions=i,this.isPublisherConnectionRequired=!n,this.isSubscriberConnectionRequired=n,this.publisher=new sr(t,i),this.subscriber=new sr(t,i),this.publisher.onConnectionStateChange=this.updateState,this.subscriber.onConnectionStateChange=this.updateState,this.publisher.onIceConnectionStateChange=this.updateState,this.subscriber.onIceConnectionStateChange=this.updateState,this.publisher.onSignalingStatechange=this.updateState,this.subscriber.onSignalingStatechange=this.updateState,this.publisher.onIceCandidate=e=>{var t;null===(t=this.onIceCandidate)||void 0===t||t.call(this,e,rn.PUBLISHER)},this.subscriber.onIceCandidate=e=>{var t;null===(t=this.onIceCandidate)||void 0===t||t.call(this,e,rn.SUBSCRIBER)},this.subscriber.onDataChannel=e=>{var t;null===(t=this.onDataChannel)||void 0===t||t.call(this,e)},this.subscriber.onTrack=e=>{var t;null===(t=this.onTrack)||void 0===t||t.call(this,e)},this.publisher.onOffer=e=>{var t;null===(t=this.onPublisherOffer)||void 0===t||t.call(this,e)},this.state=hr.NEW,this.connectionLock=new Ra}get logContext(){var e,t;return Object.assign({},null===(t=(e=this.loggerOptions).loggerContextCb)||void 0===t?void 0:t.call(e))}requirePublisher(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];this.isPublisherConnectionRequired=e,this.updateState()}requireSubscriber(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];this.isSubscriberConnectionRequired=e,this.updateState()}createAndSendPublisherOffer(e){return this.publisher.createAndSendOffer(e)}setPublisherAnswer(e){return this.publisher.setRemoteDescription(e)}removeTrack(e){return this.publisher.removeTrack(e)}close(){return wi(this,void 0,void 0,(function*(){if(this.publisher&&"closed"!==this.publisher.getSignallingState()){const e=this.publisher;for(const t of e.getSenders())try{e.canRemoveTrack()&&e.removeTrack(t)}catch(e){this.log.warn("could not removeTrack",Object.assign(Object.assign({},this.logContext),{error:e}))}}yield Promise.all([this.publisher.close(),this.subscriber.close()]),this.updateState()}))}triggerIceRestart(){return wi(this,void 0,void 0,(function*(){this.subscriber.restartingIce=!0,this.needsPublisher&&(yield this.createAndSendPublisherOffer({iceRestart:!0}))}))}addIceCandidate(e,t){return wi(this,void 0,void 0,(function*(){t===rn.PUBLISHER?yield this.publisher.addIceCandidate(e):yield this.subscriber.addIceCandidate(e)}))}createSubscriberAnswerFromOffer(e){return wi(this,void 0,void 0,(function*(){this.log.debug("received server offer",Object.assign(Object.assign({},this.logContext),{RTCSdpType:e.type,sdp:e.sdp,signalingState:this.subscriber.getSignallingState().toString()})),yield this.subscriber.setRemoteDescription(e);return yield this.subscriber.createAndSetAnswer()}))}updateConfiguration(e,t){this.publisher.setConfiguration(e),this.subscriber.setConfiguration(e),t&&this.triggerIceRestart()}ensurePCTransportConnection(e,t){var n;return wi(this,void 0,void 0,(function*(){const i=yield this.connectionLock.lock();try{this.isPublisherConnectionRequired&&"connected"!==this.publisher.getConnectionState()&&"connecting"!==this.publisher.getConnectionState()&&(this.log.debug("negotiation required, start negotiating",this.logContext),this.publisher.negotiate()),yield Promise.all(null===(n=this.requiredTransports)||void 0===n?void 0:n.map((n=>this.ensureTransportConnected(n,e,t))))}finally{i()}}))}negotiate(e){return wi(this,void 0,void 0,(function*(){return new Promise(((t,n)=>wi(this,void 0,void 0,(function*(){const i=setTimeout((()=>{n("negotiation timed out")}),this.peerConnectionTimeout);e.signal.addEventListener("abort",(()=>{clearTimeout(i),n("negotiation aborted")})),this.publisher.once(tr,(()=>{e.signal.aborted||this.publisher.once(nr,(()=>{clearTimeout(i),t()}))})),yield this.publisher.negotiate((e=>{clearTimeout(i),n(e)}))}))))}))}addPublisherTransceiver(e,t){return this.publisher.addTransceiver(e,t)}addPublisherTrack(e){return this.publisher.addTrack(e)}createPublisherDataChannel(e,t){return this.publisher.createDataChannel(e,t)}getConnectedAddress(e){return e===rn.PUBLISHER||e===rn.SUBSCRIBER?this.publisher.getConnectedAddress():this.requiredTransports[0].getConnectedAddress()}get requiredTransports(){const e=[];return this.isPublisherConnectionRequired&&e.push(this.publisher),this.isSubscriberConnectionRequired&&e.push(this.subscriber),e}ensureTransportConnected(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:this.peerConnectionTimeout;return wi(this,void 0,void 0,(function*(){if("connected"!==e.getConnectionState())return new Promise(((e,i)=>wi(this,void 0,void 0,(function*(){const s=()=>{this.log.warn("abort transport connection",this.logContext),_o.clearTimeout(o),i(new lo("room connection has been cancelled",3))};(null==t?void 0:t.signal.aborted)&&s(),null==t||t.signal.addEventListener("abort",s);const o=_o.setTimeout((()=>{null==t||t.signal.removeEventListener("abort",s),i(new lo("could not establish pc connection"))}),n);for(;this.state!==hr.CONNECTED;)if(yield Yo(50),null==t?void 0:t.signal.aborted)return void i(new lo("room connection has been cancelled",3));_o.clearTimeout(o),null==t||t.signal.removeEventListener("abort",s),e()}))))}))}}const pr="_lossy",gr="_reliable",fr="leave-reconnect";var vr;!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"}(vr||(vr={}));class kr extends Gi.EventEmitter{get isClosed(){return this._isClosed}get pendingReconnect(){return!!this.reconnectTimeout}constructor(t){var n;super(),this.options=t,this.rtcConfig={},this.peerConnectionTimeout=ur.peerConnectionTimeout,this.fullReconnectOnNext=!1,this.subscriberPrimary=!1,this.pcState=vr.New,this._isClosed=!0,this.pendingTrackResolvers={},this.reconnectAttempts=0,this.reconnectStart=0,this.attemptingReconnect=!1,this.joinAttempts=0,this.maxJoinAttempts=1,this.shouldFailNext=!1,this.log=ki,this.handleDataChannel=e=>{let{channel:t}=e;return wi(this,void 0,void 0,(function*(){if(t){if(t.label===gr)this.reliableDCSub=t;else{if(t.label!==pr)return;this.lossyDCSub=t}this.log.debug("on data channel ".concat(t.id,", ").concat(t.label),this.logContext),t.onmessage=this.handleDataMessage}}))},this.handleDataMessage=t=>wi(this,void 0,void 0,(function*(){var n,i;const s=yield this.dataProcessLock.lock();try{let s;if(t.data instanceof ArrayBuffer)s=t.data;else{if(!(t.data instanceof Blob))return void this.log.error("unsupported data type",Object.assign(Object.assign({},this.logContext),{data:t.data}));s=yield t.data.arrayBuffer()}const o=tt.fromBinary(new Uint8Array(s));"speaker"===(null===(n=o.value)||void 0===n?void 0:n.case)?this.emit(e.EngineEvent.ActiveSpeakersUpdate,o.value.value.speakers):"user"===(null===(i=o.value)||void 0===i?void 0:i.case)&&this.emit(e.EngineEvent.DataPacketReceived,o.value.value,o.kind)}finally{s()}})),this.handleDataError=e=>{const t=0===e.currentTarget.maxRetransmits?"lossy":"reliable";if(e instanceof ErrorEvent&&e.error){const{error:n}=e.error;this.log.error("DataChannel error on ".concat(t,": ").concat(e.message),Object.assign(Object.assign({},this.logContext),{error:n}))}else this.log.error("Unknown DataChannel error on ".concat(t),Object.assign(Object.assign({},this.logContext),{event:e}))},this.handleBufferedAmountLow=e=>{const t=0===e.currentTarget.maxRetransmits?nt.LOSSY:nt.RELIABLE;this.updateAndEmitDCBufferStatus(t)},this.handleDisconnect=(t,n)=>{if(this._isClosed)return;this.log.warn("".concat(t," disconnected"),this.logContext),0===this.reconnectAttempts&&(this.reconnectStart=Date.now());const i=t=>{this.log.warn("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(t,"ms. giving up"),this.logContext),this.emit(e.EngineEvent.Disconnected),this.close()},s=Date.now()-this.reconnectStart;let o=this.getNextRetryDelay({elapsedMs:s,retryCount:this.reconnectAttempts});null!==o?(t===fr&&(o=0),this.log.debug("reconnecting in ".concat(o,"ms"),this.logContext),this.clearReconnectTimeout(),this.token&&this.regionUrlProvider&&this.regionUrlProvider.updateToken(this.token),this.reconnectTimeout=_o.setTimeout((()=>this.attemptReconnect(n).finally((()=>this.reconnectTimeout=void 0))),o)):i(s)},this.waitForRestarted=()=>new Promise(((t,n)=>{this.pcState===vr.Connected&&t();const i=()=>{this.off(e.EngineEvent.Disconnected,s),t()},s=()=>{this.off(e.EngineEvent.Restarted,i),n()};this.once(e.EngineEvent.Restarted,i),this.once(e.EngineEvent.Disconnected,s)})),this.updateAndEmitDCBufferStatus=t=>{const n=this.isBufferStatusLow(t);void 0!==n&&n!==this.dcBufferStatus.get(t)&&(this.dcBufferStatus.set(t,n),this.emit(e.EngineEvent.DCBufferStatusChanged,n,t))},this.isBufferStatusLow=e=>{const t=this.dataChannelForKind(e);if(t)return t.bufferedAmount<=t.bufferedAmountLowThreshold},this.handleBrowserOnLine=()=>{this.client.currentState===Ua.RECONNECTING&&(this.clearReconnectTimeout(),this.attemptReconnect(Ke.RR_SIGNAL_DISCONNECTED))},this.log=yi(null!==(n=t.loggerName)&&void 0!==n?n:e.LoggerNames.Engine),this.loggerOptions={loggerName:t.loggerName,loggerContextCb:()=>this.logContext},this.client=new ja(void 0,this.loggerOptions),this.client.signalLatency=this.options.expSignalLatency,this.reconnectPolicy=this.options.reconnectPolicy,this.registerOnLineListener(),this.closingLock=new Ra,this.dataProcessLock=new Ra,this.dcBufferStatus=new Map([[nt.LOSSY,!0],[nt.RELIABLE,!0]]),this.client.onParticipantUpdate=t=>this.emit(e.EngineEvent.ParticipantUpdate,t),this.client.onConnectionQuality=t=>this.emit(e.EngineEvent.ConnectionQualityUpdate,t),this.client.onRoomUpdate=t=>this.emit(e.EngineEvent.RoomUpdate,t),this.client.onSubscriptionError=t=>this.emit(e.EngineEvent.SubscriptionError,t),this.client.onSubscriptionPermissionUpdate=t=>this.emit(e.EngineEvent.SubscriptionPermissionUpdate,t),this.client.onSpeakersChanged=t=>this.emit(e.EngineEvent.SpeakersChanged,t),this.client.onStreamStateUpdate=t=>this.emit(e.EngineEvent.StreamStateChanged,t)}get logContext(){var e,t,n,i,s,o,a,r;return{room:null===(t=null===(e=this.latestJoinResponse)||void 0===e?void 0:e.room)||void 0===t?void 0:t.name,roomID:null===(i=null===(n=this.latestJoinResponse)||void 0===n?void 0:n.room)||void 0===i?void 0:i.sid,participant:null===(o=null===(s=this.latestJoinResponse)||void 0===s?void 0:s.participant)||void 0===o?void 0:o.identity,pID:null===(r=null===(a=this.latestJoinResponse)||void 0===a?void 0:a.participant)||void 0===r?void 0:r.sid}}join(e,t,n,i){return wi(this,void 0,void 0,(function*(){this.url=e,this.token=t,this.signalOpts=n,this.maxJoinAttempts=n.maxRetries;try{this.joinAttempts+=1,this.setupSignalClientCallbacks();const s=yield this.client.join(e,t,n,i);return this._isClosed=!1,this.latestJoinResponse=s,this.subscriberPrimary=s.subscriberPrimary,this.pcManager||(yield this.configure(s)),this.subscriberPrimary||this.negotiate(),this.clientConfiguration=s.clientConfiguration,s}catch(s){if(s instanceof lo&&1===s.reason&&(this.log.warn("Couldn't connect to server, attempt ".concat(this.joinAttempts," of ").concat(this.maxJoinAttempts),this.logContext),this.joinAttempts<this.maxJoinAttempts))return this.join(e,t,n,i);throw s}}))}close(){return wi(this,void 0,void 0,(function*(){const t=yield this.closingLock.lock();if(this.isClosed)t();else try{this._isClosed=!0,this.emit(e.EngineEvent.Closing),this.removeAllListeners(),this.deregisterOnLineListener(),this.clearPendingReconnect(),yield this.cleanupPeerConnections(),yield this.cleanupClient()}finally{t()}}))}cleanupPeerConnections(){var e;return wi(this,void 0,void 0,(function*(){yield null===(e=this.pcManager)||void 0===e?void 0:e.close(),this.pcManager=void 0;const t=e=>{e&&(e.close(),e.onbufferedamountlow=null,e.onclose=null,e.onclosing=null,e.onerror=null,e.onmessage=null,e.onopen=null)};t(this.lossyDC),t(this.lossyDCSub),t(this.reliableDC),t(this.reliableDCSub),this.lossyDC=void 0,this.lossyDCSub=void 0,this.reliableDC=void 0,this.reliableDCSub=void 0}))}cleanupClient(){return wi(this,void 0,void 0,(function*(){yield this.client.close(),this.client.resetCallbacks()}))}addTrack(e){if(this.pendingTrackResolvers[e.cid])throw new ho("a track with the same ID has already been published");return new Promise(((t,n)=>{const i=setTimeout((()=>{delete this.pendingTrackResolvers[e.cid],n(new lo("publication of local track timed out, no response from server"))}),1e4);this.pendingTrackResolvers[e.cid]={resolve:e=>{clearTimeout(i),t(e)},reject:()=>{clearTimeout(i),n(new Error("Cancelled publication by calling unpublish"))}},this.client.sendAddTrack(e)}))}removeTrack(e){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 this.pcManager.removeTrack(e),!0}catch(e){this.log.warn("failed to remove track",Object.assign(Object.assign({},this.logContext),{error:e}))}return!1}updateMuteStatus(e,t){this.client.sendMuteTrack(e,t)}get dataSubscriberReadyState(){var e;return null===(e=this.reliableDCSub)||void 0===e?void 0:e.readyState}getConnectedServerAddress(){var e;return wi(this,void 0,void 0,(function*(){return null===(e=this.pcManager)||void 0===e?void 0:e.getConnectedAddress()}))}setRegionUrlProvider(e){this.regionUrlProvider=e}configure(t){var n;return wi(this,void 0,void 0,(function*(){if(this.pcManager&&this.pcManager.currentState!==hr.NEW)return;this.participantSid=null===(n=t.participant)||void 0===n?void 0:n.sid;const i=this.makeRTCConfiguration(t);this.pcManager=new mr(i,t.subscriberPrimary,this.loggerOptions),this.emit(e.EngineEvent.TransportsCreated,this.pcManager.publisher,this.pcManager.subscriber),this.pcManager.onIceCandidate=(e,t)=>{this.client.sendIceCandidate(e,t)},this.pcManager.onPublisherOffer=e=>{this.client.sendOffer(e)},this.pcManager.onDataChannel=this.handleDataChannel,this.pcManager.onStateChange=(n,i,s)=>wi(this,void 0,void 0,(function*(){if(this.log.debug("primary PC state changed ".concat(n),this.logContext),n===hr.CONNECTED){const n=this.pcState===vr.New;this.pcState=vr.Connected,n&&this.emit(e.EngineEvent.Connected,t)}else n===hr.FAILED&&this.pcState===vr.Connected&&(this.pcState=vr.Disconnected,this.handleDisconnect("peerconnection failed","failed"===s?Ke.RR_SUBSCRIBER_FAILED:Ke.RR_PUBLISHER_FAILED));const i=this.client.isDisconnected||this.client.currentState===Ua.RECONNECTING,o=[hr.FAILED,hr.CLOSING,hr.CLOSED].includes(n);i&&o&&!this._isClosed&&this.emit(e.EngineEvent.Offline)})),this.pcManager.onTrack=t=>{this.emit(e.EngineEvent.MediaTrackAdded,t.track,t.streams[0],t.receiver)},this.createDataChannels()}))}setupSignalClientCallbacks(){this.client.onAnswer=e=>wi(this,void 0,void 0,(function*(){this.pcManager&&(this.log.debug("received server answer",Object.assign(Object.assign({},this.logContext),{RTCSdpType:e.type})),yield this.pcManager.setPublisherAnswer(e))})),this.client.onTrickle=(e,t)=>{this.pcManager&&(this.log.trace("got ICE candidate from peer",Object.assign(Object.assign({},this.logContext),{candidate:e,target:t})),this.pcManager.addIceCandidate(e,t))},this.client.onOffer=e=>wi(this,void 0,void 0,(function*(){if(!this.pcManager)return;const t=yield this.pcManager.createSubscriberAnswerFromOffer(e);this.client.sendAnswer(t)})),this.client.onLocalTrackPublished=e=>{var t;if(this.log.debug("received trackPublishedResponse",Object.assign(Object.assign({},this.logContext),{cid:e.cid,track:null===(t=e.track)||void 0===t?void 0:t.sid})),!this.pendingTrackResolvers[e.cid])return void this.log.error("missing track resolver for ".concat(e.cid),Object.assign(Object.assign({},this.logContext),{cid:e.cid}));const{resolve:n}=this.pendingTrackResolvers[e.cid];delete this.pendingTrackResolvers[e.cid],n(e.track)},this.client.onLocalTrackUnpublished=t=>{this.emit(e.EngineEvent.LocalTrackUnpublished,t)},this.client.onTokenRefresh=e=>{this.token=e},this.client.onRemoteMuteChanged=(t,n)=>{this.emit(e.EngineEvent.RemoteMute,t,n)},this.client.onSubscribedQualityUpdate=t=>{this.emit(e.EngineEvent.SubscribedQualityUpdate,t)},this.client.onClose=()=>{this.handleDisconnect("signal",Ke.RR_SIGNAL_DISCONNECTED)},this.client.onLeave=t=>{(null==t?void 0:t.canReconnect)?(this.fullReconnectOnNext=!0,this.handleDisconnect(fr)):(this.emit(e.EngineEvent.Disconnected,null==t?void 0:t.reason),this.close()),this.log.debug("client leave request",Object.assign(Object.assign({},this.logContext),{reason:null==t?void 0:t.reason}))}}makeRTCConfiguration(e){var t;const n=Object.assign({},this.rtcConfig);if((null===(t=this.signalOpts)||void 0===t?void 0:t.e2eeEnabled)&&(this.log.debug("E2EE - setting up transports with insertable streams",this.logContext),n.encodedInsertableStreams=!0),e.iceServers&&!n.iceServers){const t=[];e.iceServers.forEach((e=>{const n={urls:e.urls};e.username&&(n.username=e.username),e.credential&&(n.credential=e.credential),t.push(n)})),n.iceServers=t}return e.clientConfiguration&&e.clientConfiguration.forceRelay===Ve.ENABLED&&(n.iceTransportPolicy="relay"),n.sdpSemantics="unified-plan",n.continualGatheringPolicy="gather_continually",n}createDataChannels(){this.pcManager&&(this.lossyDC&&(this.lossyDC.onmessage=null,this.lossyDC.onerror=null),this.reliableDC&&(this.reliableDC.onmessage=null,this.reliableDC.onerror=null),this.lossyDC=this.pcManager.createPublisherDataChannel(pr,{ordered:!0,maxRetransmits:0}),this.reliableDC=this.pcManager.createPublisherDataChannel(gr,{ordered:!0}),this.lossyDC.onmessage=this.handleDataMessage,this.reliableDC.onmessage=this.handleDataMessage,this.lossyDC.onerror=this.handleDataError,this.reliableDC.onerror=this.handleDataError,this.lossyDC.bufferedAmountLowThreshold=65535,this.reliableDC.bufferedAmountLowThreshold=65535,this.lossyDC.onbufferedamountlow=this.handleBufferedAmountLow,this.reliableDC.onbufferedamountlow=this.handleBufferedAmountLow)}setPreferredCodec(e,t,n){if(!("getCapabilities"in RTCRtpSender))return;const i=RTCRtpSender.getCapabilities(t);if(!i)return;this.log.debug("get sender capabilities",Object.assign(Object.assign({},this.logContext),{cap:i}));const s=[],o=[],a=[];i.codecs.forEach((e=>{const t=e.mimeType.toLowerCase();if("audio/opus"===t)return void s.push(e);t==="video/".concat(n)?"h264"!==n||e.sdpFmtpLine&&e.sdpFmtpLine.includes("profile-level-id=42e01f")?s.push(e):o.push(e):a.push(e)})),function(e){if(!da())return!1;if(!("setCodecPreferences"in e))return!1;const t=Eo();if(!(null==t?void 0:t.name)||!t.version)return!1;const n=ia[t.name];return!!n&&ga(t.version,n)>=0}(e)&&e.setCodecPreferences(s.concat(o,a))}createSender(e,t,n){return wi(this,void 0,void 0,(function*(){if(Xo()){return yield this.createTransceiverRTCRtpSender(e,t,n)}if(Zo()){this.log.warn("using add-track fallback",this.logContext);return yield this.createRTCRtpSender(e.mediaStreamTrack)}throw new po("Required webRTC APIs not supported on this device")}))}createSimulcastSender(e,t,n,i){return wi(this,void 0,void 0,(function*(){if(Xo())return this.createSimulcastTransceiverSender(e,t,n,i);if(Zo())return this.log.debug("using add-track fallback",this.logContext),this.createRTCRtpSender(e.mediaStreamTrack);throw new po("Cannot stream on this device")}))}createTransceiverRTCRtpSender(e,t,n){return wi(this,void 0,void 0,(function*(){if(!this.pcManager)throw new po("publisher is closed");const i=[];e.mediaStream&&i.push(e.mediaStream);const s={direction:"sendonly",streams:i};n&&(s.sendEncodings=n);const o=yield this.pcManager.addPublisherTransceiver(e.mediaStreamTrack,s);return e.kind===jo.Kind.Video&&t.videoCodec&&(this.setPreferredCodec(o,e.kind,t.videoCodec),e.codec=t.videoCodec),o.sender}))}createSimulcastTransceiverSender(e,t,n,i){return wi(this,void 0,void 0,(function*(){if(!this.pcManager)throw new po("publisher is closed");const s={direction:"sendonly"};i&&(s.sendEncodings=i);const o=yield this.pcManager.addPublisherTransceiver(t.mediaStreamTrack,s);if(n.videoCodec)return this.setPreferredCodec(o,e.kind,n.videoCodec),e.setSimulcastTrackSender(n.videoCodec,o.sender),o.sender}))}createRTCRtpSender(e){return wi(this,void 0,void 0,(function*(){if(!this.pcManager)throw new po("publisher is closed");return this.pcManager.addPublisherTrack(e)}))}attemptReconnect(t){var n,i,s;return wi(this,void 0,void 0,(function*(){if(!this._isClosed)if(this.attemptingReconnect)ki.warn("already attempting reconnect, returning early",this.logContext);else{(null===(n=this.clientConfiguration)||void 0===n?void 0:n.resumeConnection)!==Ve.DISABLED&&(null!==(s=null===(i=this.pcManager)||void 0===i?void 0:i.currentState)&&void 0!==s?s:hr.NEW)!==hr.NEW||(this.fullReconnectOnNext=!0);try{this.attemptingReconnect=!0,this.fullReconnectOnNext?yield this.restartConnection():yield this.resumeConnection(t),this.clearPendingReconnect(),this.fullReconnectOnNext=!1}catch(t){this.reconnectAttempts+=1;let n=!0;t instanceof po?(this.log.debug("received unrecoverable error",Object.assign(Object.assign({},this.logContext),{error:t})),n=!1):t instanceof Tr||(this.fullReconnectOnNext=!0),n?this.handleDisconnect("reconnect",Ke.RR_UNKNOWN):(this.log.info("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(Date.now()-this.reconnectStart,"ms. giving up"),this.logContext),this.emit(e.EngineEvent.Disconnected),yield this.close())}finally{this.attemptingReconnect=!1}}}))}getNextRetryDelay(e){try{return this.reconnectPolicy.nextRetryDelayInMs(e)}catch(e){this.log.warn("encountered error in reconnect policy",Object.assign(Object.assign({},this.logContext),{error:e}))}return null}restartConnection(t){var n,i,s;return wi(this,void 0,void 0,(function*(){try{if(!this.url||!this.token)throw new po("could not reconnect, url or token not saved");let i;this.log.info("reconnecting, attempt: ".concat(this.reconnectAttempts),this.logContext),this.emit(e.EngineEvent.Restarting),this.client.isDisconnected||(yield this.client.sendLeave()),yield this.cleanupPeerConnections(),yield this.cleanupClient();try{if(!this.signalOpts)throw this.log.warn("attempted connection restart, without signal options present",this.logContext),new Tr;i=yield this.join(null!=t?t:this.url,this.token,this.signalOpts)}catch(e){if(e instanceof lo&&0===e.reason)throw new po("could not reconnect, token might be expired");throw new Tr}if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(this.client.setReconnected(),this.emit(e.EngineEvent.SignalRestarted,i),yield this.waitForPCReconnected(),this.client.currentState!==Ua.CONNECTED)throw new Tr("Signal connection got severed during reconnect");null===(n=this.regionUrlProvider)||void 0===n||n.resetAttempts(),this.emit(e.EngineEvent.Restarted)}catch(e){const t=yield null===(i=this.regionUrlProvider)||void 0===i?void 0:i.getNextBestRegionUrl();if(t)return void(yield this.restartConnection(t));throw null===(s=this.regionUrlProvider)||void 0===s||s.resetAttempts(),e}}))}resumeConnection(t){var n;return wi(this,void 0,void 0,(function*(){if(!this.url||!this.token)throw new po("could not reconnect, url or token not saved");if(!this.pcManager)throw new po("publisher and subscriber connections unset");let i;this.log.info("resuming signal connection, attempt ".concat(this.reconnectAttempts),this.logContext),this.emit(e.EngineEvent.Resuming);try{this.setupSignalClientCallbacks(),i=yield this.client.reconnect(this.url,this.token,this.participantSid,t)}catch(e){let t="";if(e instanceof Error&&(t=e.message,this.log.error(e.message,Object.assign(Object.assign({},this.logContext),{error:e}))),e instanceof lo&&0===e.reason)throw new po("could not reconnect, token might be expired");if(e instanceof lo&&4===e.reason)throw e;throw new Tr(t)}if(this.emit(e.EngineEvent.SignalResumed),i){const e=this.makeRTCConfiguration(i);this.pcManager.updateConfiguration(e)}else this.log.warn("Did not receive reconnect response",this.logContext);if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(yield this.pcManager.triggerIceRestart(),yield this.waitForPCReconnected(),this.client.currentState!==Ua.CONNECTED)throw new Tr("Signal connection got severed during reconnect");this.client.setReconnected(),"open"===(null===(n=this.reliableDC)||void 0===n?void 0:n.readyState)&&null===this.reliableDC.id&&this.createDataChannels(),this.emit(e.EngineEvent.Resumed)}))}waitForPCInitialConnection(e,t){return wi(this,void 0,void 0,(function*(){if(!this.pcManager)throw new po("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(t,e)}))}waitForPCReconnected(){return wi(this,void 0,void 0,(function*(){this.pcState=vr.Reconnecting,this.log.debug("waiting for peer connection to reconnect",this.logContext);try{if(yield Yo(2e3),!this.pcManager)throw new po("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(void 0,this.peerConnectionTimeout),this.pcState=vr.Connected}catch(e){throw this.pcState=vr.Disconnected,new lo("could not establish PC connection, ".concat(e.message))}}))}sendDataPacket(e,t){return wi(this,void 0,void 0,(function*(){const n=e.toBinary();yield this.ensurePublisherConnected(t);const i=this.dataChannelForKind(t);i&&i.send(n),this.updateAndEmitDCBufferStatus(t)}))}ensureDataTransportConnected(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.subscriberPrimary;var n;return wi(this,void 0,void 0,(function*(){if(!this.pcManager)throw new po("PC manager is closed");const i=t?this.pcManager.subscriber:this.pcManager.publisher,s=t?"Subscriber":"Publisher";if(!i)throw new lo("".concat(s," connection not set"));t||this.pcManager.publisher.isICEConnected||"checking"===this.pcManager.publisher.getICEConnectionState()||this.negotiate();const o=this.dataChannelForKind(e,t);if("open"===(null==o?void 0:o.readyState))return;const a=(new Date).getTime()+this.peerConnectionTimeout;for(;(new Date).getTime()<a;){if(i.isICEConnected&&"open"===(null===(n=this.dataChannelForKind(e,t))||void 0===n?void 0:n.readyState))return;yield Yo(50)}throw new lo("could not establish ".concat(s," connection, state: ").concat(i.getICEConnectionState()))}))}ensurePublisherConnected(e){return wi(this,void 0,void 0,(function*(){yield this.ensureDataTransportConnected(e,!1)}))}verifyTransport(){return!!this.pcManager&&(this.pcManager.currentState===hr.CONNECTED&&!(!this.client.ws||this.client.ws.readyState===WebSocket.CLOSED))}negotiate(){return wi(this,void 0,void 0,(function*(){return new Promise(((t,n)=>wi(this,void 0,void 0,(function*(){if(!this.pcManager)return void n(new go("PC manager is closed"));this.pcManager.requirePublisher();const i=new AbortController,s=()=>{i.abort(),this.log.debug("engine disconnected while negotiation was ongoing",this.logContext),t()};this.isClosed&&n("cannot negotiate on closed engine"),this.on(e.EngineEvent.Closing,s),this.pcManager.publisher.once(ir,(t=>{const n=new Map;t.forEach((e=>{const t=e.codec.toLowerCase();var i;i=t,Mo.includes(i)&&n.set(e.payload,t)})),this.emit(e.EngineEvent.RTPVideoMapUpdate,n)}));try{yield this.pcManager.negotiate(i),t()}catch(e){e instanceof go&&(this.fullReconnectOnNext=!0),this.handleDisconnect("negotiation",Ke.RR_UNKNOWN),n(e)}finally{this.off(e.EngineEvent.Closing,s)}}))))}))}dataChannelForKind(e,t){if(t){if(e===nt.LOSSY)return this.lossyDCSub;if(e===nt.RELIABLE)return this.reliableDCSub}else{if(e===nt.LOSSY)return this.lossyDC;if(e===nt.RELIABLE)return this.reliableDC}}sendSyncState(e,t){var n,i;if(!this.pcManager)return void this.log.warn("sync state cannot be sent without peer connection setup",this.logContext);const s=this.pcManager.subscriber.getLocalDescription(),o=this.pcManager.subscriber.getRemoteDescription(),a=null===(i=null===(n=this.signalOpts)||void 0===n?void 0:n.autoSubscribe)||void 0===i||i,r=new Array,c=new Array;e.forEach((e=>{e.isDesired!==a&&r.push(e.trackSid),e.isEnabled||c.push(e.trackSid)})),this.client.sendSyncState(new Vn({answer:s?Ba({sdp:s.sdp,type:s.type}):void 0,offer:o?Ba({sdp:o.sdp,type:o.type}):void 0,subscription:new Cn({trackSids:r,subscribe:!a,participantTracks:[]}),publishTracks:Jo(t),dataChannels:this.dataChannelsInfo(),trackSidsDisabled:c}))}failNext(){this.shouldFailNext=!0}dataChannelsInfo(){const e=[],t=(t,n)=>{void 0!==(null==t?void 0:t.id)&&null!==t.id&&e.push(new qn({label:t.label,id:t.id,target:n}))};return t(this.dataChannelForKind(nt.LOSSY),rn.PUBLISHER),t(this.dataChannelForKind(nt.RELIABLE),rn.PUBLISHER),t(this.dataChannelForKind(nt.LOSSY,!0),rn.SUBSCRIBER),t(this.dataChannelForKind(nt.RELIABLE,!0),rn.SUBSCRIBER),e}clearReconnectTimeout(){this.reconnectTimeout&&_o.clearTimeout(this.reconnectTimeout)}clearPendingReconnect(){this.clearReconnectTimeout(),this.reconnectAttempts=0}registerOnLineListener(){da()&&window.addEventListener("online",this.handleBrowserOnLine)}deregisterOnLineListener(){da()&&window.removeEventListener("online",this.handleBrowserOnLine)}}class Tr extends Error{}class yr{constructor(e,t){this.lastUpdateAt=0,this.settingsCacheTime=3e3,this.attemptedRegions=[],this.serverUrl=new URL(e),this.token=t}updateToken(e){this.token=e}isCloud(){return ua(this.serverUrl)}getServerUrl(){return this.serverUrl}getNextBestRegionUrl(e){return wi(this,void 0,void 0,(function*(){if(!this.isCloud())throw Error("region availability is only supported for LiveKit Cloud domains");(!this.regionSettings||Date.now()-this.lastUpdateAt>this.settingsCacheTime)&&(this.regionSettings=yield this.fetchRegionSettings(e));const t=this.regionSettings.regions.filter((e=>!this.attemptedRegions.find((t=>t.url===e.url))));if(t.length>0){const e=t[0];return this.attemptedRegions.push(e),ki.debug("next region: ".concat(e.region)),e.url}return null}))}resetAttempts(){this.attemptedRegions=[]}fetchRegionSettings(e){return wi(this,void 0,void 0,(function*(){const t=yield fetch("".concat((n=this.serverUrl,"".concat(n.protocol.replace("ws","http"),"//").concat(n.host,"/settings")),"/regions"),{headers:{authorization:"Bearer ".concat(this.token)},signal:e});var n;if(t.ok){const e=yield t.json();return this.lastUpdateAt=Date.now(),e}throw new lo("Could not fetch region settings: ".concat(t.statusText),401===t.status?0:void 0,t.status)}))}}const br=2e3;function Cr(e,t){if(!t)return 0;let n,i;return"bytesReceived"in e?(n=e.bytesReceived,i=t.bytesReceived):"bytesSent"in e&&(n=e.bytesSent,i=t.bytesSent),void 0===n||void 0===i||void 0===e.timestamp||void 0===t.timestamp?0:8*(n-i)*1e3/(e.timestamp-t.timestamp)}class Sr extends xa{constructor(e,t){let n=!(arguments.length>2&&void 0!==arguments[2])||arguments[2],i=arguments.length>3?arguments[3]:void 0,s=arguments.length>4?arguments[4]:void 0;super(e,jo.Kind.Audio,t,n,s),this.stopOnMute=!1,this.monitorSender=()=>wi(this,void 0,void 0,(function*(){if(!this.sender)return void(this._currentBitrate=0);let e;try{e=yield this.getSenderStats()}catch(e){return void this.log.error("could not get audio sender stats",Object.assign(Object.assign({},this.logContext),{error:e}))}e&&this.prevStats&&(this._currentBitrate=Cr(e,this.prevStats)),this.prevStats=e})),this.audioContext=i,this.checkForSilence()}setDeviceId(e){return wi(this,void 0,void 0,(function*(){return this._constraints.deviceId===e&&this._mediaStreamTrack.getSettings().deviceId===_a(e)||(this._constraints.deviceId=e,this.isMuted||(yield this.restartTrack()),this.isMuted||_a(e)===this._mediaStreamTrack.getSettings().deviceId)}))}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return wi(this,void 0,void 0,(function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug("Track already muted",this.logContext),this):(this.source===jo.Source.Microphone&&this.stopOnMute&&!this.isUserProvided&&(this.log.debug("stopping mic track",this.logContext),this._mediaStreamTrack.stop()),yield e.mute.call(this),this)}finally{t()}}))}unmute(){const e=Object.create(null,{unmute:{get:()=>super.unmute}});return wi(this,void 0,void 0,(function*(){const t=yield this.muteLock.lock();try{if(!this.isMuted)return this.log.debug("Track already unmuted",this.logContext),this;const t=this._constraints.deviceId&&this._mediaStreamTrack.getSettings().deviceId!==_a(this._constraints.deviceId);return this.source!==jo.Source.Microphone||!this.stopOnMute&&"ended"!==this._mediaStreamTrack.readyState&&!t||this.isUserProvided||(this.log.debug("reacquiring mic track",this.logContext),yield this.restartTrack()),yield e.unmute.call(this),this}finally{t()}}))}restartTrack(e){return wi(this,void 0,void 0,(function*(){let t;if(e){const n=Ko({audio:e});"boolean"!=typeof n.audio&&(t=n.audio)}yield this.restart(t)}))}restart(e){const t=Object.create(null,{restart:{get:()=>super.restart}});return wi(this,void 0,void 0,(function*(){const n=yield t.restart.call(this,e);return this.checkForSilence(),n}))}startMonitor(){da()&&(this.monitorInterval||(this.monitorInterval=setInterval((()=>{this.monitorSender()}),br)))}setProcessor(t){var n;return wi(this,void 0,void 0,(function*(){const i=yield this.processorLock.lock();try{if(!this.audioContext)throw Error("Audio context needs to be set on LocalAudioTrack in order to enable processors");this.processor&&(yield this.stopProcessor());const i={kind:this.kind,track:this._mediaStreamTrack,audioContext:this.audioContext};this.log.debug("setting up audio processor ".concat(t.name),this.logContext),yield t.init(i),this.processor=t,this.processor.processedTrack&&(yield null===(n=this.sender)||void 0===n?void 0:n.replaceTrack(this.processor.processedTrack)),this.emit(e.TrackEvent.TrackProcessorUpdate,this.processor)}finally{i()}}))}setAudioContext(e){this.audioContext=e}getSenderStats(){var e;return wi(this,void 0,void 0,(function*(){if(!(null===(e=this.sender)||void 0===e?void 0:e.getStats))return;let t;return(yield this.sender.getStats()).forEach((e=>{"outbound-rtp"===e.type&&(t={type:"audio",streamId:e.id,packetsSent:e.packetsSent,packetsLost:e.packetsLost,bytesSent:e.bytesSent,timestamp:e.timestamp,roundTripTime:e.roundTripTime,jitter:e.jitter})})),t}))}checkForSilence(){return wi(this,void 0,void 0,(function*(){const t=yield function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:200;return wi(this,void 0,void 0,(function*(){const n=Go();if(n){const i=n.createAnalyser();i.fftSize=2048;const s=i.frequencyBinCount,o=new Uint8Array(s);n.createMediaStreamSource(new MediaStream([e.mediaStreamTrack])).connect(i),yield Yo(t),i.getByteTimeDomainData(o);const a=o.some((e=>128!==e&&0!==e));return n.close(),!a}return!1}))}(this);return t&&(this.isMuted||this.log.warn("silence detected on local audio track",this.logContext),this.emit(e.TrackEvent.AudioSilenceDetected)),t}))}}function Er(e,t,n){switch(e.kind){case"audio":return new Sr(e,t,!1,void 0,n);case"video":return new Ur(e,t,!1,n);default:throw new ho("unsupported track type: ".concat(e.kind))}}const wr=Object.values(No),Pr=Object.values(Lo),Rr=Object.values(Ao),_r=[No.h180,No.h360],Ir=[Lo.h180,Lo.h360],Or=e=>[{scaleResolutionDownBy:2,fps:e.encoding.maxFramerate}].map((t=>{var n,i;return new Io(Math.floor(e.width/t.scaleResolutionDownBy),Math.floor(e.height/t.scaleResolutionDownBy),Math.max(15e4,Math.floor(e.encoding.maxBitrate/(Math.pow(t.scaleResolutionDownBy,2)*((null!==(n=e.encoding.maxFramerate)&&void 0!==n?n:30)/(null!==(i=t.fps)&&void 0!==i?i:30))))),t.fps,e.encoding.priority)})),Mr=["q","h","f"];function xr(e,t,n,i){var s,o;let a=null==i?void 0:i.videoEncoding;e&&(a=null==i?void 0:i.screenShareEncoding);const r=null==i?void 0:i.simulcast,c=null==i?void 0:i.scalabilityMode,d=null==i?void 0:i.videoCodec;if(!a&&!r&&!c||!t||!n)return[{}];a||(a=function(e,t,n,i){const s=function(e,t,n){if(e)return Rr;const i=t>n?t/n:n/t;if(Math.abs(i-16/9)<Math.abs(i-4/3))return wr;return Pr}(e,t,n);let{encoding:o}=s[0];const a=Math.max(t,n);for(let e=0;e<s.length;e+=1){const t=s[e];if(o=t.encoding,t.width>=a)break}if(i)switch(i){case"av1":o=Object.assign({},o),o.maxBitrate=.7*o.maxBitrate;break;case"vp9":o=Object.assign({},o),o.maxBitrate=.85*o.maxBitrate}return o}(e,t,n,d),ki.debug("using video encoding",a));const l=new Io(t,n,a.maxBitrate,a.maxFramerate,a.priority);if(c&&ta(d)){ki.debug("using svc with scalabilityMode ".concat(c));const e=new Ar(c),t=[];if(e.spatial>3)throw new Error("unsupported scalabilityMode: ".concat(c));for(let n=0;n<e.spatial;n+=1)t.push({rid:Mr[2-n],maxBitrate:a.maxBitrate/Math.pow(3,n),maxFramerate:l.encoding.maxFramerate});return t[0].scalabilityMode=c,ki.debug("encodings",t),t}if(!r)return[a];let u,h=[];if(h=e?null!==(s=Lr(null==i?void 0:i.screenShareSimulcastLayers))&&void 0!==s?s:Dr(e,l):null!==(o=Lr(null==i?void 0:i.videoSimulcastLayers))&&void 0!==o?o:Dr(e,l),h.length>0){const e=h[0];h.length>1&&([,u]=h);const i=Math.max(t,n);if(i>=960&&u)return Nr(t,n,[e,u,l]);if(i>=480)return Nr(t,n,[e,l])}return Nr(t,n,[l])}function Dr(e,t){if(e)return Or(t);const{width:n,height:i}=t,s=n>i?n/i:i/n;return Math.abs(s-16/9)<Math.abs(s-4/3)?_r:Ir}function Nr(e,t,n){const i=[];if(n.forEach(((n,s)=>{if(s>=Mr.length)return;const o=Math.min(e,t),a={rid:Mr[s],scaleResolutionDownBy:Math.max(1,o/Math.min(n.width,n.height)),maxBitrate:n.encoding.maxBitrate};n.encoding.maxFramerate&&(a.maxFramerate=n.encoding.maxFramerate);const r=oa()||0===s;n.encoding.priority&&r&&(a.priority=n.encoding.priority,a.networkPriority=n.encoding.priority),i.push(a)})),la()&&"ios"===ma()){let e;i.forEach((t=>{e?t.maxFramerate&&t.maxFramerate>e&&(e=t.maxFramerate):e=t.maxFramerate}));let t=!0;i.forEach((n=>{var i;n.maxFramerate!=e&&(t&&(t=!1,ki.info("Simulcast on iOS React-Native requires all encodings to share the same framerate.")),ki.info('Setting framerate of encoding "'.concat(null!==(i=n.rid)&&void 0!==i?i:"",'" to ').concat(e)),n.maxFramerate=e)}))}return i}function Lr(e){if(e)return e.sort(((e,t)=>{const{encoding:n}=e,{encoding:i}=t;return n.maxBitrate>i.maxBitrate?1:n.maxBitrate<i.maxBitrate?-1:n.maxBitrate===i.maxBitrate&&n.maxFramerate&&i.maxFramerate?n.maxFramerate>i.maxFramerate?1:-1:0}))}class Ar{constructor(e){const t=e.match(/^L(\d)T(\d)(h|_KEY|_KEY_SHIFT){0,1}$/);if(!t)throw new Error("invalid scalability mode");if(this.spatial=parseInt(t[1]),this.temporal=parseInt(t[2]),t.length>3)switch(t[3]){case"h":case"_KEY":case"_KEY_SHIFT":this.suffix=t[3]}}toString(){var e;return"L".concat(this.spatial,"T").concat(this.temporal).concat(null!==(e=this.suffix)&&void 0!==e?e:"")}}class Ur extends xa{constructor(e,t){let n=!(arguments.length>2&&void 0!==arguments[2])||arguments[2],i=arguments.length>3?arguments[3]:void 0;super(e,jo.Kind.Video,t,n,i),this.simulcastCodecs=new Map,this.monitorSender=()=>wi(this,void 0,void 0,(function*(){if(!this.sender)return void(this._currentBitrate=0);let e;try{e=yield this.getSenderStats()}catch(e){return void this.log.error("could not get audio sender stats",Object.assign(Object.assign({},this.logContext),{error:e}))}const t=new Map(e.map((e=>[e.rid,e])));if(this.prevStats){let e=0;t.forEach(((t,n)=>{var i;const s=null===(i=this.prevStats)||void 0===i?void 0:i.get(n);e+=Cr(t,s)})),this._currentBitrate=e}this.prevStats=t})),this.senderLock=new Ra}get isSimulcast(){return!!(this.sender&&this.sender.getParameters().encodings.length>1)}startMonitor(e){var t;if(this.signalClient=e,!da())return;const n=null===(t=this.sender)||void 0===t?void 0:t.getParameters();n&&(this.encodings=n.encodings),this.monitorInterval||(this.monitorInterval=setInterval((()=>{this.monitorSender()}),br))}stop(){this._mediaStreamTrack.getConstraints(),this.simulcastCodecs.forEach((e=>{e.mediaStreamTrack.stop()})),super.stop()}pauseUpstream(){const e=Object.create(null,{pauseUpstream:{get:()=>super.pauseUpstream}});var t,n,i,s,o;return wi(this,void 0,void 0,(function*(){yield e.pauseUpstream.call(this);try{for(var a,r=!0,c=Ri(this.simulcastCodecs.values());a=yield c.next(),!(t=a.done);r=!0){s=a.value,r=!1;const e=s;yield null===(o=e.sender)||void 0===o?void 0:o.replaceTrack(null)}}catch(e){n={error:e}}finally{try{r||t||!(i=c.return)||(yield i.call(c))}finally{if(n)throw n.error}}}))}resumeUpstream(){const e=Object.create(null,{resumeUpstream:{get:()=>super.resumeUpstream}});var t,n,i,s,o;return wi(this,void 0,void 0,(function*(){yield e.resumeUpstream.call(this);try{for(var a,r=!0,c=Ri(this.simulcastCodecs.values());a=yield c.next(),!(t=a.done);r=!0){s=a.value,r=!1;const e=s;yield null===(o=e.sender)||void 0===o?void 0:o.replaceTrack(e.mediaStreamTrack)}}catch(e){n={error:e}}finally{try{r||t||!(i=c.return)||(yield i.call(c))}finally{if(n)throw n.error}}}))}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return wi(this,void 0,void 0,(function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug("Track already muted",this.logContext),this):(this.source!==jo.Source.Camera||this.isUserProvided||(this.log.debug("stopping camera track",this.logContext),this._mediaStreamTrack.stop()),yield e.mute.call(this),this)}finally{t()}}))}unmute(){const e=Object.create(null,{unmute:{get:()=>super.unmute}});return wi(this,void 0,void 0,(function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.source!==jo.Source.Camera||this.isUserProvided||(this.log.debug("reacquiring camera track",this.logContext),yield this.restartTrack()),yield e.unmute.call(this),this):(this.log.debug("Track already unmuted",this.logContext),this)}finally{t()}}))}setTrackMuted(e){super.setTrackMuted(e);for(const t of this.simulcastCodecs.values())t.mediaStreamTrack.enabled=!e}getSenderStats(){var e;return wi(this,void 0,void 0,(function*(){if(!(null===(e=this.sender)||void 0===e?void 0:e.getStats))return[];const t=[],n=yield this.sender.getStats();return n.forEach((e=>{var i;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!==(i=e.rid)&&void 0!==i?i:e.id,retransmittedPacketsSent:e.retransmittedPacketsSent,qualityLimitationReason:e.qualityLimitationReason,qualityLimitationResolutionChanges:e.qualityLimitationResolutionChanges},o=n.get(e.remoteId);o&&(s.jitter=o.jitter,s.packetsLost=o.packetsLost,s.roundTripTime=o.roundTripTime),t.push(s)}})),t}))}setPublishingQuality(t){const n=[];for(let i=e.VideoQuality.LOW;i<=e.VideoQuality.HIGH;i+=1)n.push(new Ln({quality:i,enabled:i<=t}));this.log.debug("setting publishing quality. max quality ".concat(t),this.logContext),this.setPublishingLayers(n)}setDeviceId(e){return wi(this,void 0,void 0,(function*(){return this._constraints.deviceId===e&&this._mediaStreamTrack.getSettings().deviceId===_a(e)||(this._constraints.deviceId=e,this.isMuted||(yield this.restartTrack()),this.isMuted||_a(e)===this._mediaStreamTrack.getSettings().deviceId)}))}restartTrack(e){var t,n,i,s;return wi(this,void 0,void 0,(function*(){let o;if(e){const t=Ko({video:e});"boolean"!=typeof t.video&&(o=t.video)}yield this.restart(o);try{for(var a,r=!0,c=Ri(this.simulcastCodecs.values());a=yield c.next(),!(t=a.done);r=!0){s=a.value,r=!1;const e=s;e.sender&&(e.mediaStreamTrack=this.mediaStreamTrack.clone(),yield e.sender.replaceTrack(e.mediaStreamTrack))}}catch(e){n={error:e}}finally{try{r||t||!(i=c.return)||(yield i.call(c))}finally{if(n)throw n.error}}}))}setProcessor(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];const n=Object.create(null,{setProcessor:{get:()=>super.setProcessor}});var i,s,o,a,r,c;return wi(this,void 0,void 0,(function*(){if(yield n.setProcessor.call(this,e,t),null===(r=this.processor)||void 0===r?void 0:r.processedTrack)try{for(var d,l=!0,u=Ri(this.simulcastCodecs.values());d=yield u.next(),!(i=d.done);l=!0){a=d.value,l=!1;const e=a;yield null===(c=e.sender)||void 0===c?void 0:c.replaceTrack(this.processor.processedTrack)}}catch(e){s={error:e}}finally{try{l||i||!(o=u.return)||(yield o.call(u))}finally{if(s)throw s.error}}}))}addSimulcastTrack(e,t){if(this.simulcastCodecs.has(e))return void this.log.error("".concat(e," already added, skipping adding simulcast codec"),this.logContext);const n={codec:e,mediaStreamTrack:this.mediaStreamTrack.clone(),sender:void 0,encodings:t};return this.simulcastCodecs.set(e,n),n}setSimulcastTrackSender(e,t){const n=this.simulcastCodecs.get(e);n&&(n.sender=t,setTimeout((()=>{this.subscribedCodecs&&this.setPublishingCodecs(this.subscribedCodecs)}),5e3))}setPublishingCodecs(e){var t,n,i,s,o,a,r;return wi(this,void 0,void 0,(function*(){if(this.log.debug("setting publishing codecs",Object.assign(Object.assign({},this.logContext),{codecs:e,currentCodec:this.codec})),!this.codec&&e.length>0)return yield this.setPublishingLayers(e[0].qualities),[];this.subscribedCodecs=e;const c=[];try{for(t=!0,n=Ri(e);i=yield n.next(),!(s=i.done);t=!0){r=i.value,t=!1;const e=r;if(this.codec&&this.codec!==e.codec){const t=this.simulcastCodecs.get(e.codec);if(this.log.debug("try setPublishingCodec for ".concat(e.codec),Object.assign(Object.assign({},this.logContext),{simulcastCodecInfo:t})),t&&t.sender)t.encodings&&(this.log.debug("try setPublishingLayersForSender ".concat(e.codec),this.logContext),yield jr(t.sender,t.encodings,e.qualities,this.senderLock,this.log,this.logContext));else for(const t of e.qualities)if(t.enabled){c.push(e.codec);break}}else yield this.setPublishingLayers(e.qualities)}}catch(e){o={error:e}}finally{try{t||s||!(a=n.return)||(yield a.call(n))}finally{if(o)throw o.error}}return c}))}setPublishingLayers(e){return wi(this,void 0,void 0,(function*(){this.log.debug("setting publishing layers",Object.assign(Object.assign({},this.logContext),{qualities:e})),this.sender&&this.encodings&&(yield jr(this.sender,this.encodings,e,this.senderLock,this.log,this.logContext))}))}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return wi(this,void 0,void 0,(function*(){yield e.handleAppVisibilityChanged.call(this),ca()&&this.isInBackground&&this.source===jo.Source.Camera&&(this._mediaStreamTrack.enabled=!1)}))}}function jr(e,t,n,i,s,o){return wi(this,void 0,void 0,(function*(){const a=yield i.lock();s.debug("setPublishingLayersForSender",Object.assign(Object.assign({},o),{sender:e,qualities:n,senderEncodings:t}));try{const i=e.getParameters(),{encodings:a}=i;if(!a)return;if(a.length!==t.length)return void s.warn("cannot set publishing layers, encodings mismatch",Object.assign(Object.assign({},o),{encodings:a,senderEncodings:t}));let r=!1;!1&&a[0].scalabilityMode||a.forEach(((e,i)=>{var a;let c=null!==(a=e.rid)&&void 0!==a?a:"";""===c&&(c="q");const d=Fr(c),l=n.find((e=>e.quality===d));l&&e.active!==l.enabled&&(r=!0,e.active=l.enabled,s.debug("setting layer ".concat(l.quality," to ").concat(e.active?"enabled":"disabled"),o),oa()&&(l.enabled?(e.scaleResolutionDownBy=t[i].scaleResolutionDownBy,e.maxBitrate=t[i].maxBitrate,e.maxFrameRate=t[i].maxFrameRate):(e.scaleResolutionDownBy=4,e.maxBitrate=10,e.maxFrameRate=2)))})),r&&(i.encodings=a,s.debug("setting encodings",Object.assign(Object.assign({},o),{encodings:i.encodings})),yield e.setParameters(i))}finally{a()}}))}function Fr(t){switch(t){case"f":default:return e.VideoQuality.HIGH;case"h":return e.VideoQuality.MEDIUM;case"q":return e.VideoQuality.LOW}}function Br(t,n,i,s){if(!i)return[new et({quality:e.VideoQuality.HIGH,width:t,height:n,bitrate:0,ssrc:0})];if(s){const s=i[0].scalabilityMode,o=new Ar(s),a=[];for(let s=0;s<o.spatial;s+=1)a.push(new et({quality:e.VideoQuality.HIGH-s,width:Math.ceil(t/Math.pow(2,s)),height:Math.ceil(n/Math.pow(2,s)),bitrate:i[0].maxBitrate?Math.ceil(i[0].maxBitrate/Math.pow(3,s)):0,ssrc:0}));return a}return i.map((e=>{var i,s,o;const a=null!==(i=e.scaleResolutionDownBy)&&void 0!==i?i:1;let r=Fr(null!==(s=e.rid)&&void 0!==s?s:"");return new et({quality:r,width:Math.ceil(t/a),height:Math.ceil(n/a),bitrate:null!==(o=e.maxBitrate)&&void 0!==o?o:0,ssrc:0})}))}class Vr extends jo{constructor(e,t,n,i,s){super(e,n,s),this.sid=t,this.receiver=i}setMuted(t){this.isMuted!==t&&(this.isMuted=t,this._mediaStreamTrack.enabled=!t,this.emit(t?e.TrackEvent.Muted:e.TrackEvent.Unmuted,this))}setMediaStream(t){this.mediaStream=t;const n=i=>{i.track===this._mediaStreamTrack&&(t.removeEventListener("removetrack",n),this.receiver=void 0,this._currentBitrate=0,this.emit(e.TrackEvent.Ended,this))};t.addEventListener("removetrack",n)}start(){this.startMonitor(),super.enable()}stop(){this.stopMonitor(),super.disable()}getRTCStatsReport(){var e;return wi(this,void 0,void 0,(function*(){if(!(null===(e=this.receiver)||void 0===e?void 0:e.getStats))return;return yield this.receiver.getStats()}))}startMonitor(){this.monitorInterval||(this.monitorInterval=setInterval((()=>this.monitorReceiver()),br))}}class qr extends Vr{constructor(e,t,n,i,s,o){super(e,t,jo.Kind.Audio,n,o),this.monitorReceiver=()=>wi(this,void 0,void 0,(function*(){if(!this.receiver)return void(this._currentBitrate=0);const e=yield this.getReceiverStats();e&&this.prevStats&&this.receiver&&(this._currentBitrate=Cr(e,this.prevStats)),this.prevStats=e})),this.audioContext=i,this.webAudioPluginNodes=[],s&&(this.sinkId=s.deviceId)}setVolume(e){var t;for(const n of this.attachedElements)this.audioContext?null===(t=this.gainNode)||void 0===t||t.gain.setTargetAtTime(e,0,.1):n.volume=e;la()&&this._mediaStreamTrack._setVolume(e),this.elementVolume=e}getVolume(){if(this.elementVolume)return this.elementVolume;if(la())return 1;let e=0;return this.attachedElements.forEach((t=>{t.volume>e&&(e=t.volume)})),e}setSinkId(e){return wi(this,void 0,void 0,(function*(){this.sinkId=e,yield Promise.all(this.attachedElements.map((t=>{if(na(t))return t.setSinkId(e)})))}))}attach(e){const t=0===this.attachedElements.length;return e?super.attach(e):e=super.attach(),this.sinkId&&na(e)&&e.setSinkId(this.sinkId),this.audioContext&&t&&(this.log.debug("using audio context mapping",this.logContext),this.connectWebAudio(this.audioContext,e),e.volume=0,e.muted=!0),this.elementVolume&&this.setVolume(this.elementVolume),e}detach(e){let t;return e?(t=super.detach(e),this.audioContext&&(this.attachedElements.length>0?this.connectWebAudio(this.audioContext,this.attachedElements[0]):this.disconnectWebAudio())):(t=super.detach(),this.disconnectWebAudio()),t}setAudioContext(e){this.audioContext=e,e&&this.attachedElements.length>0?this.connectWebAudio(e,this.attachedElements[0]):e||this.disconnectWebAudio()}setWebAudioPlugins(e){this.webAudioPluginNodes=e,this.attachedElements.length>0&&this.audioContext&&this.connectWebAudio(this.audioContext,this.attachedElements[0])}connectWebAudio(t,n){this.disconnectWebAudio(),this.sourceNode=t.createMediaStreamSource(n.srcObject);let i=this.sourceNode;this.webAudioPluginNodes.forEach((e=>{i.connect(e),i=e})),this.gainNode=t.createGain(),i.connect(this.gainNode),this.gainNode.connect(t.destination),this.elementVolume&&this.gainNode.gain.setTargetAtTime(this.elementVolume,0,.1),"running"!==t.state&&t.resume().then((()=>{"running"!==t.state&&this.emit(e.TrackEvent.AudioPlaybackFailed,new Error("Audio Context couldn't be started automatically"))})).catch((t=>{this.emit(e.TrackEvent.AudioPlaybackFailed,t)}))}disconnectWebAudio(){var e,t;null===(e=this.gainNode)||void 0===e||e.disconnect(),null===(t=this.sourceNode)||void 0===t||t.disconnect(),this.gainNode=void 0,this.sourceNode=void 0}getReceiverStats(){return wi(this,void 0,void 0,(function*(){if(!this.receiver||!this.receiver.getStats)return;let e;return(yield this.receiver.getStats()).forEach((t=>{"inbound-rtp"===t.type&&(e={type:"audio",timestamp:t.timestamp,jitter:t.jitter,bytesReceived:t.bytesReceived,concealedSamples:t.concealedSamples,concealmentEvents:t.concealmentEvents,silentConcealedSamples:t.silentConcealedSamples,silentConcealmentEvents:t.silentConcealmentEvents,totalAudioEnergy:t.totalAudioEnergy,totalSamplesDuration:t.totalSamplesDuration})})),e}))}}class Kr extends Vr{constructor(e,t,n,i,s){super(e,t,jo.Kind.Video,n,s),this.elementInfos=[],this.monitorReceiver=()=>wi(this,void 0,void 0,(function*(){if(!this.receiver)return void(this._currentBitrate=0);const e=yield this.getReceiverStats();e&&this.prevStats&&this.receiver&&(this._currentBitrate=Cr(e,this.prevStats)),this.prevStats=e})),this.debouncedHandleResize=bo((()=>{this.updateDimensions()}),100),this.adaptiveStreamSettings=i}get isAdaptiveStream(){return void 0!==this.adaptiveStreamSettings}get mediaStreamTrack(){return this._mediaStreamTrack}setMuted(e){super.setMuted(e),this.attachedElements.forEach((t=>{e?Bo(this._mediaStreamTrack,t):Fo(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 Gr(e);this.observeElementInfo(t)}return e}observeElementInfo(e){this.adaptiveStreamSettings&&void 0===this.elementInfos.find((t=>t===e))?(e.handleResize=()=>{this.debouncedHandleResize()},e.handleVisibilityChanged=()=>{this.updateVisibility()},this.elementInfos.push(e),e.observe(),this.debouncedHandleResize(),this.updateVisibility()):this.log.warn("visibility resize observer not triggered",this.logContext)}stopObservingElementInfo(e){if(!this.isAdaptiveStream)return void this.log.warn("stopObservingElementInfo ignored",this.logContext);const t=this.elementInfos.filter((t=>t===e));for(const e of t)e.stopObserving();this.elementInfos=this.elementInfos.filter((t=>t!==e)),this.updateVisibility(),this.debouncedHandleResize()}detach(e){let t=[];if(e)return this.stopObservingElement(e),super.detach(e);t=super.detach();for(const e of t)this.stopObservingElement(e);return t}getDecoderImplementation(){var e;return null===(e=this.prevStats)||void 0===e?void 0:e.decoderImplementation}getReceiverStats(){return wi(this,void 0,void 0,(function*(){if(!this.receiver||!this.receiver.getStats)return;const e=yield this.receiver.getStats();let t,n="",i=new Map;return e.forEach((e=>{"inbound-rtp"===e.type?(n=e.codecId,t={type:"video",framesDecoded:e.framesDecoded,framesDropped:e.framesDropped,framesReceived:e.framesReceived,packetsReceived:e.packetsReceived,packetsLost:e.packetsLost,frameWidth:e.frameWidth,frameHeight:e.frameHeight,pliCount:e.pliCount,firCount:e.firCount,nackCount:e.nackCount,jitter:e.jitter,timestamp:e.timestamp,bytesReceived:e.bytesReceived,decoderImplementation:e.decoderImplementation}):"codec"===e.type&&i.set(e.id,e)})),t&&""!==n&&i.get(n)&&(t.mimeType=i.get(n).mimeType),t}))}stopObservingElement(e){const t=this.elementInfos.filter((t=>t.element===e));for(const e of t)this.stopObservingElementInfo(e)}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return wi(this,void 0,void 0,(function*(){yield e.handleAppVisibilityChanged.call(this),this.isAdaptiveStream&&this.updateVisibility()}))}updateVisibility(){var t,n;const i=this.elementInfos.reduce(((e,t)=>Math.max(e,t.visibilityChangedAt||0)),0),s=!(null!==(n=null===(t=this.adaptiveStreamSettings)||void 0===t?void 0:t.pauseVideoInBackground)&&void 0!==n&&!n)&&this.isInBackground,o=this.elementInfos.some((e=>e.pictureInPicture)),a=this.elementInfos.some((e=>e.visible))&&!s||o;this.lastVisible!==a&&(!a&&Date.now()-i<100?_o.setTimeout((()=>{this.updateVisibility()}),100):(this.lastVisible=a,this.emit(e.TrackEvent.VisibilityChanged,a,this)))}updateDimensions(){var t,n;let i=0,s=0;const o=this.getPixelDensity();for(const e of this.elementInfos){const t=e.width()*o,n=e.height()*o;t+n>i+s&&(i=t,s=n)}(null===(t=this.lastDimensions)||void 0===t?void 0:t.width)===i&&(null===(n=this.lastDimensions)||void 0===n?void 0:n.height)===s||(this.lastDimensions={width:i,height:s},this.emit(e.TrackEvent.VideoDimensionsChanged,this.lastDimensions,this))}getPixelDensity(){var e;const t=null===(e=this.adaptiveStreamSettings)||void 0===e?void 0:e.pixelDensity;if("screen"===t)return pa();if(!t){return pa()>2?2:1}return t}}class Gr{get visible(){return this.isPiP||this.isIntersecting}get pictureInPicture(){return this.isPiP}constructor(e,t){this.onVisibilityChanged=e=>{var t;const{target:n,isIntersecting:i}=e;n===this.element&&(this.isIntersecting=i,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:Wr(e),this.isPiP=da()&&document.pictureInPictureElement===e,this.visibilityChangedAt=0}width(){return this.element.clientWidth}height(){return this.element.clientHeight}observe(){this.isIntersecting=Wr(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,ba().observe(this.element),Ta().observe(this.element),this.element.addEventListener("enterpictureinpicture",this.onEnterPiP),this.element.addEventListener("leavepictureinpicture",this.onLeavePiP)}stopObserving(){var e,t;null===(e=ba())||void 0===e||e.unobserve(this.element),null===(t=Ta())||void 0===t||t.unobserve(this.element),this.element.removeEventListener("enterpictureinpicture",this.onEnterPiP),this.element.removeEventListener("leavepictureinpicture",this.onLeavePiP)}}function Wr(e){let t=e.offsetTop,n=e.offsetLeft;const i=e.offsetWidth,s=e.offsetHeight,{hidden:o}=e,{opacity:a,display:r}=getComputedStyle(e);for(;e.offsetParent;)t+=(e=e.offsetParent).offsetTop,n+=e.offsetLeft;return t<window.pageYOffset+window.innerHeight&&n<window.pageXOffset+window.innerWidth&&t+s>window.pageYOffset&&n+i>window.pageXOffset&&!o&&(""===a||parseFloat(a)>0)&&"none"!==r}class Hr extends Gi.EventEmitter{constructor(t,n,i,s){var o;super(),this.metadataMuted=!1,this.encryption=Xe.NONE,this.log=ki,this.handleMuted=()=>{this.emit(e.TrackEvent.Muted)},this.handleUnmuted=()=>{this.emit(e.TrackEvent.Unmuted)},this.log=yi(null!==(o=null==s?void 0:s.loggerName)&&void 0!==o?o:e.LoggerNames.Publication),this.loggerContextCb=this.loggerContextCb,this.setMaxListeners(100),this.kind=t,this.trackSid=n,this.trackName=i,this.source=jo.Source.Unknown}setTrack(t){this.track&&(this.track.off(e.TrackEvent.Muted,this.handleMuted),this.track.off(e.TrackEvent.Unmuted,this.handleUnmuted)),this.track=t,t&&(t.on(e.TrackEvent.Muted,this.handleMuted),t.on(e.TrackEvent.Unmuted,this.handleUnmuted))}get logContext(){var e;return Object.assign(Object.assign({},null===(e=this.loggerContextCb)||void 0===e?void 0:e.call(this)),zo(this))}get isMuted(){return this.metadataMuted}get isEnabled(){return!0}get isSubscribed(){return void 0!==this.track}get isEncrypted(){return this.encryption!==Xe.NONE}get audioTrack(){if(this.track instanceof Sr||this.track instanceof qr)return this.track}get videoTrack(){if(this.track instanceof Ur||this.track instanceof Kr)return this.track}updateInfo(e){this.trackSid=e.sid,this.trackName=e.name,this.source=jo.sourceFromProto(e.source),this.mimeType=e.mimeType,this.kind===jo.Kind.Video&&e.width>0&&(this.dimensions={width:e.width,height:e.height},this.simulcasted=e.simulcast),this.encryption=e.encryption,this.trackInfo=e,this.log.debug("update publication info",Object.assign(Object.assign({},this.logContext),{info:e}))}}!function(e){var t,n;(t=e.SubscriptionStatus||(e.SubscriptionStatus={})).Desired="desired",t.Subscribed="subscribed",t.Unsubscribed="unsubscribed",(n=e.PermissionStatus||(e.PermissionStatus={})).Allowed="allowed",n.NotAllowed="not_allowed"}(Hr||(Hr={}));class Jr extends Hr{get isUpstreamPaused(){var e;return null===(e=this.track)||void 0===e?void 0:e.isUpstreamPaused}constructor(t,n,i,s){super(t,n.sid,n.name,s),this.track=void 0,this.handleTrackEnded=()=>{this.emit(e.TrackEvent.Ended)},this.updateInfo(n),this.setTrack(i)}setTrack(t){this.track&&this.track.off(e.TrackEvent.Ended,this.handleTrackEnded),super.setTrack(t),t&&t.on(e.TrackEvent.Ended,this.handleTrackEnded)}get isMuted(){return this.track?this.track.isMuted:super.isMuted}get audioTrack(){return super.audioTrack}get videoTrack(){return super.videoTrack}mute(){var e;return wi(this,void 0,void 0,(function*(){return null===(e=this.track)||void 0===e?void 0:e.mute()}))}unmute(){var e;return wi(this,void 0,void 0,(function*(){return null===(e=this.track)||void 0===e?void 0:e.unmute()}))}pauseUpstream(){var e;return wi(this,void 0,void 0,(function*(){yield null===(e=this.track)||void 0===e?void 0:e.pauseUpstream()}))}resumeUpstream(){var e;return wi(this,void 0,void 0,(function*(){yield null===(e=this.track)||void 0===e?void 0:e.resumeUpstream()}))}}e.ConnectionQuality=void 0,function(e){e.Excellent="excellent",e.Good="good",e.Poor="poor",e.Lost="lost",e.Unknown="unknown"}(e.ConnectionQuality||(e.ConnectionQuality={}));class zr extends Gi.EventEmitter{get logContext(){var e,t;return Object.assign({},null===(t=null===(e=this.loggerOptions)||void 0===e?void 0:e.loggerContextCb)||void 0===t?void 0:t.call(e))}get isEncrypted(){return this.trackPublications.size>0&&Array.from(this.trackPublications.values()).every((e=>e.isEncrypted))}get isAgent(){var e,t;return null!==(t=null===(e=this.permissions)||void 0===e?void 0:e.agent)&&void 0!==t&&t}constructor(t,n,i,s,o){var a;super(),this.audioLevel=0,this.isSpeaking=!1,this._connectionQuality=e.ConnectionQuality.Unknown,this.log=ki,this.log=yi(null!==(a=null==o?void 0:o.loggerName)&&void 0!==a?a:e.LoggerNames.Participant),this.loggerOptions=o,this.setMaxListeners(100),this.sid=t,this.identity=n,this.name=i,this.metadata=s,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map}getTrackPublications(){return Array.from(this.trackPublications.values())}getTrackPublication(e){for(const[,t]of this.trackPublications)if(t.source===e)return t}getTrackPublicationByName(e){for(const[,t]of this.trackPublications)if(t.trackName===e)return t}get connectionQuality(){return this._connectionQuality}get isCameraEnabled(){var e;const t=this.getTrackPublication(jo.Source.Camera);return!(null===(e=null==t?void 0:t.isMuted)||void 0===e||e)}get isMicrophoneEnabled(){var e;const t=this.getTrackPublication(jo.Source.Microphone);return!(null===(e=null==t?void 0:t.isMuted)||void 0===e||e)}get isScreenShareEnabled(){return!!this.getTrackPublication(jo.Source.ScreenShare)}get isLocal(){return!1}get joinedAt(){return this.participantInfo?new Date(1e3*Number.parseInt(this.participantInfo.joinedAt.toString())):new Date}updateInfo(e){return!(this.participantInfo&&this.participantInfo.sid===e.sid&&this.participantInfo.version>e.version)&&(this.identity=e.identity,this.sid=e.sid,this._setName(e.name),this._setMetadata(e.metadata),e.permission&&this.setPermissions(e.permission),this.participantInfo=e,this.log.trace("update participant info",Object.assign(Object.assign({},this.logContext),{info:e})),!0)}_setMetadata(t){const n=this.metadata!==t,i=this.metadata;this.metadata=t,n&&this.emit(e.ParticipantEvent.ParticipantMetadataChanged,i)}_setName(t){const n=this.name!==t;this.name=t,n&&this.emit(e.ParticipantEvent.ParticipantNameChanged,t)}setPermissions(t){var n,i,s,o,a;const r=this.permissions,c=t.canPublish!==(null===(n=this.permissions)||void 0===n?void 0:n.canPublish)||t.canSubscribe!==(null===(i=this.permissions)||void 0===i?void 0:i.canSubscribe)||t.canPublishData!==(null===(s=this.permissions)||void 0===s?void 0:s.canPublishData)||t.hidden!==(null===(o=this.permissions)||void 0===o?void 0:o.hidden)||t.recorder!==(null===(a=this.permissions)||void 0===a?void 0:a.recorder)||t.canPublishSources.length!==this.permissions.canPublishSources.length||t.canPublishSources.some(((e,t)=>{var n;return e!==(null===(n=this.permissions)||void 0===n?void 0:n.canPublishSources[t])}));return this.permissions=t,c&&this.emit(e.ParticipantEvent.ParticipantPermissionsChanged,r),c}setIsSpeaking(t){t!==this.isSpeaking&&(this.isSpeaking=t,t&&(this.lastSpokeAt=new Date),this.emit(e.ParticipantEvent.IsSpeakingChanged,t))}setConnectionQuality(t){const n=this._connectionQuality;this._connectionQuality=function(t){switch(t){case Be.EXCELLENT:return e.ConnectionQuality.Excellent;case Be.GOOD:return e.ConnectionQuality.Good;case Be.POOR:return e.ConnectionQuality.Poor;case Be.LOST:return e.ConnectionQuality.Lost;default:return e.ConnectionQuality.Unknown}}(t),n!==this._connectionQuality&&this.emit(e.ParticipantEvent.ConnectionQualityChanged,this._connectionQuality)}setAudioContext(e){this.audioContext=e,this.audioTrackPublications.forEach((t=>(t.track instanceof qr||t.track instanceof Sr)&&t.track.setAudioContext(e)))}addTrackPublication(t){t.on(e.TrackEvent.Muted,(()=>{this.emit(e.ParticipantEvent.TrackMuted,t)})),t.on(e.TrackEvent.Unmuted,(()=>{this.emit(e.ParticipantEvent.TrackUnmuted,t)}));const n=t;switch(n.track&&(n.track.sid=t.trackSid),this.trackPublications.set(t.trackSid,t),t.kind){case jo.Kind.Audio:this.audioTrackPublications.set(t.trackSid,t);break;case jo.Kind.Video:this.videoTrackPublications.set(t.trackSid,t)}}}class Qr extends zr{constructor(e,t,n,i){super(e,t,void 0,void 0,{loggerName:i.loggerName,loggerContextCb:()=>this.engine.logContext}),this.pendingPublishing=new Set,this.pendingPublishPromises=new Map,this.participantTrackPermissions=[],this.allParticipantsAllowedToSubscribe=!0,this.encryptionType=Xe.NONE,this.handleReconnecting=()=>{this.reconnectFuture||(this.reconnectFuture=new Pa)},this.handleReconnected=()=>{var e,t;null===(t=null===(e=this.reconnectFuture)||void 0===e?void 0:e.resolve)||void 0===t||t.call(e),this.reconnectFuture=void 0,this.updateTrackSubscriptionPermissions()},this.handleDisconnected=()=>{var e,t;this.reconnectFuture&&(this.reconnectFuture.promise.catch((e=>this.log.warn(e.message,this.logContext))),null===(t=null===(e=this.reconnectFuture)||void 0===e?void 0:e.reject)||void 0===t||t.call(e,"Got disconnected during reconnection attempt"),this.reconnectFuture=void 0)},this.updateTrackSubscriptionPermissions=()=>{this.log.debug("updating track subscription permissions",Object.assign(Object.assign({},this.logContext),{allParticipantsAllowed:this.allParticipantsAllowedToSubscribe,participantTrackPermissions:this.participantTrackPermissions})),this.engine.client.sendUpdateSubscriptionPermissions(this.allParticipantsAllowedToSubscribe,this.participantTrackPermissions.map((e=>function(e){var t,n,i;if(!e.participantSid&&!e.participantIdentity)throw new Error("Invalid track permission, must provide at least one of participantIdentity and participantSid");return new jn({participantIdentity:null!==(t=e.participantIdentity)&&void 0!==t?t:"",participantSid:null!==(n=e.participantSid)&&void 0!==n?n:"",allTracks:null!==(i=e.allowAll)&&void 0!==i&&i,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):this.log.error("could not update mute status for unpublished track",Object.assign(Object.assign({},this.logContext),zo(e)))},this.onTrackUpstreamPaused=e=>{this.log.debug("upstream paused",Object.assign(Object.assign({},this.logContext),zo(e))),this.onTrackMuted(e,!0)},this.onTrackUpstreamResumed=e=>{this.log.debug("upstream resumed",Object.assign(Object.assign({},this.logContext),zo(e))),this.onTrackMuted(e,e.isMuted)},this.handleSubscribedQualityUpdate=e=>wi(this,void 0,void 0,(function*(){var t,n,i,s,o,a;if(!(null===(o=this.roomOptions)||void 0===o?void 0:o.dynacast))return;const r=this.videoTrackPublications.get(e.trackSid);if(r)if(e.subscribedCodecs.length>0){if(!r.videoTrack)return;const o=yield r.videoTrack.setPublishingCodecs(e.subscribedCodecs);try{for(var c,d=!0,l=Ri(o);!(t=(c=yield l.next()).done);d=!0){s=c.value,d=!1;const e=s;xo(e)&&(this.log.debug("publish ".concat(e," for ").concat(r.videoTrack.sid),Object.assign(Object.assign({},this.logContext),zo(r))),yield this.publishAdditionalCodecForTrack(r.videoTrack,e,r.options))}}catch(e){n={error:e}}finally{try{d||t||!(i=l.return)||(yield i.call(l))}finally{if(n)throw n.error}}}else e.subscribedQualities.length>0&&(yield null===(a=r.videoTrack)||void 0===a?void 0:a.setPublishingLayers(e.subscribedQualities));else this.log.warn("received subscribed quality update for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:e.trackSid}))})),this.handleLocalTrackUnpublished=e=>{const t=this.trackPublications.get(e.trackSid);t?this.unpublishTrack(t.track):this.log.warn("received unpublished event for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:e.trackSid}))},this.handleTrackEnded=e=>wi(this,void 0,void 0,(function*(){if(e.source===jo.Source.ScreenShare||e.source===jo.Source.ScreenShareAudio)this.log.debug("unpublishing local track due to TrackEnded",Object.assign(Object.assign({},this.logContext),zo(e))),this.unpublishTrack(e);else if(e.isUserProvided)yield e.mute();else if(e instanceof Sr||e instanceof Ur)try{if(da())try{const t=yield null===navigator||void 0===navigator?void 0:navigator.permissions.query({name:e.source===jo.Source.Camera?"camera":"microphone"});if(t&&"denied"===t.state)throw this.log.warn("user has revoked access to ".concat(e.source),Object.assign(Object.assign({},this.logContext),zo(e))),t.onchange=()=>{"denied"!==t.state&&(e.isMuted||e.restartTrack(),t.onchange=null)},new Error("GetUserMedia Permission denied")}catch(e){}e.isMuted||(this.log.debug("track ended, attempting to use a different device",Object.assign(Object.assign({},this.logContext),zo(e))),yield e.restartTrack())}catch(t){this.log.warn("could not restart track, muting instead",Object.assign(Object.assign({},this.logContext),zo(e))),yield e.mute()}})),this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this.engine=n,this.roomOptions=i,this.setupEngine(n),this.activeDeviceMap=new Map}get lastCameraError(){return this.cameraError}get lastMicrophoneError(){return this.microphoneError}get isE2EEEnabled(){return this.encryptionType!==Xe.NONE}getTrackPublication(e){const t=super.getTrackPublication(e);if(t)return t}getTrackPublicationByName(e){const t=super.getTrackPublicationByName(e);if(t)return t}setupEngine(t){this.engine=t,this.engine.on(e.EngineEvent.RemoteMute,((e,t)=>{const n=this.trackPublications.get(e);n&&n.track&&(t?n.mute():n.unmute())})),this.engine.on(e.EngineEvent.Connected,this.handleReconnected).on(e.EngineEvent.SignalRestarted,this.handleReconnected).on(e.EngineEvent.SignalResumed,this.handleReconnected).on(e.EngineEvent.Restarting,this.handleReconnecting).on(e.EngineEvent.Resuming,this.handleReconnecting).on(e.EngineEvent.LocalTrackUnpublished,this.handleLocalTrackUnpublished).on(e.EngineEvent.SubscribedQualityUpdate,this.handleSubscribedQualityUpdate).on(e.EngineEvent.Disconnected,this.handleDisconnected)}setMetadata(e){var t;this.engine.client.sendUpdateLocalMetadata(e,null!==(t=this.name)&&void 0!==t?t:"")}setName(e){var t;this.engine.client.sendUpdateLocalMetadata(null!==(t=this.metadata)&&void 0!==t?t:"",e)}setCameraEnabled(e,t,n){return this.setTrackEnabled(jo.Source.Camera,e,t,n)}setMicrophoneEnabled(e,t,n){return this.setTrackEnabled(jo.Source.Microphone,e,t,n)}setScreenShareEnabled(e,t,n){return this.setTrackEnabled(jo.Source.ScreenShare,e,t,n)}setPermissions(t){const n=this.permissions,i=super.setPermissions(t);return i&&n&&this.emit(e.ParticipantEvent.ParticipantPermissionsChanged,n),i}setE2EEEnabled(e){return wi(this,void 0,void 0,(function*(){this.encryptionType=e?Xe.GCM:Xe.NONE,yield this.republishAllTracks(void 0,!1)}))}setTrackEnabled(t,n,i,s){var o,a;return wi(this,void 0,void 0,(function*(){this.log.debug("setTrackEnabled",Object.assign(Object.assign({},this.logContext),{source:t,enabled:n}));let r=this.getTrackPublication(t);if(n)if(r)yield r.unmute();else{let n;if(this.pendingPublishing.has(t))return void this.log.info("skipping duplicate published source",Object.assign(Object.assign({},this.logContext),{source:t}));this.pendingPublishing.add(t);try{switch(t){case jo.Source.Camera:n=yield this.createTracks({video:null===(o=i)||void 0===o||o});break;case jo.Source.Microphone:n=yield this.createTracks({audio:null===(a=i)||void 0===a||a});break;case jo.Source.ScreenShare:n=yield this.createScreenTracks(Object.assign({},i));break;default:throw new ho(t)}const e=[];for(const t of n)this.log.info("publishing track",Object.assign(Object.assign({},this.logContext),zo(t))),e.push(this.publishTrack(t,s));const c=yield Promise.all(e);[r]=c}catch(t){throw null==n||n.forEach((e=>{e.stop()})),t instanceof Error&&!(t instanceof ho)&&this.emit(e.ParticipantEvent.MediaDevicesError,t),t}finally{this.pendingPublishing.delete(t)}}else if(r&&r.track)if(t===jo.Source.ScreenShare){r=yield this.unpublishTrack(r.track);const e=this.getTrackPublication(jo.Source.ScreenShareAudio);e&&e.track&&this.unpublishTrack(e.track)}else yield r.mute();return r}))}enableCameraAndMicrophone(){return wi(this,void 0,void 0,(function*(){if(!this.pendingPublishing.has(jo.Source.Camera)&&!this.pendingPublishing.has(jo.Source.Microphone)){this.pendingPublishing.add(jo.Source.Camera),this.pendingPublishing.add(jo.Source.Microphone);try{const e=yield this.createTracks({audio:!0,video:!0});yield Promise.all(e.map((e=>this.publishTrack(e))))}finally{this.pendingPublishing.delete(jo.Source.Camera),this.pendingPublishing.delete(jo.Source.Microphone)}}}))}createTracks(t){var n,i;return wi(this,void 0,void 0,(function*(){const s=Ko(Vo(t,null===(n=this.roomOptions)||void 0===n?void 0:n.audioCaptureDefaults,null===(i=this.roomOptions)||void 0===i?void 0:i.videoCaptureDefaults));let o;try{o=yield navigator.mediaDevices.getUserMedia(s)}catch(e){throw e instanceof Error&&(s.audio&&(this.microphoneError=e),s.video&&(this.cameraError=e)),e}return s.audio&&(this.microphoneError=void 0,this.emit(e.ParticipantEvent.AudioStreamAcquired)),s.video&&(this.cameraError=void 0),o.getTracks().map((e=>{const n="audio"===e.kind;let i;n?t.audio:t.video;const a=n?s.audio:s.video;"boolean"!=typeof a&&(i=a);const r=Er(e,i,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});return r.kind===jo.Kind.Video?r.source=jo.Source.Camera:r.kind===jo.Kind.Audio&&(r.source=jo.Source.Microphone),r.mediaStream=o,r}))}))}createScreenTracks(t){return wi(this,void 0,void 0,(function*(){if(void 0===t&&(t={}),void 0===navigator.mediaDevices.getDisplayMedia)throw new uo("getDisplayMedia not supported");void 0!==t.resolution||ra()||(t.resolution=Ao.h1080fps30.resolution);const n=Wo(t),i=yield navigator.mediaDevices.getDisplayMedia(n),s=i.getVideoTracks();if(0===s.length)throw new ho("no video track found");const o=new Ur(s[0],void 0,!1,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});o.source=jo.Source.ScreenShare,t.contentHint&&(o.mediaStreamTrack.contentHint=t.contentHint);const a=[o];if(i.getAudioTracks().length>0){this.emit(e.ParticipantEvent.AudioStreamAcquired);const t=new Sr(i.getAudioTracks()[0],void 0,!1,this.audioContext,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});t.source=jo.Source.ScreenShareAudio,a.push(t)}return a}))}publishTrack(e,t){var n,i,s,o;return wi(this,void 0,void 0,(function*(){let a,r;if(e instanceof Sr&&e.setAudioContext(this.audioContext),yield null===(n=this.reconnectFuture)||void 0===n?void 0:n.promise,e instanceof xa&&this.pendingPublishPromises.has(e)&&(yield this.pendingPublishPromises.get(e)),e instanceof MediaStreamTrack)a=e.getConstraints();else{let t;switch(a=e.constraints,e.source){case jo.Source.Microphone:t="audioinput";break;case jo.Source.Camera:t="videoinput"}t&&this.activeDeviceMap.has(t)&&(a=Object.assign(Object.assign({},a),{deviceId:this.activeDeviceMap.get(t)}))}if(e instanceof MediaStreamTrack)switch(e.kind){case"audio":e=new Sr(e,a,!0,this.audioContext,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});break;case"video":e=new Ur(e,a,!0,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});break;default:throw new ho("unsupported MediaStreamTrack kind ".concat(e.kind))}else e.updateLoggerOptions({loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});if(this.trackPublications.forEach((t=>{t.track&&t.track===e&&(r=t)})),r)return this.log.warn("track has already been published, skipping",Object.assign(Object.assign({},this.logContext),zo(r))),r;const c="channelCount"in e.mediaStreamTrack.getSettings()&&2===e.mediaStreamTrack.getSettings().channelCount||2===e.mediaStreamTrack.getConstraints().channelCount,d=null!==(i=null==t?void 0:t.forceStereo)&&void 0!==i?i:c;d&&(t||(t={}),void 0===t.dtx&&this.log.info("Opus DTX will be disabled for stereo tracks by default. Enable them explicitly to make it work.",Object.assign(Object.assign({},this.logContext),zo(e))),void 0===t.red&&this.log.info("Opus RED will be disabled for stereo tracks by default. Enable them explicitly to make it work."),null!==(s=t.dtx)&&void 0!==s||(t.dtx=!1),null!==(o=t.red)&&void 0!==o||(t.red=!1));const l=Object.assign(Object.assign({},this.roomOptions.publishDefaults),t);aa()&&this.roomOptions.e2ee&&(this.log.info("End-to-end encryption is set up, simulcast publishing will be disabled on Safari",Object.assign({},this.logContext)),l.simulcast=!1),l.source&&(e.source=l.source);const u=this.publish(e,l,d);this.pendingPublishPromises.set(e,u);try{return yield u}catch(e){throw e}finally{this.pendingPublishPromises.delete(e)}}))}publish(t,n,i){var s,o,a,r,c,d,l,u,h,m,p,g;return wi(this,void 0,void 0,(function*(){Array.from(this.trackPublications.values()).find((e=>t instanceof xa&&e.source===t.source))&&t.source!==jo.Source.Unknown&&this.log.info("publishing a second track with the same source: ".concat(t.source),Object.assign(Object.assign({},this.logContext),zo(t))),n.stopMicTrackOnMute&&t instanceof Sr&&(t.stopOnMute=!0),t.source===jo.Source.ScreenShare&&oa()&&(n.simulcast=!1),"av1"!==n.videoCodec||$o()||(n.videoCodec=void 0),"vp9"!==n.videoCodec||ea()||(n.videoCodec=void 0),void 0===n.videoCodec&&(n.videoCodec=ar);const f=n.videoCodec;t.on(e.TrackEvent.Muted,this.onTrackMuted),t.on(e.TrackEvent.Unmuted,this.onTrackUnmuted),t.on(e.TrackEvent.Ended,this.handleTrackEnded),t.on(e.TrackEvent.UpstreamPaused,this.onTrackUpstreamPaused),t.on(e.TrackEvent.UpstreamResumed,this.onTrackUpstreamResumed);const v=new mn({cid:t.mediaStreamTrack.id,name:n.name,type:jo.kindToProto(t.kind),muted:t.isMuted,source:jo.sourceToProto(t.source),disableDtx:!(null===(s=n.dtx)||void 0===s||s),encryption:this.encryptionType,stereo:i,disableRed:this.isE2EEEnabled||!(null===(o=n.red)||void 0===o||o),stream:null==n?void 0:n.stream});let k;if(t.kind===jo.Kind.Video){let e={width:0,height:0};try{e=yield t.waitForDimensions()}catch(n){const i=null!==(r=null===(a=this.roomOptions.videoCaptureDefaults)||void 0===a?void 0:a.resolution)&&void 0!==r?r:No.h720.resolution;e={width:i.width,height:i.height},this.log.error("could not determine track dimensions, using defaults",Object.assign(Object.assign(Object.assign({},this.logContext),zo(t)),{dims:e}))}v.width=e.width,v.height=e.height,t instanceof Ur&&(ta(f)&&(t.source===jo.Source.ScreenShare&&"vp9"===f&&(n.scalabilityMode="L1T3"),n.scalabilityMode=null!==(c=n.scalabilityMode)&&void 0!==c?c:"L3T3_KEY"),v.simulcastCodecs=[new hn({codec:f,cid:t.mediaStreamTrack.id})],!0===n.backupCodec&&(n.backupCodec={codec:ar}),n.backupCodec&&f!==n.backupCodec.codec&&v.encryption===Xe.NONE&&(this.roomOptions.dynacast||(this.roomOptions.dynacast=!0),v.simulcastCodecs.push(new hn({codec:n.backupCodec.codec,cid:""})))),k=xr(t.source===jo.Source.ScreenShare,v.width,v.height,n),v.layers=Br(v.width,v.height,k,ta(n.videoCodec))}else t.kind===jo.Kind.Audio&&(k=[{maxBitrate:null===(d=n.audioPreset)||void 0===d?void 0:d.maxBitrate,priority:null!==(u=null===(l=n.audioPreset)||void 0===l?void 0:l.priority)&&void 0!==u?u:"high",networkPriority:null!==(m=null===(h=n.audioPreset)||void 0===h?void 0:h.priority)&&void 0!==m?m:"high"}]);if(!this.engine||this.engine.isClosed)throw new po("cannot publish track when not connected");const T=yield this.engine.addTrack(v);let y;if(T.codecs.forEach((e=>{void 0===y&&(y=e.mimeType)})),y&&t.kind===jo.Kind.Video){const e=Ho(y);e!==f&&(this.log.debug("falling back to server selected codec",Object.assign(Object.assign(Object.assign({},this.logContext),zo(t)),{codec:e})),n.videoCodec=e,k=xr(t.source===jo.Source.ScreenShare,v.width,v.height,n))}const b=new Jr(t.kind,T,t,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});if(b.options=n,t.sid=T.sid,!this.engine.pcManager)throw new po("pcManager is not ready");if(this.log.debug("publishing ".concat(t.kind," with encodings"),Object.assign(Object.assign({},this.logContext),{encodings:k,trackInfo:T})),t.sender=yield this.engine.createSender(t,n,k),k)if(oa()&&t.kind===jo.Kind.Audio){let e;for(const n of this.engine.pcManager.publisher.getTransceivers())if(n.sender===t.sender){e=n;break}e&&this.engine.pcManager.publisher.setTrackCodecBitrate({transceiver:e,codec:"opus",maxbr:(null===(p=k[0])||void 0===p?void 0:p.maxBitrate)?k[0].maxBitrate/1e3:0})}else t.codec&&ta(t.codec)&&(null===(g=k[0])||void 0===g?void 0:g.maxBitrate)&&this.engine.pcManager.publisher.setTrackCodecBitrate({cid:v.cid,codec:t.codec,maxbr:k[0].maxBitrate/1e3});return yield this.engine.negotiate(),t instanceof Ur?t.startMonitor(this.engine.client):t instanceof Sr&&t.startMonitor(),this.addTrackPublication(b),this.emit(e.ParticipantEvent.LocalTrackPublished,b),b}))}get isLocal(){return!0}publishAdditionalCodecForTrack(e,t,n){var i;return wi(this,void 0,void 0,(function*(){if(this.encryptionType!==Xe.NONE)return;let s;if(this.trackPublications.forEach((t=>{t.track&&t.track===e&&(s=t)})),!s)throw new ho("track is not published");if(!(e instanceof Ur))throw new ho("track is not a video track");const o=Object.assign(Object.assign({},null===(i=this.roomOptions)||void 0===i?void 0:i.publishDefaults),n),a=function(e,t,n){var i,s,o,a;if(!n.backupCodec||!0===n.backupCodec||n.backupCodec.codec===n.videoCodec)return;t!==n.backupCodec.codec&&ki.warn("requested a different codec than specified as backup",{serverRequested:t,backup:n.backupCodec.codec}),n.videoCodec=t,n.videoEncoding=n.backupCodec.encoding;const r=e.mediaStreamTrack.getSettings(),c=null!==(i=r.width)&&void 0!==i?i:null===(s=e.dimensions)||void 0===s?void 0:s.width,d=null!==(o=r.height)&&void 0!==o?o:null===(a=e.dimensions)||void 0===a?void 0:a.height;return xr(e.source===jo.Source.ScreenShare,c,d,n)}(e,t,o);if(!a)return void this.log.info("backup codec has been disabled, ignoring request to add additional codec for track",Object.assign(Object.assign({},this.logContext),zo(e)));const r=e.addSimulcastTrack(t,a);if(!r)return;const c=new mn({cid:r.mediaStreamTrack.id,type:jo.kindToProto(e.kind),muted:e.isMuted,source:jo.sourceToProto(e.source),sid:e.sid,simulcastCodecs:[{codec:o.videoCodec,cid:r.mediaStreamTrack.id}]});if(c.layers=Br(c.width,c.height,a),!this.engine||this.engine.isClosed)throw new po("cannot publish track when not connected");const d=yield this.engine.addTrack(c);yield this.engine.createSimulcastSender(e,r,o,a),yield this.engine.negotiate(),this.log.debug("published ".concat(t," for track ").concat(e.sid),Object.assign(Object.assign({},this.logContext),{encodings:a,trackInfo:d}))}))}unpublishTrack(t,n){var i,s;return wi(this,void 0,void 0,(function*(){const o=this.getPublicationForTrack(t),a=o?zo(o):void 0;if(this.log.debug("unpublishing track",Object.assign(Object.assign({},this.logContext),a)),!o||!o.track)return void this.log.warn("track was not unpublished because no publication was found",Object.assign(Object.assign({},this.logContext),a));(t=o.track).off(e.TrackEvent.Muted,this.onTrackMuted),t.off(e.TrackEvent.Unmuted,this.onTrackUnmuted),t.off(e.TrackEvent.Ended,this.handleTrackEnded),t.off(e.TrackEvent.UpstreamPaused,this.onTrackUpstreamPaused),t.off(e.TrackEvent.UpstreamResumed,this.onTrackUpstreamResumed),void 0===n&&(n=null===(s=null===(i=this.roomOptions)||void 0===i?void 0:i.stopLocalTrackOnUnpublish)||void 0===s||s),n&&t.stop();let r=!1;const c=t.sender;if(t.sender=void 0,this.engine.pcManager&&this.engine.pcManager.currentState<hr.FAILED&&c)try{for(const e of this.engine.pcManager.publisher.getTransceivers())e.sender===c&&(e.direction="inactive",r=!0);if(this.engine.removeTrack(c)&&(r=!0),t instanceof Ur){for(const[,e]of t.simulcastCodecs)e.sender&&(this.engine.removeTrack(e.sender)&&(r=!0),e.sender=void 0);t.simulcastCodecs.clear()}}catch(e){this.log.warn("failed to unpublish track",Object.assign(Object.assign(Object.assign({},this.logContext),a),{error:e}))}switch(this.trackPublications.delete(o.trackSid),o.kind){case jo.Kind.Audio:this.audioTrackPublications.delete(o.trackSid);break;case jo.Kind.Video:this.videoTrackPublications.delete(o.trackSid)}return this.emit(e.ParticipantEvent.LocalTrackUnpublished,o),o.setTrack(void 0),r&&(yield this.engine.negotiate()),o}))}unpublishTracks(e){return wi(this,void 0,void 0,(function*(){return(yield Promise.all(e.map((e=>this.unpublishTrack(e))))).filter((e=>e instanceof Jr))}))}republishAllTracks(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return wi(this,void 0,void 0,(function*(){const n=[];this.trackPublications.forEach((t=>{t.track&&(e&&(t.options=Object.assign(Object.assign({},t.options),e)),n.push(t))})),yield Promise.all(n.map((e=>wi(this,void 0,void 0,(function*(){const n=e.track;yield this.unpublishTrack(n,!1),t&&!n.isMuted&&n.source!==jo.Source.ScreenShare&&n.source!==jo.Source.ScreenShareAudio&&(n instanceof Sr||n instanceof Ur)&&!n.isUserProvided&&(this.log.debug("restarting existing track",Object.assign(Object.assign({},this.logContext),{track:e.trackSid})),yield n.restartTrack()),yield this.publishTrack(n,e.options)})))))}))}publishData(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return wi(this,void 0,void 0,(function*(){const n=t.reliable?nt.RELIABLE:nt.LOSSY,i=t.destinationIdentities,s=t.topic,o=new tt({kind:n,value:{case:"user",value:new ot({participantIdentity:this.identity,payload:e,destinationIdentities:i,topic:s})}});yield this.engine.sendDataPacket(o,n)}))}setTrackSubscriptionPermissions(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[];this.participantTrackPermissions=t,this.allParticipantsAllowedToSubscribe=e,this.engine.client.isDisconnected||this.updateTrackSubscriptionPermissions()}updateInfo(e){return e.sid===this.sid&&(!!super.updateInfo(e)&&(e.tracks.forEach((e=>{var t,n;const i=this.trackPublications.get(e.sid);if(i){const s=i.isMuted||null!==(n=null===(t=i.track)||void 0===t?void 0:t.isUpstreamPaused)&&void 0!==n&&n;s!==e.muted&&(this.log.debug("updating server mute state after reconcile",Object.assign(Object.assign(Object.assign({},this.logContext),zo(i)),{mutedOnServer:s})),this.engine.client.sendMuteTrack(e.sid,s))}})),!0))}getPublicationForTrack(e){let t;return this.trackPublications.forEach((n=>{const i=n.track;i&&(e instanceof MediaStreamTrack?(i instanceof Sr||i instanceof Ur)&&i.mediaStreamTrack===e&&(t=n):e===i&&(t=n))})),t}}class Yr extends Hr{constructor(t,n,i,s){super(t,n.sid,n.name,s),this.track=void 0,this.allowed=!0,this.disabled=!1,this.currentVideoQuality=e.VideoQuality.HIGH,this.handleEnded=t=>{this.setTrack(void 0),this.emit(e.TrackEvent.Ended,t)},this.handleVisibilityChange=e=>{this.log.debug("adaptivestream video visibility ".concat(this.trackSid,", visible=").concat(e),this.logContext),this.disabled=!e,this.emitTrackUpdate()},this.handleVideoDimensionsChange=e=>{this.log.debug("adaptivestream video dimensions ".concat(e.width,"x").concat(e.height),this.logContext),this.videoDimensions=e,this.emitTrackUpdate()},this.subscribed=i,this.updateInfo(n)}setSubscribed(t){const n=this.subscriptionStatus,i=this.permissionStatus;this.subscribed=t,t&&(this.allowed=!0);const s=new Cn({trackSids:[this.trackSid],subscribe:this.subscribed,participantTracks:[new rt({participantSid:"",trackSids:[this.trackSid]})]});this.emit(e.TrackEvent.UpdateSubscription,s),this.emitSubscriptionUpdateIfChanged(n),this.emitPermissionUpdateIfChanged(i)}get subscriptionStatus(){return!1===this.subscribed?Hr.SubscriptionStatus.Unsubscribed:super.isSubscribed?Hr.SubscriptionStatus.Subscribed:Hr.SubscriptionStatus.Desired}get permissionStatus(){return this.allowed?Hr.PermissionStatus.Allowed:Hr.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,n;this.isManualOperationAllowed()&&((null===(t=this.videoDimensions)||void 0===t?void 0:t.width)===e.width&&(null===(n=this.videoDimensions)||void 0===n?void 0:n.height)===e.height||(this.track instanceof Kr&&(this.videoDimensions=e),this.currentVideoQuality=void 0,this.emitTrackUpdate()))}setVideoFPS(e){this.isManualOperationAllowed()&&this.track instanceof Kr&&this.fps!==e&&(this.fps=e,this.emitTrackUpdate())}get videoQuality(){return this.currentVideoQuality}setTrack(t){const n=this.subscriptionStatus,i=this.permissionStatus,s=this.track;s!==t&&(s&&(s.off(e.TrackEvent.VideoDimensionsChanged,this.handleVideoDimensionsChange),s.off(e.TrackEvent.VisibilityChanged,this.handleVisibilityChange),s.off(e.TrackEvent.Ended,this.handleEnded),s.detach(),s.stopMonitor(),this.emit(e.TrackEvent.Unsubscribed,s)),super.setTrack(t),t&&(t.sid=this.trackSid,t.on(e.TrackEvent.VideoDimensionsChanged,this.handleVideoDimensionsChange),t.on(e.TrackEvent.VisibilityChanged,this.handleVisibilityChange),t.on(e.TrackEvent.Ended,this.handleEnded),this.emit(e.TrackEvent.Subscribed,t)),this.emitPermissionUpdateIfChanged(i),this.emitSubscriptionUpdateIfChanged(n))}setAllowed(e){const t=this.subscriptionStatus,n=this.permissionStatus;this.allowed=e,this.emitPermissionUpdateIfChanged(n),this.emitSubscriptionUpdateIfChanged(t)}setSubscriptionError(t){this.emit(e.TrackEvent.SubscriptionFailed,t)}updateInfo(t){super.updateInfo(t);const n=this.metadataMuted;this.metadataMuted=t.muted,this.track?this.track.setMuted(t.muted):n!==t.muted&&this.emit(t.muted?e.TrackEvent.Muted:e.TrackEvent.Unmuted)}emitSubscriptionUpdateIfChanged(t){const n=this.subscriptionStatus;t!==n&&this.emit(e.TrackEvent.SubscriptionStatusChanged,n,t)}emitPermissionUpdateIfChanged(t){this.permissionStatus!==t&&this.emit(e.TrackEvent.SubscriptionPermissionChanged,this.permissionStatus,t)}isManualOperationAllowed(){return this.kind===jo.Kind.Video&&this.isAdaptiveStream?(this.log.warn("adaptive stream is enabled, cannot change video track settings",this.logContext),!1):!!this.isDesired||(this.log.warn("cannot update track settings when not subscribed",this.logContext),!1)}get isAdaptiveStream(){return this.track instanceof Kr&&this.track.isAdaptiveStream}emitTrackUpdate(){const t=new Sn({trackSids:[this.trackSid],disabled:this.disabled,fps:this.fps});this.videoDimensions?(t.width=Math.ceil(this.videoDimensions.width),t.height=Math.ceil(this.videoDimensions.height)):void 0!==this.currentVideoQuality?t.quality=this.currentVideoQuality:t.quality=e.VideoQuality.HIGH,this.emit(e.TrackEvent.UpdateSettings,t)}}class Xr extends zr{static fromParticipantInfo(e,t){return new Xr(e,t.sid,t.identity,t.name,t.metadata)}get logContext(){return Object.assign(Object.assign({},super.logContext),{rpID:this.sid,remoteParticipant:this.identity})}constructor(e,t,n,i,s,o){super(t,n||"",i,s,o),this.signalClient=e,this.trackPublications=new Map,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.volumeMap=new Map}addTrackPublication(t){super.addTrackPublication(t),t.on(e.TrackEvent.UpdateSettings,(e=>{this.log.debug("send update settings",Object.assign(Object.assign({},this.logContext),zo(t))),this.signalClient.sendUpdateTrackSettings(e)})),t.on(e.TrackEvent.UpdateSubscription,(e=>{e.participantTracks.forEach((e=>{e.participantSid=this.sid})),this.signalClient.sendUpdateSubscription(e)})),t.on(e.TrackEvent.SubscriptionPermissionChanged,(n=>{this.emit(e.ParticipantEvent.TrackSubscriptionPermissionChanged,t,n)})),t.on(e.TrackEvent.SubscriptionStatusChanged,(n=>{this.emit(e.ParticipantEvent.TrackSubscriptionStatusChanged,t,n)})),t.on(e.TrackEvent.Subscribed,(n=>{this.emit(e.ParticipantEvent.TrackSubscribed,n,t)})),t.on(e.TrackEvent.Unsubscribed,(n=>{this.emit(e.ParticipantEvent.TrackUnsubscribed,n,t)})),t.on(e.TrackEvent.SubscriptionFailed,(n=>{this.emit(e.ParticipantEvent.TrackSubscriptionFailed,t.trackSid,n)}))}getTrackPublication(e){const t=super.getTrackPublication(e);if(t)return t}getTrackPublicationByName(e){const t=super.getTrackPublicationByName(e);if(t)return t}setVolume(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:jo.Source.Microphone;this.volumeMap.set(t,e);const n=this.getTrackPublication(t);n&&n.track&&n.track.setVolume(e)}getVolume(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:jo.Source.Microphone;const t=this.getTrackPublication(e);return t&&t.track?t.track.getVolume():this.volumeMap.get(e)}addSubscribedMediaTrack(t,n,i,s,o,a){let r=this.getTrackPublicationBySid(n);if(r||n.startsWith("TR")||this.trackPublications.forEach((e=>{r||t.kind!==e.kind.toString()||(r=e)})),!r)return 0===a?(this.log.error("could not find published track",Object.assign(Object.assign({},this.logContext),{trackSid:n})),void this.emit(e.ParticipantEvent.TrackSubscriptionFailed,n)):(void 0===a&&(a=20),void setTimeout((()=>{this.addSubscribedMediaTrack(t,n,i,s,o,a-1)}),150));if("ended"===t.readyState)return this.log.error("unable to subscribe because MediaStreamTrack is ended. Do not call MediaStreamTrack.stop()",Object.assign(Object.assign({},this.logContext),zo(r))),void this.emit(e.ParticipantEvent.TrackSubscriptionFailed,n);let c;return c="video"===t.kind?new Kr(t,n,s,o):new qr(t,n,s,this.audioContext,this.audioOutput),c.source=r.source,c.isMuted=r.isMuted,c.setMediaStream(i),c.start(),r.setTrack(c),this.volumeMap.has(r.source)&&c instanceof qr&&c.setVolume(this.volumeMap.get(r.source)),r}get hasMetadata(){return!!this.participantInfo}getTrackPublicationBySid(e){return this.trackPublications.get(e)}updateInfo(t){if(!super.updateInfo(t))return!1;const n=new Map,i=new Map;return t.tracks.forEach((e=>{var t,s;let o=this.getTrackPublicationBySid(e.sid);if(o)o.updateInfo(e);else{const n=jo.kindFromProto(e.type);if(!n)return;o=new Yr(n,e,null===(t=this.signalClient.connectOptions)||void 0===t?void 0:t.autoSubscribe,{loggerContextCb:()=>this.logContext,loggerName:null===(s=this.loggerOptions)||void 0===s?void 0:s.loggerName}),o.updateInfo(e),i.set(e.sid,o);const a=Array.from(this.trackPublications.values()).find((e=>e.source===(null==o?void 0:o.source)));a&&o.source!==jo.Source.Unknown&&this.log.debug("received a second track publication for ".concat(this.identity," with the same source: ").concat(o.source),Object.assign(Object.assign({},this.logContext),{oldTrack:zo(a),newTrack:zo(o)})),this.addTrackPublication(o)}n.set(e.sid,o)})),this.trackPublications.forEach((e=>{n.has(e.trackSid)||(this.log.trace("detected removed track on remote participant, unpublishing",Object.assign(Object.assign({},this.logContext),zo(e))),this.unpublishTrack(e.trackSid,!0))})),i.forEach((t=>{this.emit(e.ParticipantEvent.TrackPublished,t)})),!0}unpublishTrack(t,n){const i=this.trackPublications.get(t);if(!i)return;const{track:s}=i;switch(s&&(s.stop(),i.setTrack(void 0)),this.trackPublications.delete(t),i.kind){case jo.Kind.Audio:this.audioTrackPublications.delete(t);break;case jo.Kind.Video:this.videoTrackPublications.delete(t)}n&&this.emit(e.ParticipantEvent.TrackUnpublished,i)}setAudioOutput(e){return wi(this,void 0,void 0,(function*(){this.audioOutput=e;const t=[];this.audioTrackPublications.forEach((n=>{var i;n.track instanceof qr&&t.push(n.track.setSinkId(null!==(i=e.deviceId)&&void 0!==i?i:"default"))})),yield Promise.all(t)}))}emit(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),i=1;i<t;i++)n[i-1]=arguments[i];return this.log.trace("participant event",Object.assign(Object.assign({},this.logContext),{event:e,args:n})),super.emit(e,...n)}}var Zr;e.ConnectionState=void 0,(Zr=e.ConnectionState||(e.ConnectionState={})).Disconnected="disconnected",Zr.Connecting="connecting",Zr.Connected="connected",Zr.Reconnecting="reconnecting";class $r extends Gi.EventEmitter{constructor(t){var n,i,s;super(),n=this,this.state=e.ConnectionState.Disconnected,this.activeSpeakers=[],this.isE2EEEnabled=!1,this.audioEnabled=!0,this.isVideoPlaybackBlocked=!1,this.log=ki,this.bufferedEvents=[],this.isResuming=!1,this.connect=(t,n,i)=>wi(this,void 0,void 0,(function*(){var s;if(!sa())throw la()?Error("WebRTC isn't detected, have you called registerGlobals?"):Error("LiveKit doesn't seem to be supported on this browser. Try to update your browser and make sure no browser extensions are disabling webRTC.");const o=yield this.disconnectLock.lock();if(this.state===e.ConnectionState.Connected)return this.log.info("already connected to room ".concat(this.name),this.logContext),o(),Promise.resolve();if(this.connectFuture)return o(),this.connectFuture.promise;this.setAndEmitConnectionState(e.ConnectionState.Connecting),(null===(s=this.regionUrlProvider)||void 0===s?void 0:s.getServerUrl().toString())!==t&&(this.regionUrl=void 0,this.regionUrlProvider=void 0),ua(new URL(t))&&(void 0===this.regionUrlProvider?this.regionUrlProvider=new yr(t,n):this.regionUrlProvider.updateToken(n),this.regionUrlProvider.fetchRegionSettings().catch((e=>{this.log.warn("could not fetch region settings",Object.assign(Object.assign({},this.logContext),{error:e}))})));const a=(e,s,r)=>wi(this,void 0,void 0,(function*(){var c;this.abortController&&this.abortController.abort();const d=new AbortController;this.abortController=d,null==o||o();try{yield this.attemptConnection(null!=r?r:t,n,i,d),this.abortController=void 0,e()}catch(t){if(this.regionUrlProvider&&t instanceof lo&&3!==t.reason&&0!==t.reason){let n=null;try{n=yield this.regionUrlProvider.getNextBestRegionUrl(null===(c=this.abortController)||void 0===c?void 0:c.signal)}catch(e){if(e instanceof lo&&(401===e.status||3===e.reason))return this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),void s(e)}n?(this.log.info("Initial connection failed with ConnectionError: ".concat(t.message,". Retrying with another region: ").concat(n),this.logContext),yield a(e,s,n)):(this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),s(t))}else this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),s(t)}})),r=this.regionUrl;return this.regionUrl=void 0,this.connectFuture=new Pa(((e,t)=>{a(e,t,r)}),(()=>{this.clearConnectionFutures()})),this.connectFuture.promise})),this.connectSignal=(e,t,n,i,s,o)=>wi(this,void 0,void 0,(function*(){var a,r,c;const d=yield n.join(e,t,{autoSubscribe:i.autoSubscribe,adaptiveStream:"object"==typeof s.adaptiveStream||s.adaptiveStream,maxRetries:i.maxRetries,e2eeEnabled:!!this.e2eeManager,websocketTimeout:i.websocketTimeout},o.signal);let l=d.serverInfo;if(l||(l={version:d.serverVersion,region:d.serverRegion}),this.log.debug("connected to Livekit Server ".concat(Object.entries(l).map((e=>{let[t,n]=e;return"".concat(t,": ").concat(n)})).join(", ")),{room:null===(a=d.room)||void 0===a?void 0:a.name,roomSid:null===(r=d.room)||void 0===r?void 0:r.sid,identity:null===(c=d.participant)||void 0===c?void 0:c.identity}),!d.serverVersion)throw new mo("unknown server version");return"0.15.1"===d.serverVersion&&this.options.dynacast&&(this.log.debug("disabling dynacast due to server version",this.logContext),s.dynacast=!1),d})),this.applyJoinResponse=e=>{const t=e.participant;if(this.localParticipant.sid=t.sid,this.localParticipant.identity=t.identity,this.options.e2ee&&this.e2eeManager)try{this.e2eeManager.setSifTrailer(e.sifTrailer)}catch(e){this.log.error(e instanceof Error?e.message:"Could not set SifTrailer",Object.assign(Object.assign({},this.logContext),{error:e}))}this.handleParticipantUpdates([t,...e.otherParticipants]),e.room&&this.handleRoomUpdate(e.room)},this.attemptConnection=(t,n,i,s)=>wi(this,void 0,void 0,(function*(){var o,a,r;this.state===e.ConnectionState.Reconnecting||this.isResuming||(null===(o=this.engine)||void 0===o?void 0:o.pendingReconnect)?(this.log.info("Reconnection attempt replaced by new connection attempt",this.logContext),this.recreateEngine()):this.maybeCreateEngine(),(null===(a=this.regionUrlProvider)||void 0===a?void 0:a.isCloud())&&this.engine.setRegionUrlProvider(this.regionUrlProvider),this.acquireAudioContext(),this.connOptions=Object.assign(Object.assign({},ur),i),this.connOptions.rtcConfig&&(this.engine.rtcConfig=this.connOptions.rtcConfig),this.connOptions.peerConnectionTimeout&&(this.engine.peerConnectionTimeout=this.connOptions.peerConnectionTimeout);try{const i=yield this.connectSignal(t,n,this.engine,this.connOptions,this.options,s);this.applyJoinResponse(i),this.setupLocalParticipantEvents(),this.emit(e.RoomEvent.SignalConnected)}catch(e){yield this.engine.close(),this.recreateEngine();const t=new lo("could not establish signal connection");throw e instanceof Error&&(t.message="".concat(t.message,": ").concat(e.message)),e instanceof lo&&(t.reason=e.reason,t.status=e.status),this.log.debug("error trying to establish signal connection",Object.assign(Object.assign({},this.logContext),{error:e})),t}if(s.signal.aborted)throw yield this.engine.close(),this.recreateEngine(),new lo("Connection attempt aborted");try{yield this.engine.waitForPCInitialConnection(this.connOptions.peerConnectionTimeout,s)}catch(e){throw yield this.engine.close(),this.recreateEngine(),e}da()&&this.options.disconnectOnPageLeave&&(window.addEventListener("pagehide",this.onPageLeave),window.addEventListener("beforeunload",this.onPageLeave)),da()&&(document.addEventListener("freeze",this.onPageLeave),null===(r=navigator.mediaDevices)||void 0===r||r.addEventListener("devicechange",this.handleDeviceChange)),this.setAndEmitConnectionState(e.ConnectionState.Connected),this.emit(e.RoomEvent.Connected),this.registerConnectionReconcile()})),this.disconnect=function(){let t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return wi(n,void 0,void 0,(function*(){var n,i,s,o;const a=yield this.disconnectLock.lock();try{if(this.state===e.ConnectionState.Disconnected)return void this.log.debug("already disconnected",this.logContext);this.log.info("disconnect from room",Object.assign({},this.logContext)),(this.state===e.ConnectionState.Connecting||this.state===e.ConnectionState.Reconnecting||this.isResuming)&&(this.log.warn("abort connection attempt",this.logContext),null===(n=this.abortController)||void 0===n||n.abort(),null===(s=null===(i=this.connectFuture)||void 0===i?void 0:i.reject)||void 0===s||s.call(i,new lo("Client initiated disconnect")),this.connectFuture=void 0),(null===(o=this.engine)||void 0===o?void 0:o.client.isDisconnected)||(yield this.engine.client.sendLeave()),this.engine&&(yield this.engine.close()),this.handleDisconnect(t,qe.CLIENT_INITIATED),this.engine=void 0}finally{a()}}))},this.onPageLeave=()=>wi(this,void 0,void 0,(function*(){this.log.info("Page leave detected, disconnecting",this.logContext),yield this.disconnect()})),this.startAudio=()=>wi(this,void 0,void 0,(function*(){const t=[],n=Eo();if(n&&"iOS"===n.os){const n="livekit-dummy-audio-el";let i=document.getElementById(n);if(!i){i=document.createElement("audio"),i.id=n,i.autoplay=!0,i.hidden=!0;const t=wa();t.enabled=!0;const s=new MediaStream([t]);i.srcObject=s,document.addEventListener("visibilitychange",(()=>{i&&(i.srcObject=document.hidden?null:s,document.hidden||(this.log.debug("page visible again, triggering startAudio to resume playback and update playback status",this.logContext),this.startAudio()))})),document.body.append(i),this.once(e.RoomEvent.Disconnected,(()=>{null==i||i.remove(),i=null}))}t.push(i)}this.remoteParticipants.forEach((e=>{e.audioTrackPublications.forEach((e=>{e.track&&e.track.attachedElements.forEach((e=>{t.push(e)}))}))}));try{yield Promise.all([this.acquireAudioContext(),...t.map((e=>(e.muted=!1,e.play())))]),this.handleAudioPlaybackStarted()}catch(e){throw this.handleAudioPlaybackFailed(e),e}})),this.startVideo=()=>wi(this,void 0,void 0,(function*(){const e=[];for(const t of this.remoteParticipants.values())t.videoTrackPublications.forEach((t=>{var n;null===(n=t.track)||void 0===n||n.attachedElements.forEach((t=>{e.includes(t)||e.push(t)}))}));yield Promise.all(e.map((e=>e.play()))).then((()=>{this.handleVideoPlaybackStarted()})).catch((e=>{"NotAllowedError"===e.name?this.handleVideoPlaybackFailed():this.log.warn("Resuming video playback failed, make sure you call `startVideo` directly in a user gesture handler",this.logContext)}))})),this.handleRestarting=()=>{this.clearConnectionReconcile(),this.isResuming=!1;for(const e of this.remoteParticipants.values())this.handleParticipantDisconnected(e.identity,e);this.setAndEmitConnectionState(e.ConnectionState.Reconnecting)&&this.emit(e.RoomEvent.Reconnecting)},this.handleSignalRestarted=t=>wi(this,void 0,void 0,(function*(){this.log.debug("signal reconnected to server, region ".concat(t.serverRegion),Object.assign(Object.assign({},this.logContext),{region:t.serverRegion})),this.bufferedEvents=[],this.applyJoinResponse(t);try{yield this.localParticipant.republishAllTracks(void 0,!0)}catch(e){this.log.error("error trying to re-publish tracks after reconnection",Object.assign(Object.assign({},this.logContext),{error:e}))}try{yield this.engine.waitForRestarted(),this.log.debug("fully reconnected to server",Object.assign(Object.assign({},this.logContext),{region:t.serverRegion}))}catch(e){return}this.setAndEmitConnectionState(e.ConnectionState.Connected),this.emit(e.RoomEvent.Reconnected),this.registerConnectionReconcile(),this.emitBufferedEvents()})),this.handleParticipantUpdates=e=>{e.forEach((e=>{var t;if(e.identity===this.localParticipant.identity)return void this.localParticipant.updateInfo(e);""===e.identity&&(e.identity=null!==(t=this.sidToIdentity.get(e.sid))&&void 0!==t?t:"");let n=this.remoteParticipants.get(e.identity);e.state===Qe.DISCONNECTED?this.handleParticipantDisconnected(e.identity,n):n=this.getOrCreateParticipant(e.identity,e)}))},this.handleActiveSpeakersUpdate=t=>{const n=[],i={};t.forEach((e=>{if(i[e.sid]=!0,e.sid===this.localParticipant.sid)this.localParticipant.audioLevel=e.level,this.localParticipant.setIsSpeaking(!0),n.push(this.localParticipant);else{const t=this.getRemoteParticipantBySid(e.sid);t&&(t.audioLevel=e.level,t.setIsSpeaking(!0),n.push(t))}})),i[this.localParticipant.sid]||(this.localParticipant.audioLevel=0,this.localParticipant.setIsSpeaking(!1)),this.remoteParticipants.forEach((e=>{i[e.sid]||(e.audioLevel=0,e.setIsSpeaking(!1))})),this.activeSpeakers=n,this.emitWhenConnected(e.RoomEvent.ActiveSpeakersChanged,n)},this.handleSpeakersChanged=t=>{const n=new Map;this.activeSpeakers.forEach((e=>{n.set(e.sid,e)})),t.forEach((e=>{let t=this.getRemoteParticipantBySid(e.sid);e.sid===this.localParticipant.sid&&(t=this.localParticipant),t&&(t.audioLevel=e.level,t.setIsSpeaking(e.active),e.active?n.set(e.sid,t):n.delete(e.sid))}));const i=Array.from(n.values());i.sort(((e,t)=>t.audioLevel-e.audioLevel)),this.activeSpeakers=i,this.emitWhenConnected(e.RoomEvent.ActiveSpeakersChanged,i)},this.handleStreamStateUpdate=t=>{t.streamStates.forEach((t=>{const n=this.getRemoteParticipantBySid(t.participantSid);if(!n)return;const i=n.getTrackPublicationBySid(t.trackSid);i&&i.track&&(i.track.streamState=jo.streamStateFromProto(t.state),n.emit(e.ParticipantEvent.TrackStreamStateChanged,i,i.track.streamState),this.emitWhenConnected(e.RoomEvent.TrackStreamStateChanged,i,i.track.streamState,n))}))},this.handleSubscriptionPermissionUpdate=e=>{const t=this.getRemoteParticipantBySid(e.participantSid);if(!t)return;const n=t.getTrackPublicationBySid(e.trackSid);n&&n.setAllowed(e.allowed)},this.handleSubscriptionError=e=>{const t=Array.from(this.remoteParticipants.values()).find((t=>t.trackPublications.has(e.trackSid)));if(!t)return;const n=t.getTrackPublicationBySid(e.trackSid);n&&n.setSubscriptionError(e.err)},this.handleDataPacket=(t,n)=>{const i=this.remoteParticipants.get(t.participantIdentity);this.emit(e.RoomEvent.DataReceived,t.payload,i,n,t.topic),null==i||i.emit(e.ParticipantEvent.DataReceived,t.payload,n)},this.handleAudioPlaybackStarted=()=>{this.canPlaybackAudio||(this.audioEnabled=!0,this.emit(e.RoomEvent.AudioPlaybackStatusChanged,!0))},this.handleAudioPlaybackFailed=t=>{this.log.warn("could not playback audio",Object.assign(Object.assign({},this.logContext),{error:t})),this.canPlaybackAudio&&(this.audioEnabled=!1,this.emit(e.RoomEvent.AudioPlaybackStatusChanged,!1))},this.handleVideoPlaybackStarted=()=>{this.isVideoPlaybackBlocked&&(this.isVideoPlaybackBlocked=!1,this.emit(e.RoomEvent.VideoPlaybackStatusChanged,!0))},this.handleVideoPlaybackFailed=()=>{this.isVideoPlaybackBlocked||(this.isVideoPlaybackBlocked=!0,this.emit(e.RoomEvent.VideoPlaybackStatusChanged,!1))},this.handleDeviceChange=()=>wi(this,void 0,void 0,(function*(){this.emit(e.RoomEvent.MediaDevicesChanged)})),this.handleRoomUpdate=t=>{const n=this.roomInfo;this.roomInfo=t,n&&n.metadata!==t.metadata&&this.emitWhenConnected(e.RoomEvent.RoomMetadataChanged,t.metadata),(null==n?void 0:n.activeRecording)!==t.activeRecording&&this.emitWhenConnected(e.RoomEvent.RecordingStatusChanged,t.activeRecording)},this.handleConnectionQualityUpdate=e=>{e.updates.forEach((e=>{if(e.participantSid===this.localParticipant.sid)return void this.localParticipant.setConnectionQuality(e.quality);const t=this.getRemoteParticipantBySid(e.participantSid);t&&t.setConnectionQuality(e.quality)}))},this.onLocalParticipantMetadataChanged=t=>{this.emit(e.RoomEvent.ParticipantMetadataChanged,t,this.localParticipant)},this.onLocalParticipantNameChanged=t=>{this.emit(e.RoomEvent.ParticipantNameChanged,t,this.localParticipant)},this.onLocalTrackMuted=t=>{this.emit(e.RoomEvent.TrackMuted,t,this.localParticipant)},this.onLocalTrackUnmuted=t=>{this.emit(e.RoomEvent.TrackUnmuted,t,this.localParticipant)},this.onTrackProcessorUpdate=e=>{var t;null===(t=null==e?void 0:e.onPublish)||void 0===t||t.call(e,this)},this.onLocalTrackPublished=t=>wi(this,void 0,void 0,(function*(){var n,i,s,o,a;if(null===(n=t.track)||void 0===n||n.on(e.TrackEvent.TrackProcessorUpdate,this.onTrackProcessorUpdate),null===(o=null===(s=null===(i=t.track)||void 0===i?void 0:i.getProcessor())||void 0===s?void 0:s.onPublish)||void 0===o||o.call(s,this),this.emit(e.RoomEvent.LocalTrackPublished,t,this.localParticipant),t.track instanceof Sr){(yield t.track.checkForSilence())&&this.emit(e.RoomEvent.LocalAudioSilenceDetected,t)}const r=yield null===(a=t.track)||void 0===a?void 0:a.getDeviceId(),c=(d=t.source)===jo.Source.Microphone?"audioinput":d===jo.Source.Camera?"videoinput":void 0;var d;c&&r&&r!==this.localParticipant.activeDeviceMap.get(c)&&(this.localParticipant.activeDeviceMap.set(c,r),this.emit(e.RoomEvent.ActiveDeviceChanged,c,r))})),this.onLocalTrackUnpublished=t=>{var n;null===(n=t.track)||void 0===n||n.off(e.TrackEvent.TrackProcessorUpdate,this.onTrackProcessorUpdate),this.emit(e.RoomEvent.LocalTrackUnpublished,t,this.localParticipant)},this.onLocalConnectionQualityChanged=t=>{this.emit(e.RoomEvent.ConnectionQualityChanged,t,this.localParticipant)},this.onMediaDevicesError=t=>{this.emit(e.RoomEvent.MediaDevicesError,t)},this.onLocalParticipantPermissionsChanged=t=>{this.emit(e.RoomEvent.ParticipantPermissionsChanged,t,this.localParticipant)},this.setMaxListeners(100),this.remoteParticipants=new Map,this.sidToIdentity=new Map,this.options=Object.assign(Object.assign({},lr),t),this.log=yi(null!==(i=this.options.loggerName)&&void 0!==i?i:e.LoggerNames.Room),this.options.audioCaptureDefaults=Object.assign(Object.assign({},cr),null==t?void 0:t.audioCaptureDefaults),this.options.videoCaptureDefaults=Object.assign(Object.assign({},dr),null==t?void 0:t.videoCaptureDefaults),this.options.publishDefaults=Object.assign(Object.assign({},rr),null==t?void 0:t.publishDefaults),this.maybeCreateEngine(),this.disconnectLock=new Ra,this.localParticipant=new Qr("","",this.engine,this.options),this.options.videoCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("videoinput",_a(this.options.videoCaptureDefaults.deviceId)),this.options.audioCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("audioinput",_a(this.options.audioCaptureDefaults.deviceId)),(null===(s=this.options.audioOutput)||void 0===s?void 0:s.deviceId)&&this.switchActiveDevice("audiooutput",_a(this.options.audioOutput.deviceId)).catch((e=>this.log.warn("Could not set audio output: ".concat(e.message),this.logContext))),this.options.e2ee&&this.setupE2EE()}setE2EEEnabled(e){return wi(this,void 0,void 0,(function*(){if(!this.e2eeManager)throw Error("e2ee not configured, please set e2ee settings within the room options");yield Promise.all([this.localParticipant.setE2EEEnabled(e)]),""!==this.localParticipant.identity&&this.e2eeManager.setParticipantCryptorEnabled(e,this.localParticipant.identity)}))}setupE2EE(){var t;this.options.e2ee&&(this.e2eeManager=new Da(this.options.e2ee),this.e2eeManager.on(e.EncryptionEvent.ParticipantEncryptionStatusChanged,((t,n)=>{n instanceof Qr&&(this.isE2EEEnabled=t),this.emit(e.RoomEvent.ParticipantEncryptionStatusChanged,t,n)})),this.e2eeManager.on(e.EncryptionEvent.EncryptionError,(t=>this.emit(e.RoomEvent.EncryptionError,t))),null===(t=this.e2eeManager)||void 0===t||t.setup(this))}get logContext(){var e;return{room:this.name,roomID:null===(e=this.roomInfo)||void 0===e?void 0:e.sid,participant:this.localParticipant.identity,pID:this.localParticipant.sid}}get isRecording(){var e,t;return null!==(t=null===(e=this.roomInfo)||void 0===e?void 0:e.activeRecording)&&void 0!==t&&t}getSid(){return wi(this,void 0,void 0,(function*(){return this.state===e.ConnectionState.Disconnected?"":this.roomInfo&&""!==this.roomInfo.sid?this.roomInfo.sid:new Promise(((t,n)=>{const i=n=>{""!==n.sid&&(this.engine.off(e.EngineEvent.RoomUpdate,i),t(n.sid))};this.engine.on(e.EngineEvent.RoomUpdate,i),this.once(e.RoomEvent.Disconnected,(()=>{this.engine.off(e.EngineEvent.RoomUpdate,i),n("Room disconnected before room server id was available")}))}))}))}get name(){var e,t;return null!==(t=null===(e=this.roomInfo)||void 0===e?void 0:e.name)&&void 0!==t?t:""}get metadata(){var e;return null===(e=this.roomInfo)||void 0===e?void 0:e.metadata}get numParticipants(){var e,t;return null!==(t=null===(e=this.roomInfo)||void 0===e?void 0:e.numParticipants)&&void 0!==t?t:0}get numPublishers(){var e,t;return null!==(t=null===(e=this.roomInfo)||void 0===e?void 0:e.numPublishers)&&void 0!==t?t:0}maybeCreateEngine(){this.engine&&!this.engine.isClosed||(this.engine=new kr(this.options),this.engine.on(e.EngineEvent.ParticipantUpdate,this.handleParticipantUpdates).on(e.EngineEvent.RoomUpdate,this.handleRoomUpdate).on(e.EngineEvent.SpeakersChanged,this.handleSpeakersChanged).on(e.EngineEvent.StreamStateChanged,this.handleStreamStateUpdate).on(e.EngineEvent.ConnectionQualityUpdate,this.handleConnectionQualityUpdate).on(e.EngineEvent.SubscriptionError,this.handleSubscriptionError).on(e.EngineEvent.SubscriptionPermissionUpdate,this.handleSubscriptionPermissionUpdate).on(e.EngineEvent.MediaTrackAdded,((e,t,n)=>{this.onTrackAdded(e,t,n)})).on(e.EngineEvent.Disconnected,(e=>{this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e)})).on(e.EngineEvent.ActiveSpeakersUpdate,this.handleActiveSpeakersUpdate).on(e.EngineEvent.DataPacketReceived,this.handleDataPacket).on(e.EngineEvent.Resuming,(()=>{this.clearConnectionReconcile(),this.isResuming=!0,this.log.info("Resuming signal connection",this.logContext)})).on(e.EngineEvent.Resumed,(()=>{this.registerConnectionReconcile(),this.isResuming=!1,this.log.info("Resumed signal connection",this.logContext),this.updateSubscriptions(),this.emitBufferedEvents()})).on(e.EngineEvent.SignalResumed,(()=>{this.bufferedEvents=[],(this.state===e.ConnectionState.Reconnecting||this.isResuming)&&this.sendSyncState()})).on(e.EngineEvent.Restarting,this.handleRestarting).on(e.EngineEvent.SignalRestarted,this.handleSignalRestarted).on(e.EngineEvent.Offline,(()=>{this.setAndEmitConnectionState(e.ConnectionState.Reconnecting)&&this.emit(e.RoomEvent.Reconnecting)})).on(e.EngineEvent.DCBufferStatusChanged,((t,n)=>{this.emit(e.RoomEvent.DCBufferStatusChanged,t,n)})),this.localParticipant&&this.localParticipant.setupEngine(this.engine),this.e2eeManager&&this.e2eeManager.setupEngine(this.engine))}static getLocalDevices(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return Ma.getInstance().getDevices(e,t)}prepareConnection(t,n){return wi(this,void 0,void 0,(function*(){if(this.state===e.ConnectionState.Disconnected){this.log.debug("prepareConnection to ".concat(t),this.logContext);try{if(ua(new URL(t))&&n){this.regionUrlProvider=new yr(t,n);const i=yield this.regionUrlProvider.getNextBestRegionUrl();i&&this.state===e.ConnectionState.Disconnected&&(this.regionUrl=i,yield fetch(Ia(i),{method:"HEAD"}),this.log.debug("prepared connection to ".concat(i),this.logContext))}else yield fetch(Ia(t),{method:"HEAD"})}catch(e){this.log.warn("could not prepare connection",Object.assign(Object.assign({},this.logContext),{error:e}))}}}))}getParticipantByIdentity(e){return this.localParticipant.identity===e?this.localParticipant:this.remoteParticipants.get(e)}clearConnectionFutures(){this.connectFuture=void 0}simulateScenario(e,t){return wi(this,void 0,void 0,(function*(){let n,i=()=>{};switch(e){case"signal-reconnect":yield this.engine.client.handleOnClose("simulate disconnect");break;case"speaker":n=new Kn({scenario:{case:"speakerUpdate",value:3}});break;case"node-failure":n=new Kn({scenario:{case:"nodeFailure",value:!0}});break;case"server-leave":n=new Kn({scenario:{case:"serverLeave",value:!0}});break;case"migration":n=new Kn({scenario:{case:"migration",value:!0}});break;case"resume-reconnect":this.engine.failNext(),yield this.engine.client.handleOnClose("simulate resume-disconnect");break;case"disconnect-signal-on-resume":i=()=>wi(this,void 0,void 0,(function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")})),n=new Kn({scenario:{case:"disconnectSignalOnResume",value:!0}});break;case"disconnect-signal-on-resume-no-messages":i=()=>wi(this,void 0,void 0,(function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")})),n=new Kn({scenario:{case:"disconnectSignalOnResumeNoMessages",value:!0}});break;case"full-reconnect":this.engine.fullReconnectOnNext=!0,yield this.engine.client.handleOnClose("simulate full-reconnect");break;case"force-tcp":case"force-tls":n=new Kn({scenario:{case:"switchCandidateProtocol",value:"force-tls"===e?2:1}}),i=()=>wi(this,void 0,void 0,(function*(){const e=this.engine.client.onLeave;e&&e(new En({reason:qe.CLIENT_INITIATED,canReconnect:!0}))}));break;case"subscriber-bandwidth":if(void 0===t||"number"!=typeof t)throw new Error("subscriber-bandwidth requires a number as argument");n=new Kn({scenario:{case:"subscriberBandwidth",value:BigInt(t)}})}n&&(yield this.engine.client.sendSimulateScenario(n),yield i())}))}get canPlaybackAudio(){return this.audioEnabled}get canPlaybackVideo(){return!this.isVideoPlaybackBlocked}getActiveDevice(e){return this.localParticipant.activeDeviceMap.get(e)}switchActiveDevice(t,n){let i=arguments.length>2&&void 0!==arguments[2]&&arguments[2];var s,o,a,r;return wi(this,void 0,void 0,(function*(){let c=!1,d=!0;const l=i?{exact:n}:n;if("audioinput"===t){const e=this.options.audioCaptureDefaults.deviceId;this.options.audioCaptureDefaults.deviceId=l,c=e!==l;const t=Array.from(this.localParticipant.audioTrackPublications.values()).filter((e=>e.source===jo.Source.Microphone));try{d=(yield Promise.all(t.map((e=>{var t;return null===(t=e.audioTrack)||void 0===t?void 0:t.setDeviceId(l)})))).every((e=>!0===e))}catch(t){throw this.options.audioCaptureDefaults.deviceId=e,t}}else if("videoinput"===t){const e=this.options.videoCaptureDefaults.deviceId;this.options.videoCaptureDefaults.deviceId=l,c=e!==l;const t=Array.from(this.localParticipant.videoTrackPublications.values()).filter((e=>e.source===jo.Source.Camera));try{d=(yield Promise.all(t.map((e=>{var t;return null===(t=e.videoTrack)||void 0===t?void 0:t.setDeviceId(l)})))).every((e=>!0===e))}catch(t){throw this.options.videoCaptureDefaults.deviceId=e,t}}else if("audiooutput"===t){if(!na()&&!this.options.webAudioMix||this.options.webAudioMix&&this.audioContext&&!("setSinkId"in this.audioContext))throw new Error("cannot switch audio output, setSinkId not supported");this.options.webAudioMix&&(n=null!==(s=yield Ma.getInstance().normalizeDeviceId("audiooutput",n))&&void 0!==s?s:""),null!==(o=(r=this.options).audioOutput)&&void 0!==o||(r.audioOutput={});const e=this.options.audioOutput.deviceId;this.options.audioOutput.deviceId=n,c=e!==l;try{this.options.webAudioMix?null===(a=this.audioContext)||void 0===a||a.setSinkId(n):yield Promise.all(Array.from(this.remoteParticipants.values()).map((e=>e.setAudioOutput({deviceId:n}))))}catch(t){throw this.options.audioOutput.deviceId=e,t}}return c&&d&&(this.localParticipant.activeDeviceMap.set(t,n),this.emit(e.RoomEvent.ActiveDeviceChanged,t,n)),d}))}setupLocalParticipantEvents(){this.localParticipant.on(e.ParticipantEvent.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).on(e.ParticipantEvent.ParticipantNameChanged,this.onLocalParticipantNameChanged).on(e.ParticipantEvent.TrackMuted,this.onLocalTrackMuted).on(e.ParticipantEvent.TrackUnmuted,this.onLocalTrackUnmuted).on(e.ParticipantEvent.LocalTrackPublished,this.onLocalTrackPublished).on(e.ParticipantEvent.LocalTrackUnpublished,this.onLocalTrackUnpublished).on(e.ParticipantEvent.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).on(e.ParticipantEvent.MediaDevicesError,this.onMediaDevicesError).on(e.ParticipantEvent.AudioStreamAcquired,this.startAudio).on(e.ParticipantEvent.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged)}recreateEngine(){var e;null===(e=this.engine)||void 0===e||e.close(),this.engine=void 0,this.isResuming=!1,this.remoteParticipants.clear(),this.sidToIdentity.clear(),this.bufferedEvents=[],this.maybeCreateEngine()}onTrackAdded(t,n,i){if(this.state===e.ConnectionState.Connecting||this.state===e.ConnectionState.Reconnecting){const s=()=>{this.onTrackAdded(t,n,i),o()},o=()=>{this.off(e.RoomEvent.Reconnected,s),this.off(e.RoomEvent.Connected,s),this.off(e.RoomEvent.Disconnected,o)};return this.once(e.RoomEvent.Reconnected,s),this.once(e.RoomEvent.Connected,s),void this.once(e.RoomEvent.Disconnected,o)}if(this.state===e.ConnectionState.Disconnected)return void this.log.warn("skipping incoming track after Room disconnected",this.logContext);const s=function(e){const t=e.split("|");return t.length>1?[t[0],e.substr(t[0].length+1)]:[e,""]}(n.id),o=s[0];let a=s[1],r=t.id;if(a&&a.startsWith("TR")&&(r=a),o===this.localParticipant.sid)return void this.log.warn("tried to create RemoteParticipant for local participant",this.logContext);const c=Array.from(this.remoteParticipants.values()).find((e=>e.sid===o));if(!c)return void this.log.error("Tried to add a track for a participant, that's not present. Sid: ".concat(o),this.logContext);let d;this.options.adaptiveStream&&(d="object"==typeof this.options.adaptiveStream?this.options.adaptiveStream:{}),c.addSubscribedMediaTrack(t,r,n,i,d)}handleDisconnect(){let t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0],n=arguments.length>1?arguments[1]:void 0;var i;if(this.clearConnectionReconcile(),this.isResuming=!1,this.bufferedEvents=[],this.state!==e.ConnectionState.Disconnected){this.regionUrl=void 0;try{this.remoteParticipants.forEach((e=>{e.trackPublications.forEach((t=>{e.unpublishTrack(t.trackSid)}))})),this.localParticipant.trackPublications.forEach((e=>{var n,i;e.track&&this.localParticipant.unpublishTrack(e.track,t),t&&(null===(n=e.track)||void 0===n||n.detach(),null===(i=e.track)||void 0===i||i.stop())})),this.localParticipant.off(e.ParticipantEvent.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).off(e.ParticipantEvent.ParticipantNameChanged,this.onLocalParticipantNameChanged).off(e.ParticipantEvent.TrackMuted,this.onLocalTrackMuted).off(e.ParticipantEvent.TrackUnmuted,this.onLocalTrackUnmuted).off(e.ParticipantEvent.LocalTrackPublished,this.onLocalTrackPublished).off(e.ParticipantEvent.LocalTrackUnpublished,this.onLocalTrackUnpublished).off(e.ParticipantEvent.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).off(e.ParticipantEvent.MediaDevicesError,this.onMediaDevicesError).off(e.ParticipantEvent.AudioStreamAcquired,this.startAudio).off(e.ParticipantEvent.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged),this.localParticipant.trackPublications.clear(),this.localParticipant.videoTrackPublications.clear(),this.localParticipant.audioTrackPublications.clear(),this.remoteParticipants.clear(),this.sidToIdentity.clear(),this.activeSpeakers=[],this.audioContext&&"boolean"==typeof this.options.webAudioMix&&(this.audioContext.close(),this.audioContext=void 0),da()&&(window.removeEventListener("beforeunload",this.onPageLeave),window.removeEventListener("pagehide",this.onPageLeave),window.removeEventListener("freeze",this.onPageLeave),null===(i=navigator.mediaDevices)||void 0===i||i.removeEventListener("devicechange",this.handleDeviceChange))}finally{this.setAndEmitConnectionState(e.ConnectionState.Disconnected),this.emit(e.RoomEvent.Disconnected,n)}}}handleParticipantDisconnected(t,n){this.remoteParticipants.delete(t),n&&(n.trackPublications.forEach((e=>{n.unpublishTrack(e.trackSid,!0)})),this.emit(e.RoomEvent.ParticipantDisconnected,n))}acquireAudioContext(){var t,n;return wi(this,void 0,void 0,(function*(){if("boolean"!=typeof this.options.webAudioMix&&this.options.webAudioMix.audioContext?this.audioContext=this.options.webAudioMix.audioContext:this.audioContext&&"closed"!==this.audioContext.state||(this.audioContext=null!==(t=Go())&&void 0!==t?t:void 0),this.audioContext&&"suspended"===this.audioContext.state)try{yield this.audioContext.resume()}catch(e){this.log.warn("Could not resume audio context",Object.assign(Object.assign({},this.logContext),{error:e}))}this.options.webAudioMix&&this.remoteParticipants.forEach((e=>e.setAudioContext(this.audioContext))),this.localParticipant.setAudioContext(this.audioContext);const i="running"===(null===(n=this.audioContext)||void 0===n?void 0:n.state);i!==this.canPlaybackAudio&&(this.audioEnabled=i,this.emit(e.RoomEvent.AudioPlaybackStatusChanged,i))}))}createParticipant(e,t){var n;let i;return i=t?Xr.fromParticipantInfo(this.engine.client,t):new Xr(this.engine.client,"",e,void 0,void 0,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}),this.options.webAudioMix&&i.setAudioContext(this.audioContext),(null===(n=this.options.audioOutput)||void 0===n?void 0:n.deviceId)&&i.setAudioOutput(this.options.audioOutput).catch((e=>this.log.warn("Could not set audio output: ".concat(e.message),this.logContext))),i}getOrCreateParticipant(t,n){if(this.remoteParticipants.has(t)){const e=this.remoteParticipants.get(t);if(n){e.updateInfo(n)&&this.sidToIdentity.set(n.sid,n.identity)}return e}const i=this.createParticipant(t,n);return this.remoteParticipants.set(t,i),this.sidToIdentity.set(n.sid,n.identity),this.emitWhenConnected(e.RoomEvent.ParticipantConnected,i),i.on(e.ParticipantEvent.TrackPublished,(t=>{this.emitWhenConnected(e.RoomEvent.TrackPublished,t,i)})).on(e.ParticipantEvent.TrackSubscribed,((t,n)=>{t.kind===jo.Kind.Audio?(t.on(e.TrackEvent.AudioPlaybackStarted,this.handleAudioPlaybackStarted),t.on(e.TrackEvent.AudioPlaybackFailed,this.handleAudioPlaybackFailed)):t.kind===jo.Kind.Video&&(t.on(e.TrackEvent.VideoPlaybackFailed,this.handleVideoPlaybackFailed),t.on(e.TrackEvent.VideoPlaybackStarted,this.handleVideoPlaybackStarted)),this.emit(e.RoomEvent.TrackSubscribed,t,n,i)})).on(e.ParticipantEvent.TrackUnpublished,(t=>{this.emit(e.RoomEvent.TrackUnpublished,t,i)})).on(e.ParticipantEvent.TrackUnsubscribed,((t,n)=>{this.emit(e.RoomEvent.TrackUnsubscribed,t,n,i)})).on(e.ParticipantEvent.TrackSubscriptionFailed,(t=>{this.emit(e.RoomEvent.TrackSubscriptionFailed,t,i)})).on(e.ParticipantEvent.TrackMuted,(t=>{this.emitWhenConnected(e.RoomEvent.TrackMuted,t,i)})).on(e.ParticipantEvent.TrackUnmuted,(t=>{this.emitWhenConnected(e.RoomEvent.TrackUnmuted,t,i)})).on(e.ParticipantEvent.ParticipantMetadataChanged,(t=>{this.emitWhenConnected(e.RoomEvent.ParticipantMetadataChanged,t,i)})).on(e.ParticipantEvent.ParticipantNameChanged,(t=>{this.emitWhenConnected(e.RoomEvent.ParticipantNameChanged,t,i)})).on(e.ParticipantEvent.ConnectionQualityChanged,(t=>{this.emitWhenConnected(e.RoomEvent.ConnectionQualityChanged,t,i)})).on(e.ParticipantEvent.ParticipantPermissionsChanged,(t=>{this.emitWhenConnected(e.RoomEvent.ParticipantPermissionsChanged,t,i)})).on(e.ParticipantEvent.TrackSubscriptionStatusChanged,((t,n)=>{this.emitWhenConnected(e.RoomEvent.TrackSubscriptionStatusChanged,t,n,i)})).on(e.ParticipantEvent.TrackSubscriptionFailed,((t,n)=>{this.emit(e.RoomEvent.TrackSubscriptionFailed,t,i,n)})).on(e.ParticipantEvent.TrackSubscriptionPermissionChanged,((t,n)=>{this.emitWhenConnected(e.RoomEvent.TrackSubscriptionPermissionChanged,t,n,i)})),n&&i.updateInfo(n),i}sendSyncState(){const e=Array.from(this.remoteParticipants.values()).reduce(((e,t)=>(e.push(...t.getTrackPublications()),e)),[]),t=this.localParticipant.getTrackPublications();this.engine.sendSyncState(e,t)}updateSubscriptions(){for(const e of this.remoteParticipants.values())for(const t of e.videoTrackPublications.values())t.isSubscribed&&t instanceof Yr&&t.emitTrackUpdate()}getRemoteParticipantBySid(e){const t=this.sidToIdentity.get(e);if(t)return this.remoteParticipants.get(t)}registerConnectionReconcile(){this.clearConnectionReconcile();let e=0;this.connectionReconcileInterval=_o.setInterval((()=>{this.engine&&!this.engine.isClosed&&this.engine.verifyTransport()?e=0:(e++,this.log.warn("detected connection state mismatch",Object.assign(Object.assign({},this.logContext),{numFailures:e,engine:{closed:this.engine.isClosed,transportsConnected:this.engine.verifyTransport()}})),e>=3&&(this.recreateEngine(),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,qe.STATE_MISMATCH)))}),2e3)}clearConnectionReconcile(){this.connectionReconcileInterval&&_o.clearInterval(this.connectionReconcileInterval)}setAndEmitConnectionState(t){return t!==this.state&&(this.state=t,this.emit(e.RoomEvent.ConnectionStateChanged,this.state),!0)}emitBufferedEvents(){this.bufferedEvents.forEach((e=>{let[t,n]=e;this.emit(t,...n)})),this.bufferedEvents=[]}emitWhenConnected(t){for(var n=arguments.length,i=new Array(n>1?n-1:0),s=1;s<n;s++)i[s-1]=arguments[s];if(this.state===e.ConnectionState.Reconnecting||this.isResuming||!this.engine||this.engine.pendingReconnect)this.bufferedEvents.push([t,i]);else if(this.state===e.ConnectionState.Connected)return this.emit(t,...i);return!1}simulateParticipants(t){var n,i;return wi(this,void 0,void 0,(function*(){const s=Object.assign({audio:!0,video:!0,useRealTracks:!1},t.publish),o=Object.assign({count:9,audio:!1,video:!0,aspectRatios:[1.66,1.7,1.3]},t.participants);if(this.handleDisconnect(),this.roomInfo=new We({sid:"RM_SIMULATED",name:"simulated-room",emptyTimeout:0,maxParticipants:0,creationTime:O.parse((new Date).getTime()),metadata:"",numParticipants:1,numPublishers:1,turnPassword:"",enabledCodecs:[],activeRecording:!1}),this.localParticipant.updateInfo(new ze({identity:"simulated-local",name:"local-name"})),this.setupLocalParticipantEvents(),this.emit(e.RoomEvent.SignalConnected),this.emit(e.RoomEvent.Connected),this.setAndEmitConnectionState(e.ConnectionState.Connected),s.video){const t=new Jr(jo.Kind.Video,new $e({source:je.CAMERA,sid:Math.floor(1e4*Math.random()).toString(),type:Ue.AUDIO,name:"video-dummy"}),new Ur(s.useRealTracks?(yield window.navigator.mediaDevices.getUserMedia({video:!0})).getVideoTracks()[0]:Ea(160*(null!==(n=o.aspectRatios[0])&&void 0!==n?n:1),160,!0,!0),void 0,!1,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(t),this.localParticipant.emit(e.ParticipantEvent.LocalTrackPublished,t)}if(s.audio){const t=new Jr(jo.Kind.Audio,new $e({source:je.MICROPHONE,sid:Math.floor(1e4*Math.random()).toString(),type:Ue.AUDIO}),new Sr(s.useRealTracks?(yield navigator.mediaDevices.getUserMedia({audio:!0})).getAudioTracks()[0]:wa(),void 0,!1,this.audioContext,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(t),this.localParticipant.emit(e.ParticipantEvent.LocalTrackPublished,t)}for(let e=0;e<o.count-1;e+=1){let t=new ze({sid:Math.floor(1e4*Math.random()).toString(),identity:"simulated-".concat(e),state:Qe.ACTIVE,tracks:[],joinedAt:O.parse(Date.now())});const n=this.getOrCreateParticipant(t.identity,t);if(o.video){const s=Ea(160*(null!==(i=o.aspectRatios[e%o.aspectRatios.length])&&void 0!==i?i:1),160,!1,!0),a=new $e({source:je.CAMERA,sid:Math.floor(1e4*Math.random()).toString(),type:Ue.AUDIO});n.addSubscribedMediaTrack(s,a.sid,new MediaStream([s])),t.tracks=[...t.tracks,a]}if(o.audio){const e=wa(),i=new $e({source:je.MICROPHONE,sid:Math.floor(1e4*Math.random()).toString(),type:Ue.AUDIO});n.addSubscribedMediaTrack(e,i.sid,new MediaStream([e])),t.tracks=[...t.tracks,i]}n.updateInfo(t)}}))}emit(t){for(var n=arguments.length,i=new Array(n>1?n-1:0),s=1;s<n;s++)i[s-1]=arguments[s];if(t!==e.RoomEvent.ActiveSpeakersChanged){const e=ec(i).filter((e=>void 0!==e));this.log.debug("room event ".concat(t),Object.assign(Object.assign({},this.logContext),{event:t,args:e}))}return super.emit(t,...i)}}function ec(e){return e.map((e=>{if(e)return Array.isArray(e)?ec(e):"object"==typeof e?"logContext"in e&&e.logContext:e}))}var tc;!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"}(tc||(tc={}));class nc extends Gi.EventEmitter{constructor(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};super(),this.status=tc.IDLE,this.logs=[],this.errorsAsWarnings=!1,this.url=e,this.token=t,this.name=this.constructor.name,this.room=new $r(n.roomOptions),this.connectOptions=n.connectOptions,n.errorsAsWarnings&&(this.errorsAsWarnings=n.errorsAsWarnings)}run(e){return wi(this,void 0,void 0,(function*(){if(this.status!==tc.IDLE)throw Error("check is running already");this.setStatus(tc.RUNNING);try{yield this.perform()}catch(e){e instanceof Error&&(this.errorsAsWarnings?this.appendWarning(e.message):this.appendError(e.message))}return yield this.disconnect(),yield new Promise((e=>setTimeout(e,500))),this.status!==tc.SKIPPED&&this.setStatus(this.isSuccess()?tc.SUCCESS:tc.FAILED),e&&e(),this.getInfo()}))}isSuccess(){return!this.logs.some((e=>"error"===e.level))}connect(){return wi(this,void 0,void 0,(function*(){return this.room.state===e.ConnectionState.Connected||(yield this.room.connect(this.url,this.token)),this.room}))}disconnect(){return wi(this,void 0,void 0,(function*(){this.room&&this.room.state!==e.ConnectionState.Disconnected&&(yield this.room.disconnect(),yield new Promise((e=>setTimeout(e,500))))}))}skip(){this.setStatus(tc.SKIPPED)}appendMessage(e){this.logs.push({level:"info",message:e}),this.emit("update",this.getInfo())}appendWarning(e){this.logs.push({level:"warning",message:e}),this.emit("update",this.getInfo())}appendError(e){this.logs.push({level:"error",message:e}),this.emit("update",this.getInfo())}setStatus(e){this.status=e,this.emit("update",this.getInfo())}get engine(){var e;return null===(e=this.room)||void 0===e?void 0:e.engine}getInfo(){return{logs:this.logs,name:this.name,status:this.status,description:this.description}}}function ic(e){var t,n;return wi(this,void 0,void 0,(function*(){null!=e||(e={}),null!==(t=e.audio)&&void 0!==t||(e.audio=!0),null!==(n=e.video)&&void 0!==n||(e.video=!0);const i=Ko(Vo(e,cr,dr)),s=navigator.mediaDevices.getUserMedia(i);e.audio&&(Ma.userMediaPromiseMap.set("audioinput",s),s.catch((()=>Ma.userMediaPromiseMap.delete("audioinput")))),e.video&&(Ma.userMediaPromiseMap.set("videoinput",s),s.catch((()=>Ma.userMediaPromiseMap.delete("videoinput"))));const o=yield s;return o.getTracks().map((t=>{const n="audio"===t.kind;let s;n?e.audio:e.video;const a=n?i.audio:i.video;"boolean"!=typeof a&&(s=a),s?s.deviceId=t.getSettings().deviceId:s={deviceId:t.getSettings().deviceId};const r=Er(t,s);return r.kind===jo.Kind.Video?r.source=jo.Source.Camera:r.kind===jo.Kind.Audio&&(r.source=jo.Source.Microphone),r.mediaStream=o,r}))}))}function sc(e){return wi(this,void 0,void 0,(function*(){return(yield ic({audio:!1,video:e}))[0]}))}function oc(e){return wi(this,void 0,void 0,(function*(){return(yield ic({audio:e,video:!1}))[0]}))}class ac extends nc{get description(){return"Can publish audio"}perform(){var e;return wi(this,void 0,void 0,(function*(){const t=yield this.connect(),n=yield oc();t.localParticipant.publishTrack(n),yield new Promise((e=>setTimeout(e,3e3)));const i=yield null===(e=n.sender)||void 0===e?void 0:e.getStats();if(!i)throw new Error("Could not get RTCStats");let s=0;if(i.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 rc extends nc{get description(){return"Can publish video"}perform(){var e;return wi(this,void 0,void 0,(function*(){const t=yield this.connect(),n=yield sc();t.localParticipant.publishTrack(n),yield new Promise((e=>setTimeout(e,3e3)));const i=yield null===(e=n.sender)||void 0===e?void 0:e.getStats();if(!i)throw new Error("Could not get RTCStats");let s=0;if(i.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 cc extends nc{get description(){return"Resuming connection after interruption"}perform(){var t;return wi(this,void 0,void 0,(function*(){const n=yield this.connect();let i,s=!1,o=!1;const a=new Promise((e=>{setTimeout(e,5e3),i=e}));n.on(e.RoomEvent.Reconnecting,(()=>{s=!0})).on(e.RoomEvent.Reconnected,(()=>{o=!0,i(!0)})),null===(t=n.engine.client.ws)||void 0===t||t.close();const r=n.engine.client.onClose;if(r&&r(""),yield a,!s)throw new Error("Did not attempt to reconnect");if(!o||n.state!==e.ConnectionState.Connected)throw this.appendWarning("reconnection is only possible in Redis-based configurations"),new Error("Not able to reconnect")}))}}class dc extends nc{get description(){return"Can connect via TURN"}perform(){var e,t;return wi(this,void 0,void 0,(function*(){const n=new ja,i=yield n.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3});let s=!1,o=!1,a=!1;for(let e of i.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."),yield n.close(),(null===(t=null===(e=this.connectOptions)||void 0===e?void 0:e.rtcConfig)||void 0===t?void 0:t.iceServers)||o?yield this.room.connect(this.url,this.token,{rtcConfig:{iceTransportPolicy:"relay"}}):(this.appendWarning("No TURN servers configured."),this.skip(),yield new Promise((e=>setTimeout(e,0))))}))}}class lc extends nc{get description(){return"Establishing WebRTC connection"}perform(){return wi(this,void 0,void 0,(function*(){let t=!1,n=!1;this.room.on(e.RoomEvent.SignalConnected,(()=>{const e=this.room.engine.client.onTrickle;this.room.engine.client.onTrickle=(i,s)=>{if(i.candidate){const e=new RTCIceCandidate(i);let s="".concat(e.protocol," ").concat(e.address,":").concat(e.port," ").concat(e.type);e.address&&(!function(e){const t=e.split(".");if(4===t.length){if("10"===t[0])return!0;if("192"===t[0]&&"168"===t[1])return!0;if("172"===t[0]){const e=parseInt(t[1],10);if(e>=16&&e<=31)return!0}}return!1}(e.address)?"tcp"===e.protocol&&"passive"===e.tcpType?(t=!0,s+=" (passive)"):"udp"===e.protocol&&(n=!0):s+=" (private)"),this.appendMessage(s)}e&&e(i,s)},this.room.engine.pcManager&&(this.room.engine.pcManager.subscriber.onIceCandidateError=e=>{e instanceof RTCPeerConnectionIceErrorEvent&&this.appendWarning("error with ICE candidate: ".concat(e.errorCode," ").concat(e.errorText," ").concat(e.url))})}));try{yield this.connect(),ki.info("now the room is connected")}catch(e){throw this.appendWarning("ports need to be open on firewall in order to connect."),e}t||this.appendWarning("Server is not configured for ICE/TCP"),n||this.appendWarning("No public IPv4 UDP candidates were found. Your server is likely not configured correctly")}))}}class uc extends nc{get description(){return"Connecting to signal connection via WebSocket"}perform(){var e,t,n;return wi(this,void 0,void 0,(function*(){(this.url.startsWith("ws:")||this.url.startsWith("http:"))&&this.appendWarning("Server is insecure, clients may block connections to it");let i=new ja;const s=yield i.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3});this.appendMessage("Connected to server, version ".concat(s.serverVersion,".")),(null===(e=s.serverInfo)||void 0===e?void 0:e.edition)===dt.Cloud&&(null===(t=s.serverInfo)||void 0===t?void 0:t.region)&&this.appendMessage("LiveKit Cloud: ".concat(null===(n=s.serverInfo)||void 0===n?void 0:n.region)),yield i.close()}))}}class hc extends Gi.EventEmitter{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:tc.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!==tc.FAILED))}getResults(){return Array.from(this.checkResults.values())}createAndRunCheck(e){return wi(this,void 0,void 0,(function*(){const t=this.getNextCheckId(),n=new e(this.url,this.token),i=e=>{this.updateCheck(t,e)};n.on("update",i);const s=yield n.run();return n.off("update",i),s}))}checkWebsocket(){return wi(this,void 0,void 0,(function*(){return this.createAndRunCheck(uc)}))}checkWebRTC(){return wi(this,void 0,void 0,(function*(){return this.createAndRunCheck(lc)}))}checkTURN(){return wi(this,void 0,void 0,(function*(){return this.createAndRunCheck(dc)}))}checkReconnect(){return wi(this,void 0,void 0,(function*(){return this.createAndRunCheck(cc)}))}checkPublishAudio(){return wi(this,void 0,void 0,(function*(){return this.createAndRunCheck(ac)}))}checkPublishVideo(){return wi(this,void 0,void 0,(function*(){return this.createAndRunCheck(rc)}))}}const mc=new Map([["obs virtual camera",{facingMode:"environment",confidence:"medium"}]]),pc=new Map([["iphone",{facingMode:"environment",confidence:"medium"}],["ipad",{facingMode:"environment",confidence:"medium"}]]);function gc(e){var t;const n=e.trim().toLowerCase();if(""!==n)return mc.has(n)?mc.get(n):null===(t=Array.from(pc.entries()).find((e=>{let[t]=e;return n.includes(t)})))||void 0===t?void 0:t[1]}e.BaseKeyProvider=ro,e.ConnectionCheck=hc,e.ConnectionError=lo,e.CriticalTimers=_o,e.DataPacket_Kind=nt,e.DefaultReconnectPolicy=Ei,e.DeviceUnsupportedError=uo,e.DisconnectReason=qe,e.ExternalE2EEKeyProvider=class extends ro{constructor(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};super(Object.assign(Object.assign({},e),{sharedKey:!0,ratchetWindowSize:0,failureTolerance:-1}))}setKey(e){return wi(this,void 0,void 0,(function*(){const t="string"==typeof e?yield so(e):yield oo(e);this.onSetEncryptionKey(t)}))}},e.LivekitError=co,e.LocalAudioTrack=Sr,e.LocalParticipant=Qr,e.LocalTrack=xa,e.LocalTrackPublication=Jr,e.LocalVideoTrack=Ur,e.NegotiationError=go,e.Participant=zr,e.PublishDataError=class extends co{constructor(e){super(13,null!=e?e:"unable to publish data")}},e.RemoteAudioTrack=qr,e.RemoteParticipant=Xr,e.RemoteTrack=Vr,e.RemoteTrackPublication=Yr,e.RemoteVideoTrack=Kr,e.Room=$r,e.ScreenSharePresets=Ao,e.Track=jo,e.TrackInvalidError=ho,e.TrackPublication=Hr,e.UnexpectedConnectionState=po,e.UnsupportedServer=mo,e.VideoPreset=Io,e.VideoPresets=No,e.VideoPresets43=Lo,e.attachToElement=Fo,e.createAudioAnalyser=function(e,t){const n=Object.assign({cloneTrack:!1,fftSize:2048,smoothingTimeConstant:.8,minDecibels:-100,maxDecibels:-80},t),i=Go();if(!i)throw new Error("Audio Context not supported on this browser");const s=n.cloneTrack?e.mediaStreamTrack.clone():e.mediaStreamTrack,o=i.createMediaStreamSource(new MediaStream([s])),a=i.createAnalyser();a.minDecibels=n.minDecibels,a.maxDecibels=n.maxDecibels,a.fftSize=n.fftSize,a.smoothingTimeConstant=n.smoothingTimeConstant,o.connect(a);const r=new Uint8Array(a.frequencyBinCount);return{calculateVolume:()=>{a.getByteFrequencyData(r);let e=0;for(const t of r)e+=Math.pow(t/255,2);return Math.sqrt(e/r.length)},analyser:a,cleanup:()=>wi(this,void 0,void 0,(function*(){yield i.close(),n.cloneTrack&&s.stop()}))}},e.createE2EEKey=function(){return window.crypto.getRandomValues(new Uint8Array(32))},e.createKeyMaterialFromBuffer=oo,e.createKeyMaterialFromString=so,e.createLocalAudioTrack=oc,e.createLocalScreenTracks=function(e){return wi(this,void 0,void 0,(function*(){if(void 0===e&&(e={}),void 0!==e.resolution||ra()||(e.resolution=Ao.h1080fps30.resolution),void 0===navigator.mediaDevices.getDisplayMedia)throw new uo("getDisplayMedia not supported");const t=Wo(e),n=yield navigator.mediaDevices.getDisplayMedia(t),i=n.getVideoTracks();if(0===i.length)throw new ho("no video track found");const s=new Ur(i[0],void 0,!1);s.source=jo.Source.ScreenShare;const o=[s];if(n.getAudioTracks().length>0){const e=new Sr(n.getAudioTracks()[0],void 0,!1);e.source=jo.Source.ScreenShareAudio,o.push(e)}return o}))},e.createLocalTracks=ic,e.createLocalVideoTrack=sc,e.deriveKeys=function(e,t){return wi(this,void 0,void 0,(function*(){const n=ao(e.algorithm.name,t),i=yield crypto.subtle.deriveKey(n,e,{name:Ys,length:128},!1,["encrypt","decrypt"]);return{material:e,encryptionKey:i}}))},e.detachTrack=Bo,e.facingModeFromDeviceLabel=gc,e.facingModeFromLocalTrack=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};var n;const i=e instanceof xa?e.mediaStreamTrack:e,s=i.getSettings();let o={facingMode:null!==(n=t.defaultFacingMode)&&void 0!==n?n:"user",confidence:"low"};if("facingMode"in s){const e=s.facingMode;ki.trace("rawFacingMode",{rawFacingMode:e}),e&&"string"==typeof e&&function(e){const t=["user","environment","left","right"];return void 0===e||t.includes(e)}(e)&&(o={facingMode:e,confidence:"high"})}if(["low","medium"].includes(o.confidence)){ki.trace("Try to get facing mode from device label: (".concat(i.label,")"));const e=gc(i.label);void 0!==e&&(o=e)}return o},e.getEmptyAudioStreamTrack=wa,e.getEmptyVideoStreamTrack=function(){return Ca||(Ca=Ea()),Ca.clone()},e.getLogger=yi,e.importKey=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{name:Ys},n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"encrypt";return wi(this,void 0,void 0,(function*(){return crypto.subtle.importKey("raw",e,t,!1,"derive"===n?["deriveBits","deriveKey"]:["encrypt","decrypt"])}))},e.isBackupCodec=xo,e.isBrowserSupported=sa,e.isE2EESupported=to,e.isInsertableStreamSupported=io,e.isScriptTransformSupported=no,e.isVideoFrame=function(e){return"type"in e},e.needsRbspUnescaping=function(e){for(var t=0;t<e.length-3;t++)if(0==e[t]&&0==e[t+1]&&3==e[t+2])return!0;return!1},e.parseRbsp=function(e){const t=[];for(var n=e.length,i=0;i<e.length;)n-i>=3&&!e[i]&&!e[i+1]&&3==e[i+2]?(t.push(e[i++]),t.push(e[i++]),i++):t.push(e[i++]);return new Uint8Array(t)},e.protocolVersion=12,e.ratchet=function(e,t){return wi(this,void 0,void 0,(function*(){const n=ao(e.algorithm.name,t);return crypto.subtle.deriveBits(n,e,256)}))},e.setLogExtension=function(t,n){(n?[n]:Ti).forEach((n=>{const i=n.methodFactory;n.methodFactory=(n,s,o)=>{const a=i(n,s,o),r=e.LogLevel[n],c=r>=s&&r<e.LogLevel.silent;return(e,n)=>{n?a(e,n):a(e),c&&t(r,e,n)}},n.setLevel(n.getLevel())}))},e.setLogLevel=function(e,t){t&&vi.getLogger(t).setLevel(e);for(const t of Ti)t.setLevel(e)},e.supportsAV1=$o,e.supportsAdaptiveStream=function(){return void 0!==typeof ResizeObserver&&void 0!==typeof IntersectionObserver},e.supportsDynacast=function(){return Xo()},e.supportsVP9=ea,e.version=Ro,e.videoCodecs=Mo,e.writeRbsp=function(e){const t=[];for(var n=0,i=0;i<e.length;++i){var s=e[i];s<=3&&n>=2&&(t.push(3),n=0),t.push(s),0==s?++n:n=0}return new Uint8Array(t)}}));
|
1
|
+
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).LivekitClient={})}(this,(function(e){"use strict";function t(e,t){return t.forEach((function(t){t&&"string"!=typeof t&&!Array.isArray(t)&&Object.keys(t).forEach((function(n){if("default"!==n&&!(n in e)){var i=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(e,n,i.get?i:{enumerable:!0,get:function(){return t[n]}})}}))})),Object.freeze(e)}function n(e,t){if(!e)throw new Error(t)}const i=34028234663852886e22,s=-34028234663852886e22,o=4294967295,a=2147483647,r=-2147483648;function c(e){if("number"!=typeof e)throw new Error("invalid int 32: "+typeof e);if(!Number.isInteger(e)||e>a||e<r)throw new Error("invalid int 32: "+e)}function d(e){if("number"!=typeof e)throw new Error("invalid uint 32: "+typeof e);if(!Number.isInteger(e)||e>o||e<0)throw new Error("invalid uint 32: "+e)}function l(e){if("number"!=typeof e)throw new Error("invalid float 32: "+typeof e);if(Number.isFinite(e)&&(e>i||e<s))throw new Error("invalid float 32: "+e)}const u=Symbol("@bufbuild/protobuf/enum-type");function h(e){const t=e[u];return n(t,"missing enum type on enum object"),t}function m(e,t,n,i){e[u]=p(t,n.map((t=>({no:t.no,name:t.name,localName:e[t.no]}))))}function p(e,t,n){const i=Object.create(null),s=Object.create(null),o=[];for(const e of t){const t=f(e);o.push(t),i[e.name]=t,s[e.no]=t}return{typeName:e,values:o,findName:e=>i[e],findNumber:e=>s[e]}}function g(e,t,n){const i={};for(const e of t){const t=f(e);i[t.localName]=t.no,i[t.no]=t.localName}return m(i,e,t),i}function f(e){return"localName"in e?e:Object.assign(Object.assign({},e),{localName:e.name})}class v{equals(e){return this.getType().runtime.util.equals(this.getType(),this,e)}clone(){return this.getType().runtime.util.clone(this)}fromBinary(e,t){const n=this.getType().runtime.bin,i=n.makeReadOptions(t);return n.readMessage(this,i.readerFactory(e),e.byteLength,i),this}fromJson(e,t){const n=this.getType(),i=n.runtime.json,s=i.makeReadOptions(t);return i.readMessage(n,e,s,this),this}fromJsonString(e,t){let n;try{n=JSON.parse(e)}catch(e){throw new Error("cannot decode ".concat(this.getType().typeName," from JSON: ").concat(e instanceof Error?e.message:String(e)))}return this.fromJson(n,t)}toBinary(e){const t=this.getType().runtime.bin,n=t.makeWriteOptions(e),i=n.writerFactory();return t.writeMessage(this,i,n),i.finish()}toJson(e){const t=this.getType().runtime.json,n=t.makeWriteOptions(e);return t.writeMessage(this,n)}toJsonString(e){var t;const n=this.toJson(e);return JSON.stringify(n,null,null!==(t=null==e?void 0:e.prettySpaces)&&void 0!==t?t:0)}toJSON(){return this.toJson({emitDefaultValues:!0})}getType(){return Object.getPrototypeOf(this).constructor}}var k,T;function y(){let e=0,t=0;for(let n=0;n<28;n+=7){let i=this.buf[this.pos++];if(e|=(127&i)<<n,0==(128&i))return this.assertBounds(),[e,t]}let n=this.buf[this.pos++];if(e|=(15&n)<<28,t=(112&n)>>4,0==(128&n))return this.assertBounds(),[e,t];for(let n=3;n<=31;n+=7){let i=this.buf[this.pos++];if(t|=(127&i)<<n,0==(128&i))return this.assertBounds(),[e,t]}throw new Error("invalid varint")}function b(e,t,n){for(let i=0;i<28;i+=7){const s=e>>>i,o=!(s>>>7==0&&0==t),a=255&(o?128|s:s);if(n.push(a),!o)return}const i=e>>>28&15|(7&t)<<4,s=!(t>>3==0);if(n.push(255&(s?128|i:i)),s){for(let e=3;e<31;e+=7){const i=t>>>e,s=!(i>>>7==0),o=255&(s?128|i:i);if(n.push(o),!s)return}n.push(t>>>31&1)}}!function(e){e[e.DOUBLE=1]="DOUBLE",e[e.FLOAT=2]="FLOAT",e[e.INT64=3]="INT64",e[e.UINT64=4]="UINT64",e[e.INT32=5]="INT32",e[e.FIXED64=6]="FIXED64",e[e.FIXED32=7]="FIXED32",e[e.BOOL=8]="BOOL",e[e.STRING=9]="STRING",e[e.BYTES=12]="BYTES",e[e.UINT32=13]="UINT32",e[e.SFIXED32=15]="SFIXED32",e[e.SFIXED64=16]="SFIXED64",e[e.SINT32=17]="SINT32",e[e.SINT64=18]="SINT64"}(k||(k={})),function(e){e[e.BIGINT=0]="BIGINT",e[e.STRING=1]="STRING"}(T||(T={}));const C=4294967296;function S(e){const t="-"===e[0];t&&(e=e.slice(1));const n=1e6;let i=0,s=0;function o(t,o){const a=Number(e.slice(t,o));s*=n,i=i*n+a,i>=C&&(s+=i/C|0,i%=C)}return o(-24,-18),o(-18,-12),o(-12,-6),o(-6),t?P(i,s):w(i,s)}function E(e,t){if(({lo:e,hi:t}=function(e,t){return{lo:e>>>0,hi:t>>>0}}(e,t)),t<=2097151)return String(C*t+e);const n=16777215&(e>>>24|t<<8),i=t>>16&65535;let s=(16777215&e)+6777216*n+6710656*i,o=n+8147497*i,a=2*i;const r=1e7;return s>=r&&(o+=Math.floor(s/r),s%=r),o>=r&&(a+=Math.floor(o/r),o%=r),a.toString()+R(o)+R(s)}function w(e,t){return{lo:0|e,hi:0|t}}function P(e,t){return t=~t,e?e=1+~e:t+=1,w(e,t)}const R=e=>{const t=String(e);return"0000000".slice(t.length)+t};function _(e,t){if(e>=0){for(;e>127;)t.push(127&e|128),e>>>=7;t.push(e)}else{for(let n=0;n<9;n++)t.push(127&e|128),e>>=7;t.push(1)}}function I(){let e=this.buf[this.pos++],t=127&e;if(0==(128&e))return this.assertBounds(),t;if(e=this.buf[this.pos++],t|=(127&e)<<7,0==(128&e))return this.assertBounds(),t;if(e=this.buf[this.pos++],t|=(127&e)<<14,0==(128&e))return this.assertBounds(),t;if(e=this.buf[this.pos++],t|=(127&e)<<21,0==(128&e))return this.assertBounds(),t;e=this.buf[this.pos++],t|=(15&e)<<28;for(let t=5;0!=(128&e)&&t<10;t++)e=this.buf[this.pos++];if(0!=(128&e))throw new Error("invalid varint");return this.assertBounds(),t>>>0}const O=function(){const e=new DataView(new ArrayBuffer(8));if("function"==typeof BigInt&&"function"==typeof e.getBigInt64&&"function"==typeof e.getBigUint64&&"function"==typeof e.setBigInt64&&"function"==typeof e.setBigUint64&&("object"!=typeof process||"object"!=typeof process.env||"1"!==process.env.BUF_BIGINT_DISABLE)){const t=BigInt("-9223372036854775808"),n=BigInt("9223372036854775807"),i=BigInt("0"),s=BigInt("18446744073709551615");return{zero:BigInt(0),supported:!0,parse(e){const i="bigint"==typeof e?e:BigInt(e);if(i>n||i<t)throw new Error("int64 invalid: ".concat(e));return i},uParse(e){const t="bigint"==typeof e?e:BigInt(e);if(t>s||t<i)throw new Error("uint64 invalid: ".concat(e));return t},enc(t){return e.setBigInt64(0,this.parse(t),!0),{lo:e.getInt32(0,!0),hi:e.getInt32(4,!0)}},uEnc(t){return e.setBigInt64(0,this.uParse(t),!0),{lo:e.getInt32(0,!0),hi:e.getInt32(4,!0)}},dec:(t,n)=>(e.setInt32(0,t,!0),e.setInt32(4,n,!0),e.getBigInt64(0,!0)),uDec:(t,n)=>(e.setInt32(0,t,!0),e.setInt32(4,n,!0),e.getBigUint64(0,!0))}}const t=e=>n(/^-?[0-9]+$/.test(e),"int64 invalid: ".concat(e)),i=e=>n(/^[0-9]+$/.test(e),"uint64 invalid: ".concat(e));return{zero:"0",supported:!1,parse:e=>("string"!=typeof e&&(e=e.toString()),t(e),e),uParse:e=>("string"!=typeof e&&(e=e.toString()),i(e),e),enc:e=>("string"!=typeof e&&(e=e.toString()),t(e),S(e)),uEnc:e=>("string"!=typeof e&&(e=e.toString()),i(e),S(e)),dec:(e,t)=>function(e,t){let n=w(e,t);const i=2147483648&n.hi;i&&(n=P(n.lo,n.hi));const s=E(n.lo,n.hi);return i?"-"+s:s}(e,t),uDec:(e,t)=>E(e,t)}}();var M;!function(e){e[e.Varint=0]="Varint",e[e.Bit64=1]="Bit64",e[e.LengthDelimited=2]="LengthDelimited",e[e.StartGroup=3]="StartGroup",e[e.EndGroup=4]="EndGroup",e[e.Bit32=5]="Bit32"}(M||(M={}));class x{constructor(e){this.stack=[],this.textEncoder=null!=e?e:new TextEncoder,this.chunks=[],this.buf=[]}finish(){this.chunks.push(new Uint8Array(this.buf));let e=0;for(let t=0;t<this.chunks.length;t++)e+=this.chunks[t].length;let t=new Uint8Array(e),n=0;for(let e=0;e<this.chunks.length;e++)t.set(this.chunks[e],n),n+=this.chunks[e].length;return this.chunks=[],t}fork(){return this.stack.push({chunks:this.chunks,buf:this.buf}),this.chunks=[],this.buf=[],this}join(){let e=this.finish(),t=this.stack.pop();if(!t)throw new Error("invalid state, fork stack empty");return this.chunks=t.chunks,this.buf=t.buf,this.uint32(e.byteLength),this.raw(e)}tag(e,t){return this.uint32((e<<3|t)>>>0)}raw(e){return this.buf.length&&(this.chunks.push(new Uint8Array(this.buf)),this.buf=[]),this.chunks.push(e),this}uint32(e){for(d(e);e>127;)this.buf.push(127&e|128),e>>>=7;return this.buf.push(e),this}int32(e){return c(e),_(e,this.buf),this}bool(e){return this.buf.push(e?1:0),this}bytes(e){return this.uint32(e.byteLength),this.raw(e)}string(e){let t=this.textEncoder.encode(e);return this.uint32(t.byteLength),this.raw(t)}float(e){l(e);let t=new Uint8Array(4);return new DataView(t.buffer).setFloat32(0,e,!0),this.raw(t)}double(e){let t=new Uint8Array(8);return new DataView(t.buffer).setFloat64(0,e,!0),this.raw(t)}fixed32(e){d(e);let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!0),this.raw(t)}sfixed32(e){c(e);let t=new Uint8Array(4);return new DataView(t.buffer).setInt32(0,e,!0),this.raw(t)}sint32(e){return c(e),_(e=(e<<1^e>>31)>>>0,this.buf),this}sfixed64(e){let t=new Uint8Array(8),n=new DataView(t.buffer),i=O.enc(e);return n.setInt32(0,i.lo,!0),n.setInt32(4,i.hi,!0),this.raw(t)}fixed64(e){let t=new Uint8Array(8),n=new DataView(t.buffer),i=O.uEnc(e);return n.setInt32(0,i.lo,!0),n.setInt32(4,i.hi,!0),this.raw(t)}int64(e){let t=O.enc(e);return b(t.lo,t.hi,this.buf),this}sint64(e){let t=O.enc(e),n=t.hi>>31;return b(t.lo<<1^n,(t.hi<<1|t.lo>>>31)^n,this.buf),this}uint64(e){let t=O.uEnc(e);return b(t.lo,t.hi,this.buf),this}}class D{constructor(e,t){this.varint64=y,this.uint32=I,this.buf=e,this.len=e.length,this.pos=0,this.view=new DataView(e.buffer,e.byteOffset,e.byteLength),this.textDecoder=null!=t?t:new TextDecoder}tag(){let e=this.uint32(),t=e>>>3,n=7&e;if(t<=0||n<0||n>5)throw new Error("illegal tag: field no "+t+" wire type "+n);return[t,n]}skip(e){let t=this.pos;switch(e){case M.Varint:for(;128&this.buf[this.pos++];);break;case M.Bit64:this.pos+=4;case M.Bit32:this.pos+=4;break;case M.LengthDelimited:let t=this.uint32();this.pos+=t;break;case M.StartGroup:let n;for(;(n=this.tag()[1])!==M.EndGroup;)this.skip(n);break;default:throw new Error("cant skip wire type "+e)}return this.assertBounds(),this.buf.subarray(t,this.pos)}assertBounds(){if(this.pos>this.len)throw new RangeError("premature EOF")}int32(){return 0|this.uint32()}sint32(){let e=this.uint32();return e>>>1^-(1&e)}int64(){return O.dec(...this.varint64())}uint64(){return O.uDec(...this.varint64())}sint64(){let[e,t]=this.varint64(),n=-(1&e);return e=(e>>>1|(1&t)<<31)^n,t=t>>>1^n,O.dec(e,t)}bool(){let[e,t]=this.varint64();return 0!==e||0!==t}fixed32(){return this.view.getUint32((this.pos+=4)-4,!0)}sfixed32(){return this.view.getInt32((this.pos+=4)-4,!0)}fixed64(){return O.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return O.dec(this.sfixed32(),this.sfixed32())}float(){return this.view.getFloat32((this.pos+=4)-4,!0)}double(){return this.view.getFloat64((this.pos+=8)-8,!0)}bytes(){let e=this.uint32(),t=this.pos;return this.pos+=e,this.assertBounds(),this.buf.subarray(t,t+e)}string(){return this.textDecoder.decode(this.bytes())}}function N(e,t,n){if(t===n)return!0;if(e==k.BYTES){if(!(t instanceof Uint8Array&&n instanceof Uint8Array))return!1;if(t.length!==n.length)return!1;for(let e=0;e<t.length;e++)if(t[e]!==n[e])return!1;return!0}switch(e){case k.UINT64:case k.FIXED64:case k.INT64:case k.SFIXED64:case k.SINT64:return t==n}return!1}function L(e,t){switch(e){case k.BOOL:return!1;case k.UINT64:case k.FIXED64:case k.INT64:case k.SFIXED64:case k.SINT64:return 0==t?O.zero:"0";case k.DOUBLE:case k.FLOAT:return 0;case k.BYTES:return new Uint8Array(0);case k.STRING:return"";default:return 0}}function A(e,t){const n=void 0===t;let i=M.Varint,s=0===t;switch(e){case k.STRING:s=n||!t.length,i=M.LengthDelimited;break;case k.BOOL:s=!1===t;break;case k.DOUBLE:i=M.Bit64;break;case k.FLOAT:i=M.Bit32;break;case k.INT64:case k.UINT64:s=n||0==t;break;case k.FIXED64:s=n||0==t,i=M.Bit64;break;case k.BYTES:s=n||!t.byteLength,i=M.LengthDelimited;break;case k.FIXED32:case k.SFIXED32:i=M.Bit32;break;case k.SFIXED64:s=n||0==t,i=M.Bit64;break;case k.SINT64:s=n||0==t}return[i,k[e].toLowerCase(),n||s]}function U(e){const t=e.field.localName,n=Object.create(null);return n[t]=function(e){const t=e.field;if(t.repeated)return[];if(void 0!==t.default)return t.default;switch(t.kind){case"enum":return t.T.values[0].no;case"scalar":return L(t.T,t.L);case"message":const e=t.T,n=new e;return e.fieldWrapper?e.fieldWrapper.unwrapField(n):n;case"map":throw"map fields are not allowed to be extensions"}}(e),[n,()=>n[t]]}function j(e,t){return t instanceof v||!e.fieldWrapper?t:e.fieldWrapper.wrapField(t)}k.DOUBLE,k.FLOAT,k.INT64,k.UINT64,k.INT32,k.UINT32,k.BOOL,k.STRING,k.BYTES;const F=Symbol("@bufbuild/protobuf/unknown-fields"),B={readUnknownFields:!0,readerFactory:e=>new D(e)},V={writeUnknownFields:!0,writerFactory:()=>new x};function q(e){return e?Object.assign(Object.assign({},B),e):B}function K(e){return e?Object.assign(Object.assign({},V),e):V}function G(e,t,n,i,s){let{repeated:o,localName:a}=n;switch(n.oneof&&((e=e[n.oneof.localName]).case!=a&&delete e.value,e.case=a,a="value"),n.kind){case"scalar":case"enum":const r="enum"==n.kind?k.INT32:n.T;let c=J;if("scalar"==n.kind&&n.L>0&&(c=H),o){let n=e[a];if(i==M.LengthDelimited&&r!=k.STRING&&r!=k.BYTES){let e=t.uint32()+t.pos;for(;t.pos<e;)n.push(c(t,r))}else n.push(c(t,r))}else e[a]=c(t,r);break;case"message":const d=n.T;o?e[a].push(W(t,new d,s,n)):e[a]instanceof v?W(t,e[a],s,n):(e[a]=W(t,new d,s,n),!d.fieldWrapper||n.oneof||n.repeated||(e[a]=d.fieldWrapper.unwrapField(e[a])));break;case"map":let[l,u]=function(e,t,n){const i=t.uint32(),s=t.pos+i;let o,a;for(;t.pos<s;){let[i]=t.tag();switch(i){case 1:o=J(t,e.K);break;case 2:switch(e.V.kind){case"scalar":a=J(t,e.V.T);break;case"enum":a=t.int32();break;case"message":a=W(t,new e.V.T,n,void 0)}}}if(void 0===o){let t=L(e.K,T.BIGINT);o=e.K==k.BOOL?t.toString():t}"string"!=typeof o&&"number"!=typeof o&&(o=o.toString());if(void 0===a)switch(e.V.kind){case"scalar":a=L(e.V.T,T.BIGINT);break;case"enum":a=0;break;case"message":a=new e.V.T}return[o,a]}(n,t,s);e[a][l]=u}}function W(e,t,n,i){const s=t.getType().runtime.bin,o=null==i?void 0:i.delimited;return s.readMessage(t,e,o?null==i?void 0:i.no:e.uint32(),n,o),t}function H(e,t){const n=J(e,t);return"bigint"==typeof n?n.toString():n}function J(e,t){switch(t){case k.STRING:return e.string();case k.BOOL:return e.bool();case k.DOUBLE:return e.double();case k.FLOAT:return e.float();case k.INT32:return e.int32();case k.INT64:return e.int64();case k.UINT64:return e.uint64();case k.FIXED64:return e.fixed64();case k.BYTES:return e.bytes();case k.FIXED32:return e.fixed32();case k.SFIXED32:return e.sfixed32();case k.SFIXED64:return e.sfixed64();case k.SINT64:return e.sint64();case k.UINT32:return e.uint32();case k.SINT32:return e.sint32()}}function z(e,t,i,s,o){e.tag(i.no,M.LengthDelimited),e.fork();let a=s;switch(i.K){case k.INT32:case k.FIXED32:case k.UINT32:case k.SFIXED32:case k.SINT32:a=Number.parseInt(s);break;case k.BOOL:n("true"==s||"false"==s),a="true"==s}switch(Y(e,i.K,1,a,!0),i.V.kind){case"scalar":Y(e,i.V.T,2,o,!0);break;case"enum":Y(e,k.INT32,2,o,!0);break;case"message":e.tag(2,M.LengthDelimited).bytes(o.toBinary(t))}e.join()}function Q(e,t,n,i){const s=j(n.T,i);(null==n?void 0:n.delimited)?e.tag(n.no,M.StartGroup).raw(s.toBinary(t)).tag(n.no,M.EndGroup):e.tag(n.no,M.LengthDelimited).bytes(s.toBinary(t))}function Y(e,t,n,i,s){let[o,a,r]=A(t,i);r&&!s||e.tag(n,o)[a](i)}function X(e,t,n,i){const s=e.repeated;switch(e.kind){case"scalar":case"enum":let o="enum"==e.kind?k.INT32:e.T;if(s)if(e.packed)!function(e,t,n,i){if(!i.length)return;e.tag(n,M.LengthDelimited).fork();let[,s]=A(t);for(let t=0;t<i.length;t++)e[s](i[t]);e.join()}(n,o,e.no,t);else for(const i of t)Y(n,o,e.no,i,!0);else void 0!==t&&Y(n,o,e.no,t,!!e.oneof||e.opt);break;case"message":if(s)for(const s of t)Q(n,i,e,s);else void 0!==t&&Q(n,i,e,t);break;case"map":for(const[s,o]of Object.entries(t))z(n,i,e,s,o)}}let Z="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),$=[];for(let e=0;e<Z.length;e++)$[Z[e].charCodeAt(0)]=e;$["-".charCodeAt(0)]=Z.indexOf("+"),$["_".charCodeAt(0)]=Z.indexOf("/");const ee={dec(e){let t=3*e.length/4;"="==e[e.length-2]?t-=2:"="==e[e.length-1]&&(t-=1);let n,i=new Uint8Array(t),s=0,o=0,a=0;for(let t=0;t<e.length;t++){if(n=$[e.charCodeAt(t)],void 0===n)switch(e[t]){case"=":o=0;case"\n":case"\r":case"\t":case" ":continue;default:throw Error("invalid base64 string.")}switch(o){case 0:a=n,o=1;break;case 1:i[s++]=a<<2|(48&n)>>4,a=n,o=2;break;case 2:i[s++]=(15&a)<<4|(60&n)>>2,a=n,o=3;break;case 3:i[s++]=(3&a)<<6|n,o=0}}if(1==o)throw Error("invalid base64 string.");return i.subarray(0,s)},enc(e){let t,n="",i=0,s=0;for(let o=0;o<e.length;o++)switch(t=e[o],i){case 0:n+=Z[t>>2],s=(3&t)<<4,i=1;break;case 1:n+=Z[s|t>>4],s=(15&t)<<2,i=2;break;case 2:n+=Z[s|t>>6],n+=Z[63&t],i=0}return i&&(n+=Z[s],n+="=",1==i&&(n+="=")),n}};function te(e,t,n){se(t,e);const i=t.runtime.bin.makeReadOptions(n),s=function(e,t){if(!t.repeated&&("enum"==t.kind||"scalar"==t.kind)){for(let n=e.length-1;n>=0;--n)if(e[n].no==t.no)return[e[n]];return[]}return e.filter((e=>e.no===t.no))}(e.getType().runtime.bin.listUnknownFields(e),t.field),[o,a]=U(t);for(const e of s)t.runtime.bin.readField(o,i.readerFactory(e.data),t.field,e.wireType,i);return a()}function ne(e,t,n,i){se(t,e);const s=t.runtime.bin.makeReadOptions(i),o=t.runtime.bin.makeWriteOptions(i);if(ie(e,t)){const n=e.getType().runtime.bin.listUnknownFields(e).filter((e=>e.no!=t.field.no));e.getType().runtime.bin.discardUnknownFields(e);for(const t of n)e.getType().runtime.bin.onUnknownField(e,t.no,t.wireType,t.data)}const a=o.writerFactory();let r=t.field;r.opt||r.repeated||"enum"!=r.kind&&"scalar"!=r.kind||(r=Object.assign(Object.assign({},t.field),{opt:!0})),t.runtime.bin.writeField(r,n,a,o);const c=s.readerFactory(a.finish());for(;c.pos<c.len;){const[t,n]=c.tag(),i=c.skip(n);e.getType().runtime.bin.onUnknownField(e,t,n,i)}}function ie(e,t){const n=e.getType();return t.extendee.typeName===n.typeName&&!!n.runtime.bin.listUnknownFields(e).find((e=>e.no==t.field.no))}function se(e,t){n(e.extendee.typeName==t.getType().typeName,"extension ".concat(e.typeName," can only be applied to message ").concat(e.extendee.typeName))}const oe={ignoreUnknownFields:!1},ae={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0};function re(e){return e?Object.assign(Object.assign({},oe),e):oe}function ce(e){return e?Object.assign(Object.assign({},ae),e):ae}function de(e){if(null===e)return"null";switch(typeof e){case"object":return Array.isArray(e)?"array":"object";case"string":return e.length>100?"string":'"'.concat(e.split('"').join('\\"'),'"');default:return String(e)}}function le(e,t,n,i,s,o){let a=n.localName;if(n.oneof){if(null===t&&"scalar"==n.kind)return;e=e[n.oneof.localName]={case:a},a="value"}if(n.repeated){if(null===t)return;if(!Array.isArray(t))throw new Error("cannot decode field ".concat(s.typeName,".").concat(n.name," from JSON: ").concat(de(t)));const o=e[a];for(const e of t){if(null===e)throw new Error("cannot decode field ".concat(s.typeName,".").concat(n.name," from JSON: ").concat(de(e)));let t;switch(n.kind){case"message":t=n.T.fromJson(e,i);break;case"enum":if(t=he(n.T,e,i.ignoreUnknownFields,!0),void 0===t)continue;break;case"scalar":try{t=ue(n.T,e,n.L,!0)}catch(t){let i="cannot decode field ".concat(s.typeName,".").concat(n.name," from JSON: ").concat(de(e));throw t instanceof Error&&t.message.length>0&&(i+=": ".concat(t.message)),new Error(i)}}o.push(t)}}else if("map"==n.kind){if(null===t)return;if("object"!=typeof t||Array.isArray(t))throw new Error("cannot decode field ".concat(s.typeName,".").concat(n.name," from JSON: ").concat(de(t)));const o=e[a];for(const[e,a]of Object.entries(t)){if(null===a)throw new Error("cannot decode field ".concat(s.typeName,".").concat(n.name," from JSON: map value null"));let r;switch(n.V.kind){case"message":r=n.V.T.fromJson(a,i);break;case"enum":if(r=he(n.V.T,a,i.ignoreUnknownFields,!0),void 0===r)continue;break;case"scalar":try{r=ue(n.V.T,a,T.BIGINT,!0)}catch(e){let i="cannot decode map value for field ".concat(s.typeName,".").concat(n.name," from JSON: ").concat(de(t));throw e instanceof Error&&e.message.length>0&&(i+=": ".concat(e.message)),new Error(i)}}try{o[ue(n.K,n.K==k.BOOL?"true"==e||"false"!=e&&e:e,T.BIGINT,!0).toString()]=r}catch(e){let i="cannot decode map key for field ".concat(s.typeName,".").concat(n.name," from JSON: ").concat(de(t));throw e instanceof Error&&e.message.length>0&&(i+=": ".concat(e.message)),new Error(i)}}}else switch(n.kind){case"message":const r=n.T;if(null===t&&"google.protobuf.Value"!=r.typeName){if(n.oneof)throw new Error("cannot decode field ".concat(s.typeName,".").concat(n.name," from JSON: null is invalid for oneof field"));return}e[a]instanceof v?e[a].fromJson(t,i):(e[a]=r.fromJson(t,i),r.fieldWrapper&&!n.oneof&&(e[a]=r.fieldWrapper.unwrapField(e[a])));break;case"enum":const c=he(n.T,t,i.ignoreUnknownFields,o);void 0!==c&&(e[a]=c);break;case"scalar":try{e[a]=ue(n.T,t,n.L,o)}catch(e){let i="cannot decode field ".concat(s.typeName,".").concat(n.name," from JSON: ").concat(de(t));throw e instanceof Error&&e.message.length>0&&(i+=": ".concat(e.message)),new Error(i)}}}function ue(e,t,n,i){switch(e){case k.DOUBLE:case k.FLOAT:if(null===t)return i?0:void 0;if("NaN"===t)return Number.NaN;if("Infinity"===t)return Number.POSITIVE_INFINITY;if("-Infinity"===t)return Number.NEGATIVE_INFINITY;if(""===t)break;if("string"==typeof t&&t.trim().length!==t.length)break;if("string"!=typeof t&&"number"!=typeof t)break;const s=Number(t);if(Number.isNaN(s))break;if(!Number.isFinite(s))break;return e==k.FLOAT&&l(s),s;case k.INT32:case k.FIXED32:case k.SFIXED32:case k.SINT32:case k.UINT32:if(null===t)return i?0:void 0;let o;if("number"==typeof t?o=t:"string"==typeof t&&t.length>0&&t.trim().length===t.length&&(o=Number(t)),void 0===o)break;return e==k.UINT32?d(o):c(o),o;case k.INT64:case k.SFIXED64:case k.SINT64:if(null===t)return i?O.zero:void 0;if("number"!=typeof t&&"string"!=typeof t)break;const a=O.parse(t);return n?a.toString():a;case k.FIXED64:case k.UINT64:if(null===t)return i?O.zero:void 0;if("number"!=typeof t&&"string"!=typeof t)break;const r=O.uParse(t);return n?r.toString():r;case k.BOOL:if(null===t)return!i&&void 0;if("boolean"!=typeof t)break;return t;case k.STRING:if(null===t)return i?"":void 0;if("string"!=typeof t)break;try{encodeURIComponent(t)}catch(e){throw new Error("invalid UTF8")}return t;case k.BYTES:if(null===t)return i?new Uint8Array(0):void 0;if(""===t)return new Uint8Array(0);if("string"!=typeof t)break;return ee.dec(t)}throw new Error}function he(e,t,n,i){if(null===t)return i?e.values[0].no:void 0;switch(typeof t){case"number":if(Number.isInteger(t))return t;break;case"string":const i=e.findName(t);if(i||n)return null==i?void 0:i.no}throw new Error("cannot decode enum ".concat(e.typeName," from JSON: ").concat(de(t)))}function me(e,t,n,i){var s;if(void 0===t)return t;if(!n&&e.values[0].no===t)return;if(i)return t;if("google.protobuf.NullValue"==e.typeName)return null;const o=e.findNumber(t);return null!==(s=null==o?void 0:o.name)&&void 0!==s?s:t}function pe(e,t,i){if(void 0!==t)switch(e){case k.INT32:case k.SFIXED32:case k.SINT32:case k.FIXED32:case k.UINT32:return n("number"==typeof t),0!=t||i?t:void 0;case k.FLOAT:case k.DOUBLE:return n("number"==typeof t),Number.isNaN(t)?"NaN":t===Number.POSITIVE_INFINITY?"Infinity":t===Number.NEGATIVE_INFINITY?"-Infinity":0!==t||i?t:void 0;case k.STRING:return n("string"==typeof t),t.length>0||i?t:void 0;case k.BOOL:return n("boolean"==typeof t),t||i?t:void 0;case k.UINT64:case k.FIXED64:case k.INT64:case k.SFIXED64:case k.SINT64:return n("bigint"==typeof t||"string"==typeof t||"number"==typeof t),i||0!=t?t.toString(10):void 0;case k.BYTES:return n(t instanceof Uint8Array),i||t.byteLength>0?ee.enc(t):void 0}}function ge(e){if(void 0===e)return e;if(e instanceof v)return e.clone();if(e instanceof Uint8Array){const t=new Uint8Array(e.byteLength);return t.set(e),t}return e}function fe(e){return e instanceof Uint8Array?e:new Uint8Array(e)}class ve{constructor(e,t){this._fields=e,this._normalizer=t}findJsonName(e){if(!this.jsonNames){const e={};for(const t of this.list())e[t.jsonName]=e[t.name]=t;this.jsonNames=e}return this.jsonNames[e]}find(e){if(!this.numbers){const e={};for(const t of this.list())e[t.no]=t;this.numbers=e}return this.numbers[e]}list(){return this.all||(this.all=this._normalizer(this._fields)),this.all}byNumber(){return this.numbersAsc||(this.numbersAsc=this.list().concat().sort(((e,t)=>e.no-t.no))),this.numbersAsc}byMember(){if(!this.members){this.members=[];const e=this.members;let t;for(const n of this.list())n.oneof?n.oneof!==t&&(t=n.oneof,e.push(t)):e.push(n)}return this.members}}function ke(e,t){const n=ye(e);return t?n:we(Ee(n))}const Te=ye;function ye(e){let t=!1;const n=[];for(let i=0;i<e.length;i++){let s=e.charAt(i);switch(s){case"_":t=!0;break;case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":n.push(s),t=!1;break;default:t&&(t=!1,s=s.toUpperCase()),n.push(s)}}return n.join("")}const be=new Set(["constructor","toString","toJSON","valueOf"]),Ce=new Set(["getType","clone","equals","fromBinary","fromJson","fromJsonString","toBinary","toJson","toJsonString","toObject"]),Se=e=>"".concat(e,"$"),Ee=e=>Ce.has(e)?Se(e):e,we=e=>be.has(e)?Se(e):e;class Pe{constructor(e){this.kind="oneof",this.repeated=!1,this.packed=!1,this.opt=!1,this.default=void 0,this.fields=[],this.name=e,this.localName=ke(e,!1)}addField(e){n(e.oneof===this,"field ".concat(e.name," not one of ").concat(this.name)),this.fields.push(e)}findField(e){if(!this._lookup){this._lookup=Object.create(null);for(let e=0;e<this.fields.length;e++)this._lookup[this.fields[e].localName]=this.fields[e]}return this._lookup[e]}}const Re=(_e="proto3",Ie=function(e,t){const n=t(me,pe);return{makeReadOptions:re,makeWriteOptions:ce,readMessage(t,n,i,s){if(null==n||Array.isArray(n)||"object"!=typeof n)throw new Error("cannot decode message ".concat(t.typeName," from JSON: ").concat(de(n)));s=null!=s?s:new t;const o=new Map,a=i.typeRegistry;for(const[r,c]of Object.entries(n)){const n=t.fields.findJsonName(r);if(n){if(n.oneof){if(null===c&&"scalar"==n.kind)continue;const e=o.get(n.oneof);if(void 0!==e)throw new Error("cannot decode message ".concat(t.typeName,' from JSON: multiple keys for oneof "').concat(n.oneof.name,'" present: "').concat(e,'", "').concat(r,'"'));o.set(n.oneof,r)}le(s,c,n,i,t,e)}else{let e=!1;if((null==a?void 0:a.findExtension)&&r.startsWith("[")&&r.endsWith("]")){const n=a.findExtension(r.substring(1,r.length-1));if(n&&n.extendee.typeName==t.typeName){e=!0;const[t,o]=U(n);le(t,c,n.field,i,n,!0),ne(s,n,o(),i)}}if(!e&&!i.ignoreUnknownFields)throw new Error("cannot decode message ".concat(t.typeName,' from JSON: key "').concat(r,'" is unknown'))}}return s},writeMessage(e,t){const i=e.getType(),s={};let o;try{for(const a of i.fields.byMember()){let i;if("oneof"==a.kind){const s=e[a.localName];if(void 0===s.value)continue;if(o=a.findField(s.case),!o)throw"oneof case not found: "+s.case;i=n(o,s.value,t)}else o=a,i=n(o,e[o.localName],t);void 0!==i&&(s[t.useProtoFieldName?o.name:o.jsonName]=i)}const a=t.typeRegistry;if(null==a?void 0:a.findExtensionFor)for(const o of i.runtime.bin.listUnknownFields(e)){const r=a.findExtensionFor(i.typeName,o.no);if(r&&ie(e,r)){const i=te(e,r,t),o=n(r.field,i,t);void 0!==o&&(s[r.field.jsonName]=o)}}}catch(e){const t=o?"cannot encode field ".concat(i.typeName,".").concat(o.name," to JSON"):"cannot encode message ".concat(i.typeName," to JSON"),n=e instanceof Error?e.message:String(e);throw new Error(t+(n.length>0?": ".concat(n):""))}return s},readScalar:(t,n,i)=>ue(t,n,i,e),writeScalar:pe,debug:de}}(!0,((e,t)=>function(i,s,o){if("map"==i.kind){const a={};switch(i.V.kind){case"scalar":for(const[e,o]of Object.entries(s)){const s=t(i.V.T,o,!0);n(void 0!==s),a[e.toString()]=s}break;case"message":for(const[e,t]of Object.entries(s))a[e.toString()]=t.toJson(o);break;case"enum":const r=i.V.T;for(const[t,i]of Object.entries(s)){n(void 0===i||"number"==typeof i);const s=e(r,i,!0,o.enumAsInteger);n(void 0!==s),a[t.toString()]=s}}return o.emitDefaultValues||Object.keys(a).length>0?a:void 0}if(i.repeated){const n=[];switch(i.kind){case"scalar":for(let e=0;e<s.length;e++)n.push(t(i.T,s[e],!0));break;case"enum":for(let t=0;t<s.length;t++)n.push(e(i.T,s[t],!0,o.enumAsInteger));break;case"message":for(let e=0;e<s.length;e++)n.push(s[e].toJson(o))}return o.emitDefaultValues||n.length>0?n:void 0}if(void 0!==s)switch(i.kind){case"scalar":return t(i.T,s,!!i.oneof||i.opt||o.emitDefaultValues);case"enum":return e(i.T,s,!!i.oneof||i.opt||o.emitDefaultValues,o.enumAsInteger);case"message":return j(i.T,s).toJson(o)}})),Oe=Object.assign(Object.assign({},{makeReadOptions:q,makeWriteOptions:K,listUnknownFields(e){var t;return null!==(t=e[F])&&void 0!==t?t:[]},discardUnknownFields(e){delete e[F]},writeUnknownFields(e,t){const n=e[F];if(n)for(const e of n)t.tag(e.no,e.wireType).raw(e.data)},onUnknownField(e,t,n,i){const s=e;Array.isArray(s[F])||(s[F]=[]),s[F].push({no:t,wireType:n,data:i})},readMessage(e,t,n,i,s){const o=e.getType(),a=s?t.len:t.pos+n;let r,c;for(;t.pos<a&&([r,c]=t.tag(),c!=M.EndGroup);){const n=o.fields.find(r);if(n)G(e,t,n,c,i);else{const n=t.skip(c);i.readUnknownFields&&this.onUnknownField(e,r,c,n)}}if(s&&(c!=M.EndGroup||r!==n))throw new Error("invalid end group tag")},readField:G}),{writeField:X,writeMessage(e,t,n){const i=e.getType();for(const s of i.fields.byNumber()){let i,o=s.localName;if(s.oneof){const t=e[s.oneof.localName];if(t.case!==o)continue;i=t.value}else i=e[o];X(s,i,t,n)}return n.writeUnknownFields&&this.writeUnknownFields(e,t),t}}),Me=Object.assign(Object.assign({},{setEnumType:m,initPartial(e,t){if(void 0===e)return;const n=t.getType();for(const i of n.fields.byMember()){const n=i.localName,s=t,o=e;if(void 0!==o[n])switch(i.kind){case"oneof":const e=o[n].case;if(void 0===e)continue;const t=i.findField(e);let a=o[n].value;!t||"message"!=t.kind||a instanceof t.T?t&&"scalar"===t.kind&&t.T===k.BYTES&&(a=fe(a)):a=new t.T(a),s[n]={case:e,value:a};break;case"scalar":case"enum":let r=o[n];i.T===k.BYTES&&(r=i.repeated?r.map(fe):fe(r)),s[n]=r;break;case"map":switch(i.V.kind){case"scalar":case"enum":if(i.V.T===k.BYTES)for(const[e,t]of Object.entries(o[n]))s[n][e]=fe(t);else Object.assign(s[n],o[n]);break;case"message":const e=i.V.T;for(const t of Object.keys(o[n])){let i=o[n][t];e.fieldWrapper||(i=new e(i)),s[n][t]=i}}break;case"message":const c=i.T;if(i.repeated)s[n]=o[n].map((e=>e instanceof c?e:new c(e)));else if(void 0!==o[n]){const e=o[n];c.fieldWrapper?"google.protobuf.BytesValue"===c.typeName?s[n]=fe(e):s[n]=e:s[n]=e instanceof c?e:new c(e)}}}},equals:(e,t,n)=>t===n||!(!t||!n)&&e.fields.byMember().every((e=>{const i=t[e.localName],s=n[e.localName];if(e.repeated){if(i.length!==s.length)return!1;switch(e.kind){case"message":return i.every(((t,n)=>e.T.equals(t,s[n])));case"scalar":return i.every(((t,n)=>N(e.T,t,s[n])));case"enum":return i.every(((e,t)=>N(k.INT32,e,s[t])))}throw new Error("repeated cannot contain ".concat(e.kind))}switch(e.kind){case"message":return e.T.equals(i,s);case"enum":return N(k.INT32,i,s);case"scalar":return N(e.T,i,s);case"oneof":if(i.case!==s.case)return!1;const t=e.findField(i.case);if(void 0===t)return!0;switch(t.kind){case"message":return t.T.equals(i.value,s.value);case"enum":return N(k.INT32,i.value,s.value);case"scalar":return N(t.T,i.value,s.value)}throw new Error("oneof cannot contain ".concat(t.kind));case"map":const n=Object.keys(i).concat(Object.keys(s));switch(e.V.kind){case"message":const t=e.V.T;return n.every((e=>t.equals(i[e],s[e])));case"enum":return n.every((e=>N(k.INT32,i[e],s[e])));case"scalar":const o=e.V.T;return n.every((e=>N(o,i[e],s[e])))}}})),clone(e){const t=e.getType(),n=new t,i=n;for(const n of t.fields.byMember()){const t=e[n.localName];let s;if(n.repeated)s=t.map(ge);else if("map"==n.kind){s=i[n.localName];for(const[e,n]of Object.entries(t))s[e]=ge(n)}else s="oneof"==n.kind?n.findField(t.case)?{case:t.case,value:ge(t.value)}:{case:void 0}:ge(t);i[n.localName]=s}return n}}),{newFieldList:e=>new ve(e,xe),initFields(e){for(const t of e.getType().fields.byMember()){if(t.opt)continue;const n=t.localName,i=e;if(t.repeated)i[n]=[];else switch(t.kind){case"oneof":i[n]={case:void 0};break;case"enum":i[n]=0;break;case"map":i[n]={};break;case"scalar":i[n]=L(t.T,t.L)}}}}),{syntax:_e,json:Ie,bin:Oe,util:Me,makeMessageType(e,t,n){return function(e,t,n,i){var s;const o=null!==(s=null==i?void 0:i.localName)&&void 0!==s?s:t.substring(t.lastIndexOf(".")+1),a={[o]:function(t){e.util.initFields(this),e.util.initPartial(t,this)}}[o];return Object.setPrototypeOf(a.prototype,new v),Object.assign(a,{runtime:e,typeName:t,fields:e.util.newFieldList(n),fromBinary:(e,t)=>(new a).fromBinary(e,t),fromJson:(e,t)=>(new a).fromJson(e,t),fromJsonString:(e,t)=>(new a).fromJsonString(e,t),equals:(t,n)=>e.util.equals(a,t,n)}),a}(this,e,t,n)},makeEnum:g,makeEnumType:p,getEnumType:h,makeExtension(e,t,n){return function(e,t,n,i){let s;return{typeName:t,extendee:n,get field(){if(!s){const n="function"==typeof i?i():i;n.name=t.split(".").pop(),n.jsonName="[".concat(t,"]"),s=e.util.newFieldList([n]).list()[0]}return s},runtime:e}}(this,e,t,n)}});var _e,Ie,Oe,Me;function xe(e){var t,n,i,s;const o=[];let a;for(const r of"function"==typeof e?e():e){const e=r;if(e.localName=ke(r.name,void 0!==r.oneof),e.jsonName=null!==(t=r.jsonName)&&void 0!==t?t:Te(r.name),e.repeated=null!==(n=r.repeated)&&void 0!==n&&n,"scalar"==r.kind&&(e.L=null!==(i=r.L)&&void 0!==i?i:T.BIGINT),void 0!==r.oneof){const t="string"==typeof r.oneof?r.oneof:r.oneof.name;a&&a.name==t||(a=new Pe(t)),e.oneof=a,a.addField(e)}"message"==r.kind&&(e.delimited=!1),e.packed=null!==(s=r.packed)&&void 0!==s?s:"enum"==r.kind||"scalar"==r.kind&&r.T!=k.BYTES&&r.T!=k.STRING,o.push(e)}return o}class De extends v{constructor(e){super(),this.seconds=O.zero,this.nanos=0,Re.util.initPartial(e,this)}fromJson(e,t){if("string"!=typeof e)throw new Error("cannot decode google.protobuf.Timestamp from JSON: ".concat(Re.json.debug(e)));const n=e.match(/^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})(?:Z|\.([0-9]{3,9})Z|([+-][0-9][0-9]:[0-9][0-9]))$/);if(!n)throw new Error("cannot decode google.protobuf.Timestamp from JSON: invalid RFC 3339 string");const i=Date.parse(n[1]+"-"+n[2]+"-"+n[3]+"T"+n[4]+":"+n[5]+":"+n[6]+(n[8]?n[8]:"Z"));if(Number.isNaN(i))throw new Error("cannot decode google.protobuf.Timestamp from JSON: invalid RFC 3339 string");if(i<Date.parse("0001-01-01T00:00:00Z")||i>Date.parse("9999-12-31T23:59:59Z"))throw new Error("cannot decode message google.protobuf.Timestamp from JSON: must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive");return this.seconds=O.parse(i/1e3),this.nanos=0,n[7]&&(this.nanos=parseInt("1"+n[7]+"0".repeat(9-n[7].length))-1e9),this}toJson(e){const t=1e3*Number(this.seconds);if(t<Date.parse("0001-01-01T00:00:00Z")||t>Date.parse("9999-12-31T23:59:59Z"))throw new Error("cannot encode google.protobuf.Timestamp to JSON: must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive");if(this.nanos<0)throw new Error("cannot encode google.protobuf.Timestamp to JSON: nanos must not be negative");let n="Z";if(this.nanos>0){const e=(this.nanos+1e9).toString().substring(1);n="000000"===e.substring(3)?"."+e.substring(0,3)+"Z":"000"===e.substring(6)?"."+e.substring(0,6)+"Z":"."+e+"Z"}return new Date(t).toISOString().replace(".000Z",n)}toDate(){return new Date(1e3*Number(this.seconds)+Math.ceil(this.nanos/1e6))}static now(){return De.fromDate(new Date)}static fromDate(e){const t=e.getTime();return new De({seconds:O.parse(Math.floor(t/1e3)),nanos:t%1e3*1e6})}static fromBinary(e,t){return(new De).fromBinary(e,t)}static fromJson(e,t){return(new De).fromJson(e,t)}static fromJsonString(e,t){return(new De).fromJsonString(e,t)}static equals(e,t){return Re.util.equals(De,e,t)}}De.runtime=Re,De.typeName="google.protobuf.Timestamp",De.fields=Re.util.newFieldList((()=>[{no:1,name:"seconds",kind:"scalar",T:3},{no:2,name:"nanos",kind:"scalar",T:5}]));const Ne=Re.makeEnum("livekit.AudioCodec",[{no:0,name:"DEFAULT_AC"},{no:1,name:"OPUS"},{no:2,name:"AAC"}]),Le=Re.makeEnum("livekit.VideoCodec",[{no:0,name:"DEFAULT_VC"},{no:1,name:"H264_BASELINE"},{no:2,name:"H264_MAIN"},{no:3,name:"H264_HIGH"},{no:4,name:"VP8"}]),Ae=Re.makeEnum("livekit.ImageCodec",[{no:0,name:"IC_DEFAULT"},{no:1,name:"IC_JPEG"}]),Ue=Re.makeEnum("livekit.TrackType",[{no:0,name:"AUDIO"},{no:1,name:"VIDEO"},{no:2,name:"DATA"}]),je=Re.makeEnum("livekit.TrackSource",[{no:0,name:"UNKNOWN"},{no:1,name:"CAMERA"},{no:2,name:"MICROPHONE"},{no:3,name:"SCREEN_SHARE"},{no:4,name:"SCREEN_SHARE_AUDIO"}]),Fe=Re.makeEnum("livekit.VideoQuality",[{no:0,name:"LOW"},{no:1,name:"MEDIUM"},{no:2,name:"HIGH"},{no:3,name:"OFF"}]),Be=Re.makeEnum("livekit.ConnectionQuality",[{no:0,name:"POOR"},{no:1,name:"GOOD"},{no:2,name:"EXCELLENT"},{no:3,name:"LOST"}]),Ve=Re.makeEnum("livekit.ClientConfigSetting",[{no:0,name:"UNSET"},{no:1,name:"DISABLED"},{no:2,name:"ENABLED"}]),qe=Re.makeEnum("livekit.DisconnectReason",[{no:0,name:"UNKNOWN_REASON"},{no:1,name:"CLIENT_INITIATED"},{no:2,name:"DUPLICATE_IDENTITY"},{no:3,name:"SERVER_SHUTDOWN"},{no:4,name:"PARTICIPANT_REMOVED"},{no:5,name:"ROOM_DELETED"},{no:6,name:"STATE_MISMATCH"},{no:7,name:"JOIN_FAILURE"},{no:8,name:"MIGRATION"},{no:9,name:"SIGNAL_CLOSE"}]),Ke=Re.makeEnum("livekit.ReconnectReason",[{no:0,name:"RR_UNKNOWN"},{no:1,name:"RR_SIGNAL_DISCONNECTED"},{no:2,name:"RR_PUBLISHER_FAILED"},{no:3,name:"RR_SUBSCRIBER_FAILED"},{no:4,name:"RR_SWITCH_CANDIDATE"}]),Ge=Re.makeEnum("livekit.SubscriptionError",[{no:0,name:"SE_UNKNOWN"},{no:1,name:"SE_CODEC_UNSUPPORTED"},{no:2,name:"SE_TRACK_NOTFOUND"}]),We=Re.makeMessageType("livekit.Room",(()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",T:9},{no:3,name:"empty_timeout",kind:"scalar",T:13},{no:14,name:"departure_timeout",kind:"scalar",T:13},{no:4,name:"max_participants",kind:"scalar",T:13},{no:5,name:"creation_time",kind:"scalar",T:3},{no:6,name:"turn_password",kind:"scalar",T:9},{no:7,name:"enabled_codecs",kind:"message",T:He,repeated:!0},{no:8,name:"metadata",kind:"scalar",T:9},{no:9,name:"num_participants",kind:"scalar",T:13},{no:11,name:"num_publishers",kind:"scalar",T:13},{no:10,name:"active_recording",kind:"scalar",T:8},{no:13,name:"version",kind:"message",T:ft}])),He=Re.makeMessageType("livekit.Codec",(()=>[{no:1,name:"mime",kind:"scalar",T:9},{no:2,name:"fmtp_line",kind:"scalar",T:9}]));Re.makeMessageType("livekit.PlayoutDelay",(()=>[{no:1,name:"enabled",kind:"scalar",T:8},{no:2,name:"min",kind:"scalar",T:13},{no:3,name:"max",kind:"scalar",T:13}]));const Je=Re.makeMessageType("livekit.ParticipantPermission",(()=>[{no:1,name:"can_subscribe",kind:"scalar",T:8},{no:2,name:"can_publish",kind:"scalar",T:8},{no:3,name:"can_publish_data",kind:"scalar",T:8},{no:9,name:"can_publish_sources",kind:"enum",T:Re.getEnumType(je),repeated:!0},{no:7,name:"hidden",kind:"scalar",T:8},{no:8,name:"recorder",kind:"scalar",T:8},{no:10,name:"can_update_metadata",kind:"scalar",T:8},{no:11,name:"agent",kind:"scalar",T:8}])),ze=Re.makeMessageType("livekit.ParticipantInfo",(()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"identity",kind:"scalar",T:9},{no:3,name:"state",kind:"enum",T:Re.getEnumType(Qe)},{no:4,name:"tracks",kind:"message",T:$e,repeated:!0},{no:5,name:"metadata",kind:"scalar",T:9},{no:6,name:"joined_at",kind:"scalar",T:3},{no:9,name:"name",kind:"scalar",T:9},{no:10,name:"version",kind:"scalar",T:13},{no:11,name:"permission",kind:"message",T:Je},{no:12,name:"region",kind:"scalar",T:9},{no:13,name:"is_publisher",kind:"scalar",T:8},{no:14,name:"kind",kind:"enum",T:Re.getEnumType(Ye)}])),Qe=Re.makeEnum("livekit.ParticipantInfo.State",[{no:0,name:"JOINING"},{no:1,name:"JOINED"},{no:2,name:"ACTIVE"},{no:3,name:"DISCONNECTED"}]),Ye=Re.makeEnum("livekit.ParticipantInfo.Kind",[{no:0,name:"STANDARD"},{no:1,name:"INGRESS"},{no:2,name:"EGRESS"},{no:3,name:"SIP"},{no:4,name:"AGENT"}]);Re.makeMessageType("livekit.Encryption",[]);const Xe=Re.makeEnum("livekit.Encryption.Type",[{no:0,name:"NONE"},{no:1,name:"GCM"},{no:2,name:"CUSTOM"}]),Ze=Re.makeMessageType("livekit.SimulcastCodecInfo",(()=>[{no:1,name:"mime_type",kind:"scalar",T:9},{no:2,name:"mid",kind:"scalar",T:9},{no:3,name:"cid",kind:"scalar",T:9},{no:4,name:"layers",kind:"message",T:et,repeated:!0}])),$e=Re.makeMessageType("livekit.TrackInfo",(()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"type",kind:"enum",T:Re.getEnumType(Ue)},{no:3,name:"name",kind:"scalar",T:9},{no:4,name:"muted",kind:"scalar",T:8},{no:5,name:"width",kind:"scalar",T:13},{no:6,name:"height",kind:"scalar",T:13},{no:7,name:"simulcast",kind:"scalar",T:8},{no:8,name:"disable_dtx",kind:"scalar",T:8},{no:9,name:"source",kind:"enum",T:Re.getEnumType(je)},{no:10,name:"layers",kind:"message",T:et,repeated:!0},{no:11,name:"mime_type",kind:"scalar",T:9},{no:12,name:"mid",kind:"scalar",T:9},{no:13,name:"codecs",kind:"message",T:Ze,repeated:!0},{no:14,name:"stereo",kind:"scalar",T:8},{no:15,name:"disable_red",kind:"scalar",T:8},{no:16,name:"encryption",kind:"enum",T:Re.getEnumType(Xe)},{no:17,name:"stream",kind:"scalar",T:9},{no:18,name:"version",kind:"message",T:ft}])),et=Re.makeMessageType("livekit.VideoLayer",(()=>[{no:1,name:"quality",kind:"enum",T:Re.getEnumType(Fe)},{no:2,name:"width",kind:"scalar",T:13},{no:3,name:"height",kind:"scalar",T:13},{no:4,name:"bitrate",kind:"scalar",T:13},{no:5,name:"ssrc",kind:"scalar",T:13}])),tt=Re.makeMessageType("livekit.DataPacket",(()=>[{no:1,name:"kind",kind:"enum",T:Re.getEnumType(nt)},{no:4,name:"participant_identity",kind:"scalar",T:9},{no:5,name:"destination_identities",kind:"scalar",T:9,repeated:!0},{no:2,name:"user",kind:"message",T:ot,oneof:"value"},{no:3,name:"speaker",kind:"message",T:it,oneof:"value"},{no:6,name:"sip_dtmf",kind:"message",T:at,oneof:"value"}])),nt=Re.makeEnum("livekit.DataPacket.Kind",[{no:0,name:"RELIABLE"},{no:1,name:"LOSSY"}]),it=Re.makeMessageType("livekit.ActiveSpeakerUpdate",(()=>[{no:1,name:"speakers",kind:"message",T:st,repeated:!0}])),st=Re.makeMessageType("livekit.SpeakerInfo",(()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"level",kind:"scalar",T:2},{no:3,name:"active",kind:"scalar",T:8}])),ot=Re.makeMessageType("livekit.UserPacket",(()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:5,name:"participant_identity",kind:"scalar",T:9},{no:2,name:"payload",kind:"scalar",T:12},{no:3,name:"destination_sids",kind:"scalar",T:9,repeated:!0},{no:6,name:"destination_identities",kind:"scalar",T:9,repeated:!0},{no:4,name:"topic",kind:"scalar",T:9,opt:!0}])),at=Re.makeMessageType("livekit.SipDTMF",(()=>[{no:3,name:"code",kind:"scalar",T:13},{no:4,name:"digit",kind:"scalar",T:9}])),rt=Re.makeMessageType("livekit.ParticipantTracks",(()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"track_sids",kind:"scalar",T:9,repeated:!0}])),ct=Re.makeMessageType("livekit.ServerInfo",(()=>[{no:1,name:"edition",kind:"enum",T:Re.getEnumType(dt)},{no:2,name:"version",kind:"scalar",T:9},{no:3,name:"protocol",kind:"scalar",T:5},{no:4,name:"region",kind:"scalar",T:9},{no:5,name:"node_id",kind:"scalar",T:9},{no:6,name:"debug_info",kind:"scalar",T:9}])),dt=Re.makeEnum("livekit.ServerInfo.Edition",[{no:0,name:"Standard"},{no:1,name:"Cloud"}]),lt=Re.makeMessageType("livekit.ClientInfo",(()=>[{no:1,name:"sdk",kind:"enum",T:Re.getEnumType(ut)},{no:2,name:"version",kind:"scalar",T:9},{no:3,name:"protocol",kind:"scalar",T:5},{no:4,name:"os",kind:"scalar",T:9},{no:5,name:"os_version",kind:"scalar",T:9},{no:6,name:"device_model",kind:"scalar",T:9},{no:7,name:"browser",kind:"scalar",T:9},{no:8,name:"browser_version",kind:"scalar",T:9},{no:9,name:"address",kind:"scalar",T:9},{no:10,name:"network",kind:"scalar",T:9}])),ut=Re.makeEnum("livekit.ClientInfo.SDK",[{no:0,name:"UNKNOWN"},{no:1,name:"JS"},{no:2,name:"SWIFT"},{no:3,name:"ANDROID"},{no:4,name:"FLUTTER"},{no:5,name:"GO"},{no:6,name:"UNITY"},{no:7,name:"REACT_NATIVE"},{no:8,name:"RUST"},{no:9,name:"PYTHON"},{no:10,name:"CPP"}]),ht=Re.makeMessageType("livekit.ClientConfiguration",(()=>[{no:1,name:"video",kind:"message",T:mt},{no:2,name:"screen",kind:"message",T:mt},{no:3,name:"resume_connection",kind:"enum",T:Re.getEnumType(Ve)},{no:4,name:"disabled_codecs",kind:"message",T:pt},{no:5,name:"force_relay",kind:"enum",T:Re.getEnumType(Ve)}])),mt=Re.makeMessageType("livekit.VideoConfiguration",(()=>[{no:1,name:"hardware_encoder",kind:"enum",T:Re.getEnumType(Ve)}])),pt=Re.makeMessageType("livekit.DisabledCodecs",(()=>[{no:1,name:"codecs",kind:"message",T:He,repeated:!0},{no:2,name:"publish",kind:"message",T:He,repeated:!0}])),gt=Re.makeMessageType("livekit.RTPDrift",(()=>[{no:1,name:"start_time",kind:"message",T:De},{no:2,name:"end_time",kind:"message",T:De},{no:3,name:"duration",kind:"scalar",T:1},{no:4,name:"start_timestamp",kind:"scalar",T:4},{no:5,name:"end_timestamp",kind:"scalar",T:4},{no:6,name:"rtp_clock_ticks",kind:"scalar",T:4},{no:7,name:"drift_samples",kind:"scalar",T:3},{no:8,name:"drift_ms",kind:"scalar",T:1},{no:9,name:"clock_rate",kind:"scalar",T:1}]));Re.makeMessageType("livekit.RTPStats",(()=>[{no:1,name:"start_time",kind:"message",T:De},{no:2,name:"end_time",kind:"message",T:De},{no:3,name:"duration",kind:"scalar",T:1},{no:4,name:"packets",kind:"scalar",T:13},{no:5,name:"packet_rate",kind:"scalar",T:1},{no:6,name:"bytes",kind:"scalar",T:4},{no:39,name:"header_bytes",kind:"scalar",T:4},{no:7,name:"bitrate",kind:"scalar",T:1},{no:8,name:"packets_lost",kind:"scalar",T:13},{no:9,name:"packet_loss_rate",kind:"scalar",T:1},{no:10,name:"packet_loss_percentage",kind:"scalar",T:2},{no:11,name:"packets_duplicate",kind:"scalar",T:13},{no:12,name:"packet_duplicate_rate",kind:"scalar",T:1},{no:13,name:"bytes_duplicate",kind:"scalar",T:4},{no:40,name:"header_bytes_duplicate",kind:"scalar",T:4},{no:14,name:"bitrate_duplicate",kind:"scalar",T:1},{no:15,name:"packets_padding",kind:"scalar",T:13},{no:16,name:"packet_padding_rate",kind:"scalar",T:1},{no:17,name:"bytes_padding",kind:"scalar",T:4},{no:41,name:"header_bytes_padding",kind:"scalar",T:4},{no:18,name:"bitrate_padding",kind:"scalar",T:1},{no:19,name:"packets_out_of_order",kind:"scalar",T:13},{no:20,name:"frames",kind:"scalar",T:13},{no:21,name:"frame_rate",kind:"scalar",T:1},{no:22,name:"jitter_current",kind:"scalar",T:1},{no:23,name:"jitter_max",kind:"scalar",T:1},{no:24,name:"gap_histogram",kind:"map",K:5,V:{kind:"scalar",T:13}},{no:25,name:"nacks",kind:"scalar",T:13},{no:37,name:"nack_acks",kind:"scalar",T:13},{no:26,name:"nack_misses",kind:"scalar",T:13},{no:38,name:"nack_repeated",kind:"scalar",T:13},{no:27,name:"plis",kind:"scalar",T:13},{no:28,name:"last_pli",kind:"message",T:De},{no:29,name:"firs",kind:"scalar",T:13},{no:30,name:"last_fir",kind:"message",T:De},{no:31,name:"rtt_current",kind:"scalar",T:13},{no:32,name:"rtt_max",kind:"scalar",T:13},{no:33,name:"key_frames",kind:"scalar",T:13},{no:34,name:"last_key_frame",kind:"message",T:De},{no:35,name:"layer_lock_plis",kind:"scalar",T:13},{no:36,name:"last_layer_lock_pli",kind:"message",T:De},{no:44,name:"packet_drift",kind:"message",T:gt},{no:45,name:"report_drift",kind:"message",T:gt}]));const ft=Re.makeMessageType("livekit.TimedVersion",(()=>[{no:1,name:"unix_micro",kind:"scalar",T:3},{no:2,name:"ticks",kind:"scalar",T:5}])),vt=Re.makeEnum("livekit.EncodedFileType",[{no:0,name:"DEFAULT_FILETYPE"},{no:1,name:"MP4"},{no:2,name:"OGG"}]),kt=Re.makeEnum("livekit.SegmentedFileProtocol",[{no:0,name:"DEFAULT_SEGMENTED_FILE_PROTOCOL"},{no:1,name:"HLS_PROTOCOL"}]),Tt=Re.makeEnum("livekit.SegmentedFileSuffix",[{no:0,name:"INDEX"},{no:1,name:"TIMESTAMP"}]),yt=Re.makeEnum("livekit.ImageFileSuffix",[{no:0,name:"IMAGE_SUFFIX_INDEX"},{no:1,name:"IMAGE_SUFFIX_TIMESTAMP"}]),bt=Re.makeEnum("livekit.StreamProtocol",[{no:0,name:"DEFAULT_PROTOCOL"},{no:1,name:"RTMP"}]),Ct=Re.makeEnum("livekit.EncodingOptionsPreset",[{no:0,name:"H264_720P_30"},{no:1,name:"H264_720P_60"},{no:2,name:"H264_1080P_30"},{no:3,name:"H264_1080P_60"},{no:4,name:"PORTRAIT_H264_720P_30"},{no:5,name:"PORTRAIT_H264_720P_60"},{no:6,name:"PORTRAIT_H264_1080P_30"},{no:7,name:"PORTRAIT_H264_1080P_60"}]),St=Re.makeEnum("livekit.EgressStatus",[{no:0,name:"EGRESS_STARTING"},{no:1,name:"EGRESS_ACTIVE"},{no:2,name:"EGRESS_ENDING"},{no:3,name:"EGRESS_COMPLETE"},{no:4,name:"EGRESS_FAILED"},{no:5,name:"EGRESS_ABORTED"},{no:6,name:"EGRESS_LIMIT_REACHED"}]),Et=Re.makeMessageType("livekit.RoomCompositeEgressRequest",(()=>[{no:1,name:"room_name",kind:"scalar",T:9},{no:2,name:"layout",kind:"scalar",T:9},{no:3,name:"audio_only",kind:"scalar",T:8},{no:4,name:"video_only",kind:"scalar",T:8},{no:5,name:"custom_base_url",kind:"scalar",T:9},{no:6,name:"file",kind:"message",T:It,oneof:"output"},{no:7,name:"stream",kind:"message",T:Ut,oneof:"output"},{no:10,name:"segments",kind:"message",T:Ot,oneof:"output"},{no:8,name:"preset",kind:"enum",T:Re.getEnumType(Ct),oneof:"options"},{no:9,name:"advanced",kind:"message",T:jt,oneof:"options"},{no:11,name:"file_outputs",kind:"message",T:It,repeated:!0},{no:12,name:"stream_outputs",kind:"message",T:Ut,repeated:!0},{no:13,name:"segment_outputs",kind:"message",T:Ot,repeated:!0},{no:14,name:"image_outputs",kind:"message",T:xt,repeated:!0}])),wt=Re.makeMessageType("livekit.WebEgressRequest",(()=>[{no:1,name:"url",kind:"scalar",T:9},{no:2,name:"audio_only",kind:"scalar",T:8},{no:3,name:"video_only",kind:"scalar",T:8},{no:12,name:"await_start_signal",kind:"scalar",T:8},{no:4,name:"file",kind:"message",T:It,oneof:"output"},{no:5,name:"stream",kind:"message",T:Ut,oneof:"output"},{no:6,name:"segments",kind:"message",T:Ot,oneof:"output"},{no:7,name:"preset",kind:"enum",T:Re.getEnumType(Ct),oneof:"options"},{no:8,name:"advanced",kind:"message",T:jt,oneof:"options"},{no:9,name:"file_outputs",kind:"message",T:It,repeated:!0},{no:10,name:"stream_outputs",kind:"message",T:Ut,repeated:!0},{no:11,name:"segment_outputs",kind:"message",T:Ot,repeated:!0},{no:13,name:"image_outputs",kind:"message",T:xt,repeated:!0}])),Pt=Re.makeMessageType("livekit.ParticipantEgressRequest",(()=>[{no:1,name:"room_name",kind:"scalar",T:9},{no:2,name:"identity",kind:"scalar",T:9},{no:3,name:"screen_share",kind:"scalar",T:8},{no:4,name:"preset",kind:"enum",T:Re.getEnumType(Ct),oneof:"options"},{no:5,name:"advanced",kind:"message",T:jt,oneof:"options"},{no:6,name:"file_outputs",kind:"message",T:It,repeated:!0},{no:7,name:"stream_outputs",kind:"message",T:Ut,repeated:!0},{no:8,name:"segment_outputs",kind:"message",T:Ot,repeated:!0},{no:9,name:"image_outputs",kind:"message",T:xt,repeated:!0}])),Rt=Re.makeMessageType("livekit.TrackCompositeEgressRequest",(()=>[{no:1,name:"room_name",kind:"scalar",T:9},{no:2,name:"audio_track_id",kind:"scalar",T:9},{no:3,name:"video_track_id",kind:"scalar",T:9},{no:4,name:"file",kind:"message",T:It,oneof:"output"},{no:5,name:"stream",kind:"message",T:Ut,oneof:"output"},{no:8,name:"segments",kind:"message",T:Ot,oneof:"output"},{no:6,name:"preset",kind:"enum",T:Re.getEnumType(Ct),oneof:"options"},{no:7,name:"advanced",kind:"message",T:jt,oneof:"options"},{no:11,name:"file_outputs",kind:"message",T:It,repeated:!0},{no:12,name:"stream_outputs",kind:"message",T:Ut,repeated:!0},{no:13,name:"segment_outputs",kind:"message",T:Ot,repeated:!0},{no:14,name:"image_outputs",kind:"message",T:xt,repeated:!0}])),_t=Re.makeMessageType("livekit.TrackEgressRequest",(()=>[{no:1,name:"room_name",kind:"scalar",T:9},{no:2,name:"track_id",kind:"scalar",T:9},{no:3,name:"file",kind:"message",T:Mt,oneof:"output"},{no:4,name:"websocket_url",kind:"scalar",T:9,oneof:"output"}])),It=Re.makeMessageType("livekit.EncodedFileOutput",(()=>[{no:1,name:"file_type",kind:"enum",T:Re.getEnumType(vt)},{no:2,name:"filepath",kind:"scalar",T:9},{no:6,name:"disable_manifest",kind:"scalar",T:8},{no:3,name:"s3",kind:"message",T:Dt,oneof:"output"},{no:4,name:"gcp",kind:"message",T:Nt,oneof:"output"},{no:5,name:"azure",kind:"message",T:Lt,oneof:"output"},{no:7,name:"aliOSS",kind:"message",T:At,oneof:"output"}])),Ot=Re.makeMessageType("livekit.SegmentedFileOutput",(()=>[{no:1,name:"protocol",kind:"enum",T:Re.getEnumType(kt)},{no:2,name:"filename_prefix",kind:"scalar",T:9},{no:3,name:"playlist_name",kind:"scalar",T:9},{no:11,name:"live_playlist_name",kind:"scalar",T:9},{no:4,name:"segment_duration",kind:"scalar",T:13},{no:10,name:"filename_suffix",kind:"enum",T:Re.getEnumType(Tt)},{no:8,name:"disable_manifest",kind:"scalar",T:8},{no:5,name:"s3",kind:"message",T:Dt,oneof:"output"},{no:6,name:"gcp",kind:"message",T:Nt,oneof:"output"},{no:7,name:"azure",kind:"message",T:Lt,oneof:"output"},{no:9,name:"aliOSS",kind:"message",T:At,oneof:"output"}])),Mt=Re.makeMessageType("livekit.DirectFileOutput",(()=>[{no:1,name:"filepath",kind:"scalar",T:9},{no:5,name:"disable_manifest",kind:"scalar",T:8},{no:2,name:"s3",kind:"message",T:Dt,oneof:"output"},{no:3,name:"gcp",kind:"message",T:Nt,oneof:"output"},{no:4,name:"azure",kind:"message",T:Lt,oneof:"output"},{no:6,name:"aliOSS",kind:"message",T:At,oneof:"output"}])),xt=Re.makeMessageType("livekit.ImageOutput",(()=>[{no:1,name:"capture_interval",kind:"scalar",T:13},{no:2,name:"width",kind:"scalar",T:5},{no:3,name:"height",kind:"scalar",T:5},{no:4,name:"filename_prefix",kind:"scalar",T:9},{no:5,name:"filename_suffix",kind:"enum",T:Re.getEnumType(yt)},{no:6,name:"image_codec",kind:"enum",T:Re.getEnumType(Ae)},{no:7,name:"disable_manifest",kind:"scalar",T:8},{no:8,name:"s3",kind:"message",T:Dt,oneof:"output"},{no:9,name:"gcp",kind:"message",T:Nt,oneof:"output"},{no:10,name:"azure",kind:"message",T:Lt,oneof:"output"},{no:11,name:"aliOSS",kind:"message",T:At,oneof:"output"}])),Dt=Re.makeMessageType("livekit.S3Upload",(()=>[{no:1,name:"access_key",kind:"scalar",T:9},{no:2,name:"secret",kind:"scalar",T:9},{no:3,name:"region",kind:"scalar",T:9},{no:4,name:"endpoint",kind:"scalar",T:9},{no:5,name:"bucket",kind:"scalar",T:9},{no:6,name:"force_path_style",kind:"scalar",T:8},{no:7,name:"metadata",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:8,name:"tagging",kind:"scalar",T:9},{no:9,name:"content_disposition",kind:"scalar",T:9}])),Nt=Re.makeMessageType("livekit.GCPUpload",(()=>[{no:1,name:"credentials",kind:"scalar",T:9},{no:2,name:"bucket",kind:"scalar",T:9},{no:3,name:"endpoint",kind:"scalar",T:9}])),Lt=Re.makeMessageType("livekit.AzureBlobUpload",(()=>[{no:1,name:"account_name",kind:"scalar",T:9},{no:2,name:"account_key",kind:"scalar",T:9},{no:3,name:"container_name",kind:"scalar",T:9}])),At=Re.makeMessageType("livekit.AliOSSUpload",(()=>[{no:1,name:"access_key",kind:"scalar",T:9},{no:2,name:"secret",kind:"scalar",T:9},{no:3,name:"region",kind:"scalar",T:9},{no:4,name:"endpoint",kind:"scalar",T:9},{no:5,name:"bucket",kind:"scalar",T:9}])),Ut=Re.makeMessageType("livekit.StreamOutput",(()=>[{no:1,name:"protocol",kind:"enum",T:Re.getEnumType(bt)},{no:2,name:"urls",kind:"scalar",T:9,repeated:!0}])),jt=Re.makeMessageType("livekit.EncodingOptions",(()=>[{no:1,name:"width",kind:"scalar",T:5},{no:2,name:"height",kind:"scalar",T:5},{no:3,name:"depth",kind:"scalar",T:5},{no:4,name:"framerate",kind:"scalar",T:5},{no:5,name:"audio_codec",kind:"enum",T:Re.getEnumType(Ne)},{no:6,name:"audio_bitrate",kind:"scalar",T:5},{no:11,name:"audio_quality",kind:"scalar",T:5},{no:7,name:"audio_frequency",kind:"scalar",T:5},{no:8,name:"video_codec",kind:"enum",T:Re.getEnumType(Le)},{no:9,name:"video_bitrate",kind:"scalar",T:5},{no:12,name:"video_quality",kind:"scalar",T:5},{no:10,name:"key_frame_interval",kind:"scalar",T:1}]));Re.makeMessageType("livekit.UpdateLayoutRequest",(()=>[{no:1,name:"egress_id",kind:"scalar",T:9},{no:2,name:"layout",kind:"scalar",T:9}])),Re.makeMessageType("livekit.UpdateStreamRequest",(()=>[{no:1,name:"egress_id",kind:"scalar",T:9},{no:2,name:"add_output_urls",kind:"scalar",T:9,repeated:!0},{no:3,name:"remove_output_urls",kind:"scalar",T:9,repeated:!0}])),Re.makeMessageType("livekit.ListEgressRequest",(()=>[{no:1,name:"room_name",kind:"scalar",T:9},{no:2,name:"egress_id",kind:"scalar",T:9},{no:3,name:"active",kind:"scalar",T:8}])),Re.makeMessageType("livekit.ListEgressResponse",(()=>[{no:1,name:"items",kind:"message",T:Ft,repeated:!0}])),Re.makeMessageType("livekit.StopEgressRequest",(()=>[{no:1,name:"egress_id",kind:"scalar",T:9}]));const Ft=Re.makeMessageType("livekit.EgressInfo",(()=>[{no:1,name:"egress_id",kind:"scalar",T:9},{no:2,name:"room_id",kind:"scalar",T:9},{no:13,name:"room_name",kind:"scalar",T:9},{no:3,name:"status",kind:"enum",T:Re.getEnumType(St)},{no:10,name:"started_at",kind:"scalar",T:3},{no:11,name:"ended_at",kind:"scalar",T:3},{no:18,name:"updated_at",kind:"scalar",T:3},{no:21,name:"details",kind:"scalar",T:9},{no:9,name:"error",kind:"scalar",T:9},{no:4,name:"room_composite",kind:"message",T:Et,oneof:"request"},{no:14,name:"web",kind:"message",T:wt,oneof:"request"},{no:19,name:"participant",kind:"message",T:Pt,oneof:"request"},{no:5,name:"track_composite",kind:"message",T:Rt,oneof:"request"},{no:6,name:"track",kind:"message",T:_t,oneof:"request"},{no:7,name:"stream",kind:"message",T:Bt,oneof:"result"},{no:8,name:"file",kind:"message",T:Kt,oneof:"result"},{no:12,name:"segments",kind:"message",T:Gt,oneof:"result"},{no:15,name:"stream_results",kind:"message",T:Vt,repeated:!0},{no:16,name:"file_results",kind:"message",T:Kt,repeated:!0},{no:17,name:"segment_results",kind:"message",T:Gt,repeated:!0},{no:20,name:"image_results",kind:"message",T:Wt,repeated:!0}])),Bt=Re.makeMessageType("livekit.StreamInfoList",(()=>[{no:1,name:"info",kind:"message",T:Vt,repeated:!0}])),Vt=Re.makeMessageType("livekit.StreamInfo",(()=>[{no:1,name:"url",kind:"scalar",T:9},{no:2,name:"started_at",kind:"scalar",T:3},{no:3,name:"ended_at",kind:"scalar",T:3},{no:4,name:"duration",kind:"scalar",T:3},{no:5,name:"status",kind:"enum",T:Re.getEnumType(qt)},{no:6,name:"error",kind:"scalar",T:9}])),qt=Re.makeEnum("livekit.StreamInfo.Status",[{no:0,name:"ACTIVE"},{no:1,name:"FINISHED"},{no:2,name:"FAILED"}]),Kt=Re.makeMessageType("livekit.FileInfo",(()=>[{no:1,name:"filename",kind:"scalar",T:9},{no:2,name:"started_at",kind:"scalar",T:3},{no:3,name:"ended_at",kind:"scalar",T:3},{no:6,name:"duration",kind:"scalar",T:3},{no:4,name:"size",kind:"scalar",T:3},{no:5,name:"location",kind:"scalar",T:9}])),Gt=Re.makeMessageType("livekit.SegmentsInfo",(()=>[{no:1,name:"playlist_name",kind:"scalar",T:9},{no:8,name:"live_playlist_name",kind:"scalar",T:9},{no:2,name:"duration",kind:"scalar",T:3},{no:3,name:"size",kind:"scalar",T:3},{no:4,name:"playlist_location",kind:"scalar",T:9},{no:9,name:"live_playlist_location",kind:"scalar",T:9},{no:5,name:"segment_count",kind:"scalar",T:3},{no:6,name:"started_at",kind:"scalar",T:3},{no:7,name:"ended_at",kind:"scalar",T:3}])),Wt=Re.makeMessageType("livekit.ImagesInfo",(()=>[{no:1,name:"image_count",kind:"scalar",T:3},{no:2,name:"started_at",kind:"scalar",T:3},{no:3,name:"ended_at",kind:"scalar",T:3}])),Ht=Re.makeMessageType("livekit.AutoParticipantEgress",(()=>[{no:1,name:"preset",kind:"enum",T:Re.getEnumType(Ct),oneof:"options"},{no:2,name:"advanced",kind:"message",T:jt,oneof:"options"},{no:3,name:"file_outputs",kind:"message",T:It,repeated:!0},{no:4,name:"segment_outputs",kind:"message",T:Ot,repeated:!0}])),Jt=Re.makeMessageType("livekit.AutoTrackEgress",(()=>[{no:1,name:"filepath",kind:"scalar",T:9},{no:5,name:"disable_manifest",kind:"scalar",T:8},{no:2,name:"s3",kind:"message",T:Dt,oneof:"output"},{no:3,name:"gcp",kind:"message",T:Nt,oneof:"output"},{no:4,name:"azure",kind:"message",T:Lt,oneof:"output"}]));Re.makeMessageType("livekit.CreateRoomRequest",(()=>[{no:1,name:"name",kind:"scalar",T:9},{no:2,name:"empty_timeout",kind:"scalar",T:13},{no:10,name:"departure_timeout",kind:"scalar",T:13},{no:3,name:"max_participants",kind:"scalar",T:13},{no:4,name:"node_id",kind:"scalar",T:9},{no:5,name:"metadata",kind:"scalar",T:9},{no:6,name:"egress",kind:"message",T:zt},{no:7,name:"min_playout_delay",kind:"scalar",T:13},{no:8,name:"max_playout_delay",kind:"scalar",T:13},{no:9,name:"sync_streams",kind:"scalar",T:8}]));const zt=Re.makeMessageType("livekit.RoomEgress",(()=>[{no:1,name:"room",kind:"message",T:Et},{no:3,name:"participant",kind:"message",T:Ht},{no:2,name:"tracks",kind:"message",T:Jt}]));Re.makeMessageType("livekit.ListRoomsRequest",(()=>[{no:1,name:"names",kind:"scalar",T:9,repeated:!0}])),Re.makeMessageType("livekit.ListRoomsResponse",(()=>[{no:1,name:"rooms",kind:"message",T:We,repeated:!0}])),Re.makeMessageType("livekit.DeleteRoomRequest",(()=>[{no:1,name:"room",kind:"scalar",T:9}])),Re.makeMessageType("livekit.DeleteRoomResponse",[]),Re.makeMessageType("livekit.ListParticipantsRequest",(()=>[{no:1,name:"room",kind:"scalar",T:9}])),Re.makeMessageType("livekit.ListParticipantsResponse",(()=>[{no:1,name:"participants",kind:"message",T:ze,repeated:!0}])),Re.makeMessageType("livekit.RoomParticipantIdentity",(()=>[{no:1,name:"room",kind:"scalar",T:9},{no:2,name:"identity",kind:"scalar",T:9}])),Re.makeMessageType("livekit.RemoveParticipantResponse",[]),Re.makeMessageType("livekit.MuteRoomTrackRequest",(()=>[{no:1,name:"room",kind:"scalar",T:9},{no:2,name:"identity",kind:"scalar",T:9},{no:3,name:"track_sid",kind:"scalar",T:9},{no:4,name:"muted",kind:"scalar",T:8}])),Re.makeMessageType("livekit.MuteRoomTrackResponse",(()=>[{no:1,name:"track",kind:"message",T:$e}])),Re.makeMessageType("livekit.UpdateParticipantRequest",(()=>[{no:1,name:"room",kind:"scalar",T:9},{no:2,name:"identity",kind:"scalar",T:9},{no:3,name:"metadata",kind:"scalar",T:9},{no:4,name:"permission",kind:"message",T:Je},{no:5,name:"name",kind:"scalar",T:9}])),Re.makeMessageType("livekit.UpdateSubscriptionsRequest",(()=>[{no:1,name:"room",kind:"scalar",T:9},{no:2,name:"identity",kind:"scalar",T:9},{no:3,name:"track_sids",kind:"scalar",T:9,repeated:!0},{no:4,name:"subscribe",kind:"scalar",T:8},{no:5,name:"participant_tracks",kind:"message",T:rt,repeated:!0}])),Re.makeMessageType("livekit.UpdateSubscriptionsResponse",[]),Re.makeMessageType("livekit.SendDataRequest",(()=>[{no:1,name:"room",kind:"scalar",T:9},{no:2,name:"data",kind:"scalar",T:12},{no:3,name:"kind",kind:"enum",T:Re.getEnumType(nt)},{no:4,name:"destination_sids",kind:"scalar",T:9,repeated:!0},{no:6,name:"destination_identities",kind:"scalar",T:9,repeated:!0},{no:5,name:"topic",kind:"scalar",T:9,opt:!0}])),Re.makeMessageType("livekit.SendDataResponse",[]),Re.makeMessageType("livekit.UpdateRoomMetadataRequest",(()=>[{no:1,name:"room",kind:"scalar",T:9},{no:2,name:"metadata",kind:"scalar",T:9}]));const Qt=Re.makeEnum("livekit.JobType",[{no:0,name:"JT_ROOM"},{no:1,name:"JT_PUBLISHER"}]),Yt=Re.makeEnum("livekit.WorkerStatus",[{no:0,name:"WS_AVAILABLE"},{no:1,name:"WS_FULL"}]),Xt=Re.makeEnum("livekit.JobStatus",[{no:0,name:"JS_UNKNOWN"},{no:1,name:"JS_SUCCESS"},{no:2,name:"JS_FAILED"}]);Re.makeMessageType("livekit.AgentInfo",(()=>[{no:1,name:"id",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",T:9},{no:3,name:"version",kind:"scalar",T:9}]));const Zt=Re.makeMessageType("livekit.Job",(()=>[{no:1,name:"id",kind:"scalar",T:9},{no:2,name:"type",kind:"enum",T:Re.getEnumType(Qt)},{no:3,name:"room",kind:"message",T:We},{no:4,name:"participant",kind:"message",T:ze,opt:!0}]));Re.makeMessageType("livekit.WorkerMessage",(()=>[{no:1,name:"register",kind:"message",T:$t,oneof:"message"},{no:2,name:"availability",kind:"message",T:nn,oneof:"message"},{no:3,name:"status",kind:"message",T:an,oneof:"message"},{no:4,name:"job_update",kind:"message",T:sn,oneof:"message"}])),Re.makeMessageType("livekit.ServerMessage",(()=>[{no:1,name:"register",kind:"message",T:en,oneof:"message"},{no:2,name:"availability",kind:"message",T:tn,oneof:"message"},{no:3,name:"assignment",kind:"message",T:on,oneof:"message"}]));const $t=Re.makeMessageType("livekit.RegisterWorkerRequest",(()=>[{no:1,name:"type",kind:"enum",T:Re.getEnumType(Qt)},{no:2,name:"worker_id",kind:"scalar",T:9},{no:3,name:"version",kind:"scalar",T:9},{no:4,name:"name",kind:"scalar",T:9}])),en=Re.makeMessageType("livekit.RegisterWorkerResponse",(()=>[{no:1,name:"worker_id",kind:"scalar",T:9},{no:2,name:"server_version",kind:"scalar",T:9}])),tn=Re.makeMessageType("livekit.AvailabilityRequest",(()=>[{no:1,name:"job",kind:"message",T:Zt}])),nn=Re.makeMessageType("livekit.AvailabilityResponse",(()=>[{no:1,name:"job_id",kind:"scalar",T:9},{no:2,name:"available",kind:"scalar",T:8}])),sn=Re.makeMessageType("livekit.JobStatusUpdate",(()=>[{no:1,name:"job_id",kind:"scalar",T:9},{no:2,name:"status",kind:"enum",T:Re.getEnumType(Xt)},{no:3,name:"error",kind:"scalar",T:9},{no:4,name:"user_data",kind:"scalar",T:9}])),on=Re.makeMessageType("livekit.JobAssignment",(()=>[{no:1,name:"job",kind:"message",T:Zt}])),an=Re.makeMessageType("livekit.UpdateWorkerStatus",(()=>[{no:1,name:"status",kind:"enum",T:Re.getEnumType(Yt)}])),rn=Re.makeEnum("livekit.SignalTarget",[{no:0,name:"PUBLISHER"},{no:1,name:"SUBSCRIBER"}]),cn=Re.makeEnum("livekit.StreamState",[{no:0,name:"ACTIVE"},{no:1,name:"PAUSED"}]),dn=Re.makeEnum("livekit.CandidateProtocol",[{no:0,name:"UDP"},{no:1,name:"TCP"},{no:2,name:"TLS"}]),ln=Re.makeMessageType("livekit.SignalRequest",(()=>[{no:1,name:"offer",kind:"message",T:yn,oneof:"message"},{no:2,name:"answer",kind:"message",T:yn,oneof:"message"},{no:3,name:"trickle",kind:"message",T:pn,oneof:"message"},{no:4,name:"add_track",kind:"message",T:mn,oneof:"message"},{no:5,name:"mute",kind:"message",T:gn,oneof:"message"},{no:6,name:"subscription",kind:"message",T:Cn,oneof:"message"},{no:7,name:"track_setting",kind:"message",T:Sn,oneof:"message"},{no:8,name:"leave",kind:"message",T:En,oneof:"message"},{no:10,name:"update_layers",kind:"message",T:Pn,oneof:"message"},{no:11,name:"subscription_permission",kind:"message",T:Fn,oneof:"message"},{no:12,name:"sync_state",kind:"message",T:Vn,oneof:"message"},{no:13,name:"simulate",kind:"message",T:Kn,oneof:"message"},{no:14,name:"ping",kind:"scalar",T:3,oneof:"message"},{no:15,name:"update_metadata",kind:"message",T:Rn,oneof:"message"},{no:16,name:"ping_req",kind:"message",T:Gn,oneof:"message"}])),un=Re.makeMessageType("livekit.SignalResponse",(()=>[{no:1,name:"join",kind:"message",T:fn,oneof:"message"},{no:2,name:"answer",kind:"message",T:yn,oneof:"message"},{no:3,name:"offer",kind:"message",T:yn,oneof:"message"},{no:4,name:"trickle",kind:"message",T:pn,oneof:"message"},{no:5,name:"update",kind:"message",T:bn,oneof:"message"},{no:6,name:"track_published",kind:"message",T:kn,oneof:"message"},{no:8,name:"leave",kind:"message",T:En,oneof:"message"},{no:9,name:"mute",kind:"message",T:gn,oneof:"message"},{no:10,name:"speakers_changed",kind:"message",T:In,oneof:"message"},{no:11,name:"room_update",kind:"message",T:On,oneof:"message"},{no:12,name:"connection_quality",kind:"message",T:xn,oneof:"message"},{no:13,name:"stream_state_update",kind:"message",T:Nn,oneof:"message"},{no:14,name:"subscribed_quality_update",kind:"message",T:Un,oneof:"message"},{no:15,name:"subscription_permission_update",kind:"message",T:Bn,oneof:"message"},{no:16,name:"refresh_token",kind:"scalar",T:9,oneof:"message"},{no:17,name:"track_unpublished",kind:"message",T:Tn,oneof:"message"},{no:18,name:"pong",kind:"scalar",T:3,oneof:"message"},{no:19,name:"reconnect",kind:"message",T:vn,oneof:"message"},{no:20,name:"pong_resp",kind:"message",T:Wn,oneof:"message"},{no:21,name:"subscription_response",kind:"message",T:zn,oneof:"message"}])),hn=Re.makeMessageType("livekit.SimulcastCodec",(()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"cid",kind:"scalar",T:9}])),mn=Re.makeMessageType("livekit.AddTrackRequest",(()=>[{no:1,name:"cid",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",T:9},{no:3,name:"type",kind:"enum",T:Re.getEnumType(Ue)},{no:4,name:"width",kind:"scalar",T:13},{no:5,name:"height",kind:"scalar",T:13},{no:6,name:"muted",kind:"scalar",T:8},{no:7,name:"disable_dtx",kind:"scalar",T:8},{no:8,name:"source",kind:"enum",T:Re.getEnumType(je)},{no:9,name:"layers",kind:"message",T:et,repeated:!0},{no:10,name:"simulcast_codecs",kind:"message",T:hn,repeated:!0},{no:11,name:"sid",kind:"scalar",T:9},{no:12,name:"stereo",kind:"scalar",T:8},{no:13,name:"disable_red",kind:"scalar",T:8},{no:14,name:"encryption",kind:"enum",T:Re.getEnumType(Xe)},{no:15,name:"stream",kind:"scalar",T:9}])),pn=Re.makeMessageType("livekit.TrickleRequest",(()=>[{no:1,name:"candidateInit",kind:"scalar",T:9},{no:2,name:"target",kind:"enum",T:Re.getEnumType(rn)}])),gn=Re.makeMessageType("livekit.MuteTrackRequest",(()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"muted",kind:"scalar",T:8}])),fn=Re.makeMessageType("livekit.JoinResponse",(()=>[{no:1,name:"room",kind:"message",T:We},{no:2,name:"participant",kind:"message",T:ze},{no:3,name:"other_participants",kind:"message",T:ze,repeated:!0},{no:4,name:"server_version",kind:"scalar",T:9},{no:5,name:"ice_servers",kind:"message",T:_n,repeated:!0},{no:6,name:"subscriber_primary",kind:"scalar",T:8},{no:7,name:"alternative_url",kind:"scalar",T:9},{no:8,name:"client_configuration",kind:"message",T:ht},{no:9,name:"server_region",kind:"scalar",T:9},{no:10,name:"ping_timeout",kind:"scalar",T:5},{no:11,name:"ping_interval",kind:"scalar",T:5},{no:12,name:"server_info",kind:"message",T:ct},{no:13,name:"sif_trailer",kind:"scalar",T:12}])),vn=Re.makeMessageType("livekit.ReconnectResponse",(()=>[{no:1,name:"ice_servers",kind:"message",T:_n,repeated:!0},{no:2,name:"client_configuration",kind:"message",T:ht}])),kn=Re.makeMessageType("livekit.TrackPublishedResponse",(()=>[{no:1,name:"cid",kind:"scalar",T:9},{no:2,name:"track",kind:"message",T:$e}])),Tn=Re.makeMessageType("livekit.TrackUnpublishedResponse",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9}])),yn=Re.makeMessageType("livekit.SessionDescription",(()=>[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"sdp",kind:"scalar",T:9}])),bn=Re.makeMessageType("livekit.ParticipantUpdate",(()=>[{no:1,name:"participants",kind:"message",T:ze,repeated:!0}])),Cn=Re.makeMessageType("livekit.UpdateSubscription",(()=>[{no:1,name:"track_sids",kind:"scalar",T:9,repeated:!0},{no:2,name:"subscribe",kind:"scalar",T:8},{no:3,name:"participant_tracks",kind:"message",T:rt,repeated:!0}])),Sn=Re.makeMessageType("livekit.UpdateTrackSettings",(()=>[{no:1,name:"track_sids",kind:"scalar",T:9,repeated:!0},{no:3,name:"disabled",kind:"scalar",T:8},{no:4,name:"quality",kind:"enum",T:Re.getEnumType(Fe)},{no:5,name:"width",kind:"scalar",T:13},{no:6,name:"height",kind:"scalar",T:13},{no:7,name:"fps",kind:"scalar",T:13},{no:8,name:"priority",kind:"scalar",T:13}])),En=Re.makeMessageType("livekit.LeaveRequest",(()=>[{no:1,name:"can_reconnect",kind:"scalar",T:8},{no:2,name:"reason",kind:"enum",T:Re.getEnumType(qe)},{no:3,name:"action",kind:"enum",T:Re.getEnumType(wn)},{no:4,name:"regions",kind:"message",T:Hn}])),wn=Re.makeEnum("livekit.LeaveRequest.Action",[{no:0,name:"DISCONNECT"},{no:1,name:"RESUME"},{no:2,name:"RECONNECT"}]),Pn=Re.makeMessageType("livekit.UpdateVideoLayers",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"layers",kind:"message",T:et,repeated:!0}])),Rn=Re.makeMessageType("livekit.UpdateParticipantMetadata",(()=>[{no:1,name:"metadata",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",T:9}])),_n=Re.makeMessageType("livekit.ICEServer",(()=>[{no:1,name:"urls",kind:"scalar",T:9,repeated:!0},{no:2,name:"username",kind:"scalar",T:9},{no:3,name:"credential",kind:"scalar",T:9}])),In=Re.makeMessageType("livekit.SpeakersChanged",(()=>[{no:1,name:"speakers",kind:"message",T:st,repeated:!0}])),On=Re.makeMessageType("livekit.RoomUpdate",(()=>[{no:1,name:"room",kind:"message",T:We}])),Mn=Re.makeMessageType("livekit.ConnectionQualityInfo",(()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"quality",kind:"enum",T:Re.getEnumType(Be)},{no:3,name:"score",kind:"scalar",T:2}])),xn=Re.makeMessageType("livekit.ConnectionQualityUpdate",(()=>[{no:1,name:"updates",kind:"message",T:Mn,repeated:!0}])),Dn=Re.makeMessageType("livekit.StreamStateInfo",(()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"track_sid",kind:"scalar",T:9},{no:3,name:"state",kind:"enum",T:Re.getEnumType(cn)}])),Nn=Re.makeMessageType("livekit.StreamStateUpdate",(()=>[{no:1,name:"stream_states",kind:"message",T:Dn,repeated:!0}])),Ln=Re.makeMessageType("livekit.SubscribedQuality",(()=>[{no:1,name:"quality",kind:"enum",T:Re.getEnumType(Fe)},{no:2,name:"enabled",kind:"scalar",T:8}])),An=Re.makeMessageType("livekit.SubscribedCodec",(()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"qualities",kind:"message",T:Ln,repeated:!0}])),Un=Re.makeMessageType("livekit.SubscribedQualityUpdate",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribed_qualities",kind:"message",T:Ln,repeated:!0},{no:3,name:"subscribed_codecs",kind:"message",T:An,repeated:!0}])),jn=Re.makeMessageType("livekit.TrackPermission",(()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"all_tracks",kind:"scalar",T:8},{no:3,name:"track_sids",kind:"scalar",T:9,repeated:!0},{no:4,name:"participant_identity",kind:"scalar",T:9}])),Fn=Re.makeMessageType("livekit.SubscriptionPermission",(()=>[{no:1,name:"all_participants",kind:"scalar",T:8},{no:2,name:"track_permissions",kind:"message",T:jn,repeated:!0}])),Bn=Re.makeMessageType("livekit.SubscriptionPermissionUpdate",(()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"track_sid",kind:"scalar",T:9},{no:3,name:"allowed",kind:"scalar",T:8}])),Vn=Re.makeMessageType("livekit.SyncState",(()=>[{no:1,name:"answer",kind:"message",T:yn},{no:2,name:"subscription",kind:"message",T:Cn},{no:3,name:"publish_tracks",kind:"message",T:kn,repeated:!0},{no:4,name:"data_channels",kind:"message",T:qn,repeated:!0},{no:5,name:"offer",kind:"message",T:yn},{no:6,name:"track_sids_disabled",kind:"scalar",T:9,repeated:!0}])),qn=Re.makeMessageType("livekit.DataChannelInfo",(()=>[{no:1,name:"label",kind:"scalar",T:9},{no:2,name:"id",kind:"scalar",T:13},{no:3,name:"target",kind:"enum",T:Re.getEnumType(rn)}])),Kn=Re.makeMessageType("livekit.SimulateScenario",(()=>[{no:1,name:"speaker_update",kind:"scalar",T:5,oneof:"scenario"},{no:2,name:"node_failure",kind:"scalar",T:8,oneof:"scenario"},{no:3,name:"migration",kind:"scalar",T:8,oneof:"scenario"},{no:4,name:"server_leave",kind:"scalar",T:8,oneof:"scenario"},{no:5,name:"switch_candidate_protocol",kind:"enum",T:Re.getEnumType(dn),oneof:"scenario"},{no:6,name:"subscriber_bandwidth",kind:"scalar",T:3,oneof:"scenario"},{no:7,name:"disconnect_signal_on_resume",kind:"scalar",T:8,oneof:"scenario"},{no:8,name:"disconnect_signal_on_resume_no_messages",kind:"scalar",T:8,oneof:"scenario"}])),Gn=Re.makeMessageType("livekit.Ping",(()=>[{no:1,name:"timestamp",kind:"scalar",T:3},{no:2,name:"rtt",kind:"scalar",T:3}])),Wn=Re.makeMessageType("livekit.Pong",(()=>[{no:1,name:"last_ping_timestamp",kind:"scalar",T:3},{no:2,name:"timestamp",kind:"scalar",T:3}])),Hn=Re.makeMessageType("livekit.RegionSettings",(()=>[{no:1,name:"regions",kind:"message",T:Jn,repeated:!0}])),Jn=Re.makeMessageType("livekit.RegionInfo",(()=>[{no:1,name:"region",kind:"scalar",T:9},{no:2,name:"url",kind:"scalar",T:9},{no:3,name:"distance",kind:"scalar",T:3}])),zn=Re.makeMessageType("livekit.SubscriptionResponse",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"err",kind:"enum",T:Re.getEnumType(Ge)}])),Qn=Re.makeEnum("livekit.IngressInput",[{no:0,name:"RTMP_INPUT"},{no:1,name:"WHIP_INPUT"},{no:2,name:"URL_INPUT"}]),Yn=Re.makeEnum("livekit.IngressAudioEncodingPreset",[{no:0,name:"OPUS_STEREO_96KBPS"},{no:1,name:"OPUS_MONO_64KBS"}]),Xn=Re.makeEnum("livekit.IngressVideoEncodingPreset",[{no:0,name:"H264_720P_30FPS_3_LAYERS"},{no:1,name:"H264_1080P_30FPS_3_LAYERS"},{no:2,name:"H264_540P_25FPS_2_LAYERS"},{no:3,name:"H264_720P_30FPS_1_LAYER"},{no:4,name:"H264_1080P_30FPS_1_LAYER"},{no:5,name:"H264_720P_30FPS_3_LAYERS_HIGH_MOTION"},{no:6,name:"H264_1080P_30FPS_3_LAYERS_HIGH_MOTION"},{no:7,name:"H264_540P_25FPS_2_LAYERS_HIGH_MOTION"},{no:8,name:"H264_720P_30FPS_1_LAYER_HIGH_MOTION"},{no:9,name:"H264_1080P_30FPS_1_LAYER_HIGH_MOTION"}]);Re.makeMessageType("livekit.CreateIngressRequest",(()=>[{no:1,name:"input_type",kind:"enum",T:Re.getEnumType(Qn)},{no:9,name:"url",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",T:9},{no:3,name:"room_name",kind:"scalar",T:9},{no:4,name:"participant_identity",kind:"scalar",T:9},{no:5,name:"participant_name",kind:"scalar",T:9},{no:10,name:"participant_metadata",kind:"scalar",T:9},{no:8,name:"bypass_transcoding",kind:"scalar",T:8},{no:6,name:"audio",kind:"message",T:Zn},{no:7,name:"video",kind:"message",T:$n}]));const Zn=Re.makeMessageType("livekit.IngressAudioOptions",(()=>[{no:1,name:"name",kind:"scalar",T:9},{no:2,name:"source",kind:"enum",T:Re.getEnumType(je)},{no:3,name:"preset",kind:"enum",T:Re.getEnumType(Yn),oneof:"encoding_options"},{no:4,name:"options",kind:"message",T:ei,oneof:"encoding_options"}])),$n=Re.makeMessageType("livekit.IngressVideoOptions",(()=>[{no:1,name:"name",kind:"scalar",T:9},{no:2,name:"source",kind:"enum",T:Re.getEnumType(je)},{no:3,name:"preset",kind:"enum",T:Re.getEnumType(Xn),oneof:"encoding_options"},{no:4,name:"options",kind:"message",T:ti,oneof:"encoding_options"}])),ei=Re.makeMessageType("livekit.IngressAudioEncodingOptions",(()=>[{no:1,name:"audio_codec",kind:"enum",T:Re.getEnumType(Ne)},{no:2,name:"bitrate",kind:"scalar",T:13},{no:3,name:"disable_dtx",kind:"scalar",T:8},{no:4,name:"channels",kind:"scalar",T:13}])),ti=Re.makeMessageType("livekit.IngressVideoEncodingOptions",(()=>[{no:1,name:"video_codec",kind:"enum",T:Re.getEnumType(Le)},{no:2,name:"frame_rate",kind:"scalar",T:1},{no:3,name:"layers",kind:"message",T:et,repeated:!0}])),ni=Re.makeMessageType("livekit.IngressInfo",(()=>[{no:1,name:"ingress_id",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",T:9},{no:3,name:"stream_key",kind:"scalar",T:9},{no:4,name:"url",kind:"scalar",T:9},{no:5,name:"input_type",kind:"enum",T:Re.getEnumType(Qn)},{no:13,name:"bypass_transcoding",kind:"scalar",T:8},{no:6,name:"audio",kind:"message",T:Zn},{no:7,name:"video",kind:"message",T:$n},{no:8,name:"room_name",kind:"scalar",T:9},{no:9,name:"participant_identity",kind:"scalar",T:9},{no:10,name:"participant_name",kind:"scalar",T:9},{no:14,name:"participant_metadata",kind:"scalar",T:9},{no:11,name:"reusable",kind:"scalar",T:8},{no:12,name:"state",kind:"message",T:ii}])),ii=Re.makeMessageType("livekit.IngressState",(()=>[{no:1,name:"status",kind:"enum",T:Re.getEnumType(si)},{no:2,name:"error",kind:"scalar",T:9},{no:3,name:"video",kind:"message",T:oi},{no:4,name:"audio",kind:"message",T:ai},{no:5,name:"room_id",kind:"scalar",T:9},{no:7,name:"started_at",kind:"scalar",T:3},{no:8,name:"ended_at",kind:"scalar",T:3},{no:9,name:"resource_id",kind:"scalar",T:9},{no:6,name:"tracks",kind:"message",T:$e,repeated:!0}])),si=Re.makeEnum("livekit.IngressState.Status",[{no:0,name:"ENDPOINT_INACTIVE"},{no:1,name:"ENDPOINT_BUFFERING"},{no:2,name:"ENDPOINT_PUBLISHING"},{no:3,name:"ENDPOINT_ERROR"},{no:4,name:"ENDPOINT_COMPLETE"}]),oi=Re.makeMessageType("livekit.InputVideoState",(()=>[{no:1,name:"mime_type",kind:"scalar",T:9},{no:2,name:"average_bitrate",kind:"scalar",T:13},{no:3,name:"width",kind:"scalar",T:13},{no:4,name:"height",kind:"scalar",T:13},{no:5,name:"framerate",kind:"scalar",T:1}])),ai=Re.makeMessageType("livekit.InputAudioState",(()=>[{no:1,name:"mime_type",kind:"scalar",T:9},{no:2,name:"average_bitrate",kind:"scalar",T:13},{no:3,name:"channels",kind:"scalar",T:13},{no:4,name:"sample_rate",kind:"scalar",T:13}]));Re.makeMessageType("livekit.UpdateIngressRequest",(()=>[{no:1,name:"ingress_id",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",T:9},{no:3,name:"room_name",kind:"scalar",T:9},{no:4,name:"participant_identity",kind:"scalar",T:9},{no:5,name:"participant_name",kind:"scalar",T:9},{no:9,name:"participant_metadata",kind:"scalar",T:9},{no:8,name:"bypass_transcoding",kind:"scalar",T:8,opt:!0},{no:6,name:"audio",kind:"message",T:Zn},{no:7,name:"video",kind:"message",T:$n}])),Re.makeMessageType("livekit.ListIngressRequest",(()=>[{no:1,name:"room_name",kind:"scalar",T:9},{no:2,name:"ingress_id",kind:"scalar",T:9}])),Re.makeMessageType("livekit.ListIngressResponse",(()=>[{no:1,name:"items",kind:"message",T:ni,repeated:!0}])),Re.makeMessageType("livekit.DeleteIngressRequest",(()=>[{no:1,name:"ingress_id",kind:"scalar",T:9}])),Re.makeMessageType("livekit.WebhookEvent",(()=>[{no:1,name:"event",kind:"scalar",T:9},{no:2,name:"room",kind:"message",T:We},{no:3,name:"participant",kind:"message",T:ze},{no:9,name:"egress_info",kind:"message",T:Ft},{no:10,name:"ingress_info",kind:"message",T:ni},{no:8,name:"track",kind:"message",T:$e},{no:6,name:"id",kind:"scalar",T:9},{no:7,name:"created_at",kind:"scalar",T:3},{no:11,name:"num_dropped",kind:"scalar",T:5}])),Re.makeMessageType("livekit.CreateSIPTrunkRequest",(()=>[{no:1,name:"inbound_addresses",kind:"scalar",T:9,repeated:!0},{no:2,name:"outbound_address",kind:"scalar",T:9},{no:3,name:"outbound_number",kind:"scalar",T:9},{no:4,name:"inbound_numbers_regex",kind:"scalar",T:9,repeated:!0},{no:9,name:"inbound_numbers",kind:"scalar",T:9,repeated:!0},{no:5,name:"inbound_username",kind:"scalar",T:9},{no:6,name:"inbound_password",kind:"scalar",T:9},{no:7,name:"outbound_username",kind:"scalar",T:9},{no:8,name:"outbound_password",kind:"scalar",T:9}]));const ri=Re.makeMessageType("livekit.SIPTrunkInfo",(()=>[{no:1,name:"sip_trunk_id",kind:"scalar",T:9},{no:2,name:"inbound_addresses",kind:"scalar",T:9,repeated:!0},{no:3,name:"outbound_address",kind:"scalar",T:9},{no:4,name:"outbound_number",kind:"scalar",T:9},{no:5,name:"inbound_numbers_regex",kind:"scalar",T:9,repeated:!0},{no:10,name:"inbound_numbers",kind:"scalar",T:9,repeated:!0},{no:6,name:"inbound_username",kind:"scalar",T:9},{no:7,name:"inbound_password",kind:"scalar",T:9},{no:8,name:"outbound_username",kind:"scalar",T:9},{no:9,name:"outbound_password",kind:"scalar",T:9}]));Re.makeMessageType("livekit.ListSIPTrunkRequest",[]),Re.makeMessageType("livekit.ListSIPTrunkResponse",(()=>[{no:1,name:"items",kind:"message",T:ri,repeated:!0}])),Re.makeMessageType("livekit.DeleteSIPTrunkRequest",(()=>[{no:1,name:"sip_trunk_id",kind:"scalar",T:9}]));const ci=Re.makeMessageType("livekit.SIPDispatchRuleDirect",(()=>[{no:1,name:"room_name",kind:"scalar",T:9},{no:2,name:"pin",kind:"scalar",T:9}])),di=Re.makeMessageType("livekit.SIPDispatchRuleIndividual",(()=>[{no:1,name:"room_prefix",kind:"scalar",T:9},{no:2,name:"pin",kind:"scalar",T:9}])),li=Re.makeMessageType("livekit.SIPDispatchRule",(()=>[{no:1,name:"dispatch_rule_direct",kind:"message",T:ci,oneof:"rule"},{no:2,name:"dispatch_rule_individual",kind:"message",T:di,oneof:"rule"}]));Re.makeMessageType("livekit.CreateSIPDispatchRuleRequest",(()=>[{no:1,name:"rule",kind:"message",T:li},{no:2,name:"trunk_ids",kind:"scalar",T:9,repeated:!0},{no:3,name:"hide_phone_number",kind:"scalar",T:8}]));const ui=Re.makeMessageType("livekit.SIPDispatchRuleInfo",(()=>[{no:1,name:"sip_dispatch_rule_id",kind:"scalar",T:9},{no:2,name:"rule",kind:"message",T:li},{no:3,name:"trunk_ids",kind:"scalar",T:9,repeated:!0},{no:4,name:"hide_phone_number",kind:"scalar",T:8}]));Re.makeMessageType("livekit.ListSIPDispatchRuleRequest",[]),Re.makeMessageType("livekit.ListSIPDispatchRuleResponse",(()=>[{no:1,name:"items",kind:"message",T:ui,repeated:!0}])),Re.makeMessageType("livekit.DeleteSIPDispatchRuleRequest",(()=>[{no:1,name:"sip_dispatch_rule_id",kind:"scalar",T:9}])),Re.makeMessageType("livekit.CreateSIPParticipantRequest",(()=>[{no:1,name:"sip_trunk_id",kind:"scalar",T:9},{no:2,name:"sip_call_to",kind:"scalar",T:9},{no:3,name:"room_name",kind:"scalar",T:9},{no:4,name:"participant_identity",kind:"scalar",T:9}])),Re.makeMessageType("livekit.SIPParticipantInfo",(()=>[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"participant_identity",kind:"scalar",T:9},{no:3,name:"room_name",kind:"scalar",T:9}]));var hi="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function mi(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var pi={exports:{}};!function(e){var t,n;t=hi,n=function(){var e=function(){},t="undefined",n=typeof window!==t&&typeof window.navigator!==t&&/Trident\/|MSIE /.test(window.navigator.userAgent),i=["trace","debug","info","warn","error"];function s(e,t){var n=e[t];if("function"==typeof n.bind)return n.bind(e);try{return Function.prototype.bind.call(n,e)}catch(t){return function(){return Function.prototype.apply.apply(n,[e,arguments])}}}function o(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function a(t,n){for(var s=0;s<i.length;s++){var o=i[s];this[o]=s<t?e:this.methodFactory(o,t,n)}this.log=this.debug}function r(e,n,i){return function(){typeof console!==t&&(a.call(this,n,i),this[e].apply(this,arguments))}}function c(i,a,c){return function(i){return"debug"===i&&(i="log"),typeof console!==t&&("trace"===i&&n?o:void 0!==console[i]?s(console,i):void 0!==console.log?s(console,"log"):e)}(i)||r.apply(this,arguments)}function d(e,n,s){var o,r=this;n=null==n?"WARN":n;var d="loglevel";function l(){var e;if(typeof window!==t&&d){try{e=window.localStorage[d]}catch(e){}if(typeof e===t)try{var n=window.document.cookie,i=n.indexOf(encodeURIComponent(d)+"=");-1!==i&&(e=/^([^;]+)/.exec(n.slice(i))[1])}catch(e){}return void 0===r.levels[e]&&(e=void 0),e}}"string"==typeof e?d+=":"+e:"symbol"==typeof e&&(d=void 0),r.name=e,r.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},r.methodFactory=s||c,r.getLevel=function(){return o},r.setLevel=function(n,s){if("string"==typeof n&&void 0!==r.levels[n.toUpperCase()]&&(n=r.levels[n.toUpperCase()]),!("number"==typeof n&&n>=0&&n<=r.levels.SILENT))throw"log.setLevel() called with invalid level: "+n;if(o=n,!1!==s&&function(e){var n=(i[e]||"silent").toUpperCase();if(typeof window!==t&&d){try{return void(window.localStorage[d]=n)}catch(e){}try{window.document.cookie=encodeURIComponent(d)+"="+n+";"}catch(e){}}}(n),a.call(r,n,e),typeof console===t&&n<r.levels.SILENT)return"No console available for logging"},r.setDefaultLevel=function(e){n=e,l()||r.setLevel(e,!1)},r.resetLevel=function(){r.setLevel(n,!1),function(){if(typeof window!==t&&d){try{return void window.localStorage.removeItem(d)}catch(e){}try{window.document.cookie=encodeURIComponent(d)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch(e){}}}()},r.enableAll=function(e){r.setLevel(r.levels.TRACE,e)},r.disableAll=function(e){r.setLevel(r.levels.SILENT,e)};var u=l();null==u&&(u=n),r.setLevel(u,!1)}var l=new d,u={};l.getLogger=function(e){if("symbol"!=typeof e&&"string"!=typeof e||""===e)throw new TypeError("You must supply a name when creating a logger.");var t=u[e];return t||(t=u[e]=new d(e,l.getLevel(),l.methodFactory)),t};var h=typeof window!==t?window.log:void 0;return l.noConflict=function(){return typeof window!==t&&window.log===l&&(window.log=h),l},l.getLoggers=function(){return u},l.default=l,l},e.exports?e.exports=n():t.log=n()}(pi);var gi,fi,vi=pi.exports;e.LogLevel=void 0,(gi=e.LogLevel||(e.LogLevel={}))[gi.trace=0]="trace",gi[gi.debug=1]="debug",gi[gi.info=2]="info",gi[gi.warn=3]="warn",gi[gi.error=4]="error",gi[gi.silent=5]="silent",e.LoggerNames=void 0,(fi=e.LoggerNames||(e.LoggerNames={})).Default="livekit",fi.Room="livekit-room",fi.Participant="livekit-participant",fi.Track="livekit-track",fi.Publication="livekit-track-publication",fi.Engine="livekit-engine",fi.Signal="livekit-signal",fi.PCManager="livekit-pc-manager",fi.PCTransport="livekit-pc-transport",fi.E2EE="lk-e2ee";let ki=vi.getLogger("livekit");const Ti=Object.values(e.LoggerNames).map((e=>vi.getLogger(e)));function yi(e){const t=vi.getLogger(e);return t.setDefaultLevel(ki.getLevel()),t}ki.setDefaultLevel(e.LogLevel.info);const bi=vi.getLogger("lk-e2ee"),Ci=7e3,Si=[0,300,1200,2700,4800,Ci,Ci,Ci,Ci,Ci];class Ei{constructor(e){this._retryDelays=void 0!==e?[...e]:Si}nextRetryDelayInMs(e){if(e.retryCount>=this._retryDelays.length)return null;const t=this._retryDelays[e.retryCount];return e.retryCount<=1?t:t+1e3*Math.random()}}function wi(e,t,n,i){return new(n||(n=Promise))((function(s,o){function a(e){try{c(i.next(e))}catch(e){o(e)}}function r(e){try{c(i.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?s(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(a,r)}c((i=i.apply(e,t||[])).next())}))}function Pi(e){var t="function"==typeof Symbol&&Symbol.iterator,n=t&&e[t],i=0;if(n)return n.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&i>=e.length&&(e=void 0),{value:e&&e[i++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function Ri(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t,n=e[Symbol.asyncIterator];return n?n.call(e):(e=Pi(e),t={},i("next"),i("throw"),i("return"),t[Symbol.asyncIterator]=function(){return this},t);function i(n){t[n]=e[n]&&function(t){return new Promise((function(i,s){(function(e,t,n,i){Promise.resolve(i).then((function(t){e({value:t,done:n})}),t)})(i,s,(t=e[n](t)).done,t.value)}))}}}"function"==typeof SuppressedError&&SuppressedError;var _i,Ii={exports:{}},Oi="object"==typeof Reflect?Reflect:null,Mi=Oi&&"function"==typeof Oi.apply?Oi.apply:function(e,t,n){return Function.prototype.apply.call(e,t,n)};_i=Oi&&"function"==typeof Oi.ownKeys?Oi.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var xi=Number.isNaN||function(e){return e!=e};function Di(){Di.init.call(this)}Ii.exports=Di,Ii.exports.once=function(e,t){return new Promise((function(n,i){function s(n){e.removeListener(t,o),i(n)}function o(){"function"==typeof e.removeListener&&e.removeListener("error",s),n([].slice.call(arguments))}Ki(e,t,o,{once:!0}),"error"!==t&&function(e,t,n){"function"==typeof e.on&&Ki(e,"error",t,n)}(e,s,{once:!0})}))},Di.EventEmitter=Di,Di.prototype._events=void 0,Di.prototype._eventsCount=0,Di.prototype._maxListeners=void 0;var Ni=10;function Li(e){if("function"!=typeof e)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function Ai(e){return void 0===e._maxListeners?Di.defaultMaxListeners:e._maxListeners}function Ui(e,t,n,i){var s,o,a,r;if(Li(n),void 0===(o=e._events)?(o=e._events=Object.create(null),e._eventsCount=0):(void 0!==o.newListener&&(e.emit("newListener",t,n.listener?n.listener:n),o=e._events),a=o[t]),void 0===a)a=o[t]=n,++e._eventsCount;else if("function"==typeof a?a=o[t]=i?[n,a]:[a,n]:i?a.unshift(n):a.push(n),(s=Ai(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,r=c,console&&console.warn&&console.warn(r)}return e}function ji(){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 Fi(e,t,n){var i={fired:!1,wrapFn:void 0,target:e,type:t,listener:n},s=ji.bind(i);return s.listener=n,i.wrapFn=s,s}function Bi(e,t,n){var i=e._events;if(void 0===i)return[];var s=i[t];return void 0===s?[]:"function"==typeof s?n?[s.listener||s]:[s]:n?function(e){for(var t=new Array(e.length),n=0;n<t.length;++n)t[n]=e[n].listener||e[n];return t}(s):qi(s,s.length)}function Vi(e){var t=this._events;if(void 0!==t){var n=t[e];if("function"==typeof n)return 1;if(void 0!==n)return n.length}return 0}function qi(e,t){for(var n=new Array(t),i=0;i<t;++i)n[i]=e[i];return n}function Ki(e,t,n,i){if("function"==typeof e.on)i.once?e.once(t,n):e.on(t,n);else{if("function"!=typeof e.addEventListener)throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof e);e.addEventListener(t,(function s(o){i.once&&e.removeEventListener(t,s),n(o)}))}}Object.defineProperty(Di,"defaultMaxListeners",{enumerable:!0,get:function(){return Ni},set:function(e){if("number"!=typeof e||e<0||xi(e))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+e+".");Ni=e}}),Di.init=function(){void 0!==this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},Di.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||xi(e))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this},Di.prototype.getMaxListeners=function(){return Ai(this)},Di.prototype.emit=function(e){for(var t=[],n=1;n<arguments.length;n++)t.push(arguments[n]);var i="error"===e,s=this._events;if(void 0!==s)i=i&&void 0===s.error;else if(!i)return!1;if(i){var o;if(t.length>0&&(o=t[0]),o instanceof Error)throw o;var a=new Error("Unhandled error."+(o?" ("+o.message+")":""));throw a.context=o,a}var r=s[e];if(void 0===r)return!1;if("function"==typeof r)Mi(r,this,t);else{var c=r.length,d=qi(r,c);for(n=0;n<c;++n)Mi(d[n],this,t)}return!0},Di.prototype.addListener=function(e,t){return Ui(this,e,t,!1)},Di.prototype.on=Di.prototype.addListener,Di.prototype.prependListener=function(e,t){return Ui(this,e,t,!0)},Di.prototype.once=function(e,t){return Li(t),this.on(e,Fi(this,e,t)),this},Di.prototype.prependOnceListener=function(e,t){return Li(t),this.prependListener(e,Fi(this,e,t)),this},Di.prototype.removeListener=function(e,t){var n,i,s,o,a;if(Li(t),void 0===(i=this._events))return this;if(void 0===(n=i[e]))return this;if(n===t||n.listener===t)0==--this._eventsCount?this._events=Object.create(null):(delete i[e],i.removeListener&&this.emit("removeListener",e,n.listener||t));else if("function"!=typeof n){for(s=-1,o=n.length-1;o>=0;o--)if(n[o]===t||n[o].listener===t){a=n[o].listener,s=o;break}if(s<0)return this;0===s?n.shift():function(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}(n,s),1===n.length&&(i[e]=n[0]),void 0!==i.removeListener&&this.emit("removeListener",e,a||t)}return this},Di.prototype.off=Di.prototype.removeListener,Di.prototype.removeAllListeners=function(e){var t,n,i;if(void 0===(n=this._events))return this;if(void 0===n.removeListener)return 0===arguments.length?(this._events=Object.create(null),this._eventsCount=0):void 0!==n[e]&&(0==--this._eventsCount?this._events=Object.create(null):delete n[e]),this;if(0===arguments.length){var s,o=Object.keys(n);for(i=0;i<o.length;++i)"removeListener"!==(s=o[i])&&this.removeAllListeners(s);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if("function"==typeof(t=n[e]))this.removeListener(e,t);else if(void 0!==t)for(i=t.length-1;i>=0;i--)this.removeListener(e,t[i]);return this},Di.prototype.listeners=function(e){return Bi(this,e,!0)},Di.prototype.rawListeners=function(e){return Bi(this,e,!1)},Di.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):Vi.call(e,t)},Di.prototype.listenerCount=Vi,Di.prototype.eventNames=function(){return this._eventsCount>0?_i(this._events):[]};var Gi=Ii.exports;let Wi=!0,Hi=!0;function Ji(e,t,n){const i=e.match(t);return i&&i.length>=n&&parseInt(i[n],10)}function zi(e,t,n){if(!e.RTCPeerConnection)return;const i=e.RTCPeerConnection.prototype,s=i.addEventListener;i.addEventListener=function(e,i){if(e!==t)return s.apply(this,arguments);const o=e=>{const t=n(e);t&&(i.handleEvent?i.handleEvent(t):i(t))};return this._eventMap=this._eventMap||{},this._eventMap[t]||(this._eventMap[t]=new Map),this._eventMap[t].set(i,o),s.apply(this,[e,o])};const o=i.removeEventListener;i.removeEventListener=function(e,n){if(e!==t||!this._eventMap||!this._eventMap[t])return o.apply(this,arguments);if(!this._eventMap[t].has(n))return o.apply(this,arguments);const i=this._eventMap[t].get(n);return this._eventMap[t].delete(n),0===this._eventMap[t].size&&delete this._eventMap[t],0===Object.keys(this._eventMap).length&&delete this._eventMap,o.apply(this,[e,i])},Object.defineProperty(i,"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 Qi(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(Wi=e,e?"adapter.js logging disabled":"adapter.js logging enabled")}function Yi(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(Hi=!e,"adapter.js deprecation warnings "+(e?"disabled":"enabled"))}function Xi(){if("object"==typeof window){if(Wi)return;"undefined"!=typeof console&&"function"==typeof console.log&&console.log.apply(console,arguments)}}function Zi(e,t){Hi&&console.warn(e+" is deprecated, please use "+t+" instead.")}function $i(e){return"[object Object]"===Object.prototype.toString.call(e)}function es(e){return $i(e)?Object.keys(e).reduce((function(t,n){const i=$i(e[n]),s=i?es(e[n]):e[n],o=i&&!Object.keys(s).length;return void 0===s||o?t:Object.assign(t,{[n]:s})}),{}):e}function ts(e,t,n){t&&!n.has(t.id)&&(n.set(t.id,t),Object.keys(t).forEach((i=>{i.endsWith("Id")?ts(e,e.get(t[i]),n):i.endsWith("Ids")&&t[i].forEach((t=>{ts(e,e.get(t),n)}))})))}function ns(e,t,n){const i=n?"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((n=>{n.type===i&&n.trackId===t.id&&ts(e,n,s)}))})),s}const is=Xi;function ss(e,t){const n=e&&e.navigator;if(!n.mediaDevices)return;const i=function(e){if("object"!=typeof e||e.mandatory||e.optional)return e;const t={};return Object.keys(e).forEach((n=>{if("require"===n||"advanced"===n||"mediaSource"===n)return;const i="object"==typeof e[n]?e[n]:{ideal:e[n]};void 0!==i.exact&&"number"==typeof i.exact&&(i.min=i.max=i.exact);const s=function(e,t){return e?e+t.charAt(0).toUpperCase()+t.slice(1):"deviceId"===t?"sourceId":t};if(void 0!==i.ideal){t.optional=t.optional||[];let e={};"number"==typeof i.ideal?(e[s("min",n)]=i.ideal,t.optional.push(e),e={},e[s("max",n)]=i.ideal,t.optional.push(e)):(e[s("",n)]=i.ideal,t.optional.push(e))}void 0!==i.exact&&"number"!=typeof i.exact?(t.mandatory=t.mandatory||{},t.mandatory[s("",n)]=i.exact):["min","max"].forEach((e=>{void 0!==i[e]&&(t.mandatory=t.mandatory||{},t.mandatory[s(e,n)]=i[e])}))})),e.advanced&&(t.optional=(t.optional||[]).concat(e.advanced)),t},s=function(e,s){if(t.version>=61)return s(e);if((e=JSON.parse(JSON.stringify(e)))&&"object"==typeof e.audio){const t=function(e,t,n){t in e&&!(n in e)&&(e[n]=e[t],delete e[t])};t((e=JSON.parse(JSON.stringify(e))).audio,"autoGainControl","googAutoGainControl"),t(e.audio,"noiseSuppression","googNoiseSuppression"),e.audio=i(e.audio)}if(e&&"object"==typeof e.video){let o=e.video.facingMode;o=o&&("object"==typeof o?o:{ideal:o});const a=t.version<66;if(o&&("user"===o.exact||"environment"===o.exact||"user"===o.ideal||"environment"===o.ideal)&&(!n.mediaDevices.getSupportedConstraints||!n.mediaDevices.getSupportedConstraints().facingMode||a)){let t;if(delete e.video.facingMode,"environment"===o.exact||"environment"===o.ideal?t=["back","rear"]:"user"!==o.exact&&"user"!==o.ideal||(t=["front"]),t)return n.mediaDevices.enumerateDevices().then((n=>{let a=(n=n.filter((e=>"videoinput"===e.kind))).find((e=>t.some((t=>e.label.toLowerCase().includes(t)))));return!a&&n.length&&t.includes("back")&&(a=n[n.length-1]),a&&(e.video.deviceId=o.exact?{exact:a.deviceId}:{ideal:a.deviceId}),e.video=i(e.video),is("chrome: "+JSON.stringify(e)),s(e)}))}e.video=i(e.video)}return is("chrome: "+JSON.stringify(e)),s(e)},o=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(n.getUserMedia=function(e,t,i){s(e,(e=>{n.webkitGetUserMedia(e,t,(e=>{i&&i(o(e))}))}))}.bind(n),n.mediaDevices.getUserMedia){const e=n.mediaDevices.getUserMedia.bind(n.mediaDevices);n.mediaDevices.getUserMedia=function(t){return s(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(o(e))))))}}}function os(e){e.MediaStream=e.MediaStream||e.webkitMediaStream}function as(e){if("object"==typeof e&&e.RTCPeerConnection&&!("ontrack"in e.RTCPeerConnection.prototype)){Object.defineProperty(e.RTCPeerConnection.prototype,"ontrack",{get(){return this._ontrack},set(e){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=e)},enumerable:!0,configurable:!0});const t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=t=>{t.stream.addEventListener("addtrack",(n=>{let i;i=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find((e=>e.track&&e.track.id===n.track.id)):{track:n.track};const s=new Event("track");s.track=n.track,s.receiver=i,s.transceiver={receiver:i},s.streams=[t.stream],this.dispatchEvent(s)})),t.stream.getTracks().forEach((n=>{let i;i=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find((e=>e.track&&e.track.id===n.id)):{track:n};const s=new Event("track");s.track=n,s.receiver=i,s.transceiver={receiver:i},s.streams=[t.stream],this.dispatchEvent(s)}))},this.addEventListener("addstream",this._ontrackpoly)),t.apply(this,arguments)}}else zi(e,"track",(e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e)))}function rs(e){if("object"==typeof e&&e.RTCPeerConnection&&!("getSenders"in e.RTCPeerConnection.prototype)&&"createDTMFSender"in e.RTCPeerConnection.prototype){const t=function(e,t){return{track:t,get dtmf(){return void 0===this._dtmf&&("audio"===t.kind?this._dtmf=e.createDTMFSender(t):this._dtmf=null),this._dtmf},_pc:e}};if(!e.RTCPeerConnection.prototype.getSenders){e.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};const n=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,i){let s=n.apply(this,arguments);return s||(s=t(this,e),this._senders.push(s)),s};const i=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){i.apply(this,arguments);const t=this._senders.indexOf(e);-1!==t&&this._senders.splice(t,1)}}const n=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._senders=this._senders||[],n.apply(this,[e]),e.getTracks().forEach((e=>{this._senders.push(t(this,e))}))};const i=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(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(){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 cs(e){if(!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){const[e,n,i]=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 s=function(e){const t={};return e.result().forEach((e=>{const n={id:e.id,timestamp:e.timestamp,type:{localcandidate:"local-candidate",remotecandidate:"remote-candidate"}[e.type]||e.type};e.names().forEach((t=>{n[t]=e.stat(t)})),t[n.id]=n})),t},o=function(e){return new Map(Object.keys(e).map((t=>[t,e[t]])))};if(arguments.length>=2){const i=function(e){n(o(s(e)))};return t.apply(this,[i,e])}return new Promise(((e,n)=>{t.apply(this,[function(t){e(o(s(t)))},n])})).then(n,i)}}function ds(e){if(!("object"==typeof e&&e.RTCPeerConnection&&e.RTCRtpSender&&e.RTCRtpReceiver))return;if(!("getStats"in e.RTCRtpSender.prototype)){const t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e});const n=e.RTCPeerConnection.prototype.addTrack;n&&(e.RTCPeerConnection.prototype.addTrack=function(){const e=n.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){const e=this;return this._pc.getStats().then((t=>ns(t,e.track,!0)))}}if(!("getStats"in e.RTCRtpReceiver.prototype)){const t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e}),zi(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){const e=this;return this._pc.getStats().then((t=>ns(t,e.track,!1)))}}if(!("getStats"in e.RTCRtpSender.prototype)||!("getStats"in e.RTCRtpReceiver.prototype))return;const t=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof e.MediaStreamTrack){const e=arguments[0];let t,n,i;return this.getSenders().forEach((n=>{n.track===e&&(t?i=!0:t=n)})),this.getReceivers().forEach((t=>(t.track===e&&(n?i=!0:n=t),t.track===e))),i||t&&n?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):t?t.getStats():n?n.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return t.apply(this,arguments)}}function ls(e){e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map((e=>this._shimmedLocalStreams[e][0]))};const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,n){if(!n)return t.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};const i=t.apply(this,arguments);return this._shimmedLocalStreams[n.id]?-1===this._shimmedLocalStreams[n.id].indexOf(i)&&this._shimmedLocalStreams[n.id].push(i):this._shimmedLocalStreams[n.id]=[n,i],i};const n=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._shimmedLocalStreams=this._shimmedLocalStreams||{},e.getTracks().forEach((e=>{if(this.getSenders().find((t=>t.track===e)))throw new DOMException("Track already exists.","InvalidAccessError")}));const t=this.getSenders();n.apply(this,arguments);const i=this.getSenders().filter((e=>-1===t.indexOf(e)));this._shimmedLocalStreams[e.id]=[e].concat(i)};const i=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[e.id],i.apply(this,arguments)};const s=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},e&&Object.keys(this._shimmedLocalStreams).forEach((t=>{const n=this._shimmedLocalStreams[t].indexOf(e);-1!==n&&this._shimmedLocalStreams[t].splice(n,1),1===this._shimmedLocalStreams[t].length&&delete this._shimmedLocalStreams[t]})),s.apply(this,arguments)}}function us(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return ls(e);const n=e.RTCPeerConnection.prototype.getLocalStreams;e.RTCPeerConnection.prototype.getLocalStreams=function(){const e=n.apply(this);return this._reverseStreams=this._reverseStreams||{},e.map((e=>this._reverseStreams[e.id]))};const i=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(t){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},t.getTracks().forEach((e=>{if(this.getSenders().find((t=>t.track===e)))throw new DOMException("Track already exists.","InvalidAccessError")})),!this._reverseStreams[t.id]){const n=new e.MediaStream(t.getTracks());this._streams[t.id]=n,this._reverseStreams[n.id]=t,t=n}i.apply(this,[t])};const s=e.RTCPeerConnection.prototype.removeStream;function o(e,t){let n=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((t=>{const i=e._reverseStreams[t],s=e._streams[i.id];n=n.replace(new RegExp(s.id,"g"),i.id)})),new RTCSessionDescription({type:t.type,sdp:n})}e.RTCPeerConnection.prototype.removeStream=function(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(t,n){if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");const i=[].slice.call(arguments,1);if(1!==i.length||!i[0].getTracks().find((e=>e===t)))throw new DOMException("The adapter.js addTrack polyfill only supports a single stream which is associated with the specified track.","NotSupportedError");if(this.getSenders().find((e=>e.track===t)))throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};const s=this._streams[n.id];if(s)s.addTrack(t),Promise.resolve().then((()=>{this.dispatchEvent(new Event("negotiationneeded"))}));else{const i=new e.MediaStream([t]);this._streams[n.id]=i,this._reverseStreams[i.id]=n,this.addStream(i)}return this.getSenders().find((e=>e.track===t))},["createOffer","createAnswer"].forEach((function(t){const n=e.RTCPeerConnection.prototype[t],i={[t](){const e=arguments;return arguments.length&&"function"==typeof arguments[0]?n.apply(this,[t=>{const n=o(this,t);e[0].apply(null,[n])},t=>{e[1]&&e[1].apply(null,t)},arguments[2]]):n.apply(this,arguments).then((e=>o(this,e)))}};e.RTCPeerConnection.prototype[t]=i[t]}));const a=e.RTCPeerConnection.prototype.setLocalDescription;e.RTCPeerConnection.prototype.setLocalDescription=function(){return arguments.length&&arguments[0].type?(arguments[0]=function(e,t){let n=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((t=>{const i=e._reverseStreams[t],s=e._streams[i.id];n=n.replace(new RegExp(i.id,"g"),s.id)})),new RTCSessionDescription({type:t.type,sdp:n})}(this,arguments[0]),a.apply(this,arguments)):a.apply(this,arguments)};const r=Object.getOwnPropertyDescriptor(e.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(e.RTCPeerConnection.prototype,"localDescription",{get(){const e=r.get.apply(this);return""===e.type?e:o(this,e)}}),e.RTCPeerConnection.prototype.removeTrack=function(e){if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!e._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(!(e._pc===this))throw new DOMException("Sender was not created by this connection.","InvalidAccessError");let t;this._streams=this._streams||{},Object.keys(this._streams).forEach((n=>{this._streams[n].getTracks().find((t=>e.track===t))&&(t=this._streams[n])})),t&&(1===t.getTracks().length?this.removeStream(this._reverseStreams[t.id]):t.removeTrack(e.track),this.dispatchEvent(new Event("negotiationneeded")))}}function hs(e,t){!e.RTCPeerConnection&&e.webkitRTCPeerConnection&&(e.RTCPeerConnection=e.webkitRTCPeerConnection),e.RTCPeerConnection&&t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach((function(t){const n=e.RTCPeerConnection.prototype[t],i={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),n.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=i[t]}))}function ms(e,t){zi(e,"negotiationneeded",(e=>{const n=e.target;if(!(t.version<72||n.getConfiguration&&"plan-b"===n.getConfiguration().sdpSemantics)||"stable"===n.signalingState)return e}))}var ps=Object.freeze({__proto__:null,fixNegotiationNeeded:ms,shimAddTrackRemoveTrack:us,shimAddTrackRemoveTrackWithNative:ls,shimGetDisplayMedia:function(e,t){e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||e.navigator.mediaDevices&&("function"==typeof t?e.navigator.mediaDevices.getDisplayMedia=function(n){return t(n).then((t=>{const i=n.video&&n.video.width,s=n.video&&n.video.height,o=n.video&&n.video.frameRate;return n.video={mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:t,maxFrameRate:o||3}},i&&(n.video.mandatory.maxWidth=i),s&&(n.video.mandatory.maxHeight=s),e.navigator.mediaDevices.getUserMedia(n)}))}:console.error("shimGetDisplayMedia: getSourceId argument is not a function"))},shimGetSendersWithDtmf:rs,shimGetStats:cs,shimGetUserMedia:ss,shimMediaStream:os,shimOnTrack:as,shimPeerConnection:hs,shimSenderReceiverGetStats:ds});function gs(e,t){const n=e&&e.navigator,i=e&&e.MediaStreamTrack;if(n.getUserMedia=function(e,t,i){Zi("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),n.mediaDevices.getUserMedia(e).then(t,i)},!(t.version>55&&"autoGainControl"in n.mediaDevices.getSupportedConstraints())){const e=function(e,t,n){t in e&&!(n in e)&&(e[n]=e[t],delete e[t])},t=n.mediaDevices.getUserMedia.bind(n.mediaDevices);if(n.mediaDevices.getUserMedia=function(n){return"object"==typeof n&&"object"==typeof n.audio&&(n=JSON.parse(JSON.stringify(n)),e(n.audio,"autoGainControl","mozAutoGainControl"),e(n.audio,"noiseSuppression","mozNoiseSuppression")),t(n)},i&&i.prototype.getSettings){const t=i.prototype.getSettings;i.prototype.getSettings=function(){const n=t.apply(this,arguments);return e(n,"mozAutoGainControl","autoGainControl"),e(n,"mozNoiseSuppression","noiseSuppression"),n}}if(i&&i.prototype.applyConstraints){const t=i.prototype.applyConstraints;i.prototype.applyConstraints=function(n){return"audio"===this.kind&&"object"==typeof n&&(n=JSON.parse(JSON.stringify(n)),e(n,"autoGainControl","mozAutoGainControl"),e(n,"noiseSuppression","mozNoiseSuppression")),t.apply(this,[n])}}}}function fs(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 vs(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 n=e.RTCPeerConnection.prototype[t],i={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),n.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=i[t]}));const n={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},i=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){const[e,s,o]=arguments;return i.apply(this,[e||null]).then((e=>{if(t.version<53&&!s)try{e.forEach((e=>{e.type=n[e.type]||e.type}))}catch(t){if("TypeError"!==t.name)throw t;e.forEach(((t,i)=>{e.set(i,Object.assign({},t,{type:n[t.type]||t.type}))}))}return e})).then(s,o)}}function ks(e){if("object"!=typeof e||!e.RTCPeerConnection||!e.RTCRtpSender)return;if(e.RTCRtpSender&&"getStats"in e.RTCRtpSender.prototype)return;const t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e});const n=e.RTCPeerConnection.prototype.addTrack;n&&(e.RTCPeerConnection.prototype.addTrack=function(){const e=n.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function Ts(e){if("object"!=typeof e||!e.RTCPeerConnection||!e.RTCRtpSender)return;if(e.RTCRtpSender&&"getStats"in e.RTCRtpReceiver.prototype)return;const t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e}),zi(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function ys(e){e.RTCPeerConnection&&!("removeStream"in e.RTCPeerConnection.prototype)&&(e.RTCPeerConnection.prototype.removeStream=function(e){Zi("removeStream","removeTrack"),this.getSenders().forEach((t=>{t.track&&e.getTracks().includes(t.track)&&this.removeTrack(t)}))})}function bs(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)}function Cs(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.addTransceiver;t&&(e.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let e=arguments[1]&&arguments[1].sendEncodings;void 0===e&&(e=[]),e=[...e];const n=e.length>0;n&&e.forEach((e=>{if("rid"in e){if(!/^[a-z0-9]{0,16}$/i.test(e.rid))throw new TypeError("Invalid RID value provided.")}if("scaleResolutionDownBy"in e&&!(parseFloat(e.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in e&&!(parseFloat(e.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")}));const i=t.apply(this,arguments);if(n){const{sender:t}=i,n=t.getParameters();(!("encodings"in n)||1===n.encodings.length&&0===Object.keys(n.encodings[0]).length)&&(n.encodings=e,t.sendEncodings=e,this.setParametersPromises.push(t.setParameters(n).then((()=>{delete t.sendEncodings})).catch((()=>{delete t.sendEncodings}))))}return i})}function Ss(e){if("object"!=typeof e||!e.RTCRtpSender)return;const t=e.RTCRtpSender.prototype.getParameters;t&&(e.RTCRtpSender.prototype.getParameters=function(){const e=t.apply(this,arguments);return"encodings"in e||(e.encodings=[].concat(this.sendEncodings||[{}])),e})}function Es(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then((()=>t.apply(this,arguments))).finally((()=>{this.setParametersPromises=[]})):t.apply(this,arguments)}}function ws(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.createAnswer;e.RTCPeerConnection.prototype.createAnswer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then((()=>t.apply(this,arguments))).finally((()=>{this.setParametersPromises=[]})):t.apply(this,arguments)}}var Ps=Object.freeze({__proto__:null,shimAddTransceiver:Cs,shimCreateAnswer:ws,shimCreateOffer:Es,shimGetDisplayMedia:function(e,t){e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||e.navigator.mediaDevices&&(e.navigator.mediaDevices.getDisplayMedia=function(n){if(!n||!n.video){const e=new DOMException("getDisplayMedia without video constraints is undefined");return e.name="NotFoundError",e.code=8,Promise.reject(e)}return!0===n.video?n.video={mediaSource:t}:n.video.mediaSource=t,e.navigator.mediaDevices.getUserMedia(n)})},shimGetParameters:Ss,shimGetUserMedia:gs,shimOnTrack:fs,shimPeerConnection:vs,shimRTCDataChannel:bs,shimReceiverGetStats:Ts,shimRemoveStream:ys,shimSenderGetStats:ks});function Rs(e){if("object"==typeof e&&e.RTCPeerConnection){if("getLocalStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in e.RTCPeerConnection.prototype)){const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addStream=function(e){this._localStreams||(this._localStreams=[]),this._localStreams.includes(e)||this._localStreams.push(e),e.getAudioTracks().forEach((n=>t.call(this,n,e))),e.getVideoTracks().forEach((n=>t.call(this,n,e)))},e.RTCPeerConnection.prototype.addTrack=function(e){for(var n=arguments.length,i=new Array(n>1?n-1:0),s=1;s<n;s++)i[s-1]=arguments[s];return i&&i.forEach((e=>{this._localStreams?this._localStreams.includes(e)||this._localStreams.push(e):this._localStreams=[e]})),t.apply(this,arguments)}}"removeStream"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.removeStream=function(e){this._localStreams||(this._localStreams=[]);const t=this._localStreams.indexOf(e);if(-1===t)return;this._localStreams.splice(t,1);const n=e.getTracks();this.getSenders().forEach((e=>{n.includes(e.track)&&this.removeTrack(e)}))})}}function _s(e){if("object"==typeof e&&e.RTCPeerConnection&&("getRemoteStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!("onaddstream"in e.RTCPeerConnection.prototype))){Object.defineProperty(e.RTCPeerConnection.prototype,"onaddstream",{get(){return this._onaddstream},set(e){this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=e),this.addEventListener("track",this._onaddstreampoly=e=>{e.streams.forEach((e=>{if(this._remoteStreams||(this._remoteStreams=[]),this._remoteStreams.includes(e))return;this._remoteStreams.push(e);const t=new Event("addstream");t.stream=e,this.dispatchEvent(t)}))})}});const t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){const e=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(t){t.streams.forEach((t=>{if(e._remoteStreams||(e._remoteStreams=[]),e._remoteStreams.indexOf(t)>=0)return;e._remoteStreams.push(t);const n=new Event("addstream");n.stream=t,e.dispatchEvent(n)}))}),t.apply(e,arguments)}}}function Is(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype,n=t.createOffer,i=t.createAnswer,s=t.setLocalDescription,o=t.setRemoteDescription,a=t.addIceCandidate;t.createOffer=function(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},t.createAnswer=function(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};let r=function(e,t,n){const i=s.apply(this,[e]);return n?(i.then(t,n),Promise.resolve()):i};t.setLocalDescription=r,r=function(e,t,n){const i=o.apply(this,[e]);return n?(i.then(t,n),Promise.resolve()):i},t.setRemoteDescription=r,r=function(e,t,n){const i=a.apply(this,[e]);return n?(i.then(t,n),Promise.resolve()):i},t.addIceCandidate=r}function Os(e){const t=e&&e.navigator;if(t.mediaDevices&&t.mediaDevices.getUserMedia){const e=t.mediaDevices,n=e.getUserMedia.bind(e);t.mediaDevices.getUserMedia=e=>n(Ms(e))}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=function(e,n,i){t.mediaDevices.getUserMedia(e).then(n,i)}.bind(t))}function Ms(e){return e&&void 0!==e.video?Object.assign({},e,{video:es(e.video)}):e}function xs(e){if(!e.RTCPeerConnection)return;const t=e.RTCPeerConnection;e.RTCPeerConnection=function(e,n){if(e&&e.iceServers){const t=[];for(let n=0;n<e.iceServers.length;n++){let i=e.iceServers[n];void 0===i.urls&&i.url?(Zi("RTCIceServer.url","RTCIceServer.urls"),i=JSON.parse(JSON.stringify(i)),i.urls=i.url,delete i.url,t.push(i)):t.push(e.iceServers[n])}e.iceServers=t}return new t(e,n)},e.RTCPeerConnection.prototype=t.prototype,"generateCertificate"in t&&Object.defineProperty(e.RTCPeerConnection,"generateCertificate",{get:()=>t.generateCertificate})}function Ds(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 Ns(e){const t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(e){if(e){void 0!==e.offerToReceiveAudio&&(e.offerToReceiveAudio=!!e.offerToReceiveAudio);const t=this.getTransceivers().find((e=>"audio"===e.receiver.track.kind));!1===e.offerToReceiveAudio&&t?"sendrecv"===t.direction?t.setDirection?t.setDirection("sendonly"):t.direction="sendonly":"recvonly"===t.direction&&(t.setDirection?t.setDirection("inactive"):t.direction="inactive"):!0!==e.offerToReceiveAudio||t||this.addTransceiver("audio",{direction:"recvonly"}),void 0!==e.offerToReceiveVideo&&(e.offerToReceiveVideo=!!e.offerToReceiveVideo);const n=this.getTransceivers().find((e=>"video"===e.receiver.track.kind));!1===e.offerToReceiveVideo&&n?"sendrecv"===n.direction?n.setDirection?n.setDirection("sendonly"):n.direction="sendonly":"recvonly"===n.direction&&(n.setDirection?n.setDirection("inactive"):n.direction="inactive"):!0!==e.offerToReceiveVideo||n||this.addTransceiver("video",{direction:"recvonly"})}return t.apply(this,arguments)}}function Ls(e){"object"!=typeof e||e.AudioContext||(e.AudioContext=e.webkitAudioContext)}var As=Object.freeze({__proto__:null,shimAudioContext:Ls,shimCallbacksAPI:Is,shimConstraints:Ms,shimCreateOfferLegacy:Ns,shimGetUserMedia:Os,shimLocalStreamsAPI:Rs,shimRTCIceServerUrls:xs,shimRemoteStreamsAPI:_s,shimTrackEventTransceiver:Ds}),Us={exports:{}};!function(e){const t={generateIdentifier:function(){return Math.random().toString(36).substring(2,12)}};t.localCName=t.generateIdentifier(),t.splitLines=function(e){return e.trim().split("\n").map((e=>e.trim()))},t.splitSections=function(e){return e.split("\nm=").map(((e,t)=>(t>0?"m="+e:e).trim()+"\r\n"))},t.getDescription=function(e){const n=t.splitSections(e);return n&&n[0]},t.getMediaSections=function(e){const n=t.splitSections(e);return n.shift(),n},t.matchPrefix=function(e,n){return t.splitLines(e).filter((e=>0===e.indexOf(n)))},t.parseCandidate=function(e){let t;t=0===e.indexOf("a=candidate:")?e.substring(12).split(" "):e.substring(10).split(" ");const n={foundation:t[0],component:{1:"rtp",2:"rtcp"}[t[1]]||t[1],protocol:t[2].toLowerCase(),priority:parseInt(t[3],10),ip:t[4],address:t[4],port:parseInt(t[5],10),type:t[7]};for(let e=8;e<t.length;e+=2)switch(t[e]){case"raddr":n.relatedAddress=t[e+1];break;case"rport":n.relatedPort=parseInt(t[e+1],10);break;case"tcptype":n.tcpType=t[e+1];break;case"ufrag":n.ufrag=t[e+1],n.usernameFragment=t[e+1];break;default:void 0===n[t[e]]&&(n[t[e]]=t[e+1])}return n},t.writeCandidate=function(e){const t=[];t.push(e.foundation);const n=e.component;"rtp"===n?t.push(1):"rtcp"===n?t.push(2):t.push(n),t.push(e.protocol.toUpperCase()),t.push(e.priority),t.push(e.address||e.ip),t.push(e.port);const i=e.type;return t.push("typ"),t.push(i),"host"!==i&&e.relatedAddress&&e.relatedPort&&(t.push("raddr"),t.push(e.relatedAddress),t.push("rport"),t.push(e.relatedPort)),e.tcpType&&"tcp"===e.protocol.toLowerCase()&&(t.push("tcptype"),t.push(e.tcpType)),(e.usernameFragment||e.ufrag)&&(t.push("ufrag"),t.push(e.usernameFragment||e.ufrag)),"candidate:"+t.join(" ")},t.parseIceOptions=function(e){return e.substring(14).split(" ")},t.parseRtpMap=function(e){let t=e.substring(9).split(" ");const n={payloadType:parseInt(t.shift(),10)};return t=t[0].split("/"),n.name=t[0],n.clockRate=parseInt(t[1],10),n.channels=3===t.length?parseInt(t[2],10):1,n.numChannels=n.channels,n},t.writeRtpMap=function(e){let t=e.payloadType;void 0!==e.preferredPayloadType&&(t=e.preferredPayloadType);const n=e.channels||e.numChannels||1;return"a=rtpmap:"+t+" "+e.name+"/"+e.clockRate+(1!==n?"/"+n:"")+"\r\n"},t.parseExtmap=function(e){const t=e.substring(9).split(" ");return{id:parseInt(t[0],10),direction:t[0].indexOf("/")>0?t[0].split("/")[1]:"sendrecv",uri:t[1],attributes:t.slice(2).join(" ")}},t.writeExtmap=function(e){return"a=extmap:"+(e.id||e.preferredId)+(e.direction&&"sendrecv"!==e.direction?"/"+e.direction:"")+" "+e.uri+(e.attributes?" "+e.attributes:"")+"\r\n"},t.parseFmtp=function(e){const t={};let n;const i=e.substring(e.indexOf(" ")+1).split(";");for(let e=0;e<i.length;e++)n=i[e].trim().split("="),t[n[0].trim()]=n[1];return t},t.writeFmtp=function(e){let t="",n=e.payloadType;if(void 0!==e.preferredPayloadType&&(n=e.preferredPayloadType),e.parameters&&Object.keys(e.parameters).length){const i=[];Object.keys(e.parameters).forEach((t=>{void 0!==e.parameters[t]?i.push(t+"="+e.parameters[t]):i.push(t)})),t+="a=fmtp:"+n+" "+i.join(";")+"\r\n"}return t},t.parseRtcpFb=function(e){const t=e.substring(e.indexOf(" ")+1).split(" ");return{type:t.shift(),parameter:t.join(" ")}},t.writeRtcpFb=function(e){let t="",n=e.payloadType;return void 0!==e.preferredPayloadType&&(n=e.preferredPayloadType),e.rtcpFeedback&&e.rtcpFeedback.length&&e.rtcpFeedback.forEach((e=>{t+="a=rtcp-fb:"+n+" "+e.type+(e.parameter&&e.parameter.length?" "+e.parameter:"")+"\r\n"})),t},t.parseSsrcMedia=function(e){const t=e.indexOf(" "),n={ssrc:parseInt(e.substring(7,t),10)},i=e.indexOf(":",t);return i>-1?(n.attribute=e.substring(t+1,i),n.value=e.substring(i+1)):n.attribute=e.substring(t+1),n},t.parseSsrcGroup=function(e){const t=e.substring(13).split(" ");return{semantics:t.shift(),ssrcs:t.map((e=>parseInt(e,10)))}},t.getMid=function(e){const n=t.matchPrefix(e,"a=mid:")[0];if(n)return n.substring(6)},t.parseFingerprint=function(e){const t=e.substring(14).split(" ");return{algorithm:t[0].toLowerCase(),value:t[1].toUpperCase()}},t.getDtlsParameters=function(e,n){return{role:"auto",fingerprints:t.matchPrefix(e+n,"a=fingerprint:").map(t.parseFingerprint)}},t.writeDtlsParameters=function(e,t){let n="a=setup:"+t+"\r\n";return e.fingerprints.forEach((e=>{n+="a=fingerprint:"+e.algorithm+" "+e.value+"\r\n"})),n},t.parseCryptoLine=function(e){const t=e.substring(9).split(" ");return{tag:parseInt(t[0],10),cryptoSuite:t[1],keyParams:t[2],sessionParams:t.slice(3)}},t.writeCryptoLine=function(e){return"a=crypto:"+e.tag+" "+e.cryptoSuite+" "+("object"==typeof e.keyParams?t.writeCryptoKeyParams(e.keyParams):e.keyParams)+(e.sessionParams?" "+e.sessionParams.join(" "):"")+"\r\n"},t.parseCryptoKeyParams=function(e){if(0!==e.indexOf("inline:"))return null;const t=e.substring(7).split("|");return{keyMethod:"inline",keySalt:t[0],lifeTime:t[1],mkiValue:t[2]?t[2].split(":")[0]:void 0,mkiLength:t[2]?t[2].split(":")[1]:void 0}},t.writeCryptoKeyParams=function(e){return e.keyMethod+":"+e.keySalt+(e.lifeTime?"|"+e.lifeTime:"")+(e.mkiValue&&e.mkiLength?"|"+e.mkiValue+":"+e.mkiLength:"")},t.getCryptoParameters=function(e,n){return t.matchPrefix(e+n,"a=crypto:").map(t.parseCryptoLine)},t.getIceParameters=function(e,n){const i=t.matchPrefix(e+n,"a=ice-ufrag:")[0],s=t.matchPrefix(e+n,"a=ice-pwd:")[0];return i&&s?{usernameFragment:i.substring(12),password:s.substring(10)}:null},t.writeIceParameters=function(e){let t="a=ice-ufrag:"+e.usernameFragment+"\r\na=ice-pwd:"+e.password+"\r\n";return e.iceLite&&(t+="a=ice-lite\r\n"),t},t.parseRtpParameters=function(e){const n={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},i=t.splitLines(e)[0].split(" ");n.profile=i[2];for(let s=3;s<i.length;s++){const o=i[s],a=t.matchPrefix(e,"a=rtpmap:"+o+" ")[0];if(a){const i=t.parseRtpMap(a),s=t.matchPrefix(e,"a=fmtp:"+o+" ");switch(i.parameters=s.length?t.parseFmtp(s[0]):{},i.rtcpFeedback=t.matchPrefix(e,"a=rtcp-fb:"+o+" ").map(t.parseRtcpFb),n.codecs.push(i),i.name.toUpperCase()){case"RED":case"ULPFEC":n.fecMechanisms.push(i.name.toUpperCase())}}}t.matchPrefix(e,"a=extmap:").forEach((e=>{n.headerExtensions.push(t.parseExtmap(e))}));const s=t.matchPrefix(e,"a=rtcp-fb:* ").map(t.parseRtcpFb);return n.codecs.forEach((e=>{s.forEach((t=>{e.rtcpFeedback.find((e=>e.type===t.type&&e.parameter===t.parameter))||e.rtcpFeedback.push(t)}))})),n},t.writeRtpDescription=function(e,n){let i="";i+="m="+e+" ",i+=n.codecs.length>0?"9":"0",i+=" "+(n.profile||"UDP/TLS/RTP/SAVPF")+" ",i+=n.codecs.map((e=>void 0!==e.preferredPayloadType?e.preferredPayloadType:e.payloadType)).join(" ")+"\r\n",i+="c=IN IP4 0.0.0.0\r\n",i+="a=rtcp:9 IN IP4 0.0.0.0\r\n",n.codecs.forEach((e=>{i+=t.writeRtpMap(e),i+=t.writeFmtp(e),i+=t.writeRtcpFb(e)}));let s=0;return n.codecs.forEach((e=>{e.maxptime>s&&(s=e.maxptime)})),s>0&&(i+="a=maxptime:"+s+"\r\n"),n.headerExtensions&&n.headerExtensions.forEach((e=>{i+=t.writeExtmap(e)})),i},t.parseRtpEncodingParameters=function(e){const n=[],i=t.parseRtpParameters(e),s=-1!==i.fecMechanisms.indexOf("RED"),o=-1!==i.fecMechanisms.indexOf("ULPFEC"),a=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"cname"===e.attribute)),r=a.length>0&&a[0].ssrc;let c;const d=t.matchPrefix(e,"a=ssrc-group:FID").map((e=>e.substring(17).split(" ").map((e=>parseInt(e,10)))));d.length>0&&d[0].length>1&&d[0][0]===r&&(c=d[0][1]),i.codecs.forEach((e=>{if("RTX"===e.name.toUpperCase()&&e.parameters.apt){let t={ssrc:r,codecPayloadType:parseInt(e.parameters.apt,10)};r&&c&&(t.rtx={ssrc:c}),n.push(t),s&&(t=JSON.parse(JSON.stringify(t)),t.fec={ssrc:r,mechanism:o?"red+ulpfec":"red"},n.push(t))}})),0===n.length&&r&&n.push({ssrc:r});let l=t.matchPrefix(e,"b=");return l.length&&(l=0===l[0].indexOf("b=TIAS:")?parseInt(l[0].substring(7),10):0===l[0].indexOf("b=AS:")?1e3*parseInt(l[0].substring(5),10)*.95-16e3:void 0,n.forEach((e=>{e.maxBitrate=l}))),n},t.parseRtcpParameters=function(e){const n={},i=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"cname"===e.attribute))[0];i&&(n.cname=i.value,n.ssrc=i.ssrc);const s=t.matchPrefix(e,"a=rtcp-rsize");n.reducedSize=s.length>0,n.compound=0===s.length;const o=t.matchPrefix(e,"a=rtcp-mux");return n.mux=o.length>0,n},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 n;const i=t.matchPrefix(e,"a=msid:");if(1===i.length)return n=i[0].substring(7).split(" "),{stream:n[0],track:n[1]};const s=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"msid"===e.attribute));return s.length>0?(n=s[0].value.split(" "),{stream:n[0],track:n[1]}):void 0},t.parseSctpDescription=function(e){const n=t.parseMLine(e),i=t.matchPrefix(e,"a=max-message-size:");let s;i.length>0&&(s=parseInt(i[0].substring(19),10)),isNaN(s)&&(s=65536);const o=t.matchPrefix(e,"a=sctp-port:");if(o.length>0)return{port:parseInt(o[0].substring(12),10),protocol:n.fmt,maxMessageSize:s};const a=t.matchPrefix(e,"a=sctpmap:");if(a.length>0){const e=a[0].substring(10).split(" ");return{port:parseInt(e[0],10),protocol:e[1],maxMessageSize:s}}},t.writeSctpDescription=function(e,t){let n=[];return n="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&&n.push("a=max-message-size:"+t.maxMessageSize+"\r\n"),n.join("")},t.generateSessionId=function(){return Math.random().toString().substr(2,22)},t.writeSessionBoilerplate=function(e,n,i){let s;const o=void 0!==n?n:2;s=e||t.generateSessionId();return"v=0\r\no="+(i||"thisisadapterortc")+" "+s+" "+o+" IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\n"},t.getDirection=function(e,n){const i=t.splitLines(e);for(let e=0;e<i.length;e++)switch(i[e]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return i[e].substring(2)}return n?t.getDirection(n):"sendrecv"},t.getKind=function(e){return t.splitLines(e)[0].split(" ")[0].substring(2)},t.isRejected=function(e){return"0"===e.split(" ",2)[1]},t.parseMLine=function(e){const n=t.splitLines(e)[0].substring(2).split(" ");return{kind:n[0],port:parseInt(n[1],10),protocol:n[2],fmt:n.slice(3).join(" ")}},t.parseOLine=function(e){const n=t.matchPrefix(e,"o=")[0].substring(2).split(" ");return{username:n[0],sessionId:n[1],sessionVersion:parseInt(n[2],10),netType:n[3],addressType:n[4],address:n[5]}},t.isValidSDP=function(e){if("string"!=typeof e||0===e.length)return!1;const n=t.splitLines(e);for(let e=0;e<n.length;e++)if(n[e].length<2||"="!==n[e].charAt(1))return!1;return!0},e.exports=t}(Us);var js=Us.exports,Fs=mi(js),Bs=t({__proto__:null,default:Fs},[js]);function Vs(e){if(!e.RTCIceCandidate||e.RTCIceCandidate&&"foundation"in e.RTCIceCandidate.prototype)return;const t=e.RTCIceCandidate;e.RTCIceCandidate=function(e){if("object"==typeof e&&e.candidate&&0===e.candidate.indexOf("a=")&&((e=JSON.parse(JSON.stringify(e))).candidate=e.candidate.substring(2)),e.candidate&&e.candidate.length){const n=new t(e),i=Fs.parseCandidate(e.candidate);for(const e in i)e in n||Object.defineProperty(n,e,{value:i[e]});return n.toJSON=function(){return{candidate:n.candidate,sdpMid:n.sdpMid,sdpMLineIndex:n.sdpMLineIndex,usernameFragment:n.usernameFragment}},n}return new t(e)},e.RTCIceCandidate.prototype=t.prototype,zi(e,"icecandidate",(t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new e.RTCIceCandidate(t.candidate),writable:"false"}),t)))}function qs(e){!e.RTCIceCandidate||e.RTCIceCandidate&&"relayProtocol"in e.RTCIceCandidate.prototype||zi(e,"icecandidate",(e=>{if(e.candidate){const t=Fs.parseCandidate(e.candidate.candidate);"relay"===t.type&&(e.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[t.priority>>24])}return e}))}function Ks(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 n=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,"chrome"===t.browser&&t.version>=76){const{sdpSemantics:e}=this.getConfiguration();"plan-b"===e&&Object.defineProperty(this,"sctp",{get(){return void 0===this._sctp?null:this._sctp},enumerable:!0,configurable:!0})}if(function(e){if(!e||!e.sdp)return!1;const t=Fs.splitSections(e.sdp);return t.shift(),t.some((e=>{const t=Fs.parseMLine(e);return t&&"application"===t.kind&&-1!==t.protocol.indexOf("SCTP")}))}(arguments[0])){const e=function(e){const t=e.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(null===t||t.length<2)return-1;const n=parseInt(t[1],10);return n!=n?-1:n}(arguments[0]),n=function(e){let n=65536;return"firefox"===t.browser&&(n=t.version<57?-1===e?16384:2147483637:t.version<60?57===t.version?65535:65536:2147483637),n}(e),i=function(e,n){let i=65536;"firefox"===t.browser&&57===t.version&&(i=65535);const s=Fs.matchPrefix(e.sdp,"a=max-message-size:");return s.length>0?i=parseInt(s[0].substring(19),10):"firefox"===t.browser&&-1!==n&&(i=2147483637),i}(arguments[0],e);let s;s=0===n&&0===i?Number.POSITIVE_INFINITY:0===n||0===i?Math.max(n,i):Math.min(n,i);const o={};Object.defineProperty(o,"maxMessageSize",{get:()=>s}),this._sctp=o}return n.apply(this,arguments)}}function Gs(e){if(!e.RTCPeerConnection||!("createDataChannel"in e.RTCPeerConnection.prototype))return;function t(e,t){const n=e.send;e.send=function(){const i=arguments[0],s=i.length||i.size||i.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 n.apply(e,arguments)}}const n=e.RTCPeerConnection.prototype.createDataChannel;e.RTCPeerConnection.prototype.createDataChannel=function(){const e=n.apply(this,arguments);return t(e,this),e},zi(e,"datachannel",(e=>(t(e.channel,e.target),e)))}function Ws(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 n=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 n=new Event("connectionstatechange",e);t.dispatchEvent(n)}return e},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),n.apply(this,arguments)}}))}function Hs(e,t){if(!e.RTCPeerConnection)return;if("chrome"===t.browser&&t.version>=71)return;if("safari"===t.browser&&t.version>=605)return;const n=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(t){if(t&&t.sdp&&-1!==t.sdp.indexOf("\na=extmap-allow-mixed")){const n=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:n}):t.sdp=n}return n.apply(this,arguments)}}function Js(e,t){if(!e.RTCPeerConnection||!e.RTCPeerConnection.prototype)return;const n=e.RTCPeerConnection.prototype.addIceCandidate;n&&0!==n.length&&(e.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?("chrome"===t.browser&&t.version<78||"firefox"===t.browser&&t.version<68||"safari"===t.browser)&&arguments[0]&&""===arguments[0].candidate?Promise.resolve():n.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}function zs(e,t){if(!e.RTCPeerConnection||!e.RTCPeerConnection.prototype)return;const n=e.RTCPeerConnection.prototype.setLocalDescription;n&&0!==n.length&&(e.RTCPeerConnection.prototype.setLocalDescription=function(){let e=arguments[0]||{};if("object"!=typeof e||e.type&&e.sdp)return n.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 n.apply(this,[e]);return("offer"===e.type?this.createOffer:this.createAnswer).apply(this).then((e=>n.apply(this,[e])))})}var Qs=Object.freeze({__proto__:null,removeExtmapAllowMixed:Hs,shimAddIceCandidateNullOrEmpty:Js,shimConnectionState:Ws,shimMaxMessageSize:Ks,shimParameterlessSetLocalDescription:zs,shimRTCIceCandidate:Vs,shimRTCIceCandidateRelayProtocol:qs,shimSendThrowTypeError:Gs});!function(){let{window:e}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{shimChrome:!0,shimFirefox:!0,shimSafari:!0};const n=Xi,i=function(e){const t={browser:null,version:null};if(void 0===e||!e.navigator||!e.navigator.userAgent)return t.browser="Not a browser.",t;const{navigator:n}=e;if(n.mozGetUserMedia)t.browser="firefox",t.version=Ji(n.userAgent,/Firefox\/(\d+)\./,1);else if(n.webkitGetUserMedia||!1===e.isSecureContext&&e.webkitRTCPeerConnection)t.browser="chrome",t.version=Ji(n.userAgent,/Chrom(e|ium)\/(\d+)\./,2);else{if(!e.RTCPeerConnection||!n.userAgent.match(/AppleWebKit\/(\d+)\./))return t.browser="Not a supported browser.",t;t.browser="safari",t.version=Ji(n.userAgent,/AppleWebKit\/(\d+)\./,1),t.supportsUnifiedPlan=e.RTCRtpTransceiver&&"currentDirection"in e.RTCRtpTransceiver.prototype}return t}(e),s={browserDetails:i,commonShim:Qs,extractVersion:Ji,disableLog:Qi,disableWarnings:Yi,sdp:Bs};switch(i.browser){case"chrome":if(!ps||!hs||!t.shimChrome)return n("Chrome shim is not included in this adapter release."),s;if(null===i.version)return n("Chrome shim can not determine version, not shimming."),s;n("adapter.js shimming chrome."),s.browserShim=ps,Js(e,i),zs(e),ss(e,i),os(e),hs(e,i),as(e),us(e,i),rs(e),cs(e),ds(e),ms(e,i),Vs(e),qs(e),Ws(e),Ks(e,i),Gs(e),Hs(e,i);break;case"firefox":if(!Ps||!vs||!t.shimFirefox)return n("Firefox shim is not included in this adapter release."),s;n("adapter.js shimming firefox."),s.browserShim=Ps,Js(e,i),zs(e),gs(e,i),vs(e,i),fs(e),ys(e),ks(e),Ts(e),bs(e),Cs(e),Ss(e),Es(e),ws(e),Vs(e),Ws(e),Ks(e,i),Gs(e);break;case"safari":if(!As||!t.shimSafari)return n("Safari shim is not included in this adapter release."),s;n("adapter.js shimming safari."),s.browserShim=As,Js(e,i),zs(e),xs(e),Ns(e),Is(e),Rs(e),_s(e),Ds(e),Os(e),Ls(e),Vs(e),qs(e),Ks(e,i),Gs(e),Hs(e,i);break;default:n("Unsupported browser!")}}({window:"undefined"==typeof window?void 0:window});const Ys="AES-GCM",Xs="lk_e2ee",Zs={sharedKey:!1,ratchetSalt:"LKFrameEncryptionKey",ratchetWindowSize:8,failureTolerance:10};var $s,eo;function to(){return io()||no()}function no(){return void 0!==window.RTCRtpScriptTransform}function io(){return void 0!==window.RTCRtpSender&&void 0!==window.RTCRtpSender.prototype.createEncodedStreams}function so(e){return wi(this,void 0,void 0,(function*(){let t=new TextEncoder;return yield crypto.subtle.importKey("raw",t.encode(e),{name:"PBKDF2"},!1,["deriveBits","deriveKey"])}))}function oo(e){return wi(this,void 0,void 0,(function*(){return yield crypto.subtle.importKey("raw",e,"HKDF",!1,["deriveBits","deriveKey"])}))}function ao(e,t){const n=(new TextEncoder).encode(t);switch(e){case"HKDF":return{name:"HKDF",salt:n,hash:"SHA-256",info:new ArrayBuffer(128)};case"PBKDF2":return{name:"PBKDF2",salt:n,hash:"SHA-256",iterations:1e5};default:throw new Error("algorithm ".concat(e," is currently unsupported"))}}e.KeyProviderEvent=void 0,($s=e.KeyProviderEvent||(e.KeyProviderEvent={})).SetKey="setKey",$s.RatchetRequest="ratchetRequest",$s.KeyRatcheted="keyRatcheted",e.KeyHandlerEvent=void 0,(e.KeyHandlerEvent||(e.KeyHandlerEvent={})).KeyRatcheted="keyRatcheted",e.EncryptionEvent=void 0,(eo=e.EncryptionEvent||(e.EncryptionEvent={})).ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",eo.EncryptionError="encryptionError",e.CryptorEvent=void 0,(e.CryptorEvent||(e.CryptorEvent={})).Error="cryptorError";class ro extends Gi.EventEmitter{constructor(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};super(),this.onKeyRatcheted=(e,t)=>{ki.debug("key ratcheted event received",{material:e,keyIndex:t})},this.keyInfoMap=new Map,this.options=Object.assign(Object.assign({},Zs),t),this.on(e.KeyProviderEvent.KeyRatcheted,this.onKeyRatcheted)}onSetEncryptionKey(t,n,i){const s={key:t,participantIdentity:n,keyIndex:i};if(!this.options.sharedKey&&!n)throw new Error("participant identity needs to be passed for encryption key if sharedKey option is false");this.keyInfoMap.set("".concat(null!=n?n:"shared","-").concat(null!=i?i:0),s),this.emit(e.KeyProviderEvent.SetKey,s)}getKeys(){return Array.from(this.keyInfoMap.values())}getOptions(){return this.options}ratchetKey(t,n){this.emit(e.KeyProviderEvent.RatchetRequest,t,n)}}class co extends Error{constructor(e,t){super(t||"an error has occured"),this.code=e}}class lo extends co{constructor(e,t,n){super(1,e),this.status=n,this.reason=t}}class uo extends co{constructor(e){super(21,null!=e?e:"device is unsupported")}}class ho extends co{constructor(e){super(20,null!=e?e:"track is invalid")}}class mo extends co{constructor(e){super(10,null!=e?e:"unsupported server")}}class po extends co{constructor(e){super(12,null!=e?e:"unexpected connection state")}}class go extends co{constructor(e){super(13,null!=e?e:"unable to negotiate")}}var fo,vo,ko,To,yo;function bo(e,t,n){var i,s,o;void 0===t&&(t=50),void 0===n&&(n={});var a=null!=(i=n.isImmediate)&&i,r=null!=(s=n.callback)&&s,c=n.maxWait,d=Date.now(),l=[];function u(){if(void 0!==c){var e=Date.now()-d;if(e+t>=c)return c-e}return t}var h=function(){var t=[].slice.call(arguments),n=this;return new Promise((function(i,s){var c=a&&void 0===o;if(void 0!==o&&clearTimeout(o),o=setTimeout((function(){if(o=void 0,d=Date.now(),!a){var i=e.apply(n,t);r&&r(i),l.forEach((function(e){return(0,e.resolve)(i)})),l=[]}}),u()),c){var h=e.apply(n,t);return r&&r(h),i(h)}l.push({resolve:i,reject:s})}))};return h.cancel=function(e){void 0!==o&&clearTimeout(o),l.forEach((function(t){return(0,t.reject)(e)})),l=[]},h}e.MediaDeviceFailure=void 0,(fo=e.MediaDeviceFailure||(e.MediaDeviceFailure={})).PermissionDenied="PermissionDenied",fo.NotFound="NotFound",fo.DeviceInUse="DeviceInUse",fo.Other="Other",function(e){e.getFailure=function(t){if(t&&"name"in t)return"NotFoundError"===t.name||"DevicesNotFoundError"===t.name?e.NotFound:"NotAllowedError"===t.name||"PermissionDeniedError"===t.name?e.PermissionDenied:"NotReadableError"===t.name||"TrackStartError"===t.name?e.DeviceInUse:e.Other}}(e.MediaDeviceFailure||(e.MediaDeviceFailure={})),e.RoomEvent=void 0,(vo=e.RoomEvent||(e.RoomEvent={})).Connected="connected",vo.Reconnecting="reconnecting",vo.Reconnected="reconnected",vo.Disconnected="disconnected",vo.ConnectionStateChanged="connectionStateChanged",vo.MediaDevicesChanged="mediaDevicesChanged",vo.ParticipantConnected="participantConnected",vo.ParticipantDisconnected="participantDisconnected",vo.TrackPublished="trackPublished",vo.TrackSubscribed="trackSubscribed",vo.TrackSubscriptionFailed="trackSubscriptionFailed",vo.TrackUnpublished="trackUnpublished",vo.TrackUnsubscribed="trackUnsubscribed",vo.TrackMuted="trackMuted",vo.TrackUnmuted="trackUnmuted",vo.LocalTrackPublished="localTrackPublished",vo.LocalTrackUnpublished="localTrackUnpublished",vo.LocalAudioSilenceDetected="localAudioSilenceDetected",vo.ActiveSpeakersChanged="activeSpeakersChanged",vo.ParticipantMetadataChanged="participantMetadataChanged",vo.ParticipantNameChanged="participantNameChanged",vo.RoomMetadataChanged="roomMetadataChanged",vo.DataReceived="dataReceived",vo.ConnectionQualityChanged="connectionQualityChanged",vo.TrackStreamStateChanged="trackStreamStateChanged",vo.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",vo.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",vo.AudioPlaybackStatusChanged="audioPlaybackChanged",vo.VideoPlaybackStatusChanged="videoPlaybackChanged",vo.MediaDevicesError="mediaDevicesError",vo.ParticipantPermissionsChanged="participantPermissionsChanged",vo.SignalConnected="signalConnected",vo.RecordingStatusChanged="recordingStatusChanged",vo.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",vo.EncryptionError="encryptionError",vo.DCBufferStatusChanged="dcBufferStatusChanged",vo.ActiveDeviceChanged="activeDeviceChanged",e.ParticipantEvent=void 0,(ko=e.ParticipantEvent||(e.ParticipantEvent={})).TrackPublished="trackPublished",ko.TrackSubscribed="trackSubscribed",ko.TrackSubscriptionFailed="trackSubscriptionFailed",ko.TrackUnpublished="trackUnpublished",ko.TrackUnsubscribed="trackUnsubscribed",ko.TrackMuted="trackMuted",ko.TrackUnmuted="trackUnmuted",ko.LocalTrackPublished="localTrackPublished",ko.LocalTrackUnpublished="localTrackUnpublished",ko.ParticipantMetadataChanged="participantMetadataChanged",ko.ParticipantNameChanged="participantNameChanged",ko.DataReceived="dataReceived",ko.IsSpeakingChanged="isSpeakingChanged",ko.ConnectionQualityChanged="connectionQualityChanged",ko.TrackStreamStateChanged="trackStreamStateChanged",ko.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",ko.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",ko.MediaDevicesError="mediaDevicesError",ko.AudioStreamAcquired="audioStreamAcquired",ko.ParticipantPermissionsChanged="participantPermissionsChanged",ko.PCTrackAdded="pcTrackAdded",e.EngineEvent=void 0,(To=e.EngineEvent||(e.EngineEvent={})).TransportsCreated="transportsCreated",To.Connected="connected",To.Disconnected="disconnected",To.Resuming="resuming",To.Resumed="resumed",To.Restarting="restarting",To.Restarted="restarted",To.SignalResumed="signalResumed",To.SignalRestarted="signalRestarted",To.Closing="closing",To.MediaTrackAdded="mediaTrackAdded",To.ActiveSpeakersUpdate="activeSpeakersUpdate",To.DataPacketReceived="dataPacketReceived",To.RTPVideoMapUpdate="rtpVideoMapUpdate",To.DCBufferStatusChanged="dcBufferStatusChanged",To.ParticipantUpdate="participantUpdate",To.RoomUpdate="roomUpdate",To.SpeakersChanged="speakersChanged",To.StreamStateChanged="streamStateChanged",To.ConnectionQualityUpdate="connectionQualityUpdate",To.SubscriptionError="subscriptionError",To.SubscriptionPermissionUpdate="subscriptionPermissionUpdate",To.RemoteMute="remoteMute",To.SubscribedQualityUpdate="subscribedQualityUpdate",To.LocalTrackUnpublished="localTrackUnpublished",To.Offline="offline",e.TrackEvent=void 0,(yo=e.TrackEvent||(e.TrackEvent={})).Message="message",yo.Muted="muted",yo.Unmuted="unmuted",yo.Restarted="restarted",yo.Ended="ended",yo.Subscribed="subscribed",yo.Unsubscribed="unsubscribed",yo.UpdateSettings="updateSettings",yo.UpdateSubscription="updateSubscription",yo.AudioPlaybackStarted="audioPlaybackStarted",yo.AudioPlaybackFailed="audioPlaybackFailed",yo.AudioSilenceDetected="audioSilenceDetected",yo.VisibilityChanged="visibilityChanged",yo.VideoDimensionsChanged="videoDimensionsChanged",yo.VideoPlaybackStarted="videoPlaybackStarted",yo.VideoPlaybackFailed="videoPlaybackFailed",yo.ElementAttached="elementAttached",yo.ElementDetached="elementDetached",yo.UpstreamPaused="upstreamPaused",yo.UpstreamResumed="upstreamResumed",yo.SubscriptionPermissionChanged="subscriptionPermissionChanged",yo.SubscriptionStatusChanged="subscriptionStatusChanged",yo.SubscriptionFailed="subscriptionFailed",yo.TrackProcessorUpdate="trackProcessorUpdate";const Co=/version\/(\d+(\.?_?\d+)+)/i;let So;function Eo(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(void 0===e&&"undefined"==typeof navigator)return;const n=(null!=e?e:navigator.userAgent).toLowerCase();if(void 0===So||t){const e=wo.find((e=>{let{test:t}=e;return t.test(n)}));So=null==e?void 0:e.describe(n)}return So}const wo=[{test:/firefox|iceweasel|fxios/i,describe:e=>({name:"Firefox",version:Po(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,e),os:e.toLowerCase().includes("fxios")?"iOS":void 0})},{test:/chrom|crios|crmo/i,describe:e=>({name:"Chrome",version:Po(/(?:chrome|chromium|crios|crmo)\/(\d+(\.?_?\d+)+)/i,e),os:e.toLowerCase().includes("crios")?"iOS":void 0})},{test:/safari|applewebkit/i,describe:e=>({name:"Safari",version:Po(Co,e),os:e.includes("mobile/")?"iOS":"macOS"})}];function Po(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1;const i=t.match(e);return i&&i.length>=n&&i[n]||""}const Ro="2.0.8";class _o{}_o.setTimeout=function(){return setTimeout(...arguments)},_o.setInterval=function(){return setInterval(...arguments)},_o.clearTimeout=function(){return clearTimeout(...arguments)},_o.clearInterval=function(){return clearInterval(...arguments)};class Io{constructor(e,t,n,i,s){if("object"==typeof e)this.width=e.width,this.height=e.height,this.aspectRatio=e.aspectRatio,this.encoding={maxBitrate:e.maxBitrate,maxFramerate:e.maxFramerate,priority:e.priority};else{if(void 0===t||void 0===n)throw new TypeError("Unsupported options: provide at least width, height and maxBitrate");this.width=e,this.height=t,this.aspectRatio=e/t,this.encoding={maxBitrate:n,maxFramerate:i,priority:s}}}get resolution(){return{width:this.width,height:this.height,frameRate:this.encoding.maxFramerate,aspectRatio:this.aspectRatio}}}const Oo=["vp8","h264"],Mo=["vp8","h264","vp9","av1"];function xo(e){return!!Oo.find((t=>t===e))}var Do;e.AudioPresets=void 0,(Do=e.AudioPresets||(e.AudioPresets={})).telephone={maxBitrate:12e3},Do.speech={maxBitrate:2e4},Do.music={maxBitrate:32e3},Do.musicStereo={maxBitrate:48e3},Do.musicHighQuality={maxBitrate:64e3},Do.musicHighQualityStereo={maxBitrate:96e3};const No={h90:new Io(160,90,9e4,20),h180:new Io(320,180,16e4,20),h216:new Io(384,216,18e4,20),h360:new Io(640,360,45e4,20),h540:new Io(960,540,8e5,25),h720:new Io(1280,720,17e5,30),h1080:new Io(1920,1080,3e6,30),h1440:new Io(2560,1440,5e6,30),h2160:new Io(3840,2160,8e6,30)},Lo={h120:new Io(160,120,7e4,20),h180:new Io(240,180,125e3,20),h240:new Io(320,240,14e4,20),h360:new Io(480,360,33e4,20),h480:new Io(640,480,5e5,20),h540:new Io(720,540,6e5,25),h720:new Io(960,720,13e5,30),h1080:new Io(1440,1080,23e5,30),h1440:new Io(1920,1440,38e5,30)},Ao={h360fps3:new Io(640,360,2e5,3,"medium"),h360fps15:new Io(640,360,4e5,15,"medium"),h720fps5:new Io(1280,720,8e5,5,"medium"),h720fps15:new Io(1280,720,15e5,15,"medium"),h720fps30:new Io(1280,720,2e6,30,"medium"),h1080fps15:new Io(1920,1080,25e5,15,"medium"),h1080fps30:new Io(1920,1080,5e6,30,"medium"),original:new Io(0,0,7e6,30,"medium")};const Uo=[];e.VideoQuality=void 0,function(e){e[e.LOW=0]="LOW",e[e.MEDIUM=1]="MEDIUM",e[e.HIGH=2]="HIGH"}(e.VideoQuality||(e.VideoQuality={}));class jo extends Gi.EventEmitter{constructor(t,n){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};var s;super(),this.attachedElements=[],this.isMuted=!1,this.streamState=jo.StreamState.Active,this.isInBackground=!1,this._currentBitrate=0,this.log=ki,this.appVisibilityChangedListener=()=>{this.backgroundTimeout&&clearTimeout(this.backgroundTimeout),"hidden"===document.visibilityState?this.backgroundTimeout=setTimeout((()=>this.handleAppVisibilityChanged()),5e3):this.handleAppVisibilityChanged()},this.log=yi(null!==(s=i.loggerName)&&void 0!==s?s:e.LoggerNames.Track),this.loggerContextCb=i.loggerContextCb,this.setMaxListeners(100),this.kind=n,this._mediaStreamTrack=t,this._mediaStreamID=t.id,this.source=jo.Source.Unknown}get logContext(){var e;return Object.assign(Object.assign({},null===(e=this.loggerContextCb)||void 0===e?void 0:e.call(this)),zo(this))}get currentBitrate(){return this._currentBitrate}get mediaStreamTrack(){return this._mediaStreamTrack}get mediaStreamID(){return this._mediaStreamID}attach(t){let n="audio";this.kind===jo.Kind.Video&&(n="video"),0===this.attachedElements.length&&jo.Kind.Video&&this.addAppVisibilityListener(),t||("audio"===n&&(Uo.forEach((e=>{null!==e.parentElement||t||(t=e)})),t&&Uo.splice(Uo.indexOf(t),1)),t||(t=document.createElement(n))),this.attachedElements.includes(t)||this.attachedElements.push(t),Fo(this.mediaStreamTrack,t);const i=t.srcObject.getTracks(),s=i.some((e=>"audio"===e.kind));return t.play().then((()=>{this.emit(s?e.TrackEvent.AudioPlaybackStarted:e.TrackEvent.VideoPlaybackStarted)})).catch((n=>{"NotAllowedError"===n.name?this.emit(s?e.TrackEvent.AudioPlaybackFailed:e.TrackEvent.VideoPlaybackFailed,n):"AbortError"===n.name?ki.debug("".concat(s?"audio":"video"," playback aborted, likely due to new play request")):ki.warn("could not playback ".concat(s?"audio":"video"),n),s&&t&&i.some((e=>"video"===e.kind))&&"NotAllowedError"===n.name&&(t.muted=!0,t.play().catch((()=>{})))})),this.emit(e.TrackEvent.ElementAttached,t),t}detach(t){try{if(t){Bo(this.mediaStreamTrack,t);const n=this.attachedElements.indexOf(t);return n>=0&&(this.attachedElements.splice(n,1),this.recycleElement(t),this.emit(e.TrackEvent.ElementDetached,t)),t}const n=[];return this.attachedElements.forEach((t=>{Bo(this.mediaStreamTrack,t),n.push(t),this.recycleElement(t),this.emit(e.TrackEvent.ElementDetached,t)})),this.attachedElements=[],n}finally{0===this.attachedElements.length&&this.removeAppVisibilityListener()}}stop(){this.stopMonitor(),this._mediaStreamTrack.stop()}enable(){this._mediaStreamTrack.enabled=!0}disable(){this._mediaStreamTrack.enabled=!1}stopMonitor(){this.monitorInterval&&clearInterval(this.monitorInterval)}updateLoggerOptions(e){e.loggerName&&(this.log=yi(e.loggerName)),e.loggerContextCb&&(this.loggerContextCb=e.loggerContextCb)}recycleElement(e){if(e instanceof HTMLAudioElement){let t=!0;e.pause(),Uo.forEach((e=>{e.parentElement||(t=!1)})),t&&Uo.push(e)}}handleAppVisibilityChanged(){return wi(this,void 0,void 0,(function*(){this.isInBackground="hidden"===document.visibilityState}))}addAppVisibilityListener(){da()?(this.isInBackground="hidden"===document.visibilityState,document.addEventListener("visibilitychange",this.appVisibilityChangedListener)):this.isInBackground=!1}removeAppVisibilityListener(){da()&&document.removeEventListener("visibilitychange",this.appVisibilityChangedListener)}}function Fo(e,t){let n,i;n=t.srcObject instanceof MediaStream?t.srcObject:new MediaStream,i="audio"===e.kind?n.getAudioTracks():n.getVideoTracks(),i.includes(e)||(i.forEach((e=>{n.removeTrack(e)})),n.addTrack(e)),aa()&&t instanceof HTMLVideoElement||(t.autoplay=!0),t.muted=0===n.getAudioTracks().length,t instanceof HTMLVideoElement&&(t.playsInline=!0),t.srcObject!==n&&(t.srcObject=n,(aa()||oa())&&t instanceof HTMLVideoElement&&setTimeout((()=>{t.srcObject=n,t.play().catch((()=>{}))}),0))}function Bo(e,t){if(t.srcObject instanceof MediaStream){const n=t.srcObject;n.removeTrack(e),n.getTracks().length>0?t.srcObject=n:t.srcObject=null}}function Vo(e,t,n){var i;const s=null!==(i=function(e){if(void 0!==e)return"function"==typeof structuredClone?structuredClone(e):JSON.parse(JSON.stringify(e))}(e))&&void 0!==i?i:{};return!0===s.audio&&(s.audio={}),!0===s.video&&(s.video={}),s.audio&&qo(s.audio,t),s.video&&qo(s.video,n),s}function qo(e,t){return Object.keys(t).forEach((n=>{void 0===e[n]&&(e[n]=t[n])})),e}function Ko(e){const t={};if(e.video)if("object"==typeof e.video){const n={},i=n,s=e.video;Object.keys(s).forEach((e=>{if("resolution"===e)qo(i,s.resolution);else i[e]=s[e]})),t.video=n}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 Go(){const e="undefined"!=typeof window&&(window.AudioContext||window.webkitAudioContext);if(e)return new e({latencyHint:"interactive"})}function Wo(e){var t,n;let i=null===(t=e.video)||void 0===t||t;return e.resolution&&e.resolution.width>0&&e.resolution.height>0&&(i="boolean"==typeof i?{}:i,i=aa()?Object.assign(Object.assign({},i),{width:{max:e.resolution.width},height:{max:e.resolution.height},frameRate:e.resolution.frameRate}):Object.assign(Object.assign({},i),{width:{ideal:e.resolution.width},height:{ideal:e.resolution.height},frameRate:e.resolution.frameRate})),{audio:null!==(n=e.audio)&&void 0!==n&&n,video:i,controller:e.controller,selfBrowserSurface:e.selfBrowserSurface,surfaceSwitching:e.surfaceSwitching,systemAudio:e.systemAudio,preferCurrentTab:e.preferCurrentTab}}function Ho(e){const t=e.split("/")[1].toLowerCase();if(!Mo.includes(t))throw Error("Video codec not supported: ".concat(t));return t}function Jo(e){const t=[];return e.forEach((e=>{void 0!==e.track&&t.push(new kn({cid:e.track.mediaStreamID,track:e.trackInfo}))})),t}function zo(e){return e instanceof jo?{trackID:e.sid,source:e.source,muted:e.isMuted,enabled:e.mediaStreamTrack.enabled,kind:e.kind,streamID:e.mediaStreamID,streamTrackID:e.mediaStreamTrack.id}:{trackID:e.trackSid,enabled:e.isEnabled,muted:e.isMuted,trackInfo:Object.assign({mimeType:e.mimeType,name:e.trackName,encrypted:e.isEncrypted,kind:e.kind,source:e.source},e.track?zo(e.track):{})}}!function(e){let t,n,i;!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"}(n=e.Source||(e.Source={})),function(e){e.Active="active",e.Paused="paused",e.Unknown="unknown"}(i=e.StreamState||(e.StreamState={})),e.kindToProto=function(e){switch(e){case t.Audio:return Ue.AUDIO;case t.Video:return Ue.VIDEO;default:return Ue.DATA}},e.kindFromProto=function(e){switch(e){case Ue.AUDIO:return t.Audio;case Ue.VIDEO:return t.Video;default:return t.Unknown}},e.sourceToProto=function(e){switch(e){case n.Camera:return je.CAMERA;case n.Microphone:return je.MICROPHONE;case n.ScreenShare:return je.SCREEN_SHARE;case n.ScreenShareAudio:return je.SCREEN_SHARE_AUDIO;default:return je.UNKNOWN}},e.sourceFromProto=function(e){switch(e){case je.CAMERA:return n.Camera;case je.MICROPHONE:return n.Microphone;case je.SCREEN_SHARE:return n.ScreenShare;case je.SCREEN_SHARE_AUDIO:return n.ScreenShareAudio;default:return n.Unknown}},e.streamStateFromProto=function(e){switch(e){case cn.ACTIVE:return i.Active;case cn.PAUSED:return i.Paused;default:return i.Unknown}}}(jo||(jo={}));const Qo="https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension";function Yo(e){return wi(this,void 0,void 0,(function*(){return new Promise((t=>_o.setTimeout(t,e)))}))}function Xo(){return"addTransceiver"in RTCPeerConnection.prototype}function Zo(){return"addTrack"in RTCPeerConnection.prototype}function $o(){if(!("getCapabilities"in RTCRtpSender))return!1;if(aa())return!1;const e=RTCRtpSender.getCapabilities("video");let t=!1;if(e)for(const n of e.codecs)if("video/AV1"===n.mimeType){t=!0;break}return t}function ea(){if(!("getCapabilities"in RTCRtpSender))return!1;if(oa())return!1;if(aa()){const e=Eo();if((null==e?void 0:e.version)&&ga(e.version,"16")<0)return!1}const e=RTCRtpSender.getCapabilities("video");let t=!1;if(e)for(const n of e.codecs)if("video/VP9"===n.mimeType){t=!0;break}return t}function ta(e){return"av1"===e||"vp9"===e}function na(e){return!!document&&(e||(e=document.createElement("audio")),"setSinkId"in e)}const ia={Chrome:"100",Safari:"15",Firefox:"100"};function sa(){return"undefined"!=typeof RTCPeerConnection&&(Xo()||Zo())}function oa(){var e;return"Firefox"===(null===(e=Eo())||void 0===e?void 0:e.name)}function aa(){var e;return"Safari"===(null===(e=Eo())||void 0===e?void 0:e.name)}function ra(){const e=Eo();return"Safari"===(null==e?void 0:e.name)&&e.version.startsWith("17.")}function ca(){return!!da()&&/Tablet|iPad|Mobile|Android|BlackBerry/.test(navigator.userAgent)}function da(){return"undefined"!=typeof document}function la(){return"ReactNative"==navigator.product}function ua(e){return e.hostname.endsWith(".livekit.cloud")||e.hostname.endsWith(".livekit.run")}function ha(){if(global&&global.LiveKitReactNativeGlobal)return global.LiveKitReactNativeGlobal}function ma(){if(!la())return;let e=ha();return e?e.platform:void 0}function pa(){if(da())return window.devicePixelRatio;if(la()){let e=ha();if(e)return e.devicePixelRatio}return 1}function ga(e,t){const n=e.split("."),i=t.split("."),s=Math.min(n.length,i.length);for(let e=0;e<s;++e){const t=parseInt(n[e],10),o=parseInt(i[e],10);if(t>o)return 1;if(t<o)return-1;if(e===s-1&&t===o)return 0}return""===e&&""!==t?-1:""===t?1:n.length==i.length?0:n.length<i.length?-1:1}function fa(e){for(const t of e)t.target.handleResize(t)}function va(e){for(const t of e)t.target.handleVisibilityChanged(t)}let ka=null;const Ta=()=>(ka||(ka=new ResizeObserver(fa)),ka);let ya=null;const ba=()=>(ya||(ya=new IntersectionObserver(va,{root:null,rootMargin:"0px"})),ya);let Ca,Sa;function Ea(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:16,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:16,n=arguments.length>2&&void 0!==arguments[2]&&arguments[2],i=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),i&&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(),[r]=a.getTracks();if(!r)throw Error("Could not get empty media stream video track");return r.enabled=n,r}function wa(){if(!Sa){const e=new AudioContext,t=e.createOscillator(),n=e.createGain();n.gain.setValueAtTime(0,0);const i=e.createMediaStreamDestination();if(t.connect(n),n.connect(i),t.start(),[Sa]=i.stream.getAudioTracks(),!Sa)throw Error("Could not get empty media stream audio track");Sa.enabled=!1}return Sa.clone()}class Pa{constructor(e,t){this.onFinally=t,this.promise=new Promise(((t,n)=>wi(this,void 0,void 0,(function*(){this.resolve=t,this.reject=n,e&&(yield e(t,n))})))).finally((()=>{var e;return null===(e=this.onFinally)||void 0===e?void 0:e.call(this)}))}}class Ra{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()})),n=this._locking.then((()=>e));return this._locking=this._locking.then((()=>t)),n}}function _a(e){if("string"==typeof e)return e;if(Array.isArray(e))return e[0];if(e.exact)return Array.isArray(e.exact)?e.exact[0]:e.exact;if(e.ideal)return Array.isArray(e.ideal)?e.ideal[0]:e.ideal;throw Error("could not unwrap constraint")}function Ia(e){return e.startsWith("ws")?e.replace(/^(ws)/,"http"):e}const Oa="default";class Ma{static getInstance(){return void 0===this.instance&&(this.instance=new Ma),this.instance}getDevices(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];var n;return wi(this,void 0,void 0,(function*(){if((null===(n=Ma.userMediaPromiseMap)||void 0===n?void 0:n.size)>0){ki.debug("awaiting getUserMedia promise");try{e?yield Ma.userMediaPromiseMap.get(e):yield Promise.all(Ma.userMediaPromiseMap.values())}catch(e){ki.warn("error waiting for media permissons")}}let i=yield navigator.mediaDevices.enumerateDevices();if(t&&(!aa()||!this.hasDeviceInUse(e))){if(0===i.length||i.some((t=>{const n=""===t.label,i=!e||t.kind===e;return n&&i}))){const t={video:"audioinput"!==e&&"audiooutput"!==e,audio:"videoinput"!==e},n=yield navigator.mediaDevices.getUserMedia(t);i=yield navigator.mediaDevices.enumerateDevices(),n.getTracks().forEach((e=>{e.stop()}))}}return e&&(i=i.filter((t=>t.kind===e))),i}))}normalizeDeviceId(e,t,n){return wi(this,void 0,void 0,(function*(){if(t!==Oa)return t;const i=yield this.getDevices(e),s=new Map(i.map((e=>[e.groupId,0])));i.forEach((e=>{var t;return s.set(e.groupId,(null!==(t=s.get(e.groupId))&&void 0!==t?t:0)+1)}));const o=i.find((e=>{var t;return(n===e.groupId||(null!==(t=s.get(e.groupId))&&void 0!==t?t:0)>1)&&e.deviceId!==Oa}));return null==o?void 0:o.deviceId}))}hasDeviceInUse(e){return e?Ma.userMediaPromiseMap.has(e):Ma.userMediaPromiseMap.size>0}}Ma.mediaDeviceKinds=["audioinput","audiooutput","videoinput"],Ma.userMediaPromiseMap=new Map;class xa extends jo{get constraints(){return this._constraints}constructor(t,n,i){let s=arguments.length>3&&void 0!==arguments[3]&&arguments[3];super(t,n,arguments.length>4?arguments[4]:void 0),this._isUpstreamPaused=!1,this.handleTrackMuteEvent=()=>this.debouncedTrackMuteHandler().catch((()=>this.log.debug("track mute bounce got cancelled by an unmute event",this.logContext))),this.debouncedTrackMuteHandler=bo((()=>wi(this,void 0,void 0,(function*(){yield this.pauseUpstream()}))),5e3),this.handleTrackUnmuteEvent=()=>wi(this,void 0,void 0,(function*(){this.debouncedTrackMuteHandler.cancel("unmute"),yield this.resumeUpstream()})),this.handleEnded=()=>{this.isInBackground&&(this.reacquireTrack=!0),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent),this.emit(e.TrackEvent.Ended,this)},this.reacquireTrack=!1,this.providedByUser=s,this.muteLock=new Ra,this.pauseUpstreamLock=new Ra,this.processorLock=new Ra,this.restartLock=new Ra,this.setMediaStreamTrack(t,!0),this._constraints=t.getConstraints(),i&&(this._constraints=i)}get id(){return this._mediaStreamTrack.id}get dimensions(){if(this.kind!==jo.Kind.Video)return;const{width:e,height:t}=this._mediaStreamTrack.getSettings();return e&&t?{width:e,height:t}:void 0}get isUpstreamPaused(){return this._isUpstreamPaused}get isUserProvided(){return this.providedByUser}get mediaStreamTrack(){var e,t;return null!==(t=null===(e=this.processor)||void 0===e?void 0:e.processedTrack)&&void 0!==t?t:this._mediaStreamTrack}setMediaStreamTrack(e,t){return wi(this,void 0,void 0,(function*(){if(e===this._mediaStreamTrack&&!t)return;let n;if(this._mediaStreamTrack&&(this.attachedElements.forEach((e=>{Bo(this._mediaStreamTrack,e)})),this.debouncedTrackMuteHandler.cancel("new-track"),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent)),this.mediaStream=new MediaStream([e]),e&&(e.addEventListener("ended",this.handleEnded),e.addEventListener("mute",this.handleTrackMuteEvent),e.addEventListener("unmute",this.handleTrackUnmuteEvent),this._constraints=e.getConstraints()),this.processor&&e){const t=yield this.processorLock.lock();try{if(this.log.debug("restarting processor",this.logContext),"unknown"===this.kind)throw TypeError("cannot set processor on track of unknown kind");this.processorElement&&(Fo(e,this.processorElement),this.processorElement.muted=!0),yield this.processor.restart({track:e,kind:this.kind,element:this.processorElement}),n=this.processor.processedTrack}finally{t()}}this.sender&&(yield this.sender.replaceTrack(null!=n?n:e)),this.providedByUser||this._mediaStreamTrack===e||this._mediaStreamTrack.stop(),this._mediaStreamTrack=e,e&&(this._mediaStreamTrack.enabled=!this.isMuted,yield this.resumeUpstream(),this.attachedElements.forEach((t=>{Fo(null!=n?n:e,t)})))}))}waitForDimensions(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1e3;var t;return wi(this,void 0,void 0,(function*(){if(this.kind===jo.Kind.Audio)throw new Error("cannot get dimensions for audio tracks");"iOS"===(null===(t=Eo())||void 0===t?void 0:t.os)&&(yield Yo(10));const n=Date.now();for(;Date.now()-n<e;){const e=this.dimensions;if(e)return e;yield Yo(50)}throw new ho("unable to get track dimensions after timeout")}))}getDeviceId(){return wi(this,void 0,void 0,(function*(){if(this.source===jo.Source.ScreenShare)return;const{deviceId:e,groupId:t}=this._mediaStreamTrack.getSettings(),n=this.kind===jo.Kind.Audio?"audioinput":"videoinput";return Ma.getInstance().normalizeDeviceId(n,e,t)}))}mute(){return wi(this,void 0,void 0,(function*(){return this.setTrackMuted(!0),this}))}unmute(){return wi(this,void 0,void 0,(function*(){return this.setTrackMuted(!1),this}))}replaceTrack(e,t){return wi(this,void 0,void 0,(function*(){if(!this.sender)throw new ho("unable to replace an unpublished track");let n,i;return"boolean"==typeof t?n=t:void 0!==t&&(n=t.userProvidedTrack,i=t.stopProcessor),this.providedByUser=null==n||n,this.log.debug("replace MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(e),i&&this.processor&&(yield this.stopProcessor()),this}))}restart(t){return wi(this,void 0,void 0,(function*(){const n=yield this.restartLock.lock();try{t||(t=this._constraints),this.log.debug("restarting track with constraints",Object.assign(Object.assign({},this.logContext),{constraints:t}));const n={audio:!1,video:!1};this.kind===jo.Kind.Video?n.video=t:n.audio=t,this.attachedElements.forEach((e=>{Bo(this.mediaStreamTrack,e)})),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.stop();const i=(yield navigator.mediaDevices.getUserMedia(n)).getTracks()[0];return i.addEventListener("ended",this.handleEnded),this.log.debug("re-acquired MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(i),this._constraints=t,this.emit(e.TrackEvent.Restarted,this),this}finally{n()}}))}setTrackMuted(t){this.log.debug("setting ".concat(this.kind," track ").concat(t?"muted":"unmuted"),this.logContext),this.isMuted===t&&this._mediaStreamTrack.enabled!==t||(this.isMuted=t,this._mediaStreamTrack.enabled=!t,this.emit(t?e.TrackEvent.Muted:e.TrackEvent.Unmuted,this))}get needsReAcquisition(){return"live"!==this._mediaStreamTrack.readyState||this._mediaStreamTrack.muted||!this._mediaStreamTrack.enabled||this.reacquireTrack}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return wi(this,void 0,void 0,(function*(){yield e.handleAppVisibilityChanged.call(this),ca()&&(this.log.debug("visibility changed, is in Background: ".concat(this.isInBackground),this.logContext),this.isInBackground||!this.needsReAcquisition||this.isUserProvided||this.isMuted||(this.log.debug("track needs to be reacquired, restarting ".concat(this.source),this.logContext),yield this.restart(),this.reacquireTrack=!1))}))}stop(){var e;super.stop(),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent),null===(e=this.processor)||void 0===e||e.destroy(),this.processor=void 0}pauseUpstream(){return wi(this,void 0,void 0,(function*(){const t=yield this.pauseUpstreamLock.lock();try{if(!0===this._isUpstreamPaused)return;if(!this.sender)return void this.log.warn("unable to pause upstream for an unpublished track",this.logContext);this._isUpstreamPaused=!0,this.emit(e.TrackEvent.UpstreamPaused,this);const t=Eo();if("Safari"===(null==t?void 0:t.name)&&ga(t.version,"12.0")<0)throw new uo("pauseUpstream is not supported on Safari < 12.");yield this.sender.replaceTrack(null)}finally{t()}}))}resumeUpstream(){return wi(this,void 0,void 0,(function*(){const t=yield this.pauseUpstreamLock.lock();try{if(!1===this._isUpstreamPaused)return;if(!this.sender)return void this.log.warn("unable to resume upstream for an unpublished track",this.logContext);this._isUpstreamPaused=!1,this.emit(e.TrackEvent.UpstreamResumed,this),yield this.sender.replaceTrack(this._mediaStreamTrack)}finally{t()}}))}getRTCStatsReport(){var e;return wi(this,void 0,void 0,(function*(){if(!(null===(e=this.sender)||void 0===e?void 0:e.getStats))return;return yield this.sender.getStats()}))}setProcessor(t){let n=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];var i,s;return wi(this,void 0,void 0,(function*(){const o=yield this.processorLock.lock();try{this.log.debug("setting up processor",this.logContext);const o={kind:this.kind,track:this._mediaStreamTrack,element:this.processorElement,audioContext:this.audioContext};if(yield t.init(o),this.processor&&(yield this.stopProcessor()),"unknown"===this.kind)throw TypeError("cannot set processor on track of unknown kind");if(this.processorElement=null!==(i=this.processorElement)&&void 0!==i?i:document.createElement(this.kind),Fo(this._mediaStreamTrack,this.processorElement),this.processorElement.muted=!0,this.processorElement.play().catch((e=>this.log.error("failed to play processor element",Object.assign(Object.assign({},this.logContext),{error:e})))),this.processor=t,this.processor.processedTrack){for(const e of this.attachedElements)e!==this.processorElement&&n&&(Bo(this._mediaStreamTrack,e),Fo(this.processor.processedTrack,e));yield null===(s=this.sender)||void 0===s?void 0:s.replaceTrack(this.processor.processedTrack)}this.emit(e.TrackEvent.TrackProcessorUpdate,this.processor)}finally{o()}}))}getProcessor(){return this.processor}stopProcessor(){var t,n;return wi(this,void 0,void 0,(function*(){this.processor&&(this.log.debug("stopping processor",this.logContext),null===(t=this.processor.processedTrack)||void 0===t||t.stop(),yield this.processor.destroy(),this.processor=void 0,null===(n=this.processorElement)||void 0===n||n.remove(),this.processorElement=void 0,yield this._mediaStreamTrack.applyConstraints(this._constraints),yield this.setMediaStreamTrack(this._mediaStreamTrack,!0),this.emit(e.TrackEvent.TrackProcessorUpdate))}))}}class Da extends Gi.EventEmitter{constructor(t){super(),this.onWorkerMessage=t=>{var n,i;const{kind:s,data:o}=t.data;switch(s){case"error":ki.error(o.error.message),this.emit(e.EncryptionEvent.EncryptionError,o.error);break;case"initAck":o.enabled&&this.keyProvider.getKeys().forEach((e=>{this.postKey(e)}));break;case"enable":if(this.encryptionEnabled!==o.enabled&&o.participantIdentity===(null===(n=this.room)||void 0===n?void 0:n.localParticipant.identity))this.emit(e.EncryptionEvent.ParticipantEncryptionStatusChanged,o.enabled,this.room.localParticipant),this.encryptionEnabled=o.enabled;else if(o.participantIdentity){const t=null===(i=this.room)||void 0===i?void 0:i.getParticipantByIdentity(o.participantIdentity);if(!t)throw TypeError("couldn't set encryption status, participant not found".concat(o.participantIdentity));this.emit(e.EncryptionEvent.ParticipantEncryptionStatusChanged,o.enabled,t)}this.encryptionEnabled&&this.keyProvider.getKeys().forEach((e=>{this.postKey(e)}));break;case"ratchetKey":this.keyProvider.emit(e.KeyProviderEvent.KeyRatcheted,o.material,o.keyIndex)}},this.onWorkerError=t=>{ki.error("e2ee worker encountered an error:",{error:t.error}),this.emit(e.EncryptionEvent.EncryptionError,t.error)},this.keyProvider=t.keyProvider,this.worker=t.worker,this.encryptionEnabled=!1}setup(e){if(!to())throw new uo("tried to setup end-to-end encryption on an unsupported browser");if(ki.info("setting up e2ee"),e!==this.room){this.room=e,this.setupEventListeners(e,this.keyProvider);const t={kind:"init",data:{keyProviderOptions:this.keyProvider.getOptions(),loglevel:bi.getLevel()}};this.worker&&(ki.info("initializing worker",{worker:this.worker}),this.worker.onmessage=this.onWorkerMessage,this.worker.onerror=this.onWorkerError,this.worker.postMessage(t))}}setParticipantCryptorEnabled(e,t){ki.debug("set e2ee to ".concat(e," for participant ").concat(t)),this.postEnable(e,t)}setSifTrailer(e){e&&0!==e.length?this.postSifTrailer(e):ki.warn("ignoring server sent trailer as it's empty")}setupEngine(t){t.on(e.EngineEvent.RTPVideoMapUpdate,(e=>{this.postRTPMap(e)}))}setupEventListeners(t,n){t.on(e.RoomEvent.TrackPublished,((e,t)=>this.setParticipantCryptorEnabled(e.trackInfo.encryption!==Xe.NONE,t.identity))),t.on(e.RoomEvent.ConnectionStateChanged,(n=>{n===e.ConnectionState.Connected&&t.remoteParticipants.forEach((e=>{e.trackPublications.forEach((t=>{this.setParticipantCryptorEnabled(t.trackInfo.encryption!==Xe.NONE,e.identity)}))}))})).on(e.RoomEvent.TrackUnsubscribed,((e,t,n)=>{var i;const s={kind:"removeTransform",data:{participantIdentity:n.identity,trackId:e.mediaStreamID}};null===(i=this.worker)||void 0===i||i.postMessage(s)})).on(e.RoomEvent.TrackSubscribed,((e,t,n)=>{this.setupE2EEReceiver(e,n.identity,t.trackInfo)})).on(e.RoomEvent.SignalConnected,(()=>{if(!this.room)throw new TypeError("expected room to be present on signal connect");this.setParticipantCryptorEnabled(this.room.localParticipant.isE2EEEnabled,this.room.localParticipant.identity),n.getKeys().forEach((e=>{this.postKey(e)}))})),t.localParticipant.on(e.ParticipantEvent.LocalTrackPublished,(e=>wi(this,void 0,void 0,(function*(){this.setupE2EESender(e.track,e.track.sender)})))),n.on(e.KeyProviderEvent.SetKey,(e=>this.postKey(e))).on(e.KeyProviderEvent.RatchetRequest,((e,t)=>this.postRatchetRequest(e,t)))}postRatchetRequest(e,t){if(!this.worker)throw Error("could not ratchet key, worker is missing");const n={kind:"ratchetRequest",data:{participantIdentity:e,keyIndex:t}};this.worker.postMessage(n)}postKey(e){let{key:t,participantIdentity:n,keyIndex:i}=e;var s;if(!this.worker)throw Error("could not set key, worker is missing");const o={kind:"setKey",data:{participantIdentity:n,isPublisher:n===(null===(s=this.room)||void 0===s?void 0:s.localParticipant.identity),key:t,keyIndex:i}};this.worker.postMessage(o)}postEnable(e,t){if(!this.worker)throw new ReferenceError("failed to enable e2ee, worker is not ready");{const n={kind:"enable",data:{enabled:e,participantIdentity:t}};this.worker.postMessage(n)}}postRTPMap(e){var t;if(!this.worker)throw TypeError("could not post rtp map, worker is missing");if(!(null===(t=this.room)||void 0===t?void 0:t.localParticipant.identity))throw TypeError("could not post rtp map, local participant identity is missing");const n={kind:"setRTPMap",data:{map:e,participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(n)}postSifTrailer(e){if(!this.worker)throw Error("could not post SIF trailer, worker is missing");const t={kind:"setSifTrailer",data:{trailer:e}};this.worker.postMessage(t)}setupE2EEReceiver(e,t,n){if(e.receiver){if(!(null==n?void 0:n.mimeType)||""===n.mimeType)throw new TypeError("MimeType missing from trackInfo, cannot set up E2EE cryptor");this.handleReceiver(e.receiver,e.mediaStreamID,t,"video"===e.kind?Ho(n.mimeType):void 0)}}setupE2EESender(e,t){e instanceof xa&&t?this.handleSender(t,e.mediaStreamID,void 0):t||ki.warn("early return because sender is not ready")}handleReceiver(e,t,n,i){return wi(this,void 0,void 0,(function*(){if(this.worker){if(no()){const s={kind:"decode",participantIdentity:n,trackId:t,codec:i};e.transform=new RTCRtpScriptTransform(this.worker,s)}else{if(Xs in e&&i){const e={kind:"updateCodec",data:{trackId:t,codec:i,participantIdentity:n}};return void this.worker.postMessage(e)}let s=e.writableStream,o=e.readableStream;if(!s||!o){const t=e.createEncodedStreams();e.writableStream=t.writable,s=t.writable,e.readableStream=t.readable,o=t.readable}const a={kind:"decode",data:{readableStream:o,writableStream:s,trackId:t,codec:i,participantIdentity:n}};this.worker.postMessage(a,[o,s])}e[Xs]=!0}}))}handleSender(e,t,n){var i;if(!(Xs in e)&&this.worker){if(!(null===(i=this.room)||void 0===i?void 0:i.localParticipant.identity)||""===this.room.localParticipant.identity)throw TypeError("local identity needs to be known in order to set up encrypted sender");if(no()){ki.info("initialize script transform");const i={kind:"encode",participantIdentity:this.room.localParticipant.identity,trackId:t,codec:n};e.transform=new RTCRtpScriptTransform(this.worker,i)}else{ki.info("initialize encoded streams");const i=e.createEncodedStreams(),s={kind:"encode",data:{readableStream:i.readable,writableStream:i.writable,codec:n,trackId:t,participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(s,[i.readable,i.writable])}e[Xs]=!0}}}var Na;!function(e){e[e.WAITING=0]="WAITING",e[e.RUNNING=1]="RUNNING",e[e.COMPLETED=2]="COMPLETED"}(Na||(Na={}));class La{constructor(){this.pendingTasks=new Map,this.taskMutex=new Ra,this.nextTaskIndex=0}run(e){return wi(this,void 0,void 0,(function*(){const t={id:this.nextTaskIndex++,enqueuedAt:Date.now(),status:Na.WAITING};this.pendingTasks.set(t.id,t);const n=yield this.taskMutex.lock();try{return t.executedAt=Date.now(),t.status=Na.RUNNING,yield e()}finally{t.status=Na.COMPLETED,this.pendingTasks.delete(t.id),n()}}))}flush(){return wi(this,void 0,void 0,(function*(){return this.run((()=>wi(this,void 0,void 0,(function*(){}))))}))}snapshot(){return Array.from(this.pendingTasks.values())}}const Aa=["syncState","trickle","offer","answer","simulate","leave"];var Ua;!function(e){e[e.CONNECTING=0]="CONNECTING",e[e.CONNECTED=1]="CONNECTED",e[e.RECONNECTING=2]="RECONNECTING",e[e.DISCONNECTING=3]="DISCONNECTING",e[e.DISCONNECTED=4]="DISCONNECTED"}(Ua||(Ua={}));class ja{get currentState(){return this.state}get isDisconnected(){return this.state===Ua.DISCONNECTING||this.state===Ua.DISCONNECTED}get isEstablishingConnection(){return this.state===Ua.CONNECTING||this.state===Ua.RECONNECTING}constructor(){let t=arguments.length>0&&void 0!==arguments[0]&&arguments[0],n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};var i;this.rtt=0,this.state=Ua.DISCONNECTED,this.log=ki,this.resetCallbacks=()=>{this.onAnswer=void 0,this.onLeave=void 0,this.onLocalTrackPublished=void 0,this.onLocalTrackUnpublished=void 0,this.onNegotiateRequested=void 0,this.onOffer=void 0,this.onRemoteMuteChanged=void 0,this.onSubscribedQualityUpdate=void 0,this.onTokenRefresh=void 0,this.onTrickle=void 0,this.onClose=void 0},this.log=yi(null!==(i=n.loggerName)&&void 0!==i?i:e.LoggerNames.Signal),this.loggerContextCb=n.loggerContextCb,this.useJSON=t,this.requestQueue=new La,this.queuedRequests=[],this.closingLock=new Ra,this.connectionLock=new Ra,this.state=Ua.DISCONNECTED}get logContext(){var e,t;return null!==(t=null===(e=this.loggerContextCb)||void 0===e?void 0:e.call(this))&&void 0!==t?t:{}}join(e,t,n,i){return wi(this,void 0,void 0,(function*(){this.state=Ua.CONNECTING,this.options=n;return yield this.connect(e,t,n,i)}))}reconnect(e,t,n,i){return wi(this,void 0,void 0,(function*(){if(!this.options)return void this.log.warn("attempted to reconnect without signal options being set, ignoring",this.logContext);this.state=Ua.RECONNECTING,this.clearPingInterval();return yield this.connect(e,t,Object.assign(Object.assign({},this.options),{reconnect:!0,sid:n,reconnectReason:i}))}))}connect(e,t,n,i){this.connectOptions=n,e=(e=function(e){return e.startsWith("http")?e.replace(/^(http)/,"ws"):e}(e)).replace(/\/$/,""),e+="/rtc";const s=function(e,t,n){var i;const s=new URLSearchParams;s.set("access_token",e),n.reconnect&&(s.set("reconnect","1"),n.sid&&s.set("sid",n.sid));s.set("auto_subscribe",n.autoSubscribe?"1":"0"),s.set("sdk",la()?"reactnative":"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);n.adaptiveStream&&s.set("adaptive_stream","1");n.reconnectReason&&s.set("reconnect_reason",n.reconnectReason.toString());(null===(i=navigator.connection)||void 0===i?void 0:i.type)&&s.set("network",navigator.connection.type);return"?".concat(s.toString())}(t,function(){var e;const t=new lt({sdk:ut.JS,protocol:12,version:Ro});return la()&&(t.os=null!==(e=ma())&&void 0!==e?e:""),t}(),n);return new Promise(((t,o)=>wi(this,void 0,void 0,(function*(){const a=yield this.connectionLock.lock();try{const a=()=>wi(this,void 0,void 0,(function*(){this.close(),clearTimeout(r),o(new lo("room connection has been cancelled (signal)"))})),r=setTimeout((()=>{this.close(),o(new lo("room connection has timed out (signal)"))}),n.websocketTimeout);(null==i?void 0:i.aborted)&&a(),null==i||i.addEventListener("abort",a),this.log.debug("connecting to ".concat(e+s),this.logContext),this.ws&&(yield this.close(!1)),this.ws=new WebSocket(e+s),this.ws.binaryType="arraybuffer",this.ws.onopen=()=>{clearTimeout(r)},this.ws.onerror=t=>wi(this,void 0,void 0,(function*(){if(this.state===Ua.CONNECTED)this.handleWSError(t);else{this.state=Ua.DISCONNECTED,clearTimeout(r);try{const t=yield fetch("http".concat(e.substring(2),"/validate").concat(s));if(t.status.toFixed(0).startsWith("4")){const e=yield t.text();o(new lo(e,0,t.status))}else o(new lo("Internal error",2,t.status))}catch(e){o(new lo("server was not reachable",1))}}})),this.ws.onmessage=e=>wi(this,void 0,void 0,(function*(){var s,r,c;let d;if("string"==typeof e.data){const t=JSON.parse(e.data);d=un.fromJson(t,{ignoreUnknownFields:!0})}else{if(!(e.data instanceof ArrayBuffer))return void this.log.error("could not decode websocket message: ".concat(typeof e.data),this.logContext);d=un.fromBinary(new Uint8Array(e.data))}if(this.state!==Ua.CONNECTED){let e=!1;if("join"===(null===(s=d.message)||void 0===s?void 0:s.case)?(this.state=Ua.CONNECTED,null==i||i.removeEventListener("abort",a),this.pingTimeoutDuration=d.message.value.pingTimeout,this.pingIntervalDuration=d.message.value.pingInterval,this.pingTimeoutDuration&&this.pingTimeoutDuration>0&&(this.log.debug("ping config",Object.assign(Object.assign({},this.logContext),{timeout:this.pingTimeoutDuration,interval:this.pingIntervalDuration})),this.startPingInterval()),t(d.message.value)):this.state===Ua.RECONNECTING&&"leave"!==d.message.case?(this.state=Ua.CONNECTED,null==i||i.removeEventListener("abort",a),this.startPingInterval(),"reconnect"===(null===(r=d.message)||void 0===r?void 0:r.case)?t(d.message.value):(this.log.debug("declaring signal reconnected without reconnect response received",this.logContext),t(void 0),e=!0)):this.isEstablishingConnection&&"leave"===d.message.case?o(new lo("Received leave request while trying to (re)connect",4)):n.reconnect||o(new lo("did not receive join response, got ".concat(null===(c=d.message)||void 0===c?void 0:c.case," instead"))),!e)return}this.signalLatency&&(yield Yo(this.signalLatency)),this.handleSignalResponse(d)})),this.ws.onclose=e=>{this.isEstablishingConnection&&o(new lo("Websocket got closed during a (re)connection attempt")),this.log.warn("websocket closed",Object.assign(Object.assign({},this.logContext),{reason:e.reason,code:e.code,wasClean:e.wasClean,state:this.state})),this.handleOnClose(e.reason)}}finally{a()}}))))}close(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return wi(this,void 0,void 0,(function*(){const t=yield this.closingLock.lock();try{if(e&&(this.state=Ua.DISCONNECTING),this.ws){this.ws.onmessage=null,this.ws.onopen=null,this.ws.onclose=null;const e=new Promise((e=>{this.ws?this.ws.onclose=()=>{e()}:e()}));this.ws.readyState<this.ws.CLOSING&&(this.ws.close(),yield Promise.race([e,Yo(250)])),this.ws=void 0}}finally{e&&(this.state=Ua.DISCONNECTED),this.clearPingInterval(),t()}}))}sendOffer(e){this.log.debug("sending offer",Object.assign(Object.assign({},this.logContext),{offerSdp:e.sdp})),this.sendRequest({case:"offer",value:Ba(e)})}sendAnswer(e){return this.log.debug("sending answer",Object.assign(Object.assign({},this.logContext),{answerSdp:e.sdp})),this.sendRequest({case:"answer",value:Ba(e)})}sendIceCandidate(e,t){return this.log.trace("sending ice candidate",Object.assign(Object.assign({},this.logContext),{candidate:e})),this.sendRequest({case:"trickle",value:new pn({candidateInit:JSON.stringify(e),target:t})})}sendMuteTrack(e,t){return this.sendRequest({case:"mute",value:new gn({sid:e,muted:t})})}sendAddTrack(e){return this.sendRequest({case:"addTrack",value:e})}sendUpdateLocalMetadata(e,t){return this.sendRequest({case:"updateMetadata",value:new Rn({metadata:e,name:t})})}sendUpdateTrackSettings(e){this.sendRequest({case:"trackSetting",value:e})}sendUpdateSubscription(e){return this.sendRequest({case:"subscription",value:e})}sendSyncState(e){return this.sendRequest({case:"syncState",value:e})}sendUpdateVideoLayers(e,t){return this.sendRequest({case:"updateLayers",value:new Pn({trackSid:e,layers:t})})}sendUpdateSubscriptionPermissions(e,t){return this.sendRequest({case:"subscriptionPermission",value:new Fn({allParticipants:e,trackPermissions:t})})}sendSimulateScenario(e){return this.sendRequest({case:"simulate",value:e})}sendPing(){return Promise.all([this.sendRequest({case:"ping",value:O.parse(Date.now())}),this.sendRequest({case:"pingReq",value:new Gn({timestamp:O.parse(Date.now()),rtt:O.parse(this.rtt)})})])}sendLeave(){return this.sendRequest({case:"leave",value:new En({canReconnect:!1,reason:qe.CLIENT_INITIATED})})}sendRequest(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return wi(this,void 0,void 0,(function*(){const n=!t&&!function(e){const t=Aa.indexOf(e.case)>=0;return ki.trace("request allowed to bypass queue:",{canPass:t,req:e}),t}(e);if(n&&this.state===Ua.RECONNECTING)return void this.queuedRequests.push((()=>wi(this,void 0,void 0,(function*(){yield this.sendRequest(e,!0)}))));if(t||(yield this.requestQueue.flush()),this.signalLatency&&(yield Yo(this.signalLatency)),!this.ws||this.ws.readyState!==this.ws.OPEN)return void this.log.error("cannot send signal request before connected, type: ".concat(null==e?void 0:e.case),this.logContext);const i=new ln({message:e});try{this.useJSON?this.ws.send(i.toJsonString()):this.ws.send(i.toBinary())}catch(e){this.log.error("error sending signal message",Object.assign(Object.assign({},this.logContext),{error:e}))}}))}handleSignalResponse(e){var t,n;const i=e.message;if(null==i)return void this.log.debug("received unsupported message",this.logContext);let s=!1;if("answer"===i.case){const e=Fa(i.value);this.onAnswer&&this.onAnswer(e)}else if("offer"===i.case){const e=Fa(i.value);this.onOffer&&this.onOffer(e)}else if("trickle"===i.case){const e=JSON.parse(i.value.candidateInit);this.onTrickle&&this.onTrickle(e,i.value.target)}else"update"===i.case?this.onParticipantUpdate&&this.onParticipantUpdate(null!==(t=i.value.participants)&&void 0!==t?t:[]):"trackPublished"===i.case?this.onLocalTrackPublished&&this.onLocalTrackPublished(i.value):"speakersChanged"===i.case?this.onSpeakersChanged&&this.onSpeakersChanged(null!==(n=i.value.speakers)&&void 0!==n?n:[]):"leave"===i.case?this.onLeave&&this.onLeave(i.value):"mute"===i.case?this.onRemoteMuteChanged&&this.onRemoteMuteChanged(i.value.sid,i.value.muted):"roomUpdate"===i.case?this.onRoomUpdate&&i.value.room&&this.onRoomUpdate(i.value.room):"connectionQuality"===i.case?this.onConnectionQuality&&this.onConnectionQuality(i.value):"streamStateUpdate"===i.case?this.onStreamStateUpdate&&this.onStreamStateUpdate(i.value):"subscribedQualityUpdate"===i.case?this.onSubscribedQualityUpdate&&this.onSubscribedQualityUpdate(i.value):"subscriptionPermissionUpdate"===i.case?this.onSubscriptionPermissionUpdate&&this.onSubscriptionPermissionUpdate(i.value):"refreshToken"===i.case?this.onTokenRefresh&&this.onTokenRefresh(i.value):"trackUnpublished"===i.case?this.onLocalTrackUnpublished&&this.onLocalTrackUnpublished(i.value):"subscriptionResponse"===i.case?this.onSubscriptionError&&this.onSubscriptionError(i.value):"pong"===i.case||("pongResp"===i.case?(this.rtt=Date.now()-Number.parseInt(i.value.lastPingTimestamp.toString()),this.resetPingTimeout(),s=!0):this.log.debug("unsupported message",Object.assign(Object.assign({},this.logContext),{msgCase:i.case})));s||this.resetPingTimeout()}setReconnected(){for(;this.queuedRequests.length>0;){const e=this.queuedRequests.shift();e&&this.requestQueue.run(e)}}handleOnClose(e){return wi(this,void 0,void 0,(function*(){if(this.state===Ua.DISCONNECTED)return;const t=this.onClose;yield this.close(),this.log.debug("websocket connection closed: ".concat(e),Object.assign(Object.assign({},this.logContext),{reason:e})),t&&t(e)}))}handleWSError(e){this.log.error("websocket error",Object.assign(Object.assign({},this.logContext),{error:e}))}resetPingTimeout(){this.clearPingTimeout(),this.pingTimeoutDuration?this.pingTimeout=_o.setTimeout((()=>{this.log.warn("ping timeout triggered. last pong received at: ".concat(new Date(Date.now()-1e3*this.pingTimeoutDuration).toUTCString()),this.logContext),this.handleOnClose("ping timeout")}),1e3*this.pingTimeoutDuration):this.log.warn("ping timeout duration not set",this.logContext)}clearPingTimeout(){this.pingTimeout&&_o.clearTimeout(this.pingTimeout)}startPingInterval(){this.clearPingInterval(),this.resetPingTimeout(),this.pingIntervalDuration?(this.log.debug("start ping interval",this.logContext),this.pingInterval=_o.setInterval((()=>{this.sendPing()}),1e3*this.pingIntervalDuration)):this.log.warn("ping interval duration not set",this.logContext)}clearPingInterval(){this.log.debug("clearing ping interval",this.logContext),this.clearPingTimeout(),this.pingInterval&&_o.clearInterval(this.pingInterval)}}function Fa(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 Ba(e){return new yn({sdp:e.sdp,type:e.type})}var Va={},qa={exports:{}},Ka=qa.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(Ka).forEach((function(e){Ka[e].forEach((function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")}))}));var Ga=qa.exports;!function(e){var t=function(e){return String(Number(e))===e?Number(e):e},n=function(e,n,i){var s=e.name&&e.names;e.push&&!n[e.push]?n[e.push]=[]:s&&!n[e.name]&&(n[e.name]={});var o=e.push?{}:s?n[e.name]:n;!function(e,n,i,s){if(s&&!i)n[s]=t(e[1]);else for(var o=0;o<i.length;o+=1)null!=e[o+1]&&(n[i[o]]=t(e[o+1]))}(i.match(e.reg),o,e.names,e.name),e.push&&n[e.push].push(o)},i=Ga,s=RegExp.prototype.test.bind(/^([a-z])=(.*)/);e.parse=function(e){var t={},o=[],a=t;return e.split(/(\r\n|\r|\n)/).filter(s).forEach((function(e){var t=e[0],s=e.slice(2);"m"===t&&(o.push({rtp:[],fmtp:[]}),a=o[o.length-1]);for(var r=0;r<(i[t]||[]).length;r+=1){var c=i[t][r];if(c.reg.test(s))return n(c,a,s)}})),t.media=o,t};var o=function(e,n){var i=n.split(/=(.+)/,2);return 2===i.length?e[i[0]]=t(i[1]):1===i.length&&n.length>1&&(e[i[0]]=void 0),e};e.parseParams=function(e){return e.split(/;\s?/).reduce(o,{})},e.parseFmtpConfig=e.parseParams,e.parsePayloads=function(e){return e.toString().split(" ").map(Number)},e.parseRemoteCandidates=function(e){for(var n=[],i=e.split(" ").map(t),s=0;s<i.length;s+=3)n.push({component:i[s],ip:i[s+1],port:i[s+2]});return n},e.parseImageAttributes=function(e){return e.split(" ").map((function(e){return e.substring(1,e.length-1).split(",").reduce(o,{})}))},e.parseSimulcastStreamList=function(e){return e.split(";").map((function(e){return e.split(",").map((function(e){var n,i=!1;return"~"!==e[0]?n=t(e):(n=t(e.substring(1,e.length)),i=!0),{scid:n,paused:i}}))}))}}(Va);var Wa=Ga,Ha=/%[sdv%]/g,Ja=function(e){var t=1,n=arguments,i=n.length;return e.replace(Ha,(function(e){if(t>=i)return e;var s=n[t];switch(t+=1,e){case"%%":return"%";case"%s":return String(s);case"%d":return Number(s);case"%v":return""}}))},za=function(e,t,n){var i=[e+"="+(t.format instanceof Function?t.format(t.push?n:n[t.name]):t.format)];if(t.names)for(var s=0;s<t.names.length;s+=1){var o=t.names[s];t.name?i.push(n[t.name][o]):i.push(n[t.names[s]])}else i.push(n[t.name]);return Ja.apply(null,i)},Qa=["v","o","s","i","u","e","p","c","b","t","r","z","a"],Ya=["i","c","b","a"],Xa=Va,Za=function(e,t){t=t||{},null==e.version&&(e.version=0),null==e.name&&(e.name=" "),e.media.forEach((function(e){null==e.payloads&&(e.payloads="")}));var n=t.outerOrder||Qa,i=t.innerOrder||Ya,s=[];return n.forEach((function(t){Wa[t].forEach((function(n){n.name in e&&null!=e[n.name]?s.push(za(t,n,e)):n.push in e&&null!=e[n.push]&&e[n.push].forEach((function(e){s.push(za(t,n,e))}))}))})),e.media.forEach((function(e){s.push(za("m",Wa.m[0],e)),i.forEach((function(t){Wa[t].forEach((function(n){n.name in e&&null!=e[n.name]?s.push(za(t,n,e)):n.push in e&&null!=e[n.push]&&e[n.push].forEach((function(e){s.push(za(t,n,e))}))}))}))})),s.join("\r\n")+"\r\n"},$a=Za,er=Xa.parse;const tr="negotiationStarted",nr="negotiationComplete",ir="rtpVideoPayloadTypes";class sr extends Gi.EventEmitter{get pc(){return this._pc||(this._pc=this.createPC()),this._pc}constructor(t){let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};var i;super(),this.log=ki,this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate=!1,this.trackBitrates=[],this.remoteStereoMids=[],this.remoteNackMids=[],this.negotiate=bo((e=>wi(this,void 0,void 0,(function*(){this.emit(tr);try{yield this.createAndSendOffer()}catch(t){if(!e)throw t;e(t)}}))),100),this.close=()=>{this._pc&&(this._pc.close(),this._pc.onconnectionstatechange=null,this._pc.oniceconnectionstatechange=null,this._pc.onicegatheringstatechange=null,this._pc.ondatachannel=null,this._pc.onnegotiationneeded=null,this._pc.onsignalingstatechange=null,this._pc.onicecandidate=null,this._pc.ondatachannel=null,this._pc.ontrack=null,this._pc.onconnectionstatechange=null,this._pc.oniceconnectionstatechange=null,this._pc=null)},this.log=yi(null!==(i=n.loggerName)&&void 0!==i?i:e.LoggerNames.PCTransport),this.loggerOptions=n,this.config=t,this._pc=this.createPC()}createPC(){const e=new RTCPeerConnection(this.config);return e.onicecandidate=e=>{var t;e.candidate&&(null===(t=this.onIceCandidate)||void 0===t||t.call(this,e.candidate))},e.onicecandidateerror=e=>{var t;null===(t=this.onIceCandidateError)||void 0===t||t.call(this,e)},e.oniceconnectionstatechange=()=>{var t;null===(t=this.onIceConnectionStateChange)||void 0===t||t.call(this,e.iceConnectionState)},e.onsignalingstatechange=()=>{var t;null===(t=this.onSignalingStatechange)||void 0===t||t.call(this,e.signalingState)},e.onconnectionstatechange=()=>{var t;null===(t=this.onConnectionStateChange)||void 0===t||t.call(this,e.connectionState)},e.ondatachannel=e=>{var t;null===(t=this.onDataChannel)||void 0===t||t.call(this,e)},e.ontrack=e=>{var t;null===(t=this.onTrack)||void 0===t||t.call(this,e)},e}get logContext(){var e,t;return Object.assign({},null===(t=(e=this.loggerOptions).loggerContextCb)||void 0===t?void 0:t.call(e))}get isICEConnected(){return null!==this._pc&&("connected"===this.pc.iceConnectionState||"completed"===this.pc.iceConnectionState)}addIceCandidate(e){return wi(this,void 0,void 0,(function*(){if(this.pc.remoteDescription&&!this.restartingIce)return this.pc.addIceCandidate(e);this.pendingCandidates.push(e)}))}setRemoteDescription(e){var t;return wi(this,void 0,void 0,(function*(){let n;if("offer"===e.type){let{stereoMids:t,nackMids:n}=function(e){var t;const n=[],i=[],s=er(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)))&&i.push(e.mid),e.fmtp.some((t=>t.payload===o&&(t.config.includes("sprop-stereo=1")&&n.push(e.mid),!0))))})),{stereoMids:n,nackMids:i}}(e);this.remoteStereoMids=t,this.remoteNackMids=n}else if("answer"===e.type){const i=er(null!==(t=e.sdp)&&void 0!==t?t:"");i.media.forEach((e=>{"audio"===e.type&&this.trackBitrates.some((t=>{if(!t.transceiver||e.mid!=t.transceiver.mid)return!1;let n=0;if(e.rtp.some((e=>e.codec.toUpperCase()===t.codec.toUpperCase()&&(n=e.payload,!0))),0===n)return!0;let i=!1;for(const s of e.fmtp)if(s.payload===n){s.config=s.config.split(";").filter((e=>!e.includes("maxaveragebitrate"))).join(";"),t.maxbr>0&&(s.config+=";maxaveragebitrate=".concat(1e3*t.maxbr)),i=!0;break}return i||t.maxbr>0&&e.fmtp.push({payload:n,config:"maxaveragebitrate=".concat(1e3*t.maxbr)}),!0}))})),n=$a(i)}if(yield this.setMungedSDP(e,n,!0),this.pendingCandidates.forEach((e=>{this.pc.addIceCandidate(e)})),this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate)this.renegotiate=!1,yield this.createAndSendOffer();else if("answer"===e.type&&(this.emit(nr),e.sdp)){er(e.sdp).media.forEach((e=>{"video"===e.type&&this.emit(ir,e.rtp)}))}}))}createAndSendOffer(e){var t;return wi(this,void 0,void 0,(function*(){if(void 0===this.onOffer)return;if((null==e?void 0:e.iceRestart)&&(this.log.debug("restarting ICE",this.logContext),this.restartingIce=!0),this._pc&&"have-local-offer"===this._pc.signalingState){const t=this._pc.remoteDescription;if(!(null==e?void 0:e.iceRestart)||!t)return void(this.renegotiate=!0);yield this._pc.setRemoteDescription(t)}else if(!this._pc||"closed"===this._pc.signalingState)return void this.log.warn("could not createOffer with closed peer connection",this.logContext);this.log.debug("starting to negotiate",this.logContext);const n=yield this.pc.createOffer(e),i=er(null!==(t=n.sdp)&&void 0!==t?t:"");i.media.forEach((e=>{"audio"===e.type?or(e,[],[]):"video"===e.type&&(!function(e){var t,n,i,s;const o=null===(n=null===(t=e.rtp[0])||void 0===t?void 0:t.codec)||void 0===n?void 0:n.toLowerCase();if(!ta(o))return;let a=0;const r=null===(i=e.ext)||void 0===i?void 0:i.some((e=>e.uri===Qo||(e.value>a&&(a=e.value),!1)));r||null===(s=e.ext)||void 0===s||s.push({value:a+1,uri:Qo})}(e),this.trackBitrates.some((t=>{if(!e.msid||!t.cid||!e.msid.includes(t.cid))return!1;let n=0;if(e.rtp.some((e=>e.codec.toUpperCase()===t.codec.toUpperCase()&&(n=e.payload,!0))),0===n)return!0;const i=Math.round(.7*t.maxbr);for(const t of e.fmtp)if(t.payload===n){t.config.includes("x-google-start-bitrate")||(t.config+=";x-google-start-bitrate=".concat(i));break}return!0})))})),yield this.setMungedSDP(n,$a(i)),this.onOffer(n)}))}createAndSetAnswer(){var e;return wi(this,void 0,void 0,(function*(){const t=yield this.pc.createAnswer(),n=er(null!==(e=t.sdp)&&void 0!==e?e:"");return n.media.forEach((e=>{"audio"===e.type&&or(e,this.remoteStereoMids,this.remoteNackMids)})),yield this.setMungedSDP(t,$a(n)),t}))}createDataChannel(e,t){return this.pc.createDataChannel(e,t)}addTransceiver(e,t){return this.pc.addTransceiver(e,t)}addTrack(e){if(!this._pc)throw new po("PC closed, cannot add track");return this._pc.addTrack(e)}setTrackCodecBitrate(e){this.trackBitrates.push(e)}setConfiguration(e){var t;if(!this._pc)throw new po("PC closed, cannot configure");return null===(t=this._pc)||void 0===t?void 0:t.setConfiguration(e)}canRemoveTrack(){var e;return!!(null===(e=this._pc)||void 0===e?void 0:e.removeTrack)}removeTrack(e){var t;return null===(t=this._pc)||void 0===t?void 0:t.removeTrack(e)}getConnectionState(){var e,t;return null!==(t=null===(e=this._pc)||void 0===e?void 0:e.connectionState)&&void 0!==t?t:"closed"}getICEConnectionState(){var e,t;return null!==(t=null===(e=this._pc)||void 0===e?void 0:e.iceConnectionState)&&void 0!==t?t:"closed"}getSignallingState(){var e,t;return null!==(t=null===(e=this._pc)||void 0===e?void 0:e.signalingState)&&void 0!==t?t:"closed"}getTransceivers(){var e,t;return null!==(t=null===(e=this._pc)||void 0===e?void 0:e.getTransceivers())&&void 0!==t?t:[]}getSenders(){var e,t;return null!==(t=null===(e=this._pc)||void 0===e?void 0:e.getSenders())&&void 0!==t?t:[]}getLocalDescription(){var e;return null===(e=this._pc)||void 0===e?void 0:e.localDescription}getRemoteDescription(){var e;return null===(e=this.pc)||void 0===e?void 0:e.remoteDescription}getStats(){return this.pc.getStats()}getConnectedAddress(){var e;return wi(this,void 0,void 0,(function*(){if(!this._pc)return;let t="";const n=new Map,i=new Map;if((yield this._pc.getStats()).forEach((e=>{switch(e.type){case"transport":t=e.selectedCandidatePairId;break;case"candidate-pair":""===t&&e.selected&&(t=e.id),n.set(e.id,e);break;case"remote-candidate":i.set(e.id,"".concat(e.address,":").concat(e.port))}})),""===t)return;const s=null===(e=n.get(t))||void 0===e?void 0:e.remoteCandidateId;return void 0!==s?i.get(s):void 0}))}setMungedSDP(e,t,n){return wi(this,void 0,void 0,(function*(){if(t){const i=e.sdp;e.sdp=t;try{return this.log.debug("setting munged ".concat(n?"remote":"local"," description"),this.logContext),void(n?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e))}catch(n){this.log.warn("not able to set ".concat(e.type,", falling back to unmodified sdp"),Object.assign(Object.assign({},this.logContext),{error:n,sdp:t})),e.sdp=i}}try{n?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e)}catch(t){let i="unknown error";t instanceof Error?i=t.message:"string"==typeof t&&(i=t);const s={error:i,sdp:e.sdp};throw!n&&this.pc.remoteDescription&&(s.remoteSdp=this.pc.remoteDescription),this.log.error("unable to set ".concat(e.type),Object.assign(Object.assign({},this.logContext),{fields:s})),new go(i)}}))}}function or(e,t,n){let i=0;e.rtp.some((e=>"opus"===e.codec&&(i=e.payload,!0))),i>0&&(e.rtcpFb||(e.rtcpFb=[]),n.includes(e.mid)&&!e.rtcpFb.some((e=>e.payload===i&&"nack"===e.type))&&e.rtcpFb.push({payload:i,type:"nack"}),t.includes(e.mid)&&e.fmtp.some((e=>e.payload===i&&(e.config.includes("stereo=1")||(e.config+=";stereo=1"),!0))))}const ar="vp8",rr={audioPreset:e.AudioPresets.music,dtx:!0,red:!0,forceStereo:!1,simulcast:!0,screenShareEncoding:Ao.h1080fps15.encoding,stopMicTrackOnMute:!1,videoCodec:ar,backupCodec:!0},cr={autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0},dr={resolution:No.h720.resolution},lr={adaptiveStream:!1,dynacast:!1,stopLocalTrackOnUnpublish:!0,reconnectPolicy:new Ei,disconnectOnPageLeave:!0,webAudioMix:!0},ur={autoSubscribe:!0,maxRetries:1,peerConnectionTimeout:15e3,websocketTimeout:15e3};var hr;!function(e){e[e.NEW=0]="NEW",e[e.CONNECTING=1]="CONNECTING",e[e.CONNECTED=2]="CONNECTED",e[e.FAILED=3]="FAILED",e[e.CLOSING=4]="CLOSING",e[e.CLOSED=5]="CLOSED"}(hr||(hr={}));class mr{get needsPublisher(){return this.isPublisherConnectionRequired}get needsSubscriber(){return this.isSubscriberConnectionRequired}get currentState(){return this.state}constructor(t,n,i){var s;this.peerConnectionTimeout=ur.peerConnectionTimeout,this.log=ki,this.updateState=()=>{var e;const t=this.state,n=this.requiredTransports.map((e=>e.getConnectionState()));n.every((e=>"connected"===e))?this.state=hr.CONNECTED:n.some((e=>"failed"===e))?this.state=hr.FAILED:n.some((e=>"connecting"===e))?this.state=hr.CONNECTING:n.every((e=>"closed"===e))?this.state=hr.CLOSED:n.some((e=>"closed"===e))?this.state=hr.CLOSING:n.every((e=>"new"===e))&&(this.state=hr.NEW),t!==this.state&&(this.log.debug("pc state change: from ".concat(hr[t]," to ").concat(hr[this.state]),this.logContext),null===(e=this.onStateChange)||void 0===e||e.call(this,this.state,this.publisher.getConnectionState(),this.subscriber.getConnectionState()))},this.log=yi(null!==(s=i.loggerName)&&void 0!==s?s:e.LoggerNames.PCManager),this.loggerOptions=i,this.isPublisherConnectionRequired=!n,this.isSubscriberConnectionRequired=n,this.publisher=new sr(t,i),this.subscriber=new sr(t,i),this.publisher.onConnectionStateChange=this.updateState,this.subscriber.onConnectionStateChange=this.updateState,this.publisher.onIceConnectionStateChange=this.updateState,this.subscriber.onIceConnectionStateChange=this.updateState,this.publisher.onSignalingStatechange=this.updateState,this.subscriber.onSignalingStatechange=this.updateState,this.publisher.onIceCandidate=e=>{var t;null===(t=this.onIceCandidate)||void 0===t||t.call(this,e,rn.PUBLISHER)},this.subscriber.onIceCandidate=e=>{var t;null===(t=this.onIceCandidate)||void 0===t||t.call(this,e,rn.SUBSCRIBER)},this.subscriber.onDataChannel=e=>{var t;null===(t=this.onDataChannel)||void 0===t||t.call(this,e)},this.subscriber.onTrack=e=>{var t;null===(t=this.onTrack)||void 0===t||t.call(this,e)},this.publisher.onOffer=e=>{var t;null===(t=this.onPublisherOffer)||void 0===t||t.call(this,e)},this.state=hr.NEW,this.connectionLock=new Ra}get logContext(){var e,t;return Object.assign({},null===(t=(e=this.loggerOptions).loggerContextCb)||void 0===t?void 0:t.call(e))}requirePublisher(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];this.isPublisherConnectionRequired=e,this.updateState()}requireSubscriber(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];this.isSubscriberConnectionRequired=e,this.updateState()}createAndSendPublisherOffer(e){return this.publisher.createAndSendOffer(e)}setPublisherAnswer(e){return this.publisher.setRemoteDescription(e)}removeTrack(e){return this.publisher.removeTrack(e)}close(){return wi(this,void 0,void 0,(function*(){if(this.publisher&&"closed"!==this.publisher.getSignallingState()){const e=this.publisher;for(const t of e.getSenders())try{e.canRemoveTrack()&&e.removeTrack(t)}catch(e){this.log.warn("could not removeTrack",Object.assign(Object.assign({},this.logContext),{error:e}))}}yield Promise.all([this.publisher.close(),this.subscriber.close()]),this.updateState()}))}triggerIceRestart(){return wi(this,void 0,void 0,(function*(){this.subscriber.restartingIce=!0,this.needsPublisher&&(yield this.createAndSendPublisherOffer({iceRestart:!0}))}))}addIceCandidate(e,t){return wi(this,void 0,void 0,(function*(){t===rn.PUBLISHER?yield this.publisher.addIceCandidate(e):yield this.subscriber.addIceCandidate(e)}))}createSubscriberAnswerFromOffer(e){return wi(this,void 0,void 0,(function*(){this.log.debug("received server offer",Object.assign(Object.assign({},this.logContext),{RTCSdpType:e.type,sdp:e.sdp,signalingState:this.subscriber.getSignallingState().toString()})),yield this.subscriber.setRemoteDescription(e);return yield this.subscriber.createAndSetAnswer()}))}updateConfiguration(e,t){this.publisher.setConfiguration(e),this.subscriber.setConfiguration(e),t&&this.triggerIceRestart()}ensurePCTransportConnection(e,t){var n;return wi(this,void 0,void 0,(function*(){const i=yield this.connectionLock.lock();try{this.isPublisherConnectionRequired&&"connected"!==this.publisher.getConnectionState()&&"connecting"!==this.publisher.getConnectionState()&&(this.log.debug("negotiation required, start negotiating",this.logContext),this.publisher.negotiate()),yield Promise.all(null===(n=this.requiredTransports)||void 0===n?void 0:n.map((n=>this.ensureTransportConnected(n,e,t))))}finally{i()}}))}negotiate(e){return wi(this,void 0,void 0,(function*(){return new Promise(((t,n)=>wi(this,void 0,void 0,(function*(){const i=setTimeout((()=>{n("negotiation timed out")}),this.peerConnectionTimeout);e.signal.addEventListener("abort",(()=>{clearTimeout(i),n("negotiation aborted")})),this.publisher.once(tr,(()=>{e.signal.aborted||this.publisher.once(nr,(()=>{clearTimeout(i),t()}))})),yield this.publisher.negotiate((e=>{clearTimeout(i),n(e)}))}))))}))}addPublisherTransceiver(e,t){return this.publisher.addTransceiver(e,t)}addPublisherTrack(e){return this.publisher.addTrack(e)}createPublisherDataChannel(e,t){return this.publisher.createDataChannel(e,t)}getConnectedAddress(e){return e===rn.PUBLISHER||e===rn.SUBSCRIBER?this.publisher.getConnectedAddress():this.requiredTransports[0].getConnectedAddress()}get requiredTransports(){const e=[];return this.isPublisherConnectionRequired&&e.push(this.publisher),this.isSubscriberConnectionRequired&&e.push(this.subscriber),e}ensureTransportConnected(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:this.peerConnectionTimeout;return wi(this,void 0,void 0,(function*(){if("connected"!==e.getConnectionState())return new Promise(((e,i)=>wi(this,void 0,void 0,(function*(){const s=()=>{this.log.warn("abort transport connection",this.logContext),_o.clearTimeout(o),i(new lo("room connection has been cancelled",3))};(null==t?void 0:t.signal.aborted)&&s(),null==t||t.signal.addEventListener("abort",s);const o=_o.setTimeout((()=>{null==t||t.signal.removeEventListener("abort",s),i(new lo("could not establish pc connection"))}),n);for(;this.state!==hr.CONNECTED;)if(yield Yo(50),null==t?void 0:t.signal.aborted)return void i(new lo("room connection has been cancelled",3));_o.clearTimeout(o),null==t||t.signal.removeEventListener("abort",s),e()}))))}))}}const pr="_lossy",gr="_reliable",fr="leave-reconnect";var vr;!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"}(vr||(vr={}));class kr extends Gi.EventEmitter{get isClosed(){return this._isClosed}get pendingReconnect(){return!!this.reconnectTimeout}constructor(t){var n;super(),this.options=t,this.rtcConfig={},this.peerConnectionTimeout=ur.peerConnectionTimeout,this.fullReconnectOnNext=!1,this.subscriberPrimary=!1,this.pcState=vr.New,this._isClosed=!0,this.pendingTrackResolvers={},this.reconnectAttempts=0,this.reconnectStart=0,this.attemptingReconnect=!1,this.joinAttempts=0,this.maxJoinAttempts=1,this.shouldFailNext=!1,this.log=ki,this.handleDataChannel=e=>{let{channel:t}=e;return wi(this,void 0,void 0,(function*(){if(t){if(t.label===gr)this.reliableDCSub=t;else{if(t.label!==pr)return;this.lossyDCSub=t}this.log.debug("on data channel ".concat(t.id,", ").concat(t.label),this.logContext),t.onmessage=this.handleDataMessage}}))},this.handleDataMessage=t=>wi(this,void 0,void 0,(function*(){var n,i;const s=yield this.dataProcessLock.lock();try{let s;if(t.data instanceof ArrayBuffer)s=t.data;else{if(!(t.data instanceof Blob))return void this.log.error("unsupported data type",Object.assign(Object.assign({},this.logContext),{data:t.data}));s=yield t.data.arrayBuffer()}const o=tt.fromBinary(new Uint8Array(s));"speaker"===(null===(n=o.value)||void 0===n?void 0:n.case)?this.emit(e.EngineEvent.ActiveSpeakersUpdate,o.value.value.speakers):"user"===(null===(i=o.value)||void 0===i?void 0:i.case)&&this.emit(e.EngineEvent.DataPacketReceived,o.value.value,o.kind)}finally{s()}})),this.handleDataError=e=>{const t=0===e.currentTarget.maxRetransmits?"lossy":"reliable";if(e instanceof ErrorEvent&&e.error){const{error:n}=e.error;this.log.error("DataChannel error on ".concat(t,": ").concat(e.message),Object.assign(Object.assign({},this.logContext),{error:n}))}else this.log.error("Unknown DataChannel error on ".concat(t),Object.assign(Object.assign({},this.logContext),{event:e}))},this.handleBufferedAmountLow=e=>{const t=0===e.currentTarget.maxRetransmits?nt.LOSSY:nt.RELIABLE;this.updateAndEmitDCBufferStatus(t)},this.handleDisconnect=(t,n)=>{if(this._isClosed)return;this.log.warn("".concat(t," disconnected"),this.logContext),0===this.reconnectAttempts&&(this.reconnectStart=Date.now());const i=t=>{this.log.warn("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(t,"ms. giving up"),this.logContext),this.emit(e.EngineEvent.Disconnected),this.close()},s=Date.now()-this.reconnectStart;let o=this.getNextRetryDelay({elapsedMs:s,retryCount:this.reconnectAttempts});null!==o?(t===fr&&(o=0),this.log.debug("reconnecting in ".concat(o,"ms"),this.logContext),this.clearReconnectTimeout(),this.token&&this.regionUrlProvider&&this.regionUrlProvider.updateToken(this.token),this.reconnectTimeout=_o.setTimeout((()=>this.attemptReconnect(n).finally((()=>this.reconnectTimeout=void 0))),o)):i(s)},this.waitForRestarted=()=>new Promise(((t,n)=>{this.pcState===vr.Connected&&t();const i=()=>{this.off(e.EngineEvent.Disconnected,s),t()},s=()=>{this.off(e.EngineEvent.Restarted,i),n()};this.once(e.EngineEvent.Restarted,i),this.once(e.EngineEvent.Disconnected,s)})),this.updateAndEmitDCBufferStatus=t=>{const n=this.isBufferStatusLow(t);void 0!==n&&n!==this.dcBufferStatus.get(t)&&(this.dcBufferStatus.set(t,n),this.emit(e.EngineEvent.DCBufferStatusChanged,n,t))},this.isBufferStatusLow=e=>{const t=this.dataChannelForKind(e);if(t)return t.bufferedAmount<=t.bufferedAmountLowThreshold},this.handleBrowserOnLine=()=>{this.client.currentState===Ua.RECONNECTING&&(this.clearReconnectTimeout(),this.attemptReconnect(Ke.RR_SIGNAL_DISCONNECTED))},this.log=yi(null!==(n=t.loggerName)&&void 0!==n?n:e.LoggerNames.Engine),this.loggerOptions={loggerName:t.loggerName,loggerContextCb:()=>this.logContext},this.client=new ja(void 0,this.loggerOptions),this.client.signalLatency=this.options.expSignalLatency,this.reconnectPolicy=this.options.reconnectPolicy,this.registerOnLineListener(),this.closingLock=new Ra,this.dataProcessLock=new Ra,this.dcBufferStatus=new Map([[nt.LOSSY,!0],[nt.RELIABLE,!0]]),this.client.onParticipantUpdate=t=>this.emit(e.EngineEvent.ParticipantUpdate,t),this.client.onConnectionQuality=t=>this.emit(e.EngineEvent.ConnectionQualityUpdate,t),this.client.onRoomUpdate=t=>this.emit(e.EngineEvent.RoomUpdate,t),this.client.onSubscriptionError=t=>this.emit(e.EngineEvent.SubscriptionError,t),this.client.onSubscriptionPermissionUpdate=t=>this.emit(e.EngineEvent.SubscriptionPermissionUpdate,t),this.client.onSpeakersChanged=t=>this.emit(e.EngineEvent.SpeakersChanged,t),this.client.onStreamStateUpdate=t=>this.emit(e.EngineEvent.StreamStateChanged,t)}get logContext(){var e,t,n,i,s,o,a,r;return{room:null===(t=null===(e=this.latestJoinResponse)||void 0===e?void 0:e.room)||void 0===t?void 0:t.name,roomID:null===(i=null===(n=this.latestJoinResponse)||void 0===n?void 0:n.room)||void 0===i?void 0:i.sid,participant:null===(o=null===(s=this.latestJoinResponse)||void 0===s?void 0:s.participant)||void 0===o?void 0:o.identity,pID:null===(r=null===(a=this.latestJoinResponse)||void 0===a?void 0:a.participant)||void 0===r?void 0:r.sid}}join(e,t,n,i){return wi(this,void 0,void 0,(function*(){this.url=e,this.token=t,this.signalOpts=n,this.maxJoinAttempts=n.maxRetries;try{this.joinAttempts+=1,this.setupSignalClientCallbacks();const s=yield this.client.join(e,t,n,i);return this._isClosed=!1,this.latestJoinResponse=s,this.subscriberPrimary=s.subscriberPrimary,this.pcManager||(yield this.configure(s)),this.subscriberPrimary||this.negotiate(),this.clientConfiguration=s.clientConfiguration,s}catch(s){if(s instanceof lo&&1===s.reason&&(this.log.warn("Couldn't connect to server, attempt ".concat(this.joinAttempts," of ").concat(this.maxJoinAttempts),this.logContext),this.joinAttempts<this.maxJoinAttempts))return this.join(e,t,n,i);throw s}}))}close(){return wi(this,void 0,void 0,(function*(){const t=yield this.closingLock.lock();if(this.isClosed)t();else try{this._isClosed=!0,this.emit(e.EngineEvent.Closing),this.removeAllListeners(),this.deregisterOnLineListener(),this.clearPendingReconnect(),yield this.cleanupPeerConnections(),yield this.cleanupClient()}finally{t()}}))}cleanupPeerConnections(){var e;return wi(this,void 0,void 0,(function*(){yield null===(e=this.pcManager)||void 0===e?void 0:e.close(),this.pcManager=void 0;const t=e=>{e&&(e.close(),e.onbufferedamountlow=null,e.onclose=null,e.onclosing=null,e.onerror=null,e.onmessage=null,e.onopen=null)};t(this.lossyDC),t(this.lossyDCSub),t(this.reliableDC),t(this.reliableDCSub),this.lossyDC=void 0,this.lossyDCSub=void 0,this.reliableDC=void 0,this.reliableDCSub=void 0}))}cleanupClient(){return wi(this,void 0,void 0,(function*(){yield this.client.close(),this.client.resetCallbacks()}))}addTrack(e){if(this.pendingTrackResolvers[e.cid])throw new ho("a track with the same ID has already been published");return new Promise(((t,n)=>{const i=setTimeout((()=>{delete this.pendingTrackResolvers[e.cid],n(new lo("publication of local track timed out, no response from server"))}),1e4);this.pendingTrackResolvers[e.cid]={resolve:e=>{clearTimeout(i),t(e)},reject:()=>{clearTimeout(i),n(new Error("Cancelled publication by calling unpublish"))}},this.client.sendAddTrack(e)}))}removeTrack(e){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 this.pcManager.removeTrack(e),!0}catch(e){this.log.warn("failed to remove track",Object.assign(Object.assign({},this.logContext),{error:e}))}return!1}updateMuteStatus(e,t){this.client.sendMuteTrack(e,t)}get dataSubscriberReadyState(){var e;return null===(e=this.reliableDCSub)||void 0===e?void 0:e.readyState}getConnectedServerAddress(){var e;return wi(this,void 0,void 0,(function*(){return null===(e=this.pcManager)||void 0===e?void 0:e.getConnectedAddress()}))}setRegionUrlProvider(e){this.regionUrlProvider=e}configure(t){var n;return wi(this,void 0,void 0,(function*(){if(this.pcManager&&this.pcManager.currentState!==hr.NEW)return;this.participantSid=null===(n=t.participant)||void 0===n?void 0:n.sid;const i=this.makeRTCConfiguration(t);this.pcManager=new mr(i,t.subscriberPrimary,this.loggerOptions),this.emit(e.EngineEvent.TransportsCreated,this.pcManager.publisher,this.pcManager.subscriber),this.pcManager.onIceCandidate=(e,t)=>{this.client.sendIceCandidate(e,t)},this.pcManager.onPublisherOffer=e=>{this.client.sendOffer(e)},this.pcManager.onDataChannel=this.handleDataChannel,this.pcManager.onStateChange=(n,i,s)=>wi(this,void 0,void 0,(function*(){if(this.log.debug("primary PC state changed ".concat(n),this.logContext),n===hr.CONNECTED){const n=this.pcState===vr.New;this.pcState=vr.Connected,n&&this.emit(e.EngineEvent.Connected,t)}else n===hr.FAILED&&this.pcState===vr.Connected&&(this.pcState=vr.Disconnected,this.handleDisconnect("peerconnection failed","failed"===s?Ke.RR_SUBSCRIBER_FAILED:Ke.RR_PUBLISHER_FAILED));const i=this.client.isDisconnected||this.client.currentState===Ua.RECONNECTING,o=[hr.FAILED,hr.CLOSING,hr.CLOSED].includes(n);i&&o&&!this._isClosed&&this.emit(e.EngineEvent.Offline)})),this.pcManager.onTrack=t=>{this.emit(e.EngineEvent.MediaTrackAdded,t.track,t.streams[0],t.receiver)},this.createDataChannels()}))}setupSignalClientCallbacks(){this.client.onAnswer=e=>wi(this,void 0,void 0,(function*(){this.pcManager&&(this.log.debug("received server answer",Object.assign(Object.assign({},this.logContext),{RTCSdpType:e.type})),yield this.pcManager.setPublisherAnswer(e))})),this.client.onTrickle=(e,t)=>{this.pcManager&&(this.log.trace("got ICE candidate from peer",Object.assign(Object.assign({},this.logContext),{candidate:e,target:t})),this.pcManager.addIceCandidate(e,t))},this.client.onOffer=e=>wi(this,void 0,void 0,(function*(){if(!this.pcManager)return;const t=yield this.pcManager.createSubscriberAnswerFromOffer(e);this.client.sendAnswer(t)})),this.client.onLocalTrackPublished=e=>{var t;if(this.log.debug("received trackPublishedResponse",Object.assign(Object.assign({},this.logContext),{cid:e.cid,track:null===(t=e.track)||void 0===t?void 0:t.sid})),!this.pendingTrackResolvers[e.cid])return void this.log.error("missing track resolver for ".concat(e.cid),Object.assign(Object.assign({},this.logContext),{cid:e.cid}));const{resolve:n}=this.pendingTrackResolvers[e.cid];delete this.pendingTrackResolvers[e.cid],n(e.track)},this.client.onLocalTrackUnpublished=t=>{this.emit(e.EngineEvent.LocalTrackUnpublished,t)},this.client.onTokenRefresh=e=>{this.token=e},this.client.onRemoteMuteChanged=(t,n)=>{this.emit(e.EngineEvent.RemoteMute,t,n)},this.client.onSubscribedQualityUpdate=t=>{this.emit(e.EngineEvent.SubscribedQualityUpdate,t)},this.client.onClose=()=>{this.handleDisconnect("signal",Ke.RR_SIGNAL_DISCONNECTED)},this.client.onLeave=t=>{(null==t?void 0:t.canReconnect)?(this.fullReconnectOnNext=!0,this.handleDisconnect(fr)):(this.emit(e.EngineEvent.Disconnected,null==t?void 0:t.reason),this.close()),this.log.debug("client leave request",Object.assign(Object.assign({},this.logContext),{reason:null==t?void 0:t.reason}))}}makeRTCConfiguration(e){var t;const n=Object.assign({},this.rtcConfig);if((null===(t=this.signalOpts)||void 0===t?void 0:t.e2eeEnabled)&&(this.log.debug("E2EE - setting up transports with insertable streams",this.logContext),n.encodedInsertableStreams=!0),e.iceServers&&!n.iceServers){const t=[];e.iceServers.forEach((e=>{const n={urls:e.urls};e.username&&(n.username=e.username),e.credential&&(n.credential=e.credential),t.push(n)})),n.iceServers=t}return e.clientConfiguration&&e.clientConfiguration.forceRelay===Ve.ENABLED&&(n.iceTransportPolicy="relay"),n.sdpSemantics="unified-plan",n.continualGatheringPolicy="gather_continually",n}createDataChannels(){this.pcManager&&(this.lossyDC&&(this.lossyDC.onmessage=null,this.lossyDC.onerror=null),this.reliableDC&&(this.reliableDC.onmessage=null,this.reliableDC.onerror=null),this.lossyDC=this.pcManager.createPublisherDataChannel(pr,{ordered:!0,maxRetransmits:0}),this.reliableDC=this.pcManager.createPublisherDataChannel(gr,{ordered:!0}),this.lossyDC.onmessage=this.handleDataMessage,this.reliableDC.onmessage=this.handleDataMessage,this.lossyDC.onerror=this.handleDataError,this.reliableDC.onerror=this.handleDataError,this.lossyDC.bufferedAmountLowThreshold=65535,this.reliableDC.bufferedAmountLowThreshold=65535,this.lossyDC.onbufferedamountlow=this.handleBufferedAmountLow,this.reliableDC.onbufferedamountlow=this.handleBufferedAmountLow)}setPreferredCodec(e,t,n){if(!("getCapabilities"in RTCRtpSender))return;const i=RTCRtpSender.getCapabilities(t);if(!i)return;this.log.debug("get sender capabilities",Object.assign(Object.assign({},this.logContext),{cap:i}));const s=[],o=[],a=[];i.codecs.forEach((e=>{const t=e.mimeType.toLowerCase();if("audio/opus"===t)return void s.push(e);t==="video/".concat(n)?"h264"!==n||e.sdpFmtpLine&&e.sdpFmtpLine.includes("profile-level-id=42e01f")?s.push(e):o.push(e):a.push(e)})),function(e){if(!da())return!1;if(!("setCodecPreferences"in e))return!1;const t=Eo();if(!(null==t?void 0:t.name)||!t.version)return!1;const n=ia[t.name];return!!n&&ga(t.version,n)>=0}(e)&&e.setCodecPreferences(s.concat(o,a))}createSender(e,t,n){return wi(this,void 0,void 0,(function*(){if(Xo()){return yield this.createTransceiverRTCRtpSender(e,t,n)}if(Zo()){this.log.warn("using add-track fallback",this.logContext);return yield this.createRTCRtpSender(e.mediaStreamTrack)}throw new po("Required webRTC APIs not supported on this device")}))}createSimulcastSender(e,t,n,i){return wi(this,void 0,void 0,(function*(){if(Xo())return this.createSimulcastTransceiverSender(e,t,n,i);if(Zo())return this.log.debug("using add-track fallback",this.logContext),this.createRTCRtpSender(e.mediaStreamTrack);throw new po("Cannot stream on this device")}))}createTransceiverRTCRtpSender(e,t,n){return wi(this,void 0,void 0,(function*(){if(!this.pcManager)throw new po("publisher is closed");const i=[];e.mediaStream&&i.push(e.mediaStream);const s={direction:"sendonly",streams:i};n&&(s.sendEncodings=n);const o=yield this.pcManager.addPublisherTransceiver(e.mediaStreamTrack,s);return e.kind===jo.Kind.Video&&t.videoCodec&&(this.setPreferredCodec(o,e.kind,t.videoCodec),e.codec=t.videoCodec),o.sender}))}createSimulcastTransceiverSender(e,t,n,i){return wi(this,void 0,void 0,(function*(){if(!this.pcManager)throw new po("publisher is closed");const s={direction:"sendonly"};i&&(s.sendEncodings=i);const o=yield this.pcManager.addPublisherTransceiver(t.mediaStreamTrack,s);if(n.videoCodec)return this.setPreferredCodec(o,e.kind,n.videoCodec),e.setSimulcastTrackSender(n.videoCodec,o.sender),o.sender}))}createRTCRtpSender(e){return wi(this,void 0,void 0,(function*(){if(!this.pcManager)throw new po("publisher is closed");return this.pcManager.addPublisherTrack(e)}))}attemptReconnect(t){var n,i,s;return wi(this,void 0,void 0,(function*(){if(!this._isClosed)if(this.attemptingReconnect)ki.warn("already attempting reconnect, returning early",this.logContext);else{(null===(n=this.clientConfiguration)||void 0===n?void 0:n.resumeConnection)!==Ve.DISABLED&&(null!==(s=null===(i=this.pcManager)||void 0===i?void 0:i.currentState)&&void 0!==s?s:hr.NEW)!==hr.NEW||(this.fullReconnectOnNext=!0);try{this.attemptingReconnect=!0,this.fullReconnectOnNext?yield this.restartConnection():yield this.resumeConnection(t),this.clearPendingReconnect(),this.fullReconnectOnNext=!1}catch(t){this.reconnectAttempts+=1;let n=!0;t instanceof po?(this.log.debug("received unrecoverable error",Object.assign(Object.assign({},this.logContext),{error:t})),n=!1):t instanceof Tr||(this.fullReconnectOnNext=!0),n?this.handleDisconnect("reconnect",Ke.RR_UNKNOWN):(this.log.info("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(Date.now()-this.reconnectStart,"ms. giving up"),this.logContext),this.emit(e.EngineEvent.Disconnected),yield this.close())}finally{this.attemptingReconnect=!1}}}))}getNextRetryDelay(e){try{return this.reconnectPolicy.nextRetryDelayInMs(e)}catch(e){this.log.warn("encountered error in reconnect policy",Object.assign(Object.assign({},this.logContext),{error:e}))}return null}restartConnection(t){var n,i,s;return wi(this,void 0,void 0,(function*(){try{if(!this.url||!this.token)throw new po("could not reconnect, url or token not saved");let i;this.log.info("reconnecting, attempt: ".concat(this.reconnectAttempts),this.logContext),this.emit(e.EngineEvent.Restarting),this.client.isDisconnected||(yield this.client.sendLeave()),yield this.cleanupPeerConnections(),yield this.cleanupClient();try{if(!this.signalOpts)throw this.log.warn("attempted connection restart, without signal options present",this.logContext),new Tr;i=yield this.join(null!=t?t:this.url,this.token,this.signalOpts)}catch(e){if(e instanceof lo&&0===e.reason)throw new po("could not reconnect, token might be expired");throw new Tr}if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(this.client.setReconnected(),this.emit(e.EngineEvent.SignalRestarted,i),yield this.waitForPCReconnected(),this.client.currentState!==Ua.CONNECTED)throw new Tr("Signal connection got severed during reconnect");null===(n=this.regionUrlProvider)||void 0===n||n.resetAttempts(),this.emit(e.EngineEvent.Restarted)}catch(e){const t=yield null===(i=this.regionUrlProvider)||void 0===i?void 0:i.getNextBestRegionUrl();if(t)return void(yield this.restartConnection(t));throw null===(s=this.regionUrlProvider)||void 0===s||s.resetAttempts(),e}}))}resumeConnection(t){var n;return wi(this,void 0,void 0,(function*(){if(!this.url||!this.token)throw new po("could not reconnect, url or token not saved");if(!this.pcManager)throw new po("publisher and subscriber connections unset");let i;this.log.info("resuming signal connection, attempt ".concat(this.reconnectAttempts),this.logContext),this.emit(e.EngineEvent.Resuming);try{this.setupSignalClientCallbacks(),i=yield this.client.reconnect(this.url,this.token,this.participantSid,t)}catch(e){let t="";if(e instanceof Error&&(t=e.message,this.log.error(e.message,Object.assign(Object.assign({},this.logContext),{error:e}))),e instanceof lo&&0===e.reason)throw new po("could not reconnect, token might be expired");if(e instanceof lo&&4===e.reason)throw e;throw new Tr(t)}if(this.emit(e.EngineEvent.SignalResumed),i){const e=this.makeRTCConfiguration(i);this.pcManager.updateConfiguration(e)}else this.log.warn("Did not receive reconnect response",this.logContext);if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(yield this.pcManager.triggerIceRestart(),yield this.waitForPCReconnected(),this.client.currentState!==Ua.CONNECTED)throw new Tr("Signal connection got severed during reconnect");this.client.setReconnected(),"open"===(null===(n=this.reliableDC)||void 0===n?void 0:n.readyState)&&null===this.reliableDC.id&&this.createDataChannels(),this.emit(e.EngineEvent.Resumed)}))}waitForPCInitialConnection(e,t){return wi(this,void 0,void 0,(function*(){if(!this.pcManager)throw new po("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(t,e)}))}waitForPCReconnected(){return wi(this,void 0,void 0,(function*(){this.pcState=vr.Reconnecting,this.log.debug("waiting for peer connection to reconnect",this.logContext);try{if(yield Yo(2e3),!this.pcManager)throw new po("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(void 0,this.peerConnectionTimeout),this.pcState=vr.Connected}catch(e){throw this.pcState=vr.Disconnected,new lo("could not establish PC connection, ".concat(e.message))}}))}sendDataPacket(e,t){return wi(this,void 0,void 0,(function*(){const n=e.toBinary();yield this.ensurePublisherConnected(t);const i=this.dataChannelForKind(t);i&&i.send(n),this.updateAndEmitDCBufferStatus(t)}))}ensureDataTransportConnected(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.subscriberPrimary;var n;return wi(this,void 0,void 0,(function*(){if(!this.pcManager)throw new po("PC manager is closed");const i=t?this.pcManager.subscriber:this.pcManager.publisher,s=t?"Subscriber":"Publisher";if(!i)throw new lo("".concat(s," connection not set"));t||this.pcManager.publisher.isICEConnected||"checking"===this.pcManager.publisher.getICEConnectionState()||this.negotiate();const o=this.dataChannelForKind(e,t);if("open"===(null==o?void 0:o.readyState))return;const a=(new Date).getTime()+this.peerConnectionTimeout;for(;(new Date).getTime()<a;){if(i.isICEConnected&&"open"===(null===(n=this.dataChannelForKind(e,t))||void 0===n?void 0:n.readyState))return;yield Yo(50)}throw new lo("could not establish ".concat(s," connection, state: ").concat(i.getICEConnectionState()))}))}ensurePublisherConnected(e){return wi(this,void 0,void 0,(function*(){yield this.ensureDataTransportConnected(e,!1)}))}verifyTransport(){return!!this.pcManager&&(this.pcManager.currentState===hr.CONNECTED&&!(!this.client.ws||this.client.ws.readyState===WebSocket.CLOSED))}negotiate(){return wi(this,void 0,void 0,(function*(){return new Promise(((t,n)=>wi(this,void 0,void 0,(function*(){if(!this.pcManager)return void n(new go("PC manager is closed"));this.pcManager.requirePublisher();const i=new AbortController,s=()=>{i.abort(),this.log.debug("engine disconnected while negotiation was ongoing",this.logContext),t()};this.isClosed&&n("cannot negotiate on closed engine"),this.on(e.EngineEvent.Closing,s),this.pcManager.publisher.once(ir,(t=>{const n=new Map;t.forEach((e=>{const t=e.codec.toLowerCase();var i;i=t,Mo.includes(i)&&n.set(e.payload,t)})),this.emit(e.EngineEvent.RTPVideoMapUpdate,n)}));try{yield this.pcManager.negotiate(i),t()}catch(e){e instanceof go&&(this.fullReconnectOnNext=!0),this.handleDisconnect("negotiation",Ke.RR_UNKNOWN),n(e)}finally{this.off(e.EngineEvent.Closing,s)}}))))}))}dataChannelForKind(e,t){if(t){if(e===nt.LOSSY)return this.lossyDCSub;if(e===nt.RELIABLE)return this.reliableDCSub}else{if(e===nt.LOSSY)return this.lossyDC;if(e===nt.RELIABLE)return this.reliableDC}}sendSyncState(e,t){var n,i;if(!this.pcManager)return void this.log.warn("sync state cannot be sent without peer connection setup",this.logContext);const s=this.pcManager.subscriber.getLocalDescription(),o=this.pcManager.subscriber.getRemoteDescription(),a=null===(i=null===(n=this.signalOpts)||void 0===n?void 0:n.autoSubscribe)||void 0===i||i,r=new Array,c=new Array;e.forEach((e=>{e.isDesired!==a&&r.push(e.trackSid),e.isEnabled||c.push(e.trackSid)})),this.client.sendSyncState(new Vn({answer:s?Ba({sdp:s.sdp,type:s.type}):void 0,offer:o?Ba({sdp:o.sdp,type:o.type}):void 0,subscription:new Cn({trackSids:r,subscribe:!a,participantTracks:[]}),publishTracks:Jo(t),dataChannels:this.dataChannelsInfo(),trackSidsDisabled:c}))}failNext(){this.shouldFailNext=!0}dataChannelsInfo(){const e=[],t=(t,n)=>{void 0!==(null==t?void 0:t.id)&&null!==t.id&&e.push(new qn({label:t.label,id:t.id,target:n}))};return t(this.dataChannelForKind(nt.LOSSY),rn.PUBLISHER),t(this.dataChannelForKind(nt.RELIABLE),rn.PUBLISHER),t(this.dataChannelForKind(nt.LOSSY,!0),rn.SUBSCRIBER),t(this.dataChannelForKind(nt.RELIABLE,!0),rn.SUBSCRIBER),e}clearReconnectTimeout(){this.reconnectTimeout&&_o.clearTimeout(this.reconnectTimeout)}clearPendingReconnect(){this.clearReconnectTimeout(),this.reconnectAttempts=0}registerOnLineListener(){da()&&window.addEventListener("online",this.handleBrowserOnLine)}deregisterOnLineListener(){da()&&window.removeEventListener("online",this.handleBrowserOnLine)}}class Tr extends Error{}class yr{constructor(e,t){this.lastUpdateAt=0,this.settingsCacheTime=3e3,this.attemptedRegions=[],this.serverUrl=new URL(e),this.token=t}updateToken(e){this.token=e}isCloud(){return ua(this.serverUrl)}getServerUrl(){return this.serverUrl}getNextBestRegionUrl(e){return wi(this,void 0,void 0,(function*(){if(!this.isCloud())throw Error("region availability is only supported for LiveKit Cloud domains");(!this.regionSettings||Date.now()-this.lastUpdateAt>this.settingsCacheTime)&&(this.regionSettings=yield this.fetchRegionSettings(e));const t=this.regionSettings.regions.filter((e=>!this.attemptedRegions.find((t=>t.url===e.url))));if(t.length>0){const e=t[0];return this.attemptedRegions.push(e),ki.debug("next region: ".concat(e.region)),e.url}return null}))}resetAttempts(){this.attemptedRegions=[]}fetchRegionSettings(e){return wi(this,void 0,void 0,(function*(){const t=yield fetch("".concat((n=this.serverUrl,"".concat(n.protocol.replace("ws","http"),"//").concat(n.host,"/settings")),"/regions"),{headers:{authorization:"Bearer ".concat(this.token)},signal:e});var n;if(t.ok){const e=yield t.json();return this.lastUpdateAt=Date.now(),e}throw new lo("Could not fetch region settings: ".concat(t.statusText),401===t.status?0:void 0,t.status)}))}}const br=2e3;function Cr(e,t){if(!t)return 0;let n,i;return"bytesReceived"in e?(n=e.bytesReceived,i=t.bytesReceived):"bytesSent"in e&&(n=e.bytesSent,i=t.bytesSent),void 0===n||void 0===i||void 0===e.timestamp||void 0===t.timestamp?0:8*(n-i)*1e3/(e.timestamp-t.timestamp)}class Sr extends xa{constructor(e,t){let n=!(arguments.length>2&&void 0!==arguments[2])||arguments[2],i=arguments.length>3?arguments[3]:void 0,s=arguments.length>4?arguments[4]:void 0;super(e,jo.Kind.Audio,t,n,s),this.stopOnMute=!1,this.monitorSender=()=>wi(this,void 0,void 0,(function*(){if(!this.sender)return void(this._currentBitrate=0);let e;try{e=yield this.getSenderStats()}catch(e){return void this.log.error("could not get audio sender stats",Object.assign(Object.assign({},this.logContext),{error:e}))}e&&this.prevStats&&(this._currentBitrate=Cr(e,this.prevStats)),this.prevStats=e})),this.audioContext=i,this.checkForSilence()}setDeviceId(e){return wi(this,void 0,void 0,(function*(){return this._constraints.deviceId===e&&this._mediaStreamTrack.getSettings().deviceId===_a(e)||(this._constraints.deviceId=e,this.isMuted||(yield this.restartTrack()),this.isMuted||_a(e)===this._mediaStreamTrack.getSettings().deviceId)}))}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return wi(this,void 0,void 0,(function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug("Track already muted",this.logContext),this):(this.source===jo.Source.Microphone&&this.stopOnMute&&!this.isUserProvided&&(this.log.debug("stopping mic track",this.logContext),this._mediaStreamTrack.stop()),yield e.mute.call(this),this)}finally{t()}}))}unmute(){const e=Object.create(null,{unmute:{get:()=>super.unmute}});return wi(this,void 0,void 0,(function*(){const t=yield this.muteLock.lock();try{if(!this.isMuted)return this.log.debug("Track already unmuted",this.logContext),this;const t=this._constraints.deviceId&&this._mediaStreamTrack.getSettings().deviceId!==_a(this._constraints.deviceId);return this.source!==jo.Source.Microphone||!this.stopOnMute&&"ended"!==this._mediaStreamTrack.readyState&&!t||this.isUserProvided||(this.log.debug("reacquiring mic track",this.logContext),yield this.restartTrack()),yield e.unmute.call(this),this}finally{t()}}))}restartTrack(e){return wi(this,void 0,void 0,(function*(){let t;if(e){const n=Ko({audio:e});"boolean"!=typeof n.audio&&(t=n.audio)}yield this.restart(t)}))}restart(e){const t=Object.create(null,{restart:{get:()=>super.restart}});return wi(this,void 0,void 0,(function*(){const n=yield t.restart.call(this,e);return this.checkForSilence(),n}))}startMonitor(){da()&&(this.monitorInterval||(this.monitorInterval=setInterval((()=>{this.monitorSender()}),br)))}setProcessor(t){var n;return wi(this,void 0,void 0,(function*(){const i=yield this.processorLock.lock();try{if(!this.audioContext)throw Error("Audio context needs to be set on LocalAudioTrack in order to enable processors");this.processor&&(yield this.stopProcessor());const i={kind:this.kind,track:this._mediaStreamTrack,audioContext:this.audioContext};this.log.debug("setting up audio processor ".concat(t.name),this.logContext),yield t.init(i),this.processor=t,this.processor.processedTrack&&(yield null===(n=this.sender)||void 0===n?void 0:n.replaceTrack(this.processor.processedTrack)),this.emit(e.TrackEvent.TrackProcessorUpdate,this.processor)}finally{i()}}))}setAudioContext(e){this.audioContext=e}getSenderStats(){var e;return wi(this,void 0,void 0,(function*(){if(!(null===(e=this.sender)||void 0===e?void 0:e.getStats))return;let t;return(yield this.sender.getStats()).forEach((e=>{"outbound-rtp"===e.type&&(t={type:"audio",streamId:e.id,packetsSent:e.packetsSent,packetsLost:e.packetsLost,bytesSent:e.bytesSent,timestamp:e.timestamp,roundTripTime:e.roundTripTime,jitter:e.jitter})})),t}))}checkForSilence(){return wi(this,void 0,void 0,(function*(){const t=yield function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:200;return wi(this,void 0,void 0,(function*(){const n=Go();if(n){const i=n.createAnalyser();i.fftSize=2048;const s=i.frequencyBinCount,o=new Uint8Array(s);n.createMediaStreamSource(new MediaStream([e.mediaStreamTrack])).connect(i),yield Yo(t),i.getByteTimeDomainData(o);const a=o.some((e=>128!==e&&0!==e));return n.close(),!a}return!1}))}(this);return t&&(this.isMuted||this.log.warn("silence detected on local audio track",this.logContext),this.emit(e.TrackEvent.AudioSilenceDetected)),t}))}}function Er(e,t,n){switch(e.kind){case"audio":return new Sr(e,t,!1,void 0,n);case"video":return new Ur(e,t,!1,n);default:throw new ho("unsupported track type: ".concat(e.kind))}}const wr=Object.values(No),Pr=Object.values(Lo),Rr=Object.values(Ao),_r=[No.h180,No.h360],Ir=[Lo.h180,Lo.h360],Or=e=>[{scaleResolutionDownBy:2,fps:e.encoding.maxFramerate}].map((t=>{var n,i;return new Io(Math.floor(e.width/t.scaleResolutionDownBy),Math.floor(e.height/t.scaleResolutionDownBy),Math.max(15e4,Math.floor(e.encoding.maxBitrate/(Math.pow(t.scaleResolutionDownBy,2)*((null!==(n=e.encoding.maxFramerate)&&void 0!==n?n:30)/(null!==(i=t.fps)&&void 0!==i?i:30))))),t.fps,e.encoding.priority)})),Mr=["q","h","f"];function xr(e,t,n,i){var s,o;let a=null==i?void 0:i.videoEncoding;e&&(a=null==i?void 0:i.screenShareEncoding);const r=null==i?void 0:i.simulcast,c=null==i?void 0:i.scalabilityMode,d=null==i?void 0:i.videoCodec;if(!a&&!r&&!c||!t||!n)return[{}];a||(a=function(e,t,n,i){const s=function(e,t,n){if(e)return Rr;const i=t>n?t/n:n/t;if(Math.abs(i-16/9)<Math.abs(i-4/3))return wr;return Pr}(e,t,n);let{encoding:o}=s[0];const a=Math.max(t,n);for(let e=0;e<s.length;e+=1){const t=s[e];if(o=t.encoding,t.width>=a)break}if(i)switch(i){case"av1":o=Object.assign({},o),o.maxBitrate=.7*o.maxBitrate;break;case"vp9":o=Object.assign({},o),o.maxBitrate=.85*o.maxBitrate}return o}(e,t,n,d),ki.debug("using video encoding",a));const l=new Io(t,n,a.maxBitrate,a.maxFramerate,a.priority);if(c&&ta(d)){const e=new Ar(c),t=[];if(e.spatial>3)throw new Error("unsupported scalabilityMode: ".concat(c));const n=Eo();if(aa()||"Chrome"===(null==n?void 0:n.name)&&ga(null==n?void 0:n.version,"113")<0){for(let n=0;n<e.spatial;n+=1)t.push({rid:Mr[2-n],maxBitrate:a.maxBitrate/Math.pow(3,n),maxFramerate:l.encoding.maxFramerate});t[0].scalabilityMode=c}else t.push({maxBitrate:a.maxBitrate,maxFramerate:l.encoding.maxFramerate,scalabilityMode:c});return ki.debug("using svc encoding",{encodings:t}),t}if(!r)return[a];let u,h=[];if(h=e?null!==(s=Lr(null==i?void 0:i.screenShareSimulcastLayers))&&void 0!==s?s:Dr(e,l):null!==(o=Lr(null==i?void 0:i.videoSimulcastLayers))&&void 0!==o?o:Dr(e,l),h.length>0){const e=h[0];h.length>1&&([,u]=h);const i=Math.max(t,n);if(i>=960&&u)return Nr(t,n,[e,u,l]);if(i>=480)return Nr(t,n,[e,l])}return Nr(t,n,[l])}function Dr(e,t){if(e)return Or(t);const{width:n,height:i}=t,s=n>i?n/i:i/n;return Math.abs(s-16/9)<Math.abs(s-4/3)?_r:Ir}function Nr(e,t,n){const i=[];if(n.forEach(((n,s)=>{if(s>=Mr.length)return;const o=Math.min(e,t),a={rid:Mr[s],scaleResolutionDownBy:Math.max(1,o/Math.min(n.width,n.height)),maxBitrate:n.encoding.maxBitrate};n.encoding.maxFramerate&&(a.maxFramerate=n.encoding.maxFramerate);const r=oa()||0===s;n.encoding.priority&&r&&(a.priority=n.encoding.priority,a.networkPriority=n.encoding.priority),i.push(a)})),la()&&"ios"===ma()){let e;i.forEach((t=>{e?t.maxFramerate&&t.maxFramerate>e&&(e=t.maxFramerate):e=t.maxFramerate}));let t=!0;i.forEach((n=>{var i;n.maxFramerate!=e&&(t&&(t=!1,ki.info("Simulcast on iOS React-Native requires all encodings to share the same framerate.")),ki.info('Setting framerate of encoding "'.concat(null!==(i=n.rid)&&void 0!==i?i:"",'" to ').concat(e)),n.maxFramerate=e)}))}return i}function Lr(e){if(e)return e.sort(((e,t)=>{const{encoding:n}=e,{encoding:i}=t;return n.maxBitrate>i.maxBitrate?1:n.maxBitrate<i.maxBitrate?-1:n.maxBitrate===i.maxBitrate&&n.maxFramerate&&i.maxFramerate?n.maxFramerate>i.maxFramerate?1:-1:0}))}class Ar{constructor(e){const t=e.match(/^L(\d)T(\d)(h|_KEY|_KEY_SHIFT){0,1}$/);if(!t)throw new Error("invalid scalability mode");if(this.spatial=parseInt(t[1]),this.temporal=parseInt(t[2]),t.length>3)switch(t[3]){case"h":case"_KEY":case"_KEY_SHIFT":this.suffix=t[3]}}toString(){var e;return"L".concat(this.spatial,"T").concat(this.temporal).concat(null!==(e=this.suffix)&&void 0!==e?e:"")}}class Ur extends xa{constructor(e,t){let n=!(arguments.length>2&&void 0!==arguments[2])||arguments[2],i=arguments.length>3?arguments[3]:void 0;super(e,jo.Kind.Video,t,n,i),this.simulcastCodecs=new Map,this.monitorSender=()=>wi(this,void 0,void 0,(function*(){if(!this.sender)return void(this._currentBitrate=0);let e;try{e=yield this.getSenderStats()}catch(e){return void this.log.error("could not get audio sender stats",Object.assign(Object.assign({},this.logContext),{error:e}))}const t=new Map(e.map((e=>[e.rid,e])));if(this.prevStats){let e=0;t.forEach(((t,n)=>{var i;const s=null===(i=this.prevStats)||void 0===i?void 0:i.get(n);e+=Cr(t,s)})),this._currentBitrate=e}this.prevStats=t})),this.senderLock=new Ra}get isSimulcast(){return!!(this.sender&&this.sender.getParameters().encodings.length>1)}startMonitor(e){var t;if(this.signalClient=e,!da())return;const n=null===(t=this.sender)||void 0===t?void 0:t.getParameters();n&&(this.encodings=n.encodings),this.monitorInterval||(this.monitorInterval=setInterval((()=>{this.monitorSender()}),br))}stop(){this._mediaStreamTrack.getConstraints(),this.simulcastCodecs.forEach((e=>{e.mediaStreamTrack.stop()})),super.stop()}pauseUpstream(){const e=Object.create(null,{pauseUpstream:{get:()=>super.pauseUpstream}});var t,n,i,s,o;return wi(this,void 0,void 0,(function*(){yield e.pauseUpstream.call(this);try{for(var a,r=!0,c=Ri(this.simulcastCodecs.values());a=yield c.next(),!(t=a.done);r=!0){s=a.value,r=!1;const e=s;yield null===(o=e.sender)||void 0===o?void 0:o.replaceTrack(null)}}catch(e){n={error:e}}finally{try{r||t||!(i=c.return)||(yield i.call(c))}finally{if(n)throw n.error}}}))}resumeUpstream(){const e=Object.create(null,{resumeUpstream:{get:()=>super.resumeUpstream}});var t,n,i,s,o;return wi(this,void 0,void 0,(function*(){yield e.resumeUpstream.call(this);try{for(var a,r=!0,c=Ri(this.simulcastCodecs.values());a=yield c.next(),!(t=a.done);r=!0){s=a.value,r=!1;const e=s;yield null===(o=e.sender)||void 0===o?void 0:o.replaceTrack(e.mediaStreamTrack)}}catch(e){n={error:e}}finally{try{r||t||!(i=c.return)||(yield i.call(c))}finally{if(n)throw n.error}}}))}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return wi(this,void 0,void 0,(function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug("Track already muted",this.logContext),this):(this.source!==jo.Source.Camera||this.isUserProvided||(this.log.debug("stopping camera track",this.logContext),this._mediaStreamTrack.stop()),yield e.mute.call(this),this)}finally{t()}}))}unmute(){const e=Object.create(null,{unmute:{get:()=>super.unmute}});return wi(this,void 0,void 0,(function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.source!==jo.Source.Camera||this.isUserProvided||(this.log.debug("reacquiring camera track",this.logContext),yield this.restartTrack()),yield e.unmute.call(this),this):(this.log.debug("Track already unmuted",this.logContext),this)}finally{t()}}))}setTrackMuted(e){super.setTrackMuted(e);for(const t of this.simulcastCodecs.values())t.mediaStreamTrack.enabled=!e}getSenderStats(){var e;return wi(this,void 0,void 0,(function*(){if(!(null===(e=this.sender)||void 0===e?void 0:e.getStats))return[];const t=[],n=yield this.sender.getStats();return n.forEach((e=>{var i;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!==(i=e.rid)&&void 0!==i?i:e.id,retransmittedPacketsSent:e.retransmittedPacketsSent,qualityLimitationReason:e.qualityLimitationReason,qualityLimitationResolutionChanges:e.qualityLimitationResolutionChanges},o=n.get(e.remoteId);o&&(s.jitter=o.jitter,s.packetsLost=o.packetsLost,s.roundTripTime=o.roundTripTime),t.push(s)}})),t}))}setPublishingQuality(t){const n=[];for(let i=e.VideoQuality.LOW;i<=e.VideoQuality.HIGH;i+=1)n.push(new Ln({quality:i,enabled:i<=t}));this.log.debug("setting publishing quality. max quality ".concat(t),this.logContext),this.setPublishingLayers(n)}setDeviceId(e){return wi(this,void 0,void 0,(function*(){return this._constraints.deviceId===e&&this._mediaStreamTrack.getSettings().deviceId===_a(e)||(this._constraints.deviceId=e,this.isMuted||(yield this.restartTrack()),this.isMuted||_a(e)===this._mediaStreamTrack.getSettings().deviceId)}))}restartTrack(e){var t,n,i,s;return wi(this,void 0,void 0,(function*(){let o;if(e){const t=Ko({video:e});"boolean"!=typeof t.video&&(o=t.video)}yield this.restart(o);try{for(var a,r=!0,c=Ri(this.simulcastCodecs.values());a=yield c.next(),!(t=a.done);r=!0){s=a.value,r=!1;const e=s;e.sender&&(e.mediaStreamTrack=this.mediaStreamTrack.clone(),yield e.sender.replaceTrack(e.mediaStreamTrack))}}catch(e){n={error:e}}finally{try{r||t||!(i=c.return)||(yield i.call(c))}finally{if(n)throw n.error}}}))}setProcessor(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];const n=Object.create(null,{setProcessor:{get:()=>super.setProcessor}});var i,s,o,a,r,c;return wi(this,void 0,void 0,(function*(){if(yield n.setProcessor.call(this,e,t),null===(r=this.processor)||void 0===r?void 0:r.processedTrack)try{for(var d,l=!0,u=Ri(this.simulcastCodecs.values());d=yield u.next(),!(i=d.done);l=!0){a=d.value,l=!1;const e=a;yield null===(c=e.sender)||void 0===c?void 0:c.replaceTrack(this.processor.processedTrack)}}catch(e){s={error:e}}finally{try{l||i||!(o=u.return)||(yield o.call(u))}finally{if(s)throw s.error}}}))}addSimulcastTrack(e,t){if(this.simulcastCodecs.has(e))return void this.log.error("".concat(e," already added, skipping adding simulcast codec"),this.logContext);const n={codec:e,mediaStreamTrack:this.mediaStreamTrack.clone(),sender:void 0,encodings:t};return this.simulcastCodecs.set(e,n),n}setSimulcastTrackSender(e,t){const n=this.simulcastCodecs.get(e);n&&(n.sender=t,setTimeout((()=>{this.subscribedCodecs&&this.setPublishingCodecs(this.subscribedCodecs)}),5e3))}setPublishingCodecs(e){var t,n,i,s,o,a,r;return wi(this,void 0,void 0,(function*(){if(this.log.debug("setting publishing codecs",Object.assign(Object.assign({},this.logContext),{codecs:e,currentCodec:this.codec})),!this.codec&&e.length>0)return yield this.setPublishingLayers(e[0].qualities),[];this.subscribedCodecs=e;const c=[];try{for(t=!0,n=Ri(e);i=yield n.next(),!(s=i.done);t=!0){r=i.value,t=!1;const e=r;if(this.codec&&this.codec!==e.codec){const t=this.simulcastCodecs.get(e.codec);if(this.log.debug("try setPublishingCodec for ".concat(e.codec),Object.assign(Object.assign({},this.logContext),{simulcastCodecInfo:t})),t&&t.sender)t.encodings&&(this.log.debug("try setPublishingLayersForSender ".concat(e.codec),this.logContext),yield jr(t.sender,t.encodings,e.qualities,this.senderLock,this.log,this.logContext));else for(const t of e.qualities)if(t.enabled){c.push(e.codec);break}}else yield this.setPublishingLayers(e.qualities)}}catch(e){o={error:e}}finally{try{t||s||!(a=n.return)||(yield a.call(n))}finally{if(o)throw o.error}}return c}))}setPublishingLayers(e){return wi(this,void 0,void 0,(function*(){this.log.debug("setting publishing layers",Object.assign(Object.assign({},this.logContext),{qualities:e})),this.sender&&this.encodings&&(yield jr(this.sender,this.encodings,e,this.senderLock,this.log,this.logContext))}))}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return wi(this,void 0,void 0,(function*(){yield e.handleAppVisibilityChanged.call(this),ca()&&this.isInBackground&&this.source===jo.Source.Camera&&(this._mediaStreamTrack.enabled=!1)}))}}function jr(e,t,n,i,s,o){return wi(this,void 0,void 0,(function*(){const a=yield i.lock();s.debug("setPublishingLayersForSender",Object.assign(Object.assign({},o),{sender:e,qualities:n,senderEncodings:t}));try{const i=e.getParameters(),{encodings:a}=i;if(!a)return;if(a.length!==t.length)return void s.warn("cannot set publishing layers, encodings mismatch",Object.assign(Object.assign({},o),{encodings:a,senderEncodings:t}));let r=!1;!1&&a[0].scalabilityMode||a.forEach(((e,i)=>{var a;let c=null!==(a=e.rid)&&void 0!==a?a:"";""===c&&(c="q");const d=Fr(c),l=n.find((e=>e.quality===d));l&&e.active!==l.enabled&&(r=!0,e.active=l.enabled,s.debug("setting layer ".concat(l.quality," to ").concat(e.active?"enabled":"disabled"),o),oa()&&(l.enabled?(e.scaleResolutionDownBy=t[i].scaleResolutionDownBy,e.maxBitrate=t[i].maxBitrate,e.maxFrameRate=t[i].maxFrameRate):(e.scaleResolutionDownBy=4,e.maxBitrate=10,e.maxFrameRate=2)))})),r&&(i.encodings=a,s.debug("setting encodings",Object.assign(Object.assign({},o),{encodings:i.encodings})),yield e.setParameters(i))}finally{a()}}))}function Fr(t){switch(t){case"f":default:return e.VideoQuality.HIGH;case"h":return e.VideoQuality.MEDIUM;case"q":return e.VideoQuality.LOW}}function Br(t,n,i,s){if(!i)return[new et({quality:e.VideoQuality.HIGH,width:t,height:n,bitrate:0,ssrc:0})];if(s){const s=i[0].scalabilityMode,o=new Ar(s),a=[];for(let s=0;s<o.spatial;s+=1)a.push(new et({quality:e.VideoQuality.HIGH-s,width:Math.ceil(t/Math.pow(2,s)),height:Math.ceil(n/Math.pow(2,s)),bitrate:i[0].maxBitrate?Math.ceil(i[0].maxBitrate/Math.pow(3,s)):0,ssrc:0}));return a}return i.map((e=>{var i,s,o;const a=null!==(i=e.scaleResolutionDownBy)&&void 0!==i?i:1;let r=Fr(null!==(s=e.rid)&&void 0!==s?s:"");return new et({quality:r,width:Math.ceil(t/a),height:Math.ceil(n/a),bitrate:null!==(o=e.maxBitrate)&&void 0!==o?o:0,ssrc:0})}))}class Vr extends jo{constructor(e,t,n,i,s){super(e,n,s),this.sid=t,this.receiver=i}setMuted(t){this.isMuted!==t&&(this.isMuted=t,this._mediaStreamTrack.enabled=!t,this.emit(t?e.TrackEvent.Muted:e.TrackEvent.Unmuted,this))}setMediaStream(t){this.mediaStream=t;const n=i=>{i.track===this._mediaStreamTrack&&(t.removeEventListener("removetrack",n),this.receiver=void 0,this._currentBitrate=0,this.emit(e.TrackEvent.Ended,this))};t.addEventListener("removetrack",n)}start(){this.startMonitor(),super.enable()}stop(){this.stopMonitor(),super.disable()}getRTCStatsReport(){var e;return wi(this,void 0,void 0,(function*(){if(!(null===(e=this.receiver)||void 0===e?void 0:e.getStats))return;return yield this.receiver.getStats()}))}startMonitor(){this.monitorInterval||(this.monitorInterval=setInterval((()=>this.monitorReceiver()),br))}}class qr extends Vr{constructor(e,t,n,i,s,o){super(e,t,jo.Kind.Audio,n,o),this.monitorReceiver=()=>wi(this,void 0,void 0,(function*(){if(!this.receiver)return void(this._currentBitrate=0);const e=yield this.getReceiverStats();e&&this.prevStats&&this.receiver&&(this._currentBitrate=Cr(e,this.prevStats)),this.prevStats=e})),this.audioContext=i,this.webAudioPluginNodes=[],s&&(this.sinkId=s.deviceId)}setVolume(e){var t;for(const n of this.attachedElements)this.audioContext?null===(t=this.gainNode)||void 0===t||t.gain.setTargetAtTime(e,0,.1):n.volume=e;la()&&this._mediaStreamTrack._setVolume(e),this.elementVolume=e}getVolume(){if(this.elementVolume)return this.elementVolume;if(la())return 1;let e=0;return this.attachedElements.forEach((t=>{t.volume>e&&(e=t.volume)})),e}setSinkId(e){return wi(this,void 0,void 0,(function*(){this.sinkId=e,yield Promise.all(this.attachedElements.map((t=>{if(na(t))return t.setSinkId(e)})))}))}attach(e){const t=0===this.attachedElements.length;return e?super.attach(e):e=super.attach(),this.sinkId&&na(e)&&e.setSinkId(this.sinkId),this.audioContext&&t&&(this.log.debug("using audio context mapping",this.logContext),this.connectWebAudio(this.audioContext,e),e.volume=0,e.muted=!0),this.elementVolume&&this.setVolume(this.elementVolume),e}detach(e){let t;return e?(t=super.detach(e),this.audioContext&&(this.attachedElements.length>0?this.connectWebAudio(this.audioContext,this.attachedElements[0]):this.disconnectWebAudio())):(t=super.detach(),this.disconnectWebAudio()),t}setAudioContext(e){this.audioContext=e,e&&this.attachedElements.length>0?this.connectWebAudio(e,this.attachedElements[0]):e||this.disconnectWebAudio()}setWebAudioPlugins(e){this.webAudioPluginNodes=e,this.attachedElements.length>0&&this.audioContext&&this.connectWebAudio(this.audioContext,this.attachedElements[0])}connectWebAudio(t,n){this.disconnectWebAudio(),this.sourceNode=t.createMediaStreamSource(n.srcObject);let i=this.sourceNode;this.webAudioPluginNodes.forEach((e=>{i.connect(e),i=e})),this.gainNode=t.createGain(),i.connect(this.gainNode),this.gainNode.connect(t.destination),this.elementVolume&&this.gainNode.gain.setTargetAtTime(this.elementVolume,0,.1),"running"!==t.state&&t.resume().then((()=>{"running"!==t.state&&this.emit(e.TrackEvent.AudioPlaybackFailed,new Error("Audio Context couldn't be started automatically"))})).catch((t=>{this.emit(e.TrackEvent.AudioPlaybackFailed,t)}))}disconnectWebAudio(){var e,t;null===(e=this.gainNode)||void 0===e||e.disconnect(),null===(t=this.sourceNode)||void 0===t||t.disconnect(),this.gainNode=void 0,this.sourceNode=void 0}getReceiverStats(){return wi(this,void 0,void 0,(function*(){if(!this.receiver||!this.receiver.getStats)return;let e;return(yield this.receiver.getStats()).forEach((t=>{"inbound-rtp"===t.type&&(e={type:"audio",timestamp:t.timestamp,jitter:t.jitter,bytesReceived:t.bytesReceived,concealedSamples:t.concealedSamples,concealmentEvents:t.concealmentEvents,silentConcealedSamples:t.silentConcealedSamples,silentConcealmentEvents:t.silentConcealmentEvents,totalAudioEnergy:t.totalAudioEnergy,totalSamplesDuration:t.totalSamplesDuration})})),e}))}}class Kr extends Vr{constructor(e,t,n,i,s){super(e,t,jo.Kind.Video,n,s),this.elementInfos=[],this.monitorReceiver=()=>wi(this,void 0,void 0,(function*(){if(!this.receiver)return void(this._currentBitrate=0);const e=yield this.getReceiverStats();e&&this.prevStats&&this.receiver&&(this._currentBitrate=Cr(e,this.prevStats)),this.prevStats=e})),this.debouncedHandleResize=bo((()=>{this.updateDimensions()}),100),this.adaptiveStreamSettings=i}get isAdaptiveStream(){return void 0!==this.adaptiveStreamSettings}get mediaStreamTrack(){return this._mediaStreamTrack}setMuted(e){super.setMuted(e),this.attachedElements.forEach((t=>{e?Bo(this._mediaStreamTrack,t):Fo(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 Gr(e);this.observeElementInfo(t)}return e}observeElementInfo(e){this.adaptiveStreamSettings&&void 0===this.elementInfos.find((t=>t===e))?(e.handleResize=()=>{this.debouncedHandleResize()},e.handleVisibilityChanged=()=>{this.updateVisibility()},this.elementInfos.push(e),e.observe(),this.debouncedHandleResize(),this.updateVisibility()):this.log.warn("visibility resize observer not triggered",this.logContext)}stopObservingElementInfo(e){if(!this.isAdaptiveStream)return void this.log.warn("stopObservingElementInfo ignored",this.logContext);const t=this.elementInfos.filter((t=>t===e));for(const e of t)e.stopObserving();this.elementInfos=this.elementInfos.filter((t=>t!==e)),this.updateVisibility(),this.debouncedHandleResize()}detach(e){let t=[];if(e)return this.stopObservingElement(e),super.detach(e);t=super.detach();for(const e of t)this.stopObservingElement(e);return t}getDecoderImplementation(){var e;return null===(e=this.prevStats)||void 0===e?void 0:e.decoderImplementation}getReceiverStats(){return wi(this,void 0,void 0,(function*(){if(!this.receiver||!this.receiver.getStats)return;const e=yield this.receiver.getStats();let t,n="",i=new Map;return e.forEach((e=>{"inbound-rtp"===e.type?(n=e.codecId,t={type:"video",framesDecoded:e.framesDecoded,framesDropped:e.framesDropped,framesReceived:e.framesReceived,packetsReceived:e.packetsReceived,packetsLost:e.packetsLost,frameWidth:e.frameWidth,frameHeight:e.frameHeight,pliCount:e.pliCount,firCount:e.firCount,nackCount:e.nackCount,jitter:e.jitter,timestamp:e.timestamp,bytesReceived:e.bytesReceived,decoderImplementation:e.decoderImplementation}):"codec"===e.type&&i.set(e.id,e)})),t&&""!==n&&i.get(n)&&(t.mimeType=i.get(n).mimeType),t}))}stopObservingElement(e){const t=this.elementInfos.filter((t=>t.element===e));for(const e of t)this.stopObservingElementInfo(e)}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return wi(this,void 0,void 0,(function*(){yield e.handleAppVisibilityChanged.call(this),this.isAdaptiveStream&&this.updateVisibility()}))}updateVisibility(){var t,n;const i=this.elementInfos.reduce(((e,t)=>Math.max(e,t.visibilityChangedAt||0)),0),s=!(null!==(n=null===(t=this.adaptiveStreamSettings)||void 0===t?void 0:t.pauseVideoInBackground)&&void 0!==n&&!n)&&this.isInBackground,o=this.elementInfos.some((e=>e.pictureInPicture)),a=this.elementInfos.some((e=>e.visible))&&!s||o;this.lastVisible!==a&&(!a&&Date.now()-i<100?_o.setTimeout((()=>{this.updateVisibility()}),100):(this.lastVisible=a,this.emit(e.TrackEvent.VisibilityChanged,a,this)))}updateDimensions(){var t,n;let i=0,s=0;const o=this.getPixelDensity();for(const e of this.elementInfos){const t=e.width()*o,n=e.height()*o;t+n>i+s&&(i=t,s=n)}(null===(t=this.lastDimensions)||void 0===t?void 0:t.width)===i&&(null===(n=this.lastDimensions)||void 0===n?void 0:n.height)===s||(this.lastDimensions={width:i,height:s},this.emit(e.TrackEvent.VideoDimensionsChanged,this.lastDimensions,this))}getPixelDensity(){var e;const t=null===(e=this.adaptiveStreamSettings)||void 0===e?void 0:e.pixelDensity;if("screen"===t)return pa();if(!t){return pa()>2?2:1}return t}}class Gr{get visible(){return this.isPiP||this.isIntersecting}get pictureInPicture(){return this.isPiP}constructor(e,t){this.onVisibilityChanged=e=>{var t;const{target:n,isIntersecting:i}=e;n===this.element&&(this.isIntersecting=i,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:Wr(e),this.isPiP=da()&&document.pictureInPictureElement===e,this.visibilityChangedAt=0}width(){return this.element.clientWidth}height(){return this.element.clientHeight}observe(){this.isIntersecting=Wr(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,ba().observe(this.element),Ta().observe(this.element),this.element.addEventListener("enterpictureinpicture",this.onEnterPiP),this.element.addEventListener("leavepictureinpicture",this.onLeavePiP)}stopObserving(){var e,t;null===(e=ba())||void 0===e||e.unobserve(this.element),null===(t=Ta())||void 0===t||t.unobserve(this.element),this.element.removeEventListener("enterpictureinpicture",this.onEnterPiP),this.element.removeEventListener("leavepictureinpicture",this.onLeavePiP)}}function Wr(e){let t=e.offsetTop,n=e.offsetLeft;const i=e.offsetWidth,s=e.offsetHeight,{hidden:o}=e,{opacity:a,display:r}=getComputedStyle(e);for(;e.offsetParent;)t+=(e=e.offsetParent).offsetTop,n+=e.offsetLeft;return t<window.pageYOffset+window.innerHeight&&n<window.pageXOffset+window.innerWidth&&t+s>window.pageYOffset&&n+i>window.pageXOffset&&!o&&(""===a||parseFloat(a)>0)&&"none"!==r}class Hr extends Gi.EventEmitter{constructor(t,n,i,s){var o;super(),this.metadataMuted=!1,this.encryption=Xe.NONE,this.log=ki,this.handleMuted=()=>{this.emit(e.TrackEvent.Muted)},this.handleUnmuted=()=>{this.emit(e.TrackEvent.Unmuted)},this.log=yi(null!==(o=null==s?void 0:s.loggerName)&&void 0!==o?o:e.LoggerNames.Publication),this.loggerContextCb=this.loggerContextCb,this.setMaxListeners(100),this.kind=t,this.trackSid=n,this.trackName=i,this.source=jo.Source.Unknown}setTrack(t){this.track&&(this.track.off(e.TrackEvent.Muted,this.handleMuted),this.track.off(e.TrackEvent.Unmuted,this.handleUnmuted)),this.track=t,t&&(t.on(e.TrackEvent.Muted,this.handleMuted),t.on(e.TrackEvent.Unmuted,this.handleUnmuted))}get logContext(){var e;return Object.assign(Object.assign({},null===(e=this.loggerContextCb)||void 0===e?void 0:e.call(this)),zo(this))}get isMuted(){return this.metadataMuted}get isEnabled(){return!0}get isSubscribed(){return void 0!==this.track}get isEncrypted(){return this.encryption!==Xe.NONE}get audioTrack(){if(this.track instanceof Sr||this.track instanceof qr)return this.track}get videoTrack(){if(this.track instanceof Ur||this.track instanceof Kr)return this.track}updateInfo(e){this.trackSid=e.sid,this.trackName=e.name,this.source=jo.sourceFromProto(e.source),this.mimeType=e.mimeType,this.kind===jo.Kind.Video&&e.width>0&&(this.dimensions={width:e.width,height:e.height},this.simulcasted=e.simulcast),this.encryption=e.encryption,this.trackInfo=e,this.log.debug("update publication info",Object.assign(Object.assign({},this.logContext),{info:e}))}}!function(e){var t,n;(t=e.SubscriptionStatus||(e.SubscriptionStatus={})).Desired="desired",t.Subscribed="subscribed",t.Unsubscribed="unsubscribed",(n=e.PermissionStatus||(e.PermissionStatus={})).Allowed="allowed",n.NotAllowed="not_allowed"}(Hr||(Hr={}));class Jr extends Hr{get isUpstreamPaused(){var e;return null===(e=this.track)||void 0===e?void 0:e.isUpstreamPaused}constructor(t,n,i,s){super(t,n.sid,n.name,s),this.track=void 0,this.handleTrackEnded=()=>{this.emit(e.TrackEvent.Ended)},this.updateInfo(n),this.setTrack(i)}setTrack(t){this.track&&this.track.off(e.TrackEvent.Ended,this.handleTrackEnded),super.setTrack(t),t&&t.on(e.TrackEvent.Ended,this.handleTrackEnded)}get isMuted(){return this.track?this.track.isMuted:super.isMuted}get audioTrack(){return super.audioTrack}get videoTrack(){return super.videoTrack}mute(){var e;return wi(this,void 0,void 0,(function*(){return null===(e=this.track)||void 0===e?void 0:e.mute()}))}unmute(){var e;return wi(this,void 0,void 0,(function*(){return null===(e=this.track)||void 0===e?void 0:e.unmute()}))}pauseUpstream(){var e;return wi(this,void 0,void 0,(function*(){yield null===(e=this.track)||void 0===e?void 0:e.pauseUpstream()}))}resumeUpstream(){var e;return wi(this,void 0,void 0,(function*(){yield null===(e=this.track)||void 0===e?void 0:e.resumeUpstream()}))}}e.ConnectionQuality=void 0,function(e){e.Excellent="excellent",e.Good="good",e.Poor="poor",e.Lost="lost",e.Unknown="unknown"}(e.ConnectionQuality||(e.ConnectionQuality={}));class zr extends Gi.EventEmitter{get logContext(){var e,t;return Object.assign({},null===(t=null===(e=this.loggerOptions)||void 0===e?void 0:e.loggerContextCb)||void 0===t?void 0:t.call(e))}get isEncrypted(){return this.trackPublications.size>0&&Array.from(this.trackPublications.values()).every((e=>e.isEncrypted))}get isAgent(){var e,t;return null!==(t=null===(e=this.permissions)||void 0===e?void 0:e.agent)&&void 0!==t&&t}constructor(t,n,i,s,o){var a;super(),this.audioLevel=0,this.isSpeaking=!1,this._connectionQuality=e.ConnectionQuality.Unknown,this.log=ki,this.log=yi(null!==(a=null==o?void 0:o.loggerName)&&void 0!==a?a:e.LoggerNames.Participant),this.loggerOptions=o,this.setMaxListeners(100),this.sid=t,this.identity=n,this.name=i,this.metadata=s,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map}getTrackPublications(){return Array.from(this.trackPublications.values())}getTrackPublication(e){for(const[,t]of this.trackPublications)if(t.source===e)return t}getTrackPublicationByName(e){for(const[,t]of this.trackPublications)if(t.trackName===e)return t}get connectionQuality(){return this._connectionQuality}get isCameraEnabled(){var e;const t=this.getTrackPublication(jo.Source.Camera);return!(null===(e=null==t?void 0:t.isMuted)||void 0===e||e)}get isMicrophoneEnabled(){var e;const t=this.getTrackPublication(jo.Source.Microphone);return!(null===(e=null==t?void 0:t.isMuted)||void 0===e||e)}get isScreenShareEnabled(){return!!this.getTrackPublication(jo.Source.ScreenShare)}get isLocal(){return!1}get joinedAt(){return this.participantInfo?new Date(1e3*Number.parseInt(this.participantInfo.joinedAt.toString())):new Date}updateInfo(e){return!(this.participantInfo&&this.participantInfo.sid===e.sid&&this.participantInfo.version>e.version)&&(this.identity=e.identity,this.sid=e.sid,this._setName(e.name),this._setMetadata(e.metadata),e.permission&&this.setPermissions(e.permission),this.participantInfo=e,this.log.trace("update participant info",Object.assign(Object.assign({},this.logContext),{info:e})),!0)}_setMetadata(t){const n=this.metadata!==t,i=this.metadata;this.metadata=t,n&&this.emit(e.ParticipantEvent.ParticipantMetadataChanged,i)}_setName(t){const n=this.name!==t;this.name=t,n&&this.emit(e.ParticipantEvent.ParticipantNameChanged,t)}setPermissions(t){var n,i,s,o,a;const r=this.permissions,c=t.canPublish!==(null===(n=this.permissions)||void 0===n?void 0:n.canPublish)||t.canSubscribe!==(null===(i=this.permissions)||void 0===i?void 0:i.canSubscribe)||t.canPublishData!==(null===(s=this.permissions)||void 0===s?void 0:s.canPublishData)||t.hidden!==(null===(o=this.permissions)||void 0===o?void 0:o.hidden)||t.recorder!==(null===(a=this.permissions)||void 0===a?void 0:a.recorder)||t.canPublishSources.length!==this.permissions.canPublishSources.length||t.canPublishSources.some(((e,t)=>{var n;return e!==(null===(n=this.permissions)||void 0===n?void 0:n.canPublishSources[t])}));return this.permissions=t,c&&this.emit(e.ParticipantEvent.ParticipantPermissionsChanged,r),c}setIsSpeaking(t){t!==this.isSpeaking&&(this.isSpeaking=t,t&&(this.lastSpokeAt=new Date),this.emit(e.ParticipantEvent.IsSpeakingChanged,t))}setConnectionQuality(t){const n=this._connectionQuality;this._connectionQuality=function(t){switch(t){case Be.EXCELLENT:return e.ConnectionQuality.Excellent;case Be.GOOD:return e.ConnectionQuality.Good;case Be.POOR:return e.ConnectionQuality.Poor;case Be.LOST:return e.ConnectionQuality.Lost;default:return e.ConnectionQuality.Unknown}}(t),n!==this._connectionQuality&&this.emit(e.ParticipantEvent.ConnectionQualityChanged,this._connectionQuality)}setAudioContext(e){this.audioContext=e,this.audioTrackPublications.forEach((t=>(t.track instanceof qr||t.track instanceof Sr)&&t.track.setAudioContext(e)))}addTrackPublication(t){t.on(e.TrackEvent.Muted,(()=>{this.emit(e.ParticipantEvent.TrackMuted,t)})),t.on(e.TrackEvent.Unmuted,(()=>{this.emit(e.ParticipantEvent.TrackUnmuted,t)}));const n=t;switch(n.track&&(n.track.sid=t.trackSid),this.trackPublications.set(t.trackSid,t),t.kind){case jo.Kind.Audio:this.audioTrackPublications.set(t.trackSid,t);break;case jo.Kind.Video:this.videoTrackPublications.set(t.trackSid,t)}}}class Qr extends zr{constructor(e,t,n,i){super(e,t,void 0,void 0,{loggerName:i.loggerName,loggerContextCb:()=>this.engine.logContext}),this.pendingPublishing=new Set,this.pendingPublishPromises=new Map,this.participantTrackPermissions=[],this.allParticipantsAllowedToSubscribe=!0,this.encryptionType=Xe.NONE,this.handleReconnecting=()=>{this.reconnectFuture||(this.reconnectFuture=new Pa)},this.handleReconnected=()=>{var e,t;null===(t=null===(e=this.reconnectFuture)||void 0===e?void 0:e.resolve)||void 0===t||t.call(e),this.reconnectFuture=void 0,this.updateTrackSubscriptionPermissions()},this.handleDisconnected=()=>{var e,t;this.reconnectFuture&&(this.reconnectFuture.promise.catch((e=>this.log.warn(e.message,this.logContext))),null===(t=null===(e=this.reconnectFuture)||void 0===e?void 0:e.reject)||void 0===t||t.call(e,"Got disconnected during reconnection attempt"),this.reconnectFuture=void 0)},this.updateTrackSubscriptionPermissions=()=>{this.log.debug("updating track subscription permissions",Object.assign(Object.assign({},this.logContext),{allParticipantsAllowed:this.allParticipantsAllowedToSubscribe,participantTrackPermissions:this.participantTrackPermissions})),this.engine.client.sendUpdateSubscriptionPermissions(this.allParticipantsAllowedToSubscribe,this.participantTrackPermissions.map((e=>function(e){var t,n,i;if(!e.participantSid&&!e.participantIdentity)throw new Error("Invalid track permission, must provide at least one of participantIdentity and participantSid");return new jn({participantIdentity:null!==(t=e.participantIdentity)&&void 0!==t?t:"",participantSid:null!==(n=e.participantSid)&&void 0!==n?n:"",allTracks:null!==(i=e.allowAll)&&void 0!==i&&i,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):this.log.error("could not update mute status for unpublished track",Object.assign(Object.assign({},this.logContext),zo(e)))},this.onTrackUpstreamPaused=e=>{this.log.debug("upstream paused",Object.assign(Object.assign({},this.logContext),zo(e))),this.onTrackMuted(e,!0)},this.onTrackUpstreamResumed=e=>{this.log.debug("upstream resumed",Object.assign(Object.assign({},this.logContext),zo(e))),this.onTrackMuted(e,e.isMuted)},this.handleSubscribedQualityUpdate=e=>wi(this,void 0,void 0,(function*(){var t,n,i,s,o,a;if(!(null===(o=this.roomOptions)||void 0===o?void 0:o.dynacast))return;const r=this.videoTrackPublications.get(e.trackSid);if(r)if(e.subscribedCodecs.length>0){if(!r.videoTrack)return;const o=yield r.videoTrack.setPublishingCodecs(e.subscribedCodecs);try{for(var c,d=!0,l=Ri(o);!(t=(c=yield l.next()).done);d=!0){s=c.value,d=!1;const e=s;xo(e)&&(this.log.debug("publish ".concat(e," for ").concat(r.videoTrack.sid),Object.assign(Object.assign({},this.logContext),zo(r))),yield this.publishAdditionalCodecForTrack(r.videoTrack,e,r.options))}}catch(e){n={error:e}}finally{try{d||t||!(i=l.return)||(yield i.call(l))}finally{if(n)throw n.error}}}else e.subscribedQualities.length>0&&(yield null===(a=r.videoTrack)||void 0===a?void 0:a.setPublishingLayers(e.subscribedQualities));else this.log.warn("received subscribed quality update for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:e.trackSid}))})),this.handleLocalTrackUnpublished=e=>{const t=this.trackPublications.get(e.trackSid);t?this.unpublishTrack(t.track):this.log.warn("received unpublished event for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:e.trackSid}))},this.handleTrackEnded=e=>wi(this,void 0,void 0,(function*(){if(e.source===jo.Source.ScreenShare||e.source===jo.Source.ScreenShareAudio)this.log.debug("unpublishing local track due to TrackEnded",Object.assign(Object.assign({},this.logContext),zo(e))),this.unpublishTrack(e);else if(e.isUserProvided)yield e.mute();else if(e instanceof Sr||e instanceof Ur)try{if(da())try{const t=yield null===navigator||void 0===navigator?void 0:navigator.permissions.query({name:e.source===jo.Source.Camera?"camera":"microphone"});if(t&&"denied"===t.state)throw this.log.warn("user has revoked access to ".concat(e.source),Object.assign(Object.assign({},this.logContext),zo(e))),t.onchange=()=>{"denied"!==t.state&&(e.isMuted||e.restartTrack(),t.onchange=null)},new Error("GetUserMedia Permission denied")}catch(e){}e.isMuted||(this.log.debug("track ended, attempting to use a different device",Object.assign(Object.assign({},this.logContext),zo(e))),yield e.restartTrack())}catch(t){this.log.warn("could not restart track, muting instead",Object.assign(Object.assign({},this.logContext),zo(e))),yield e.mute()}})),this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this.engine=n,this.roomOptions=i,this.setupEngine(n),this.activeDeviceMap=new Map}get lastCameraError(){return this.cameraError}get lastMicrophoneError(){return this.microphoneError}get isE2EEEnabled(){return this.encryptionType!==Xe.NONE}getTrackPublication(e){const t=super.getTrackPublication(e);if(t)return t}getTrackPublicationByName(e){const t=super.getTrackPublicationByName(e);if(t)return t}setupEngine(t){this.engine=t,this.engine.on(e.EngineEvent.RemoteMute,((e,t)=>{const n=this.trackPublications.get(e);n&&n.track&&(t?n.mute():n.unmute())})),this.engine.on(e.EngineEvent.Connected,this.handleReconnected).on(e.EngineEvent.SignalRestarted,this.handleReconnected).on(e.EngineEvent.SignalResumed,this.handleReconnected).on(e.EngineEvent.Restarting,this.handleReconnecting).on(e.EngineEvent.Resuming,this.handleReconnecting).on(e.EngineEvent.LocalTrackUnpublished,this.handleLocalTrackUnpublished).on(e.EngineEvent.SubscribedQualityUpdate,this.handleSubscribedQualityUpdate).on(e.EngineEvent.Disconnected,this.handleDisconnected)}setMetadata(e){var t;this.engine.client.sendUpdateLocalMetadata(e,null!==(t=this.name)&&void 0!==t?t:"")}setName(e){var t;this.engine.client.sendUpdateLocalMetadata(null!==(t=this.metadata)&&void 0!==t?t:"",e)}setCameraEnabled(e,t,n){return this.setTrackEnabled(jo.Source.Camera,e,t,n)}setMicrophoneEnabled(e,t,n){return this.setTrackEnabled(jo.Source.Microphone,e,t,n)}setScreenShareEnabled(e,t,n){return this.setTrackEnabled(jo.Source.ScreenShare,e,t,n)}setPermissions(t){const n=this.permissions,i=super.setPermissions(t);return i&&n&&this.emit(e.ParticipantEvent.ParticipantPermissionsChanged,n),i}setE2EEEnabled(e){return wi(this,void 0,void 0,(function*(){this.encryptionType=e?Xe.GCM:Xe.NONE,yield this.republishAllTracks(void 0,!1)}))}setTrackEnabled(t,n,i,s){var o,a;return wi(this,void 0,void 0,(function*(){this.log.debug("setTrackEnabled",Object.assign(Object.assign({},this.logContext),{source:t,enabled:n}));let r=this.getTrackPublication(t);if(n)if(r)yield r.unmute();else{let n;if(this.pendingPublishing.has(t))return void this.log.info("skipping duplicate published source",Object.assign(Object.assign({},this.logContext),{source:t}));this.pendingPublishing.add(t);try{switch(t){case jo.Source.Camera:n=yield this.createTracks({video:null===(o=i)||void 0===o||o});break;case jo.Source.Microphone:n=yield this.createTracks({audio:null===(a=i)||void 0===a||a});break;case jo.Source.ScreenShare:n=yield this.createScreenTracks(Object.assign({},i));break;default:throw new ho(t)}const e=[];for(const t of n)this.log.info("publishing track",Object.assign(Object.assign({},this.logContext),zo(t))),e.push(this.publishTrack(t,s));const c=yield Promise.all(e);[r]=c}catch(t){throw null==n||n.forEach((e=>{e.stop()})),t instanceof Error&&!(t instanceof ho)&&this.emit(e.ParticipantEvent.MediaDevicesError,t),t}finally{this.pendingPublishing.delete(t)}}else if(r&&r.track)if(t===jo.Source.ScreenShare){r=yield this.unpublishTrack(r.track);const e=this.getTrackPublication(jo.Source.ScreenShareAudio);e&&e.track&&this.unpublishTrack(e.track)}else yield r.mute();return r}))}enableCameraAndMicrophone(){return wi(this,void 0,void 0,(function*(){if(!this.pendingPublishing.has(jo.Source.Camera)&&!this.pendingPublishing.has(jo.Source.Microphone)){this.pendingPublishing.add(jo.Source.Camera),this.pendingPublishing.add(jo.Source.Microphone);try{const e=yield this.createTracks({audio:!0,video:!0});yield Promise.all(e.map((e=>this.publishTrack(e))))}finally{this.pendingPublishing.delete(jo.Source.Camera),this.pendingPublishing.delete(jo.Source.Microphone)}}}))}createTracks(t){var n,i;return wi(this,void 0,void 0,(function*(){const s=Ko(Vo(t,null===(n=this.roomOptions)||void 0===n?void 0:n.audioCaptureDefaults,null===(i=this.roomOptions)||void 0===i?void 0:i.videoCaptureDefaults));let o;try{o=yield navigator.mediaDevices.getUserMedia(s)}catch(e){throw e instanceof Error&&(s.audio&&(this.microphoneError=e),s.video&&(this.cameraError=e)),e}return s.audio&&(this.microphoneError=void 0,this.emit(e.ParticipantEvent.AudioStreamAcquired)),s.video&&(this.cameraError=void 0),o.getTracks().map((e=>{const n="audio"===e.kind;let i;n?t.audio:t.video;const a=n?s.audio:s.video;"boolean"!=typeof a&&(i=a);const r=Er(e,i,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});return r.kind===jo.Kind.Video?r.source=jo.Source.Camera:r.kind===jo.Kind.Audio&&(r.source=jo.Source.Microphone),r.mediaStream=o,r}))}))}createScreenTracks(t){return wi(this,void 0,void 0,(function*(){if(void 0===t&&(t={}),void 0===navigator.mediaDevices.getDisplayMedia)throw new uo("getDisplayMedia not supported");void 0!==t.resolution||ra()||(t.resolution=Ao.h1080fps30.resolution);const n=Wo(t),i=yield navigator.mediaDevices.getDisplayMedia(n),s=i.getVideoTracks();if(0===s.length)throw new ho("no video track found");const o=new Ur(s[0],void 0,!1,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});o.source=jo.Source.ScreenShare,t.contentHint&&(o.mediaStreamTrack.contentHint=t.contentHint);const a=[o];if(i.getAudioTracks().length>0){this.emit(e.ParticipantEvent.AudioStreamAcquired);const t=new Sr(i.getAudioTracks()[0],void 0,!1,this.audioContext,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});t.source=jo.Source.ScreenShareAudio,a.push(t)}return a}))}publishTrack(e,t){var n,i,s,o;return wi(this,void 0,void 0,(function*(){let a,r;if(e instanceof Sr&&e.setAudioContext(this.audioContext),yield null===(n=this.reconnectFuture)||void 0===n?void 0:n.promise,e instanceof xa&&this.pendingPublishPromises.has(e)&&(yield this.pendingPublishPromises.get(e)),e instanceof MediaStreamTrack)a=e.getConstraints();else{let t;switch(a=e.constraints,e.source){case jo.Source.Microphone:t="audioinput";break;case jo.Source.Camera:t="videoinput"}t&&this.activeDeviceMap.has(t)&&(a=Object.assign(Object.assign({},a),{deviceId:this.activeDeviceMap.get(t)}))}if(e instanceof MediaStreamTrack)switch(e.kind){case"audio":e=new Sr(e,a,!0,this.audioContext,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});break;case"video":e=new Ur(e,a,!0,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});break;default:throw new ho("unsupported MediaStreamTrack kind ".concat(e.kind))}else e.updateLoggerOptions({loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});if(this.trackPublications.forEach((t=>{t.track&&t.track===e&&(r=t)})),r)return this.log.warn("track has already been published, skipping",Object.assign(Object.assign({},this.logContext),zo(r))),r;const c="channelCount"in e.mediaStreamTrack.getSettings()&&2===e.mediaStreamTrack.getSettings().channelCount||2===e.mediaStreamTrack.getConstraints().channelCount,d=null!==(i=null==t?void 0:t.forceStereo)&&void 0!==i?i:c;d&&(t||(t={}),void 0===t.dtx&&this.log.info("Opus DTX will be disabled for stereo tracks by default. Enable them explicitly to make it work.",Object.assign(Object.assign({},this.logContext),zo(e))),void 0===t.red&&this.log.info("Opus RED will be disabled for stereo tracks by default. Enable them explicitly to make it work."),null!==(s=t.dtx)&&void 0!==s||(t.dtx=!1),null!==(o=t.red)&&void 0!==o||(t.red=!1));const l=Object.assign(Object.assign({},this.roomOptions.publishDefaults),t);aa()&&this.roomOptions.e2ee&&(this.log.info("End-to-end encryption is set up, simulcast publishing will be disabled on Safari",Object.assign({},this.logContext)),l.simulcast=!1),l.source&&(e.source=l.source);const u=this.publish(e,l,d);this.pendingPublishPromises.set(e,u);try{return yield u}catch(e){throw e}finally{this.pendingPublishPromises.delete(e)}}))}publish(t,n,i){var s,o,a,r,c,d,l,u,h,m,p,g;return wi(this,void 0,void 0,(function*(){Array.from(this.trackPublications.values()).find((e=>t instanceof xa&&e.source===t.source))&&t.source!==jo.Source.Unknown&&this.log.info("publishing a second track with the same source: ".concat(t.source),Object.assign(Object.assign({},this.logContext),zo(t))),n.stopMicTrackOnMute&&t instanceof Sr&&(t.stopOnMute=!0),t.source===jo.Source.ScreenShare&&oa()&&(n.simulcast=!1),"av1"!==n.videoCodec||$o()||(n.videoCodec=void 0),"vp9"!==n.videoCodec||ea()||(n.videoCodec=void 0),void 0===n.videoCodec&&(n.videoCodec=ar);const f=n.videoCodec;t.on(e.TrackEvent.Muted,this.onTrackMuted),t.on(e.TrackEvent.Unmuted,this.onTrackUnmuted),t.on(e.TrackEvent.Ended,this.handleTrackEnded),t.on(e.TrackEvent.UpstreamPaused,this.onTrackUpstreamPaused),t.on(e.TrackEvent.UpstreamResumed,this.onTrackUpstreamResumed);const v=new mn({cid:t.mediaStreamTrack.id,name:n.name,type:jo.kindToProto(t.kind),muted:t.isMuted,source:jo.sourceToProto(t.source),disableDtx:!(null===(s=n.dtx)||void 0===s||s),encryption:this.encryptionType,stereo:i,disableRed:this.isE2EEEnabled||!(null===(o=n.red)||void 0===o||o),stream:null==n?void 0:n.stream});let k;if(t.kind===jo.Kind.Video){let e={width:0,height:0};try{e=yield t.waitForDimensions()}catch(n){const i=null!==(r=null===(a=this.roomOptions.videoCaptureDefaults)||void 0===a?void 0:a.resolution)&&void 0!==r?r:No.h720.resolution;e={width:i.width,height:i.height},this.log.error("could not determine track dimensions, using defaults",Object.assign(Object.assign(Object.assign({},this.logContext),zo(t)),{dims:e}))}v.width=e.width,v.height=e.height,t instanceof Ur&&(ta(f)&&(t.source===jo.Source.ScreenShare&&(n.scalabilityMode="L1T3","contentHint"in t.mediaStreamTrack&&(t.mediaStreamTrack.contentHint="motion",this.log.info("forcing contentHint to motion for screenshare with SVC codecs",Object.assign(Object.assign({},this.logContext),zo(t))))),n.scalabilityMode=null!==(c=n.scalabilityMode)&&void 0!==c?c:"L3T3_KEY"),v.simulcastCodecs=[new hn({codec:f,cid:t.mediaStreamTrack.id})],!0===n.backupCodec&&(n.backupCodec={codec:ar}),n.backupCodec&&f!==n.backupCodec.codec&&v.encryption===Xe.NONE&&(this.roomOptions.dynacast||(this.roomOptions.dynacast=!0),v.simulcastCodecs.push(new hn({codec:n.backupCodec.codec,cid:""})))),k=xr(t.source===jo.Source.ScreenShare,v.width,v.height,n),v.layers=Br(v.width,v.height,k,ta(n.videoCodec))}else t.kind===jo.Kind.Audio&&(k=[{maxBitrate:null===(d=n.audioPreset)||void 0===d?void 0:d.maxBitrate,priority:null!==(u=null===(l=n.audioPreset)||void 0===l?void 0:l.priority)&&void 0!==u?u:"high",networkPriority:null!==(m=null===(h=n.audioPreset)||void 0===h?void 0:h.priority)&&void 0!==m?m:"high"}]);if(!this.engine||this.engine.isClosed)throw new po("cannot publish track when not connected");const T=yield this.engine.addTrack(v);let y;if(T.codecs.forEach((e=>{void 0===y&&(y=e.mimeType)})),y&&t.kind===jo.Kind.Video){const e=Ho(y);e!==f&&(this.log.debug("falling back to server selected codec",Object.assign(Object.assign(Object.assign({},this.logContext),zo(t)),{codec:e})),n.videoCodec=e,k=xr(t.source===jo.Source.ScreenShare,v.width,v.height,n))}const b=new Jr(t.kind,T,t,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});if(b.options=n,t.sid=T.sid,!this.engine.pcManager)throw new po("pcManager is not ready");if(this.log.debug("publishing ".concat(t.kind," with encodings"),Object.assign(Object.assign({},this.logContext),{encodings:k,trackInfo:T})),t.sender=yield this.engine.createSender(t,n,k),k)if(oa()&&t.kind===jo.Kind.Audio){let e;for(const n of this.engine.pcManager.publisher.getTransceivers())if(n.sender===t.sender){e=n;break}e&&this.engine.pcManager.publisher.setTrackCodecBitrate({transceiver:e,codec:"opus",maxbr:(null===(p=k[0])||void 0===p?void 0:p.maxBitrate)?k[0].maxBitrate/1e3:0})}else t.codec&&"av1"==t.codec&&(null===(g=k[0])||void 0===g?void 0:g.maxBitrate)&&this.engine.pcManager.publisher.setTrackCodecBitrate({cid:v.cid,codec:t.codec,maxbr:k[0].maxBitrate/1e3});if(t.kind===jo.Kind.Video&&t.source===jo.Source.ScreenShare)try{this.log.debug("setting degradationPreference to maintain-resolution");const e=t.sender.getParameters();e.degradationPreference="maintain-resolution",yield t.sender.setParameters(e)}catch(e){this.log.warn("failed to set degradationPreference: ".concat(e))}return yield this.engine.negotiate(),t instanceof Ur?t.startMonitor(this.engine.client):t instanceof Sr&&t.startMonitor(),this.addTrackPublication(b),this.emit(e.ParticipantEvent.LocalTrackPublished,b),b}))}get isLocal(){return!0}publishAdditionalCodecForTrack(e,t,n){var i;return wi(this,void 0,void 0,(function*(){if(this.encryptionType!==Xe.NONE)return;let s;if(this.trackPublications.forEach((t=>{t.track&&t.track===e&&(s=t)})),!s)throw new ho("track is not published");if(!(e instanceof Ur))throw new ho("track is not a video track");const o=Object.assign(Object.assign({},null===(i=this.roomOptions)||void 0===i?void 0:i.publishDefaults),n),a=function(e,t,n){var i,s,o,a;if(!n.backupCodec||!0===n.backupCodec||n.backupCodec.codec===n.videoCodec)return;t!==n.backupCodec.codec&&ki.warn("requested a different codec than specified as backup",{serverRequested:t,backup:n.backupCodec.codec}),n.videoCodec=t,n.videoEncoding=n.backupCodec.encoding;const r=e.mediaStreamTrack.getSettings(),c=null!==(i=r.width)&&void 0!==i?i:null===(s=e.dimensions)||void 0===s?void 0:s.width,d=null!==(o=r.height)&&void 0!==o?o:null===(a=e.dimensions)||void 0===a?void 0:a.height;return xr(e.source===jo.Source.ScreenShare,c,d,n)}(e,t,o);if(!a)return void this.log.info("backup codec has been disabled, ignoring request to add additional codec for track",Object.assign(Object.assign({},this.logContext),zo(e)));const r=e.addSimulcastTrack(t,a);if(!r)return;const c=new mn({cid:r.mediaStreamTrack.id,type:jo.kindToProto(e.kind),muted:e.isMuted,source:jo.sourceToProto(e.source),sid:e.sid,simulcastCodecs:[{codec:o.videoCodec,cid:r.mediaStreamTrack.id}]});if(c.layers=Br(c.width,c.height,a),!this.engine||this.engine.isClosed)throw new po("cannot publish track when not connected");const d=yield this.engine.addTrack(c);yield this.engine.createSimulcastSender(e,r,o,a),yield this.engine.negotiate(),this.log.debug("published ".concat(t," for track ").concat(e.sid),Object.assign(Object.assign({},this.logContext),{encodings:a,trackInfo:d}))}))}unpublishTrack(t,n){var i,s;return wi(this,void 0,void 0,(function*(){const o=this.getPublicationForTrack(t),a=o?zo(o):void 0;if(this.log.debug("unpublishing track",Object.assign(Object.assign({},this.logContext),a)),!o||!o.track)return void this.log.warn("track was not unpublished because no publication was found",Object.assign(Object.assign({},this.logContext),a));(t=o.track).off(e.TrackEvent.Muted,this.onTrackMuted),t.off(e.TrackEvent.Unmuted,this.onTrackUnmuted),t.off(e.TrackEvent.Ended,this.handleTrackEnded),t.off(e.TrackEvent.UpstreamPaused,this.onTrackUpstreamPaused),t.off(e.TrackEvent.UpstreamResumed,this.onTrackUpstreamResumed),void 0===n&&(n=null===(s=null===(i=this.roomOptions)||void 0===i?void 0:i.stopLocalTrackOnUnpublish)||void 0===s||s),n&&t.stop();let r=!1;const c=t.sender;if(t.sender=void 0,this.engine.pcManager&&this.engine.pcManager.currentState<hr.FAILED&&c)try{for(const e of this.engine.pcManager.publisher.getTransceivers())e.sender===c&&(e.direction="inactive",r=!0);if(this.engine.removeTrack(c)&&(r=!0),t instanceof Ur){for(const[,e]of t.simulcastCodecs)e.sender&&(this.engine.removeTrack(e.sender)&&(r=!0),e.sender=void 0);t.simulcastCodecs.clear()}}catch(e){this.log.warn("failed to unpublish track",Object.assign(Object.assign(Object.assign({},this.logContext),a),{error:e}))}switch(this.trackPublications.delete(o.trackSid),o.kind){case jo.Kind.Audio:this.audioTrackPublications.delete(o.trackSid);break;case jo.Kind.Video:this.videoTrackPublications.delete(o.trackSid)}return this.emit(e.ParticipantEvent.LocalTrackUnpublished,o),o.setTrack(void 0),r&&(yield this.engine.negotiate()),o}))}unpublishTracks(e){return wi(this,void 0,void 0,(function*(){return(yield Promise.all(e.map((e=>this.unpublishTrack(e))))).filter((e=>e instanceof Jr))}))}republishAllTracks(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return wi(this,void 0,void 0,(function*(){const n=[];this.trackPublications.forEach((t=>{t.track&&(e&&(t.options=Object.assign(Object.assign({},t.options),e)),n.push(t))})),yield Promise.all(n.map((e=>wi(this,void 0,void 0,(function*(){const n=e.track;yield this.unpublishTrack(n,!1),t&&!n.isMuted&&n.source!==jo.Source.ScreenShare&&n.source!==jo.Source.ScreenShareAudio&&(n instanceof Sr||n instanceof Ur)&&!n.isUserProvided&&(this.log.debug("restarting existing track",Object.assign(Object.assign({},this.logContext),{track:e.trackSid})),yield n.restartTrack()),yield this.publishTrack(n,e.options)})))))}))}publishData(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return wi(this,void 0,void 0,(function*(){const n=t.reliable?nt.RELIABLE:nt.LOSSY,i=t.destinationIdentities,s=t.topic,o=new tt({kind:n,value:{case:"user",value:new ot({participantIdentity:this.identity,payload:e,destinationIdentities:i,topic:s})}});yield this.engine.sendDataPacket(o,n)}))}setTrackSubscriptionPermissions(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[];this.participantTrackPermissions=t,this.allParticipantsAllowedToSubscribe=e,this.engine.client.isDisconnected||this.updateTrackSubscriptionPermissions()}updateInfo(e){return e.sid===this.sid&&(!!super.updateInfo(e)&&(e.tracks.forEach((e=>{var t,n;const i=this.trackPublications.get(e.sid);if(i){const s=i.isMuted||null!==(n=null===(t=i.track)||void 0===t?void 0:t.isUpstreamPaused)&&void 0!==n&&n;s!==e.muted&&(this.log.debug("updating server mute state after reconcile",Object.assign(Object.assign(Object.assign({},this.logContext),zo(i)),{mutedOnServer:s})),this.engine.client.sendMuteTrack(e.sid,s))}})),!0))}getPublicationForTrack(e){let t;return this.trackPublications.forEach((n=>{const i=n.track;i&&(e instanceof MediaStreamTrack?(i instanceof Sr||i instanceof Ur)&&i.mediaStreamTrack===e&&(t=n):e===i&&(t=n))})),t}}class Yr extends Hr{constructor(t,n,i,s){super(t,n.sid,n.name,s),this.track=void 0,this.allowed=!0,this.disabled=!1,this.currentVideoQuality=e.VideoQuality.HIGH,this.handleEnded=t=>{this.setTrack(void 0),this.emit(e.TrackEvent.Ended,t)},this.handleVisibilityChange=e=>{this.log.debug("adaptivestream video visibility ".concat(this.trackSid,", visible=").concat(e),this.logContext),this.disabled=!e,this.emitTrackUpdate()},this.handleVideoDimensionsChange=e=>{this.log.debug("adaptivestream video dimensions ".concat(e.width,"x").concat(e.height),this.logContext),this.videoDimensions=e,this.emitTrackUpdate()},this.subscribed=i,this.updateInfo(n)}setSubscribed(t){const n=this.subscriptionStatus,i=this.permissionStatus;this.subscribed=t,t&&(this.allowed=!0);const s=new Cn({trackSids:[this.trackSid],subscribe:this.subscribed,participantTracks:[new rt({participantSid:"",trackSids:[this.trackSid]})]});this.emit(e.TrackEvent.UpdateSubscription,s),this.emitSubscriptionUpdateIfChanged(n),this.emitPermissionUpdateIfChanged(i)}get subscriptionStatus(){return!1===this.subscribed?Hr.SubscriptionStatus.Unsubscribed:super.isSubscribed?Hr.SubscriptionStatus.Subscribed:Hr.SubscriptionStatus.Desired}get permissionStatus(){return this.allowed?Hr.PermissionStatus.Allowed:Hr.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,n;this.isManualOperationAllowed()&&((null===(t=this.videoDimensions)||void 0===t?void 0:t.width)===e.width&&(null===(n=this.videoDimensions)||void 0===n?void 0:n.height)===e.height||(this.track instanceof Kr&&(this.videoDimensions=e),this.currentVideoQuality=void 0,this.emitTrackUpdate()))}setVideoFPS(e){this.isManualOperationAllowed()&&this.track instanceof Kr&&this.fps!==e&&(this.fps=e,this.emitTrackUpdate())}get videoQuality(){return this.currentVideoQuality}setTrack(t){const n=this.subscriptionStatus,i=this.permissionStatus,s=this.track;s!==t&&(s&&(s.off(e.TrackEvent.VideoDimensionsChanged,this.handleVideoDimensionsChange),s.off(e.TrackEvent.VisibilityChanged,this.handleVisibilityChange),s.off(e.TrackEvent.Ended,this.handleEnded),s.detach(),s.stopMonitor(),this.emit(e.TrackEvent.Unsubscribed,s)),super.setTrack(t),t&&(t.sid=this.trackSid,t.on(e.TrackEvent.VideoDimensionsChanged,this.handleVideoDimensionsChange),t.on(e.TrackEvent.VisibilityChanged,this.handleVisibilityChange),t.on(e.TrackEvent.Ended,this.handleEnded),this.emit(e.TrackEvent.Subscribed,t)),this.emitPermissionUpdateIfChanged(i),this.emitSubscriptionUpdateIfChanged(n))}setAllowed(e){const t=this.subscriptionStatus,n=this.permissionStatus;this.allowed=e,this.emitPermissionUpdateIfChanged(n),this.emitSubscriptionUpdateIfChanged(t)}setSubscriptionError(t){this.emit(e.TrackEvent.SubscriptionFailed,t)}updateInfo(t){super.updateInfo(t);const n=this.metadataMuted;this.metadataMuted=t.muted,this.track?this.track.setMuted(t.muted):n!==t.muted&&this.emit(t.muted?e.TrackEvent.Muted:e.TrackEvent.Unmuted)}emitSubscriptionUpdateIfChanged(t){const n=this.subscriptionStatus;t!==n&&this.emit(e.TrackEvent.SubscriptionStatusChanged,n,t)}emitPermissionUpdateIfChanged(t){this.permissionStatus!==t&&this.emit(e.TrackEvent.SubscriptionPermissionChanged,this.permissionStatus,t)}isManualOperationAllowed(){return this.kind===jo.Kind.Video&&this.isAdaptiveStream?(this.log.warn("adaptive stream is enabled, cannot change video track settings",this.logContext),!1):!!this.isDesired||(this.log.warn("cannot update track settings when not subscribed",this.logContext),!1)}get isAdaptiveStream(){return this.track instanceof Kr&&this.track.isAdaptiveStream}emitTrackUpdate(){const t=new Sn({trackSids:[this.trackSid],disabled:this.disabled,fps:this.fps});this.videoDimensions?(t.width=Math.ceil(this.videoDimensions.width),t.height=Math.ceil(this.videoDimensions.height)):void 0!==this.currentVideoQuality?t.quality=this.currentVideoQuality:t.quality=e.VideoQuality.HIGH,this.emit(e.TrackEvent.UpdateSettings,t)}}class Xr extends zr{static fromParticipantInfo(e,t){return new Xr(e,t.sid,t.identity,t.name,t.metadata)}get logContext(){return Object.assign(Object.assign({},super.logContext),{rpID:this.sid,remoteParticipant:this.identity})}constructor(e,t,n,i,s,o){super(t,n||"",i,s,o),this.signalClient=e,this.trackPublications=new Map,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.volumeMap=new Map}addTrackPublication(t){super.addTrackPublication(t),t.on(e.TrackEvent.UpdateSettings,(e=>{this.log.debug("send update settings",Object.assign(Object.assign({},this.logContext),zo(t))),this.signalClient.sendUpdateTrackSettings(e)})),t.on(e.TrackEvent.UpdateSubscription,(e=>{e.participantTracks.forEach((e=>{e.participantSid=this.sid})),this.signalClient.sendUpdateSubscription(e)})),t.on(e.TrackEvent.SubscriptionPermissionChanged,(n=>{this.emit(e.ParticipantEvent.TrackSubscriptionPermissionChanged,t,n)})),t.on(e.TrackEvent.SubscriptionStatusChanged,(n=>{this.emit(e.ParticipantEvent.TrackSubscriptionStatusChanged,t,n)})),t.on(e.TrackEvent.Subscribed,(n=>{this.emit(e.ParticipantEvent.TrackSubscribed,n,t)})),t.on(e.TrackEvent.Unsubscribed,(n=>{this.emit(e.ParticipantEvent.TrackUnsubscribed,n,t)})),t.on(e.TrackEvent.SubscriptionFailed,(n=>{this.emit(e.ParticipantEvent.TrackSubscriptionFailed,t.trackSid,n)}))}getTrackPublication(e){const t=super.getTrackPublication(e);if(t)return t}getTrackPublicationByName(e){const t=super.getTrackPublicationByName(e);if(t)return t}setVolume(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:jo.Source.Microphone;this.volumeMap.set(t,e);const n=this.getTrackPublication(t);n&&n.track&&n.track.setVolume(e)}getVolume(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:jo.Source.Microphone;const t=this.getTrackPublication(e);return t&&t.track?t.track.getVolume():this.volumeMap.get(e)}addSubscribedMediaTrack(t,n,i,s,o,a){let r=this.getTrackPublicationBySid(n);if(r||n.startsWith("TR")||this.trackPublications.forEach((e=>{r||t.kind!==e.kind.toString()||(r=e)})),!r)return 0===a?(this.log.error("could not find published track",Object.assign(Object.assign({},this.logContext),{trackSid:n})),void this.emit(e.ParticipantEvent.TrackSubscriptionFailed,n)):(void 0===a&&(a=20),void setTimeout((()=>{this.addSubscribedMediaTrack(t,n,i,s,o,a-1)}),150));if("ended"===t.readyState)return this.log.error("unable to subscribe because MediaStreamTrack is ended. Do not call MediaStreamTrack.stop()",Object.assign(Object.assign({},this.logContext),zo(r))),void this.emit(e.ParticipantEvent.TrackSubscriptionFailed,n);let c;return c="video"===t.kind?new Kr(t,n,s,o):new qr(t,n,s,this.audioContext,this.audioOutput),c.source=r.source,c.isMuted=r.isMuted,c.setMediaStream(i),c.start(),r.setTrack(c),this.volumeMap.has(r.source)&&c instanceof qr&&c.setVolume(this.volumeMap.get(r.source)),r}get hasMetadata(){return!!this.participantInfo}getTrackPublicationBySid(e){return this.trackPublications.get(e)}updateInfo(t){if(!super.updateInfo(t))return!1;const n=new Map,i=new Map;return t.tracks.forEach((e=>{var t,s;let o=this.getTrackPublicationBySid(e.sid);if(o)o.updateInfo(e);else{const n=jo.kindFromProto(e.type);if(!n)return;o=new Yr(n,e,null===(t=this.signalClient.connectOptions)||void 0===t?void 0:t.autoSubscribe,{loggerContextCb:()=>this.logContext,loggerName:null===(s=this.loggerOptions)||void 0===s?void 0:s.loggerName}),o.updateInfo(e),i.set(e.sid,o);const a=Array.from(this.trackPublications.values()).find((e=>e.source===(null==o?void 0:o.source)));a&&o.source!==jo.Source.Unknown&&this.log.debug("received a second track publication for ".concat(this.identity," with the same source: ").concat(o.source),Object.assign(Object.assign({},this.logContext),{oldTrack:zo(a),newTrack:zo(o)})),this.addTrackPublication(o)}n.set(e.sid,o)})),this.trackPublications.forEach((e=>{n.has(e.trackSid)||(this.log.trace("detected removed track on remote participant, unpublishing",Object.assign(Object.assign({},this.logContext),zo(e))),this.unpublishTrack(e.trackSid,!0))})),i.forEach((t=>{this.emit(e.ParticipantEvent.TrackPublished,t)})),!0}unpublishTrack(t,n){const i=this.trackPublications.get(t);if(!i)return;const{track:s}=i;switch(s&&(s.stop(),i.setTrack(void 0)),this.trackPublications.delete(t),i.kind){case jo.Kind.Audio:this.audioTrackPublications.delete(t);break;case jo.Kind.Video:this.videoTrackPublications.delete(t)}n&&this.emit(e.ParticipantEvent.TrackUnpublished,i)}setAudioOutput(e){return wi(this,void 0,void 0,(function*(){this.audioOutput=e;const t=[];this.audioTrackPublications.forEach((n=>{var i;n.track instanceof qr&&t.push(n.track.setSinkId(null!==(i=e.deviceId)&&void 0!==i?i:"default"))})),yield Promise.all(t)}))}emit(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),i=1;i<t;i++)n[i-1]=arguments[i];return this.log.trace("participant event",Object.assign(Object.assign({},this.logContext),{event:e,args:n})),super.emit(e,...n)}}var Zr;e.ConnectionState=void 0,(Zr=e.ConnectionState||(e.ConnectionState={})).Disconnected="disconnected",Zr.Connecting="connecting",Zr.Connected="connected",Zr.Reconnecting="reconnecting";class $r extends Gi.EventEmitter{constructor(t){var n,i,s;super(),n=this,this.state=e.ConnectionState.Disconnected,this.activeSpeakers=[],this.isE2EEEnabled=!1,this.audioEnabled=!0,this.isVideoPlaybackBlocked=!1,this.log=ki,this.bufferedEvents=[],this.isResuming=!1,this.connect=(t,n,i)=>wi(this,void 0,void 0,(function*(){var s;if(!sa())throw la()?Error("WebRTC isn't detected, have you called registerGlobals?"):Error("LiveKit doesn't seem to be supported on this browser. Try to update your browser and make sure no browser extensions are disabling webRTC.");const o=yield this.disconnectLock.lock();if(this.state===e.ConnectionState.Connected)return this.log.info("already connected to room ".concat(this.name),this.logContext),o(),Promise.resolve();if(this.connectFuture)return o(),this.connectFuture.promise;this.setAndEmitConnectionState(e.ConnectionState.Connecting),(null===(s=this.regionUrlProvider)||void 0===s?void 0:s.getServerUrl().toString())!==t&&(this.regionUrl=void 0,this.regionUrlProvider=void 0),ua(new URL(t))&&(void 0===this.regionUrlProvider?this.regionUrlProvider=new yr(t,n):this.regionUrlProvider.updateToken(n),this.regionUrlProvider.fetchRegionSettings().catch((e=>{this.log.warn("could not fetch region settings",Object.assign(Object.assign({},this.logContext),{error:e}))})));const a=(e,s,r)=>wi(this,void 0,void 0,(function*(){var c;this.abortController&&this.abortController.abort();const d=new AbortController;this.abortController=d,null==o||o();try{yield this.attemptConnection(null!=r?r:t,n,i,d),this.abortController=void 0,e()}catch(t){if(this.regionUrlProvider&&t instanceof lo&&3!==t.reason&&0!==t.reason){let n=null;try{n=yield this.regionUrlProvider.getNextBestRegionUrl(null===(c=this.abortController)||void 0===c?void 0:c.signal)}catch(e){if(e instanceof lo&&(401===e.status||3===e.reason))return this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),void s(e)}n?(this.log.info("Initial connection failed with ConnectionError: ".concat(t.message,". Retrying with another region: ").concat(n),this.logContext),this.recreateEngine(),yield a(e,s,n)):(this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),s(t))}else this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),s(t)}})),r=this.regionUrl;return this.regionUrl=void 0,this.connectFuture=new Pa(((e,t)=>{a(e,t,r)}),(()=>{this.clearConnectionFutures()})),this.connectFuture.promise})),this.connectSignal=(e,t,n,i,s,o)=>wi(this,void 0,void 0,(function*(){var a,r,c;const d=yield n.join(e,t,{autoSubscribe:i.autoSubscribe,adaptiveStream:"object"==typeof s.adaptiveStream||s.adaptiveStream,maxRetries:i.maxRetries,e2eeEnabled:!!this.e2eeManager,websocketTimeout:i.websocketTimeout},o.signal);let l=d.serverInfo;if(l||(l={version:d.serverVersion,region:d.serverRegion}),this.log.debug("connected to Livekit Server ".concat(Object.entries(l).map((e=>{let[t,n]=e;return"".concat(t,": ").concat(n)})).join(", ")),{room:null===(a=d.room)||void 0===a?void 0:a.name,roomSid:null===(r=d.room)||void 0===r?void 0:r.sid,identity:null===(c=d.participant)||void 0===c?void 0:c.identity}),!d.serverVersion)throw new mo("unknown server version");return"0.15.1"===d.serverVersion&&this.options.dynacast&&(this.log.debug("disabling dynacast due to server version",this.logContext),s.dynacast=!1),d})),this.applyJoinResponse=e=>{const t=e.participant;if(this.localParticipant.sid=t.sid,this.localParticipant.identity=t.identity,this.options.e2ee&&this.e2eeManager)try{this.e2eeManager.setSifTrailer(e.sifTrailer)}catch(e){this.log.error(e instanceof Error?e.message:"Could not set SifTrailer",Object.assign(Object.assign({},this.logContext),{error:e}))}this.handleParticipantUpdates([t,...e.otherParticipants]),e.room&&this.handleRoomUpdate(e.room)},this.attemptConnection=(t,n,i,s)=>wi(this,void 0,void 0,(function*(){var o,a,r;this.state===e.ConnectionState.Reconnecting||this.isResuming||(null===(o=this.engine)||void 0===o?void 0:o.pendingReconnect)?(this.log.info("Reconnection attempt replaced by new connection attempt",this.logContext),this.recreateEngine()):this.maybeCreateEngine(),(null===(a=this.regionUrlProvider)||void 0===a?void 0:a.isCloud())&&this.engine.setRegionUrlProvider(this.regionUrlProvider),this.acquireAudioContext(),this.connOptions=Object.assign(Object.assign({},ur),i),this.connOptions.rtcConfig&&(this.engine.rtcConfig=this.connOptions.rtcConfig),this.connOptions.peerConnectionTimeout&&(this.engine.peerConnectionTimeout=this.connOptions.peerConnectionTimeout);try{const i=yield this.connectSignal(t,n,this.engine,this.connOptions,this.options,s);this.applyJoinResponse(i),this.setupLocalParticipantEvents(),this.emit(e.RoomEvent.SignalConnected)}catch(e){yield this.engine.close(),this.recreateEngine();const t=new lo("could not establish signal connection");throw e instanceof Error&&(t.message="".concat(t.message,": ").concat(e.message)),e instanceof lo&&(t.reason=e.reason,t.status=e.status),this.log.debug("error trying to establish signal connection",Object.assign(Object.assign({},this.logContext),{error:e})),t}if(s.signal.aborted)throw yield this.engine.close(),this.recreateEngine(),new lo("Connection attempt aborted");try{yield this.engine.waitForPCInitialConnection(this.connOptions.peerConnectionTimeout,s)}catch(e){throw yield this.engine.close(),this.recreateEngine(),e}da()&&this.options.disconnectOnPageLeave&&(window.addEventListener("pagehide",this.onPageLeave),window.addEventListener("beforeunload",this.onPageLeave)),da()&&(document.addEventListener("freeze",this.onPageLeave),null===(r=navigator.mediaDevices)||void 0===r||r.addEventListener("devicechange",this.handleDeviceChange)),this.setAndEmitConnectionState(e.ConnectionState.Connected),this.emit(e.RoomEvent.Connected),this.registerConnectionReconcile()})),this.disconnect=function(){let t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return wi(n,void 0,void 0,(function*(){var n,i,s,o;const a=yield this.disconnectLock.lock();try{if(this.state===e.ConnectionState.Disconnected)return void this.log.debug("already disconnected",this.logContext);this.log.info("disconnect from room",Object.assign({},this.logContext)),(this.state===e.ConnectionState.Connecting||this.state===e.ConnectionState.Reconnecting||this.isResuming)&&(this.log.warn("abort connection attempt",this.logContext),null===(n=this.abortController)||void 0===n||n.abort(),null===(s=null===(i=this.connectFuture)||void 0===i?void 0:i.reject)||void 0===s||s.call(i,new lo("Client initiated disconnect")),this.connectFuture=void 0),(null===(o=this.engine)||void 0===o?void 0:o.client.isDisconnected)||(yield this.engine.client.sendLeave()),this.engine&&(yield this.engine.close()),this.handleDisconnect(t,qe.CLIENT_INITIATED),this.engine=void 0}finally{a()}}))},this.onPageLeave=()=>wi(this,void 0,void 0,(function*(){this.log.info("Page leave detected, disconnecting",this.logContext),yield this.disconnect()})),this.startAudio=()=>wi(this,void 0,void 0,(function*(){const t=[],n=Eo();if(n&&"iOS"===n.os){const n="livekit-dummy-audio-el";let i=document.getElementById(n);if(!i){i=document.createElement("audio"),i.id=n,i.autoplay=!0,i.hidden=!0;const t=wa();t.enabled=!0;const s=new MediaStream([t]);i.srcObject=s,document.addEventListener("visibilitychange",(()=>{i&&(i.srcObject=document.hidden?null:s,document.hidden||(this.log.debug("page visible again, triggering startAudio to resume playback and update playback status",this.logContext),this.startAudio()))})),document.body.append(i),this.once(e.RoomEvent.Disconnected,(()=>{null==i||i.remove(),i=null}))}t.push(i)}this.remoteParticipants.forEach((e=>{e.audioTrackPublications.forEach((e=>{e.track&&e.track.attachedElements.forEach((e=>{t.push(e)}))}))}));try{yield Promise.all([this.acquireAudioContext(),...t.map((e=>(e.muted=!1,e.play())))]),this.handleAudioPlaybackStarted()}catch(e){throw this.handleAudioPlaybackFailed(e),e}})),this.startVideo=()=>wi(this,void 0,void 0,(function*(){const e=[];for(const t of this.remoteParticipants.values())t.videoTrackPublications.forEach((t=>{var n;null===(n=t.track)||void 0===n||n.attachedElements.forEach((t=>{e.includes(t)||e.push(t)}))}));yield Promise.all(e.map((e=>e.play()))).then((()=>{this.handleVideoPlaybackStarted()})).catch((e=>{"NotAllowedError"===e.name?this.handleVideoPlaybackFailed():this.log.warn("Resuming video playback failed, make sure you call `startVideo` directly in a user gesture handler",this.logContext)}))})),this.handleRestarting=()=>{this.clearConnectionReconcile(),this.isResuming=!1;for(const e of this.remoteParticipants.values())this.handleParticipantDisconnected(e.identity,e);this.setAndEmitConnectionState(e.ConnectionState.Reconnecting)&&this.emit(e.RoomEvent.Reconnecting)},this.handleSignalRestarted=t=>wi(this,void 0,void 0,(function*(){this.log.debug("signal reconnected to server, region ".concat(t.serverRegion),Object.assign(Object.assign({},this.logContext),{region:t.serverRegion})),this.bufferedEvents=[],this.applyJoinResponse(t);try{yield this.localParticipant.republishAllTracks(void 0,!0)}catch(e){this.log.error("error trying to re-publish tracks after reconnection",Object.assign(Object.assign({},this.logContext),{error:e}))}try{yield this.engine.waitForRestarted(),this.log.debug("fully reconnected to server",Object.assign(Object.assign({},this.logContext),{region:t.serverRegion}))}catch(e){return}this.setAndEmitConnectionState(e.ConnectionState.Connected),this.emit(e.RoomEvent.Reconnected),this.registerConnectionReconcile(),this.emitBufferedEvents()})),this.handleParticipantUpdates=e=>{e.forEach((e=>{var t;if(e.identity===this.localParticipant.identity)return void this.localParticipant.updateInfo(e);""===e.identity&&(e.identity=null!==(t=this.sidToIdentity.get(e.sid))&&void 0!==t?t:"");let n=this.remoteParticipants.get(e.identity);e.state===Qe.DISCONNECTED?this.handleParticipantDisconnected(e.identity,n):n=this.getOrCreateParticipant(e.identity,e)}))},this.handleActiveSpeakersUpdate=t=>{const n=[],i={};t.forEach((e=>{if(i[e.sid]=!0,e.sid===this.localParticipant.sid)this.localParticipant.audioLevel=e.level,this.localParticipant.setIsSpeaking(!0),n.push(this.localParticipant);else{const t=this.getRemoteParticipantBySid(e.sid);t&&(t.audioLevel=e.level,t.setIsSpeaking(!0),n.push(t))}})),i[this.localParticipant.sid]||(this.localParticipant.audioLevel=0,this.localParticipant.setIsSpeaking(!1)),this.remoteParticipants.forEach((e=>{i[e.sid]||(e.audioLevel=0,e.setIsSpeaking(!1))})),this.activeSpeakers=n,this.emitWhenConnected(e.RoomEvent.ActiveSpeakersChanged,n)},this.handleSpeakersChanged=t=>{const n=new Map;this.activeSpeakers.forEach((e=>{n.set(e.sid,e)})),t.forEach((e=>{let t=this.getRemoteParticipantBySid(e.sid);e.sid===this.localParticipant.sid&&(t=this.localParticipant),t&&(t.audioLevel=e.level,t.setIsSpeaking(e.active),e.active?n.set(e.sid,t):n.delete(e.sid))}));const i=Array.from(n.values());i.sort(((e,t)=>t.audioLevel-e.audioLevel)),this.activeSpeakers=i,this.emitWhenConnected(e.RoomEvent.ActiveSpeakersChanged,i)},this.handleStreamStateUpdate=t=>{t.streamStates.forEach((t=>{const n=this.getRemoteParticipantBySid(t.participantSid);if(!n)return;const i=n.getTrackPublicationBySid(t.trackSid);i&&i.track&&(i.track.streamState=jo.streamStateFromProto(t.state),n.emit(e.ParticipantEvent.TrackStreamStateChanged,i,i.track.streamState),this.emitWhenConnected(e.RoomEvent.TrackStreamStateChanged,i,i.track.streamState,n))}))},this.handleSubscriptionPermissionUpdate=e=>{const t=this.getRemoteParticipantBySid(e.participantSid);if(!t)return;const n=t.getTrackPublicationBySid(e.trackSid);n&&n.setAllowed(e.allowed)},this.handleSubscriptionError=e=>{const t=Array.from(this.remoteParticipants.values()).find((t=>t.trackPublications.has(e.trackSid)));if(!t)return;const n=t.getTrackPublicationBySid(e.trackSid);n&&n.setSubscriptionError(e.err)},this.handleDataPacket=(t,n)=>{const i=this.remoteParticipants.get(t.participantIdentity);this.emit(e.RoomEvent.DataReceived,t.payload,i,n,t.topic),null==i||i.emit(e.ParticipantEvent.DataReceived,t.payload,n)},this.handleAudioPlaybackStarted=()=>{this.canPlaybackAudio||(this.audioEnabled=!0,this.emit(e.RoomEvent.AudioPlaybackStatusChanged,!0))},this.handleAudioPlaybackFailed=t=>{this.log.warn("could not playback audio",Object.assign(Object.assign({},this.logContext),{error:t})),this.canPlaybackAudio&&(this.audioEnabled=!1,this.emit(e.RoomEvent.AudioPlaybackStatusChanged,!1))},this.handleVideoPlaybackStarted=()=>{this.isVideoPlaybackBlocked&&(this.isVideoPlaybackBlocked=!1,this.emit(e.RoomEvent.VideoPlaybackStatusChanged,!0))},this.handleVideoPlaybackFailed=()=>{this.isVideoPlaybackBlocked||(this.isVideoPlaybackBlocked=!0,this.emit(e.RoomEvent.VideoPlaybackStatusChanged,!1))},this.handleDeviceChange=()=>wi(this,void 0,void 0,(function*(){this.emit(e.RoomEvent.MediaDevicesChanged)})),this.handleRoomUpdate=t=>{const n=this.roomInfo;this.roomInfo=t,n&&n.metadata!==t.metadata&&this.emitWhenConnected(e.RoomEvent.RoomMetadataChanged,t.metadata),(null==n?void 0:n.activeRecording)!==t.activeRecording&&this.emitWhenConnected(e.RoomEvent.RecordingStatusChanged,t.activeRecording)},this.handleConnectionQualityUpdate=e=>{e.updates.forEach((e=>{if(e.participantSid===this.localParticipant.sid)return void this.localParticipant.setConnectionQuality(e.quality);const t=this.getRemoteParticipantBySid(e.participantSid);t&&t.setConnectionQuality(e.quality)}))},this.onLocalParticipantMetadataChanged=t=>{this.emit(e.RoomEvent.ParticipantMetadataChanged,t,this.localParticipant)},this.onLocalParticipantNameChanged=t=>{this.emit(e.RoomEvent.ParticipantNameChanged,t,this.localParticipant)},this.onLocalTrackMuted=t=>{this.emit(e.RoomEvent.TrackMuted,t,this.localParticipant)},this.onLocalTrackUnmuted=t=>{this.emit(e.RoomEvent.TrackUnmuted,t,this.localParticipant)},this.onTrackProcessorUpdate=e=>{var t;null===(t=null==e?void 0:e.onPublish)||void 0===t||t.call(e,this)},this.onLocalTrackPublished=t=>wi(this,void 0,void 0,(function*(){var n,i,s,o,a;if(null===(n=t.track)||void 0===n||n.on(e.TrackEvent.TrackProcessorUpdate,this.onTrackProcessorUpdate),null===(o=null===(s=null===(i=t.track)||void 0===i?void 0:i.getProcessor())||void 0===s?void 0:s.onPublish)||void 0===o||o.call(s,this),this.emit(e.RoomEvent.LocalTrackPublished,t,this.localParticipant),t.track instanceof Sr){(yield t.track.checkForSilence())&&this.emit(e.RoomEvent.LocalAudioSilenceDetected,t)}const r=yield null===(a=t.track)||void 0===a?void 0:a.getDeviceId(),c=(d=t.source)===jo.Source.Microphone?"audioinput":d===jo.Source.Camera?"videoinput":void 0;var d;c&&r&&r!==this.localParticipant.activeDeviceMap.get(c)&&(this.localParticipant.activeDeviceMap.set(c,r),this.emit(e.RoomEvent.ActiveDeviceChanged,c,r))})),this.onLocalTrackUnpublished=t=>{var n;null===(n=t.track)||void 0===n||n.off(e.TrackEvent.TrackProcessorUpdate,this.onTrackProcessorUpdate),this.emit(e.RoomEvent.LocalTrackUnpublished,t,this.localParticipant)},this.onLocalConnectionQualityChanged=t=>{this.emit(e.RoomEvent.ConnectionQualityChanged,t,this.localParticipant)},this.onMediaDevicesError=t=>{this.emit(e.RoomEvent.MediaDevicesError,t)},this.onLocalParticipantPermissionsChanged=t=>{this.emit(e.RoomEvent.ParticipantPermissionsChanged,t,this.localParticipant)},this.setMaxListeners(100),this.remoteParticipants=new Map,this.sidToIdentity=new Map,this.options=Object.assign(Object.assign({},lr),t),this.log=yi(null!==(i=this.options.loggerName)&&void 0!==i?i:e.LoggerNames.Room),this.options.audioCaptureDefaults=Object.assign(Object.assign({},cr),null==t?void 0:t.audioCaptureDefaults),this.options.videoCaptureDefaults=Object.assign(Object.assign({},dr),null==t?void 0:t.videoCaptureDefaults),this.options.publishDefaults=Object.assign(Object.assign({},rr),null==t?void 0:t.publishDefaults),this.maybeCreateEngine(),this.disconnectLock=new Ra,this.localParticipant=new Qr("","",this.engine,this.options),this.options.videoCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("videoinput",_a(this.options.videoCaptureDefaults.deviceId)),this.options.audioCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("audioinput",_a(this.options.audioCaptureDefaults.deviceId)),(null===(s=this.options.audioOutput)||void 0===s?void 0:s.deviceId)&&this.switchActiveDevice("audiooutput",_a(this.options.audioOutput.deviceId)).catch((e=>this.log.warn("Could not set audio output: ".concat(e.message),this.logContext))),this.options.e2ee&&this.setupE2EE()}setE2EEEnabled(e){return wi(this,void 0,void 0,(function*(){if(!this.e2eeManager)throw Error("e2ee not configured, please set e2ee settings within the room options");yield Promise.all([this.localParticipant.setE2EEEnabled(e)]),""!==this.localParticipant.identity&&this.e2eeManager.setParticipantCryptorEnabled(e,this.localParticipant.identity)}))}setupE2EE(){var t;this.options.e2ee&&(this.e2eeManager=new Da(this.options.e2ee),this.e2eeManager.on(e.EncryptionEvent.ParticipantEncryptionStatusChanged,((t,n)=>{n instanceof Qr&&(this.isE2EEEnabled=t),this.emit(e.RoomEvent.ParticipantEncryptionStatusChanged,t,n)})),this.e2eeManager.on(e.EncryptionEvent.EncryptionError,(t=>this.emit(e.RoomEvent.EncryptionError,t))),null===(t=this.e2eeManager)||void 0===t||t.setup(this))}get logContext(){var e;return{room:this.name,roomID:null===(e=this.roomInfo)||void 0===e?void 0:e.sid,participant:this.localParticipant.identity,pID:this.localParticipant.sid}}get isRecording(){var e,t;return null!==(t=null===(e=this.roomInfo)||void 0===e?void 0:e.activeRecording)&&void 0!==t&&t}getSid(){return wi(this,void 0,void 0,(function*(){return this.state===e.ConnectionState.Disconnected?"":this.roomInfo&&""!==this.roomInfo.sid?this.roomInfo.sid:new Promise(((t,n)=>{const i=n=>{""!==n.sid&&(this.engine.off(e.EngineEvent.RoomUpdate,i),t(n.sid))};this.engine.on(e.EngineEvent.RoomUpdate,i),this.once(e.RoomEvent.Disconnected,(()=>{this.engine.off(e.EngineEvent.RoomUpdate,i),n("Room disconnected before room server id was available")}))}))}))}get name(){var e,t;return null!==(t=null===(e=this.roomInfo)||void 0===e?void 0:e.name)&&void 0!==t?t:""}get metadata(){var e;return null===(e=this.roomInfo)||void 0===e?void 0:e.metadata}get numParticipants(){var e,t;return null!==(t=null===(e=this.roomInfo)||void 0===e?void 0:e.numParticipants)&&void 0!==t?t:0}get numPublishers(){var e,t;return null!==(t=null===(e=this.roomInfo)||void 0===e?void 0:e.numPublishers)&&void 0!==t?t:0}maybeCreateEngine(){this.engine&&!this.engine.isClosed||(this.engine=new kr(this.options),this.engine.on(e.EngineEvent.ParticipantUpdate,this.handleParticipantUpdates).on(e.EngineEvent.RoomUpdate,this.handleRoomUpdate).on(e.EngineEvent.SpeakersChanged,this.handleSpeakersChanged).on(e.EngineEvent.StreamStateChanged,this.handleStreamStateUpdate).on(e.EngineEvent.ConnectionQualityUpdate,this.handleConnectionQualityUpdate).on(e.EngineEvent.SubscriptionError,this.handleSubscriptionError).on(e.EngineEvent.SubscriptionPermissionUpdate,this.handleSubscriptionPermissionUpdate).on(e.EngineEvent.MediaTrackAdded,((e,t,n)=>{this.onTrackAdded(e,t,n)})).on(e.EngineEvent.Disconnected,(e=>{this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e)})).on(e.EngineEvent.ActiveSpeakersUpdate,this.handleActiveSpeakersUpdate).on(e.EngineEvent.DataPacketReceived,this.handleDataPacket).on(e.EngineEvent.Resuming,(()=>{this.clearConnectionReconcile(),this.isResuming=!0,this.log.info("Resuming signal connection",this.logContext)})).on(e.EngineEvent.Resumed,(()=>{this.registerConnectionReconcile(),this.isResuming=!1,this.log.info("Resumed signal connection",this.logContext),this.updateSubscriptions(),this.emitBufferedEvents()})).on(e.EngineEvent.SignalResumed,(()=>{this.bufferedEvents=[],(this.state===e.ConnectionState.Reconnecting||this.isResuming)&&this.sendSyncState()})).on(e.EngineEvent.Restarting,this.handleRestarting).on(e.EngineEvent.SignalRestarted,this.handleSignalRestarted).on(e.EngineEvent.Offline,(()=>{this.setAndEmitConnectionState(e.ConnectionState.Reconnecting)&&this.emit(e.RoomEvent.Reconnecting)})).on(e.EngineEvent.DCBufferStatusChanged,((t,n)=>{this.emit(e.RoomEvent.DCBufferStatusChanged,t,n)})),this.localParticipant&&this.localParticipant.setupEngine(this.engine),this.e2eeManager&&this.e2eeManager.setupEngine(this.engine))}static getLocalDevices(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return Ma.getInstance().getDevices(e,t)}prepareConnection(t,n){return wi(this,void 0,void 0,(function*(){if(this.state===e.ConnectionState.Disconnected){this.log.debug("prepareConnection to ".concat(t),this.logContext);try{if(ua(new URL(t))&&n){this.regionUrlProvider=new yr(t,n);const i=yield this.regionUrlProvider.getNextBestRegionUrl();i&&this.state===e.ConnectionState.Disconnected&&(this.regionUrl=i,yield fetch(Ia(i),{method:"HEAD"}),this.log.debug("prepared connection to ".concat(i),this.logContext))}else yield fetch(Ia(t),{method:"HEAD"})}catch(e){this.log.warn("could not prepare connection",Object.assign(Object.assign({},this.logContext),{error:e}))}}}))}getParticipantByIdentity(e){return this.localParticipant.identity===e?this.localParticipant:this.remoteParticipants.get(e)}clearConnectionFutures(){this.connectFuture=void 0}simulateScenario(e,t){return wi(this,void 0,void 0,(function*(){let n,i=()=>{};switch(e){case"signal-reconnect":yield this.engine.client.handleOnClose("simulate disconnect");break;case"speaker":n=new Kn({scenario:{case:"speakerUpdate",value:3}});break;case"node-failure":n=new Kn({scenario:{case:"nodeFailure",value:!0}});break;case"server-leave":n=new Kn({scenario:{case:"serverLeave",value:!0}});break;case"migration":n=new Kn({scenario:{case:"migration",value:!0}});break;case"resume-reconnect":this.engine.failNext(),yield this.engine.client.handleOnClose("simulate resume-disconnect");break;case"disconnect-signal-on-resume":i=()=>wi(this,void 0,void 0,(function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")})),n=new Kn({scenario:{case:"disconnectSignalOnResume",value:!0}});break;case"disconnect-signal-on-resume-no-messages":i=()=>wi(this,void 0,void 0,(function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")})),n=new Kn({scenario:{case:"disconnectSignalOnResumeNoMessages",value:!0}});break;case"full-reconnect":this.engine.fullReconnectOnNext=!0,yield this.engine.client.handleOnClose("simulate full-reconnect");break;case"force-tcp":case"force-tls":n=new Kn({scenario:{case:"switchCandidateProtocol",value:"force-tls"===e?2:1}}),i=()=>wi(this,void 0,void 0,(function*(){const e=this.engine.client.onLeave;e&&e(new En({reason:qe.CLIENT_INITIATED,canReconnect:!0}))}));break;case"subscriber-bandwidth":if(void 0===t||"number"!=typeof t)throw new Error("subscriber-bandwidth requires a number as argument");n=new Kn({scenario:{case:"subscriberBandwidth",value:BigInt(t)}})}n&&(yield this.engine.client.sendSimulateScenario(n),yield i())}))}get canPlaybackAudio(){return this.audioEnabled}get canPlaybackVideo(){return!this.isVideoPlaybackBlocked}getActiveDevice(e){return this.localParticipant.activeDeviceMap.get(e)}switchActiveDevice(t,n){let i=arguments.length>2&&void 0!==arguments[2]&&arguments[2];var s,o,a,r;return wi(this,void 0,void 0,(function*(){let c=!1,d=!0;const l=i?{exact:n}:n;if("audioinput"===t){const e=this.options.audioCaptureDefaults.deviceId;this.options.audioCaptureDefaults.deviceId=l,c=e!==l;const t=Array.from(this.localParticipant.audioTrackPublications.values()).filter((e=>e.source===jo.Source.Microphone));try{d=(yield Promise.all(t.map((e=>{var t;return null===(t=e.audioTrack)||void 0===t?void 0:t.setDeviceId(l)})))).every((e=>!0===e))}catch(t){throw this.options.audioCaptureDefaults.deviceId=e,t}}else if("videoinput"===t){const e=this.options.videoCaptureDefaults.deviceId;this.options.videoCaptureDefaults.deviceId=l,c=e!==l;const t=Array.from(this.localParticipant.videoTrackPublications.values()).filter((e=>e.source===jo.Source.Camera));try{d=(yield Promise.all(t.map((e=>{var t;return null===(t=e.videoTrack)||void 0===t?void 0:t.setDeviceId(l)})))).every((e=>!0===e))}catch(t){throw this.options.videoCaptureDefaults.deviceId=e,t}}else if("audiooutput"===t){if(!na()&&!this.options.webAudioMix||this.options.webAudioMix&&this.audioContext&&!("setSinkId"in this.audioContext))throw new Error("cannot switch audio output, setSinkId not supported");this.options.webAudioMix&&(n=null!==(s=yield Ma.getInstance().normalizeDeviceId("audiooutput",n))&&void 0!==s?s:""),null!==(o=(r=this.options).audioOutput)&&void 0!==o||(r.audioOutput={});const e=this.options.audioOutput.deviceId;this.options.audioOutput.deviceId=n,c=e!==l;try{this.options.webAudioMix?null===(a=this.audioContext)||void 0===a||a.setSinkId(n):yield Promise.all(Array.from(this.remoteParticipants.values()).map((e=>e.setAudioOutput({deviceId:n}))))}catch(t){throw this.options.audioOutput.deviceId=e,t}}return c&&d&&(this.localParticipant.activeDeviceMap.set(t,n),this.emit(e.RoomEvent.ActiveDeviceChanged,t,n)),d}))}setupLocalParticipantEvents(){this.localParticipant.on(e.ParticipantEvent.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).on(e.ParticipantEvent.ParticipantNameChanged,this.onLocalParticipantNameChanged).on(e.ParticipantEvent.TrackMuted,this.onLocalTrackMuted).on(e.ParticipantEvent.TrackUnmuted,this.onLocalTrackUnmuted).on(e.ParticipantEvent.LocalTrackPublished,this.onLocalTrackPublished).on(e.ParticipantEvent.LocalTrackUnpublished,this.onLocalTrackUnpublished).on(e.ParticipantEvent.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).on(e.ParticipantEvent.MediaDevicesError,this.onMediaDevicesError).on(e.ParticipantEvent.AudioStreamAcquired,this.startAudio).on(e.ParticipantEvent.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged)}recreateEngine(){var e;null===(e=this.engine)||void 0===e||e.close(),this.engine=void 0,this.isResuming=!1,this.remoteParticipants.clear(),this.sidToIdentity.clear(),this.bufferedEvents=[],this.maybeCreateEngine()}onTrackAdded(t,n,i){if(this.state===e.ConnectionState.Connecting||this.state===e.ConnectionState.Reconnecting){const s=()=>{this.onTrackAdded(t,n,i),o()},o=()=>{this.off(e.RoomEvent.Reconnected,s),this.off(e.RoomEvent.Connected,s),this.off(e.RoomEvent.Disconnected,o)};return this.once(e.RoomEvent.Reconnected,s),this.once(e.RoomEvent.Connected,s),void this.once(e.RoomEvent.Disconnected,o)}if(this.state===e.ConnectionState.Disconnected)return void this.log.warn("skipping incoming track after Room disconnected",this.logContext);const s=function(e){const t=e.split("|");return t.length>1?[t[0],e.substr(t[0].length+1)]:[e,""]}(n.id),o=s[0];let a=s[1],r=t.id;if(a&&a.startsWith("TR")&&(r=a),o===this.localParticipant.sid)return void this.log.warn("tried to create RemoteParticipant for local participant",this.logContext);const c=Array.from(this.remoteParticipants.values()).find((e=>e.sid===o));if(!c)return void this.log.error("Tried to add a track for a participant, that's not present. Sid: ".concat(o),this.logContext);let d;this.options.adaptiveStream&&(d="object"==typeof this.options.adaptiveStream?this.options.adaptiveStream:{}),c.addSubscribedMediaTrack(t,r,n,i,d)}handleDisconnect(){let t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0],n=arguments.length>1?arguments[1]:void 0;var i;if(this.clearConnectionReconcile(),this.isResuming=!1,this.bufferedEvents=[],this.state!==e.ConnectionState.Disconnected){this.regionUrl=void 0;try{this.remoteParticipants.forEach((e=>{e.trackPublications.forEach((t=>{e.unpublishTrack(t.trackSid)}))})),this.localParticipant.trackPublications.forEach((e=>{var n,i;e.track&&this.localParticipant.unpublishTrack(e.track,t),t&&(null===(n=e.track)||void 0===n||n.detach(),null===(i=e.track)||void 0===i||i.stop())})),this.localParticipant.off(e.ParticipantEvent.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).off(e.ParticipantEvent.ParticipantNameChanged,this.onLocalParticipantNameChanged).off(e.ParticipantEvent.TrackMuted,this.onLocalTrackMuted).off(e.ParticipantEvent.TrackUnmuted,this.onLocalTrackUnmuted).off(e.ParticipantEvent.LocalTrackPublished,this.onLocalTrackPublished).off(e.ParticipantEvent.LocalTrackUnpublished,this.onLocalTrackUnpublished).off(e.ParticipantEvent.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).off(e.ParticipantEvent.MediaDevicesError,this.onMediaDevicesError).off(e.ParticipantEvent.AudioStreamAcquired,this.startAudio).off(e.ParticipantEvent.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged),this.localParticipant.trackPublications.clear(),this.localParticipant.videoTrackPublications.clear(),this.localParticipant.audioTrackPublications.clear(),this.remoteParticipants.clear(),this.sidToIdentity.clear(),this.activeSpeakers=[],this.audioContext&&"boolean"==typeof this.options.webAudioMix&&(this.audioContext.close(),this.audioContext=void 0),da()&&(window.removeEventListener("beforeunload",this.onPageLeave),window.removeEventListener("pagehide",this.onPageLeave),window.removeEventListener("freeze",this.onPageLeave),null===(i=navigator.mediaDevices)||void 0===i||i.removeEventListener("devicechange",this.handleDeviceChange))}finally{this.setAndEmitConnectionState(e.ConnectionState.Disconnected),this.emit(e.RoomEvent.Disconnected,n)}}}handleParticipantDisconnected(t,n){this.remoteParticipants.delete(t),n&&(n.trackPublications.forEach((e=>{n.unpublishTrack(e.trackSid,!0)})),this.emit(e.RoomEvent.ParticipantDisconnected,n))}acquireAudioContext(){var t,n;return wi(this,void 0,void 0,(function*(){if("boolean"!=typeof this.options.webAudioMix&&this.options.webAudioMix.audioContext?this.audioContext=this.options.webAudioMix.audioContext:this.audioContext&&"closed"!==this.audioContext.state||(this.audioContext=null!==(t=Go())&&void 0!==t?t:void 0),this.audioContext&&"suspended"===this.audioContext.state)try{yield this.audioContext.resume()}catch(e){this.log.warn("Could not resume audio context",Object.assign(Object.assign({},this.logContext),{error:e}))}this.options.webAudioMix&&this.remoteParticipants.forEach((e=>e.setAudioContext(this.audioContext))),this.localParticipant.setAudioContext(this.audioContext);const i="running"===(null===(n=this.audioContext)||void 0===n?void 0:n.state);i!==this.canPlaybackAudio&&(this.audioEnabled=i,this.emit(e.RoomEvent.AudioPlaybackStatusChanged,i))}))}createParticipant(e,t){var n;let i;return i=t?Xr.fromParticipantInfo(this.engine.client,t):new Xr(this.engine.client,"",e,void 0,void 0,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}),this.options.webAudioMix&&i.setAudioContext(this.audioContext),(null===(n=this.options.audioOutput)||void 0===n?void 0:n.deviceId)&&i.setAudioOutput(this.options.audioOutput).catch((e=>this.log.warn("Could not set audio output: ".concat(e.message),this.logContext))),i}getOrCreateParticipant(t,n){if(this.remoteParticipants.has(t)){const e=this.remoteParticipants.get(t);if(n){e.updateInfo(n)&&this.sidToIdentity.set(n.sid,n.identity)}return e}const i=this.createParticipant(t,n);return this.remoteParticipants.set(t,i),this.sidToIdentity.set(n.sid,n.identity),this.emitWhenConnected(e.RoomEvent.ParticipantConnected,i),i.on(e.ParticipantEvent.TrackPublished,(t=>{this.emitWhenConnected(e.RoomEvent.TrackPublished,t,i)})).on(e.ParticipantEvent.TrackSubscribed,((t,n)=>{t.kind===jo.Kind.Audio?(t.on(e.TrackEvent.AudioPlaybackStarted,this.handleAudioPlaybackStarted),t.on(e.TrackEvent.AudioPlaybackFailed,this.handleAudioPlaybackFailed)):t.kind===jo.Kind.Video&&(t.on(e.TrackEvent.VideoPlaybackFailed,this.handleVideoPlaybackFailed),t.on(e.TrackEvent.VideoPlaybackStarted,this.handleVideoPlaybackStarted)),this.emit(e.RoomEvent.TrackSubscribed,t,n,i)})).on(e.ParticipantEvent.TrackUnpublished,(t=>{this.emit(e.RoomEvent.TrackUnpublished,t,i)})).on(e.ParticipantEvent.TrackUnsubscribed,((t,n)=>{this.emit(e.RoomEvent.TrackUnsubscribed,t,n,i)})).on(e.ParticipantEvent.TrackSubscriptionFailed,(t=>{this.emit(e.RoomEvent.TrackSubscriptionFailed,t,i)})).on(e.ParticipantEvent.TrackMuted,(t=>{this.emitWhenConnected(e.RoomEvent.TrackMuted,t,i)})).on(e.ParticipantEvent.TrackUnmuted,(t=>{this.emitWhenConnected(e.RoomEvent.TrackUnmuted,t,i)})).on(e.ParticipantEvent.ParticipantMetadataChanged,(t=>{this.emitWhenConnected(e.RoomEvent.ParticipantMetadataChanged,t,i)})).on(e.ParticipantEvent.ParticipantNameChanged,(t=>{this.emitWhenConnected(e.RoomEvent.ParticipantNameChanged,t,i)})).on(e.ParticipantEvent.ConnectionQualityChanged,(t=>{this.emitWhenConnected(e.RoomEvent.ConnectionQualityChanged,t,i)})).on(e.ParticipantEvent.ParticipantPermissionsChanged,(t=>{this.emitWhenConnected(e.RoomEvent.ParticipantPermissionsChanged,t,i)})).on(e.ParticipantEvent.TrackSubscriptionStatusChanged,((t,n)=>{this.emitWhenConnected(e.RoomEvent.TrackSubscriptionStatusChanged,t,n,i)})).on(e.ParticipantEvent.TrackSubscriptionFailed,((t,n)=>{this.emit(e.RoomEvent.TrackSubscriptionFailed,t,i,n)})).on(e.ParticipantEvent.TrackSubscriptionPermissionChanged,((t,n)=>{this.emitWhenConnected(e.RoomEvent.TrackSubscriptionPermissionChanged,t,n,i)})),n&&i.updateInfo(n),i}sendSyncState(){const e=Array.from(this.remoteParticipants.values()).reduce(((e,t)=>(e.push(...t.getTrackPublications()),e)),[]),t=this.localParticipant.getTrackPublications();this.engine.sendSyncState(e,t)}updateSubscriptions(){for(const e of this.remoteParticipants.values())for(const t of e.videoTrackPublications.values())t.isSubscribed&&t instanceof Yr&&t.emitTrackUpdate()}getRemoteParticipantBySid(e){const t=this.sidToIdentity.get(e);if(t)return this.remoteParticipants.get(t)}registerConnectionReconcile(){this.clearConnectionReconcile();let e=0;this.connectionReconcileInterval=_o.setInterval((()=>{this.engine&&!this.engine.isClosed&&this.engine.verifyTransport()?e=0:(e++,this.log.warn("detected connection state mismatch",Object.assign(Object.assign({},this.logContext),{numFailures:e,engine:{closed:this.engine.isClosed,transportsConnected:this.engine.verifyTransport()}})),e>=3&&(this.recreateEngine(),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,qe.STATE_MISMATCH)))}),2e3)}clearConnectionReconcile(){this.connectionReconcileInterval&&_o.clearInterval(this.connectionReconcileInterval)}setAndEmitConnectionState(t){return t!==this.state&&(this.state=t,this.emit(e.RoomEvent.ConnectionStateChanged,this.state),!0)}emitBufferedEvents(){this.bufferedEvents.forEach((e=>{let[t,n]=e;this.emit(t,...n)})),this.bufferedEvents=[]}emitWhenConnected(t){for(var n=arguments.length,i=new Array(n>1?n-1:0),s=1;s<n;s++)i[s-1]=arguments[s];if(this.state===e.ConnectionState.Reconnecting||this.isResuming||!this.engine||this.engine.pendingReconnect)this.bufferedEvents.push([t,i]);else if(this.state===e.ConnectionState.Connected)return this.emit(t,...i);return!1}simulateParticipants(t){var n,i;return wi(this,void 0,void 0,(function*(){const s=Object.assign({audio:!0,video:!0,useRealTracks:!1},t.publish),o=Object.assign({count:9,audio:!1,video:!0,aspectRatios:[1.66,1.7,1.3]},t.participants);if(this.handleDisconnect(),this.roomInfo=new We({sid:"RM_SIMULATED",name:"simulated-room",emptyTimeout:0,maxParticipants:0,creationTime:O.parse((new Date).getTime()),metadata:"",numParticipants:1,numPublishers:1,turnPassword:"",enabledCodecs:[],activeRecording:!1}),this.localParticipant.updateInfo(new ze({identity:"simulated-local",name:"local-name"})),this.setupLocalParticipantEvents(),this.emit(e.RoomEvent.SignalConnected),this.emit(e.RoomEvent.Connected),this.setAndEmitConnectionState(e.ConnectionState.Connected),s.video){const t=new Jr(jo.Kind.Video,new $e({source:je.CAMERA,sid:Math.floor(1e4*Math.random()).toString(),type:Ue.AUDIO,name:"video-dummy"}),new Ur(s.useRealTracks?(yield window.navigator.mediaDevices.getUserMedia({video:!0})).getVideoTracks()[0]:Ea(160*(null!==(n=o.aspectRatios[0])&&void 0!==n?n:1),160,!0,!0),void 0,!1,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(t),this.localParticipant.emit(e.ParticipantEvent.LocalTrackPublished,t)}if(s.audio){const t=new Jr(jo.Kind.Audio,new $e({source:je.MICROPHONE,sid:Math.floor(1e4*Math.random()).toString(),type:Ue.AUDIO}),new Sr(s.useRealTracks?(yield navigator.mediaDevices.getUserMedia({audio:!0})).getAudioTracks()[0]:wa(),void 0,!1,this.audioContext,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(t),this.localParticipant.emit(e.ParticipantEvent.LocalTrackPublished,t)}for(let e=0;e<o.count-1;e+=1){let t=new ze({sid:Math.floor(1e4*Math.random()).toString(),identity:"simulated-".concat(e),state:Qe.ACTIVE,tracks:[],joinedAt:O.parse(Date.now())});const n=this.getOrCreateParticipant(t.identity,t);if(o.video){const s=Ea(160*(null!==(i=o.aspectRatios[e%o.aspectRatios.length])&&void 0!==i?i:1),160,!1,!0),a=new $e({source:je.CAMERA,sid:Math.floor(1e4*Math.random()).toString(),type:Ue.AUDIO});n.addSubscribedMediaTrack(s,a.sid,new MediaStream([s])),t.tracks=[...t.tracks,a]}if(o.audio){const e=wa(),i=new $e({source:je.MICROPHONE,sid:Math.floor(1e4*Math.random()).toString(),type:Ue.AUDIO});n.addSubscribedMediaTrack(e,i.sid,new MediaStream([e])),t.tracks=[...t.tracks,i]}n.updateInfo(t)}}))}emit(t){for(var n=arguments.length,i=new Array(n>1?n-1:0),s=1;s<n;s++)i[s-1]=arguments[s];if(t!==e.RoomEvent.ActiveSpeakersChanged){const e=ec(i).filter((e=>void 0!==e));this.log.debug("room event ".concat(t),Object.assign(Object.assign({},this.logContext),{event:t,args:e}))}return super.emit(t,...i)}}function ec(e){return e.map((e=>{if(e)return Array.isArray(e)?ec(e):"object"==typeof e?"logContext"in e&&e.logContext:e}))}var tc;!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"}(tc||(tc={}));class nc extends Gi.EventEmitter{constructor(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};super(),this.status=tc.IDLE,this.logs=[],this.errorsAsWarnings=!1,this.url=e,this.token=t,this.name=this.constructor.name,this.room=new $r(n.roomOptions),this.connectOptions=n.connectOptions,n.errorsAsWarnings&&(this.errorsAsWarnings=n.errorsAsWarnings)}run(e){return wi(this,void 0,void 0,(function*(){if(this.status!==tc.IDLE)throw Error("check is running already");this.setStatus(tc.RUNNING);try{yield this.perform()}catch(e){e instanceof Error&&(this.errorsAsWarnings?this.appendWarning(e.message):this.appendError(e.message))}return yield this.disconnect(),yield new Promise((e=>setTimeout(e,500))),this.status!==tc.SKIPPED&&this.setStatus(this.isSuccess()?tc.SUCCESS:tc.FAILED),e&&e(),this.getInfo()}))}isSuccess(){return!this.logs.some((e=>"error"===e.level))}connect(){return wi(this,void 0,void 0,(function*(){return this.room.state===e.ConnectionState.Connected||(yield this.room.connect(this.url,this.token)),this.room}))}disconnect(){return wi(this,void 0,void 0,(function*(){this.room&&this.room.state!==e.ConnectionState.Disconnected&&(yield this.room.disconnect(),yield new Promise((e=>setTimeout(e,500))))}))}skip(){this.setStatus(tc.SKIPPED)}appendMessage(e){this.logs.push({level:"info",message:e}),this.emit("update",this.getInfo())}appendWarning(e){this.logs.push({level:"warning",message:e}),this.emit("update",this.getInfo())}appendError(e){this.logs.push({level:"error",message:e}),this.emit("update",this.getInfo())}setStatus(e){this.status=e,this.emit("update",this.getInfo())}get engine(){var e;return null===(e=this.room)||void 0===e?void 0:e.engine}getInfo(){return{logs:this.logs,name:this.name,status:this.status,description:this.description}}}function ic(e){var t,n;return wi(this,void 0,void 0,(function*(){null!=e||(e={}),null!==(t=e.audio)&&void 0!==t||(e.audio=!0),null!==(n=e.video)&&void 0!==n||(e.video=!0);const i=Ko(Vo(e,cr,dr)),s=navigator.mediaDevices.getUserMedia(i);e.audio&&(Ma.userMediaPromiseMap.set("audioinput",s),s.catch((()=>Ma.userMediaPromiseMap.delete("audioinput")))),e.video&&(Ma.userMediaPromiseMap.set("videoinput",s),s.catch((()=>Ma.userMediaPromiseMap.delete("videoinput"))));const o=yield s;return o.getTracks().map((t=>{const n="audio"===t.kind;let s;n?e.audio:e.video;const a=n?i.audio:i.video;"boolean"!=typeof a&&(s=a),s?s.deviceId=t.getSettings().deviceId:s={deviceId:t.getSettings().deviceId};const r=Er(t,s);return r.kind===jo.Kind.Video?r.source=jo.Source.Camera:r.kind===jo.Kind.Audio&&(r.source=jo.Source.Microphone),r.mediaStream=o,r}))}))}function sc(e){return wi(this,void 0,void 0,(function*(){return(yield ic({audio:!1,video:e}))[0]}))}function oc(e){return wi(this,void 0,void 0,(function*(){return(yield ic({audio:e,video:!1}))[0]}))}class ac extends nc{get description(){return"Can publish audio"}perform(){var e;return wi(this,void 0,void 0,(function*(){const t=yield this.connect(),n=yield oc();t.localParticipant.publishTrack(n),yield new Promise((e=>setTimeout(e,3e3)));const i=yield null===(e=n.sender)||void 0===e?void 0:e.getStats();if(!i)throw new Error("Could not get RTCStats");let s=0;if(i.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 rc extends nc{get description(){return"Can publish video"}perform(){var e;return wi(this,void 0,void 0,(function*(){const t=yield this.connect(),n=yield sc();t.localParticipant.publishTrack(n),yield new Promise((e=>setTimeout(e,3e3)));const i=yield null===(e=n.sender)||void 0===e?void 0:e.getStats();if(!i)throw new Error("Could not get RTCStats");let s=0;if(i.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 cc extends nc{get description(){return"Resuming connection after interruption"}perform(){var t;return wi(this,void 0,void 0,(function*(){const n=yield this.connect();let i,s=!1,o=!1;const a=new Promise((e=>{setTimeout(e,5e3),i=e}));n.on(e.RoomEvent.Reconnecting,(()=>{s=!0})).on(e.RoomEvent.Reconnected,(()=>{o=!0,i(!0)})),null===(t=n.engine.client.ws)||void 0===t||t.close();const r=n.engine.client.onClose;if(r&&r(""),yield a,!s)throw new Error("Did not attempt to reconnect");if(!o||n.state!==e.ConnectionState.Connected)throw this.appendWarning("reconnection is only possible in Redis-based configurations"),new Error("Not able to reconnect")}))}}class dc extends nc{get description(){return"Can connect via TURN"}perform(){var e,t;return wi(this,void 0,void 0,(function*(){const n=new ja,i=yield n.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3});let s=!1,o=!1,a=!1;for(let e of i.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."),yield n.close(),(null===(t=null===(e=this.connectOptions)||void 0===e?void 0:e.rtcConfig)||void 0===t?void 0:t.iceServers)||o?yield this.room.connect(this.url,this.token,{rtcConfig:{iceTransportPolicy:"relay"}}):(this.appendWarning("No TURN servers configured."),this.skip(),yield new Promise((e=>setTimeout(e,0))))}))}}class lc extends nc{get description(){return"Establishing WebRTC connection"}perform(){return wi(this,void 0,void 0,(function*(){let t=!1,n=!1;this.room.on(e.RoomEvent.SignalConnected,(()=>{const e=this.room.engine.client.onTrickle;this.room.engine.client.onTrickle=(i,s)=>{if(i.candidate){const e=new RTCIceCandidate(i);let s="".concat(e.protocol," ").concat(e.address,":").concat(e.port," ").concat(e.type);e.address&&(!function(e){const t=e.split(".");if(4===t.length){if("10"===t[0])return!0;if("192"===t[0]&&"168"===t[1])return!0;if("172"===t[0]){const e=parseInt(t[1],10);if(e>=16&&e<=31)return!0}}return!1}(e.address)?"tcp"===e.protocol&&"passive"===e.tcpType?(t=!0,s+=" (passive)"):"udp"===e.protocol&&(n=!0):s+=" (private)"),this.appendMessage(s)}e&&e(i,s)},this.room.engine.pcManager&&(this.room.engine.pcManager.subscriber.onIceCandidateError=e=>{e instanceof RTCPeerConnectionIceErrorEvent&&this.appendWarning("error with ICE candidate: ".concat(e.errorCode," ").concat(e.errorText," ").concat(e.url))})}));try{yield this.connect(),ki.info("now the room is connected")}catch(e){throw this.appendWarning("ports need to be open on firewall in order to connect."),e}t||this.appendWarning("Server is not configured for ICE/TCP"),n||this.appendWarning("No public IPv4 UDP candidates were found. Your server is likely not configured correctly")}))}}class uc extends nc{get description(){return"Connecting to signal connection via WebSocket"}perform(){var e,t,n;return wi(this,void 0,void 0,(function*(){(this.url.startsWith("ws:")||this.url.startsWith("http:"))&&this.appendWarning("Server is insecure, clients may block connections to it");let i=new ja;const s=yield i.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3});this.appendMessage("Connected to server, version ".concat(s.serverVersion,".")),(null===(e=s.serverInfo)||void 0===e?void 0:e.edition)===dt.Cloud&&(null===(t=s.serverInfo)||void 0===t?void 0:t.region)&&this.appendMessage("LiveKit Cloud: ".concat(null===(n=s.serverInfo)||void 0===n?void 0:n.region)),yield i.close()}))}}class hc extends Gi.EventEmitter{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:tc.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!==tc.FAILED))}getResults(){return Array.from(this.checkResults.values())}createAndRunCheck(e){return wi(this,void 0,void 0,(function*(){const t=this.getNextCheckId(),n=new e(this.url,this.token),i=e=>{this.updateCheck(t,e)};n.on("update",i);const s=yield n.run();return n.off("update",i),s}))}checkWebsocket(){return wi(this,void 0,void 0,(function*(){return this.createAndRunCheck(uc)}))}checkWebRTC(){return wi(this,void 0,void 0,(function*(){return this.createAndRunCheck(lc)}))}checkTURN(){return wi(this,void 0,void 0,(function*(){return this.createAndRunCheck(dc)}))}checkReconnect(){return wi(this,void 0,void 0,(function*(){return this.createAndRunCheck(cc)}))}checkPublishAudio(){return wi(this,void 0,void 0,(function*(){return this.createAndRunCheck(ac)}))}checkPublishVideo(){return wi(this,void 0,void 0,(function*(){return this.createAndRunCheck(rc)}))}}const mc=new Map([["obs virtual camera",{facingMode:"environment",confidence:"medium"}]]),pc=new Map([["iphone",{facingMode:"environment",confidence:"medium"}],["ipad",{facingMode:"environment",confidence:"medium"}]]);function gc(e){var t;const n=e.trim().toLowerCase();if(""!==n)return mc.has(n)?mc.get(n):null===(t=Array.from(pc.entries()).find((e=>{let[t]=e;return n.includes(t)})))||void 0===t?void 0:t[1]}e.BaseKeyProvider=ro,e.ConnectionCheck=hc,e.ConnectionError=lo,e.CriticalTimers=_o,e.DataPacket_Kind=nt,e.DefaultReconnectPolicy=Ei,e.DeviceUnsupportedError=uo,e.DisconnectReason=qe,e.ExternalE2EEKeyProvider=class extends ro{constructor(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};super(Object.assign(Object.assign({},e),{sharedKey:!0,ratchetWindowSize:0,failureTolerance:-1}))}setKey(e){return wi(this,void 0,void 0,(function*(){const t="string"==typeof e?yield so(e):yield oo(e);this.onSetEncryptionKey(t)}))}},e.LivekitError=co,e.LocalAudioTrack=Sr,e.LocalParticipant=Qr,e.LocalTrack=xa,e.LocalTrackPublication=Jr,e.LocalVideoTrack=Ur,e.NegotiationError=go,e.Participant=zr,e.PublishDataError=class extends co{constructor(e){super(13,null!=e?e:"unable to publish data")}},e.RemoteAudioTrack=qr,e.RemoteParticipant=Xr,e.RemoteTrack=Vr,e.RemoteTrackPublication=Yr,e.RemoteVideoTrack=Kr,e.Room=$r,e.ScreenSharePresets=Ao,e.SubscriptionError=Ge,e.Track=jo,e.TrackInvalidError=ho,e.TrackPublication=Hr,e.UnexpectedConnectionState=po,e.UnsupportedServer=mo,e.VideoPreset=Io,e.VideoPresets=No,e.VideoPresets43=Lo,e.attachToElement=Fo,e.createAudioAnalyser=function(e,t){const n=Object.assign({cloneTrack:!1,fftSize:2048,smoothingTimeConstant:.8,minDecibels:-100,maxDecibels:-80},t),i=Go();if(!i)throw new Error("Audio Context not supported on this browser");const s=n.cloneTrack?e.mediaStreamTrack.clone():e.mediaStreamTrack,o=i.createMediaStreamSource(new MediaStream([s])),a=i.createAnalyser();a.minDecibels=n.minDecibels,a.maxDecibels=n.maxDecibels,a.fftSize=n.fftSize,a.smoothingTimeConstant=n.smoothingTimeConstant,o.connect(a);const r=new Uint8Array(a.frequencyBinCount);return{calculateVolume:()=>{a.getByteFrequencyData(r);let e=0;for(const t of r)e+=Math.pow(t/255,2);return Math.sqrt(e/r.length)},analyser:a,cleanup:()=>wi(this,void 0,void 0,(function*(){yield i.close(),n.cloneTrack&&s.stop()}))}},e.createE2EEKey=function(){return window.crypto.getRandomValues(new Uint8Array(32))},e.createKeyMaterialFromBuffer=oo,e.createKeyMaterialFromString=so,e.createLocalAudioTrack=oc,e.createLocalScreenTracks=function(e){return wi(this,void 0,void 0,(function*(){if(void 0===e&&(e={}),void 0!==e.resolution||ra()||(e.resolution=Ao.h1080fps30.resolution),void 0===navigator.mediaDevices.getDisplayMedia)throw new uo("getDisplayMedia not supported");const t=Wo(e),n=yield navigator.mediaDevices.getDisplayMedia(t),i=n.getVideoTracks();if(0===i.length)throw new ho("no video track found");const s=new Ur(i[0],void 0,!1);s.source=jo.Source.ScreenShare;const o=[s];if(n.getAudioTracks().length>0){const e=new Sr(n.getAudioTracks()[0],void 0,!1);e.source=jo.Source.ScreenShareAudio,o.push(e)}return o}))},e.createLocalTracks=ic,e.createLocalVideoTrack=sc,e.deriveKeys=function(e,t){return wi(this,void 0,void 0,(function*(){const n=ao(e.algorithm.name,t),i=yield crypto.subtle.deriveKey(n,e,{name:Ys,length:128},!1,["encrypt","decrypt"]);return{material:e,encryptionKey:i}}))},e.detachTrack=Bo,e.facingModeFromDeviceLabel=gc,e.facingModeFromLocalTrack=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};var n;const i=e instanceof xa?e.mediaStreamTrack:e,s=i.getSettings();let o={facingMode:null!==(n=t.defaultFacingMode)&&void 0!==n?n:"user",confidence:"low"};if("facingMode"in s){const e=s.facingMode;ki.trace("rawFacingMode",{rawFacingMode:e}),e&&"string"==typeof e&&function(e){const t=["user","environment","left","right"];return void 0===e||t.includes(e)}(e)&&(o={facingMode:e,confidence:"high"})}if(["low","medium"].includes(o.confidence)){ki.trace("Try to get facing mode from device label: (".concat(i.label,")"));const e=gc(i.label);void 0!==e&&(o=e)}return o},e.getBrowser=Eo,e.getEmptyAudioStreamTrack=wa,e.getEmptyVideoStreamTrack=function(){return Ca||(Ca=Ea()),Ca.clone()},e.getLogger=yi,e.importKey=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{name:Ys},n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"encrypt";return wi(this,void 0,void 0,(function*(){return crypto.subtle.importKey("raw",e,t,!1,"derive"===n?["deriveBits","deriveKey"]:["encrypt","decrypt"])}))},e.isBackupCodec=xo,e.isBrowserSupported=sa,e.isE2EESupported=to,e.isInsertableStreamSupported=io,e.isScriptTransformSupported=no,e.isVideoFrame=function(e){return"type"in e},e.needsRbspUnescaping=function(e){for(var t=0;t<e.length-3;t++)if(0==e[t]&&0==e[t+1]&&3==e[t+2])return!0;return!1},e.parseRbsp=function(e){const t=[];for(var n=e.length,i=0;i<e.length;)n-i>=3&&!e[i]&&!e[i+1]&&3==e[i+2]?(t.push(e[i++]),t.push(e[i++]),i++):t.push(e[i++]);return new Uint8Array(t)},e.protocolVersion=12,e.ratchet=function(e,t){return wi(this,void 0,void 0,(function*(){const n=ao(e.algorithm.name,t);return crypto.subtle.deriveBits(n,e,256)}))},e.setLogExtension=function(t,n){(n?[n]:Ti).forEach((n=>{const i=n.methodFactory;n.methodFactory=(n,s,o)=>{const a=i(n,s,o),r=e.LogLevel[n],c=r>=s&&r<e.LogLevel.silent;return(e,n)=>{n?a(e,n):a(e),c&&t(r,e,n)}},n.setLevel(n.getLevel())}))},e.setLogLevel=function(e,t){t&&vi.getLogger(t).setLevel(e);for(const t of Ti)t.setLevel(e)},e.supportsAV1=$o,e.supportsAdaptiveStream=function(){return void 0!==typeof ResizeObserver&&void 0!==typeof IntersectionObserver},e.supportsDynacast=function(){return Xo()},e.supportsVP9=ea,e.version=Ro,e.videoCodecs=Mo,e.writeRbsp=function(e){const t=[];for(var n=0,i=0;i<e.length;++i){var s=e[i];s<=3&&n>=2&&(t.push(3),n=0),t.push(s),0==s?++n:n=0}return new Uint8Array(t)}}));
|
2
2
|
//# sourceMappingURL=livekit-client.umd.js.map
|