livekit-client 2.5.1 → 2.5.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- 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 +4 -2
- package/dist/livekit-client.e2ee.worker.mjs.map +1 -1
- package/dist/livekit-client.esm.mjs +250 -199
- 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/room/PCTransportManager.d.ts +1 -0
- package/dist/src/room/PCTransportManager.d.ts.map +1 -1
- package/dist/src/room/Room.d.ts +3 -3
- 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/track/LocalTrack.d.ts +1 -1
- package/dist/src/room/track/LocalTrack.d.ts.map +1 -1
- package/dist/src/room/track/create.d.ts +7 -0
- package/dist/src/room/track/create.d.ts.map +1 -1
- package/dist/ts4.2/src/room/PCTransportManager.d.ts +1 -0
- package/dist/ts4.2/src/room/Room.d.ts +3 -3
- package/dist/ts4.2/src/room/track/LocalTrack.d.ts +1 -1
- package/dist/ts4.2/src/room/track/create.d.ts +7 -0
- package/package.json +8 -8
- package/src/connectionHelper/checks/Checker.ts +1 -1
- package/src/e2ee/worker/FrameCryptor.ts +3 -1
- package/src/room/PCTransportManager.ts +12 -4
- package/src/room/Room.ts +41 -6
- package/src/room/participant/LocalParticipant.ts +14 -8
- package/src/room/track/LocalTrack.ts +4 -2
- package/src/room/track/create.ts +27 -8
@@ -1,2 +1,2 @@
|
|
1
|
-
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).LivekitClient={})}(this,(function(e){"use strict";function t(e,t){return t.forEach((function(t){t&&"string"!=typeof t&&!Array.isArray(t)&&Object.keys(t).forEach((function(i){if("default"!==i&&!(i in e)){var n=Object.getOwnPropertyDescriptor(t,i);Object.defineProperty(e,i,n.get?n:{enumerable:!0,get:function(){return t[i]}})}}))})),Object.freeze(e)}function i(e,t){if(!e)throw new Error(t)}const n=34028234663852886e22,s=-34028234663852886e22,r=4294967295,o=2147483647,a=-2147483648;function c(e){if("number"!=typeof e)throw new Error("invalid int 32: "+typeof e);if(!Number.isInteger(e)||e>o||e<a)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>r||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>n||e<s))throw new Error("invalid float 32: "+e)}const u=Symbol("@bufbuild/protobuf/enum-type");function h(e){const t=e[u];return i(t,"missing enum type on enum object"),t}function p(e,t,i,n){e[u]=m(t,i.map((t=>({no:t.no,name:t.name,localName:e[t.no]}))))}function m(e,t,i){const n=Object.create(null),s=Object.create(null),r=[];for(const e of t){const t=f(e);r.push(t),n[e.name]=t,s[e.no]=t}return{typeName:e,values:r,findName:e=>n[e],findNumber:e=>s[e]}}function g(e,t,i){const n={};for(const e of t){const t=f(e);n[t.localName]=t.no,n[t.no]=t.localName}return p(n,e,t),n}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 i=this.getType().runtime.bin,n=i.makeReadOptions(t);return i.readMessage(this,n.readerFactory(e),e.byteLength,n),this}fromJson(e,t){const i=this.getType(),n=i.runtime.json,s=n.makeReadOptions(t);return n.readMessage(i,e,s,this),this}fromJsonString(e,t){let i;try{i=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(i,t)}toBinary(e){const t=this.getType().runtime.bin,i=t.makeWriteOptions(e),n=i.writerFactory();return t.writeMessage(this,n,i),n.finish()}toJson(e){const t=this.getType().runtime.json,i=t.makeWriteOptions(e);return t.writeMessage(this,i)}toJsonString(e){var t;const i=this.toJson(e);return JSON.stringify(i,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}}function k(){let e=0,t=0;for(let i=0;i<28;i+=7){let n=this.buf[this.pos++];if(e|=(127&n)<<i,0==(128&n))return this.assertBounds(),[e,t]}let i=this.buf[this.pos++];if(e|=(15&i)<<28,t=(112&i)>>4,0==(128&i))return this.assertBounds(),[e,t];for(let i=3;i<=31;i+=7){let n=this.buf[this.pos++];if(t|=(127&n)<<i,0==(128&n))return this.assertBounds(),[e,t]}throw new Error("invalid varint")}function b(e,t,i){for(let n=0;n<28;n+=7){const s=e>>>n,r=!(s>>>7==0&&0==t),o=255&(r?128|s:s);if(i.push(o),!r)return}const n=e>>>28&15|(7&t)<<4,s=!(t>>3==0);if(i.push(255&(s?128|n:n)),s){for(let e=3;e<31;e+=7){const n=t>>>e,s=!(n>>>7==0),r=255&(s?128|n:n);if(i.push(r),!s)return}i.push(t>>>31&1)}}const y=4294967296;function T(e){const t="-"===e[0];t&&(e=e.slice(1));const i=1e6;let n=0,s=0;function r(t,r){const o=Number(e.slice(t,r));s*=i,n=n*i+o,n>=y&&(s+=n/y|0,n%=y)}return r(-24,-18),r(-18,-12),r(-12,-6),r(-6),t?E(n,s):S(n,s)}function C(e,t){if(({lo:e,hi:t}=function(e,t){return{lo:e>>>0,hi:t>>>0}}(e,t)),t<=2097151)return String(y*t+e);const i=16777215&(e>>>24|t<<8),n=t>>16&65535;let s=(16777215&e)+6777216*i+6710656*n,r=i+8147497*n,o=2*n;const a=1e7;return s>=a&&(r+=Math.floor(s/a),s%=a),r>=a&&(o+=Math.floor(r/a),r%=a),o.toString()+w(r)+w(s)}function S(e,t){return{lo:0|e,hi:0|t}}function E(e,t){return t=~t,e?e=1+~e:t+=1,S(e,t)}const w=e=>{const t=String(e);return"0000000".slice(t.length)+t};function P(e,t){if(e>=0){for(;e>127;)t.push(127&e|128),e>>>=7;t.push(e)}else{for(let i=0;i<9;i++)t.push(127&e|128),e>>=7;t.push(1)}}function R(){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 I=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"),i=BigInt("9223372036854775807"),n=BigInt("0"),s=BigInt("18446744073709551615");return{zero:BigInt(0),supported:!0,parse(e){const n="bigint"==typeof e?e:BigInt(e);if(n>i||n<t)throw new Error("int64 invalid: ".concat(e));return n},uParse(e){const t="bigint"==typeof e?e:BigInt(e);if(t>s||t<n)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,i)=>(e.setInt32(0,t,!0),e.setInt32(4,i,!0),e.getBigInt64(0,!0)),uDec:(t,i)=>(e.setInt32(0,t,!0),e.setInt32(4,i,!0),e.getBigUint64(0,!0))}}const t=e=>i(/^-?[0-9]+$/.test(e),"int64 invalid: ".concat(e)),n=e=>i(/^[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()),n(e),e),enc:e=>("string"!=typeof e&&(e=e.toString()),t(e),T(e)),uEnc:e=>("string"!=typeof e&&(e=e.toString()),n(e),T(e)),dec:(e,t)=>function(e,t){let i=S(e,t);const n=2147483648&i.hi;n&&(i=E(i.lo,i.hi));const s=C(i.lo,i.hi);return n?"-"+s:s}(e,t),uDec:(e,t)=>C(e,t)}}();var O,x,D;function M(e,t,i){if(t===i)return!0;if(e==O.BYTES){if(!(t instanceof Uint8Array&&i instanceof Uint8Array))return!1;if(t.length!==i.length)return!1;for(let e=0;e<t.length;e++)if(t[e]!==i[e])return!1;return!0}switch(e){case O.UINT64:case O.FIXED64:case O.INT64:case O.SFIXED64:case O.SINT64:return t==i}return!1}function N(e,t){switch(e){case O.BOOL:return!1;case O.UINT64:case O.FIXED64:case O.INT64:case O.SFIXED64:case O.SINT64:return 0==t?I.zero:"0";case O.DOUBLE:case O.FLOAT:return 0;case O.BYTES:return new Uint8Array(0);case O.STRING:return"";default:return 0}}function _(e,t){switch(e){case O.BOOL:return!1===t;case O.STRING:return""===t;case O.BYTES:return t instanceof Uint8Array&&!t.byteLength;default:return 0==t}}!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"}(O||(O={})),function(e){e[e.BIGINT=0]="BIGINT",e[e.STRING=1]="STRING"}(x||(x={})),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"}(D||(D={}));class A{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),i=0;for(let e=0;e<this.chunks.length;e++)t.set(this.chunks[e],i),i+=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),P(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),P(e=(e<<1^e>>31)>>>0,this.buf),this}sfixed64(e){let t=new Uint8Array(8),i=new DataView(t.buffer),n=I.enc(e);return i.setInt32(0,n.lo,!0),i.setInt32(4,n.hi,!0),this.raw(t)}fixed64(e){let t=new Uint8Array(8),i=new DataView(t.buffer),n=I.uEnc(e);return i.setInt32(0,n.lo,!0),i.setInt32(4,n.hi,!0),this.raw(t)}int64(e){let t=I.enc(e);return b(t.lo,t.hi,this.buf),this}sint64(e){let t=I.enc(e),i=t.hi>>31;return b(t.lo<<1^i,(t.hi<<1|t.lo>>>31)^i,this.buf),this}uint64(e){let t=I.uEnc(e);return b(t.lo,t.hi,this.buf),this}}class L{constructor(e,t){this.varint64=k,this.uint32=R,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,i=7&e;if(t<=0||i<0||i>5)throw new Error("illegal tag: field no "+t+" wire type "+i);return[t,i]}skip(e,t){let i=this.pos;switch(e){case D.Varint:for(;128&this.buf[this.pos++];);break;case D.Bit64:this.pos+=4;case D.Bit32:this.pos+=4;break;case D.LengthDelimited:let i=this.uint32();this.pos+=i;break;case D.StartGroup:for(;;){const[e,i]=this.tag();if(i===D.EndGroup){if(void 0!==t&&e!==t)throw new Error("invalid end group tag");break}this.skip(i,e)}break;default:throw new Error("cant skip wire type "+e)}return this.assertBounds(),this.buf.subarray(i,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 I.dec(...this.varint64())}uint64(){return I.uDec(...this.varint64())}sint64(){let[e,t]=this.varint64(),i=-(1&e);return e=(e>>>1|(1&t)<<31)^i,t=t>>>1^i,I.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 I.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return I.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 U(e){const t=e.field.localName,i=Object.create(null);return i[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 N(t.T,t.L);case"message":const e=t.T,i=new e;return e.fieldWrapper?e.fieldWrapper.unwrapField(i):i;case"map":throw"map fields are not allowed to be extensions"}}(e),[i,()=>i[t]]}let j="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),F=[];for(let e=0;e<j.length;e++)F[j[e].charCodeAt(0)]=e;F["-".charCodeAt(0)]=j.indexOf("+"),F["_".charCodeAt(0)]=j.indexOf("/");const B={dec(e){let t=3*e.length/4;"="==e[e.length-2]?t-=2:"="==e[e.length-1]&&(t-=1);let i,n=new Uint8Array(t),s=0,r=0,o=0;for(let t=0;t<e.length;t++){if(i=F[e.charCodeAt(t)],void 0===i)switch(e[t]){case"=":r=0;case"\n":case"\r":case"\t":case" ":continue;default:throw Error("invalid base64 string.")}switch(r){case 0:o=i,r=1;break;case 1:n[s++]=o<<2|(48&i)>>4,o=i,r=2;break;case 2:n[s++]=(15&o)<<4|(60&i)>>2,o=i,r=3;break;case 3:n[s++]=(3&o)<<6|i,r=0}}if(1==r)throw Error("invalid base64 string.");return n.subarray(0,s)},enc(e){let t,i="",n=0,s=0;for(let r=0;r<e.length;r++)switch(t=e[r],n){case 0:i+=j[t>>2],s=(3&t)<<4,n=1;break;case 1:i+=j[s|t>>4],s=(15&t)<<2,n=2;break;case 2:i+=j[s|t>>6],i+=j[63&t],n=0}return n&&(i+=j[s],i+="=",1==n&&(i+="=")),i}};function V(e,t,i){W(t,e);const n=t.runtime.bin.makeReadOptions(i),s=function(e,t){if(!t.repeated&&("enum"==t.kind||"scalar"==t.kind)){for(let i=e.length-1;i>=0;--i)if(e[i].no==t.no)return[e[i]];return[]}return e.filter((e=>e.no===t.no))}(e.getType().runtime.bin.listUnknownFields(e),t.field),[r,o]=U(t);for(const e of s)t.runtime.bin.readField(r,n.readerFactory(e.data),t.field,e.wireType,n);return o()}function q(e,t,i,n){W(t,e);const s=t.runtime.bin.makeReadOptions(n),r=t.runtime.bin.makeWriteOptions(n);if(K(e,t)){const i=e.getType().runtime.bin.listUnknownFields(e).filter((e=>e.no!=t.field.no));e.getType().runtime.bin.discardUnknownFields(e);for(const t of i)e.getType().runtime.bin.onUnknownField(e,t.no,t.wireType,t.data)}const o=r.writerFactory();let a=t.field;a.opt||a.repeated||"enum"!=a.kind&&"scalar"!=a.kind||(a=Object.assign(Object.assign({},t.field),{opt:!0})),t.runtime.bin.writeField(a,i,o,r);const c=s.readerFactory(o.finish());for(;c.pos<c.len;){const[t,i]=c.tag(),n=c.skip(i,t);e.getType().runtime.bin.onUnknownField(e,t,i,n)}}function K(e,t){const i=e.getType();return t.extendee.typeName===i.typeName&&!!i.runtime.bin.listUnknownFields(e).find((e=>e.no==t.field.no))}function W(e,t){i(e.extendee.typeName==t.getType().typeName,"extension ".concat(e.typeName," can only be applied to message ").concat(e.extendee.typeName))}function G(e,t){const i=e.localName;if(e.repeated)return t[i].length>0;if(e.oneof)return t[e.oneof.localName].case===i;switch(e.kind){case"enum":case"scalar":return e.opt||e.req?void 0!==t[i]:"enum"==e.kind?t[i]!==e.T.values[0].no:!_(e.T,t[i]);case"message":return void 0!==t[i];case"map":return Object.keys(t[i]).length>0}}function H(e,t){const i=e.localName,n=!e.opt&&!e.req;if(e.repeated)t[i]=[];else if(e.oneof)t[e.oneof.localName]={case:void 0};else switch(e.kind){case"map":t[i]={};break;case"enum":t[i]=n?e.T.values[0].no:void 0;break;case"scalar":t[i]=n?N(e.T,e.L):void 0;break;case"message":t[i]=void 0}}function J(e,t){if(null===e||"object"!=typeof e)return!1;if(!Object.getOwnPropertyNames(v.prototype).every((t=>t in e&&"function"==typeof e[t])))return!1;const i=e.getType();return null!==i&&"function"==typeof i&&"typeName"in i&&"string"==typeof i.typeName&&(void 0===t||i.typeName==t.typeName)}function Q(e,t){return J(t)||!e.fieldWrapper?t:e.fieldWrapper.wrapField(t)}O.DOUBLE,O.FLOAT,O.INT64,O.UINT64,O.INT32,O.UINT32,O.BOOL,O.STRING,O.BYTES;const z={ignoreUnknownFields:!1},Y={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0};function X(e){return e?Object.assign(Object.assign({},z),e):z}function $(e){return e?Object.assign(Object.assign({},Y),e):Y}const Z=Symbol(),ee=Symbol();function te(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 ie(e,t,n,s,r){let o=n.localName;if(n.repeated){if(i("map"!=n.kind),null===t)return;if(!Array.isArray(t))throw new Error("cannot decode field ".concat(r.typeName,".").concat(n.name," from JSON: ").concat(te(t)));const a=e[o];for(const e of t){if(null===e)throw new Error("cannot decode field ".concat(r.typeName,".").concat(n.name," from JSON: ").concat(te(e)));switch(n.kind){case"message":a.push(n.T.fromJson(e,s));break;case"enum":const t=re(n.T,e,s.ignoreUnknownFields,!0);t!==ee&&a.push(t);break;case"scalar":try{a.push(se(n.T,e,n.L,!0))}catch(t){let i="cannot decode field ".concat(r.typeName,".").concat(n.name," from JSON: ").concat(te(e));throw t instanceof Error&&t.message.length>0&&(i+=": ".concat(t.message)),new Error(i)}}}}else if("map"==n.kind){if(null===t)return;if("object"!=typeof t||Array.isArray(t))throw new Error("cannot decode field ".concat(r.typeName,".").concat(n.name," from JSON: ").concat(te(t)));const i=e[o];for(const[e,o]of Object.entries(t)){if(null===o)throw new Error("cannot decode field ".concat(r.typeName,".").concat(n.name," from JSON: map value null"));let a;try{a=ne(n.K,e)}catch(e){let i="cannot decode map key for field ".concat(r.typeName,".").concat(n.name," from JSON: ").concat(te(t));throw e instanceof Error&&e.message.length>0&&(i+=": ".concat(e.message)),new Error(i)}switch(n.V.kind){case"message":i[a]=n.V.T.fromJson(o,s);break;case"enum":const e=re(n.V.T,o,s.ignoreUnknownFields,!0);e!==ee&&(i[a]=e);break;case"scalar":try{i[a]=se(n.V.T,o,x.BIGINT,!0)}catch(e){let i="cannot decode map value for field ".concat(r.typeName,".").concat(n.name," from JSON: ").concat(te(t));throw e instanceof Error&&e.message.length>0&&(i+=": ".concat(e.message)),new Error(i)}}}}else switch(n.oneof&&(e=e[n.oneof.localName]={case:o},o="value"),n.kind){case"message":const i=n.T;if(null===t&&"google.protobuf.Value"!=i.typeName)return;let a=e[o];J(a)?a.fromJson(t,s):(e[o]=a=i.fromJson(t,s),i.fieldWrapper&&!n.oneof&&(e[o]=i.fieldWrapper.unwrapField(a)));break;case"enum":const c=re(n.T,t,s.ignoreUnknownFields,!1);switch(c){case Z:H(n,e);break;case ee:break;default:e[o]=c}break;case"scalar":try{const i=se(n.T,t,n.L,!1);if(i===Z)H(n,e);else e[o]=i}catch(e){let i="cannot decode field ".concat(r.typeName,".").concat(n.name," from JSON: ").concat(te(t));throw e instanceof Error&&e.message.length>0&&(i+=": ".concat(e.message)),new Error(i)}}}function ne(e,t){if(e===O.BOOL)switch(t){case"true":t=!0;break;case"false":t=!1}return se(e,t,x.BIGINT,!0).toString()}function se(e,t,i,n){if(null===t)return n?N(e,i):Z;switch(e){case O.DOUBLE:case O.FLOAT: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 n=Number(t);if(Number.isNaN(n))break;if(!Number.isFinite(n))break;return e==O.FLOAT&&l(n),n;case O.INT32:case O.FIXED32:case O.SFIXED32:case O.SINT32:case O.UINT32:let s;if("number"==typeof t?s=t:"string"==typeof t&&t.length>0&&t.trim().length===t.length&&(s=Number(t)),void 0===s)break;return e==O.UINT32||e==O.FIXED32?d(s):c(s),s;case O.INT64:case O.SFIXED64:case O.SINT64:if("number"!=typeof t&&"string"!=typeof t)break;const r=I.parse(t);return i?r.toString():r;case O.FIXED64:case O.UINT64:if("number"!=typeof t&&"string"!=typeof t)break;const o=I.uParse(t);return i?o.toString():o;case O.BOOL:if("boolean"!=typeof t)break;return t;case O.STRING:if("string"!=typeof t)break;try{encodeURIComponent(t)}catch(e){throw new Error("invalid UTF8")}return t;case O.BYTES:if(""===t)return new Uint8Array(0);if("string"!=typeof t)break;return B.dec(t)}throw new Error}function re(e,t,i,n){if(null===t)return"google.protobuf.NullValue"==e.typeName?0:n?e.values[0].no:Z;switch(typeof t){case"number":if(Number.isInteger(t))return t;break;case"string":const n=e.findName(t);if(void 0!==n)return n.no;if(i)return ee}throw new Error("cannot decode enum ".concat(e.typeName," from JSON: ").concat(te(t)))}function oe(e){return!(!e.repeated&&"map"!=e.kind)||!e.oneof&&("message"!=e.kind&&(!e.opt&&!e.req))}function ae(e,t,n){if("map"==e.kind){i("object"==typeof t&&null!=t);const s={},r=Object.entries(t);switch(e.V.kind){case"scalar":for(const[t,i]of r)s[t.toString()]=de(e.V.T,i);break;case"message":for(const[e,t]of r)s[e.toString()]=t.toJson(n);break;case"enum":const t=e.V.T;for(const[e,i]of r)s[e.toString()]=ce(t,i,n.enumAsInteger)}return n.emitDefaultValues||r.length>0?s:void 0}if(e.repeated){i(Array.isArray(t));const s=[];switch(e.kind){case"scalar":for(let i=0;i<t.length;i++)s.push(de(e.T,t[i]));break;case"enum":for(let i=0;i<t.length;i++)s.push(ce(e.T,t[i],n.enumAsInteger));break;case"message":for(let e=0;e<t.length;e++)s.push(t[e].toJson(n))}return n.emitDefaultValues||s.length>0?s:void 0}switch(e.kind){case"scalar":return de(e.T,t);case"enum":return ce(e.T,t,n.enumAsInteger);case"message":return Q(e.T,t).toJson(n)}}function ce(e,t,n){var s;if(i("number"==typeof t),"google.protobuf.NullValue"==e.typeName)return null;if(n)return t;const r=e.findNumber(t);return null!==(s=null==r?void 0:r.name)&&void 0!==s?s:t}function de(e,t){switch(e){case O.INT32:case O.SFIXED32:case O.SINT32:case O.FIXED32:case O.UINT32:return i("number"==typeof t),t;case O.FLOAT:case O.DOUBLE:return i("number"==typeof t),Number.isNaN(t)?"NaN":t===Number.POSITIVE_INFINITY?"Infinity":t===Number.NEGATIVE_INFINITY?"-Infinity":t;case O.STRING:return i("string"==typeof t),t;case O.BOOL:return i("boolean"==typeof t),t;case O.UINT64:case O.FIXED64:case O.INT64:case O.SFIXED64:case O.SINT64:return i("bigint"==typeof t||"string"==typeof t||"number"==typeof t),t.toString();case O.BYTES:return i(t instanceof Uint8Array),B.enc(t)}}const le=Symbol("@bufbuild/protobuf/unknown-fields"),ue={readUnknownFields:!0,readerFactory:e=>new L(e)},he={writeUnknownFields:!0,writerFactory:()=>new A};function pe(e){return e?Object.assign(Object.assign({},ue),e):ue}function me(e){return e?Object.assign(Object.assign({},he),e):he}function ge(e,t,i,n,s){let{repeated:r,localName:o}=i;switch(i.oneof&&((e=e[i.oneof.localName]).case!=o&&delete e.value,e.case=o,o="value"),i.kind){case"scalar":case"enum":const a="enum"==i.kind?O.INT32:i.T;let c=ke;if("scalar"==i.kind&&i.L>0&&(c=ve),r){let i=e[o];if(n==D.LengthDelimited&&a!=O.STRING&&a!=O.BYTES){let e=t.uint32()+t.pos;for(;t.pos<e;)i.push(c(t,a))}else i.push(c(t,a))}else e[o]=c(t,a);break;case"message":const d=i.T;r?e[o].push(fe(t,new d,s,i)):J(e[o])?fe(t,e[o],s,i):(e[o]=fe(t,new d,s,i),!d.fieldWrapper||i.oneof||i.repeated||(e[o]=d.fieldWrapper.unwrapField(e[o])));break;case"map":let[l,u]=function(e,t,i){const n=t.uint32(),s=t.pos+n;let r,o;for(;t.pos<s;){const[n]=t.tag();switch(n){case 1:r=ke(t,e.K);break;case 2:switch(e.V.kind){case"scalar":o=ke(t,e.V.T);break;case"enum":o=t.int32();break;case"message":o=fe(t,new e.V.T,i,void 0)}}}void 0===r&&(r=N(e.K,x.BIGINT));"string"!=typeof r&&"number"!=typeof r&&(r=r.toString());if(void 0===o)switch(e.V.kind){case"scalar":o=N(e.V.T,x.BIGINT);break;case"enum":o=e.V.T.values[0].no;break;case"message":o=new e.V.T}return[r,o]}(i,t,s);e[o][l]=u}}function fe(e,t,i,n){const s=t.getType().runtime.bin,r=null==n?void 0:n.delimited;return s.readMessage(t,e,r?n.no:e.uint32(),i,r),t}function ve(e,t){const i=ke(e,t);return"bigint"==typeof i?i.toString():i}function ke(e,t){switch(t){case O.STRING:return e.string();case O.BOOL:return e.bool();case O.DOUBLE:return e.double();case O.FLOAT:return e.float();case O.INT32:return e.int32();case O.INT64:return e.int64();case O.UINT64:return e.uint64();case O.FIXED64:return e.fixed64();case O.BYTES:return e.bytes();case O.FIXED32:return e.fixed32();case O.SFIXED32:return e.sfixed32();case O.SFIXED64:return e.sfixed64();case O.SINT64:return e.sint64();case O.UINT32:return e.uint32();case O.SINT32:return e.sint32()}}function be(e,t,n,s){i(void 0!==t);const r=e.repeated;switch(e.kind){case"scalar":case"enum":let o="enum"==e.kind?O.INT32:e.T;if(r)if(i(Array.isArray(t)),e.packed)!function(e,t,i,n){if(!n.length)return;e.tag(i,D.LengthDelimited).fork();let[,s]=Se(t);for(let t=0;t<n.length;t++)e[s](n[t]);e.join()}(n,o,e.no,t);else for(const i of t)Ce(n,o,e.no,i);else Ce(n,o,e.no,t);break;case"message":if(r){i(Array.isArray(t));for(const i of t)Te(n,s,e,i)}else Te(n,s,e,t);break;case"map":i("object"==typeof t&&null!=t);for(const[i,r]of Object.entries(t))ye(n,s,e,i,r)}}function ye(e,t,n,s,r){e.tag(n.no,D.LengthDelimited),e.fork();let o=s;switch(n.K){case O.INT32:case O.FIXED32:case O.UINT32:case O.SFIXED32:case O.SINT32:o=Number.parseInt(s);break;case O.BOOL:i("true"==s||"false"==s),o="true"==s}switch(Ce(e,n.K,1,o),n.V.kind){case"scalar":Ce(e,n.V.T,2,r);break;case"enum":Ce(e,O.INT32,2,r);break;case"message":i(void 0!==r),e.tag(2,D.LengthDelimited).bytes(r.toBinary(t))}e.join()}function Te(e,t,i,n){const s=Q(i.T,n);i.delimited?e.tag(i.no,D.StartGroup).raw(s.toBinary(t)).tag(i.no,D.EndGroup):e.tag(i.no,D.LengthDelimited).bytes(s.toBinary(t))}function Ce(e,t,n,s){i(void 0!==s);let[r,o]=Se(t);e.tag(n,r)[o](s)}function Se(e){let t=D.Varint;switch(e){case O.BYTES:case O.STRING:t=D.LengthDelimited;break;case O.DOUBLE:case O.FIXED64:case O.SFIXED64:t=D.Bit64;break;case O.FIXED32:case O.SFIXED32:case O.FLOAT:t=D.Bit32}return[t,O[e].toLowerCase()]}function Ee(e){if(void 0===e)return e;if(J(e))return e.clone();if(e instanceof Uint8Array){const t=new Uint8Array(e.byteLength);return t.set(e),t}return e}function we(e){return e instanceof Uint8Array?e:new Uint8Array(e)}class Pe{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 i of this.list())i.oneof?i.oneof!==t&&(t=i.oneof,e.push(t)):e.push(i)}return this.members}}function Re(e,t){const i=Oe(e);return t?i:_e(Ne(i))}const Ie=Oe;function Oe(e){let t=!1;const i=[];for(let n=0;n<e.length;n++){let s=e.charAt(n);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":i.push(s),t=!1;break;default:t&&(t=!1,s=s.toUpperCase()),i.push(s)}}return i.join("")}const xe=new Set(["constructor","toString","toJSON","valueOf"]),De=new Set(["getType","clone","equals","fromBinary","fromJson","fromJsonString","toBinary","toJson","toJsonString","toObject"]),Me=e=>"".concat(e,"$"),Ne=e=>De.has(e)?Me(e):e,_e=e=>xe.has(e)?Me(e):e;class Ae{constructor(e){this.kind="oneof",this.repeated=!1,this.packed=!1,this.opt=!1,this.req=!1,this.default=void 0,this.fields=[],this.name=e,this.localName=Re(e,!1)}addField(e){i(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 Le=(Ue=e=>new Pe(e,(e=>function(e,t){var i,n,s,r,o,a;const c=[];let d;for(const t of"function"==typeof e?e():e){const e=t;if(e.localName=Re(t.name,void 0!==t.oneof),e.jsonName=null!==(i=t.jsonName)&&void 0!==i?i:Ie(t.name),e.repeated=null!==(n=t.repeated)&&void 0!==n&&n,"scalar"==t.kind&&(e.L=null!==(s=t.L)&&void 0!==s?s:x.BIGINT),e.delimited=null!==(r=t.delimited)&&void 0!==r&&r,e.req=null!==(o=t.req)&&void 0!==o&&o,e.opt=null!==(a=t.opt)&&void 0!==a&&a,void 0===t.packed&&(e.packed="enum"==t.kind||"scalar"==t.kind&&t.T!=O.BYTES&&t.T!=O.STRING),void 0!==t.oneof){const i="string"==typeof t.oneof?t.oneof:t.oneof.name;d&&d.name==i||(d=new Ae(i)),e.oneof=d,d.addField(e)}c.push(e)}return c}(e))),je=e=>{for(const t of e.getType().fields.byMember()){if(t.opt)continue;const i=t.localName,n=e;if(t.repeated)n[i]=[];else switch(t.kind){case"oneof":n[i]={case:void 0};break;case"enum":n[i]=0;break;case"map":n[i]={};break;case"scalar":n[i]=N(t.T,t.L)}}},{syntax:"proto3",json:{makeReadOptions:X,makeWriteOptions:$,readMessage(e,t,i,n){if(null==t||Array.isArray(t)||"object"!=typeof t)throw new Error("cannot decode message ".concat(e.typeName," from JSON: ").concat(te(t)));n=null!=n?n:new e;const s=new Map,r=i.typeRegistry;for(const[o,a]of Object.entries(t)){const t=e.fields.findJsonName(o);if(t){if(t.oneof){if(null===a&&"scalar"==t.kind)continue;const i=s.get(t.oneof);if(void 0!==i)throw new Error("cannot decode message ".concat(e.typeName,' from JSON: multiple keys for oneof "').concat(t.oneof.name,'" present: "').concat(i,'", "').concat(o,'"'));s.set(t.oneof,o)}ie(n,a,t,i,e)}else{let t=!1;if((null==r?void 0:r.findExtension)&&o.startsWith("[")&&o.endsWith("]")){const s=r.findExtension(o.substring(1,o.length-1));if(s&&s.extendee.typeName==e.typeName){t=!0;const[e,r]=U(s);ie(e,a,s.field,i,s),q(n,s,r(),i)}}if(!t&&!i.ignoreUnknownFields)throw new Error("cannot decode message ".concat(e.typeName,' from JSON: key "').concat(o,'" is unknown'))}}return n},writeMessage(e,t){const i=e.getType(),n={};let s;try{for(s of i.fields.byNumber()){if(!G(s,e)){if(s.req)throw"required field not set";if(!t.emitDefaultValues)continue;if(!oe(s))continue}const i=ae(s,s.oneof?e[s.oneof.localName].value:e[s.localName],t);void 0!==i&&(n[t.useProtoFieldName?s.name:s.jsonName]=i)}const r=t.typeRegistry;if(null==r?void 0:r.findExtensionFor)for(const s of i.runtime.bin.listUnknownFields(e)){const o=r.findExtensionFor(i.typeName,s.no);if(o&&K(e,o)){const i=V(e,o,t),s=ae(o.field,i,t);void 0!==s&&(n[o.field.jsonName]=s)}}}catch(e){const t=s?"cannot encode field ".concat(i.typeName,".").concat(s.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 n},readScalar:(e,t,i)=>se(e,t,null!=i?i:x.BIGINT,!0),writeScalar(e,t,i){if(void 0!==t)return i||_(e,t)?de(e,t):void 0},debug:te},bin:{makeReadOptions:pe,makeWriteOptions:me,listUnknownFields(e){var t;return null!==(t=e[le])&&void 0!==t?t:[]},discardUnknownFields(e){delete e[le]},writeUnknownFields(e,t){const i=e[le];if(i)for(const e of i)t.tag(e.no,e.wireType).raw(e.data)},onUnknownField(e,t,i,n){const s=e;Array.isArray(s[le])||(s[le]=[]),s[le].push({no:t,wireType:i,data:n})},readMessage(e,t,i,n,s){const r=e.getType(),o=s?t.len:t.pos+i;let a,c;for(;t.pos<o&&([a,c]=t.tag(),!0!==s||c!=D.EndGroup);){const i=r.fields.find(a);if(i)ge(e,t,i,c,n);else{const i=t.skip(c,a);n.readUnknownFields&&this.onUnknownField(e,a,c,i)}}if(s&&(c!=D.EndGroup||a!==i))throw new Error("invalid end group tag")},readField:ge,writeMessage(e,t,i){const n=e.getType();for(const s of n.fields.byNumber())if(G(s,e))be(s,s.oneof?e[s.oneof.localName].value:e[s.localName],t,i);else if(s.req)throw new Error("cannot encode field ".concat(n.typeName,".").concat(s.name," to binary: required field not set"));return i.writeUnknownFields&&this.writeUnknownFields(e,t),t},writeField(e,t,i,n){void 0!==t&&be(e,t,i,n)}},util:Object.assign(Object.assign({},{setEnumType:p,initPartial(e,t){if(void 0===e)return;const i=t.getType();for(const n of i.fields.byMember()){const i=n.localName,s=t,r=e;if(null!=r[i])switch(n.kind){case"oneof":const e=r[i].case;if(void 0===e)continue;const t=n.findField(e);let o=r[i].value;t&&"message"==t.kind&&!J(o,t.T)?o=new t.T(o):t&&"scalar"===t.kind&&t.T===O.BYTES&&(o=we(o)),s[i]={case:e,value:o};break;case"scalar":case"enum":let a=r[i];n.T===O.BYTES&&(a=n.repeated?a.map(we):we(a)),s[i]=a;break;case"map":switch(n.V.kind){case"scalar":case"enum":if(n.V.T===O.BYTES)for(const[e,t]of Object.entries(r[i]))s[i][e]=we(t);else Object.assign(s[i],r[i]);break;case"message":const e=n.V.T;for(const t of Object.keys(r[i])){let n=r[i][t];e.fieldWrapper||(n=new e(n)),s[i][t]=n}}break;case"message":const c=n.T;if(n.repeated)s[i]=r[i].map((e=>J(e,c)?e:new c(e)));else{const e=r[i];c.fieldWrapper?"google.protobuf.BytesValue"===c.typeName?s[i]=we(e):s[i]=e:s[i]=J(e,c)?e:new c(e)}}}},equals:(e,t,i)=>t===i||!(!t||!i)&&e.fields.byMember().every((e=>{const n=t[e.localName],s=i[e.localName];if(e.repeated){if(n.length!==s.length)return!1;switch(e.kind){case"message":return n.every(((t,i)=>e.T.equals(t,s[i])));case"scalar":return n.every(((t,i)=>M(e.T,t,s[i])));case"enum":return n.every(((e,t)=>M(O.INT32,e,s[t])))}throw new Error("repeated cannot contain ".concat(e.kind))}switch(e.kind){case"message":return e.T.equals(n,s);case"enum":return M(O.INT32,n,s);case"scalar":return M(e.T,n,s);case"oneof":if(n.case!==s.case)return!1;const t=e.findField(n.case);if(void 0===t)return!0;switch(t.kind){case"message":return t.T.equals(n.value,s.value);case"enum":return M(O.INT32,n.value,s.value);case"scalar":return M(t.T,n.value,s.value)}throw new Error("oneof cannot contain ".concat(t.kind));case"map":const i=Object.keys(n).concat(Object.keys(s));switch(e.V.kind){case"message":const t=e.V.T;return i.every((e=>t.equals(n[e],s[e])));case"enum":return i.every((e=>M(O.INT32,n[e],s[e])));case"scalar":const r=e.V.T;return i.every((e=>M(r,n[e],s[e])))}}})),clone(e){const t=e.getType(),i=new t,n=i;for(const i of t.fields.byMember()){const t=e[i.localName];let s;if(i.repeated)s=t.map(Ee);else if("map"==i.kind){s=n[i.localName];for(const[e,i]of Object.entries(t))s[e]=Ee(i)}else s="oneof"==i.kind?i.findField(t.case)?{case:t.case,value:Ee(t.value)}:{case:void 0}:Ee(t);n[i.localName]=s}for(const i of t.runtime.bin.listUnknownFields(e))t.runtime.bin.onUnknownField(n,i.no,i.wireType,i.data);return i}}),{newFieldList:Ue,initFields:je}),makeMessageType(e,t,i){return function(e,t,i,n){var s;const r=null!==(s=null==n?void 0:n.localName)&&void 0!==s?s:t.substring(t.lastIndexOf(".")+1),o={[r]:function(t){e.util.initFields(this),e.util.initPartial(t,this)}}[r];return Object.setPrototypeOf(o.prototype,new v),Object.assign(o,{runtime:e,typeName:t,fields:e.util.newFieldList(i),fromBinary:(e,t)=>(new o).fromBinary(e,t),fromJson:(e,t)=>(new o).fromJson(e,t),fromJsonString:(e,t)=>(new o).fromJsonString(e,t),equals:(t,i)=>e.util.equals(o,t,i)}),o}(this,e,t,i)},makeEnum:g,makeEnumType:m,getEnumType:h,makeExtension(e,t,i){return function(e,t,i,n){let s;return{typeName:t,extendee:i,get field(){if(!s){const i="function"==typeof n?n():n;i.name=t.split(".").pop(),i.jsonName="[".concat(t,"]"),s=e.util.newFieldList([i]).list()[0]}return s},runtime:e}}(this,e,t,i)}});var Ue,je;const Fe=Le.makeMessageType("livekit.MetricsBatch",(()=>[{no:1,name:"str_data",kind:"scalar",T:9,repeated:!0},{no:2,name:"time_series",kind:"message",T:Be,repeated:!0},{no:3,name:"events",kind:"message",T:qe,repeated:!0}])),Be=Le.makeMessageType("livekit.TimeSeriesMetric",(()=>[{no:1,name:"label",kind:"scalar",T:13},{no:2,name:"participant_identity",kind:"scalar",T:13},{no:3,name:"track_sid",kind:"scalar",T:13},{no:4,name:"start_timestamp",kind:"scalar",T:3},{no:5,name:"end_timestamp",kind:"scalar",T:3},{no:6,name:"samples",kind:"message",T:Ve,repeated:!0}])),Ve=Le.makeMessageType("livekit.MetricSample",(()=>[{no:1,name:"timestamp",kind:"scalar",T:3},{no:2,name:"value",kind:"scalar",T:2}])),qe=Le.makeMessageType("livekit.EventMetric",(()=>[{no:1,name:"label",kind:"scalar",T:13},{no:2,name:"participant_identity",kind:"scalar",T:13},{no:3,name:"track_sid",kind:"scalar",T:13},{no:4,name:"start_timestamp",kind:"scalar",T:3},{no:5,name:"end_timestamp",kind:"scalar",T:3,opt:!0},{no:6,name:"metadata",kind:"scalar",T:9}])),Ke=Le.makeEnum("livekit.TrackType",[{no:0,name:"AUDIO"},{no:1,name:"VIDEO"},{no:2,name:"DATA"}]),We=Le.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"}]),Ge=Le.makeEnum("livekit.VideoQuality",[{no:0,name:"LOW"},{no:1,name:"MEDIUM"},{no:2,name:"HIGH"},{no:3,name:"OFF"}]),He=Le.makeEnum("livekit.ConnectionQuality",[{no:0,name:"POOR"},{no:1,name:"GOOD"},{no:2,name:"EXCELLENT"},{no:3,name:"LOST"}]),Je=Le.makeEnum("livekit.ClientConfigSetting",[{no:0,name:"UNSET"},{no:1,name:"DISABLED"},{no:2,name:"ENABLED"}]),Qe=Le.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"},{no:10,name:"ROOM_CLOSED"}]),ze=Le.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"}]),Ye=Le.makeEnum("livekit.SubscriptionError",[{no:0,name:"SE_UNKNOWN"},{no:1,name:"SE_CODEC_UNSUPPORTED"},{no:2,name:"SE_TRACK_NOTFOUND"}]),Xe=Le.makeEnum("livekit.AudioTrackFeature",[{no:0,name:"TF_STEREO"},{no:1,name:"TF_NO_DTX"},{no:2,name:"TF_AUTO_GAIN_CONTROL"},{no:3,name:"TF_ECHO_CANCELLATION"},{no:4,name:"TF_NOISE_SUPPRESSION"},{no:5,name:"TF_ENHANCED_NOISE_CANCELLATION"}]),$e=Le.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:Ze,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:Et}])),Ze=Le.makeMessageType("livekit.Codec",(()=>[{no:1,name:"mime",kind:"scalar",T:9},{no:2,name:"fmtp_line",kind:"scalar",T:9}])),et=Le.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:Le.getEnumType(We),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},{no:12,name:"can_subscribe_metrics",kind:"scalar",T:8}])),tt=Le.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:Le.getEnumType(it)},{no:4,name:"tracks",kind:"message",T:ot,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:et},{no:12,name:"region",kind:"scalar",T:9},{no:13,name:"is_publisher",kind:"scalar",T:8},{no:14,name:"kind",kind:"enum",T:Le.getEnumType(nt)},{no:15,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:16,name:"disconnect_reason",kind:"enum",T:Le.getEnumType(Qe)}])),it=Le.makeEnum("livekit.ParticipantInfo.State",[{no:0,name:"JOINING"},{no:1,name:"JOINED"},{no:2,name:"ACTIVE"},{no:3,name:"DISCONNECTED"}]),nt=Le.makeEnum("livekit.ParticipantInfo.Kind",[{no:0,name:"STANDARD"},{no:1,name:"INGRESS"},{no:2,name:"EGRESS"},{no:3,name:"SIP"},{no:4,name:"AGENT"}]),st=Le.makeEnum("livekit.Encryption.Type",[{no:0,name:"NONE"},{no:1,name:"GCM"},{no:2,name:"CUSTOM"}]),rt=Le.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:at,repeated:!0}])),ot=Le.makeMessageType("livekit.TrackInfo",(()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"type",kind:"enum",T:Le.getEnumType(Ke)},{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:Le.getEnumType(We)},{no:10,name:"layers",kind:"message",T:at,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:rt,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:Le.getEnumType(st)},{no:17,name:"stream",kind:"scalar",T:9},{no:18,name:"version",kind:"message",T:Et},{no:19,name:"audio_features",kind:"enum",T:Le.getEnumType(Xe),repeated:!0}])),at=Le.makeMessageType("livekit.VideoLayer",(()=>[{no:1,name:"quality",kind:"enum",T:Le.getEnumType(Ge)},{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}])),ct=Le.makeMessageType("livekit.DataPacket",(()=>[{no:1,name:"kind",kind:"enum",T:Le.getEnumType(dt)},{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:ht,oneof:"value"},{no:3,name:"speaker",kind:"message",T:lt,oneof:"value"},{no:6,name:"sip_dtmf",kind:"message",T:pt,oneof:"value"},{no:7,name:"transcription",kind:"message",T:mt,oneof:"value"},{no:8,name:"metrics",kind:"message",T:Fe,oneof:"value"}])),dt=Le.makeEnum("livekit.DataPacket.Kind",[{no:0,name:"RELIABLE"},{no:1,name:"LOSSY"}]),lt=Le.makeMessageType("livekit.ActiveSpeakerUpdate",(()=>[{no:1,name:"speakers",kind:"message",T:ut,repeated:!0}])),ut=Le.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}])),ht=Le.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},{no:8,name:"id",kind:"scalar",T:9,opt:!0},{no:9,name:"start_time",kind:"scalar",T:4,opt:!0},{no:10,name:"end_time",kind:"scalar",T:4,opt:!0}])),pt=Le.makeMessageType("livekit.SipDTMF",(()=>[{no:3,name:"code",kind:"scalar",T:13},{no:4,name:"digit",kind:"scalar",T:9}])),mt=Le.makeMessageType("livekit.Transcription",(()=>[{no:2,name:"transcribed_participant_identity",kind:"scalar",T:9},{no:3,name:"track_id",kind:"scalar",T:9},{no:4,name:"segments",kind:"message",T:gt,repeated:!0}])),gt=Le.makeMessageType("livekit.TranscriptionSegment",(()=>[{no:1,name:"id",kind:"scalar",T:9},{no:2,name:"text",kind:"scalar",T:9},{no:3,name:"start_time",kind:"scalar",T:4},{no:4,name:"end_time",kind:"scalar",T:4},{no:5,name:"final",kind:"scalar",T:8},{no:6,name:"language",kind:"scalar",T:9}])),ft=Le.makeMessageType("livekit.ParticipantTracks",(()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"track_sids",kind:"scalar",T:9,repeated:!0}])),vt=Le.makeMessageType("livekit.ServerInfo",(()=>[{no:1,name:"edition",kind:"enum",T:Le.getEnumType(kt)},{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},{no:7,name:"agent_protocol",kind:"scalar",T:5}])),kt=Le.makeEnum("livekit.ServerInfo.Edition",[{no:0,name:"Standard"},{no:1,name:"Cloud"}]),bt=Le.makeMessageType("livekit.ClientInfo",(()=>[{no:1,name:"sdk",kind:"enum",T:Le.getEnumType(yt)},{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}])),yt=Le.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"}]),Tt=Le.makeMessageType("livekit.ClientConfiguration",(()=>[{no:1,name:"video",kind:"message",T:Ct},{no:2,name:"screen",kind:"message",T:Ct},{no:3,name:"resume_connection",kind:"enum",T:Le.getEnumType(Je)},{no:4,name:"disabled_codecs",kind:"message",T:St},{no:5,name:"force_relay",kind:"enum",T:Le.getEnumType(Je)}])),Ct=Le.makeMessageType("livekit.VideoConfiguration",(()=>[{no:1,name:"hardware_encoder",kind:"enum",T:Le.getEnumType(Je)}])),St=Le.makeMessageType("livekit.DisabledCodecs",(()=>[{no:1,name:"codecs",kind:"message",T:Ze,repeated:!0},{no:2,name:"publish",kind:"message",T:Ze,repeated:!0}])),Et=Le.makeMessageType("livekit.TimedVersion",(()=>[{no:1,name:"unix_micro",kind:"scalar",T:3},{no:2,name:"ticks",kind:"scalar",T:5}])),wt=Le.makeEnum("livekit.SignalTarget",[{no:0,name:"PUBLISHER"},{no:1,name:"SUBSCRIBER"}]),Pt=Le.makeEnum("livekit.StreamState",[{no:0,name:"ACTIVE"},{no:1,name:"PAUSED"}]),Rt=Le.makeEnum("livekit.CandidateProtocol",[{no:0,name:"UDP"},{no:1,name:"TCP"},{no:2,name:"TLS"}]),It=Le.makeMessageType("livekit.SignalRequest",(()=>[{no:1,name:"offer",kind:"message",T:jt,oneof:"message"},{no:2,name:"answer",kind:"message",T:jt,oneof:"message"},{no:3,name:"trickle",kind:"message",T:Mt,oneof:"message"},{no:4,name:"add_track",kind:"message",T:Dt,oneof:"message"},{no:5,name:"mute",kind:"message",T:Nt,oneof:"message"},{no:6,name:"subscription",kind:"message",T:Bt,oneof:"message"},{no:7,name:"track_setting",kind:"message",T:Vt,oneof:"message"},{no:8,name:"leave",kind:"message",T:Wt,oneof:"message"},{no:10,name:"update_layers",kind:"message",T:Ht,oneof:"message"},{no:11,name:"subscription_permission",kind:"message",T:ri,oneof:"message"},{no:12,name:"sync_state",kind:"message",T:ai,oneof:"message"},{no:13,name:"simulate",kind:"message",T:di,oneof:"message"},{no:14,name:"ping",kind:"scalar",T:3,oneof:"message"},{no:15,name:"update_metadata",kind:"message",T:Jt,oneof:"message"},{no:16,name:"ping_req",kind:"message",T:li,oneof:"message"},{no:17,name:"update_audio_track",kind:"message",T:qt,oneof:"message"},{no:18,name:"update_video_track",kind:"message",T:Kt,oneof:"message"}])),Ot=Le.makeMessageType("livekit.SignalResponse",(()=>[{no:1,name:"join",kind:"message",T:_t,oneof:"message"},{no:2,name:"answer",kind:"message",T:jt,oneof:"message"},{no:3,name:"offer",kind:"message",T:jt,oneof:"message"},{no:4,name:"trickle",kind:"message",T:Mt,oneof:"message"},{no:5,name:"update",kind:"message",T:Ft,oneof:"message"},{no:6,name:"track_published",kind:"message",T:Lt,oneof:"message"},{no:8,name:"leave",kind:"message",T:Wt,oneof:"message"},{no:9,name:"mute",kind:"message",T:Nt,oneof:"message"},{no:10,name:"speakers_changed",kind:"message",T:zt,oneof:"message"},{no:11,name:"room_update",kind:"message",T:Yt,oneof:"message"},{no:12,name:"connection_quality",kind:"message",T:$t,oneof:"message"},{no:13,name:"stream_state_update",kind:"message",T:ei,oneof:"message"},{no:14,name:"subscribed_quality_update",kind:"message",T:ni,oneof:"message"},{no:15,name:"subscription_permission_update",kind:"message",T:oi,oneof:"message"},{no:16,name:"refresh_token",kind:"scalar",T:9,oneof:"message"},{no:17,name:"track_unpublished",kind:"message",T:Ut,oneof:"message"},{no:18,name:"pong",kind:"scalar",T:3,oneof:"message"},{no:19,name:"reconnect",kind:"message",T:At,oneof:"message"},{no:20,name:"pong_resp",kind:"message",T:ui,oneof:"message"},{no:21,name:"subscription_response",kind:"message",T:mi,oneof:"message"},{no:22,name:"request_response",kind:"message",T:gi,oneof:"message"},{no:23,name:"track_subscribed",kind:"message",T:vi,oneof:"message"}])),xt=Le.makeMessageType("livekit.SimulcastCodec",(()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"cid",kind:"scalar",T:9}])),Dt=Le.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:Le.getEnumType(Ke)},{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:Le.getEnumType(We)},{no:9,name:"layers",kind:"message",T:at,repeated:!0},{no:10,name:"simulcast_codecs",kind:"message",T:xt,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:Le.getEnumType(st)},{no:15,name:"stream",kind:"scalar",T:9}])),Mt=Le.makeMessageType("livekit.TrickleRequest",(()=>[{no:1,name:"candidateInit",kind:"scalar",T:9},{no:2,name:"target",kind:"enum",T:Le.getEnumType(wt)},{no:3,name:"final",kind:"scalar",T:8}])),Nt=Le.makeMessageType("livekit.MuteTrackRequest",(()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"muted",kind:"scalar",T:8}])),_t=Le.makeMessageType("livekit.JoinResponse",(()=>[{no:1,name:"room",kind:"message",T:$e},{no:2,name:"participant",kind:"message",T:tt},{no:3,name:"other_participants",kind:"message",T:tt,repeated:!0},{no:4,name:"server_version",kind:"scalar",T:9},{no:5,name:"ice_servers",kind:"message",T:Qt,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:Tt},{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:vt},{no:13,name:"sif_trailer",kind:"scalar",T:12},{no:14,name:"enabled_publish_codecs",kind:"message",T:Ze,repeated:!0},{no:15,name:"fast_publish",kind:"scalar",T:8}])),At=Le.makeMessageType("livekit.ReconnectResponse",(()=>[{no:1,name:"ice_servers",kind:"message",T:Qt,repeated:!0},{no:2,name:"client_configuration",kind:"message",T:Tt}])),Lt=Le.makeMessageType("livekit.TrackPublishedResponse",(()=>[{no:1,name:"cid",kind:"scalar",T:9},{no:2,name:"track",kind:"message",T:ot}])),Ut=Le.makeMessageType("livekit.TrackUnpublishedResponse",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9}])),jt=Le.makeMessageType("livekit.SessionDescription",(()=>[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"sdp",kind:"scalar",T:9}])),Ft=Le.makeMessageType("livekit.ParticipantUpdate",(()=>[{no:1,name:"participants",kind:"message",T:tt,repeated:!0}])),Bt=Le.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:ft,repeated:!0}])),Vt=Le.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:Le.getEnumType(Ge)},{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}])),qt=Le.makeMessageType("livekit.UpdateLocalAudioTrack",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"features",kind:"enum",T:Le.getEnumType(Xe),repeated:!0}])),Kt=Le.makeMessageType("livekit.UpdateLocalVideoTrack",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"width",kind:"scalar",T:13},{no:3,name:"height",kind:"scalar",T:13}])),Wt=Le.makeMessageType("livekit.LeaveRequest",(()=>[{no:1,name:"can_reconnect",kind:"scalar",T:8},{no:2,name:"reason",kind:"enum",T:Le.getEnumType(Qe)},{no:3,name:"action",kind:"enum",T:Le.getEnumType(Gt)},{no:4,name:"regions",kind:"message",T:hi}])),Gt=Le.makeEnum("livekit.LeaveRequest.Action",[{no:0,name:"DISCONNECT"},{no:1,name:"RESUME"},{no:2,name:"RECONNECT"}]),Ht=Le.makeMessageType("livekit.UpdateVideoLayers",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"layers",kind:"message",T:at,repeated:!0}])),Jt=Le.makeMessageType("livekit.UpdateParticipantMetadata",(()=>[{no:1,name:"metadata",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",T:9},{no:3,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:4,name:"request_id",kind:"scalar",T:13}])),Qt=Le.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}])),zt=Le.makeMessageType("livekit.SpeakersChanged",(()=>[{no:1,name:"speakers",kind:"message",T:ut,repeated:!0}])),Yt=Le.makeMessageType("livekit.RoomUpdate",(()=>[{no:1,name:"room",kind:"message",T:$e}])),Xt=Le.makeMessageType("livekit.ConnectionQualityInfo",(()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"quality",kind:"enum",T:Le.getEnumType(He)},{no:3,name:"score",kind:"scalar",T:2}])),$t=Le.makeMessageType("livekit.ConnectionQualityUpdate",(()=>[{no:1,name:"updates",kind:"message",T:Xt,repeated:!0}])),Zt=Le.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:Le.getEnumType(Pt)}])),ei=Le.makeMessageType("livekit.StreamStateUpdate",(()=>[{no:1,name:"stream_states",kind:"message",T:Zt,repeated:!0}])),ti=Le.makeMessageType("livekit.SubscribedQuality",(()=>[{no:1,name:"quality",kind:"enum",T:Le.getEnumType(Ge)},{no:2,name:"enabled",kind:"scalar",T:8}])),ii=Le.makeMessageType("livekit.SubscribedCodec",(()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"qualities",kind:"message",T:ti,repeated:!0}])),ni=Le.makeMessageType("livekit.SubscribedQualityUpdate",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribed_qualities",kind:"message",T:ti,repeated:!0},{no:3,name:"subscribed_codecs",kind:"message",T:ii,repeated:!0}])),si=Le.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}])),ri=Le.makeMessageType("livekit.SubscriptionPermission",(()=>[{no:1,name:"all_participants",kind:"scalar",T:8},{no:2,name:"track_permissions",kind:"message",T:si,repeated:!0}])),oi=Le.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}])),ai=Le.makeMessageType("livekit.SyncState",(()=>[{no:1,name:"answer",kind:"message",T:jt},{no:2,name:"subscription",kind:"message",T:Bt},{no:3,name:"publish_tracks",kind:"message",T:Lt,repeated:!0},{no:4,name:"data_channels",kind:"message",T:ci,repeated:!0},{no:5,name:"offer",kind:"message",T:jt},{no:6,name:"track_sids_disabled",kind:"scalar",T:9,repeated:!0}])),ci=Le.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:Le.getEnumType(wt)}])),di=Le.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:Le.getEnumType(Rt),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"},{no:9,name:"leave_request_full_reconnect",kind:"scalar",T:8,oneof:"scenario"}])),li=Le.makeMessageType("livekit.Ping",(()=>[{no:1,name:"timestamp",kind:"scalar",T:3},{no:2,name:"rtt",kind:"scalar",T:3}])),ui=Le.makeMessageType("livekit.Pong",(()=>[{no:1,name:"last_ping_timestamp",kind:"scalar",T:3},{no:2,name:"timestamp",kind:"scalar",T:3}])),hi=Le.makeMessageType("livekit.RegionSettings",(()=>[{no:1,name:"regions",kind:"message",T:pi,repeated:!0}])),pi=Le.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}])),mi=Le.makeMessageType("livekit.SubscriptionResponse",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"err",kind:"enum",T:Le.getEnumType(Ye)}])),gi=Le.makeMessageType("livekit.RequestResponse",(()=>[{no:1,name:"request_id",kind:"scalar",T:13},{no:2,name:"reason",kind:"enum",T:Le.getEnumType(fi)},{no:3,name:"message",kind:"scalar",T:9}])),fi=Le.makeEnum("livekit.RequestResponse.Reason",[{no:0,name:"OK"},{no:1,name:"NOT_FOUND"},{no:2,name:"NOT_ALLOWED"},{no:3,name:"LIMIT_EXCEEDED"}]),vi=Le.makeMessageType("livekit.TrackSubscribed",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9}]));var ki="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function bi(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var yi={exports:{}};!function(e){var t,i;t=ki,i=function(){var e=function(){},t="undefined",i=typeof window!==t&&typeof window.navigator!==t&&/Trident\/|MSIE /.test(window.navigator.userAgent),n=["trace","debug","info","warn","error"],s={},r=null;function o(e,t){var i=e[t];if("function"==typeof i.bind)return i.bind(e);try{return Function.prototype.bind.call(i,e)}catch(t){return function(){return Function.prototype.apply.apply(i,[e,arguments])}}}function a(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function c(){for(var i=this.getLevel(),s=0;s<n.length;s++){var r=n[s];this[r]=s<i?e:this.methodFactory(r,i,this.name)}if(this.log=this.debug,typeof console===t&&i<this.levels.SILENT)return"No console available for logging"}function d(e){return function(){typeof console!==t&&(c.call(this),this[e].apply(this,arguments))}}function l(n,s,r){return function(n){return"debug"===n&&(n="log"),typeof console!==t&&("trace"===n&&i?a:void 0!==console[n]?o(console,n):void 0!==console.log?o(console,"log"):e)}(n)||d.apply(this,arguments)}function u(e,i){var o,a,d,u=this,h="loglevel";function p(){var e;if(typeof window!==t&&h){try{e=window.localStorage[h]}catch(e){}if(typeof e===t)try{var i=window.document.cookie,n=encodeURIComponent(h),s=i.indexOf(n+"=");-1!==s&&(e=/^([^;]+)/.exec(i.slice(s+n.length+1))[1])}catch(e){}return void 0===u.levels[e]&&(e=void 0),e}}function m(e){var t=e;if("string"==typeof t&&void 0!==u.levels[t.toUpperCase()]&&(t=u.levels[t.toUpperCase()]),"number"==typeof t&&t>=0&&t<=u.levels.SILENT)return t;throw new TypeError("log.setLevel() called with invalid level: "+e)}"string"==typeof e?h+=":"+e:"symbol"==typeof e&&(h=void 0),u.name=e,u.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},u.methodFactory=i||l,u.getLevel=function(){return null!=d?d:null!=a?a:o},u.setLevel=function(e,i){return d=m(e),!1!==i&&function(e){var i=(n[e]||"silent").toUpperCase();if(typeof window!==t&&h){try{return void(window.localStorage[h]=i)}catch(e){}try{window.document.cookie=encodeURIComponent(h)+"="+i+";"}catch(e){}}}(d),c.call(u)},u.setDefaultLevel=function(e){a=m(e),p()||u.setLevel(e,!1)},u.resetLevel=function(){d=null,function(){if(typeof window!==t&&h){try{window.localStorage.removeItem(h)}catch(e){}try{window.document.cookie=encodeURIComponent(h)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch(e){}}}(),c.call(u)},u.enableAll=function(e){u.setLevel(u.levels.TRACE,e)},u.disableAll=function(e){u.setLevel(u.levels.SILENT,e)},u.rebuild=function(){if(r!==u&&(o=m(r.getLevel())),c.call(u),r===u)for(var e in s)s[e].rebuild()},o=m(r?r.getLevel():"WARN");var g=p();null!=g&&(d=m(g)),c.call(u)}(r=new u).getLogger=function(e){if("symbol"!=typeof e&&"string"!=typeof e||""===e)throw new TypeError("You must supply a name when creating a logger.");var t=s[e];return t||(t=s[e]=new u(e,r.methodFactory)),t};var h=typeof window!==t?window.log:void 0;return r.noConflict=function(){return typeof window!==t&&window.log===r&&(window.log=h),r},r.getLoggers=function(){return s},r.default=r,r},e.exports?e.exports=i():t.log=i()}(yi);var Ti,Ci,Si=yi.exports;e.LogLevel=void 0,(Ti=e.LogLevel||(e.LogLevel={}))[Ti.trace=0]="trace",Ti[Ti.debug=1]="debug",Ti[Ti.info=2]="info",Ti[Ti.warn=3]="warn",Ti[Ti.error=4]="error",Ti[Ti.silent=5]="silent",e.LoggerNames=void 0,(Ci=e.LoggerNames||(e.LoggerNames={})).Default="livekit",Ci.Room="livekit-room",Ci.Participant="livekit-participant",Ci.Track="livekit-track",Ci.Publication="livekit-track-publication",Ci.Engine="livekit-engine",Ci.Signal="livekit-signal",Ci.PCManager="livekit-pc-manager",Ci.PCTransport="livekit-pc-transport",Ci.E2EE="lk-e2ee";let Ei=Si.getLogger("livekit");const wi=Object.values(e.LoggerNames).map((e=>Si.getLogger(e)));function Pi(e){const t=Si.getLogger(e);return t.setDefaultLevel(Ei.getLevel()),t}Ei.setDefaultLevel(e.LogLevel.info);const Ri=Si.getLogger("lk-e2ee"),Ii=7e3,Oi=[0,300,1200,2700,4800,Ii,Ii,Ii,Ii,Ii];class xi{constructor(e){this._retryDelays=void 0!==e?[...e]:Oi}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 Di(e,t,i,n){return new(i||(i=Promise))((function(s,r){function o(e){try{c(n.next(e))}catch(e){r(e)}}function a(e){try{c(n.throw(e))}catch(e){r(e)}}function c(e){var t;e.done?s(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}c((n=n.apply(e,t||[])).next())}))}function Mi(e){var t="function"==typeof Symbol&&Symbol.iterator,i=t&&e[t],n=0;if(i)return i.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function Ni(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t,i=e[Symbol.asyncIterator];return i?i.call(e):(e=Mi(e),t={},n("next"),n("throw"),n("return"),t[Symbol.asyncIterator]=function(){return this},t);function n(i){t[i]=e[i]&&function(t){return new Promise((function(n,s){(function(e,t,i,n){Promise.resolve(n).then((function(t){e({value:t,done:i})}),t)})(n,s,(t=e[i](t)).done,t.value)}))}}}"function"==typeof SuppressedError&&SuppressedError;var _i,Ai={exports:{}},Li="object"==typeof Reflect?Reflect:null,Ui=Li&&"function"==typeof Li.apply?Li.apply:function(e,t,i){return Function.prototype.apply.call(e,t,i)};_i=Li&&"function"==typeof Li.ownKeys?Li.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var ji=Number.isNaN||function(e){return e!=e};function Fi(){Fi.init.call(this)}Ai.exports=Fi,Ai.exports.once=function(e,t){return new Promise((function(i,n){function s(i){e.removeListener(t,r),n(i)}function r(){"function"==typeof e.removeListener&&e.removeListener("error",s),i([].slice.call(arguments))}zi(e,t,r,{once:!0}),"error"!==t&&function(e,t,i){"function"==typeof e.on&&zi(e,"error",t,i)}(e,s,{once:!0})}))},Fi.EventEmitter=Fi,Fi.prototype._events=void 0,Fi.prototype._eventsCount=0,Fi.prototype._maxListeners=void 0;var Bi=10;function Vi(e){if("function"!=typeof e)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function qi(e){return void 0===e._maxListeners?Fi.defaultMaxListeners:e._maxListeners}function Ki(e,t,i,n){var s,r,o,a;if(Vi(i),void 0===(r=e._events)?(r=e._events=Object.create(null),e._eventsCount=0):(void 0!==r.newListener&&(e.emit("newListener",t,i.listener?i.listener:i),r=e._events),o=r[t]),void 0===o)o=r[t]=i,++e._eventsCount;else if("function"==typeof o?o=r[t]=n?[i,o]:[o,i]:n?o.unshift(i):o.push(i),(s=qi(e))>0&&o.length>s&&!o.warned){o.warned=!0;var c=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");c.name="MaxListenersExceededWarning",c.emitter=e,c.type=t,c.count=o.length,a=c,console&&console.warn&&console.warn(a)}return e}function Wi(){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 Gi(e,t,i){var n={fired:!1,wrapFn:void 0,target:e,type:t,listener:i},s=Wi.bind(n);return s.listener=i,n.wrapFn=s,s}function Hi(e,t,i){var n=e._events;if(void 0===n)return[];var s=n[t];return void 0===s?[]:"function"==typeof s?i?[s.listener||s]:[s]:i?function(e){for(var t=new Array(e.length),i=0;i<t.length;++i)t[i]=e[i].listener||e[i];return t}(s):Qi(s,s.length)}function Ji(e){var t=this._events;if(void 0!==t){var i=t[e];if("function"==typeof i)return 1;if(void 0!==i)return i.length}return 0}function Qi(e,t){for(var i=new Array(t),n=0;n<t;++n)i[n]=e[n];return i}function zi(e,t,i,n){if("function"==typeof e.on)n.once?e.once(t,i):e.on(t,i);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(r){n.once&&e.removeEventListener(t,s),i(r)}))}}Object.defineProperty(Fi,"defaultMaxListeners",{enumerable:!0,get:function(){return Bi},set:function(e){if("number"!=typeof e||e<0||ji(e))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+e+".");Bi=e}}),Fi.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},Fi.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||ji(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},Fi.prototype.getMaxListeners=function(){return qi(this)},Fi.prototype.emit=function(e){for(var t=[],i=1;i<arguments.length;i++)t.push(arguments[i]);var n="error"===e,s=this._events;if(void 0!==s)n=n&&void 0===s.error;else if(!n)return!1;if(n){var r;if(t.length>0&&(r=t[0]),r instanceof Error)throw r;var o=new Error("Unhandled error."+(r?" ("+r.message+")":""));throw o.context=r,o}var a=s[e];if(void 0===a)return!1;if("function"==typeof a)Ui(a,this,t);else{var c=a.length,d=Qi(a,c);for(i=0;i<c;++i)Ui(d[i],this,t)}return!0},Fi.prototype.addListener=function(e,t){return Ki(this,e,t,!1)},Fi.prototype.on=Fi.prototype.addListener,Fi.prototype.prependListener=function(e,t){return Ki(this,e,t,!0)},Fi.prototype.once=function(e,t){return Vi(t),this.on(e,Gi(this,e,t)),this},Fi.prototype.prependOnceListener=function(e,t){return Vi(t),this.prependListener(e,Gi(this,e,t)),this},Fi.prototype.removeListener=function(e,t){var i,n,s,r,o;if(Vi(t),void 0===(n=this._events))return this;if(void 0===(i=n[e]))return this;if(i===t||i.listener===t)0==--this._eventsCount?this._events=Object.create(null):(delete n[e],n.removeListener&&this.emit("removeListener",e,i.listener||t));else if("function"!=typeof i){for(s=-1,r=i.length-1;r>=0;r--)if(i[r]===t||i[r].listener===t){o=i[r].listener,s=r;break}if(s<0)return this;0===s?i.shift():function(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}(i,s),1===i.length&&(n[e]=i[0]),void 0!==n.removeListener&&this.emit("removeListener",e,o||t)}return this},Fi.prototype.off=Fi.prototype.removeListener,Fi.prototype.removeAllListeners=function(e){var t,i,n;if(void 0===(i=this._events))return this;if(void 0===i.removeListener)return 0===arguments.length?(this._events=Object.create(null),this._eventsCount=0):void 0!==i[e]&&(0==--this._eventsCount?this._events=Object.create(null):delete i[e]),this;if(0===arguments.length){var s,r=Object.keys(i);for(n=0;n<r.length;++n)"removeListener"!==(s=r[n])&&this.removeAllListeners(s);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if("function"==typeof(t=i[e]))this.removeListener(e,t);else if(void 0!==t)for(n=t.length-1;n>=0;n--)this.removeListener(e,t[n]);return this},Fi.prototype.listeners=function(e){return Hi(this,e,!0)},Fi.prototype.rawListeners=function(e){return Hi(this,e,!1)},Fi.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):Ji.call(e,t)},Fi.prototype.listenerCount=Ji,Fi.prototype.eventNames=function(){return this._eventsCount>0?_i(this._events):[]};var Yi=Ai.exports;let Xi=!0,$i=!0;function Zi(e,t,i){const n=e.match(t);return n&&n.length>=i&&parseInt(n[i],10)}function en(e,t,i){if(!e.RTCPeerConnection)return;const n=e.RTCPeerConnection.prototype,s=n.addEventListener;n.addEventListener=function(e,n){if(e!==t)return s.apply(this,arguments);const r=e=>{const t=i(e);t&&(n.handleEvent?n.handleEvent(t):n(t))};return this._eventMap=this._eventMap||{},this._eventMap[t]||(this._eventMap[t]=new Map),this._eventMap[t].set(n,r),s.apply(this,[e,r])};const r=n.removeEventListener;n.removeEventListener=function(e,i){if(e!==t||!this._eventMap||!this._eventMap[t])return r.apply(this,arguments);if(!this._eventMap[t].has(i))return r.apply(this,arguments);const n=this._eventMap[t].get(i);return this._eventMap[t].delete(i),0===this._eventMap[t].size&&delete this._eventMap[t],0===Object.keys(this._eventMap).length&&delete this._eventMap,r.apply(this,[e,n])},Object.defineProperty(n,"on"+t,{get(){return this["_on"+t]},set(e){this["_on"+t]&&(this.removeEventListener(t,this["_on"+t]),delete this["_on"+t]),e&&this.addEventListener(t,this["_on"+t]=e)},enumerable:!0,configurable:!0})}function tn(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(Xi=e,e?"adapter.js logging disabled":"adapter.js logging enabled")}function nn(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):($i=!e,"adapter.js deprecation warnings "+(e?"disabled":"enabled"))}function sn(){if("object"==typeof window){if(Xi)return;"undefined"!=typeof console&&"function"==typeof console.log&&console.log.apply(console,arguments)}}function rn(e,t){$i&&console.warn(e+" is deprecated, please use "+t+" instead.")}function on(e){return"[object Object]"===Object.prototype.toString.call(e)}function an(e){return on(e)?Object.keys(e).reduce((function(t,i){const n=on(e[i]),s=n?an(e[i]):e[i],r=n&&!Object.keys(s).length;return void 0===s||r?t:Object.assign(t,{[i]:s})}),{}):e}function cn(e,t,i){t&&!i.has(t.id)&&(i.set(t.id,t),Object.keys(t).forEach((n=>{n.endsWith("Id")?cn(e,e.get(t[n]),i):n.endsWith("Ids")&&t[n].forEach((t=>{cn(e,e.get(t),i)}))})))}function dn(e,t,i){const n=i?"outbound-rtp":"inbound-rtp",s=new Map;if(null===t)return s;const r=[];return e.forEach((e=>{"track"===e.type&&e.trackIdentifier===t.id&&r.push(e)})),r.forEach((t=>{e.forEach((i=>{i.type===n&&i.trackId===t.id&&cn(e,i,s)}))})),s}const ln=sn;function un(e,t){const i=e&&e.navigator;if(!i.mediaDevices)return;const n=function(e){if("object"!=typeof e||e.mandatory||e.optional)return e;const t={};return Object.keys(e).forEach((i=>{if("require"===i||"advanced"===i||"mediaSource"===i)return;const n="object"==typeof e[i]?e[i]:{ideal:e[i]};void 0!==n.exact&&"number"==typeof n.exact&&(n.min=n.max=n.exact);const s=function(e,t){return e?e+t.charAt(0).toUpperCase()+t.slice(1):"deviceId"===t?"sourceId":t};if(void 0!==n.ideal){t.optional=t.optional||[];let e={};"number"==typeof n.ideal?(e[s("min",i)]=n.ideal,t.optional.push(e),e={},e[s("max",i)]=n.ideal,t.optional.push(e)):(e[s("",i)]=n.ideal,t.optional.push(e))}void 0!==n.exact&&"number"!=typeof n.exact?(t.mandatory=t.mandatory||{},t.mandatory[s("",i)]=n.exact):["min","max"].forEach((e=>{void 0!==n[e]&&(t.mandatory=t.mandatory||{},t.mandatory[s(e,i)]=n[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,i){t in e&&!(i in e)&&(e[i]=e[t],delete e[t])};t((e=JSON.parse(JSON.stringify(e))).audio,"autoGainControl","googAutoGainControl"),t(e.audio,"noiseSuppression","googNoiseSuppression"),e.audio=n(e.audio)}if(e&&"object"==typeof e.video){let r=e.video.facingMode;r=r&&("object"==typeof r?r:{ideal:r});const o=t.version<66;if(r&&("user"===r.exact||"environment"===r.exact||"user"===r.ideal||"environment"===r.ideal)&&(!i.mediaDevices.getSupportedConstraints||!i.mediaDevices.getSupportedConstraints().facingMode||o)){let t;if(delete e.video.facingMode,"environment"===r.exact||"environment"===r.ideal?t=["back","rear"]:"user"!==r.exact&&"user"!==r.ideal||(t=["front"]),t)return i.mediaDevices.enumerateDevices().then((i=>{let o=(i=i.filter((e=>"videoinput"===e.kind))).find((e=>t.some((t=>e.label.toLowerCase().includes(t)))));return!o&&i.length&&t.includes("back")&&(o=i[i.length-1]),o&&(e.video.deviceId=r.exact?{exact:o.deviceId}:{ideal:o.deviceId}),e.video=n(e.video),ln("chrome: "+JSON.stringify(e)),s(e)}))}e.video=n(e.video)}return ln("chrome: "+JSON.stringify(e)),s(e)},r=function(e){return t.version>=64?e:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[e.name]||e.name,message:e.message,constraint:e.constraint||e.constraintName,toString(){return this.name+(this.message&&": ")+this.message}}};if(i.getUserMedia=function(e,t,n){s(e,(e=>{i.webkitGetUserMedia(e,t,(e=>{n&&n(r(e))}))}))}.bind(i),i.mediaDevices.getUserMedia){const e=i.mediaDevices.getUserMedia.bind(i.mediaDevices);i.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(r(e))))))}}}function hn(e){e.MediaStream=e.MediaStream||e.webkitMediaStream}function pn(e){if("object"==typeof e&&e.RTCPeerConnection&&!("ontrack"in e.RTCPeerConnection.prototype)){Object.defineProperty(e.RTCPeerConnection.prototype,"ontrack",{get(){return this._ontrack},set(e){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=e)},enumerable:!0,configurable:!0});const t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=t=>{t.stream.addEventListener("addtrack",(i=>{let n;n=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find((e=>e.track&&e.track.id===i.track.id)):{track:i.track};const s=new Event("track");s.track=i.track,s.receiver=n,s.transceiver={receiver:n},s.streams=[t.stream],this.dispatchEvent(s)})),t.stream.getTracks().forEach((i=>{let n;n=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find((e=>e.track&&e.track.id===i.id)):{track:i};const s=new Event("track");s.track=i,s.receiver=n,s.transceiver={receiver:n},s.streams=[t.stream],this.dispatchEvent(s)}))},this.addEventListener("addstream",this._ontrackpoly)),t.apply(this,arguments)}}else en(e,"track",(e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e)))}function mn(e){if("object"==typeof e&&e.RTCPeerConnection&&!("getSenders"in e.RTCPeerConnection.prototype)&&"createDTMFSender"in e.RTCPeerConnection.prototype){const t=function(e,t){return{track:t,get dtmf(){return void 0===this._dtmf&&("audio"===t.kind?this._dtmf=e.createDTMFSender(t):this._dtmf=null),this._dtmf},_pc:e}};if(!e.RTCPeerConnection.prototype.getSenders){e.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};const i=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,n){let s=i.apply(this,arguments);return s||(s=t(this,e),this._senders.push(s)),s};const n=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){n.apply(this,arguments);const t=this._senders.indexOf(e);-1!==t&&this._senders.splice(t,1)}}const i=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._senders=this._senders||[],i.apply(this,[e]),e.getTracks().forEach((e=>{this._senders.push(t(this,e))}))};const n=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){this._senders=this._senders||[],n.apply(this,[e]),e.getTracks().forEach((e=>{const t=this._senders.find((t=>t.track===e));t&&this._senders.splice(this._senders.indexOf(t),1)}))}}else if("object"==typeof e&&e.RTCPeerConnection&&"getSenders"in e.RTCPeerConnection.prototype&&"createDTMFSender"in e.RTCPeerConnection.prototype&&e.RTCRtpSender&&!("dtmf"in e.RTCRtpSender.prototype)){const t=e.RTCPeerConnection.prototype.getSenders;e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e},Object.defineProperty(e.RTCRtpSender.prototype,"dtmf",{get(){return void 0===this._dtmf&&("audio"===this.track.kind?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}}function gn(e){if(!("object"==typeof e&&e.RTCPeerConnection&&e.RTCRtpSender&&e.RTCRtpReceiver))return;if(!("getStats"in e.RTCRtpSender.prototype)){const t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e});const i=e.RTCPeerConnection.prototype.addTrack;i&&(e.RTCPeerConnection.prototype.addTrack=function(){const e=i.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){const e=this;return this._pc.getStats().then((t=>dn(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}),en(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){const e=this;return this._pc.getStats().then((t=>dn(t,e.track,!1)))}}if(!("getStats"in e.RTCRtpSender.prototype)||!("getStats"in e.RTCRtpReceiver.prototype))return;const t=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof e.MediaStreamTrack){const e=arguments[0];let t,i,n;return this.getSenders().forEach((i=>{i.track===e&&(t?n=!0:t=i)})),this.getReceivers().forEach((t=>(t.track===e&&(i?n=!0:i=t),t.track===e))),n||t&&i?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):t?t.getStats():i?i.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return t.apply(this,arguments)}}function fn(e){e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map((e=>this._shimmedLocalStreams[e][0]))};const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,i){if(!i)return t.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};const n=t.apply(this,arguments);return this._shimmedLocalStreams[i.id]?-1===this._shimmedLocalStreams[i.id].indexOf(n)&&this._shimmedLocalStreams[i.id].push(n):this._shimmedLocalStreams[i.id]=[i,n],n};const i=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._shimmedLocalStreams=this._shimmedLocalStreams||{},e.getTracks().forEach((e=>{if(this.getSenders().find((t=>t.track===e)))throw new DOMException("Track already exists.","InvalidAccessError")}));const t=this.getSenders();i.apply(this,arguments);const n=this.getSenders().filter((e=>-1===t.indexOf(e)));this._shimmedLocalStreams[e.id]=[e].concat(n)};const n=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[e.id],n.apply(this,arguments)};const s=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},e&&Object.keys(this._shimmedLocalStreams).forEach((t=>{const i=this._shimmedLocalStreams[t].indexOf(e);-1!==i&&this._shimmedLocalStreams[t].splice(i,1),1===this._shimmedLocalStreams[t].length&&delete this._shimmedLocalStreams[t]})),s.apply(this,arguments)}}function vn(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return fn(e);const i=e.RTCPeerConnection.prototype.getLocalStreams;e.RTCPeerConnection.prototype.getLocalStreams=function(){const e=i.apply(this);return this._reverseStreams=this._reverseStreams||{},e.map((e=>this._reverseStreams[e.id]))};const n=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(t){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},t.getTracks().forEach((e=>{if(this.getSenders().find((t=>t.track===e)))throw new DOMException("Track already exists.","InvalidAccessError")})),!this._reverseStreams[t.id]){const i=new e.MediaStream(t.getTracks());this._streams[t.id]=i,this._reverseStreams[i.id]=t,t=i}n.apply(this,[t])};const s=e.RTCPeerConnection.prototype.removeStream;function r(e,t){let i=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((t=>{const n=e._reverseStreams[t],s=e._streams[n.id];i=i.replace(new RegExp(s.id,"g"),n.id)})),new RTCSessionDescription({type:t.type,sdp:i})}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,i){if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");const n=[].slice.call(arguments,1);if(1!==n.length||!n[0].getTracks().find((e=>e===t)))throw new DOMException("The adapter.js addTrack polyfill only supports a single stream which is associated with the specified track.","NotSupportedError");if(this.getSenders().find((e=>e.track===t)))throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};const s=this._streams[i.id];if(s)s.addTrack(t),Promise.resolve().then((()=>{this.dispatchEvent(new Event("negotiationneeded"))}));else{const n=new e.MediaStream([t]);this._streams[i.id]=n,this._reverseStreams[n.id]=i,this.addStream(n)}return this.getSenders().find((e=>e.track===t))},["createOffer","createAnswer"].forEach((function(t){const i=e.RTCPeerConnection.prototype[t],n={[t](){const e=arguments;return arguments.length&&"function"==typeof arguments[0]?i.apply(this,[t=>{const i=r(this,t);e[0].apply(null,[i])},t=>{e[1]&&e[1].apply(null,t)},arguments[2]]):i.apply(this,arguments).then((e=>r(this,e)))}};e.RTCPeerConnection.prototype[t]=n[t]}));const o=e.RTCPeerConnection.prototype.setLocalDescription;e.RTCPeerConnection.prototype.setLocalDescription=function(){return arguments.length&&arguments[0].type?(arguments[0]=function(e,t){let i=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((t=>{const n=e._reverseStreams[t],s=e._streams[n.id];i=i.replace(new RegExp(n.id,"g"),s.id)})),new RTCSessionDescription({type:t.type,sdp:i})}(this,arguments[0]),o.apply(this,arguments)):o.apply(this,arguments)};const a=Object.getOwnPropertyDescriptor(e.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(e.RTCPeerConnection.prototype,"localDescription",{get(){const e=a.get.apply(this);return""===e.type?e:r(this,e)}}),e.RTCPeerConnection.prototype.removeTrack=function(e){if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!e._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(!(e._pc===this))throw new DOMException("Sender was not created by this connection.","InvalidAccessError");let t;this._streams=this._streams||{},Object.keys(this._streams).forEach((i=>{this._streams[i].getTracks().find((t=>e.track===t))&&(t=this._streams[i])})),t&&(1===t.getTracks().length?this.removeStream(this._reverseStreams[t.id]):t.removeTrack(e.track),this.dispatchEvent(new Event("negotiationneeded")))}}function kn(e,t){!e.RTCPeerConnection&&e.webkitRTCPeerConnection&&(e.RTCPeerConnection=e.webkitRTCPeerConnection),e.RTCPeerConnection&&t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach((function(t){const i=e.RTCPeerConnection.prototype[t],n={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),i.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=n[t]}))}function bn(e,t){en(e,"negotiationneeded",(e=>{const i=e.target;if(!(t.version<72||i.getConfiguration&&"plan-b"===i.getConfiguration().sdpSemantics)||"stable"===i.signalingState)return e}))}var yn=Object.freeze({__proto__:null,fixNegotiationNeeded:bn,shimAddTrackRemoveTrack:vn,shimAddTrackRemoveTrackWithNative:fn,shimGetSendersWithDtmf:mn,shimGetUserMedia:un,shimMediaStream:hn,shimOnTrack:pn,shimPeerConnection:kn,shimSenderReceiverGetStats:gn});function Tn(e,t){const i=e&&e.navigator,n=e&&e.MediaStreamTrack;if(i.getUserMedia=function(e,t,n){rn("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),i.mediaDevices.getUserMedia(e).then(t,n)},!(t.version>55&&"autoGainControl"in i.mediaDevices.getSupportedConstraints())){const e=function(e,t,i){t in e&&!(i in e)&&(e[i]=e[t],delete e[t])},t=i.mediaDevices.getUserMedia.bind(i.mediaDevices);if(i.mediaDevices.getUserMedia=function(i){return"object"==typeof i&&"object"==typeof i.audio&&(i=JSON.parse(JSON.stringify(i)),e(i.audio,"autoGainControl","mozAutoGainControl"),e(i.audio,"noiseSuppression","mozNoiseSuppression")),t(i)},n&&n.prototype.getSettings){const t=n.prototype.getSettings;n.prototype.getSettings=function(){const i=t.apply(this,arguments);return e(i,"mozAutoGainControl","autoGainControl"),e(i,"mozNoiseSuppression","noiseSuppression"),i}}if(n&&n.prototype.applyConstraints){const t=n.prototype.applyConstraints;n.prototype.applyConstraints=function(i){return"audio"===this.kind&&"object"==typeof i&&(i=JSON.parse(JSON.stringify(i)),e(i,"autoGainControl","mozAutoGainControl"),e(i,"noiseSuppression","mozNoiseSuppression")),t.apply(this,[i])}}}}function Cn(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 Sn(e,t){if("object"!=typeof e||!e.RTCPeerConnection&&!e.mozRTCPeerConnection)return;!e.RTCPeerConnection&&e.mozRTCPeerConnection&&(e.RTCPeerConnection=e.mozRTCPeerConnection),t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach((function(t){const i=e.RTCPeerConnection.prototype[t],n={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),i.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=n[t]}));const i={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},n=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){const[e,s,r]=arguments;return n.apply(this,[e||null]).then((e=>{if(t.version<53&&!s)try{e.forEach((e=>{e.type=i[e.type]||e.type}))}catch(t){if("TypeError"!==t.name)throw t;e.forEach(((t,n)=>{e.set(n,Object.assign({},t,{type:i[t.type]||t.type}))}))}return e})).then(s,r)}}function En(e){if("object"!=typeof e||!e.RTCPeerConnection||!e.RTCRtpSender)return;if(e.RTCRtpSender&&"getStats"in e.RTCRtpSender.prototype)return;const t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e});const i=e.RTCPeerConnection.prototype.addTrack;i&&(e.RTCPeerConnection.prototype.addTrack=function(){const e=i.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function wn(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}),en(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function Pn(e){e.RTCPeerConnection&&!("removeStream"in e.RTCPeerConnection.prototype)&&(e.RTCPeerConnection.prototype.removeStream=function(e){rn("removeStream","removeTrack"),this.getSenders().forEach((t=>{t.track&&e.getTracks().includes(t.track)&&this.removeTrack(t)}))})}function Rn(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)}function In(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.addTransceiver;t&&(e.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let e=arguments[1]&&arguments[1].sendEncodings;void 0===e&&(e=[]),e=[...e];const i=e.length>0;i&&e.forEach((e=>{if("rid"in e){if(!/^[a-z0-9]{0,16}$/i.test(e.rid))throw new TypeError("Invalid RID value provided.")}if("scaleResolutionDownBy"in e&&!(parseFloat(e.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in e&&!(parseFloat(e.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")}));const n=t.apply(this,arguments);if(i){const{sender:t}=n,i=t.getParameters();(!("encodings"in i)||1===i.encodings.length&&0===Object.keys(i.encodings[0]).length)&&(i.encodings=e,t.sendEncodings=e,this.setParametersPromises.push(t.setParameters(i).then((()=>{delete t.sendEncodings})).catch((()=>{delete t.sendEncodings}))))}return n})}function On(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 xn(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 Dn(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 Mn=Object.freeze({__proto__:null,shimAddTransceiver:In,shimCreateAnswer:Dn,shimCreateOffer:xn,shimGetDisplayMedia:function(e,t){e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||e.navigator.mediaDevices&&(e.navigator.mediaDevices.getDisplayMedia=function(i){if(!i||!i.video){const e=new DOMException("getDisplayMedia without video constraints is undefined");return e.name="NotFoundError",e.code=8,Promise.reject(e)}return!0===i.video?i.video={mediaSource:t}:i.video.mediaSource=t,e.navigator.mediaDevices.getUserMedia(i)})},shimGetParameters:On,shimGetUserMedia:Tn,shimOnTrack:Cn,shimPeerConnection:Sn,shimRTCDataChannel:Rn,shimReceiverGetStats:wn,shimRemoveStream:Pn,shimSenderGetStats:En});function Nn(e){if("object"==typeof e&&e.RTCPeerConnection){if("getLocalStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in e.RTCPeerConnection.prototype)){const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addStream=function(e){this._localStreams||(this._localStreams=[]),this._localStreams.includes(e)||this._localStreams.push(e),e.getAudioTracks().forEach((i=>t.call(this,i,e))),e.getVideoTracks().forEach((i=>t.call(this,i,e)))},e.RTCPeerConnection.prototype.addTrack=function(e){for(var i=arguments.length,n=new Array(i>1?i-1:0),s=1;s<i;s++)n[s-1]=arguments[s];return n&&n.forEach((e=>{this._localStreams?this._localStreams.includes(e)||this._localStreams.push(e):this._localStreams=[e]})),t.apply(this,arguments)}}"removeStream"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.removeStream=function(e){this._localStreams||(this._localStreams=[]);const t=this._localStreams.indexOf(e);if(-1===t)return;this._localStreams.splice(t,1);const i=e.getTracks();this.getSenders().forEach((e=>{i.includes(e.track)&&this.removeTrack(e)}))})}}function _n(e){if("object"==typeof e&&e.RTCPeerConnection&&("getRemoteStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!("onaddstream"in e.RTCPeerConnection.prototype))){Object.defineProperty(e.RTCPeerConnection.prototype,"onaddstream",{get(){return this._onaddstream},set(e){this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=e),this.addEventListener("track",this._onaddstreampoly=e=>{e.streams.forEach((e=>{if(this._remoteStreams||(this._remoteStreams=[]),this._remoteStreams.includes(e))return;this._remoteStreams.push(e);const t=new Event("addstream");t.stream=e,this.dispatchEvent(t)}))})}});const t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){const e=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(t){t.streams.forEach((t=>{if(e._remoteStreams||(e._remoteStreams=[]),e._remoteStreams.indexOf(t)>=0)return;e._remoteStreams.push(t);const i=new Event("addstream");i.stream=t,e.dispatchEvent(i)}))}),t.apply(e,arguments)}}}function An(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype,i=t.createOffer,n=t.createAnswer,s=t.setLocalDescription,r=t.setRemoteDescription,o=t.addIceCandidate;t.createOffer=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},t.createAnswer=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};let a=function(e,t,i){const n=s.apply(this,[e]);return i?(n.then(t,i),Promise.resolve()):n};t.setLocalDescription=a,a=function(e,t,i){const n=r.apply(this,[e]);return i?(n.then(t,i),Promise.resolve()):n},t.setRemoteDescription=a,a=function(e,t,i){const n=o.apply(this,[e]);return i?(n.then(t,i),Promise.resolve()):n},t.addIceCandidate=a}function Ln(e){const t=e&&e.navigator;if(t.mediaDevices&&t.mediaDevices.getUserMedia){const e=t.mediaDevices,i=e.getUserMedia.bind(e);t.mediaDevices.getUserMedia=e=>i(Un(e))}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=function(e,i,n){t.mediaDevices.getUserMedia(e).then(i,n)}.bind(t))}function Un(e){return e&&void 0!==e.video?Object.assign({},e,{video:an(e.video)}):e}function jn(e){if(!e.RTCPeerConnection)return;const t=e.RTCPeerConnection;e.RTCPeerConnection=function(e,i){if(e&&e.iceServers){const t=[];for(let i=0;i<e.iceServers.length;i++){let n=e.iceServers[i];void 0===n.urls&&n.url?(rn("RTCIceServer.url","RTCIceServer.urls"),n=JSON.parse(JSON.stringify(n)),n.urls=n.url,delete n.url,t.push(n)):t.push(e.iceServers[i])}e.iceServers=t}return new t(e,i)},e.RTCPeerConnection.prototype=t.prototype,"generateCertificate"in t&&Object.defineProperty(e.RTCPeerConnection,"generateCertificate",{get:()=>t.generateCertificate})}function Fn(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 Bn(e){const t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(e){if(e){void 0!==e.offerToReceiveAudio&&(e.offerToReceiveAudio=!!e.offerToReceiveAudio);const t=this.getTransceivers().find((e=>"audio"===e.receiver.track.kind));!1===e.offerToReceiveAudio&&t?"sendrecv"===t.direction?t.setDirection?t.setDirection("sendonly"):t.direction="sendonly":"recvonly"===t.direction&&(t.setDirection?t.setDirection("inactive"):t.direction="inactive"):!0!==e.offerToReceiveAudio||t||this.addTransceiver("audio",{direction:"recvonly"}),void 0!==e.offerToReceiveVideo&&(e.offerToReceiveVideo=!!e.offerToReceiveVideo);const i=this.getTransceivers().find((e=>"video"===e.receiver.track.kind));!1===e.offerToReceiveVideo&&i?"sendrecv"===i.direction?i.setDirection?i.setDirection("sendonly"):i.direction="sendonly":"recvonly"===i.direction&&(i.setDirection?i.setDirection("inactive"):i.direction="inactive"):!0!==e.offerToReceiveVideo||i||this.addTransceiver("video",{direction:"recvonly"})}return t.apply(this,arguments)}}function Vn(e){"object"!=typeof e||e.AudioContext||(e.AudioContext=e.webkitAudioContext)}var qn=Object.freeze({__proto__:null,shimAudioContext:Vn,shimCallbacksAPI:An,shimConstraints:Un,shimCreateOfferLegacy:Bn,shimGetUserMedia:Ln,shimLocalStreamsAPI:Nn,shimRTCIceServerUrls:jn,shimRemoteStreamsAPI:_n,shimTrackEventTransceiver:Fn}),Kn={exports:{}};!function(e){const t={generateIdentifier:function(){return Math.random().toString(36).substring(2,12)}};t.localCName=t.generateIdentifier(),t.splitLines=function(e){return e.trim().split("\n").map((e=>e.trim()))},t.splitSections=function(e){return e.split("\nm=").map(((e,t)=>(t>0?"m="+e:e).trim()+"\r\n"))},t.getDescription=function(e){const i=t.splitSections(e);return i&&i[0]},t.getMediaSections=function(e){const i=t.splitSections(e);return i.shift(),i},t.matchPrefix=function(e,i){return t.splitLines(e).filter((e=>0===e.indexOf(i)))},t.parseCandidate=function(e){let t;t=0===e.indexOf("a=candidate:")?e.substring(12).split(" "):e.substring(10).split(" ");const i={foundation:t[0],component:{1:"rtp",2:"rtcp"}[t[1]]||t[1],protocol:t[2].toLowerCase(),priority:parseInt(t[3],10),ip:t[4],address:t[4],port:parseInt(t[5],10),type:t[7]};for(let e=8;e<t.length;e+=2)switch(t[e]){case"raddr":i.relatedAddress=t[e+1];break;case"rport":i.relatedPort=parseInt(t[e+1],10);break;case"tcptype":i.tcpType=t[e+1];break;case"ufrag":i.ufrag=t[e+1],i.usernameFragment=t[e+1];break;default:void 0===i[t[e]]&&(i[t[e]]=t[e+1])}return i},t.writeCandidate=function(e){const t=[];t.push(e.foundation);const i=e.component;"rtp"===i?t.push(1):"rtcp"===i?t.push(2):t.push(i),t.push(e.protocol.toUpperCase()),t.push(e.priority),t.push(e.address||e.ip),t.push(e.port);const n=e.type;return t.push("typ"),t.push(n),"host"!==n&&e.relatedAddress&&e.relatedPort&&(t.push("raddr"),t.push(e.relatedAddress),t.push("rport"),t.push(e.relatedPort)),e.tcpType&&"tcp"===e.protocol.toLowerCase()&&(t.push("tcptype"),t.push(e.tcpType)),(e.usernameFragment||e.ufrag)&&(t.push("ufrag"),t.push(e.usernameFragment||e.ufrag)),"candidate:"+t.join(" ")},t.parseIceOptions=function(e){return e.substring(14).split(" ")},t.parseRtpMap=function(e){let t=e.substring(9).split(" ");const i={payloadType:parseInt(t.shift(),10)};return t=t[0].split("/"),i.name=t[0],i.clockRate=parseInt(t[1],10),i.channels=3===t.length?parseInt(t[2],10):1,i.numChannels=i.channels,i},t.writeRtpMap=function(e){let t=e.payloadType;void 0!==e.preferredPayloadType&&(t=e.preferredPayloadType);const i=e.channels||e.numChannels||1;return"a=rtpmap:"+t+" "+e.name+"/"+e.clockRate+(1!==i?"/"+i:"")+"\r\n"},t.parseExtmap=function(e){const t=e.substring(9).split(" ");return{id:parseInt(t[0],10),direction:t[0].indexOf("/")>0?t[0].split("/")[1]:"sendrecv",uri:t[1],attributes:t.slice(2).join(" ")}},t.writeExtmap=function(e){return"a=extmap:"+(e.id||e.preferredId)+(e.direction&&"sendrecv"!==e.direction?"/"+e.direction:"")+" "+e.uri+(e.attributes?" "+e.attributes:"")+"\r\n"},t.parseFmtp=function(e){const t={};let i;const n=e.substring(e.indexOf(" ")+1).split(";");for(let e=0;e<n.length;e++)i=n[e].trim().split("="),t[i[0].trim()]=i[1];return t},t.writeFmtp=function(e){let t="",i=e.payloadType;if(void 0!==e.preferredPayloadType&&(i=e.preferredPayloadType),e.parameters&&Object.keys(e.parameters).length){const n=[];Object.keys(e.parameters).forEach((t=>{void 0!==e.parameters[t]?n.push(t+"="+e.parameters[t]):n.push(t)})),t+="a=fmtp:"+i+" "+n.join(";")+"\r\n"}return t},t.parseRtcpFb=function(e){const t=e.substring(e.indexOf(" ")+1).split(" ");return{type:t.shift(),parameter:t.join(" ")}},t.writeRtcpFb=function(e){let t="",i=e.payloadType;return void 0!==e.preferredPayloadType&&(i=e.preferredPayloadType),e.rtcpFeedback&&e.rtcpFeedback.length&&e.rtcpFeedback.forEach((e=>{t+="a=rtcp-fb:"+i+" "+e.type+(e.parameter&&e.parameter.length?" "+e.parameter:"")+"\r\n"})),t},t.parseSsrcMedia=function(e){const t=e.indexOf(" "),i={ssrc:parseInt(e.substring(7,t),10)},n=e.indexOf(":",t);return n>-1?(i.attribute=e.substring(t+1,n),i.value=e.substring(n+1)):i.attribute=e.substring(t+1),i},t.parseSsrcGroup=function(e){const t=e.substring(13).split(" ");return{semantics:t.shift(),ssrcs:t.map((e=>parseInt(e,10)))}},t.getMid=function(e){const i=t.matchPrefix(e,"a=mid:")[0];if(i)return i.substring(6)},t.parseFingerprint=function(e){const t=e.substring(14).split(" ");return{algorithm:t[0].toLowerCase(),value:t[1].toUpperCase()}},t.getDtlsParameters=function(e,i){return{role:"auto",fingerprints:t.matchPrefix(e+i,"a=fingerprint:").map(t.parseFingerprint)}},t.writeDtlsParameters=function(e,t){let i="a=setup:"+t+"\r\n";return e.fingerprints.forEach((e=>{i+="a=fingerprint:"+e.algorithm+" "+e.value+"\r\n"})),i},t.parseCryptoLine=function(e){const t=e.substring(9).split(" ");return{tag:parseInt(t[0],10),cryptoSuite:t[1],keyParams:t[2],sessionParams:t.slice(3)}},t.writeCryptoLine=function(e){return"a=crypto:"+e.tag+" "+e.cryptoSuite+" "+("object"==typeof e.keyParams?t.writeCryptoKeyParams(e.keyParams):e.keyParams)+(e.sessionParams?" "+e.sessionParams.join(" "):"")+"\r\n"},t.parseCryptoKeyParams=function(e){if(0!==e.indexOf("inline:"))return null;const t=e.substring(7).split("|");return{keyMethod:"inline",keySalt:t[0],lifeTime:t[1],mkiValue:t[2]?t[2].split(":")[0]:void 0,mkiLength:t[2]?t[2].split(":")[1]:void 0}},t.writeCryptoKeyParams=function(e){return e.keyMethod+":"+e.keySalt+(e.lifeTime?"|"+e.lifeTime:"")+(e.mkiValue&&e.mkiLength?"|"+e.mkiValue+":"+e.mkiLength:"")},t.getCryptoParameters=function(e,i){return t.matchPrefix(e+i,"a=crypto:").map(t.parseCryptoLine)},t.getIceParameters=function(e,i){const n=t.matchPrefix(e+i,"a=ice-ufrag:")[0],s=t.matchPrefix(e+i,"a=ice-pwd:")[0];return n&&s?{usernameFragment:n.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 i={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},n=t.splitLines(e)[0].split(" ");i.profile=n[2];for(let s=3;s<n.length;s++){const r=n[s],o=t.matchPrefix(e,"a=rtpmap:"+r+" ")[0];if(o){const n=t.parseRtpMap(o),s=t.matchPrefix(e,"a=fmtp:"+r+" ");switch(n.parameters=s.length?t.parseFmtp(s[0]):{},n.rtcpFeedback=t.matchPrefix(e,"a=rtcp-fb:"+r+" ").map(t.parseRtcpFb),i.codecs.push(n),n.name.toUpperCase()){case"RED":case"ULPFEC":i.fecMechanisms.push(n.name.toUpperCase())}}}t.matchPrefix(e,"a=extmap:").forEach((e=>{i.headerExtensions.push(t.parseExtmap(e))}));const s=t.matchPrefix(e,"a=rtcp-fb:* ").map(t.parseRtcpFb);return i.codecs.forEach((e=>{s.forEach((t=>{e.rtcpFeedback.find((e=>e.type===t.type&&e.parameter===t.parameter))||e.rtcpFeedback.push(t)}))})),i},t.writeRtpDescription=function(e,i){let n="";n+="m="+e+" ",n+=i.codecs.length>0?"9":"0",n+=" "+(i.profile||"UDP/TLS/RTP/SAVPF")+" ",n+=i.codecs.map((e=>void 0!==e.preferredPayloadType?e.preferredPayloadType:e.payloadType)).join(" ")+"\r\n",n+="c=IN IP4 0.0.0.0\r\n",n+="a=rtcp:9 IN IP4 0.0.0.0\r\n",i.codecs.forEach((e=>{n+=t.writeRtpMap(e),n+=t.writeFmtp(e),n+=t.writeRtcpFb(e)}));let s=0;return i.codecs.forEach((e=>{e.maxptime>s&&(s=e.maxptime)})),s>0&&(n+="a=maxptime:"+s+"\r\n"),i.headerExtensions&&i.headerExtensions.forEach((e=>{n+=t.writeExtmap(e)})),n},t.parseRtpEncodingParameters=function(e){const i=[],n=t.parseRtpParameters(e),s=-1!==n.fecMechanisms.indexOf("RED"),r=-1!==n.fecMechanisms.indexOf("ULPFEC"),o=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"cname"===e.attribute)),a=o.length>0&&o[0].ssrc;let c;const d=t.matchPrefix(e,"a=ssrc-group:FID").map((e=>e.substring(17).split(" ").map((e=>parseInt(e,10)))));d.length>0&&d[0].length>1&&d[0][0]===a&&(c=d[0][1]),n.codecs.forEach((e=>{if("RTX"===e.name.toUpperCase()&&e.parameters.apt){let t={ssrc:a,codecPayloadType:parseInt(e.parameters.apt,10)};a&&c&&(t.rtx={ssrc:c}),i.push(t),s&&(t=JSON.parse(JSON.stringify(t)),t.fec={ssrc:a,mechanism:r?"red+ulpfec":"red"},i.push(t))}})),0===i.length&&a&&i.push({ssrc:a});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,i.forEach((e=>{e.maxBitrate=l}))),i},t.parseRtcpParameters=function(e){const i={},n=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"cname"===e.attribute))[0];n&&(i.cname=n.value,i.ssrc=n.ssrc);const s=t.matchPrefix(e,"a=rtcp-rsize");i.reducedSize=s.length>0,i.compound=0===s.length;const r=t.matchPrefix(e,"a=rtcp-mux");return i.mux=r.length>0,i},t.writeRtcpParameters=function(e){let t="";return e.reducedSize&&(t+="a=rtcp-rsize\r\n"),e.mux&&(t+="a=rtcp-mux\r\n"),void 0!==e.ssrc&&e.cname&&(t+="a=ssrc:"+e.ssrc+" cname:"+e.cname+"\r\n"),t},t.parseMsid=function(e){let i;const n=t.matchPrefix(e,"a=msid:");if(1===n.length)return i=n[0].substring(7).split(" "),{stream:i[0],track:i[1]};const s=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"msid"===e.attribute));return s.length>0?(i=s[0].value.split(" "),{stream:i[0],track:i[1]}):void 0},t.parseSctpDescription=function(e){const i=t.parseMLine(e),n=t.matchPrefix(e,"a=max-message-size:");let s;n.length>0&&(s=parseInt(n[0].substring(19),10)),isNaN(s)&&(s=65536);const r=t.matchPrefix(e,"a=sctp-port:");if(r.length>0)return{port:parseInt(r[0].substring(12),10),protocol:i.fmt,maxMessageSize:s};const o=t.matchPrefix(e,"a=sctpmap:");if(o.length>0){const e=o[0].substring(10).split(" ");return{port:parseInt(e[0],10),protocol:e[1],maxMessageSize:s}}},t.writeSctpDescription=function(e,t){let i=[];return i="DTLS/SCTP"!==e.protocol?["m="+e.kind+" 9 "+e.protocol+" "+t.protocol+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctp-port:"+t.port+"\r\n"]:["m="+e.kind+" 9 "+e.protocol+" "+t.port+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctpmap:"+t.port+" "+t.protocol+" 65535\r\n"],void 0!==t.maxMessageSize&&i.push("a=max-message-size:"+t.maxMessageSize+"\r\n"),i.join("")},t.generateSessionId=function(){return Math.random().toString().substr(2,22)},t.writeSessionBoilerplate=function(e,i,n){let s;const r=void 0!==i?i:2;s=e||t.generateSessionId();return"v=0\r\no="+(n||"thisisadapterortc")+" "+s+" "+r+" IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\n"},t.getDirection=function(e,i){const n=t.splitLines(e);for(let e=0;e<n.length;e++)switch(n[e]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return n[e].substring(2)}return i?t.getDirection(i):"sendrecv"},t.getKind=function(e){return t.splitLines(e)[0].split(" ")[0].substring(2)},t.isRejected=function(e){return"0"===e.split(" ",2)[1]},t.parseMLine=function(e){const i=t.splitLines(e)[0].substring(2).split(" ");return{kind:i[0],port:parseInt(i[1],10),protocol:i[2],fmt:i.slice(3).join(" ")}},t.parseOLine=function(e){const i=t.matchPrefix(e,"o=")[0].substring(2).split(" ");return{username:i[0],sessionId:i[1],sessionVersion:parseInt(i[2],10),netType:i[3],addressType:i[4],address:i[5]}},t.isValidSDP=function(e){if("string"!=typeof e||0===e.length)return!1;const i=t.splitLines(e);for(let e=0;e<i.length;e++)if(i[e].length<2||"="!==i[e].charAt(1))return!1;return!0},e.exports=t}(Kn);var Wn=Kn.exports,Gn=bi(Wn),Hn=t({__proto__:null,default:Gn},[Wn]);function Jn(e){if(!e.RTCIceCandidate||e.RTCIceCandidate&&"foundation"in e.RTCIceCandidate.prototype)return;const t=e.RTCIceCandidate;e.RTCIceCandidate=function(e){if("object"==typeof e&&e.candidate&&0===e.candidate.indexOf("a=")&&((e=JSON.parse(JSON.stringify(e))).candidate=e.candidate.substring(2)),e.candidate&&e.candidate.length){const i=new t(e),n=Gn.parseCandidate(e.candidate);for(const e in n)e in i||Object.defineProperty(i,e,{value:n[e]});return i.toJSON=function(){return{candidate:i.candidate,sdpMid:i.sdpMid,sdpMLineIndex:i.sdpMLineIndex,usernameFragment:i.usernameFragment}},i}return new t(e)},e.RTCIceCandidate.prototype=t.prototype,en(e,"icecandidate",(t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new e.RTCIceCandidate(t.candidate),writable:"false"}),t)))}function Qn(e){!e.RTCIceCandidate||e.RTCIceCandidate&&"relayProtocol"in e.RTCIceCandidate.prototype||en(e,"icecandidate",(e=>{if(e.candidate){const t=Gn.parseCandidate(e.candidate.candidate);"relay"===t.type&&(e.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[t.priority>>24])}return e}))}function zn(e,t){if(!e.RTCPeerConnection)return;"sctp"in e.RTCPeerConnection.prototype||Object.defineProperty(e.RTCPeerConnection.prototype,"sctp",{get(){return void 0===this._sctp?null:this._sctp}});const i=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,"chrome"===t.browser&&t.version>=76){const{sdpSemantics:e}=this.getConfiguration();"plan-b"===e&&Object.defineProperty(this,"sctp",{get(){return void 0===this._sctp?null:this._sctp},enumerable:!0,configurable:!0})}if(function(e){if(!e||!e.sdp)return!1;const t=Gn.splitSections(e.sdp);return t.shift(),t.some((e=>{const t=Gn.parseMLine(e);return t&&"application"===t.kind&&-1!==t.protocol.indexOf("SCTP")}))}(arguments[0])){const e=function(e){const t=e.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(null===t||t.length<2)return-1;const i=parseInt(t[1],10);return i!=i?-1:i}(arguments[0]),i=function(e){let i=65536;return"firefox"===t.browser&&(i=t.version<57?-1===e?16384:2147483637:t.version<60?57===t.version?65535:65536:2147483637),i}(e),n=function(e,i){let n=65536;"firefox"===t.browser&&57===t.version&&(n=65535);const s=Gn.matchPrefix(e.sdp,"a=max-message-size:");return s.length>0?n=parseInt(s[0].substring(19),10):"firefox"===t.browser&&-1!==i&&(n=2147483637),n}(arguments[0],e);let s;s=0===i&&0===n?Number.POSITIVE_INFINITY:0===i||0===n?Math.max(i,n):Math.min(i,n);const r={};Object.defineProperty(r,"maxMessageSize",{get:()=>s}),this._sctp=r}return i.apply(this,arguments)}}function Yn(e){if(!e.RTCPeerConnection||!("createDataChannel"in e.RTCPeerConnection.prototype))return;function t(e,t){const i=e.send;e.send=function(){const n=arguments[0],s=n.length||n.size||n.byteLength;if("open"===e.readyState&&t.sctp&&s>t.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+t.sctp.maxMessageSize+" bytes)");return i.apply(e,arguments)}}const i=e.RTCPeerConnection.prototype.createDataChannel;e.RTCPeerConnection.prototype.createDataChannel=function(){const e=i.apply(this,arguments);return t(e,this),e},en(e,"datachannel",(e=>(t(e.channel,e.target),e)))}function Xn(e){if(!e.RTCPeerConnection||"connectionState"in e.RTCPeerConnection.prototype)return;const t=e.RTCPeerConnection.prototype;Object.defineProperty(t,"connectionState",{get(){return{completed:"connected",checking:"connecting"}[this.iceConnectionState]||this.iceConnectionState},enumerable:!0,configurable:!0}),Object.defineProperty(t,"onconnectionstatechange",{get(){return this._onconnectionstatechange||null},set(e){this._onconnectionstatechange&&(this.removeEventListener("connectionstatechange",this._onconnectionstatechange),delete this._onconnectionstatechange),e&&this.addEventListener("connectionstatechange",this._onconnectionstatechange=e)},enumerable:!0,configurable:!0}),["setLocalDescription","setRemoteDescription"].forEach((e=>{const i=t[e];t[e]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=e=>{const t=e.target;if(t._lastConnectionState!==t.connectionState){t._lastConnectionState=t.connectionState;const i=new Event("connectionstatechange",e);t.dispatchEvent(i)}return e},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),i.apply(this,arguments)}}))}function $n(e,t){if(!e.RTCPeerConnection)return;if("chrome"===t.browser&&t.version>=71)return;if("safari"===t.browser&&t.version>=605)return;const i=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(t){if(t&&t.sdp&&-1!==t.sdp.indexOf("\na=extmap-allow-mixed")){const i=t.sdp.split("\n").filter((e=>"a=extmap-allow-mixed"!==e.trim())).join("\n");e.RTCSessionDescription&&t instanceof e.RTCSessionDescription?arguments[0]=new e.RTCSessionDescription({type:t.type,sdp:i}):t.sdp=i}return i.apply(this,arguments)}}function Zn(e,t){if(!e.RTCPeerConnection||!e.RTCPeerConnection.prototype)return;const i=e.RTCPeerConnection.prototype.addIceCandidate;i&&0!==i.length&&(e.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?("chrome"===t.browser&&t.version<78||"firefox"===t.browser&&t.version<68||"safari"===t.browser)&&arguments[0]&&""===arguments[0].candidate?Promise.resolve():i.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}function es(e,t){if(!e.RTCPeerConnection||!e.RTCPeerConnection.prototype)return;const i=e.RTCPeerConnection.prototype.setLocalDescription;i&&0!==i.length&&(e.RTCPeerConnection.prototype.setLocalDescription=function(){let e=arguments[0]||{};if("object"!=typeof e||e.type&&e.sdp)return i.apply(this,arguments);if(e={type:e.type,sdp:e.sdp},!e.type)switch(this.signalingState){case"stable":case"have-local-offer":case"have-remote-pranswer":e.type="offer";break;default:e.type="answer"}if(e.sdp||"offer"!==e.type&&"answer"!==e.type)return i.apply(this,[e]);return("offer"===e.type?this.createOffer:this.createAnswer).apply(this).then((e=>i.apply(this,[e])))})}var ts=Object.freeze({__proto__:null,removeExtmapAllowMixed:$n,shimAddIceCandidateNullOrEmpty:Zn,shimConnectionState:Xn,shimMaxMessageSize:zn,shimParameterlessSetLocalDescription:es,shimRTCIceCandidate:Jn,shimRTCIceCandidateRelayProtocol:Qn,shimSendThrowTypeError:Yn});!function(){let{window:e}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{shimChrome:!0,shimFirefox:!0,shimSafari:!0};const i=sn,n=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:i}=e;if(i.userAgentData&&i.userAgentData.brands){const e=i.userAgentData.brands.find((e=>"Chromium"===e.brand));if(e)return{browser:"chrome",version:parseInt(e.version,10)}}if(i.mozGetUserMedia)t.browser="firefox",t.version=Zi(i.userAgent,/Firefox\/(\d+)\./,1);else if(i.webkitGetUserMedia||!1===e.isSecureContext&&e.webkitRTCPeerConnection)t.browser="chrome",t.version=Zi(i.userAgent,/Chrom(e|ium)\/(\d+)\./,2);else{if(!e.RTCPeerConnection||!i.userAgent.match(/AppleWebKit\/(\d+)\./))return t.browser="Not a supported browser.",t;t.browser="safari",t.version=Zi(i.userAgent,/AppleWebKit\/(\d+)\./,1),t.supportsUnifiedPlan=e.RTCRtpTransceiver&&"currentDirection"in e.RTCRtpTransceiver.prototype}return t}(e),s={browserDetails:n,commonShim:ts,extractVersion:Zi,disableLog:tn,disableWarnings:nn,sdp:Hn};switch(n.browser){case"chrome":if(!yn||!kn||!t.shimChrome)return i("Chrome shim is not included in this adapter release."),s;if(null===n.version)return i("Chrome shim can not determine version, not shimming."),s;i("adapter.js shimming chrome."),s.browserShim=yn,Zn(e,n),es(e),un(e,n),hn(e),kn(e,n),pn(e),vn(e,n),mn(e),gn(e),bn(e,n),Jn(e),Qn(e),Xn(e),zn(e,n),Yn(e),$n(e,n);break;case"firefox":if(!Mn||!Sn||!t.shimFirefox)return i("Firefox shim is not included in this adapter release."),s;i("adapter.js shimming firefox."),s.browserShim=Mn,Zn(e,n),es(e),Tn(e,n),Sn(e,n),Cn(e),Pn(e),En(e),wn(e),Rn(e),In(e),On(e),xn(e),Dn(e),Jn(e),Xn(e),zn(e,n),Yn(e);break;case"safari":if(!qn||!t.shimSafari)return i("Safari shim is not included in this adapter release."),s;i("adapter.js shimming safari."),s.browserShim=qn,Zn(e,n),es(e),jn(e),Bn(e),An(e),Nn(e),_n(e),Fn(e),Ln(e),Vn(e),Jn(e),Qn(e),zn(e,n),Yn(e),$n(e,n);break;default:i("Unsupported browser!")}}({window:"undefined"==typeof window?void 0:window});const is="AES-GCM",ns="lk_e2ee",ss={sharedKey:!1,ratchetSalt:"LKFrameEncryptionKey",ratchetWindowSize:8,failureTolerance:10,keyringSize:16};var rs,os;function as(){return ds()||cs()}function cs(){return void 0!==window.RTCRtpScriptTransform}function ds(){return void 0!==window.RTCRtpSender&&void 0!==window.RTCRtpSender.prototype.createEncodedStreams}function ls(e){return Di(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 us(e){return Di(this,void 0,void 0,(function*(){return yield crypto.subtle.importKey("raw",e,"HKDF",!1,["deriveBits","deriveKey"])}))}function hs(e,t){const i=(new TextEncoder).encode(t);switch(e){case"HKDF":return{name:"HKDF",salt:i,hash:"SHA-256",info:new ArrayBuffer(128)};case"PBKDF2":return{name:"PBKDF2",salt:i,hash:"SHA-256",iterations:1e5};default:throw new Error("algorithm ".concat(e," is currently unsupported"))}}e.KeyProviderEvent=void 0,(rs=e.KeyProviderEvent||(e.KeyProviderEvent={})).SetKey="setKey",rs.RatchetRequest="ratchetRequest",rs.KeyRatcheted="keyRatcheted",e.KeyHandlerEvent=void 0,(e.KeyHandlerEvent||(e.KeyHandlerEvent={})).KeyRatcheted="keyRatcheted",e.EncryptionEvent=void 0,(os=e.EncryptionEvent||(e.EncryptionEvent={})).ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",os.EncryptionError="encryptionError",e.CryptorEvent=void 0,(e.CryptorEvent||(e.CryptorEvent={})).Error="cryptorError";class ps extends Yi.EventEmitter{constructor(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};super(),this.onKeyRatcheted=(e,t)=>{Ei.debug("key ratcheted event received",{material:e,keyIndex:t})},this.keyInfoMap=new Map,this.options=Object.assign(Object.assign({},ss),t),this.on(e.KeyProviderEvent.KeyRatcheted,this.onKeyRatcheted)}onSetEncryptionKey(t,i,n){const s={key:t,participantIdentity:i,keyIndex:n};if(!this.options.sharedKey&&!i)throw new Error("participant identity needs to be passed for encryption key if sharedKey option is false");this.keyInfoMap.set("".concat(null!=i?i:"shared","-").concat(null!=n?n:0),s),this.emit(e.KeyProviderEvent.SetKey,s)}getKeys(){return Array.from(this.keyInfoMap.values())}getOptions(){return this.options}ratchetKey(t,i){this.emit(e.KeyProviderEvent.RatchetRequest,t,i)}}class ms extends Error{constructor(e,t){super(t||"an error has occured"),this.code=e}}class gs extends ms{constructor(e,t,i){super(1,e),this.status=i,this.reason=t}}class fs extends ms{constructor(e){super(21,null!=e?e:"device is unsupported")}}class vs extends ms{constructor(e){super(20,null!=e?e:"track is invalid")}}class ks extends ms{constructor(e){super(10,null!=e?e:"unsupported server")}}class bs extends ms{constructor(e){super(12,null!=e?e:"unexpected connection state")}}class ys extends ms{constructor(e){super(13,null!=e?e:"unable to negotiate")}}class Ts extends ms{constructor(e,t){super(15,e),this.reason=t}}var Cs,Ss,Es,ws,Ps,Rs;e.MediaDeviceFailure=void 0,(Cs=e.MediaDeviceFailure||(e.MediaDeviceFailure={})).PermissionDenied="PermissionDenied",Cs.NotFound="NotFound",Cs.DeviceInUse="DeviceInUse",Cs.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.CryptorErrorReason=void 0,(Ss=e.CryptorErrorReason||(e.CryptorErrorReason={}))[Ss.InvalidKey=0]="InvalidKey",Ss[Ss.MissingKey=1]="MissingKey",Ss[Ss.InternalError=2]="InternalError";function Is(e,t,i){var n,s,r;void 0===t&&(t=50),void 0===i&&(i={});var o=null!=(n=i.isImmediate)&&n,a=null!=(s=i.callback)&&s,c=i.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),i=this;return new Promise((function(n,s){var c=o&&void 0===r;if(void 0!==r&&clearTimeout(r),r=setTimeout((function(){if(r=void 0,d=Date.now(),!o){var n=e.apply(i,t);a&&a(n),l.forEach((function(e){return(0,e.resolve)(n)})),l=[]}}),u()),c){var h=e.apply(i,t);return a&&a(h),n(h)}l.push({resolve:n,reject:s})}))};return h.cancel=function(e){void 0!==r&&clearTimeout(r),l.forEach((function(t){return(0,t.reject)(e)})),l=[]},h}e.RoomEvent=void 0,(Es=e.RoomEvent||(e.RoomEvent={})).Connected="connected",Es.Reconnecting="reconnecting",Es.SignalReconnecting="signalReconnecting",Es.Reconnected="reconnected",Es.Disconnected="disconnected",Es.ConnectionStateChanged="connectionStateChanged",Es.MediaDevicesChanged="mediaDevicesChanged",Es.ParticipantConnected="participantConnected",Es.ParticipantDisconnected="participantDisconnected",Es.TrackPublished="trackPublished",Es.TrackSubscribed="trackSubscribed",Es.TrackSubscriptionFailed="trackSubscriptionFailed",Es.TrackUnpublished="trackUnpublished",Es.TrackUnsubscribed="trackUnsubscribed",Es.TrackMuted="trackMuted",Es.TrackUnmuted="trackUnmuted",Es.LocalTrackPublished="localTrackPublished",Es.LocalTrackUnpublished="localTrackUnpublished",Es.LocalAudioSilenceDetected="localAudioSilenceDetected",Es.ActiveSpeakersChanged="activeSpeakersChanged",Es.ParticipantMetadataChanged="participantMetadataChanged",Es.ParticipantNameChanged="participantNameChanged",Es.ParticipantAttributesChanged="participantAttributesChanged",Es.RoomMetadataChanged="roomMetadataChanged",Es.DataReceived="dataReceived",Es.SipDTMFReceived="sipDTMFReceived",Es.TranscriptionReceived="transcriptionReceived",Es.ConnectionQualityChanged="connectionQualityChanged",Es.TrackStreamStateChanged="trackStreamStateChanged",Es.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",Es.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",Es.AudioPlaybackStatusChanged="audioPlaybackChanged",Es.VideoPlaybackStatusChanged="videoPlaybackChanged",Es.MediaDevicesError="mediaDevicesError",Es.ParticipantPermissionsChanged="participantPermissionsChanged",Es.SignalConnected="signalConnected",Es.RecordingStatusChanged="recordingStatusChanged",Es.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",Es.EncryptionError="encryptionError",Es.DCBufferStatusChanged="dcBufferStatusChanged",Es.ActiveDeviceChanged="activeDeviceChanged",Es.LocalTrackSubscribed="localTrackSubscribed",e.ParticipantEvent=void 0,(ws=e.ParticipantEvent||(e.ParticipantEvent={})).TrackPublished="trackPublished",ws.TrackSubscribed="trackSubscribed",ws.TrackSubscriptionFailed="trackSubscriptionFailed",ws.TrackUnpublished="trackUnpublished",ws.TrackUnsubscribed="trackUnsubscribed",ws.TrackMuted="trackMuted",ws.TrackUnmuted="trackUnmuted",ws.LocalTrackPublished="localTrackPublished",ws.LocalTrackUnpublished="localTrackUnpublished",ws.ParticipantMetadataChanged="participantMetadataChanged",ws.ParticipantNameChanged="participantNameChanged",ws.DataReceived="dataReceived",ws.SipDTMFReceived="sipDTMFReceived",ws.TranscriptionReceived="transcriptionReceived",ws.IsSpeakingChanged="isSpeakingChanged",ws.ConnectionQualityChanged="connectionQualityChanged",ws.TrackStreamStateChanged="trackStreamStateChanged",ws.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",ws.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",ws.MediaDevicesError="mediaDevicesError",ws.AudioStreamAcquired="audioStreamAcquired",ws.ParticipantPermissionsChanged="participantPermissionsChanged",ws.PCTrackAdded="pcTrackAdded",ws.AttributesChanged="attributesChanged",ws.LocalTrackSubscribed="localTrackSubscribed",e.EngineEvent=void 0,(Ps=e.EngineEvent||(e.EngineEvent={})).TransportsCreated="transportsCreated",Ps.Connected="connected",Ps.Disconnected="disconnected",Ps.Resuming="resuming",Ps.Resumed="resumed",Ps.Restarting="restarting",Ps.Restarted="restarted",Ps.SignalResumed="signalResumed",Ps.SignalRestarted="signalRestarted",Ps.Closing="closing",Ps.MediaTrackAdded="mediaTrackAdded",Ps.ActiveSpeakersUpdate="activeSpeakersUpdate",Ps.DataPacketReceived="dataPacketReceived",Ps.RTPVideoMapUpdate="rtpVideoMapUpdate",Ps.DCBufferStatusChanged="dcBufferStatusChanged",Ps.ParticipantUpdate="participantUpdate",Ps.RoomUpdate="roomUpdate",Ps.SpeakersChanged="speakersChanged",Ps.StreamStateChanged="streamStateChanged",Ps.ConnectionQualityUpdate="connectionQualityUpdate",Ps.SubscriptionError="subscriptionError",Ps.SubscriptionPermissionUpdate="subscriptionPermissionUpdate",Ps.RemoteMute="remoteMute",Ps.SubscribedQualityUpdate="subscribedQualityUpdate",Ps.LocalTrackUnpublished="localTrackUnpublished",Ps.LocalTrackSubscribed="localTrackSubscribed",Ps.Offline="offline",Ps.SignalRequestResponse="signalRequestResponse",e.TrackEvent=void 0,(Rs=e.TrackEvent||(e.TrackEvent={})).Message="message",Rs.Muted="muted",Rs.Unmuted="unmuted",Rs.Restarted="restarted",Rs.Ended="ended",Rs.Subscribed="subscribed",Rs.Unsubscribed="unsubscribed",Rs.UpdateSettings="updateSettings",Rs.UpdateSubscription="updateSubscription",Rs.AudioPlaybackStarted="audioPlaybackStarted",Rs.AudioPlaybackFailed="audioPlaybackFailed",Rs.AudioSilenceDetected="audioSilenceDetected",Rs.VisibilityChanged="visibilityChanged",Rs.VideoDimensionsChanged="videoDimensionsChanged",Rs.VideoPlaybackStarted="videoPlaybackStarted",Rs.VideoPlaybackFailed="videoPlaybackFailed",Rs.ElementAttached="elementAttached",Rs.ElementDetached="elementDetached",Rs.UpstreamPaused="upstreamPaused",Rs.UpstreamResumed="upstreamResumed",Rs.SubscriptionPermissionChanged="subscriptionPermissionChanged",Rs.SubscriptionStatusChanged="subscriptionStatusChanged",Rs.SubscriptionFailed="subscriptionFailed",Rs.TrackProcessorUpdate="trackProcessorUpdate",Rs.AudioTrackFeatureUpdate="audioTrackFeatureUpdate",Rs.TranscriptionReceived="transcriptionReceived",Rs.TimeSyncUpdate="timeSyncUpdate";const Os=/version\/(\d+(\.?_?\d+)+)/i;let xs;function Ds(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(void 0===e&&"undefined"==typeof navigator)return;const i=(null!=e?e:navigator.userAgent).toLowerCase();if(void 0===xs||t){const e=Ms.find((e=>{let{test:t}=e;return t.test(i)}));xs=null==e?void 0:e.describe(i)}return xs}const Ms=[{test:/firefox|iceweasel|fxios/i,describe:e=>({name:"Firefox",version:Ns(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,e),os:e.toLowerCase().includes("fxios")?"iOS":void 0,osVersion:_s(e)})},{test:/chrom|crios|crmo/i,describe:e=>({name:"Chrome",version:Ns(/(?:chrome|chromium|crios|crmo)\/(\d+(\.?_?\d+)+)/i,e),os:e.toLowerCase().includes("crios")?"iOS":void 0,osVersion:_s(e)})},{test:/safari|applewebkit/i,describe:e=>({name:"Safari",version:Ns(Os,e),os:e.includes("mobile/")?"iOS":"macOS",osVersion:_s(e)})}];function Ns(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1;const n=t.match(e);return n&&n.length>=i&&n[i]||""}function _s(e){return e.includes("mac os")?Ns(/\(.+?(\d+_\d+(:?_\d+)?)/,e,1).replace(/_/g,"."):void 0}const As="2.5.1";class Ls{}Ls.setTimeout=function(){return setTimeout(...arguments)},Ls.setInterval=function(){return setInterval(...arguments)},Ls.clearTimeout=function(){return clearTimeout(...arguments)},Ls.clearInterval=function(){return clearInterval(...arguments)};class Us{constructor(e,t,i,n,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===i)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:i,maxFramerate:n,priority:s}}}get resolution(){return{width:this.width,height:this.height,frameRate:this.encoding.maxFramerate,aspectRatio:this.aspectRatio}}}const js=["vp8","h264"],Fs=["vp8","h264","vp9","av1"];function Bs(e){return!!js.find((t=>t===e))}var Vs;e.AudioPresets=void 0,(Vs=e.AudioPresets||(e.AudioPresets={})).telephone={maxBitrate:12e3},Vs.speech={maxBitrate:2e4},Vs.music={maxBitrate:32e3},Vs.musicStereo={maxBitrate:48e3},Vs.musicHighQuality={maxBitrate:64e3},Vs.musicHighQualityStereo={maxBitrate:96e3};const qs={h90:new Us(160,90,9e4,20),h180:new Us(320,180,16e4,20),h216:new Us(384,216,18e4,20),h360:new Us(640,360,45e4,20),h540:new Us(960,540,8e5,25),h720:new Us(1280,720,17e5,30),h1080:new Us(1920,1080,3e6,30),h1440:new Us(2560,1440,5e6,30),h2160:new Us(3840,2160,8e6,30)},Ks={h120:new Us(160,120,7e4,20),h180:new Us(240,180,125e3,20),h240:new Us(320,240,14e4,20),h360:new Us(480,360,33e4,20),h480:new Us(640,480,5e5,20),h540:new Us(720,540,6e5,25),h720:new Us(960,720,13e5,30),h1080:new Us(1440,1080,23e5,30),h1440:new Us(1920,1440,38e5,30)},Ws={h360fps3:new Us(640,360,2e5,3,"medium"),h360fps15:new Us(640,360,4e5,15,"medium"),h720fps5:new Us(1280,720,8e5,5,"medium"),h720fps15:new Us(1280,720,15e5,15,"medium"),h720fps30:new Us(1280,720,2e6,30,"medium"),h1080fps15:new Us(1920,1080,25e5,15,"medium"),h1080fps30:new Us(1920,1080,5e6,30,"medium"),original:new Us(0,0,7e6,30,"medium")};const Gs=[];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 Hs extends Yi.EventEmitter{constructor(t,i){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};var s;super(),this.attachedElements=[],this.isMuted=!1,this.streamState=Hs.StreamState.Active,this.isInBackground=!1,this._currentBitrate=0,this.log=Ei,this.appVisibilityChangedListener=()=>{this.backgroundTimeout&&clearTimeout(this.backgroundTimeout),"hidden"===document.visibilityState?this.backgroundTimeout=setTimeout((()=>this.handleAppVisibilityChanged()),5e3):this.handleAppVisibilityChanged()},this.log=Pi(null!==(s=n.loggerName)&&void 0!==s?s:e.LoggerNames.Track),this.loggerContextCb=n.loggerContextCb,this.setMaxListeners(100),this.kind=i,this._mediaStreamTrack=t,this._mediaStreamID=t.id,this.source=Hs.Source.Unknown}get logContext(){var e;return Object.assign(Object.assign({},null===(e=this.loggerContextCb)||void 0===e?void 0:e.call(this)),ir(this))}get currentBitrate(){return this._currentBitrate}get mediaStreamTrack(){return this._mediaStreamTrack}get mediaStreamID(){return this._mediaStreamID}attach(t){let i="audio";this.kind===Hs.Kind.Video&&(i="video"),0===this.attachedElements.length&&this.kind===Hs.Kind.Video&&this.addAppVisibilityListener(),t||("audio"===i&&(Gs.forEach((e=>{null!==e.parentElement||t||(t=e)})),t&&Gs.splice(Gs.indexOf(t),1)),t||(t=document.createElement(i))),this.attachedElements.includes(t)||this.attachedElements.push(t),Js(this.mediaStreamTrack,t);const n=t.srcObject.getTracks(),s=n.some((e=>"audio"===e.kind));return t.play().then((()=>{this.emit(s?e.TrackEvent.AudioPlaybackStarted:e.TrackEvent.VideoPlaybackStarted)})).catch((i=>{"NotAllowedError"===i.name?this.emit(s?e.TrackEvent.AudioPlaybackFailed:e.TrackEvent.VideoPlaybackFailed,i):"AbortError"===i.name?Ei.debug("".concat(s?"audio":"video"," playback aborted, likely due to new play request")):Ei.warn("could not playback ".concat(s?"audio":"video"),i),s&&t&&n.some((e=>"video"===e.kind))&&"NotAllowedError"===i.name&&(t.muted=!0,t.play().catch((()=>{})))})),this.emit(e.TrackEvent.ElementAttached,t),t}detach(t){try{if(t){Qs(this.mediaStreamTrack,t);const i=this.attachedElements.indexOf(t);return i>=0&&(this.attachedElements.splice(i,1),this.recycleElement(t),this.emit(e.TrackEvent.ElementDetached,t)),t}const i=[];return this.attachedElements.forEach((t=>{Qs(this.mediaStreamTrack,t),i.push(t),this.recycleElement(t),this.emit(e.TrackEvent.ElementDetached,t)})),this.attachedElements=[],i}finally{0===this.attachedElements.length&&this.removeAppVisibilityListener()}}stop(){this.stopMonitor(),this._mediaStreamTrack.stop()}enable(){this._mediaStreamTrack.enabled=!0}disable(){this._mediaStreamTrack.enabled=!1}stopMonitor(){this.monitorInterval&&clearInterval(this.monitorInterval),this.timeSyncHandle&&cancelAnimationFrame(this.timeSyncHandle)}updateLoggerOptions(e){e.loggerName&&(this.log=Pi(e.loggerName)),e.loggerContextCb&&(this.loggerContextCb=e.loggerContextCb)}recycleElement(e){if(e instanceof HTMLAudioElement){let t=!0;e.pause(),Gs.forEach((e=>{e.parentElement||(t=!1)})),t&&Gs.push(e)}}handleAppVisibilityChanged(){return Di(this,void 0,void 0,(function*(){this.isInBackground="hidden"===document.visibilityState,this.isInBackground||this.kind!==Hs.Kind.Video||setTimeout((()=>this.attachedElements.forEach((e=>e.play().catch((()=>{}))))),0)}))}addAppVisibilityListener(){fr()?(this.isInBackground="hidden"===document.visibilityState,document.addEventListener("visibilitychange",this.appVisibilityChangedListener)):this.isInBackground=!1}removeAppVisibilityListener(){fr()&&document.removeEventListener("visibilitychange",this.appVisibilityChangedListener)}}function Js(e,t){let i,n;i=t.srcObject instanceof MediaStream?t.srcObject:new MediaStream,n="audio"===e.kind?i.getAudioTracks():i.getVideoTracks(),n.includes(e)||(n.forEach((e=>{i.removeTrack(e)})),i.addTrack(e)),pr()&&t instanceof HTMLVideoElement||(t.autoplay=!0),t.muted=0===i.getAudioTracks().length,t instanceof HTMLVideoElement&&(t.playsInline=!0),t.srcObject!==i&&(t.srcObject=i,(pr()||hr())&&t instanceof HTMLVideoElement&&setTimeout((()=>{t.srcObject=i,t.play().catch((()=>{}))}),0))}function Qs(e,t){if(t.srcObject instanceof MediaStream){const i=t.srcObject;i.removeTrack(e),i.getTracks().length>0?t.srcObject=i:t.srcObject=null}}function zs(e,t,i){var n;const s=null!==(n=function(e){if(void 0!==e)return"function"==typeof structuredClone?structuredClone(e):JSON.parse(JSON.stringify(e))}(e))&&void 0!==n?n:{};return!0===s.audio&&(s.audio={}),!0===s.video&&(s.video={}),s.audio&&Ys(s.audio,t),s.video&&Ys(s.video,i),s}function Ys(e,t){return Object.keys(t).forEach((i=>{void 0===e[i]&&(e[i]=t[i])})),e}function Xs(e){const t={};if(e.video)if("object"==typeof e.video){const i={},n=i,s=e.video;Object.keys(s).forEach((e=>{if("resolution"===e)Ys(n,s.resolution);else n[e]=s[e]})),t.video=i}else t.video=e.video;else t.video=!1;return e.audio?"object"==typeof e.audio?t.audio=e.audio:t.audio=!0:t.audio=!1,t}function $s(){const e="undefined"!=typeof window&&(window.AudioContext||window.webkitAudioContext);if(e)return new e({latencyHint:"interactive"})}function Zs(e){var t,i;let n=null===(t=e.video)||void 0===t||t;return e.resolution&&e.resolution.width>0&&e.resolution.height>0&&(n="boolean"==typeof n?{}:n,n=pr()?Object.assign(Object.assign({},n),{width:{max:e.resolution.width},height:{max:e.resolution.height},frameRate:e.resolution.frameRate}):Object.assign(Object.assign({},n),{width:{ideal:e.resolution.width},height:{ideal:e.resolution.height},frameRate:e.resolution.frameRate})),{audio:null!==(i=e.audio)&&void 0!==i&&i,video:n,controller:e.controller,selfBrowserSurface:e.selfBrowserSurface,surfaceSwitching:e.surfaceSwitching,systemAudio:e.systemAudio,preferCurrentTab:e.preferCurrentTab}}function er(e){const t=e.split("/")[1].toLowerCase();if(!Fs.includes(t))throw Error("Video codec not supported: ".concat(t));return t}function tr(e){const t=[];return e.forEach((e=>{void 0!==e.track&&t.push(new Lt({cid:e.track.mediaStreamID,track:e.trackInfo}))})),t}function ir(e){return e instanceof Hs?{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?ir(e.track):{})}}!function(e){let t,i,n;!function(e){e.Audio="audio",e.Video="video",e.Unknown="unknown"}(t=e.Kind||(e.Kind={})),function(e){e.Camera="camera",e.Microphone="microphone",e.ScreenShare="screen_share",e.ScreenShareAudio="screen_share_audio",e.Unknown="unknown"}(i=e.Source||(e.Source={})),function(e){e.Active="active",e.Paused="paused",e.Unknown="unknown"}(n=e.StreamState||(e.StreamState={})),e.kindToProto=function(e){switch(e){case t.Audio:return Ke.AUDIO;case t.Video:return Ke.VIDEO;default:return Ke.DATA}},e.kindFromProto=function(e){switch(e){case Ke.AUDIO:return t.Audio;case Ke.VIDEO:return t.Video;default:return t.Unknown}},e.sourceToProto=function(e){switch(e){case i.Camera:return We.CAMERA;case i.Microphone:return We.MICROPHONE;case i.ScreenShare:return We.SCREEN_SHARE;case i.ScreenShareAudio:return We.SCREEN_SHARE_AUDIO;default:return We.UNKNOWN}},e.sourceFromProto=function(e){switch(e){case We.CAMERA:return i.Camera;case We.MICROPHONE:return i.Microphone;case We.SCREEN_SHARE:return i.ScreenShare;case We.SCREEN_SHARE_AUDIO:return i.ScreenShareAudio;default:return i.Unknown}},e.streamStateFromProto=function(e){switch(e){case Pt.ACTIVE:return n.Active;case Pt.PAUSED:return n.Paused;default:return n.Unknown}}}(Hs||(Hs={}));const nr="https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension";function sr(e){return Di(this,void 0,void 0,(function*(){return new Promise((t=>Ls.setTimeout(t,e)))}))}function rr(){return"addTransceiver"in RTCPeerConnection.prototype}function or(){return"addTrack"in RTCPeerConnection.prototype}function ar(){if(!("getCapabilities"in RTCRtpSender))return!1;if(pr())return!1;const e=RTCRtpSender.getCapabilities("video");let t=!1;if(e)for(const i of e.codecs)if("video/AV1"===i.mimeType){t=!0;break}return t}function cr(){if(!("getCapabilities"in RTCRtpSender))return!1;if(hr())return!1;if(pr()){const e=Ds();if((null==e?void 0:e.version)&&Cr(e.version,"16")<0)return!1}const e=RTCRtpSender.getCapabilities("video");let t=!1;if(e)for(const i of e.codecs)if("video/VP9"===i.mimeType){t=!0;break}return t}function dr(e){return"av1"===e||"vp9"===e}function lr(e){return!!document&&(e||(e=document.createElement("audio")),"setSinkId"in e)}function ur(){return"undefined"!=typeof RTCPeerConnection&&(rr()||or())}function hr(){var e;return"Firefox"===(null===(e=Ds())||void 0===e?void 0:e.name)}function pr(){var e;return"Safari"===(null===(e=Ds())||void 0===e?void 0:e.name)}function mr(){const e=Ds();return"Safari"===(null==e?void 0:e.name)&&e.version.startsWith("17.")}function gr(){var e,t;return!!fr()&&(null!==(t=null===(e=navigator.userAgentData)||void 0===e?void 0:e.mobile)&&void 0!==t?t:/Tablet|iPad|Mobile|Android|BlackBerry/.test(navigator.userAgent))}function fr(){return"undefined"!=typeof document}function vr(){return"ReactNative"==navigator.product}function kr(e){return e.hostname.endsWith(".livekit.cloud")||e.hostname.endsWith(".livekit.run")}function br(){if(global&&global.LiveKitReactNativeGlobal)return global.LiveKitReactNativeGlobal}function yr(){if(!vr())return;let e=br();return e?e.platform:void 0}function Tr(){if(fr())return window.devicePixelRatio;if(vr()){let e=br();if(e)return e.devicePixelRatio}return 1}function Cr(e,t){const i=e.split("."),n=t.split("."),s=Math.min(i.length,n.length);for(let e=0;e<s;++e){const t=parseInt(i[e],10),r=parseInt(n[e],10);if(t>r)return 1;if(t<r)return-1;if(e===s-1&&t===r)return 0}return""===e&&""!==t?-1:""===t?1:i.length==n.length?0:i.length<n.length?-1:1}function Sr(e){for(const t of e)t.target.handleResize(t)}function Er(e){for(const t of e)t.target.handleVisibilityChanged(t)}let wr=null;const Pr=()=>(wr||(wr=new ResizeObserver(Sr)),wr);let Rr=null;const Ir=()=>(Rr||(Rr=new IntersectionObserver(Er,{root:null,rootMargin:"0px"})),Rr);let Or,xr;function Dr(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:16,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:16,i=arguments.length>2&&void 0!==arguments[2]&&arguments[2],n=arguments.length>3&&void 0!==arguments[3]&&arguments[3];const s=document.createElement("canvas");s.width=e,s.height=t;const r=s.getContext("2d");null==r||r.fillRect(0,0,s.width,s.height),n&&r&&(r.beginPath(),r.arc(e/2,t/2,50,0,2*Math.PI,!0),r.closePath(),r.fillStyle="grey",r.fill());const o=s.captureStream(),[a]=o.getTracks();if(!a)throw Error("Could not get empty media stream video track");return a.enabled=i,a}function Mr(){if(!xr){const e=new AudioContext,t=e.createOscillator(),i=e.createGain();i.gain.setValueAtTime(0,0);const n=e.createMediaStreamDestination();if(t.connect(i),i.connect(n),t.start(),[xr]=n.stream.getAudioTracks(),!xr)throw Error("Could not get empty media stream audio track");xr.enabled=!1}return xr.clone()}class Nr{constructor(e,t){this.onFinally=t,this.promise=new Promise(((t,i)=>Di(this,void 0,void 0,(function*(){this.resolve=t,this.reject=i,e&&(yield e(t,i))})))).finally((()=>{var e;return null===(e=this.onFinally)||void 0===e?void 0:e.call(this)}))}}class _r{constructor(){this._locking=Promise.resolve(),this._locks=0}isLocked(){return this._locks>0}lock(){let e;this._locks+=1;const t=new Promise((t=>e=()=>{this._locks-=1,t()})),i=this._locking.then((()=>e));return this._locking=this._locking.then((()=>t)),i}}function Ar(e){if("string"==typeof e||"number"==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 Lr(e){return e.startsWith("ws")?e.replace(/^(ws)/,"http"):e}const Ur="default";class jr{static getInstance(){return void 0===this.instance&&(this.instance=new jr),this.instance}getDevices(e){return Di(this,arguments,void 0,(function(e){var t=this;let i=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return function*(){var n;if((null===(n=jr.userMediaPromiseMap)||void 0===n?void 0:n.size)>0){Ei.debug("awaiting getUserMedia promise");try{e?yield jr.userMediaPromiseMap.get(e):yield Promise.all(jr.userMediaPromiseMap.values())}catch(e){Ei.warn("error waiting for media permissons")}}let s=yield navigator.mediaDevices.enumerateDevices();if(i&&(!pr()||!t.hasDeviceInUse(e))){if(0===s.filter((t=>t.kind===e)).length||s.some((t=>{const i=""===t.label,n=!e||t.kind===e;return i&&n}))){const t={video:"audioinput"!==e&&"audiooutput"!==e,audio:"videoinput"!==e},i=yield navigator.mediaDevices.getUserMedia(t);s=yield navigator.mediaDevices.enumerateDevices(),i.getTracks().forEach((e=>{e.stop()}))}}return e&&(s=s.filter((t=>t.kind===e))),s}()}))}normalizeDeviceId(e,t,i){return Di(this,void 0,void 0,(function*(){if(t!==Ur)return t;const n=yield this.getDevices(e),s=n.find((e=>e.deviceId===Ur));if(!s)return void Ei.warn("could not reliably determine default device");const r=n.find((e=>e.deviceId!==Ur&&e.groupId===(null!=i?i:s.groupId)));if(r)return null==r?void 0:r.deviceId;Ei.warn("could not reliably determine default device")}))}hasDeviceInUse(e){return e?jr.userMediaPromiseMap.has(e):jr.userMediaPromiseMap.size>0}}jr.mediaDeviceKinds=["audioinput","audiooutput","videoinput"],jr.userMediaPromiseMap=new Map;class Fr extends Hs{get sender(){return this._sender}set sender(e){this._sender=e}get constraints(){return this._constraints}constructor(t,i,n){let s=arguments.length>3&&void 0!==arguments[3]&&arguments[3];super(t,i,arguments.length>4?arguments[4]:void 0),this.manuallyStopped=!1,this._isUpstreamPaused=!1,this.handleTrackMuteEvent=()=>this.debouncedTrackMuteHandler().catch((()=>this.log.debug("track mute bounce got cancelled by an unmute event",this.logContext))),this.debouncedTrackMuteHandler=Is((()=>Di(this,void 0,void 0,(function*(){yield this.pauseUpstream()}))),5e3),this.handleTrackUnmuteEvent=()=>Di(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 _r,this.pauseUpstreamLock=new _r,this.processorLock=new _r,this.restartLock=new _r,this.setMediaStreamTrack(t,!0),this._constraints=t.getConstraints(),n&&(this._constraints=n)}get id(){return this._mediaStreamTrack.id}get dimensions(){if(this.kind!==Hs.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 Di(this,void 0,void 0,(function*(){if(e===this._mediaStreamTrack&&!t)return;let i;if(this._mediaStreamTrack&&(this.attachedElements.forEach((e=>{Qs(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&&(Js(e,this.processorElement),this.processorElement.muted=!0),yield this.processor.restart({track:e,kind:this.kind,element:this.processorElement}),i=this.processor.processedTrack}finally{t()}}this.sender&&(yield this.sender.replaceTrack(null!=i?i: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=>{Js(null!=i?i:e,t)})))}))}waitForDimensions(){return Di(this,arguments,void 0,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1e3;return function*(){var i;if(e.kind===Hs.Kind.Audio)throw new Error("cannot get dimensions for audio tracks");"iOS"===(null===(i=Ds())||void 0===i?void 0:i.os)&&(yield sr(10));const n=Date.now();for(;Date.now()-n<t;){const t=e.dimensions;if(t)return t;yield sr(50)}throw new vs("unable to get track dimensions after timeout")}()}))}getDeviceId(){return Di(this,void 0,void 0,(function*(){if(this.source===Hs.Source.ScreenShare)return;const{deviceId:e,groupId:t}=this._mediaStreamTrack.getSettings(),i=this.kind===Hs.Kind.Audio?"audioinput":"videoinput";return jr.getInstance().normalizeDeviceId(i,e,t)}))}mute(){return Di(this,void 0,void 0,(function*(){return this.setTrackMuted(!0),this}))}unmute(){return Di(this,void 0,void 0,(function*(){return this.setTrackMuted(!1),this}))}replaceTrack(e,t){return Di(this,void 0,void 0,(function*(){if(!this.sender)throw new vs("unable to replace an unpublished track");let i,n;return"boolean"==typeof t?i=t:void 0!==t&&(i=t.userProvidedTrack,n=t.stopProcessor),this.providedByUser=null==i||i,this.log.debug("replace MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(e),n&&this.processor&&(yield this.stopProcessor()),this}))}restart(t){return Di(this,void 0,void 0,(function*(){this.manuallyStopped=!1;const i=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 i={audio:!1,video:!1};this.kind===Hs.Kind.Video?i.video=t:i.audio=t,this.attachedElements.forEach((e=>{Qs(this.mediaStreamTrack,e)})),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.stop();const n=(yield navigator.mediaDevices.getUserMedia(i)).getTracks()[0];return n.addEventListener("ended",this.handleEnded),this.log.debug("re-acquired MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(n),this._constraints=t,this.emit(e.TrackEvent.Restarted,this),this.manuallyStopped&&(this.log.warn("track was stopped during a restart, stopping restarted track",this.logContext),this.stop()),this}finally{i()}}))}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 Di(this,void 0,void 0,(function*(){yield e.handleAppVisibilityChanged.call(this),gr()&&(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;this.manuallyStopped=!0,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 Di(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=Ds();if("Safari"===(null==t?void 0:t.name)&&Cr(t.version,"12.0")<0)throw new fs("pauseUpstream is not supported on Safari < 12.");yield this.sender.replaceTrack(null)}finally{t()}}))}resumeUpstream(){return Di(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(){return Di(this,void 0,void 0,(function*(){var e;if(!(null===(e=this.sender)||void 0===e?void 0:e.getStats))return;return yield this.sender.getStats()}))}setProcessor(t){return Di(this,arguments,void 0,(function(t){var i=this;let n=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return function*(){var s;const r=yield i.processorLock.lock();try{i.log.debug("setting up processor",i.logContext);const r=document.createElement(i.kind),o={kind:i.kind,track:i._mediaStreamTrack,element:r,audioContext:i.audioContext};if(yield t.init(o),i.log.debug("processor initialized",i.logContext),i.processor&&(yield i.stopProcessor()),"unknown"===i.kind)throw TypeError("cannot set processor on track of unknown kind");if(Js(i._mediaStreamTrack,r),r.muted=!0,r.play().catch((e=>i.log.error("failed to play processor element",Object.assign(Object.assign({},i.logContext),{error:e})))),i.processor=t,i.processorElement=r,i.processor.processedTrack){for(const e of i.attachedElements)e!==i.processorElement&&n&&(Qs(i._mediaStreamTrack,e),Js(i.processor.processedTrack,e));yield null===(s=i.sender)||void 0===s?void 0:s.replaceTrack(i.processor.processedTrack)}i.emit(e.TrackEvent.TrackProcessorUpdate,i.processor)}finally{r()}}()}))}getProcessor(){return this.processor}stopProcessor(){return Di(this,arguments,void 0,(function(){var t=this;let i=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return function*(){var n,s;t.processor&&(t.log.debug("stopping processor",t.logContext),null===(n=t.processor.processedTrack)||void 0===n||n.stop(),yield t.processor.destroy(),t.processor=void 0,i||(null===(s=t.processorElement)||void 0===s||s.remove(),t.processorElement=void 0),yield t._mediaStreamTrack.applyConstraints(t._constraints),yield t.setMediaStreamTrack(t._mediaStreamTrack,!0),t.emit(e.TrackEvent.TrackProcessorUpdate))}()}))}}class Br extends Yi.EventEmitter{constructor(t){super(),this.onWorkerMessage=t=>{var i,n;const{kind:s,data:r}=t.data;switch(s){case"error":Ei.error(r.error.message),this.emit(e.EncryptionEvent.EncryptionError,r.error);break;case"initAck":r.enabled&&this.keyProvider.getKeys().forEach((e=>{this.postKey(e)}));break;case"enable":if(this.encryptionEnabled!==r.enabled&&r.participantIdentity===(null===(i=this.room)||void 0===i?void 0:i.localParticipant.identity))this.emit(e.EncryptionEvent.ParticipantEncryptionStatusChanged,r.enabled,this.room.localParticipant),this.encryptionEnabled=r.enabled;else if(r.participantIdentity){const t=null===(n=this.room)||void 0===n?void 0:n.getParticipantByIdentity(r.participantIdentity);if(!t)throw TypeError("couldn't set encryption status, participant not found".concat(r.participantIdentity));this.emit(e.EncryptionEvent.ParticipantEncryptionStatusChanged,r.enabled,t)}this.encryptionEnabled&&this.keyProvider.getKeys().forEach((e=>{this.postKey(e)}));break;case"ratchetKey":this.keyProvider.emit(e.KeyProviderEvent.KeyRatcheted,r.material,r.keyIndex)}},this.onWorkerError=t=>{Ei.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(!as())throw new fs("tried to setup end-to-end encryption on an unsupported browser");if(Ei.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:Ri.getLevel()}};this.worker&&(Ei.info("initializing worker",{worker:this.worker}),this.worker.onmessage=this.onWorkerMessage,this.worker.onerror=this.onWorkerError,this.worker.postMessage(t))}}setParticipantCryptorEnabled(e,t){Ei.debug("set e2ee to ".concat(e," for participant ").concat(t)),this.postEnable(e,t)}setSifTrailer(e){e&&0!==e.length?this.postSifTrailer(e):Ei.warn("ignoring server sent trailer as it's empty")}setupEngine(t){t.on(e.EngineEvent.RTPVideoMapUpdate,(e=>{this.postRTPMap(e)}))}setupEventListeners(t,i){t.on(e.RoomEvent.TrackPublished,((e,t)=>this.setParticipantCryptorEnabled(e.trackInfo.encryption!==st.NONE,t.identity))),t.on(e.RoomEvent.ConnectionStateChanged,(i=>{i===e.ConnectionState.Connected&&t.remoteParticipants.forEach((e=>{e.trackPublications.forEach((t=>{this.setParticipantCryptorEnabled(t.trackInfo.encryption!==st.NONE,e.identity)}))}))})).on(e.RoomEvent.TrackUnsubscribed,((e,t,i)=>{var n;const s={kind:"removeTransform",data:{participantIdentity:i.identity,trackId:e.mediaStreamID}};null===(n=this.worker)||void 0===n||n.postMessage(s)})).on(e.RoomEvent.TrackSubscribed,((e,t,i)=>{this.setupE2EEReceiver(e,i.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),i.getKeys().forEach((e=>{this.postKey(e)}))})),t.localParticipant.on(e.ParticipantEvent.LocalTrackPublished,(e=>Di(this,void 0,void 0,(function*(){this.setupE2EESender(e.track,e.track.sender)})))),i.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 i={kind:"ratchetRequest",data:{participantIdentity:e,keyIndex:t}};this.worker.postMessage(i)}postKey(e){let{key:t,participantIdentity:i,keyIndex:n}=e;var s;if(!this.worker)throw Error("could not set key, worker is missing");const r={kind:"setKey",data:{participantIdentity:i,isPublisher:i===(null===(s=this.room)||void 0===s?void 0:s.localParticipant.identity),key:t,keyIndex:n}};this.worker.postMessage(r)}postEnable(e,t){if(!this.worker)throw new ReferenceError("failed to enable e2ee, worker is not ready");{const i={kind:"enable",data:{enabled:e,participantIdentity:t}};this.worker.postMessage(i)}}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 i={kind:"setRTPMap",data:{map:e,participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(i)}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,i){if(e.receiver){if(!(null==i?void 0:i.mimeType)||""===i.mimeType)throw new TypeError("MimeType missing from trackInfo, cannot set up E2EE cryptor");this.handleReceiver(e.receiver,e.mediaStreamID,t,"video"===e.kind?er(i.mimeType):void 0)}}setupE2EESender(e,t){e instanceof Fr&&t?this.handleSender(t,e.mediaStreamID,void 0):t||Ei.warn("early return because sender is not ready")}handleReceiver(e,t,i,n){return Di(this,void 0,void 0,(function*(){if(this.worker){if(cs()){const s={kind:"decode",participantIdentity:i,trackId:t,codec:n};e.transform=new RTCRtpScriptTransform(this.worker,s)}else{if(ns in e&&n){const e={kind:"updateCodec",data:{trackId:t,codec:n,participantIdentity:i}};return void this.worker.postMessage(e)}let s=e.writableStream,r=e.readableStream;if(!s||!r){const t=e.createEncodedStreams();e.writableStream=t.writable,s=t.writable,e.readableStream=t.readable,r=t.readable}const o={kind:"decode",data:{readableStream:r,writableStream:s,trackId:t,codec:n,participantIdentity:i}};this.worker.postMessage(o,[r,s])}e[ns]=!0}}))}handleSender(e,t,i){var n;if(!(ns in e)&&this.worker){if(!(null===(n=this.room)||void 0===n?void 0:n.localParticipant.identity)||""===this.room.localParticipant.identity)throw TypeError("local identity needs to be known in order to set up encrypted sender");if(cs()){Ei.info("initialize script transform");const n={kind:"encode",participantIdentity:this.room.localParticipant.identity,trackId:t,codec:i};e.transform=new RTCRtpScriptTransform(this.worker,n)}else{Ei.info("initialize encoded streams");const n=e.createEncodedStreams(),s={kind:"encode",data:{readableStream:n.readable,writableStream:n.writable,codec:i,trackId:t,participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(s,[n.readable,n.writable])}e[ns]=!0}}}var Vr;!function(e){e[e.WAITING=0]="WAITING",e[e.RUNNING=1]="RUNNING",e[e.COMPLETED=2]="COMPLETED"}(Vr||(Vr={}));class qr{constructor(){this.pendingTasks=new Map,this.taskMutex=new _r,this.nextTaskIndex=0}run(e){return Di(this,void 0,void 0,(function*(){const t={id:this.nextTaskIndex++,enqueuedAt:Date.now(),status:Vr.WAITING};this.pendingTasks.set(t.id,t);const i=yield this.taskMutex.lock();try{return t.executedAt=Date.now(),t.status=Vr.RUNNING,yield e()}finally{t.status=Vr.COMPLETED,this.pendingTasks.delete(t.id),i()}}))}flush(){return Di(this,void 0,void 0,(function*(){return this.run((()=>Di(this,void 0,void 0,(function*(){}))))}))}snapshot(){return Array.from(this.pendingTasks.values())}}const Kr=["syncState","trickle","offer","answer","simulate","leave"];var Wr;!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"}(Wr||(Wr={}));class Gr{get currentState(){return this.state}get isDisconnected(){return this.state===Wr.DISCONNECTING||this.state===Wr.DISCONNECTED}get isEstablishingConnection(){return this.state===Wr.CONNECTING||this.state===Wr.RECONNECTING}getNextRequestId(){return this._requestId+=1,this._requestId}constructor(){let t=arguments.length>0&&void 0!==arguments[0]&&arguments[0],i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};var n;this.rtt=0,this.state=Wr.DISCONNECTED,this.log=Ei,this._requestId=0,this.resetCallbacks=()=>{this.onAnswer=void 0,this.onLeave=void 0,this.onLocalTrackPublished=void 0,this.onLocalTrackUnpublished=void 0,this.onNegotiateRequested=void 0,this.onOffer=void 0,this.onRemoteMuteChanged=void 0,this.onSubscribedQualityUpdate=void 0,this.onTokenRefresh=void 0,this.onTrickle=void 0,this.onClose=void 0},this.log=Pi(null!==(n=i.loggerName)&&void 0!==n?n:e.LoggerNames.Signal),this.loggerContextCb=i.loggerContextCb,this.useJSON=t,this.requestQueue=new qr,this.queuedRequests=[],this.closingLock=new _r,this.connectionLock=new _r,this.state=Wr.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,i,n){return Di(this,void 0,void 0,(function*(){this.state=Wr.CONNECTING,this.options=i;return yield this.connect(e,t,i,n)}))}reconnect(e,t,i,n){return Di(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=Wr.RECONNECTING,this.clearPingInterval();return yield this.connect(e,t,Object.assign(Object.assign({},this.options),{reconnect:!0,sid:i,reconnectReason:n}))}))}connect(e,t,i,n){this.connectOptions=i,e=(e=function(e){return e.startsWith("http")?e.replace(/^(http)/,"ws"):e}(e)).replace(/\/$/,""),e+="/rtc";const s=function(e,t,i){var n;const s=new URLSearchParams;s.set("access_token",e),i.reconnect&&(s.set("reconnect","1"),i.sid&&s.set("sid",i.sid));s.set("auto_subscribe",i.autoSubscribe?"1":"0"),s.set("sdk",vr()?"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);i.adaptiveStream&&s.set("adaptive_stream","1");i.reconnectReason&&s.set("reconnect_reason",i.reconnectReason.toString());(null===(n=navigator.connection)||void 0===n?void 0:n.type)&&s.set("network",navigator.connection.type);return"?".concat(s.toString())}(t,function(){var e;const t=new bt({sdk:yt.JS,protocol:15,version:As});return vr()&&(t.os=null!==(e=yr())&&void 0!==e?e:""),t}(),i);return new Promise(((t,r)=>Di(this,void 0,void 0,(function*(){const o=yield this.connectionLock.lock();try{const o=()=>Di(this,void 0,void 0,(function*(){this.close(),clearTimeout(a),r(new gs("room connection has been cancelled (signal)"))})),a=setTimeout((()=>{this.close(),r(new gs("room connection has timed out (signal)"))}),i.websocketTimeout);(null==n?void 0:n.aborted)&&o(),null==n||n.addEventListener("abort",o),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(a)},this.ws.onerror=t=>Di(this,void 0,void 0,(function*(){if(this.state===Wr.CONNECTED)this.handleWSError(t);else{this.state=Wr.DISCONNECTED,clearTimeout(a);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();r(new gs(e,0,t.status))}else r(new gs("Internal error",2,t.status))}catch(e){r(new gs("server was not reachable",1))}}})),this.ws.onmessage=e=>Di(this,void 0,void 0,(function*(){var s,a,c;let d;if("string"==typeof e.data){const t=JSON.parse(e.data);d=Ot.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=Ot.fromBinary(new Uint8Array(e.data))}if(this.state!==Wr.CONNECTED){let e=!1;if("join"===(null===(s=d.message)||void 0===s?void 0:s.case)?(this.state=Wr.CONNECTED,null==n||n.removeEventListener("abort",o),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===Wr.RECONNECTING&&"leave"!==d.message.case?(this.state=Wr.CONNECTED,null==n||n.removeEventListener("abort",o),this.startPingInterval(),"reconnect"===(null===(a=d.message)||void 0===a?void 0:a.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?r(new gs("Received leave request while trying to (re)connect",4)):i.reconnect||r(new gs("did not receive join response, got ".concat(null===(c=d.message)||void 0===c?void 0:c.case," instead"))),!e)return}this.signalLatency&&(yield sr(this.signalLatency)),this.handleSignalResponse(d)})),this.ws.onclose=e=>{this.isEstablishingConnection&&r(new gs("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{o()}}))))}close(){return Di(this,arguments,void 0,(function(){var e=this;let t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return function*(){const i=yield e.closingLock.lock();try{if(e.clearPingInterval(),t&&(e.state=Wr.DISCONNECTING),e.ws){e.ws.onmessage=null,e.ws.onopen=null,e.ws.onclose=null;const t=new Promise((t=>{e.ws?e.ws.onclose=()=>{t()}:t()}));e.ws.readyState<e.ws.CLOSING&&(e.ws.close(),yield Promise.race([t,sr(250)])),e.ws=void 0}}finally{t&&(e.state=Wr.DISCONNECTED),i()}}()}))}sendOffer(e){this.log.debug("sending offer",Object.assign(Object.assign({},this.logContext),{offerSdp:e.sdp})),this.sendRequest({case:"offer",value:Jr(e)})}sendAnswer(e){return this.log.debug("sending answer",Object.assign(Object.assign({},this.logContext),{answerSdp:e.sdp})),this.sendRequest({case:"answer",value:Jr(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 Mt({candidateInit:JSON.stringify(e),target:t})})}sendMuteTrack(e,t){return this.sendRequest({case:"mute",value:new Nt({sid:e,muted:t})})}sendAddTrack(e){return this.sendRequest({case:"addTrack",value:e})}sendUpdateLocalMetadata(e,t){return Di(this,arguments,void 0,(function(e,t){var i=this;let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return function*(){const s=i.getNextRequestId();return yield i.sendRequest({case:"updateMetadata",value:new Jt({requestId:s,metadata:e,name:t,attributes:n})}),s}()}))}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 Ht({trackSid:e,layers:t})})}sendUpdateSubscriptionPermissions(e,t){return this.sendRequest({case:"subscriptionPermission",value:new ri({allParticipants:e,trackPermissions:t})})}sendSimulateScenario(e){return this.sendRequest({case:"simulate",value:e})}sendPing(){return Promise.all([this.sendRequest({case:"ping",value:I.parse(Date.now())}),this.sendRequest({case:"pingReq",value:new li({timestamp:I.parse(Date.now()),rtt:I.parse(this.rtt)})})])}sendUpdateLocalAudioTrack(e,t){return this.sendRequest({case:"updateAudioTrack",value:new qt({trackSid:e,features:t})})}sendLeave(){return this.sendRequest({case:"leave",value:new Wt({reason:Qe.CLIENT_INITIATED,action:Gt.DISCONNECT})})}sendRequest(e){return Di(this,arguments,void 0,(function(e){var t=this;let i=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return function*(){const n=!i&&!function(e){const t=Kr.indexOf(e.case)>=0;return Ei.trace("request allowed to bypass queue:",{canPass:t,req:e}),t}(e);if(n&&t.state===Wr.RECONNECTING)return void t.queuedRequests.push((()=>Di(t,void 0,void 0,(function*(){yield this.sendRequest(e,!0)}))));if(i||(yield t.requestQueue.flush()),t.signalLatency&&(yield sr(t.signalLatency)),!t.ws||t.ws.readyState!==t.ws.OPEN)return void t.log.error("cannot send signal request before connected, type: ".concat(null==e?void 0:e.case),t.logContext);const s=new It({message:e});try{t.useJSON?t.ws.send(s.toJsonString()):t.ws.send(s.toBinary())}catch(e){t.log.error("error sending signal message",Object.assign(Object.assign({},t.logContext),{error:e}))}}()}))}handleSignalResponse(e){var t,i;const n=e.message;if(null==n)return void this.log.debug("received unsupported message",this.logContext);let s=!1;if("answer"===n.case){const e=Hr(n.value);this.onAnswer&&this.onAnswer(e)}else if("offer"===n.case){const e=Hr(n.value);this.onOffer&&this.onOffer(e)}else if("trickle"===n.case){const e=JSON.parse(n.value.candidateInit);this.onTrickle&&this.onTrickle(e,n.value.target)}else"update"===n.case?this.onParticipantUpdate&&this.onParticipantUpdate(null!==(t=n.value.participants)&&void 0!==t?t:[]):"trackPublished"===n.case?this.onLocalTrackPublished&&this.onLocalTrackPublished(n.value):"speakersChanged"===n.case?this.onSpeakersChanged&&this.onSpeakersChanged(null!==(i=n.value.speakers)&&void 0!==i?i:[]):"leave"===n.case?this.onLeave&&this.onLeave(n.value):"mute"===n.case?this.onRemoteMuteChanged&&this.onRemoteMuteChanged(n.value.sid,n.value.muted):"roomUpdate"===n.case?this.onRoomUpdate&&n.value.room&&this.onRoomUpdate(n.value.room):"connectionQuality"===n.case?this.onConnectionQuality&&this.onConnectionQuality(n.value):"streamStateUpdate"===n.case?this.onStreamStateUpdate&&this.onStreamStateUpdate(n.value):"subscribedQualityUpdate"===n.case?this.onSubscribedQualityUpdate&&this.onSubscribedQualityUpdate(n.value):"subscriptionPermissionUpdate"===n.case?this.onSubscriptionPermissionUpdate&&this.onSubscriptionPermissionUpdate(n.value):"refreshToken"===n.case?this.onTokenRefresh&&this.onTokenRefresh(n.value):"trackUnpublished"===n.case?this.onLocalTrackUnpublished&&this.onLocalTrackUnpublished(n.value):"subscriptionResponse"===n.case?this.onSubscriptionError&&this.onSubscriptionError(n.value):"pong"===n.case||("pongResp"===n.case?(this.rtt=Date.now()-Number.parseInt(n.value.lastPingTimestamp.toString()),this.resetPingTimeout(),s=!0):"requestResponse"===n.case?this.onRequestResponse&&this.onRequestResponse(n.value):"trackSubscribed"===n.case?this.onLocalTrackSubscribed&&this.onLocalTrackSubscribed(n.value.trackSid):this.log.debug("unsupported message",Object.assign(Object.assign({},this.logContext),{msgCase:n.case})));s||this.resetPingTimeout()}setReconnected(){for(;this.queuedRequests.length>0;){const e=this.queuedRequests.shift();e&&this.requestQueue.run(e)}}handleOnClose(e){return Di(this,void 0,void 0,(function*(){if(this.state===Wr.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=Ls.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&&Ls.clearTimeout(this.pingTimeout)}startPingInterval(){this.clearPingInterval(),this.resetPingTimeout(),this.pingIntervalDuration?(this.log.debug("start ping interval",this.logContext),this.pingInterval=Ls.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&&Ls.clearInterval(this.pingInterval)}}function Hr(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 Jr(e){return new jt({sdp:e.sdp,type:e.type})}var Qr={},zr={exports:{}},Yr=zr.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(Yr).forEach((function(e){Yr[e].forEach((function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")}))}));var Xr=zr.exports;!function(e){var t=function(e){return String(Number(e))===e?Number(e):e},i=function(e,i,n){var s=e.name&&e.names;e.push&&!i[e.push]?i[e.push]=[]:s&&!i[e.name]&&(i[e.name]={});var r=e.push?{}:s?i[e.name]:i;!function(e,i,n,s){if(s&&!n)i[s]=t(e[1]);else for(var r=0;r<n.length;r+=1)null!=e[r+1]&&(i[n[r]]=t(e[r+1]))}(n.match(e.reg),r,e.names,e.name),e.push&&i[e.push].push(r)},n=Xr,s=RegExp.prototype.test.bind(/^([a-z])=(.*)/);e.parse=function(e){var t={},r=[],o=t;return e.split(/(\r\n|\r|\n)/).filter(s).forEach((function(e){var t=e[0],s=e.slice(2);"m"===t&&(r.push({rtp:[],fmtp:[]}),o=r[r.length-1]);for(var a=0;a<(n[t]||[]).length;a+=1){var c=n[t][a];if(c.reg.test(s))return i(c,o,s)}})),t.media=r,t};var r=function(e,i){var n=i.split(/=(.+)/,2);return 2===n.length?e[n[0]]=t(n[1]):1===n.length&&i.length>1&&(e[n[0]]=void 0),e};e.parseParams=function(e){return e.split(/;\s?/).reduce(r,{})},e.parseFmtpConfig=e.parseParams,e.parsePayloads=function(e){return e.toString().split(" ").map(Number)},e.parseRemoteCandidates=function(e){for(var i=[],n=e.split(" ").map(t),s=0;s<n.length;s+=3)i.push({component:n[s],ip:n[s+1],port:n[s+2]});return i},e.parseImageAttributes=function(e){return e.split(" ").map((function(e){return e.substring(1,e.length-1).split(",").reduce(r,{})}))},e.parseSimulcastStreamList=function(e){return e.split(";").map((function(e){return e.split(",").map((function(e){var i,n=!1;return"~"!==e[0]?i=t(e):(i=t(e.substring(1,e.length)),n=!0),{scid:i,paused:n}}))}))}}(Qr);var $r=Xr,Zr=/%[sdv%]/g,eo=function(e){var t=1,i=arguments,n=i.length;return e.replace(Zr,(function(e){if(t>=n)return e;var s=i[t];switch(t+=1,e){case"%%":return"%";case"%s":return String(s);case"%d":return Number(s);case"%v":return""}}))},to=function(e,t,i){var n=[e+"="+(t.format instanceof Function?t.format(t.push?i:i[t.name]):t.format)];if(t.names)for(var s=0;s<t.names.length;s+=1){var r=t.names[s];t.name?n.push(i[t.name][r]):n.push(i[t.names[s]])}else n.push(i[t.name]);return eo.apply(null,n)},io=["v","o","s","i","u","e","p","c","b","t","r","z","a"],no=["i","c","b","a"],so=Qr,ro=function(e,t){t=t||{},null==e.version&&(e.version=0),null==e.name&&(e.name=" "),e.media.forEach((function(e){null==e.payloads&&(e.payloads="")}));var i=t.outerOrder||io,n=t.innerOrder||no,s=[];return i.forEach((function(t){$r[t].forEach((function(i){i.name in e&&null!=e[i.name]?s.push(to(t,i,e)):i.push in e&&null!=e[i.push]&&e[i.push].forEach((function(e){s.push(to(t,i,e))}))}))})),e.media.forEach((function(e){s.push(to("m",$r.m[0],e)),n.forEach((function(t){$r[t].forEach((function(i){i.name in e&&null!=e[i.name]?s.push(to(t,i,e)):i.push in e&&null!=e[i.push]&&e[i.push].forEach((function(e){s.push(to(t,i,e))}))}))}))})),s.join("\r\n")+"\r\n"},oo=ro,ao=so.parse;const co="negotiationStarted",lo="negotiationComplete",uo="rtpVideoPayloadTypes";class ho extends Yi.EventEmitter{get pc(){return this._pc||(this._pc=this.createPC()),this._pc}constructor(t){let i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};var n;super(),this.log=Ei,this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate=!1,this.trackBitrates=[],this.remoteStereoMids=[],this.remoteNackMids=[],this.negotiate=Is((e=>Di(this,void 0,void 0,(function*(){this.emit(co);try{yield this.createAndSendOffer()}catch(t){if(!e)throw t;e(t)}}))),20),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=Pi(null!==(n=i.loggerName)&&void 0!==n?n:e.LoggerNames.PCTransport),this.loggerOptions=i,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 Di(this,void 0,void 0,(function*(){if(this.pc.remoteDescription&&!this.restartingIce)return this.pc.addIceCandidate(e);this.pendingCandidates.push(e)}))}setRemoteDescription(e){return Di(this,void 0,void 0,(function*(){var t;let i;if("offer"===e.type){let{stereoMids:t,nackMids:i}=function(e){var t;const i=[],n=[],s=ao(null!==(t=e.sdp)&&void 0!==t?t:"");let r=0;return s.media.forEach((e=>{var t;"audio"===e.type&&(e.rtp.some((e=>"opus"===e.codec&&(r=e.payload,!0))),(null===(t=e.rtcpFb)||void 0===t?void 0:t.some((e=>e.payload===r&&"nack"===e.type)))&&n.push(e.mid),e.fmtp.some((t=>t.payload===r&&(t.config.includes("sprop-stereo=1")&&i.push(e.mid),!0))))})),{stereoMids:i,nackMids:n}}(e);this.remoteStereoMids=t,this.remoteNackMids=i}else if("answer"===e.type){const n=ao(null!==(t=e.sdp)&&void 0!==t?t:"");n.media.forEach((e=>{"audio"===e.type&&this.trackBitrates.some((t=>{if(!t.transceiver||e.mid!=t.transceiver.mid)return!1;let i=0;if(e.rtp.some((e=>e.codec.toUpperCase()===t.codec.toUpperCase()&&(i=e.payload,!0))),0===i)return!0;let n=!1;for(const s of e.fmtp)if(s.payload===i){s.config=s.config.split(";").filter((e=>!e.includes("maxaveragebitrate"))).join(";"),t.maxbr>0&&(s.config+=";maxaveragebitrate=".concat(1e3*t.maxbr)),n=!0;break}return n||t.maxbr>0&&e.fmtp.push({payload:i,config:"maxaveragebitrate=".concat(1e3*t.maxbr)}),!0}))})),i=oo(n)}if(yield this.setMungedSDP(e,i,!0),this.pendingCandidates.forEach((e=>{this.pc.addIceCandidate(e)})),this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate)this.renegotiate=!1,yield this.createAndSendOffer();else if("answer"===e.type&&(this.emit(lo),e.sdp)){ao(e.sdp).media.forEach((e=>{"video"===e.type&&this.emit(uo,e.rtp)}))}}))}createAndSendOffer(e){return Di(this,void 0,void 0,(function*(){var t;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 i=yield this.pc.createOffer(e);this.log.debug("original offer",Object.assign({sdp:i.sdp},this.logContext));const n=ao(null!==(t=i.sdp)&&void 0!==t?t:"");n.media.forEach((e=>{"audio"===e.type?po(e,[],[]):"video"===e.type&&this.trackBitrates.some((t=>{if(!e.msid||!t.cid||!e.msid.includes(t.cid))return!1;let i=0;if(e.rtp.some((e=>e.codec.toUpperCase()===t.codec.toUpperCase()&&(i=e.payload,!0))),0===i)return!0;if(dr(t.codec)&&function(e){var t,i;let n=0;const s=null===(t=e.ext)||void 0===t?void 0:t.some((e=>e.uri===nr||(e.value>n&&(n=e.value),!1)));s||null===(i=e.ext)||void 0===i||i.push({value:n+1,uri:nr})}(e),"av1"!==t.codec)return!0;const n=Math.round(.7*t.maxbr);for(const t of e.fmtp)if(t.payload===i){t.config.includes("x-google-start-bitrate")||(t.config+=";x-google-start-bitrate=".concat(n));break}return!0}))})),yield this.setMungedSDP(i,oo(n)),this.onOffer(i)}))}createAndSetAnswer(){return Di(this,void 0,void 0,(function*(){var e;const t=yield this.pc.createAnswer(),i=ao(null!==(e=t.sdp)&&void 0!==e?e:"");return i.media.forEach((e=>{"audio"===e.type&&po(e,this.remoteStereoMids,this.remoteNackMids)})),yield this.setMungedSDP(t,oo(i)),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 bs("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 bs("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(){return Di(this,void 0,void 0,(function*(){var e;if(!this._pc)return;let t="";const i=new Map,n=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),i.set(e.id,e);break;case"remote-candidate":n.set(e.id,"".concat(e.address,":").concat(e.port))}})),""===t)return;const s=null===(e=i.get(t))||void 0===e?void 0:e.remoteCandidateId;return void 0!==s?n.get(s):void 0}))}setMungedSDP(e,t,i){return Di(this,void 0,void 0,(function*(){if(t){const n=e.sdp;e.sdp=t;try{return this.log.debug("setting munged ".concat(i?"remote":"local"," description"),this.logContext),void(i?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e))}catch(i){this.log.warn("not able to set ".concat(e.type,", falling back to unmodified sdp"),Object.assign(Object.assign({},this.logContext),{error:i,sdp:t})),e.sdp=n}}try{i?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e)}catch(t){let n="unknown error";t instanceof Error?n=t.message:"string"==typeof t&&(n=t);const s={error:n,sdp:e.sdp};throw!i&&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 ys(n)}}))}}function po(e,t,i){let n=0;e.rtp.some((e=>"opus"===e.codec&&(n=e.payload,!0))),n>0&&(e.rtcpFb||(e.rtcpFb=[]),i.includes(e.mid)&&!e.rtcpFb.some((e=>e.payload===n&&"nack"===e.type))&&e.rtcpFb.push({payload:n,type:"nack"}),t.includes(e.mid)&&e.fmtp.some((e=>e.payload===n&&(e.config.includes("stereo=1")||(e.config+=";stereo=1"),!0))))}const mo="vp8",go={audioPreset:e.AudioPresets.music,dtx:!0,red:!0,forceStereo:!1,simulcast:!0,screenShareEncoding:Ws.h1080fps15.encoding,stopMicTrackOnMute:!1,videoCodec:mo,backupCodec:!0},fo={autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0},vo={resolution:qs.h720.resolution},ko={adaptiveStream:!1,dynacast:!1,stopLocalTrackOnUnpublish:!0,reconnectPolicy:new xi,disconnectOnPageLeave:!0,webAudioMix:!1},bo={autoSubscribe:!0,maxRetries:1,peerConnectionTimeout:15e3,websocketTimeout:15e3};var yo;!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"}(yo||(yo={}));class To{get needsPublisher(){return this.isPublisherConnectionRequired}get needsSubscriber(){return this.isSubscriberConnectionRequired}get currentState(){return this.state}constructor(t,i,n){var s;this.peerConnectionTimeout=bo.peerConnectionTimeout,this.log=Ei,this.updateState=()=>{var e;const t=this.state,i=this.requiredTransports.map((e=>e.getConnectionState()));i.every((e=>"connected"===e))?this.state=yo.CONNECTED:i.some((e=>"failed"===e))?this.state=yo.FAILED:i.some((e=>"connecting"===e))?this.state=yo.CONNECTING:i.every((e=>"closed"===e))?this.state=yo.CLOSED:i.some((e=>"closed"===e))?this.state=yo.CLOSING:i.every((e=>"new"===e))&&(this.state=yo.NEW),t!==this.state&&(this.log.debug("pc state change: from ".concat(yo[t]," to ").concat(yo[this.state]),this.logContext),null===(e=this.onStateChange)||void 0===e||e.call(this,this.state,this.publisher.getConnectionState(),this.subscriber.getConnectionState()))},this.log=Pi(null!==(s=n.loggerName)&&void 0!==s?s:e.LoggerNames.PCManager),this.loggerOptions=n,this.isPublisherConnectionRequired=!i,this.isSubscriberConnectionRequired=i,this.publisher=new ho(t,n),this.subscriber=new ho(t,n),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,wt.PUBLISHER)},this.subscriber.onIceCandidate=e=>{var t;null===(t=this.onIceCandidate)||void 0===t||t.call(this,e,wt.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=yo.NEW,this.connectionLock=new _r}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 Di(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 Di(this,void 0,void 0,(function*(){this.subscriber.restartingIce=!0,this.needsPublisher&&(yield this.createAndSendPublisherOffer({iceRestart:!0}))}))}addIceCandidate(e,t){return Di(this,void 0,void 0,(function*(){t===wt.PUBLISHER?yield this.publisher.addIceCandidate(e):yield this.subscriber.addIceCandidate(e)}))}createSubscriberAnswerFromOffer(e){return Di(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){return Di(this,void 0,void 0,(function*(){var i;const n=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===(i=this.requiredTransports)||void 0===i?void 0:i.map((i=>this.ensureTransportConnected(i,e,t))))}finally{n()}}))}negotiate(e){return Di(this,void 0,void 0,(function*(){return new Promise(((t,i)=>Di(this,void 0,void 0,(function*(){const n=setTimeout((()=>{i("negotiation timed out")}),this.peerConnectionTimeout);e.signal.addEventListener("abort",(()=>{clearTimeout(n),i("negotiation aborted")})),this.publisher.once(co,(()=>{e.signal.aborted||this.publisher.once(lo,(()=>{clearTimeout(n),t()}))})),yield this.publisher.negotiate((e=>{clearTimeout(n),i(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===wt.PUBLISHER||e===wt.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){return Di(this,arguments,void 0,(function(e,t){var i=this;let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:this.peerConnectionTimeout;return function*(){if("connected"!==e.getConnectionState())return new Promise(((e,s)=>Di(i,void 0,void 0,(function*(){const i=()=>{this.log.warn("abort transport connection",this.logContext),Ls.clearTimeout(r),s(new gs("room connection has been cancelled",3))};(null==t?void 0:t.signal.aborted)&&i(),null==t||t.signal.addEventListener("abort",i);const r=Ls.setTimeout((()=>{null==t||t.signal.removeEventListener("abort",i),s(new gs("could not establish pc connection"))}),n);for(;this.state!==yo.CONNECTED;)if(yield sr(50),null==t?void 0:t.signal.aborted)return void s(new gs("room connection has been cancelled",3));Ls.clearTimeout(r),null==t||t.signal.removeEventListener("abort",i),e()}))))}()}))}}const Co=2e3;function So(e,t){if(!t)return 0;let i,n;return"bytesReceived"in e?(i=e.bytesReceived,n=t.bytesReceived):"bytesSent"in e&&(i=e.bytesSent,n=t.bytesSent),void 0===i||void 0===n||void 0===e.timestamp||void 0===t.timestamp?0:8*(i-n)*1e3/(e.timestamp-t.timestamp)}class Eo extends Fr{get enhancedNoiseCancellation(){return this.isKrispNoiseFilterEnabled}constructor(t,i){let n=!(arguments.length>2&&void 0!==arguments[2])||arguments[2],s=arguments.length>3?arguments[3]:void 0,r=arguments.length>4?arguments[4]:void 0;super(t,Hs.Kind.Audio,i,n,r),this.stopOnMute=!1,this.isKrispNoiseFilterEnabled=!1,this.monitorSender=()=>Di(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=So(e,this.prevStats)),this.prevStats=e})),this.handleKrispNoiseFilterEnable=()=>{this.isKrispNoiseFilterEnabled=!0,this.log.debug("Krisp noise filter enabled",this.logContext),this.emit(e.TrackEvent.AudioTrackFeatureUpdate,this,Xe.TF_ENHANCED_NOISE_CANCELLATION,!0)},this.handleKrispNoiseFilterDisable=()=>{this.isKrispNoiseFilterEnabled=!1,this.log.debug("Krisp noise filter disabled",this.logContext),this.emit(e.TrackEvent.AudioTrackFeatureUpdate,this,Xe.TF_ENHANCED_NOISE_CANCELLATION,!1)},this.audioContext=s,this.checkForSilence()}setDeviceId(e){return Di(this,void 0,void 0,(function*(){return this._constraints.deviceId===e&&this._mediaStreamTrack.getSettings().deviceId===Ar(e)||(this._constraints.deviceId=e,this.isMuted||(yield this.restartTrack()),this.isMuted||Ar(e)===this._mediaStreamTrack.getSettings().deviceId)}))}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return Di(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===Hs.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 Di(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!==Ar(this._constraints.deviceId);return this.source!==Hs.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 Di(this,void 0,void 0,(function*(){let t;if(e){const i=Xs({audio:e});"boolean"!=typeof i.audio&&(t=i.audio)}yield this.restart(t)}))}restart(e){const t=Object.create(null,{restart:{get:()=>super.restart}});return Di(this,void 0,void 0,(function*(){const i=yield t.restart.call(this,e);return this.checkForSilence(),i}))}startMonitor(){fr()&&(this.monitorInterval||(this.monitorInterval=setInterval((()=>{this.monitorSender()}),Co)))}setProcessor(t){return Di(this,void 0,void 0,(function*(){var i;const n=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 n={kind:this.kind,track:this._mediaStreamTrack,audioContext:this.audioContext};this.log.debug("setting up audio processor ".concat(t.name),this.logContext),yield t.init(n),this.processor=t,this.processor.processedTrack&&(yield null===(i=this.sender)||void 0===i?void 0:i.replaceTrack(this.processor.processedTrack),this.processor.processedTrack.addEventListener("enable-lk-krisp-noise-filter",this.handleKrispNoiseFilterEnable),this.processor.processedTrack.addEventListener("disable-lk-krisp-noise-filter",this.handleKrispNoiseFilterDisable)),this.emit(e.TrackEvent.TrackProcessorUpdate,this.processor)}finally{n()}}))}setAudioContext(e){this.audioContext=e}getSenderStats(){return Di(this,void 0,void 0,(function*(){var e;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 Di(this,void 0,void 0,(function*(){const t=yield function(e){return Di(this,arguments,void 0,(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:200;return function*(){const i=$s();if(i){const n=i.createAnalyser();n.fftSize=2048;const s=n.frequencyBinCount,r=new Uint8Array(s);i.createMediaStreamSource(new MediaStream([e.mediaStreamTrack])).connect(n),yield sr(t),n.getByteTimeDomainData(r);const o=r.some((e=>128!==e&&0!==e));return i.close(),!o}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 wo(e,t,i){switch(e.kind){case"audio":return new Eo(e,t,!1,void 0,i);case"video":return new jo(e,t,!1,i);default:throw new vs("unsupported track type: ".concat(e.kind))}}const Po=Object.values(qs),Ro=Object.values(Ks),Io=Object.values(Ws),Oo=[qs.h180,qs.h360],xo=[Ks.h180,Ks.h360],Do=e=>[{scaleResolutionDownBy:2,fps:e.encoding.maxFramerate}].map((t=>{var i,n;return new Us(Math.floor(e.width/t.scaleResolutionDownBy),Math.floor(e.height/t.scaleResolutionDownBy),Math.max(15e4,Math.floor(e.encoding.maxBitrate/(Math.pow(t.scaleResolutionDownBy,2)*((null!==(i=e.encoding.maxFramerate)&&void 0!==i?i:30)/(null!==(n=t.fps)&&void 0!==n?n:30))))),t.fps,e.encoding.priority)})),Mo=["q","h","f"];function No(e,t,i,n){var s,r;let o=null==n?void 0:n.videoEncoding;e&&(o=null==n?void 0:n.screenShareEncoding);const a=null==n?void 0:n.simulcast,c=null==n?void 0:n.scalabilityMode,d=null==n?void 0:n.videoCodec;if(!o&&!a&&!c||!t||!i)return[{}];o||(o=function(e,t,i,n){const s=function(e,t,i){if(e)return Io;const n=t>i?t/i:i/t;if(Math.abs(n-16/9)<Math.abs(n-4/3))return Po;return Ro}(e,t,i);let{encoding:r}=s[0];const o=Math.max(t,i);for(let e=0;e<s.length;e+=1){const t=s[e];if(r=t.encoding,t.width>=o)break}if(n)switch(n){case"av1":r=Object.assign({},r),r.maxBitrate=.7*r.maxBitrate;break;case"vp9":r=Object.assign({},r),r.maxBitrate=.85*r.maxBitrate}return r}(e,t,i,d),Ei.debug("using video encoding",o));const l=new Us(t,i,o.maxBitrate,o.maxFramerate,o.priority);if(c&&dr(d)){const e=new Uo(c),t=[];if(e.spatial>3)throw new Error("unsupported scalabilityMode: ".concat(c));const i=Ds();if(pr()||vr()||"Chrome"===(null==i?void 0:i.name)&&Cr(null==i?void 0:i.version,"113")<0){const i="h"==e.suffix?2:3;for(let n=0;n<e.spatial;n+=1)t.push({rid:Mo[2-n],maxBitrate:o.maxBitrate/Math.pow(i,n),maxFramerate:l.encoding.maxFramerate});t[0].scalabilityMode=c}else t.push({maxBitrate:o.maxBitrate,maxFramerate:l.encoding.maxFramerate,scalabilityMode:c});return l.encoding.priority&&(t[0].priority=l.encoding.priority,t[0].networkPriority=l.encoding.priority),Ei.debug("using svc encoding",{encodings:t}),t}if(!a)return[o];let u,h=[];if(h=e?null!==(s=Lo(null==n?void 0:n.screenShareSimulcastLayers))&&void 0!==s?s:_o(e,l):null!==(r=Lo(null==n?void 0:n.videoSimulcastLayers))&&void 0!==r?r:_o(e,l),h.length>0){const e=h[0];h.length>1&&([,u]=h);const n=Math.max(t,i);if(n>=960&&u)return Ao(t,i,[e,u,l]);if(n>=480)return Ao(t,i,[e,l])}return Ao(t,i,[l])}function _o(e,t){if(e)return Do(t);const{width:i,height:n}=t,s=i>n?i/n:n/i;return Math.abs(s-16/9)<Math.abs(s-4/3)?Oo:xo}function Ao(e,t,i){const n=[];if(i.forEach(((i,s)=>{if(s>=Mo.length)return;const r=Math.min(e,t),o={rid:Mo[s],scaleResolutionDownBy:Math.max(1,r/Math.min(i.width,i.height)),maxBitrate:i.encoding.maxBitrate};i.encoding.maxFramerate&&(o.maxFramerate=i.encoding.maxFramerate);const a=hr()||0===s;i.encoding.priority&&a&&(o.priority=i.encoding.priority,o.networkPriority=i.encoding.priority),n.push(o)})),vr()&&"ios"===yr()){let e;n.forEach((t=>{e?t.maxFramerate&&t.maxFramerate>e&&(e=t.maxFramerate):e=t.maxFramerate}));let t=!0;n.forEach((i=>{var n;i.maxFramerate!=e&&(t&&(t=!1,Ei.info("Simulcast on iOS React-Native requires all encodings to share the same framerate.")),Ei.info('Setting framerate of encoding "'.concat(null!==(n=i.rid)&&void 0!==n?n:"",'" to ').concat(e)),i.maxFramerate=e)}))}return n}function Lo(e){if(e)return e.sort(((e,t)=>{const{encoding:i}=e,{encoding:n}=t;return i.maxBitrate>n.maxBitrate?1:i.maxBitrate<n.maxBitrate?-1:i.maxBitrate===n.maxBitrate&&i.maxFramerate&&n.maxFramerate?i.maxFramerate>n.maxFramerate?1:-1:0}))}class Uo{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 jo extends Fr{get sender(){return this._sender}set sender(e){this._sender=e,this.degradationPreference&&this.setDegradationPreference(this.degradationPreference)}constructor(e,t){let i=!(arguments.length>2&&void 0!==arguments[2])||arguments[2],n=arguments.length>3?arguments[3]:void 0;super(e,Hs.Kind.Video,t,i,n),this.simulcastCodecs=new Map,this.degradationPreference="balanced",this.monitorSender=()=>Di(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,i)=>{var n;const s=null===(n=this.prevStats)||void 0===n?void 0:n.get(i);e+=So(t,s)})),this._currentBitrate=e}this.prevStats=t})),this.senderLock=new _r}get isSimulcast(){return!!(this.sender&&this.sender.getParameters().encodings.length>1)}startMonitor(e){var t;if(this.signalClient=e,!fr())return;const i=null===(t=this.sender)||void 0===t?void 0:t.getParameters();i&&(this.encodings=i.encodings),this.monitorInterval||(this.monitorInterval=setInterval((()=>{this.monitorSender()}),Co))}stop(){this._mediaStreamTrack.getConstraints(),this.simulcastCodecs.forEach((e=>{e.mediaStreamTrack.stop()})),super.stop()}pauseUpstream(){const e=Object.create(null,{pauseUpstream:{get:()=>super.pauseUpstream}});return Di(this,void 0,void 0,(function*(){var t,i,n,s,r;yield e.pauseUpstream.call(this);try{for(var o,a=!0,c=Ni(this.simulcastCodecs.values());!(t=(o=yield c.next()).done);a=!0){s=o.value,a=!1;const e=s;yield null===(r=e.sender)||void 0===r?void 0:r.replaceTrack(null)}}catch(e){i={error:e}}finally{try{a||t||!(n=c.return)||(yield n.call(c))}finally{if(i)throw i.error}}}))}resumeUpstream(){const e=Object.create(null,{resumeUpstream:{get:()=>super.resumeUpstream}});return Di(this,void 0,void 0,(function*(){var t,i,n,s,r;yield e.resumeUpstream.call(this);try{for(var o,a=!0,c=Ni(this.simulcastCodecs.values());!(t=(o=yield c.next()).done);a=!0){s=o.value,a=!1;const e=s;yield null===(r=e.sender)||void 0===r?void 0:r.replaceTrack(e.mediaStreamTrack)}}catch(e){i={error:e}}finally{try{a||t||!(n=c.return)||(yield n.call(c))}finally{if(i)throw i.error}}}))}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return Di(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!==Hs.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 Di(this,void 0,void 0,(function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.source!==Hs.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(){return Di(this,void 0,void 0,(function*(){var e;if(!(null===(e=this.sender)||void 0===e?void 0:e.getStats))return[];const t=[],i=yield this.sender.getStats();return i.forEach((e=>{var n;if("outbound-rtp"===e.type){const s={type:"video",streamId:e.id,frameHeight:e.frameHeight,frameWidth:e.frameWidth,framesPerSecond:e.framesPerSecond,framesSent:e.framesSent,firCount:e.firCount,pliCount:e.pliCount,nackCount:e.nackCount,packetsSent:e.packetsSent,bytesSent:e.bytesSent,qualityLimitationReason:e.qualityLimitationReason,qualityLimitationDurations:e.qualityLimitationDurations,qualityLimitationResolutionChanges:e.qualityLimitationResolutionChanges,rid:null!==(n=e.rid)&&void 0!==n?n:e.id,retransmittedPacketsSent:e.retransmittedPacketsSent,targetBitrate:e.targetBitrate,timestamp:e.timestamp},r=i.get(e.remoteId);r&&(s.jitter=r.jitter,s.packetsLost=r.packetsLost,s.roundTripTime=r.roundTripTime),t.push(s)}})),t.sort(((e,t)=>{var i,n;return(null!==(i=t.frameWidth)&&void 0!==i?i:0)-(null!==(n=e.frameWidth)&&void 0!==n?n:0)})),t}))}setPublishingQuality(t){const i=[];for(let n=e.VideoQuality.LOW;n<=e.VideoQuality.HIGH;n+=1)i.push(new ti({quality:n,enabled:n<=t}));this.log.debug("setting publishing quality. max quality ".concat(t),this.logContext),this.setPublishingLayers(i)}setDeviceId(e){return Di(this,void 0,void 0,(function*(){return this._constraints.deviceId===e&&this._mediaStreamTrack.getSettings().deviceId===Ar(e)||(this._constraints.deviceId=e,this.isMuted||(yield this.restartTrack()),this.isMuted||Ar(e)===this._mediaStreamTrack.getSettings().deviceId)}))}restartTrack(e){return Di(this,void 0,void 0,(function*(){var t,i,n,s;let r;if(e){const t=Xs({video:e});"boolean"!=typeof t.video&&(r=t.video)}yield this.restart(r);try{for(var o,a=!0,c=Ni(this.simulcastCodecs.values());!(t=(o=yield c.next()).done);a=!0){s=o.value,a=!1;const e=s;e.sender&&(e.mediaStreamTrack=this.mediaStreamTrack.clone(),yield e.sender.replaceTrack(e.mediaStreamTrack))}}catch(e){i={error:e}}finally{try{a||t||!(n=c.return)||(yield n.call(c))}finally{if(i)throw i.error}}}))}setProcessor(e){const t=Object.create(null,{setProcessor:{get:()=>super.setProcessor}});return Di(this,arguments,void 0,(function(e){var i=this;let n=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return function*(){var s,r,o,a,c,d;if(yield t.setProcessor.call(i,e,n),null===(c=i.processor)||void 0===c?void 0:c.processedTrack)try{for(var l,u=!0,h=Ni(i.simulcastCodecs.values());!(s=(l=yield h.next()).done);u=!0){a=l.value,u=!1;const e=a;yield null===(d=e.sender)||void 0===d?void 0:d.replaceTrack(i.processor.processedTrack)}}catch(e){r={error:e}}finally{try{u||s||!(o=h.return)||(yield o.call(h))}finally{if(r)throw r.error}}}()}))}setDegradationPreference(e){return Di(this,void 0,void 0,(function*(){if(this.degradationPreference=e,this.sender)try{this.log.debug("setting degradationPreference to ".concat(e),this.logContext);const t=this.sender.getParameters();t.degradationPreference=e,this.sender.setParameters(t)}catch(e){this.log.warn("failed to set degradationPreference",Object.assign({error:e},this.logContext))}}))}addSimulcastTrack(e,t){if(this.simulcastCodecs.has(e))return void this.log.error("".concat(e," already added, skipping adding simulcast codec"),this.logContext);const i={codec:e,mediaStreamTrack:this.mediaStreamTrack.clone(),sender:void 0,encodings:t};return this.simulcastCodecs.set(e,i),i}setSimulcastTrackSender(e,t){const i=this.simulcastCodecs.get(e);i&&(i.sender=t,setTimeout((()=>{this.subscribedCodecs&&this.setPublishingCodecs(this.subscribedCodecs)}),5e3))}setPublishingCodecs(e){return Di(this,void 0,void 0,(function*(){var t,i,n,s,r,o,a;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,i=Ni(e);!(s=(n=yield i.next()).done);t=!0){a=n.value,t=!1;const e=a;if(this.codec&&this.codec!==e.codec){const t=this.simulcastCodecs.get(e.codec);if(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 Fo(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){r={error:e}}finally{try{t||s||!(o=i.return)||(yield o.call(i))}finally{if(r)throw r.error}}return c}))}setPublishingLayers(e){return Di(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 Fo(this.sender,this.encodings,e,this.senderLock,this.log,this.logContext))}))}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return Di(this,void 0,void 0,(function*(){yield e.handleAppVisibilityChanged.call(this),gr()&&this.isInBackground&&this.source===Hs.Source.Camera&&(this._mediaStreamTrack.enabled=!1)}))}}function Fo(e,t,i,n,s,r){return Di(this,void 0,void 0,(function*(){const o=yield n.lock();s.debug("setPublishingLayersForSender",Object.assign(Object.assign({},r),{sender:e,qualities:i,senderEncodings:t}));try{const n=e.getParameters(),{encodings:o}=n;if(!o)return;if(o.length!==t.length)return void s.warn("cannot set publishing layers, encodings mismatch",Object.assign(Object.assign({},r),{encodings:o,senderEncodings:t}));let a=!1;!1&&o[0].scalabilityMode||o.forEach(((e,n)=>{var o;let c=null!==(o=e.rid)&&void 0!==o?o:"";""===c&&(c="q");const d=Bo(c),l=i.find((e=>e.quality===d));l&&e.active!==l.enabled&&(a=!0,e.active=l.enabled,s.debug("setting layer ".concat(l.quality," to ").concat(e.active?"enabled":"disabled"),r),hr()&&(l.enabled?(e.scaleResolutionDownBy=t[n].scaleResolutionDownBy,e.maxBitrate=t[n].maxBitrate,e.maxFrameRate=t[n].maxFrameRate):(e.scaleResolutionDownBy=4,e.maxBitrate=10,e.maxFrameRate=2)))})),a&&(n.encodings=o,s.debug("setting encodings",Object.assign(Object.assign({},r),{encodings:n.encodings})),yield e.setParameters(n))}finally{o()}}))}function Bo(t){switch(t){case"f":default:return e.VideoQuality.HIGH;case"h":return e.VideoQuality.MEDIUM;case"q":return e.VideoQuality.LOW}}function Vo(t,i,n,s){if(!n)return[new at({quality:e.VideoQuality.HIGH,width:t,height:i,bitrate:0,ssrc:0})];if(s){const s=n[0].scalabilityMode,r=new Uo(s),o=[],a="h"==r.suffix?1.5:2,c="h"==r.suffix?2:3;for(let s=0;s<r.spatial;s+=1)o.push(new at({quality:Math.min(e.VideoQuality.HIGH,r.spatial-1)-s,width:Math.ceil(t/Math.pow(a,s)),height:Math.ceil(i/Math.pow(a,s)),bitrate:n[0].maxBitrate?Math.ceil(n[0].maxBitrate/Math.pow(c,s)):0,ssrc:0}));return o}return n.map((e=>{var n,s,r;const o=null!==(n=e.scaleResolutionDownBy)&&void 0!==n?n:1;let a=Bo(null!==(s=e.rid)&&void 0!==s?s:"");return new at({quality:a,width:Math.ceil(t/o),height:Math.ceil(i/o),bitrate:null!==(r=e.maxBitrate)&&void 0!==r?r:0,ssrc:0})}))}const qo="_lossy",Ko="_reliable",Wo="leave-reconnect";var Go;!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"}(Go||(Go={}));class Ho extends Yi.EventEmitter{get isClosed(){return this._isClosed}get pendingReconnect(){return!!this.reconnectTimeout}constructor(t){var i;super(),this.options=t,this.rtcConfig={},this.peerConnectionTimeout=bo.peerConnectionTimeout,this.fullReconnectOnNext=!1,this.subscriberPrimary=!1,this.pcState=Go.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=Ei,this.handleDataChannel=e=>Di(this,[e],void 0,(function(e){var t=this;let{channel:i}=e;return function*(){if(i){if(i.label===Ko)t.reliableDCSub=i;else{if(i.label!==qo)return;t.lossyDCSub=i}t.log.debug("on data channel ".concat(i.id,", ").concat(i.label),t.logContext),i.onmessage=t.handleDataMessage}}()})),this.handleDataMessage=t=>Di(this,void 0,void 0,(function*(){var i,n;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 r=ct.fromBinary(new Uint8Array(s));"speaker"===(null===(i=r.value)||void 0===i?void 0:i.case)?this.emit(e.EngineEvent.ActiveSpeakersUpdate,r.value.value.speakers):("user"===(null===(n=r.value)||void 0===n?void 0:n.case)&&function(e,t){const i=e.participantIdentity?e.participantIdentity:t.participantIdentity;e.participantIdentity=i,t.participantIdentity=i;const n=0!==e.destinationIdentities.length?e.destinationIdentities:t.destinationIdentities;e.destinationIdentities=n,t.destinationIdentities=n}(r,r.value.value),this.emit(e.EngineEvent.DataPacketReceived,r))}finally{s()}})),this.handleDataError=e=>{const t=0===e.currentTarget.maxRetransmits?"lossy":"reliable";if(e instanceof ErrorEvent&&e.error){const{error:i}=e.error;this.log.error("DataChannel error on ".concat(t,": ").concat(e.message),Object.assign(Object.assign({},this.logContext),{error:i}))}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?dt.LOSSY:dt.RELIABLE;this.updateAndEmitDCBufferStatus(t)},this.handleDisconnect=(t,i)=>{if(this._isClosed)return;this.log.warn("".concat(t," disconnected"),this.logContext),0===this.reconnectAttempts&&(this.reconnectStart=Date.now());const n=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 r=this.getNextRetryDelay({elapsedMs:s,retryCount:this.reconnectAttempts});null!==r?(t===Wo&&(r=0),this.log.debug("reconnecting in ".concat(r,"ms"),this.logContext),this.clearReconnectTimeout(),this.token&&this.regionUrlProvider&&this.regionUrlProvider.updateToken(this.token),this.reconnectTimeout=Ls.setTimeout((()=>this.attemptReconnect(i).finally((()=>this.reconnectTimeout=void 0))),r)):n(s)},this.waitForRestarted=()=>new Promise(((t,i)=>{this.pcState===Go.Connected&&t();const n=()=>{this.off(e.EngineEvent.Disconnected,s),t()},s=()=>{this.off(e.EngineEvent.Restarted,n),i()};this.once(e.EngineEvent.Restarted,n),this.once(e.EngineEvent.Disconnected,s)})),this.updateAndEmitDCBufferStatus=t=>{const i=this.isBufferStatusLow(t);void 0!==i&&i!==this.dcBufferStatus.get(t)&&(this.dcBufferStatus.set(t,i),this.emit(e.EngineEvent.DCBufferStatusChanged,i,t))},this.isBufferStatusLow=e=>{const t=this.dataChannelForKind(e);if(t)return t.bufferedAmount<=t.bufferedAmountLowThreshold},this.handleBrowserOnLine=()=>{this.client.currentState===Wr.RECONNECTING&&(this.clearReconnectTimeout(),this.attemptReconnect(ze.RR_SIGNAL_DISCONNECTED))},this.log=Pi(null!==(i=t.loggerName)&&void 0!==i?i:e.LoggerNames.Engine),this.loggerOptions={loggerName:t.loggerName,loggerContextCb:()=>this.logContext},this.client=new Gr(void 0,this.loggerOptions),this.client.signalLatency=this.options.expSignalLatency,this.reconnectPolicy=this.options.reconnectPolicy,this.registerOnLineListener(),this.closingLock=new _r,this.dataProcessLock=new _r,this.dcBufferStatus=new Map([[dt.LOSSY,!0],[dt.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),this.client.onRequestResponse=t=>this.emit(e.EngineEvent.SignalRequestResponse,t)}get logContext(){var e,t,i,n,s,r,o,a;return{room:null===(t=null===(e=this.latestJoinResponse)||void 0===e?void 0:e.room)||void 0===t?void 0:t.name,roomID:null===(n=null===(i=this.latestJoinResponse)||void 0===i?void 0:i.room)||void 0===n?void 0:n.sid,participant:null===(r=null===(s=this.latestJoinResponse)||void 0===s?void 0:s.participant)||void 0===r?void 0:r.identity,pID:null===(a=null===(o=this.latestJoinResponse)||void 0===o?void 0:o.participant)||void 0===a?void 0:a.sid}}join(e,t,i,n){return Di(this,void 0,void 0,(function*(){this.url=e,this.token=t,this.signalOpts=i,this.maxJoinAttempts=i.maxRetries;try{this.joinAttempts+=1,this.setupSignalClientCallbacks();const s=yield this.client.join(e,t,i,n);return this._isClosed=!1,this.latestJoinResponse=s,this.subscriberPrimary=s.subscriberPrimary,this.pcManager||(yield this.configure(s)),this.subscriberPrimary&&!s.fastPublish||this.negotiate(),this.clientConfiguration=s.clientConfiguration,s}catch(s){if(s instanceof gs&&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,i,n);throw s}}))}close(){return Di(this,void 0,void 0,(function*(){const t=yield this.closingLock.lock();if(this.isClosed)t();else try{this._isClosed=!0,this.emit(e.EngineEvent.Closing),this.removeAllListeners(),this.deregisterOnLineListener(),this.clearPendingReconnect(),yield this.cleanupPeerConnections(),yield this.cleanupClient()}finally{t()}}))}cleanupPeerConnections(){return Di(this,void 0,void 0,(function*(){var e;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 Di(this,void 0,void 0,(function*(){yield this.client.close(),this.client.resetCallbacks()}))}addTrack(e){if(this.pendingTrackResolvers[e.cid])throw new vs("a track with the same ID has already been published");return new Promise(((t,i)=>{const n=setTimeout((()=>{delete this.pendingTrackResolvers[e.cid],i(new gs("publication of local track timed out, no response from server"))}),1e4);this.pendingTrackResolvers[e.cid]={resolve:e=>{clearTimeout(n),t(e)},reject:()=>{clearTimeout(n),i(new Error("Cancelled publication by calling unpublish"))}},this.client.sendAddTrack(e)}))}removeTrack(e){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(){return Di(this,void 0,void 0,(function*(){var e;return null===(e=this.pcManager)||void 0===e?void 0:e.getConnectedAddress()}))}setRegionUrlProvider(e){this.regionUrlProvider=e}configure(t){return Di(this,void 0,void 0,(function*(){var i,n;if(this.pcManager&&this.pcManager.currentState!==yo.NEW)return;this.participantSid=null===(i=t.participant)||void 0===i?void 0:i.sid;const s=this.makeRTCConfiguration(t);var r;this.pcManager=new To(s,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=(i,n,s)=>Di(this,void 0,void 0,(function*(){if(this.log.debug("primary PC state changed ".concat(i),this.logContext),["closed","disconnected","failed"].includes(n)&&(this.publisherConnectionPromise=void 0),i===yo.CONNECTED){const i=this.pcState===Go.New;this.pcState=Go.Connected,i&&this.emit(e.EngineEvent.Connected,t)}else i===yo.FAILED&&this.pcState===Go.Connected&&(this.pcState=Go.Disconnected,this.handleDisconnect("peerconnection failed","failed"===s?ze.RR_SUBSCRIBER_FAILED:ze.RR_PUBLISHER_FAILED));const r=this.client.isDisconnected||this.client.currentState===Wr.RECONNECTING,o=[yo.FAILED,yo.CLOSING,yo.CLOSED].includes(i);r&&o&&!this._isClosed&&this.emit(e.EngineEvent.Offline)})),this.pcManager.onTrack=t=>{this.emit(e.EngineEvent.MediaTrackAdded,t.track,t.streams[0],t.receiver)},void 0!==(r=null===(n=t.serverInfo)||void 0===n?void 0:n.protocol)&&r>13||this.createDataChannels()}))}setupSignalClientCallbacks(){this.client.onAnswer=e=>Di(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=>Di(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:i}=this.pendingTrackResolvers[e.cid];delete this.pendingTrackResolvers[e.cid],i(e.track)},this.client.onLocalTrackUnpublished=t=>{this.emit(e.EngineEvent.LocalTrackUnpublished,t)},this.client.onLocalTrackSubscribed=t=>{this.emit(e.EngineEvent.LocalTrackSubscribed,t)},this.client.onTokenRefresh=e=>{this.token=e},this.client.onRemoteMuteChanged=(t,i)=>{this.emit(e.EngineEvent.RemoteMute,t,i)},this.client.onSubscribedQualityUpdate=t=>{this.emit(e.EngineEvent.SubscribedQualityUpdate,t)},this.client.onClose=()=>{this.handleDisconnect("signal",ze.RR_SIGNAL_DISCONNECTED)},this.client.onLeave=t=>{switch(this.log.debug("client leave request",Object.assign(Object.assign({},this.logContext),{reason:null==t?void 0:t.reason})),t.regions&&this.regionUrlProvider&&(this.log.debug("updating regions",this.logContext),this.regionUrlProvider.setServerReportedRegions(t.regions)),t.action){case Gt.DISCONNECT:this.emit(e.EngineEvent.Disconnected,null==t?void 0:t.reason),this.close();break;case Gt.RECONNECT:this.fullReconnectOnNext=!0,this.handleDisconnect(Wo);break;case Gt.RESUME:this.handleDisconnect(Wo)}}}makeRTCConfiguration(e){var t;const i=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),i.encodedInsertableStreams=!0),e.iceServers&&!i.iceServers){const t=[];e.iceServers.forEach((e=>{const i={urls:e.urls};e.username&&(i.username=e.username),e.credential&&(i.credential=e.credential),t.push(i)})),i.iceServers=t}return e.clientConfiguration&&e.clientConfiguration.forceRelay===Je.ENABLED&&(i.iceTransportPolicy="relay"),i.sdpSemantics="unified-plan",i.continualGatheringPolicy="gather_continually",i}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(qo,{ordered:!0,maxRetransmits:0}),this.reliableDC=this.pcManager.createPublisherDataChannel(Ko,{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)}createSender(e,t,i){return Di(this,void 0,void 0,(function*(){if(rr()){return yield this.createTransceiverRTCRtpSender(e,t,i)}if(or()){this.log.warn("using add-track fallback",this.logContext);return yield this.createRTCRtpSender(e.mediaStreamTrack)}throw new bs("Required webRTC APIs not supported on this device")}))}createSimulcastSender(e,t,i,n){return Di(this,void 0,void 0,(function*(){if(rr())return this.createSimulcastTransceiverSender(e,t,i,n);if(or())return this.log.debug("using add-track fallback",this.logContext),this.createRTCRtpSender(e.mediaStreamTrack);throw new bs("Cannot stream on this device")}))}createTransceiverRTCRtpSender(e,t,i){return Di(this,void 0,void 0,(function*(){if(!this.pcManager)throw new bs("publisher is closed");const n=[];e.mediaStream&&n.push(e.mediaStream),e instanceof jo&&(e.codec=t.videoCodec);const s={direction:"sendonly",streams:n};i&&(s.sendEncodings=i);return(yield this.pcManager.addPublisherTransceiver(e.mediaStreamTrack,s)).sender}))}createSimulcastTransceiverSender(e,t,i,n){return Di(this,void 0,void 0,(function*(){if(!this.pcManager)throw new bs("publisher is closed");const s={direction:"sendonly"};n&&(s.sendEncodings=n);const r=yield this.pcManager.addPublisherTransceiver(t.mediaStreamTrack,s);if(i.videoCodec)return e.setSimulcastTrackSender(i.videoCodec,r.sender),r.sender}))}createRTCRtpSender(e){return Di(this,void 0,void 0,(function*(){if(!this.pcManager)throw new bs("publisher is closed");return this.pcManager.addPublisherTrack(e)}))}attemptReconnect(t){return Di(this,void 0,void 0,(function*(){var i,n,s;if(!this._isClosed)if(this.attemptingReconnect)Ei.warn("already attempting reconnect, returning early",this.logContext);else{(null===(i=this.clientConfiguration)||void 0===i?void 0:i.resumeConnection)!==Je.DISABLED&&(null!==(s=null===(n=this.pcManager)||void 0===n?void 0:n.currentState)&&void 0!==s?s:yo.NEW)!==yo.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 i=!0;t instanceof bs?(this.log.debug("received unrecoverable error",Object.assign(Object.assign({},this.logContext),{error:t})),i=!1):t instanceof Jo||(this.fullReconnectOnNext=!0),i?this.handleDisconnect("reconnect",ze.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){return Di(this,void 0,void 0,(function*(){var i,n,s;try{if(!this.url||!this.token)throw new bs("could not reconnect, url or token not saved");let n;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 Jo;n=yield this.join(null!=t?t:this.url,this.token,this.signalOpts)}catch(e){if(e instanceof gs&&0===e.reason)throw new bs("could not reconnect, token might be expired");throw new Jo}if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(this.client.setReconnected(),this.emit(e.EngineEvent.SignalRestarted,n),yield this.waitForPCReconnected(),this.client.currentState!==Wr.CONNECTED)throw new Jo("Signal connection got severed during reconnect");null===(i=this.regionUrlProvider)||void 0===i||i.resetAttempts(),this.emit(e.EngineEvent.Restarted)}catch(e){const t=yield null===(n=this.regionUrlProvider)||void 0===n?void 0:n.getNextBestRegionUrl();if(t)return void(yield this.restartConnection(t));throw null===(s=this.regionUrlProvider)||void 0===s||s.resetAttempts(),e}}))}resumeConnection(t){return Di(this,void 0,void 0,(function*(){var i;if(!this.url||!this.token)throw new bs("could not reconnect, url or token not saved");if(!this.pcManager)throw new bs("publisher and subscriber connections unset");let n;this.log.info("resuming signal connection, attempt ".concat(this.reconnectAttempts),this.logContext),this.emit(e.EngineEvent.Resuming);try{this.setupSignalClientCallbacks(),n=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 gs&&0===e.reason)throw new bs("could not reconnect, token might be expired");if(e instanceof gs&&4===e.reason)throw e;throw new Jo(t)}if(this.emit(e.EngineEvent.SignalResumed),n){const e=this.makeRTCConfiguration(n);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!==Wr.CONNECTED)throw new Jo("Signal connection got severed during reconnect");this.client.setReconnected(),"open"===(null===(i=this.reliableDC)||void 0===i?void 0:i.readyState)&&null===this.reliableDC.id&&this.createDataChannels(),this.emit(e.EngineEvent.Resumed)}))}waitForPCInitialConnection(e,t){return Di(this,void 0,void 0,(function*(){if(!this.pcManager)throw new bs("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(t,e)}))}waitForPCReconnected(){return Di(this,void 0,void 0,(function*(){this.pcState=Go.Reconnecting,this.log.debug("waiting for peer connection to reconnect",this.logContext);try{if(yield sr(2e3),!this.pcManager)throw new bs("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(void 0,this.peerConnectionTimeout),this.pcState=Go.Connected}catch(e){throw this.pcState=Go.Disconnected,new gs("could not establish PC connection, ".concat(e.message))}}))}sendDataPacket(e,t){return Di(this,void 0,void 0,(function*(){const i=e.toBinary();yield this.ensurePublisherConnected(t);const n=this.dataChannelForKind(t);n&&n.send(i),this.updateAndEmitDCBufferStatus(t)}))}ensureDataTransportConnected(e){return Di(this,arguments,void 0,(function(e){var t=this;let i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.subscriberPrimary;return function*(){var n;if(!t.pcManager)throw new bs("PC manager is closed");const s=i?t.pcManager.subscriber:t.pcManager.publisher,r=i?"Subscriber":"Publisher";if(!s)throw new gs("".concat(r," connection not set"));let o=!1;i||t.dataChannelForKind(e,i)||(t.createDataChannels(),o=!0),o||i||t.pcManager.publisher.isICEConnected||"checking"===t.pcManager.publisher.getICEConnectionState()||(o=!0),o&&t.negotiate();const a=t.dataChannelForKind(e,i);if("open"===(null==a?void 0:a.readyState))return;const c=(new Date).getTime()+t.peerConnectionTimeout;for(;(new Date).getTime()<c;){if(s.isICEConnected&&"open"===(null===(n=t.dataChannelForKind(e,i))||void 0===n?void 0:n.readyState))return;yield sr(50)}throw new gs("could not establish ".concat(r," connection, state: ").concat(s.getICEConnectionState()))}()}))}ensurePublisherConnected(e){return Di(this,void 0,void 0,(function*(){this.publisherConnectionPromise||(this.publisherConnectionPromise=this.ensureDataTransportConnected(e,!1)),yield this.publisherConnectionPromise}))}verifyTransport(){return!!this.pcManager&&(this.pcManager.currentState===yo.CONNECTED&&!(!this.client.ws||this.client.ws.readyState===WebSocket.CLOSED))}negotiate(){return Di(this,void 0,void 0,(function*(){return new Promise(((t,i)=>Di(this,void 0,void 0,(function*(){if(!this.pcManager)return void i(new ys("PC manager is closed"));this.pcManager.requirePublisher(),0!=this.pcManager.publisher.getTransceivers().length||this.lossyDC||this.reliableDC||this.createDataChannels();const n=new AbortController,s=()=>{n.abort(),this.log.debug("engine disconnected while negotiation was ongoing",this.logContext),t()};this.isClosed&&i("cannot negotiate on closed engine"),this.on(e.EngineEvent.Closing,s),this.pcManager.publisher.once(uo,(t=>{const i=new Map;t.forEach((e=>{const t=e.codec.toLowerCase();var n;n=t,Fs.includes(n)&&i.set(e.payload,t)})),this.emit(e.EngineEvent.RTPVideoMapUpdate,i)}));try{yield this.pcManager.negotiate(n),t()}catch(e){e instanceof ys&&(this.fullReconnectOnNext=!0),this.handleDisconnect("negotiation",ze.RR_UNKNOWN),i(e)}finally{this.off(e.EngineEvent.Closing,s)}}))))}))}dataChannelForKind(e,t){if(t){if(e===dt.LOSSY)return this.lossyDCSub;if(e===dt.RELIABLE)return this.reliableDCSub}else{if(e===dt.LOSSY)return this.lossyDC;if(e===dt.RELIABLE)return this.reliableDC}}sendSyncState(e,t){var i,n;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(),r=this.pcManager.subscriber.getRemoteDescription(),o=null===(n=null===(i=this.signalOpts)||void 0===i?void 0:i.autoSubscribe)||void 0===n||n,a=new Array,c=new Array;e.forEach((e=>{e.isDesired!==o&&a.push(e.trackSid),e.isEnabled||c.push(e.trackSid)})),this.client.sendSyncState(new ai({answer:s?Jr({sdp:s.sdp,type:s.type}):void 0,offer:r?Jr({sdp:r.sdp,type:r.type}):void 0,subscription:new Bt({trackSids:a,subscribe:!o,participantTracks:[]}),publishTracks:tr(t),dataChannels:this.dataChannelsInfo(),trackSidsDisabled:c}))}failNext(){this.shouldFailNext=!0}dataChannelsInfo(){const e=[],t=(t,i)=>{void 0!==(null==t?void 0:t.id)&&null!==t.id&&e.push(new ci({label:t.label,id:t.id,target:i}))};return t(this.dataChannelForKind(dt.LOSSY),wt.PUBLISHER),t(this.dataChannelForKind(dt.RELIABLE),wt.PUBLISHER),t(this.dataChannelForKind(dt.LOSSY,!0),wt.SUBSCRIBER),t(this.dataChannelForKind(dt.RELIABLE,!0),wt.SUBSCRIBER),e}clearReconnectTimeout(){this.reconnectTimeout&&Ls.clearTimeout(this.reconnectTimeout)}clearPendingReconnect(){this.clearReconnectTimeout(),this.reconnectAttempts=0}registerOnLineListener(){fr()&&window.addEventListener("online",this.handleBrowserOnLine)}deregisterOnLineListener(){fr()&&window.removeEventListener("online",this.handleBrowserOnLine)}}class Jo extends Error{}class Qo{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 kr(this.serverUrl)}getServerUrl(){return this.serverUrl}getNextBestRegionUrl(e){return Di(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),Ei.debug("next region: ".concat(e.region)),e.url}return null}))}resetAttempts(){this.attemptedRegions=[]}fetchRegionSettings(e){return Di(this,void 0,void 0,(function*(){const t=yield fetch("".concat((i=this.serverUrl,"".concat(i.protocol.replace("ws","http"),"//").concat(i.host,"/settings")),"/regions"),{headers:{authorization:"Bearer ".concat(this.token)},signal:e});var i;if(t.ok){const e=yield t.json();return this.lastUpdateAt=Date.now(),e}throw new gs("Could not fetch region settings: ".concat(t.statusText),401===t.status?0:void 0,t.status)}))}setServerReportedRegions(e){this.regionSettings=e,this.lastUpdateAt=Date.now()}}class zo extends Hs{constructor(e,t,i,n,s){super(e,i,s),this.sid=t,this.receiver=n}setMuted(t){this.isMuted!==t&&(this.isMuted=t,this._mediaStreamTrack.enabled=!t,this.emit(t?e.TrackEvent.Muted:e.TrackEvent.Unmuted,this))}setMediaStream(t){this.mediaStream=t;const i=n=>{n.track===this._mediaStreamTrack&&(t.removeEventListener("removetrack",i),this.receiver&&"playoutDelayHint"in this.receiver&&(this.receiver.playoutDelayHint=void 0),this.receiver=void 0,this._currentBitrate=0,this.emit(e.TrackEvent.Ended,this))};t.addEventListener("removetrack",i)}start(){this.startMonitor(),super.enable()}stop(){this.stopMonitor(),super.disable()}getRTCStatsReport(){return Di(this,void 0,void 0,(function*(){var e;if(!(null===(e=this.receiver)||void 0===e?void 0:e.getStats))return;return yield this.receiver.getStats()}))}setPlayoutDelay(e){this.receiver?"playoutDelayHint"in this.receiver?this.receiver.playoutDelayHint=e:this.log.warn("Playout delay not supported in this browser"):this.log.warn("Cannot set playout delay, track already ended")}getPlayoutDelay(){if(this.receiver){if("playoutDelayHint"in this.receiver)return this.receiver.playoutDelayHint;this.log.warn("Playout delay not supported in this browser")}else this.log.warn("Cannot get playout delay, track already ended");return 0}startMonitor(){this.monitorInterval||(this.monitorInterval=setInterval((()=>this.monitorReceiver()),Co)),"undefined"!=typeof RTCRtpReceiver&&"getSynchronizationSources"in RTCRtpReceiver&&this.registerTimeSyncUpdate()}registerTimeSyncUpdate(){const t=()=>{var i;this.timeSyncHandle=requestAnimationFrame((()=>t()));const n=null===(i=this.receiver)||void 0===i?void 0:i.getSynchronizationSources()[0];if(n){const{timestamp:t,rtpTimestamp:i}=n;i&&this.rtpTimestamp!==i&&(this.emit(e.TrackEvent.TimeSyncUpdate,{timestamp:t,rtpTimestamp:i}),this.rtpTimestamp=i)}};t()}}class Yo extends zo{constructor(e,t,i,n,s,r){super(e,t,Hs.Kind.Audio,i,r),this.monitorReceiver=()=>Di(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=So(e,this.prevStats)),this.prevStats=e})),this.audioContext=n,this.webAudioPluginNodes=[],s&&(this.sinkId=s.deviceId)}setVolume(e){var t;for(const i of this.attachedElements)this.audioContext?null===(t=this.gainNode)||void 0===t||t.gain.setTargetAtTime(e,0,.1):i.volume=e;vr()&&this._mediaStreamTrack._setVolume(e),this.elementVolume=e}getVolume(){if(this.elementVolume)return this.elementVolume;if(vr())return 1;let e=0;return this.attachedElements.forEach((t=>{t.volume>e&&(e=t.volume)})),e}setSinkId(e){return Di(this,void 0,void 0,(function*(){this.sinkId=e,yield Promise.all(this.attachedElements.map((t=>{if(lr(t))return t.setSinkId(e)})))}))}attach(e){const t=0===this.attachedElements.length;return e?super.attach(e):e=super.attach(),this.sinkId&&lr(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,i){this.disconnectWebAudio(),this.sourceNode=t.createMediaStreamSource(i.srcObject);let n=this.sourceNode;this.webAudioPluginNodes.forEach((e=>{n.connect(e),n=e})),this.gainNode=t.createGain(),n.connect(this.gainNode),this.gainNode.connect(t.destination),this.elementVolume&&this.gainNode.gain.setTargetAtTime(this.elementVolume,0,.1),"running"!==t.state&&t.resume().then((()=>{"running"!==t.state&&this.emit(e.TrackEvent.AudioPlaybackFailed,new Error("Audio Context couldn't be started automatically"))})).catch((t=>{this.emit(e.TrackEvent.AudioPlaybackFailed,t)}))}disconnectWebAudio(){var e,t;null===(e=this.gainNode)||void 0===e||e.disconnect(),null===(t=this.sourceNode)||void 0===t||t.disconnect(),this.gainNode=void 0,this.sourceNode=void 0}getReceiverStats(){return Di(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 Xo extends zo{constructor(e,t,i,n,s){super(e,t,Hs.Kind.Video,i,s),this.elementInfos=[],this.monitorReceiver=()=>Di(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=So(e,this.prevStats)),this.prevStats=e})),this.debouncedHandleResize=Is((()=>{this.updateDimensions()}),100),this.adaptiveStreamSettings=n}get isAdaptiveStream(){return void 0!==this.adaptiveStreamSettings}get mediaStreamTrack(){return this._mediaStreamTrack}setMuted(e){super.setMuted(e),this.attachedElements.forEach((t=>{e?Qs(this._mediaStreamTrack,t):Js(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 $o(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 Di(this,void 0,void 0,(function*(){if(!this.receiver||!this.receiver.getStats)return;const e=yield this.receiver.getStats();let t,i="",n=new Map;return e.forEach((e=>{"inbound-rtp"===e.type?(i=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&&n.set(e.id,e)})),t&&""!==i&&n.get(i)&&(t.mimeType=n.get(i).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 Di(this,void 0,void 0,(function*(){yield e.handleAppVisibilityChanged.call(this),this.isAdaptiveStream&&this.updateVisibility()}))}updateVisibility(){var t,i;const n=this.elementInfos.reduce(((e,t)=>Math.max(e,t.visibilityChangedAt||0)),0),s=!(null!==(i=null===(t=this.adaptiveStreamSettings)||void 0===t?void 0:t.pauseVideoInBackground)&&void 0!==i&&!i)&&this.isInBackground,r=this.elementInfos.some((e=>e.pictureInPicture)),o=this.elementInfos.some((e=>e.visible))&&!s||r;this.lastVisible!==o&&(!o&&Date.now()-n<100?Ls.setTimeout((()=>{this.updateVisibility()}),100):(this.lastVisible=o,this.emit(e.TrackEvent.VisibilityChanged,o,this)))}updateDimensions(){var t,i;let n=0,s=0;const r=this.getPixelDensity();for(const e of this.elementInfos){const t=e.width()*r,i=e.height()*r;t+i>n+s&&(n=t,s=i)}(null===(t=this.lastDimensions)||void 0===t?void 0:t.width)===n&&(null===(i=this.lastDimensions)||void 0===i?void 0:i.height)===s||(this.lastDimensions={width:n,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 Tr();if(!t){return Tr()>2?2:1}return t}}class $o{get visible(){return this.isPiP||this.isIntersecting}get pictureInPicture(){return this.isPiP}constructor(e,t){this.onVisibilityChanged=e=>{var t;const{target:i,isIntersecting:n}=e;i===this.element&&(this.isIntersecting=n,this.visibilityChangedAt=Date.now(),null===(t=this.handleVisibilityChanged)||void 0===t||t.call(this))},this.onEnterPiP=()=>{var e;this.isPiP=!0,null===(e=this.handleVisibilityChanged)||void 0===e||e.call(this)},this.onLeavePiP=()=>{var e;this.isPiP=!1,null===(e=this.handleVisibilityChanged)||void 0===e||e.call(this)},this.element=e,this.isIntersecting=null!=t?t:Zo(e),this.isPiP=fr()&&document.pictureInPictureElement===e,this.visibilityChangedAt=0}width(){return this.element.clientWidth}height(){return this.element.clientHeight}observe(){this.isIntersecting=Zo(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,Ir().observe(this.element),Pr().observe(this.element),this.element.addEventListener("enterpictureinpicture",this.onEnterPiP),this.element.addEventListener("leavepictureinpicture",this.onLeavePiP)}stopObserving(){var e,t;null===(e=Ir())||void 0===e||e.unobserve(this.element),null===(t=Pr())||void 0===t||t.unobserve(this.element),this.element.removeEventListener("enterpictureinpicture",this.onEnterPiP),this.element.removeEventListener("leavepictureinpicture",this.onLeavePiP)}}function Zo(e){let t=e.offsetTop,i=e.offsetLeft;const n=e.offsetWidth,s=e.offsetHeight,{hidden:r}=e,{opacity:o,display:a}=getComputedStyle(e);for(;e.offsetParent;)t+=(e=e.offsetParent).offsetTop,i+=e.offsetLeft;return t<window.pageYOffset+window.innerHeight&&i<window.pageXOffset+window.innerWidth&&t+s>window.pageYOffset&&i+n>window.pageXOffset&&!r&&(""===o||parseFloat(o)>0)&&"none"!==a}class ea extends Yi.EventEmitter{constructor(t,i,n,s){var r;super(),this.metadataMuted=!1,this.encryption=st.NONE,this.log=Ei,this.handleMuted=()=>{this.emit(e.TrackEvent.Muted)},this.handleUnmuted=()=>{this.emit(e.TrackEvent.Unmuted)},this.log=Pi(null!==(r=null==s?void 0:s.loggerName)&&void 0!==r?r:e.LoggerNames.Publication),this.loggerContextCb=this.loggerContextCb,this.setMaxListeners(100),this.kind=t,this.trackSid=i,this.trackName=n,this.source=Hs.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)),ir(this))}get isMuted(){return this.metadataMuted}get isEnabled(){return!0}get isSubscribed(){return void 0!==this.track}get isEncrypted(){return this.encryption!==st.NONE}get audioTrack(){if(this.track instanceof Eo||this.track instanceof Yo)return this.track}get videoTrack(){if(this.track instanceof jo||this.track instanceof Xo)return this.track}updateInfo(e){this.trackSid=e.sid,this.trackName=e.name,this.source=Hs.sourceFromProto(e.source),this.mimeType=e.mimeType,this.kind===Hs.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,i;(t=e.SubscriptionStatus||(e.SubscriptionStatus={})).Desired="desired",t.Subscribed="subscribed",t.Unsubscribed="unsubscribed",(i=e.PermissionStatus||(e.PermissionStatus={})).Allowed="allowed",i.NotAllowed="not_allowed"}(ea||(ea={}));class ta extends ea{get isUpstreamPaused(){var e;return null===(e=this.track)||void 0===e?void 0:e.isUpstreamPaused}constructor(t,i,n,s){super(t,i.sid,i.name,s),this.track=void 0,this.handleTrackEnded=()=>{this.emit(e.TrackEvent.Ended)},this.updateInfo(i),this.setTrack(n)}setTrack(t){this.track&&this.track.off(e.TrackEvent.Ended,this.handleTrackEnded),super.setTrack(t),t&&t.on(e.TrackEvent.Ended,this.handleTrackEnded)}get isMuted(){return this.track?this.track.isMuted:super.isMuted}get audioTrack(){return super.audioTrack}get videoTrack(){return super.videoTrack}mute(){return Di(this,void 0,void 0,(function*(){var e;return null===(e=this.track)||void 0===e?void 0:e.mute()}))}unmute(){return Di(this,void 0,void 0,(function*(){var e;return null===(e=this.track)||void 0===e?void 0:e.unmute()}))}pauseUpstream(){return Di(this,void 0,void 0,(function*(){var e;yield null===(e=this.track)||void 0===e?void 0:e.pauseUpstream()}))}resumeUpstream(){return Di(this,void 0,void 0,(function*(){var e;yield null===(e=this.track)||void 0===e?void 0:e.resumeUpstream()}))}getTrackFeatures(){var e;if(this.track instanceof Eo){const t=this.track.mediaStreamTrack.getSettings(),i=new Set;return t.autoGainControl&&i.add(Xe.TF_AUTO_GAIN_CONTROL),t.echoCancellation&&i.add(Xe.TF_ECHO_CANCELLATION),t.noiseSuppression&&i.add(Xe.TF_NOISE_SUPPRESSION),t.channelCount&&t.channelCount>1&&i.add(Xe.TF_STEREO),(null===(e=this.options)||void 0===e?void 0:e.dtx)||i.add(Xe.TF_STEREO),this.track.enhancedNoiseCancellation&&i.add(Xe.TF_ENHANCED_NOISE_CANCELLATION),Array.from(i.values())}return[]}}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 ia extends Yi.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;return(null===(e=this.permissions)||void 0===e?void 0:e.agent)||this.kind===nt.AGENT}get kind(){return this._kind}get attributes(){return Object.freeze(Object.assign({},this._attributes))}constructor(t,i,n,s,r){let o=arguments.length>5&&void 0!==arguments[5]?arguments[5]:nt.STANDARD;var a;super(),this.audioLevel=0,this.isSpeaking=!1,this._connectionQuality=e.ConnectionQuality.Unknown,this.log=Ei,this.log=Pi(null!==(a=null==r?void 0:r.loggerName)&&void 0!==a?a:e.LoggerNames.Participant),this.loggerOptions=r,this.setMaxListeners(100),this.sid=t,this.identity=i,this.name=n,this.metadata=s,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this._kind=o,this._attributes={}}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(Hs.Source.Camera);return!(null===(e=null==t?void 0:t.isMuted)||void 0===e||e)}get isMicrophoneEnabled(){var e;const t=this.getTrackPublication(Hs.Source.Microphone);return!(null===(e=null==t?void 0:t.isMuted)||void 0===e||e)}get isScreenShareEnabled(){return!!this.getTrackPublication(Hs.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),this._setAttributes(e.attributes),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 i=this.metadata!==t,n=this.metadata;this.metadata=t,i&&this.emit(e.ParticipantEvent.ParticipantMetadataChanged,n)}_setName(t){const i=this.name!==t;this.name=t,i&&this.emit(e.ParticipantEvent.ParticipantNameChanged,t)}_setAttributes(t){const i=function(e,t){var i;void 0===e&&(e={}),void 0===t&&(t={});const n=[...Object.keys(t),...Object.keys(e)],s={};for(const r of n)e[r]!==t[r]&&(s[r]=null!==(i=t[r])&&void 0!==i?i:"");return s}(t,this.attributes);this._attributes=t,Object.keys(i).length>0&&this.emit(e.ParticipantEvent.AttributesChanged,i)}setPermissions(t){var i,n,s,r,o;const a=this.permissions,c=t.canPublish!==(null===(i=this.permissions)||void 0===i?void 0:i.canPublish)||t.canSubscribe!==(null===(n=this.permissions)||void 0===n?void 0:n.canSubscribe)||t.canPublishData!==(null===(s=this.permissions)||void 0===s?void 0:s.canPublishData)||t.hidden!==(null===(r=this.permissions)||void 0===r?void 0:r.hidden)||t.recorder!==(null===(o=this.permissions)||void 0===o?void 0:o.recorder)||t.canPublishSources.length!==this.permissions.canPublishSources.length||t.canPublishSources.some(((e,t)=>{var i;return e!==(null===(i=this.permissions)||void 0===i?void 0:i.canPublishSources[t])}));return this.permissions=t,c&&this.emit(e.ParticipantEvent.ParticipantPermissionsChanged,a),c}setIsSpeaking(t){t!==this.isSpeaking&&(this.isSpeaking=t,t&&(this.lastSpokeAt=new Date),this.emit(e.ParticipantEvent.IsSpeakingChanged,t))}setConnectionQuality(t){const i=this._connectionQuality;this._connectionQuality=function(t){switch(t){case He.EXCELLENT:return e.ConnectionQuality.Excellent;case He.GOOD:return e.ConnectionQuality.Good;case He.POOR:return e.ConnectionQuality.Poor;case He.LOST:return e.ConnectionQuality.Lost;default:return e.ConnectionQuality.Unknown}}(t),i!==this._connectionQuality&&this.emit(e.ParticipantEvent.ConnectionQualityChanged,this._connectionQuality)}setAudioContext(e){this.audioContext=e,this.audioTrackPublications.forEach((t=>(t.track instanceof Yo||t.track instanceof Eo)&&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 i=t;switch(i.track&&(i.track.sid=t.trackSid),this.trackPublications.set(t.trackSid,t),t.kind){case Hs.Kind.Audio:this.audioTrackPublications.set(t.trackSid,t);break;case Hs.Kind.Video:this.videoTrackPublications.set(t.trackSid,t)}}}class na extends ia{constructor(e,t,i,n){super(e,t,void 0,void 0,{loggerName:n.loggerName,loggerContextCb:()=>this.engine.logContext}),this.pendingPublishing=new Set,this.pendingPublishPromises=new Map,this.participantTrackPermissions=[],this.allParticipantsAllowedToSubscribe=!0,this.encryptionType=st.NONE,this.enabledPublishVideoCodecs=[],this.handleReconnecting=()=>{this.reconnectFuture||(this.reconnectFuture=new Nr)},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.handleSignalRequestResponse=e=>{const{requestId:t,reason:i,message:n}=e,s=this.pendingSignalRequests.get(t);s&&(i!==fi.OK&&s.reject(new Ts(n,i)),this.pendingSignalRequests.delete(t))},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,i,n;if(!e.participantSid&&!e.participantIdentity)throw new Error("Invalid track permission, must provide at least one of participantIdentity and participantSid");return new si({participantIdentity:null!==(t=e.participantIdentity)&&void 0!==t?t:"",participantSid:null!==(i=e.participantSid)&&void 0!==i?i:"",allTracks:null!==(n=e.allowAll)&&void 0!==n&&n,trackSids:e.allowedTrackSids||[]})}(e))))},this.onTrackUnmuted=e=>{this.onTrackMuted(e,e.isUpstreamPaused)},this.onTrackMuted=(e,t)=>{void 0===t&&(t=!0),e.sid?this.engine.updateMuteStatus(e.sid,t):this.log.error("could not update mute status for unpublished track",Object.assign(Object.assign({},this.logContext),ir(e)))},this.onTrackUpstreamPaused=e=>{this.log.debug("upstream paused",Object.assign(Object.assign({},this.logContext),ir(e))),this.onTrackMuted(e,!0)},this.onTrackUpstreamResumed=e=>{this.log.debug("upstream resumed",Object.assign(Object.assign({},this.logContext),ir(e))),this.onTrackMuted(e,e.isMuted)},this.onTrackFeatureUpdate=e=>{const t=this.audioTrackPublications.get(e.sid);t?this.engine.client.sendUpdateLocalAudioTrack(t.trackSid,t.getTrackFeatures()):this.log.warn("Could not update local audio track settings, missing publication for track ".concat(e.sid),this.logContext)},this.handleSubscribedQualityUpdate=e=>Di(this,void 0,void 0,(function*(){var t,i,n,s,r,o;if(!(null===(r=this.roomOptions)||void 0===r?void 0:r.dynacast))return;const a=this.videoTrackPublications.get(e.trackSid);if(a)if(e.subscribedCodecs.length>0){if(!a.videoTrack)return;const r=yield a.videoTrack.setPublishingCodecs(e.subscribedCodecs);try{for(var c,d=!0,l=Ni(r);!(t=(c=yield l.next()).done);d=!0){s=c.value,d=!1;const e=s;Bs(e)&&(this.log.debug("publish ".concat(e," for ").concat(a.videoTrack.sid),Object.assign(Object.assign({},this.logContext),ir(a))),yield this.publishAdditionalCodecForTrack(a.videoTrack,e,a.options))}}catch(e){i={error:e}}finally{try{d||t||!(n=l.return)||(yield n.call(l))}finally{if(i)throw i.error}}}else e.subscribedQualities.length>0&&(yield null===(o=a.videoTrack)||void 0===o?void 0:o.setPublishingLayers(e.subscribedQualities));else 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=>Di(this,void 0,void 0,(function*(){if(e.source===Hs.Source.ScreenShare||e.source===Hs.Source.ScreenShareAudio)this.log.debug("unpublishing local track due to TrackEnded",Object.assign(Object.assign({},this.logContext),ir(e))),this.unpublishTrack(e);else if(e.isUserProvided)yield e.mute();else if(e instanceof Eo||e instanceof jo)try{if(fr())try{const t=yield null===navigator||void 0===navigator?void 0:navigator.permissions.query({name:e.source===Hs.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),ir(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),ir(e))),yield e.restartTrack())}catch(t){this.log.warn("could not restart track, muting instead",Object.assign(Object.assign({},this.logContext),ir(e))),yield e.mute()}})),this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this.engine=i,this.roomOptions=n,this.setupEngine(i),this.activeDeviceMap=new Map,this.pendingSignalRequests=new Map}get lastCameraError(){return this.cameraError}get lastMicrophoneError(){return this.microphoneError}get isE2EEEnabled(){return this.encryptionType!==st.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 i=this.trackPublications.get(e);i&&i.track&&(t?i.mute():i.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).on(e.EngineEvent.SignalRequestResponse,this.handleSignalRequestResponse)}setMetadata(e){return Di(this,void 0,void 0,(function*(){yield this.requestMetadataUpdate({metadata:e})}))}setName(e){return Di(this,void 0,void 0,(function*(){yield this.requestMetadataUpdate({name:e})}))}setAttributes(e){return Di(this,void 0,void 0,(function*(){yield this.requestMetadataUpdate({attributes:e})}))}requestMetadataUpdate(e){return Di(this,arguments,void 0,(function(e){var t=this;let{metadata:i,name:n,attributes:s}=e;return function*(){return new Promise(((e,r)=>Di(t,void 0,void 0,(function*(){var t,o;try{let a=!1;const c=yield this.engine.client.sendUpdateLocalMetadata(null!==(t=null!=i?i:this.metadata)&&void 0!==t?t:"",null!==(o=null!=n?n:this.name)&&void 0!==o?o:"",s),d=performance.now();for(this.pendingSignalRequests.set(c,{resolve:e,reject:e=>{r(e),a=!0},values:{name:n,metadata:i,attributes:s}});performance.now()-d<5e3&&!a;){if((!n||this.name===n)&&(!i||this.metadata===i)&&(!s||Object.entries(s).every((e=>{let[t,i]=e;return this.attributes[t]===i}))))return this.pendingSignalRequests.delete(c),void e();yield sr(50)}r(new Ts("Request to update local metadata timed out","TimeoutError"))}catch(e){e instanceof Error&&r(e)}}))))}()}))}setCameraEnabled(e,t,i){return this.setTrackEnabled(Hs.Source.Camera,e,t,i)}setMicrophoneEnabled(e,t,i){return this.setTrackEnabled(Hs.Source.Microphone,e,t,i)}setScreenShareEnabled(e,t,i){return this.setTrackEnabled(Hs.Source.ScreenShare,e,t,i)}setPermissions(t){const i=this.permissions,n=super.setPermissions(t);return n&&i&&this.emit(e.ParticipantEvent.ParticipantPermissionsChanged,i),n}setE2EEEnabled(e){return Di(this,void 0,void 0,(function*(){this.encryptionType=e?st.GCM:st.NONE,yield this.republishAllTracks(void 0,!1)}))}setTrackEnabled(t,i,n,s){return Di(this,void 0,void 0,(function*(){var r,o;this.log.debug("setTrackEnabled",Object.assign(Object.assign({},this.logContext),{source:t,enabled:i}));let a=this.getTrackPublication(t);if(i)if(a)yield a.unmute();else{let i;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 Hs.Source.Camera:i=yield this.createTracks({video:null===(r=n)||void 0===r||r});break;case Hs.Source.Microphone:i=yield this.createTracks({audio:null===(o=n)||void 0===o||o});break;case Hs.Source.ScreenShare:i=yield this.createScreenTracks(Object.assign({},n));break;default:throw new vs(t)}const e=[];for(const t of i)this.log.info("publishing track",Object.assign(Object.assign({},this.logContext),ir(t))),e.push(this.publishTrack(t,s));const c=yield Promise.all(e);[a]=c}catch(t){throw null==i||i.forEach((e=>{e.stop()})),t instanceof Error&&!(t instanceof vs)&&this.emit(e.ParticipantEvent.MediaDevicesError,t),t}finally{this.pendingPublishing.delete(t)}}else if(a&&a.track)if(t===Hs.Source.ScreenShare){a=yield this.unpublishTrack(a.track);const e=this.getTrackPublication(Hs.Source.ScreenShareAudio);e&&e.track&&this.unpublishTrack(e.track)}else yield a.mute();return a}))}enableCameraAndMicrophone(){return Di(this,void 0,void 0,(function*(){if(!this.pendingPublishing.has(Hs.Source.Camera)&&!this.pendingPublishing.has(Hs.Source.Microphone)){this.pendingPublishing.add(Hs.Source.Camera),this.pendingPublishing.add(Hs.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(Hs.Source.Camera),this.pendingPublishing.delete(Hs.Source.Microphone)}}}))}createTracks(t){return Di(this,void 0,void 0,(function*(){var i,n;const s=zs(t,null===(i=this.roomOptions)||void 0===i?void 0:i.audioCaptureDefaults,null===(n=this.roomOptions)||void 0===n?void 0:n.videoCaptureDefaults),r=Xs(s);let o;try{o=yield navigator.mediaDevices.getUserMedia(r)}catch(e){throw e instanceof Error&&(r.audio&&(this.microphoneError=e),r.video&&(this.cameraError=e)),e}return r.audio&&(this.microphoneError=void 0,this.emit(e.ParticipantEvent.AudioStreamAcquired)),r.video&&(this.cameraError=void 0),Promise.all(o.getTracks().map((e=>Di(this,void 0,void 0,(function*(){const t="audio"===e.kind;let i,n=t?s.audio:s.video;"boolean"!=typeof n&&n||(n={});const a=t?r.audio:r.video;"boolean"!=typeof a&&(i=a);const c=wo(e,i,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});return c.kind===Hs.Kind.Video?c.source=Hs.Source.Camera:c.kind===Hs.Kind.Audio&&(c.source=Hs.Source.Microphone,c.setAudioContext(this.audioContext)),c.mediaStream=o,n.processor&&(yield c.setProcessor(n.processor)),c})))))}))}createScreenTracks(t){return Di(this,void 0,void 0,(function*(){if(void 0===t&&(t={}),void 0===navigator.mediaDevices.getDisplayMedia)throw new fs("getDisplayMedia not supported");void 0!==t.resolution||mr()||(t.resolution=Ws.h1080fps30.resolution);const i=Zs(t),n=yield navigator.mediaDevices.getDisplayMedia(i),s=n.getVideoTracks();if(0===s.length)throw new vs("no video track found");const r=new jo(s[0],void 0,!1,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});r.source=Hs.Source.ScreenShare,t.contentHint&&(r.mediaStreamTrack.contentHint=t.contentHint);const o=[r];if(n.getAudioTracks().length>0){this.emit(e.ParticipantEvent.AudioStreamAcquired);const t=new Eo(n.getAudioTracks()[0],void 0,!1,this.audioContext,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});t.source=Hs.Source.ScreenShareAudio,o.push(t)}return o}))}publishTrack(e,t){return Di(this,void 0,void 0,(function*(){var i,n,s,r;let o,a;if(e instanceof Eo&&e.setAudioContext(this.audioContext),yield null===(i=this.reconnectFuture)||void 0===i?void 0:i.promise,e instanceof Fr&&this.pendingPublishPromises.has(e)&&(yield this.pendingPublishPromises.get(e)),e instanceof MediaStreamTrack)o=e.getConstraints();else{let t;switch(o=e.constraints,e.source){case Hs.Source.Microphone:t="audioinput";break;case Hs.Source.Camera:t="videoinput"}t&&this.activeDeviceMap.has(t)&&(o=Object.assign(Object.assign({},o),{deviceId:this.activeDeviceMap.get(t)}))}if(e instanceof MediaStreamTrack)switch(e.kind){case"audio":e=new Eo(e,o,!0,this.audioContext,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});break;case"video":e=new jo(e,o,!0,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});break;default:throw new vs("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&&(a=t)})),a)return this.log.warn("track has already been published, skipping",Object.assign(Object.assign({},this.logContext),ir(a))),a;const c="channelCount"in e.mediaStreamTrack.getSettings()&&2===e.mediaStreamTrack.getSettings().channelCount||2===e.mediaStreamTrack.getConstraints().channelCount,d=null!==(n=null==t?void 0:t.forceStereo)&&void 0!==n?n: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),ir(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!==(r=t.red)&&void 0!==r||(t.red=!1));const l=Object.assign(Object.assign({},this.roomOptions.publishDefaults),t);!function(){const e=Ds(),t="17.2";if(e)return"Safari"!==e.name&&"iOS"!==e.os||!!("iOS"===e.os&&e.osVersion&&Cr(t,e.osVersion)>=0)||"Safari"===e.name&&Cr(t,e.version)>=0}()&&this.roomOptions.e2ee&&(this.log.info("End-to-end encryption is set up, simulcast publishing will be disabled on Safari versions and iOS browsers running iOS < v17.2",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,i,n){return Di(this,void 0,void 0,(function*(){var s,r,o,a,c,d,l,u,h,p;Array.from(this.trackPublications.values()).find((e=>t instanceof Fr&&e.source===t.source))&&t.source!==Hs.Source.Unknown&&this.log.info("publishing a second track with the same source: ".concat(t.source),Object.assign(Object.assign({},this.logContext),ir(t))),i.stopMicTrackOnMute&&t instanceof Eo&&(t.stopOnMute=!0),t.source===Hs.Source.ScreenShare&&hr()&&(i.simulcast=!1),"av1"!==i.videoCodec||ar()||(i.videoCodec=void 0),"vp9"!==i.videoCodec||cr()||(i.videoCodec=void 0),void 0===i.videoCodec&&(i.videoCodec=mo),this.enabledPublishVideoCodecs.length>0&&(this.enabledPublishVideoCodecs.some((e=>i.videoCodec===er(e.mime)))||(i.videoCodec=er(this.enabledPublishVideoCodecs[0].mime)));const m=i.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),t.on(e.TrackEvent.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate);const g=new Dt({cid:t.mediaStreamTrack.id,name:i.name,type:Hs.kindToProto(t.kind),muted:t.isMuted,source:Hs.sourceToProto(t.source),disableDtx:!(null===(s=i.dtx)||void 0===s||s),encryption:this.encryptionType,stereo:n,disableRed:this.isE2EEEnabled||!(null===(r=i.red)||void 0===r||r),stream:null==i?void 0:i.stream});let f;if(t.kind===Hs.Kind.Video){let e={width:0,height:0};try{e=yield t.waitForDimensions()}catch(i){const n=null!==(a=null===(o=this.roomOptions.videoCaptureDefaults)||void 0===o?void 0:o.resolution)&&void 0!==a?a:qs.h720.resolution;e={width:n.width,height:n.height},this.log.error("could not determine track dimensions, using defaults",Object.assign(Object.assign(Object.assign({},this.logContext),ir(t)),{dims:e}))}g.width=e.width,g.height=e.height,t instanceof jo&&(dr(m)&&(t.source===Hs.Source.ScreenShare&&(i.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),ir(t))))),i.scalabilityMode=null!==(c=i.scalabilityMode)&&void 0!==c?c:"L3T3_KEY"),g.simulcastCodecs=[new xt({codec:m,cid:t.mediaStreamTrack.id})],!0===i.backupCodec&&(i.backupCodec={codec:mo}),i.backupCodec&&m!==i.backupCodec.codec&&g.encryption===st.NONE&&(this.roomOptions.dynacast||(this.roomOptions.dynacast=!0),g.simulcastCodecs.push(new xt({codec:i.backupCodec.codec,cid:""})))),f=No(t.source===Hs.Source.ScreenShare,g.width,g.height,i),g.layers=Vo(g.width,g.height,f,dr(i.videoCodec))}else t.kind===Hs.Kind.Audio&&(f=[{maxBitrate:null===(d=i.audioPreset)||void 0===d?void 0:d.maxBitrate,priority:null!==(u=null===(l=i.audioPreset)||void 0===l?void 0:l.priority)&&void 0!==u?u:"high",networkPriority:null!==(p=null===(h=i.audioPreset)||void 0===h?void 0:h.priority)&&void 0!==p?p:"high"}]);if(!this.engine||this.engine.isClosed)throw new bs("cannot publish track when not connected");const v=()=>Di(this,void 0,void 0,(function*(){var e,n,s;if(!this.engine.pcManager)throw new bs("pcManager is not ready");if(t.sender=yield this.engine.createSender(t,i,f),t instanceof jo&&(null!==(e=i.degradationPreference)&&void 0!==e||(i.degradationPreference=function(e){return e.source===Hs.Source.ScreenShare||e.constraints.height&&Ar(e.constraints.height)>=1080?"maintain-resolution":"balanced"}(t)),t.setDegradationPreference(i.degradationPreference)),f)if(hr()&&t.kind===Hs.Kind.Audio){let e;for(const i of this.engine.pcManager.publisher.getTransceivers())if(i.sender===t.sender){e=i;break}e&&this.engine.pcManager.publisher.setTrackCodecBitrate({transceiver:e,codec:"opus",maxbr:(null===(n=f[0])||void 0===n?void 0:n.maxBitrate)?f[0].maxBitrate/1e3:0})}else t.codec&&dr(t.codec)&&(null===(s=f[0])||void 0===s?void 0:s.maxBitrate)&&this.engine.pcManager.publisher.setTrackCodecBitrate({cid:g.cid,codec:t.codec,maxbr:f[0].maxBitrate/1e3});yield this.engine.negotiate()}));let k;if(this.enabledPublishVideoCodecs.length>0){k=(yield Promise.all([this.engine.addTrack(g),v()]))[0]}else{let e;if(k=yield this.engine.addTrack(g),k.codecs.forEach((t=>{void 0===e&&(e=t.mimeType)})),e&&t.kind===Hs.Kind.Video){const n=er(e);n!==m&&(this.log.debug("falling back to server selected codec",Object.assign(Object.assign(Object.assign({},this.logContext),ir(t)),{codec:n})),i.videoCodec=n,f=No(t.source===Hs.Source.ScreenShare,g.width,g.height,i))}yield v()}const b=new ta(t.kind,k,t,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});return b.options=i,t.sid=k.sid,this.log.debug("publishing ".concat(t.kind," with encodings"),Object.assign(Object.assign({},this.logContext),{encodings:f,trackInfo:k})),t instanceof jo?t.startMonitor(this.engine.client):t instanceof Eo&&t.startMonitor(),this.addTrackPublication(b),this.emit(e.ParticipantEvent.LocalTrackPublished,b),b}))}get isLocal(){return!0}publishAdditionalCodecForTrack(e,t,i){return Di(this,void 0,void 0,(function*(){var n;if(this.encryptionType!==st.NONE)return;let s;if(this.trackPublications.forEach((t=>{t.track&&t.track===e&&(s=t)})),!s)throw new vs("track is not published");if(!(e instanceof jo))throw new vs("track is not a video track");const r=Object.assign(Object.assign({},null===(n=this.roomOptions)||void 0===n?void 0:n.publishDefaults),i),o=function(e,t,i){var n,s,r,o;if(!i.backupCodec||!0===i.backupCodec||i.backupCodec.codec===i.videoCodec)return;t!==i.backupCodec.codec&&Ei.warn("requested a different codec than specified as backup",{serverRequested:t,backup:i.backupCodec.codec}),i.videoCodec=t,i.videoEncoding=i.backupCodec.encoding;const a=e.mediaStreamTrack.getSettings(),c=null!==(n=a.width)&&void 0!==n?n:null===(s=e.dimensions)||void 0===s?void 0:s.width,d=null!==(r=a.height)&&void 0!==r?r:null===(o=e.dimensions)||void 0===o?void 0:o.height;return No(e.source===Hs.Source.ScreenShare,c,d,i)}(e,t,r);if(!o)return void this.log.info("backup codec has been disabled, ignoring request to add additional codec for track",Object.assign(Object.assign({},this.logContext),ir(e)));const a=e.addSimulcastTrack(t,o);if(!a)return;const c=new Dt({cid:a.mediaStreamTrack.id,type:Hs.kindToProto(e.kind),muted:e.isMuted,source:Hs.sourceToProto(e.source),sid:e.sid,simulcastCodecs:[{codec:r.videoCodec,cid:a.mediaStreamTrack.id}]});if(c.layers=Vo(c.width,c.height,o),!this.engine||this.engine.isClosed)throw new bs("cannot publish track when not connected");const d=(yield Promise.all([this.engine.addTrack(c),(()=>Di(this,void 0,void 0,(function*(){yield this.engine.createSimulcastSender(e,a,r,o),yield this.engine.negotiate()})))()]))[0];this.log.debug("published ".concat(t," for track ").concat(e.sid),Object.assign(Object.assign({},this.logContext),{encodings:o,trackInfo:d}))}))}unpublishTrack(t,i){return Di(this,void 0,void 0,(function*(){var n,s;if(t instanceof Fr){const e=this.pendingPublishPromises.get(t);e&&(this.log.info("awaiting publish promise before attempting to unpublish",Object.assign(Object.assign({},this.logContext),ir(t))),yield e)}const r=this.getPublicationForTrack(t),o=r?ir(r):void 0;if(this.log.debug("unpublishing track",Object.assign(Object.assign({},this.logContext),o)),!r||!r.track)return void this.log.warn("track was not unpublished because no publication was found",Object.assign(Object.assign({},this.logContext),o));(t=r.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),t.off(e.TrackEvent.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate),void 0===i&&(i=null===(s=null===(n=this.roomOptions)||void 0===n?void 0:n.stopLocalTrackOnUnpublish)||void 0===s||s),i&&t.stop();let a=!1;const c=t.sender;if(t.sender=void 0,this.engine.pcManager&&this.engine.pcManager.currentState<yo.FAILED&&c)try{for(const e of this.engine.pcManager.publisher.getTransceivers())e.sender===c&&(e.direction="inactive",a=!0);if(this.engine.removeTrack(c)&&(a=!0),t instanceof jo){for(const[,e]of t.simulcastCodecs)e.sender&&(this.engine.removeTrack(e.sender)&&(a=!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),o),{error:e}))}switch(this.trackPublications.delete(r.trackSid),r.kind){case Hs.Kind.Audio:this.audioTrackPublications.delete(r.trackSid);break;case Hs.Kind.Video:this.videoTrackPublications.delete(r.trackSid)}return this.emit(e.ParticipantEvent.LocalTrackUnpublished,r),r.setTrack(void 0),a&&(yield this.engine.negotiate()),r}))}unpublishTracks(e){return Di(this,void 0,void 0,(function*(){return(yield Promise.all(e.map((e=>this.unpublishTrack(e))))).filter((e=>e instanceof ta))}))}republishAllTracks(e){return Di(this,arguments,void 0,(function(e){var t=this;let i=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return function*(){const n=[];t.trackPublications.forEach((t=>{t.track&&(e&&(t.options=Object.assign(Object.assign({},t.options),e)),n.push(t))})),yield Promise.all(n.map((e=>Di(t,void 0,void 0,(function*(){const t=e.track;yield this.unpublishTrack(t,!1),i&&!t.isMuted&&t.source!==Hs.Source.ScreenShare&&t.source!==Hs.Source.ScreenShareAudio&&(t instanceof Eo||t instanceof jo)&&!t.isUserProvided&&(this.log.debug("restarting existing track",Object.assign(Object.assign({},this.logContext),{track:e.trackSid})),yield t.restartTrack()),yield this.publishTrack(t,e.options)})))))}()}))}publishData(e){return Di(this,arguments,void 0,(function(e){var t=this;let i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){const n=i.reliable?dt.RELIABLE:dt.LOSSY,s=i.destinationIdentities,r=i.topic,o=new ct({kind:n,value:{case:"user",value:new ht({participantIdentity:t.identity,payload:e,destinationIdentities:s,topic:r})}});yield t.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()}setEnabledPublishCodecs(e){this.enabledPublishVideoCodecs=e.filter((e=>"video"===e.mime.split("/")[0].toLowerCase()))}updateInfo(e){return e.sid===this.sid&&(!!super.updateInfo(e)&&(e.tracks.forEach((e=>{var t,i;const n=this.trackPublications.get(e.sid);if(n){const s=n.isMuted||null!==(i=null===(t=n.track)||void 0===t?void 0:t.isUpstreamPaused)&&void 0!==i&&i;s!==e.muted&&(this.log.debug("updating server mute state after reconcile",Object.assign(Object.assign(Object.assign({},this.logContext),ir(n)),{mutedOnServer:s})),this.engine.client.sendMuteTrack(e.sid,s))}})),!0))}getPublicationForTrack(e){let t;return this.trackPublications.forEach((i=>{const n=i.track;n&&(e instanceof MediaStreamTrack?(n instanceof Eo||n instanceof jo)&&n.mediaStreamTrack===e&&(t=i):e===n&&(t=i))})),t}}class sa extends ea{constructor(t,i,n,s){super(t,i.sid,i.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=n,this.updateInfo(i)}setSubscribed(t){const i=this.subscriptionStatus,n=this.permissionStatus;this.subscribed=t,t&&(this.allowed=!0);const s=new Bt({trackSids:[this.trackSid],subscribe:this.subscribed,participantTracks:[new ft({participantSid:"",trackSids:[this.trackSid]})]});this.emit(e.TrackEvent.UpdateSubscription,s),this.emitSubscriptionUpdateIfChanged(i),this.emitPermissionUpdateIfChanged(n)}get subscriptionStatus(){return!1===this.subscribed?ea.SubscriptionStatus.Unsubscribed:super.isSubscribed?ea.SubscriptionStatus.Subscribed:ea.SubscriptionStatus.Desired}get permissionStatus(){return this.allowed?ea.PermissionStatus.Allowed:ea.PermissionStatus.NotAllowed}get isSubscribed(){return!1!==this.subscribed&&super.isSubscribed}get isDesired(){return!1!==this.subscribed}get isEnabled(){return!this.disabled}setEnabled(e){this.isManualOperationAllowed()&&this.disabled!==!e&&(this.disabled=!e,this.emitTrackUpdate())}setVideoQuality(e){this.isManualOperationAllowed()&&this.currentVideoQuality!==e&&(this.currentVideoQuality=e,this.videoDimensions=void 0,this.emitTrackUpdate())}setVideoDimensions(e){var t,i;this.isManualOperationAllowed()&&((null===(t=this.videoDimensions)||void 0===t?void 0:t.width)===e.width&&(null===(i=this.videoDimensions)||void 0===i?void 0:i.height)===e.height||(this.track instanceof Xo&&(this.videoDimensions=e),this.currentVideoQuality=void 0,this.emitTrackUpdate()))}setVideoFPS(e){this.isManualOperationAllowed()&&this.track instanceof Xo&&this.fps!==e&&(this.fps=e,this.emitTrackUpdate())}get videoQuality(){return this.currentVideoQuality}setTrack(t){const i=this.subscriptionStatus,n=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(n),this.emitSubscriptionUpdateIfChanged(i))}setAllowed(e){const t=this.subscriptionStatus,i=this.permissionStatus;this.allowed=e,this.emitPermissionUpdateIfChanged(i),this.emitSubscriptionUpdateIfChanged(t)}setSubscriptionError(t){this.emit(e.TrackEvent.SubscriptionFailed,t)}updateInfo(t){super.updateInfo(t);const i=this.metadataMuted;this.metadataMuted=t.muted,this.track?this.track.setMuted(t.muted):i!==t.muted&&this.emit(t.muted?e.TrackEvent.Muted:e.TrackEvent.Unmuted)}emitSubscriptionUpdateIfChanged(t){const i=this.subscriptionStatus;t!==i&&this.emit(e.TrackEvent.SubscriptionStatusChanged,i,t)}emitPermissionUpdateIfChanged(t){this.permissionStatus!==t&&this.emit(e.TrackEvent.SubscriptionPermissionChanged,this.permissionStatus,t)}isManualOperationAllowed(){return this.kind===Hs.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 Xo&&this.track.isAdaptiveStream}emitTrackUpdate(){const t=new Vt({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 ra extends ia{static fromParticipantInfo(e,t,i){return new ra(e,t.sid,t.identity,t.name,t.metadata,i,t.kind)}get logContext(){return Object.assign(Object.assign({},super.logContext),{rpID:this.sid,remoteParticipant:this.identity})}constructor(e,t,i,n,s,r){super(t,i||"",n,s,r,arguments.length>6&&void 0!==arguments[6]?arguments[6]:nt.STANDARD),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),ir(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,(i=>{this.emit(e.ParticipantEvent.TrackSubscriptionPermissionChanged,t,i)})),t.on(e.TrackEvent.SubscriptionStatusChanged,(i=>{this.emit(e.ParticipantEvent.TrackSubscriptionStatusChanged,t,i)})),t.on(e.TrackEvent.Subscribed,(i=>{this.emit(e.ParticipantEvent.TrackSubscribed,i,t)})),t.on(e.TrackEvent.Unsubscribed,(i=>{this.emit(e.ParticipantEvent.TrackUnsubscribed,i,t)})),t.on(e.TrackEvent.SubscriptionFailed,(i=>{this.emit(e.ParticipantEvent.TrackSubscriptionFailed,t.trackSid,i)}))}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]:Hs.Source.Microphone;this.volumeMap.set(t,e);const i=this.getTrackPublication(t);i&&i.track&&i.track.setVolume(e)}getVolume(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:Hs.Source.Microphone;const t=this.getTrackPublication(e);return t&&t.track?t.track.getVolume():this.volumeMap.get(e)}addSubscribedMediaTrack(t,i,n,s,r,o){let a=this.getTrackPublicationBySid(i);if(a||i.startsWith("TR")||this.trackPublications.forEach((e=>{a||t.kind!==e.kind.toString()||(a=e)})),!a)return 0===o?(this.log.error("could not find published track",Object.assign(Object.assign({},this.logContext),{trackSid:i})),void this.emit(e.ParticipantEvent.TrackSubscriptionFailed,i)):(void 0===o&&(o=20),void setTimeout((()=>{this.addSubscribedMediaTrack(t,i,n,s,r,o-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),ir(a))),void this.emit(e.ParticipantEvent.TrackSubscriptionFailed,i);let c;return c="video"===t.kind?new Xo(t,i,s,r):new Yo(t,i,s,this.audioContext,this.audioOutput),c.source=a.source,c.isMuted=a.isMuted,c.setMediaStream(n),c.start(),a.setTrack(c),this.volumeMap.has(a.source)&&c instanceof Yo&&c.setVolume(this.volumeMap.get(a.source)),a}get hasMetadata(){return!!this.participantInfo}getTrackPublicationBySid(e){return this.trackPublications.get(e)}updateInfo(t){if(!super.updateInfo(t))return!1;const i=new Map,n=new Map;return t.tracks.forEach((e=>{var t,s;let r=this.getTrackPublicationBySid(e.sid);if(r)r.updateInfo(e);else{const i=Hs.kindFromProto(e.type);if(!i)return;r=new sa(i,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}),r.updateInfo(e),n.set(e.sid,r);const o=Array.from(this.trackPublications.values()).find((e=>e.source===(null==r?void 0:r.source)));o&&r.source!==Hs.Source.Unknown&&this.log.debug("received a second track publication for ".concat(this.identity," with the same source: ").concat(r.source),Object.assign(Object.assign({},this.logContext),{oldTrack:ir(o),newTrack:ir(r)})),this.addTrackPublication(r)}i.set(e.sid,r)})),this.trackPublications.forEach((e=>{i.has(e.trackSid)||(this.log.trace("detected removed track on remote participant, unpublishing",Object.assign(Object.assign({},this.logContext),ir(e))),this.unpublishTrack(e.trackSid,!0))})),n.forEach((t=>{this.emit(e.ParticipantEvent.TrackPublished,t)})),!0}unpublishTrack(t,i){const n=this.trackPublications.get(t);if(!n)return;const{track:s}=n;switch(s&&(s.stop(),n.setTrack(void 0)),this.trackPublications.delete(t),n.kind){case Hs.Kind.Audio:this.audioTrackPublications.delete(t);break;case Hs.Kind.Video:this.videoTrackPublications.delete(t)}i&&this.emit(e.ParticipantEvent.TrackUnpublished,n)}setAudioOutput(e){return Di(this,void 0,void 0,(function*(){this.audioOutput=e;const t=[];this.audioTrackPublications.forEach((i=>{var n;i.track instanceof Yo&&t.push(i.track.setSinkId(null!==(n=e.deviceId)&&void 0!==n?n:"default"))})),yield Promise.all(t)}))}emit(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),n=1;n<t;n++)i[n-1]=arguments[n];return this.log.trace("participant event",Object.assign(Object.assign({},this.logContext),{event:e,args:i})),super.emit(e,...i)}}var oa;e.ConnectionState=void 0,(oa=e.ConnectionState||(e.ConnectionState={})).Disconnected="disconnected",oa.Connecting="connecting",oa.Connected="connected",oa.Reconnecting="reconnecting",oa.SignalReconnecting="signalReconnecting";class aa extends Yi.EventEmitter{constructor(t){var i,n,s;super(),i=this,this.state=e.ConnectionState.Disconnected,this.activeSpeakers=[],this.isE2EEEnabled=!1,this.audioEnabled=!0,this.isVideoPlaybackBlocked=!1,this.log=Ei,this.bufferedEvents=[],this.isResuming=!1,this.connect=(t,i,n)=>Di(this,void 0,void 0,(function*(){var s;if(!ur())throw vr()?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 r=yield this.disconnectLock.lock();if(this.state===e.ConnectionState.Connected)return this.log.info("already connected to room ".concat(this.name),this.logContext),r(),Promise.resolve();if(this.connectFuture)return r(),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),kr(new URL(t))&&(void 0===this.regionUrlProvider?this.regionUrlProvider=new Qo(t,i):this.regionUrlProvider.updateToken(i),this.regionUrlProvider.fetchRegionSettings().then((e=>{var t;null===(t=this.regionUrlProvider)||void 0===t||t.setServerReportedRegions(e)})).catch((e=>{this.log.warn("could not fetch region settings",Object.assign(Object.assign({},this.logContext),{error:e}))})));const o=(e,s,a)=>Di(this,void 0,void 0,(function*(){var c,d;this.abortController&&this.abortController.abort();const l=new AbortController;this.abortController=l,null==r||r();try{yield this.attemptConnection(null!=a?a:t,i,n,l),this.abortController=void 0,e()}catch(t){if(this.regionUrlProvider&&t instanceof gs&&3!==t.reason&&0!==t.reason){let i=null;try{i=yield this.regionUrlProvider.getNextBestRegionUrl(null===(c=this.abortController)||void 0===c?void 0:c.signal)}catch(e){if(e instanceof gs&&(401===e.status||3===e.reason))return this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),void s(e)}i&&!(null===(d=this.abortController)||void 0===d?void 0:d.signal.aborted)?(this.log.info("Initial connection failed with ConnectionError: ".concat(t.message,". Retrying with another region: ").concat(i),this.logContext),this.recreateEngine(),yield o(e,s,i)):(this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),s(t))}else this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),s(t)}})),a=this.regionUrl;return this.regionUrl=void 0,this.connectFuture=new Nr(((e,t)=>{o(e,t,a)}),(()=>{this.clearConnectionFutures()})),this.connectFuture.promise})),this.connectSignal=(e,t,i,n,s,r)=>Di(this,void 0,void 0,(function*(){var o,a,c;const d=yield i.join(e,t,{autoSubscribe:n.autoSubscribe,adaptiveStream:"object"==typeof s.adaptiveStream||s.adaptiveStream,maxRetries:n.maxRetries,e2eeEnabled:!!this.e2eeManager,websocketTimeout:n.websocketTimeout},r.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,i]=e;return"".concat(t,": ").concat(i)})).join(", ")),{room:null===(o=d.room)||void 0===o?void 0:o.name,roomSid:null===(a=d.room)||void 0===a?void 0:a.sid,identity:null===(c=d.participant)||void 0===c?void 0:c.identity}),!d.serverVersion)throw new ks("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.localParticipant.setEnabledPublishCodecs(e.enabledPublishCodecs),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,i,n,s)=>Di(this,void 0,void 0,(function*(){var r,o,a;this.state===e.ConnectionState.Reconnecting||this.isResuming||(null===(r=this.engine)||void 0===r?void 0:r.pendingReconnect)?(this.log.info("Reconnection attempt replaced by new connection attempt",this.logContext),this.recreateEngine()):this.maybeCreateEngine(),(null===(o=this.regionUrlProvider)||void 0===o?void 0:o.isCloud())&&this.engine.setRegionUrlProvider(this.regionUrlProvider),this.acquireAudioContext(),this.connOptions=Object.assign(Object.assign({},bo),n),this.connOptions.rtcConfig&&(this.engine.rtcConfig=this.connOptions.rtcConfig),this.connOptions.peerConnectionTimeout&&(this.engine.peerConnectionTimeout=this.connOptions.peerConnectionTimeout);try{const n=yield this.connectSignal(t,i,this.engine,this.connOptions,this.options,s);this.applyJoinResponse(n),this.setupLocalParticipantEvents(),this.emit(e.RoomEvent.SignalConnected)}catch(e){yield this.engine.close(),this.recreateEngine();const t=new gs("could not establish signal connection");throw e instanceof Error&&(t.message="".concat(t.message,": ").concat(e.message)),e instanceof gs&&(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 gs("Connection attempt aborted");try{yield this.engine.waitForPCInitialConnection(this.connOptions.peerConnectionTimeout,s)}catch(e){throw yield this.engine.close(),this.recreateEngine(),e}fr()&&this.options.disconnectOnPageLeave&&(window.addEventListener("pagehide",this.onPageLeave),window.addEventListener("beforeunload",this.onPageLeave)),fr()&&(document.addEventListener("freeze",this.onPageLeave),null===(a=navigator.mediaDevices)||void 0===a||a.addEventListener("devicechange",this.handleDeviceChange)),this.setAndEmitConnectionState(e.ConnectionState.Connected),this.emit(e.RoomEvent.Connected),this.registerConnectionReconcile()})),this.disconnect=function(){for(var t=arguments.length,n=new Array(t),s=0;s<t;s++)n[s]=arguments[s];return Di(i,[...n],void 0,(function(){var t=this;let i=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return function*(){var n,s,r,o;const a=yield t.disconnectLock.lock();try{if(t.state===e.ConnectionState.Disconnected)return void t.log.debug("already disconnected",t.logContext);t.log.info("disconnect from room",Object.assign({},t.logContext)),(t.state===e.ConnectionState.Connecting||t.state===e.ConnectionState.Reconnecting||t.isResuming)&&(t.log.warn("abort connection attempt",t.logContext),null===(n=t.abortController)||void 0===n||n.abort(),null===(r=null===(s=t.connectFuture)||void 0===s?void 0:s.reject)||void 0===r||r.call(s,new gs("Client initiated disconnect")),t.connectFuture=void 0),(null===(o=t.engine)||void 0===o?void 0:o.client.isDisconnected)||(yield t.engine.client.sendLeave()),t.engine&&(yield t.engine.close()),t.handleDisconnect(i,Qe.CLIENT_INITIATED),t.engine=void 0}finally{a()}}()}))},this.onPageLeave=()=>Di(this,void 0,void 0,(function*(){this.log.info("Page leave detected, disconnecting",this.logContext),yield this.disconnect()})),this.startAudio=()=>Di(this,void 0,void 0,(function*(){const t=[],i=Ds();if(i&&"iOS"===i.os){const i="livekit-dummy-audio-el";let n=document.getElementById(i);if(!n){n=document.createElement("audio"),n.id=i,n.autoplay=!0,n.hidden=!0;const t=Mr();t.enabled=!0;const s=new MediaStream([t]);n.srcObject=s,document.addEventListener("visibilitychange",(()=>{n&&(n.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(n),this.once(e.RoomEvent.Disconnected,(()=>{null==n||n.remove(),n=null}))}t.push(n)}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=()=>Di(this,void 0,void 0,(function*(){const e=[];for(const t of this.remoteParticipants.values())t.videoTrackPublications.forEach((t=>{var i;null===(i=t.track)||void 0===i||i.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=>Di(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 i=this.remoteParticipants.get(e.identity);e.state===it.DISCONNECTED?this.handleParticipantDisconnected(e.identity,i):i=this.getOrCreateParticipant(e.identity,e)}))},this.handleActiveSpeakersUpdate=t=>{const i=[],n={};t.forEach((e=>{if(n[e.sid]=!0,e.sid===this.localParticipant.sid)this.localParticipant.audioLevel=e.level,this.localParticipant.setIsSpeaking(!0),i.push(this.localParticipant);else{const t=this.getRemoteParticipantBySid(e.sid);t&&(t.audioLevel=e.level,t.setIsSpeaking(!0),i.push(t))}})),n[this.localParticipant.sid]||(this.localParticipant.audioLevel=0,this.localParticipant.setIsSpeaking(!1)),this.remoteParticipants.forEach((e=>{n[e.sid]||(e.audioLevel=0,e.setIsSpeaking(!1))})),this.activeSpeakers=i,this.emitWhenConnected(e.RoomEvent.ActiveSpeakersChanged,i)},this.handleSpeakersChanged=t=>{const i=new Map;this.activeSpeakers.forEach((e=>{const t=this.remoteParticipants.get(e.identity);t&&t.sid!==e.sid||i.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?i.set(e.sid,t):i.delete(e.sid))}));const n=Array.from(i.values());n.sort(((e,t)=>t.audioLevel-e.audioLevel)),this.activeSpeakers=n,this.emitWhenConnected(e.RoomEvent.ActiveSpeakersChanged,n)},this.handleStreamStateUpdate=t=>{t.streamStates.forEach((t=>{const i=this.getRemoteParticipantBySid(t.participantSid);if(!i)return;const n=i.getTrackPublicationBySid(t.trackSid);n&&n.track&&(n.track.streamState=Hs.streamStateFromProto(t.state),i.emit(e.ParticipantEvent.TrackStreamStateChanged,n,n.track.streamState),this.emitWhenConnected(e.RoomEvent.TrackStreamStateChanged,n,n.track.streamState,i))}))},this.handleSubscriptionPermissionUpdate=e=>{const t=this.getRemoteParticipantBySid(e.participantSid);if(!t)return;const i=t.getTrackPublicationBySid(e.trackSid);i&&i.setAllowed(e.allowed)},this.handleSubscriptionError=e=>{const t=Array.from(this.remoteParticipants.values()).find((t=>t.trackPublications.has(e.trackSid)));if(!t)return;const i=t.getTrackPublicationBySid(e.trackSid);i&&i.setSubscriptionError(e.err)},this.handleDataPacket=e=>{const t=this.remoteParticipants.get(e.participantIdentity);"user"===e.value.case?this.handleUserPacket(t,e.value.value,e.kind):"transcription"===e.value.case?this.handleTranscription(t,e.value.value):"sipDtmf"===e.value.case&&this.handleSipDtmf(t,e.value.value)},this.handleUserPacket=(t,i,n)=>{this.emit(e.RoomEvent.DataReceived,i.payload,t,n,i.topic),null==t||t.emit(e.ParticipantEvent.DataReceived,i.payload,n)},this.handleSipDtmf=(t,i)=>{this.emit(e.RoomEvent.SipDTMFReceived,i,t),null==t||t.emit(e.ParticipantEvent.SipDTMFReceived,i)},this.bufferedSegments=new Map,this.handleTranscription=(t,i)=>{const n=i.transcribedParticipantIdentity===this.localParticipant.identity?this.localParticipant:this.getParticipantByIdentity(i.transcribedParticipantIdentity),s=null==n?void 0:n.trackPublications.get(i.trackId),r=function(e,t){return e.segments.map((e=>{let{id:i,text:n,language:s,startTime:r,endTime:o,final:a}=e;var c;const d=null!==(c=t.get(i))&&void 0!==c?c:Date.now(),l=Date.now();return a?t.delete(i):t.set(i,d),{id:i,text:n,startTime:Number.parseInt(r.toString()),endTime:Number.parseInt(o.toString()),final:a,language:s,firstReceivedTime:d,lastReceivedTime:l}}))}(i,this.transcriptionReceivedTimes);null==s||s.emit(e.TrackEvent.TranscriptionReceived,r),null==n||n.emit(e.ParticipantEvent.TranscriptionReceived,r,s),this.emit(e.RoomEvent.TranscriptionReceived,r,n,s)},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=()=>Di(this,void 0,void 0,(function*(){this.emit(e.RoomEvent.MediaDevicesChanged)})),this.handleRoomUpdate=t=>{const i=this.roomInfo;this.roomInfo=t,i&&i.metadata!==t.metadata&&this.emitWhenConnected(e.RoomEvent.RoomMetadataChanged,t.metadata),(null==i?void 0:i.activeRecording)!==t.activeRecording&&this.emitWhenConnected(e.RoomEvent.RecordingStatusChanged,t.activeRecording)},this.handleConnectionQualityUpdate=e=>{e.updates.forEach((e=>{if(e.participantSid===this.localParticipant.sid)return void this.localParticipant.setConnectionQuality(e.quality);const t=this.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.onLocalAttributesChanged=t=>{this.emit(e.RoomEvent.ParticipantAttributesChanged,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=>Di(this,void 0,void 0,(function*(){var i,n,s,r,o;if(null===(i=t.track)||void 0===i||i.on(e.TrackEvent.TrackProcessorUpdate,this.onTrackProcessorUpdate),null===(r=null===(s=null===(n=t.track)||void 0===n?void 0:n.getProcessor())||void 0===s?void 0:s.onPublish)||void 0===r||r.call(s,this),this.emit(e.RoomEvent.LocalTrackPublished,t,this.localParticipant),t.track instanceof Eo){(yield t.track.checkForSilence())&&this.emit(e.RoomEvent.LocalAudioSilenceDetected,t)}const a=yield null===(o=t.track)||void 0===o?void 0:o.getDeviceId(),c=(d=t.source)===Hs.Source.Microphone?"audioinput":d===Hs.Source.Camera?"videoinput":void 0;var d;c&&a&&a!==this.localParticipant.activeDeviceMap.get(c)&&(this.localParticipant.activeDeviceMap.set(c,a),this.emit(e.RoomEvent.ActiveDeviceChanged,c,a))})),this.onLocalTrackUnpublished=t=>{var i;null===(i=t.track)||void 0===i||i.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({},ko),t),this.log=Pi(null!==(n=this.options.loggerName)&&void 0!==n?n:e.LoggerNames.Room),this.transcriptionReceivedTimes=new Map,this.options.audioCaptureDefaults=Object.assign(Object.assign({},fo),null==t?void 0:t.audioCaptureDefaults),this.options.videoCaptureDefaults=Object.assign(Object.assign({},vo),null==t?void 0:t.videoCaptureDefaults),this.options.publishDefaults=Object.assign(Object.assign({},go),null==t?void 0:t.publishDefaults),this.maybeCreateEngine(),this.disconnectLock=new _r,this.localParticipant=new na("","",this.engine,this.options),this.options.videoCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("videoinput",Ar(this.options.videoCaptureDefaults.deviceId)),this.options.audioCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("audioinput",Ar(this.options.audioCaptureDefaults.deviceId)),(null===(s=this.options.audioOutput)||void 0===s?void 0:s.deviceId)&&this.switchActiveDevice("audiooutput",Ar(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 Di(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 Br(this.options.e2ee),this.e2eeManager.on(e.EncryptionEvent.ParticipantEncryptionStatusChanged,((t,i)=>{i instanceof na&&(this.isE2EEEnabled=t),this.emit(e.RoomEvent.ParticipantEncryptionStatusChanged,t,i)})),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 Di(this,void 0,void 0,(function*(){return this.state===e.ConnectionState.Disconnected?"":this.roomInfo&&""!==this.roomInfo.sid?this.roomInfo.sid:new Promise(((t,i)=>{const n=i=>{""!==i.sid&&(this.engine.off(e.EngineEvent.RoomUpdate,n),t(i.sid))};this.engine.on(e.EngineEvent.RoomUpdate,n),this.once(e.RoomEvent.Disconnected,(()=>{this.engine.off(e.EngineEvent.RoomUpdate,n),i("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 Ho(this.options),this.engine.on(e.EngineEvent.ParticipantUpdate,this.handleParticipantUpdates).on(e.EngineEvent.RoomUpdate,this.handleRoomUpdate).on(e.EngineEvent.SpeakersChanged,this.handleSpeakersChanged).on(e.EngineEvent.StreamStateChanged,this.handleStreamStateUpdate).on(e.EngineEvent.ConnectionQualityUpdate,this.handleConnectionQualityUpdate).on(e.EngineEvent.SubscriptionError,this.handleSubscriptionError).on(e.EngineEvent.SubscriptionPermissionUpdate,this.handleSubscriptionPermissionUpdate).on(e.EngineEvent.MediaTrackAdded,((e,t,i)=>{this.onTrackAdded(e,t,i)})).on(e.EngineEvent.Disconnected,(e=>{this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e)})).on(e.EngineEvent.ActiveSpeakersUpdate,this.handleActiveSpeakersUpdate).on(e.EngineEvent.DataPacketReceived,this.handleDataPacket).on(e.EngineEvent.Resuming,(()=>{this.clearConnectionReconcile(),this.isResuming=!0,this.log.info("Resuming signal connection",this.logContext),this.setAndEmitConnectionState(e.ConnectionState.SignalReconnecting)&&this.emit(e.RoomEvent.SignalReconnecting)})).on(e.EngineEvent.Resumed,(()=>{this.registerConnectionReconcile(),this.isResuming=!1,this.log.info("Resumed signal connection",this.logContext),this.updateSubscriptions(),this.emitBufferedEvents(),this.setAndEmitConnectionState(e.ConnectionState.Connected)&&this.emit(e.RoomEvent.Reconnected)})).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,i)=>{this.emit(e.RoomEvent.DCBufferStatusChanged,t,i)})).on(e.EngineEvent.LocalTrackSubscribed,(t=>{const i=this.localParticipant.getTrackPublications().find((e=>{let{trackSid:i}=e;return i===t}));i?(this.localParticipant.emit(e.ParticipantEvent.LocalTrackSubscribed,i),this.emitWhenConnected(e.RoomEvent.LocalTrackSubscribed,i,this.localParticipant)):this.log.warn("could not find local track subscription for subscribed event",this.logContext)})),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 jr.getInstance().getDevices(e,t)}prepareConnection(t,i){return Di(this,void 0,void 0,(function*(){if(this.state===e.ConnectionState.Disconnected){this.log.debug("prepareConnection to ".concat(t),this.logContext);try{if(kr(new URL(t))&&i){this.regionUrlProvider=new Qo(t,i);const n=yield this.regionUrlProvider.getNextBestRegionUrl();n&&this.state===e.ConnectionState.Disconnected&&(this.regionUrl=n,yield fetch(Lr(n),{method:"HEAD"}),this.log.debug("prepared connection to ".concat(n),this.logContext))}else yield fetch(Lr(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 Di(this,void 0,void 0,(function*(){let i,n=()=>{};switch(e){case"signal-reconnect":yield this.engine.client.handleOnClose("simulate disconnect");break;case"speaker":i=new di({scenario:{case:"speakerUpdate",value:3}});break;case"node-failure":i=new di({scenario:{case:"nodeFailure",value:!0}});break;case"server-leave":i=new di({scenario:{case:"serverLeave",value:!0}});break;case"migration":i=new di({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":n=()=>Di(this,void 0,void 0,(function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")})),i=new di({scenario:{case:"disconnectSignalOnResume",value:!0}});break;case"disconnect-signal-on-resume-no-messages":n=()=>Di(this,void 0,void 0,(function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")})),i=new di({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":i=new di({scenario:{case:"switchCandidateProtocol",value:"force-tls"===e?2:1}}),n=()=>Di(this,void 0,void 0,(function*(){const e=this.engine.client.onLeave;e&&e(new Wt({reason:Qe.CLIENT_INITIATED,action:Gt.RECONNECT}))}));break;case"subscriber-bandwidth":if(void 0===t||"number"!=typeof t)throw new Error("subscriber-bandwidth requires a number as argument");i=new di({scenario:{case:"subscriberBandwidth",value:BigInt(t)}});break;case"leave-full-reconnect":i=new di({scenario:{case:"leaveRequestFullReconnect",value:!0}})}i&&(yield this.engine.client.sendSimulateScenario(i),yield n())}))}get canPlaybackAudio(){return this.audioEnabled}get canPlaybackVideo(){return!this.isVideoPlaybackBlocked}getActiveDevice(e){return this.localParticipant.activeDeviceMap.get(e)}switchActiveDevice(t,i){return Di(this,arguments,void 0,(function(t,i){var n=this;let s=arguments.length>2&&void 0!==arguments[2]&&arguments[2];return function*(){var r,o,a,c;let d=!1,l=!0;const u=s?{exact:i}:i;if("audioinput"===t){const e=n.options.audioCaptureDefaults.deviceId;n.options.audioCaptureDefaults.deviceId=u,d=e!==u;const t=Array.from(n.localParticipant.audioTrackPublications.values()).filter((e=>e.source===Hs.Source.Microphone));try{l=(yield Promise.all(t.map((e=>{var t;return null===(t=e.audioTrack)||void 0===t?void 0:t.setDeviceId(u)})))).every((e=>!0===e))}catch(t){throw n.options.audioCaptureDefaults.deviceId=e,t}}else if("videoinput"===t){const e=n.options.videoCaptureDefaults.deviceId;n.options.videoCaptureDefaults.deviceId=u,d=e!==u;const t=Array.from(n.localParticipant.videoTrackPublications.values()).filter((e=>e.source===Hs.Source.Camera));try{l=(yield Promise.all(t.map((e=>{var t;return null===(t=e.videoTrack)||void 0===t?void 0:t.setDeviceId(u)})))).every((e=>!0===e))}catch(t){throw n.options.videoCaptureDefaults.deviceId=e,t}}else if("audiooutput"===t){if(!lr()&&!n.options.webAudioMix||n.options.webAudioMix&&n.audioContext&&!("setSinkId"in n.audioContext))throw new Error("cannot switch audio output, setSinkId not supported");n.options.webAudioMix&&(i=null!==(r=yield jr.getInstance().normalizeDeviceId("audiooutput",i))&&void 0!==r?r:""),null!==(o=(c=n.options).audioOutput)&&void 0!==o||(c.audioOutput={});const e=n.options.audioOutput.deviceId;n.options.audioOutput.deviceId=i,d=e!==u;try{n.options.webAudioMix&&(null===(a=n.audioContext)||void 0===a||a.setSinkId(i)),yield Promise.all(Array.from(n.remoteParticipants.values()).map((e=>e.setAudioOutput({deviceId:i}))))}catch(t){throw n.options.audioOutput.deviceId=e,t}}return d&&l&&(n.localParticipant.activeDeviceMap.set(t,i),n.emit(e.RoomEvent.ActiveDeviceChanged,t,i)),l}()}))}setupLocalParticipantEvents(){this.localParticipant.on(e.ParticipantEvent.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).on(e.ParticipantEvent.ParticipantNameChanged,this.onLocalParticipantNameChanged).on(e.ParticipantEvent.AttributesChanged,this.onLocalAttributesChanged).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,i,n){if(this.state===e.ConnectionState.Connecting||this.state===e.ConnectionState.Reconnecting){const s=()=>{this.onTrackAdded(t,i,n),r()},r=()=>{this.off(e.RoomEvent.Reconnected,s),this.off(e.RoomEvent.Connected,s),this.off(e.RoomEvent.Disconnected,r)};return this.once(e.RoomEvent.Reconnected,s),this.once(e.RoomEvent.Connected,s),void this.once(e.RoomEvent.Disconnected,r)}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,""]}(i.id),r=s[0];let o=s[1],a=t.id;if(o&&o.startsWith("TR")&&(a=o),r===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===r));if(!c)return void this.log.error("Tried to add a track for a participant, that's not present. Sid: ".concat(r),this.logContext);let d;this.options.adaptiveStream&&(d="object"==typeof this.options.adaptiveStream?this.options.adaptiveStream:{}),c.addSubscribedMediaTrack(t,a,i,n,d)}handleDisconnect(){let t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0],i=arguments.length>1?arguments[1]:void 0;var n;if(this.clearConnectionReconcile(),this.isResuming=!1,this.bufferedEvents=[],this.transcriptionReceivedTimes.clear(),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 i,n;e.track&&this.localParticipant.unpublishTrack(e.track,t),t&&(null===(i=e.track)||void 0===i||i.detach(),null===(n=e.track)||void 0===n||n.stop())})),this.localParticipant.off(e.ParticipantEvent.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).off(e.ParticipantEvent.ParticipantNameChanged,this.onLocalParticipantNameChanged).off(e.ParticipantEvent.AttributesChanged,this.onLocalAttributesChanged).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),fr()&&(window.removeEventListener("beforeunload",this.onPageLeave),window.removeEventListener("pagehide",this.onPageLeave),window.removeEventListener("freeze",this.onPageLeave),null===(n=navigator.mediaDevices)||void 0===n||n.removeEventListener("devicechange",this.handleDeviceChange))}finally{this.setAndEmitConnectionState(e.ConnectionState.Disconnected),this.emit(e.RoomEvent.Disconnected,i)}}}handleParticipantDisconnected(t,i){this.remoteParticipants.delete(t),i&&(i.trackPublications.forEach((e=>{i.unpublishTrack(e.trackSid,!0)})),this.emit(e.RoomEvent.ParticipantDisconnected,i))}acquireAudioContext(){return Di(this,void 0,void 0,(function*(){var t,i;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=$s())&&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 n="running"===(null===(i=this.audioContext)||void 0===i?void 0:i.state);n!==this.canPlaybackAudio&&(this.audioEnabled=n,this.emit(e.RoomEvent.AudioPlaybackStatusChanged,n))}))}createParticipant(e,t){var i;let n;return n=t?ra.fromParticipantInfo(this.engine.client,t,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}):new ra(this.engine.client,"",e,void 0,void 0,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}),this.options.webAudioMix&&n.setAudioContext(this.audioContext),(null===(i=this.options.audioOutput)||void 0===i?void 0:i.deviceId)&&n.setAudioOutput(this.options.audioOutput).catch((e=>this.log.warn("Could not set audio output: ".concat(e.message),this.logContext))),n}getOrCreateParticipant(t,i){if(this.remoteParticipants.has(t)){const e=this.remoteParticipants.get(t);if(i){e.updateInfo(i)&&this.sidToIdentity.set(i.sid,i.identity)}return e}const n=this.createParticipant(t,i);return this.remoteParticipants.set(t,n),this.sidToIdentity.set(i.sid,i.identity),this.emitWhenConnected(e.RoomEvent.ParticipantConnected,n),n.on(e.ParticipantEvent.TrackPublished,(t=>{this.emitWhenConnected(e.RoomEvent.TrackPublished,t,n)})).on(e.ParticipantEvent.TrackSubscribed,((t,i)=>{t.kind===Hs.Kind.Audio?(t.on(e.TrackEvent.AudioPlaybackStarted,this.handleAudioPlaybackStarted),t.on(e.TrackEvent.AudioPlaybackFailed,this.handleAudioPlaybackFailed)):t.kind===Hs.Kind.Video&&(t.on(e.TrackEvent.VideoPlaybackFailed,this.handleVideoPlaybackFailed),t.on(e.TrackEvent.VideoPlaybackStarted,this.handleVideoPlaybackStarted)),this.emit(e.RoomEvent.TrackSubscribed,t,i,n)})).on(e.ParticipantEvent.TrackUnpublished,(t=>{this.emit(e.RoomEvent.TrackUnpublished,t,n)})).on(e.ParticipantEvent.TrackUnsubscribed,((t,i)=>{this.emit(e.RoomEvent.TrackUnsubscribed,t,i,n)})).on(e.ParticipantEvent.TrackSubscriptionFailed,(t=>{this.emit(e.RoomEvent.TrackSubscriptionFailed,t,n)})).on(e.ParticipantEvent.TrackMuted,(t=>{this.emitWhenConnected(e.RoomEvent.TrackMuted,t,n)})).on(e.ParticipantEvent.TrackUnmuted,(t=>{this.emitWhenConnected(e.RoomEvent.TrackUnmuted,t,n)})).on(e.ParticipantEvent.ParticipantMetadataChanged,(t=>{this.emitWhenConnected(e.RoomEvent.ParticipantMetadataChanged,t,n)})).on(e.ParticipantEvent.ParticipantNameChanged,(t=>{this.emitWhenConnected(e.RoomEvent.ParticipantNameChanged,t,n)})).on(e.ParticipantEvent.AttributesChanged,(t=>{this.emitWhenConnected(e.RoomEvent.ParticipantAttributesChanged,t,n)})).on(e.ParticipantEvent.ConnectionQualityChanged,(t=>{this.emitWhenConnected(e.RoomEvent.ConnectionQualityChanged,t,n)})).on(e.ParticipantEvent.ParticipantPermissionsChanged,(t=>{this.emitWhenConnected(e.RoomEvent.ParticipantPermissionsChanged,t,n)})).on(e.ParticipantEvent.TrackSubscriptionStatusChanged,((t,i)=>{this.emitWhenConnected(e.RoomEvent.TrackSubscriptionStatusChanged,t,i,n)})).on(e.ParticipantEvent.TrackSubscriptionFailed,((t,i)=>{this.emit(e.RoomEvent.TrackSubscriptionFailed,t,n,i)})).on(e.ParticipantEvent.TrackSubscriptionPermissionChanged,((t,i)=>{this.emitWhenConnected(e.RoomEvent.TrackSubscriptionPermissionChanged,t,i,n)})),i&&n.updateInfo(i),n}sendSyncState(){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 sa&&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=Ls.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)))}),4e3)}clearConnectionReconcile(){this.connectionReconcileInterval&&Ls.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,i]=e;this.emit(t,...i)})),this.bufferedEvents=[]}emitWhenConnected(t){for(var i=arguments.length,n=new Array(i>1?i-1:0),s=1;s<i;s++)n[s-1]=arguments[s];if(this.state===e.ConnectionState.Reconnecting||this.isResuming||!this.engine||this.engine.pendingReconnect)this.bufferedEvents.push([t,n]);else if(this.state===e.ConnectionState.Connected)return this.emit(t,...n);return!1}simulateParticipants(t){return Di(this,void 0,void 0,(function*(){var i,n;const s=Object.assign({audio:!0,video:!0,useRealTracks:!1},t.publish),r=Object.assign({count:9,audio:!1,video:!0,aspectRatios:[1.66,1.7,1.3]},t.participants);if(this.handleDisconnect(),this.roomInfo=new $e({sid:"RM_SIMULATED",name:"simulated-room",emptyTimeout:0,maxParticipants:0,creationTime:I.parse((new Date).getTime()),metadata:"",numParticipants:1,numPublishers:1,turnPassword:"",enabledCodecs:[],activeRecording:!1}),this.localParticipant.updateInfo(new tt({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 ta(Hs.Kind.Video,new ot({source:We.CAMERA,sid:Math.floor(1e4*Math.random()).toString(),type:Ke.AUDIO,name:"video-dummy"}),new jo(s.useRealTracks?(yield window.navigator.mediaDevices.getUserMedia({video:!0})).getVideoTracks()[0]:Dr(160*(null!==(i=r.aspectRatios[0])&&void 0!==i?i: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 ta(Hs.Kind.Audio,new ot({source:We.MICROPHONE,sid:Math.floor(1e4*Math.random()).toString(),type:Ke.AUDIO}),new Eo(s.useRealTracks?(yield navigator.mediaDevices.getUserMedia({audio:!0})).getAudioTracks()[0]:Mr(),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<r.count-1;e+=1){let t=new tt({sid:Math.floor(1e4*Math.random()).toString(),identity:"simulated-".concat(e),state:it.ACTIVE,tracks:[],joinedAt:I.parse(Date.now())});const i=this.getOrCreateParticipant(t.identity,t);if(r.video){const s=Dr(160*(null!==(n=r.aspectRatios[e%r.aspectRatios.length])&&void 0!==n?n:1),160,!1,!0),o=new ot({source:We.CAMERA,sid:Math.floor(1e4*Math.random()).toString(),type:Ke.AUDIO});i.addSubscribedMediaTrack(s,o.sid,new MediaStream([s]),new RTCRtpReceiver),t.tracks=[...t.tracks,o]}if(r.audio){const e=Mr(),n=new ot({source:We.MICROPHONE,sid:Math.floor(1e4*Math.random()).toString(),type:Ke.AUDIO});i.addSubscribedMediaTrack(e,n.sid,new MediaStream([e]),new RTCRtpReceiver),t.tracks=[...t.tracks,n]}i.updateInfo(t)}}))}emit(t){for(var i=arguments.length,n=new Array(i>1?i-1:0),s=1;s<i;s++)n[s-1]=arguments[s];if(t!==e.RoomEvent.ActiveSpeakersChanged){const e=ca(n).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,...n)}}function ca(e){return e.map((e=>{if(e)return Array.isArray(e)?ca(e):"object"==typeof e?"logContext"in e&&e.logContext:e}))}var da;e.CheckStatus=void 0,(da=e.CheckStatus||(e.CheckStatus={}))[da.IDLE=0]="IDLE",da[da.RUNNING=1]="RUNNING",da[da.SKIPPED=2]="SKIPPED",da[da.SUCCESS=3]="SUCCESS",da[da.FAILED=4]="FAILED";class la extends Yi.EventEmitter{constructor(t,i){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};super(),this.status=e.CheckStatus.IDLE,this.logs=[],this.errorsAsWarnings=!1,this.url=t,this.token=i,this.name=this.constructor.name,this.room=new aa(n.roomOptions),this.connectOptions=n.connectOptions,n.errorsAsWarnings&&(this.errorsAsWarnings=n.errorsAsWarnings)}run(t){return Di(this,void 0,void 0,(function*(){if(this.status!==e.CheckStatus.IDLE)throw Error("check is running already");this.setStatus(e.CheckStatus.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!==e.CheckStatus.SKIPPED&&this.setStatus(this.isSuccess()?e.CheckStatus.SUCCESS:e.CheckStatus.FAILED),t&&t(),this.getInfo()}))}isSuccess(){return!this.logs.some((e=>"error"===e.level))}connect(){return Di(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 Di(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(e.CheckStatus.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 ua(e){return Di(this,void 0,void 0,(function*(){var t,i;null!=e||(e={}),null!==(t=e.audio)&&void 0!==t||(e.audio=!0),null!==(i=e.video)&&void 0!==i||(e.video=!0);const n=Xs(zs(e,fo,vo)),s=navigator.mediaDevices.getUserMedia(n);e.audio&&(jr.userMediaPromiseMap.set("audioinput",s),s.catch((()=>jr.userMediaPromiseMap.delete("audioinput")))),e.video&&(jr.userMediaPromiseMap.set("videoinput",s),s.catch((()=>jr.userMediaPromiseMap.delete("videoinput"))));const r=yield s;return Promise.all(r.getTracks().map((t=>Di(this,void 0,void 0,(function*(){const i="audio"===t.kind;let s,o=i?e.audio:e.video;"boolean"!=typeof o&&o||(o={});const a=i?n.audio:n.video;"boolean"!=typeof a&&(s=a),s?s.deviceId=t.getSettings().deviceId:s={deviceId:t.getSettings().deviceId};const c=wo(t,s);return c.kind===Hs.Kind.Video?c.source=Hs.Source.Camera:c.kind===Hs.Kind.Audio&&(c.source=Hs.Source.Microphone),c.mediaStream=r,o.processor&&(c instanceof Eo||c instanceof jo)&&(yield c.setProcessor(o.processor)),c})))))}))}function ha(e){return Di(this,void 0,void 0,(function*(){return(yield ua({audio:!1,video:e}))[0]}))}function pa(e){return Di(this,void 0,void 0,(function*(){return(yield ua({audio:e,video:!1}))[0]}))}class ma extends la{get description(){return"Can publish audio"}perform(){return Di(this,void 0,void 0,(function*(){var e;const t=yield this.connect(),i=yield pa();t.localParticipant.publishTrack(i),yield new Promise((e=>setTimeout(e,3e3)));const n=yield null===(e=i.sender)||void 0===e?void 0:e.getStats();if(!n)throw new Error("Could not get RTCStats");let s=0;if(n.forEach((e=>{"outbound-rtp"!==e.type||"audio"!==e.kind&&(e.kind||"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 ga extends la{get description(){return"Can publish video"}perform(){return Di(this,void 0,void 0,(function*(){var e;const t=yield this.connect(),i=yield ha();t.localParticipant.publishTrack(i),yield new Promise((e=>setTimeout(e,5e3)));const n=yield null===(e=i.sender)||void 0===e?void 0:e.getStats();if(!n)throw new Error("Could not get RTCStats");let s=0;if(n.forEach((e=>{"outbound-rtp"!==e.type||"video"!==e.kind&&(e.kind||"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 fa extends la{get description(){return"Resuming connection after interruption"}perform(){return Di(this,void 0,void 0,(function*(){var t;const i=yield this.connect();let n,s=!1,r=!1;const o=new Promise((e=>{setTimeout(e,5e3),n=e})),a=()=>{s=!0};i.on(e.RoomEvent.SignalReconnecting,a).on(e.RoomEvent.Reconnecting,a).on(e.RoomEvent.Reconnected,(()=>{r=!0,n(!0)})),null===(t=i.engine.client.ws)||void 0===t||t.close();const c=i.engine.client.onClose;if(c&&c(""),yield o,!s)throw new Error("Did not attempt to reconnect");if(!r||i.state!==e.ConnectionState.Connected)throw this.appendWarning("reconnection is only possible in Redis-based configurations"),new Error("Not able to reconnect")}))}}class va extends la{get description(){return"Can connect via TURN"}perform(){return Di(this,void 0,void 0,(function*(){var e,t;const i=new Gr,n=yield i.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3});let s=!1,r=!1,o=!1;for(let e of n.iceServers)for(let t of e.urls)t.startsWith("turn:")?(r=!0,o=!0):t.startsWith("turns:")&&(r=!0,o=!0,s=!0),t.startsWith("stun:")&&(o=!0);o?r&&!s&&this.appendWarning("TURN is configured server side, but TURN/TLS is unavailable."):this.appendWarning("No STUN servers configured on server side."),yield i.close(),(null===(t=null===(e=this.connectOptions)||void 0===e?void 0:e.rtcConfig)||void 0===t?void 0:t.iceServers)||r?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 ka extends la{get description(){return"Establishing WebRTC connection"}perform(){return Di(this,void 0,void 0,(function*(){let t=!1,i=!1;this.room.on(e.RoomEvent.SignalConnected,(()=>{const e=this.room.engine.client.onTrickle;this.room.engine.client.onTrickle=(n,s)=>{if(n.candidate){const e=new RTCIceCandidate(n);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&&(i=!0):s+=" (private)"),this.appendMessage(s)}e&&e(n,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(),Ei.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"),i||this.appendWarning("No public IPv4 UDP candidates were found. Your server is likely not configured correctly")}))}}class ba extends la{get description(){return"Connecting to signal connection via WebSocket"}perform(){return Di(this,void 0,void 0,(function*(){var e,t,i;(this.url.startsWith("ws:")||this.url.startsWith("http:"))&&this.appendWarning("Server is insecure, clients may block connections to it");let n=new Gr;const s=yield n.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)===kt.Cloud&&(null===(t=s.serverInfo)||void 0===t?void 0:t.region)&&this.appendMessage("LiveKit Cloud: ".concat(null===(i=s.serverInfo)||void 0===i?void 0:i.region)),yield n.close()}))}}class ya extends Yi.EventEmitter{constructor(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};super(),this.options={},this.checkResults=new Map,this.url=e,this.token=t,this.options=i}getNextCheckId(){const t=this.checkResults.size;return this.checkResults.set(t,{logs:[],status:e.CheckStatus.IDLE,name:"",description:""}),t}updateCheck(e,t){this.checkResults.set(e,t),this.emit("checkUpdate",e,t)}isSuccess(){return Array.from(this.checkResults.values()).every((t=>t.status!==e.CheckStatus.FAILED))}getResults(){return Array.from(this.checkResults.values())}createAndRunCheck(e){return Di(this,void 0,void 0,(function*(){const t=this.getNextCheckId(),i=new e(this.url,this.token,this.options),n=e=>{this.updateCheck(t,e)};i.on("update",n);const s=yield i.run();return i.off("update",n),s}))}checkWebsocket(){return Di(this,void 0,void 0,(function*(){return this.createAndRunCheck(ba)}))}checkWebRTC(){return Di(this,void 0,void 0,(function*(){return this.createAndRunCheck(ka)}))}checkTURN(){return Di(this,void 0,void 0,(function*(){return this.createAndRunCheck(va)}))}checkReconnect(){return Di(this,void 0,void 0,(function*(){return this.createAndRunCheck(fa)}))}checkPublishAudio(){return Di(this,void 0,void 0,(function*(){return this.createAndRunCheck(ma)}))}checkPublishVideo(){return Di(this,void 0,void 0,(function*(){return this.createAndRunCheck(ga)}))}}const Ta=new Map([["obs virtual camera",{facingMode:"environment",confidence:"medium"}]]),Ca=new Map([["iphone",{facingMode:"environment",confidence:"medium"}],["ipad",{facingMode:"environment",confidence:"medium"}]]);function Sa(e){var t;const i=e.trim().toLowerCase();if(""!==i)return Ta.has(i)?Ta.get(i):null===(t=Array.from(Ca.entries()).find((e=>{let[t]=e;return i.includes(t)})))||void 0===t?void 0:t[1]}e.BaseKeyProvider=ps,e.Checker=la,e.ConnectionCheck=ya,e.ConnectionError=gs,e.CriticalTimers=Ls,e.CryptorError=class extends ms{constructor(t){let i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:e.CryptorErrorReason.InternalError,n=arguments.length>2?arguments[2]:void 0;super(40,t),this.reason=i,this.participantIdentity=n}},e.DataPacket_Kind=dt,e.DefaultReconnectPolicy=xi,e.DeviceUnsupportedError=fs,e.DisconnectReason=Qe,e.ExternalE2EEKeyProvider=class extends ps{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 Di(this,void 0,void 0,(function*(){const t="string"==typeof e?yield ls(e):yield us(e);this.onSetEncryptionKey(t)}))}},e.LivekitError=ms,e.LocalAudioTrack=Eo,e.LocalParticipant=na,e.LocalTrack=Fr,e.LocalTrackPublication=ta,e.LocalVideoTrack=jo,e.Mutex=_r,e.NegotiationError=ys,e.Participant=ia,e.ParticipantKind=nt,e.PublishDataError=class extends ms{constructor(e){super(13,null!=e?e:"unable to publish data")}},e.RemoteAudioTrack=Yo,e.RemoteParticipant=ra,e.RemoteTrack=zo,e.RemoteTrackPublication=sa,e.RemoteVideoTrack=Xo,e.Room=aa,e.ScreenSharePresets=Ws,e.SignalRequestError=Ts,e.SubscriptionError=Ye,e.Track=Hs,e.TrackInvalidError=vs,e.TrackPublication=ea,e.UnexpectedConnectionState=bs,e.UnsupportedServer=ks,e.VideoPreset=Us,e.VideoPresets=qs,e.VideoPresets43=Ks,e.attachToElement=Js,e.createAudioAnalyser=function(e,t){const i=Object.assign({cloneTrack:!1,fftSize:2048,smoothingTimeConstant:.8,minDecibels:-100,maxDecibels:-80},t),n=$s();if(!n)throw new Error("Audio Context not supported on this browser");const s=i.cloneTrack?e.mediaStreamTrack.clone():e.mediaStreamTrack,r=n.createMediaStreamSource(new MediaStream([s])),o=n.createAnalyser();o.minDecibels=i.minDecibels,o.maxDecibels=i.maxDecibels,o.fftSize=i.fftSize,o.smoothingTimeConstant=i.smoothingTimeConstant,r.connect(o);const a=new Uint8Array(o.frequencyBinCount);return{calculateVolume:()=>{o.getByteFrequencyData(a);let e=0;for(const t of a)e+=Math.pow(t/255,2);return Math.sqrt(e/a.length)},analyser:o,cleanup:()=>Di(this,void 0,void 0,(function*(){yield n.close(),i.cloneTrack&&s.stop()}))}},e.createE2EEKey=function(){return window.crypto.getRandomValues(new Uint8Array(32))},e.createKeyMaterialFromBuffer=us,e.createKeyMaterialFromString=ls,e.createLocalAudioTrack=pa,e.createLocalScreenTracks=function(e){return Di(this,void 0,void 0,(function*(){if(void 0===e&&(e={}),void 0!==e.resolution||mr()||(e.resolution=Ws.h1080fps30.resolution),void 0===navigator.mediaDevices.getDisplayMedia)throw new fs("getDisplayMedia not supported");const t=Zs(e),i=yield navigator.mediaDevices.getDisplayMedia(t),n=i.getVideoTracks();if(0===n.length)throw new vs("no video track found");const s=new jo(n[0],void 0,!1);s.source=Hs.Source.ScreenShare;const r=[s];if(i.getAudioTracks().length>0){const e=new Eo(i.getAudioTracks()[0],void 0,!1);e.source=Hs.Source.ScreenShareAudio,r.push(e)}return r}))},e.createLocalTracks=ua,e.createLocalVideoTrack=ha,e.deriveKeys=function(e,t){return Di(this,void 0,void 0,(function*(){const i=hs(e.algorithm.name,t),n=yield crypto.subtle.deriveKey(i,e,{name:is,length:128},!1,["encrypt","decrypt"]);return{material:e,encryptionKey:n}}))},e.detachTrack=Qs,e.facingModeFromDeviceLabel=Sa,e.facingModeFromLocalTrack=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};var i;const n=e instanceof Fr?e.mediaStreamTrack:e,s=n.getSettings();let r={facingMode:null!==(i=t.defaultFacingMode)&&void 0!==i?i:"user",confidence:"low"};if("facingMode"in s){const e=s.facingMode;Ei.trace("rawFacingMode",{rawFacingMode:e}),e&&"string"==typeof e&&function(e){const t=["user","environment","left","right"];return void 0===e||t.includes(e)}(e)&&(r={facingMode:e,confidence:"high"})}if(["low","medium"].includes(r.confidence)){Ei.trace("Try to get facing mode from device label: (".concat(n.label,")"));const e=Sa(n.label);void 0!==e&&(r=e)}return r},e.getBrowser=Ds,e.getEmptyAudioStreamTrack=Mr,e.getEmptyVideoStreamTrack=function(){return Or||(Or=Dr()),Or.clone()},e.getLogger=Pi,e.importKey=function(e){return Di(this,arguments,void 0,(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{name:is},i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"encrypt";return function*(){return crypto.subtle.importKey("raw",e,t,!1,"derive"===i?["deriveBits","deriveKey"]:["encrypt","decrypt"])}()}))},e.isBackupCodec=Bs,e.isBrowserSupported=ur,e.isE2EESupported=as,e.isInsertableStreamSupported=ds,e.isScriptTransformSupported=cs,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 i=e.length,n=0;n<e.length;)i-n>=3&&!e[n]&&!e[n+1]&&3==e[n+2]?(t.push(e[n++]),t.push(e[n++]),n++):t.push(e[n++]);return new Uint8Array(t)},e.protocolVersion=15,e.ratchet=function(e,t){return Di(this,void 0,void 0,(function*(){const i=hs(e.algorithm.name,t);return crypto.subtle.deriveBits(i,e,256)}))},e.setLogExtension=function(t,i){(i?[i]:wi).forEach((i=>{const n=i.methodFactory;i.methodFactory=(i,s,r)=>{const o=n(i,s,r),a=e.LogLevel[i],c=a>=s&&a<e.LogLevel.silent;return(e,i)=>{i?o(e,i):o(e),c&&t(a,e,i)}},i.setLevel(i.getLevel())}))},e.setLogLevel=function(e,t){if(t)Si.getLogger(t).setLevel(e);else for(const t of wi)t.setLevel(e)},e.supportsAV1=ar,e.supportsAdaptiveStream=function(){return void 0!==typeof ResizeObserver&&void 0!==typeof IntersectionObserver},e.supportsDynacast=function(){return rr()},e.supportsVP9=cr,e.version=As,e.videoCodecs=Fs,e.writeRbsp=function(e){const t=[];for(var i=0,n=0;n<e.length;++n){var s=e[n];s<=3&&i>=2&&(t.push(3),i=0),t.push(s),0==s?++i:i=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(i){if("default"!==i&&!(i in e)){var n=Object.getOwnPropertyDescriptor(t,i);Object.defineProperty(e,i,n.get?n:{enumerable:!0,get:function(){return t[i]}})}}))})),Object.freeze(e)}function i(e,t){if(!e)throw new Error(t)}const n=34028234663852886e22,s=-34028234663852886e22,r=4294967295,o=2147483647,a=-2147483648;function c(e){if("number"!=typeof e)throw new Error("invalid int 32: "+typeof e);if(!Number.isInteger(e)||e>o||e<a)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>r||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>n||e<s))throw new Error("invalid float 32: "+e)}const u=Symbol("@bufbuild/protobuf/enum-type");function h(e){const t=e[u];return i(t,"missing enum type on enum object"),t}function p(e,t,i,n){e[u]=m(t,i.map((t=>({no:t.no,name:t.name,localName:e[t.no]}))))}function m(e,t,i){const n=Object.create(null),s=Object.create(null),r=[];for(const e of t){const t=f(e);r.push(t),n[e.name]=t,s[e.no]=t}return{typeName:e,values:r,findName:e=>n[e],findNumber:e=>s[e]}}function g(e,t,i){const n={};for(const e of t){const t=f(e);n[t.localName]=t.no,n[t.no]=t.localName}return p(n,e,t),n}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 i=this.getType().runtime.bin,n=i.makeReadOptions(t);return i.readMessage(this,n.readerFactory(e),e.byteLength,n),this}fromJson(e,t){const i=this.getType(),n=i.runtime.json,s=n.makeReadOptions(t);return n.readMessage(i,e,s,this),this}fromJsonString(e,t){let i;try{i=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(i,t)}toBinary(e){const t=this.getType().runtime.bin,i=t.makeWriteOptions(e),n=i.writerFactory();return t.writeMessage(this,n,i),n.finish()}toJson(e){const t=this.getType().runtime.json,i=t.makeWriteOptions(e);return t.writeMessage(this,i)}toJsonString(e){var t;const i=this.toJson(e);return JSON.stringify(i,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}}function k(){let e=0,t=0;for(let i=0;i<28;i+=7){let n=this.buf[this.pos++];if(e|=(127&n)<<i,0==(128&n))return this.assertBounds(),[e,t]}let i=this.buf[this.pos++];if(e|=(15&i)<<28,t=(112&i)>>4,0==(128&i))return this.assertBounds(),[e,t];for(let i=3;i<=31;i+=7){let n=this.buf[this.pos++];if(t|=(127&n)<<i,0==(128&n))return this.assertBounds(),[e,t]}throw new Error("invalid varint")}function b(e,t,i){for(let n=0;n<28;n+=7){const s=e>>>n,r=!(s>>>7==0&&0==t),o=255&(r?128|s:s);if(i.push(o),!r)return}const n=e>>>28&15|(7&t)<<4,s=!(t>>3==0);if(i.push(255&(s?128|n:n)),s){for(let e=3;e<31;e+=7){const n=t>>>e,s=!(n>>>7==0),r=255&(s?128|n:n);if(i.push(r),!s)return}i.push(t>>>31&1)}}const y=4294967296;function T(e){const t="-"===e[0];t&&(e=e.slice(1));const i=1e6;let n=0,s=0;function r(t,r){const o=Number(e.slice(t,r));s*=i,n=n*i+o,n>=y&&(s+=n/y|0,n%=y)}return r(-24,-18),r(-18,-12),r(-12,-6),r(-6),t?E(n,s):S(n,s)}function C(e,t){if(({lo:e,hi:t}=function(e,t){return{lo:e>>>0,hi:t>>>0}}(e,t)),t<=2097151)return String(y*t+e);const i=16777215&(e>>>24|t<<8),n=t>>16&65535;let s=(16777215&e)+6777216*i+6710656*n,r=i+8147497*n,o=2*n;const a=1e7;return s>=a&&(r+=Math.floor(s/a),s%=a),r>=a&&(o+=Math.floor(r/a),r%=a),o.toString()+w(r)+w(s)}function S(e,t){return{lo:0|e,hi:0|t}}function E(e,t){return t=~t,e?e=1+~e:t+=1,S(e,t)}const w=e=>{const t=String(e);return"0000000".slice(t.length)+t};function P(e,t){if(e>=0){for(;e>127;)t.push(127&e|128),e>>>=7;t.push(e)}else{for(let i=0;i<9;i++)t.push(127&e|128),e>>=7;t.push(1)}}function R(){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 I=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"),i=BigInt("9223372036854775807"),n=BigInt("0"),s=BigInt("18446744073709551615");return{zero:BigInt(0),supported:!0,parse(e){const n="bigint"==typeof e?e:BigInt(e);if(n>i||n<t)throw new Error("int64 invalid: ".concat(e));return n},uParse(e){const t="bigint"==typeof e?e:BigInt(e);if(t>s||t<n)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,i)=>(e.setInt32(0,t,!0),e.setInt32(4,i,!0),e.getBigInt64(0,!0)),uDec:(t,i)=>(e.setInt32(0,t,!0),e.setInt32(4,i,!0),e.getBigUint64(0,!0))}}const t=e=>i(/^-?[0-9]+$/.test(e),"int64 invalid: ".concat(e)),n=e=>i(/^[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()),n(e),e),enc:e=>("string"!=typeof e&&(e=e.toString()),t(e),T(e)),uEnc:e=>("string"!=typeof e&&(e=e.toString()),n(e),T(e)),dec:(e,t)=>function(e,t){let i=S(e,t);const n=2147483648&i.hi;n&&(i=E(i.lo,i.hi));const s=C(i.lo,i.hi);return n?"-"+s:s}(e,t),uDec:(e,t)=>C(e,t)}}();var O,x,D;function M(e,t,i){if(t===i)return!0;if(e==O.BYTES){if(!(t instanceof Uint8Array&&i instanceof Uint8Array))return!1;if(t.length!==i.length)return!1;for(let e=0;e<t.length;e++)if(t[e]!==i[e])return!1;return!0}switch(e){case O.UINT64:case O.FIXED64:case O.INT64:case O.SFIXED64:case O.SINT64:return t==i}return!1}function N(e,t){switch(e){case O.BOOL:return!1;case O.UINT64:case O.FIXED64:case O.INT64:case O.SFIXED64:case O.SINT64:return 0==t?I.zero:"0";case O.DOUBLE:case O.FLOAT:return 0;case O.BYTES:return new Uint8Array(0);case O.STRING:return"";default:return 0}}function _(e,t){switch(e){case O.BOOL:return!1===t;case O.STRING:return""===t;case O.BYTES:return t instanceof Uint8Array&&!t.byteLength;default:return 0==t}}!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"}(O||(O={})),function(e){e[e.BIGINT=0]="BIGINT",e[e.STRING=1]="STRING"}(x||(x={})),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"}(D||(D={}));class A{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),i=0;for(let e=0;e<this.chunks.length;e++)t.set(this.chunks[e],i),i+=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),P(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),P(e=(e<<1^e>>31)>>>0,this.buf),this}sfixed64(e){let t=new Uint8Array(8),i=new DataView(t.buffer),n=I.enc(e);return i.setInt32(0,n.lo,!0),i.setInt32(4,n.hi,!0),this.raw(t)}fixed64(e){let t=new Uint8Array(8),i=new DataView(t.buffer),n=I.uEnc(e);return i.setInt32(0,n.lo,!0),i.setInt32(4,n.hi,!0),this.raw(t)}int64(e){let t=I.enc(e);return b(t.lo,t.hi,this.buf),this}sint64(e){let t=I.enc(e),i=t.hi>>31;return b(t.lo<<1^i,(t.hi<<1|t.lo>>>31)^i,this.buf),this}uint64(e){let t=I.uEnc(e);return b(t.lo,t.hi,this.buf),this}}class L{constructor(e,t){this.varint64=k,this.uint32=R,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,i=7&e;if(t<=0||i<0||i>5)throw new Error("illegal tag: field no "+t+" wire type "+i);return[t,i]}skip(e,t){let i=this.pos;switch(e){case D.Varint:for(;128&this.buf[this.pos++];);break;case D.Bit64:this.pos+=4;case D.Bit32:this.pos+=4;break;case D.LengthDelimited:let i=this.uint32();this.pos+=i;break;case D.StartGroup:for(;;){const[e,i]=this.tag();if(i===D.EndGroup){if(void 0!==t&&e!==t)throw new Error("invalid end group tag");break}this.skip(i,e)}break;default:throw new Error("cant skip wire type "+e)}return this.assertBounds(),this.buf.subarray(i,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 I.dec(...this.varint64())}uint64(){return I.uDec(...this.varint64())}sint64(){let[e,t]=this.varint64(),i=-(1&e);return e=(e>>>1|(1&t)<<31)^i,t=t>>>1^i,I.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 I.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return I.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 U(e){const t=e.field.localName,i=Object.create(null);return i[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 N(t.T,t.L);case"message":const e=t.T,i=new e;return e.fieldWrapper?e.fieldWrapper.unwrapField(i):i;case"map":throw"map fields are not allowed to be extensions"}}(e),[i,()=>i[t]]}let j="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),F=[];for(let e=0;e<j.length;e++)F[j[e].charCodeAt(0)]=e;F["-".charCodeAt(0)]=j.indexOf("+"),F["_".charCodeAt(0)]=j.indexOf("/");const B={dec(e){let t=3*e.length/4;"="==e[e.length-2]?t-=2:"="==e[e.length-1]&&(t-=1);let i,n=new Uint8Array(t),s=0,r=0,o=0;for(let t=0;t<e.length;t++){if(i=F[e.charCodeAt(t)],void 0===i)switch(e[t]){case"=":r=0;case"\n":case"\r":case"\t":case" ":continue;default:throw Error("invalid base64 string.")}switch(r){case 0:o=i,r=1;break;case 1:n[s++]=o<<2|(48&i)>>4,o=i,r=2;break;case 2:n[s++]=(15&o)<<4|(60&i)>>2,o=i,r=3;break;case 3:n[s++]=(3&o)<<6|i,r=0}}if(1==r)throw Error("invalid base64 string.");return n.subarray(0,s)},enc(e){let t,i="",n=0,s=0;for(let r=0;r<e.length;r++)switch(t=e[r],n){case 0:i+=j[t>>2],s=(3&t)<<4,n=1;break;case 1:i+=j[s|t>>4],s=(15&t)<<2,n=2;break;case 2:i+=j[s|t>>6],i+=j[63&t],n=0}return n&&(i+=j[s],i+="=",1==n&&(i+="=")),i}};function V(e,t,i){W(t,e);const n=t.runtime.bin.makeReadOptions(i),s=function(e,t){if(!t.repeated&&("enum"==t.kind||"scalar"==t.kind)){for(let i=e.length-1;i>=0;--i)if(e[i].no==t.no)return[e[i]];return[]}return e.filter((e=>e.no===t.no))}(e.getType().runtime.bin.listUnknownFields(e),t.field),[r,o]=U(t);for(const e of s)t.runtime.bin.readField(r,n.readerFactory(e.data),t.field,e.wireType,n);return o()}function q(e,t,i,n){W(t,e);const s=t.runtime.bin.makeReadOptions(n),r=t.runtime.bin.makeWriteOptions(n);if(K(e,t)){const i=e.getType().runtime.bin.listUnknownFields(e).filter((e=>e.no!=t.field.no));e.getType().runtime.bin.discardUnknownFields(e);for(const t of i)e.getType().runtime.bin.onUnknownField(e,t.no,t.wireType,t.data)}const o=r.writerFactory();let a=t.field;a.opt||a.repeated||"enum"!=a.kind&&"scalar"!=a.kind||(a=Object.assign(Object.assign({},t.field),{opt:!0})),t.runtime.bin.writeField(a,i,o,r);const c=s.readerFactory(o.finish());for(;c.pos<c.len;){const[t,i]=c.tag(),n=c.skip(i,t);e.getType().runtime.bin.onUnknownField(e,t,i,n)}}function K(e,t){const i=e.getType();return t.extendee.typeName===i.typeName&&!!i.runtime.bin.listUnknownFields(e).find((e=>e.no==t.field.no))}function W(e,t){i(e.extendee.typeName==t.getType().typeName,"extension ".concat(e.typeName," can only be applied to message ").concat(e.extendee.typeName))}function G(e,t){const i=e.localName;if(e.repeated)return t[i].length>0;if(e.oneof)return t[e.oneof.localName].case===i;switch(e.kind){case"enum":case"scalar":return e.opt||e.req?void 0!==t[i]:"enum"==e.kind?t[i]!==e.T.values[0].no:!_(e.T,t[i]);case"message":return void 0!==t[i];case"map":return Object.keys(t[i]).length>0}}function H(e,t){const i=e.localName,n=!e.opt&&!e.req;if(e.repeated)t[i]=[];else if(e.oneof)t[e.oneof.localName]={case:void 0};else switch(e.kind){case"map":t[i]={};break;case"enum":t[i]=n?e.T.values[0].no:void 0;break;case"scalar":t[i]=n?N(e.T,e.L):void 0;break;case"message":t[i]=void 0}}function J(e,t){if(null===e||"object"!=typeof e)return!1;if(!Object.getOwnPropertyNames(v.prototype).every((t=>t in e&&"function"==typeof e[t])))return!1;const i=e.getType();return null!==i&&"function"==typeof i&&"typeName"in i&&"string"==typeof i.typeName&&(void 0===t||i.typeName==t.typeName)}function Q(e,t){return J(t)||!e.fieldWrapper?t:e.fieldWrapper.wrapField(t)}O.DOUBLE,O.FLOAT,O.INT64,O.UINT64,O.INT32,O.UINT32,O.BOOL,O.STRING,O.BYTES;const z={ignoreUnknownFields:!1},Y={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0};function X(e){return e?Object.assign(Object.assign({},z),e):z}function $(e){return e?Object.assign(Object.assign({},Y),e):Y}const Z=Symbol(),ee=Symbol();function te(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 ie(e,t,n,s,r){let o=n.localName;if(n.repeated){if(i("map"!=n.kind),null===t)return;if(!Array.isArray(t))throw new Error("cannot decode field ".concat(r.typeName,".").concat(n.name," from JSON: ").concat(te(t)));const a=e[o];for(const e of t){if(null===e)throw new Error("cannot decode field ".concat(r.typeName,".").concat(n.name," from JSON: ").concat(te(e)));switch(n.kind){case"message":a.push(n.T.fromJson(e,s));break;case"enum":const t=re(n.T,e,s.ignoreUnknownFields,!0);t!==ee&&a.push(t);break;case"scalar":try{a.push(se(n.T,e,n.L,!0))}catch(t){let i="cannot decode field ".concat(r.typeName,".").concat(n.name," from JSON: ").concat(te(e));throw t instanceof Error&&t.message.length>0&&(i+=": ".concat(t.message)),new Error(i)}}}}else if("map"==n.kind){if(null===t)return;if("object"!=typeof t||Array.isArray(t))throw new Error("cannot decode field ".concat(r.typeName,".").concat(n.name," from JSON: ").concat(te(t)));const i=e[o];for(const[e,o]of Object.entries(t)){if(null===o)throw new Error("cannot decode field ".concat(r.typeName,".").concat(n.name," from JSON: map value null"));let a;try{a=ne(n.K,e)}catch(e){let i="cannot decode map key for field ".concat(r.typeName,".").concat(n.name," from JSON: ").concat(te(t));throw e instanceof Error&&e.message.length>0&&(i+=": ".concat(e.message)),new Error(i)}switch(n.V.kind){case"message":i[a]=n.V.T.fromJson(o,s);break;case"enum":const e=re(n.V.T,o,s.ignoreUnknownFields,!0);e!==ee&&(i[a]=e);break;case"scalar":try{i[a]=se(n.V.T,o,x.BIGINT,!0)}catch(e){let i="cannot decode map value for field ".concat(r.typeName,".").concat(n.name," from JSON: ").concat(te(t));throw e instanceof Error&&e.message.length>0&&(i+=": ".concat(e.message)),new Error(i)}}}}else switch(n.oneof&&(e=e[n.oneof.localName]={case:o},o="value"),n.kind){case"message":const i=n.T;if(null===t&&"google.protobuf.Value"!=i.typeName)return;let a=e[o];J(a)?a.fromJson(t,s):(e[o]=a=i.fromJson(t,s),i.fieldWrapper&&!n.oneof&&(e[o]=i.fieldWrapper.unwrapField(a)));break;case"enum":const c=re(n.T,t,s.ignoreUnknownFields,!1);switch(c){case Z:H(n,e);break;case ee:break;default:e[o]=c}break;case"scalar":try{const i=se(n.T,t,n.L,!1);if(i===Z)H(n,e);else e[o]=i}catch(e){let i="cannot decode field ".concat(r.typeName,".").concat(n.name," from JSON: ").concat(te(t));throw e instanceof Error&&e.message.length>0&&(i+=": ".concat(e.message)),new Error(i)}}}function ne(e,t){if(e===O.BOOL)switch(t){case"true":t=!0;break;case"false":t=!1}return se(e,t,x.BIGINT,!0).toString()}function se(e,t,i,n){if(null===t)return n?N(e,i):Z;switch(e){case O.DOUBLE:case O.FLOAT: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 n=Number(t);if(Number.isNaN(n))break;if(!Number.isFinite(n))break;return e==O.FLOAT&&l(n),n;case O.INT32:case O.FIXED32:case O.SFIXED32:case O.SINT32:case O.UINT32:let s;if("number"==typeof t?s=t:"string"==typeof t&&t.length>0&&t.trim().length===t.length&&(s=Number(t)),void 0===s)break;return e==O.UINT32||e==O.FIXED32?d(s):c(s),s;case O.INT64:case O.SFIXED64:case O.SINT64:if("number"!=typeof t&&"string"!=typeof t)break;const r=I.parse(t);return i?r.toString():r;case O.FIXED64:case O.UINT64:if("number"!=typeof t&&"string"!=typeof t)break;const o=I.uParse(t);return i?o.toString():o;case O.BOOL:if("boolean"!=typeof t)break;return t;case O.STRING:if("string"!=typeof t)break;try{encodeURIComponent(t)}catch(e){throw new Error("invalid UTF8")}return t;case O.BYTES:if(""===t)return new Uint8Array(0);if("string"!=typeof t)break;return B.dec(t)}throw new Error}function re(e,t,i,n){if(null===t)return"google.protobuf.NullValue"==e.typeName?0:n?e.values[0].no:Z;switch(typeof t){case"number":if(Number.isInteger(t))return t;break;case"string":const n=e.findName(t);if(void 0!==n)return n.no;if(i)return ee}throw new Error("cannot decode enum ".concat(e.typeName," from JSON: ").concat(te(t)))}function oe(e){return!(!e.repeated&&"map"!=e.kind)||!e.oneof&&("message"!=e.kind&&(!e.opt&&!e.req))}function ae(e,t,n){if("map"==e.kind){i("object"==typeof t&&null!=t);const s={},r=Object.entries(t);switch(e.V.kind){case"scalar":for(const[t,i]of r)s[t.toString()]=de(e.V.T,i);break;case"message":for(const[e,t]of r)s[e.toString()]=t.toJson(n);break;case"enum":const t=e.V.T;for(const[e,i]of r)s[e.toString()]=ce(t,i,n.enumAsInteger)}return n.emitDefaultValues||r.length>0?s:void 0}if(e.repeated){i(Array.isArray(t));const s=[];switch(e.kind){case"scalar":for(let i=0;i<t.length;i++)s.push(de(e.T,t[i]));break;case"enum":for(let i=0;i<t.length;i++)s.push(ce(e.T,t[i],n.enumAsInteger));break;case"message":for(let e=0;e<t.length;e++)s.push(t[e].toJson(n))}return n.emitDefaultValues||s.length>0?s:void 0}switch(e.kind){case"scalar":return de(e.T,t);case"enum":return ce(e.T,t,n.enumAsInteger);case"message":return Q(e.T,t).toJson(n)}}function ce(e,t,n){var s;if(i("number"==typeof t),"google.protobuf.NullValue"==e.typeName)return null;if(n)return t;const r=e.findNumber(t);return null!==(s=null==r?void 0:r.name)&&void 0!==s?s:t}function de(e,t){switch(e){case O.INT32:case O.SFIXED32:case O.SINT32:case O.FIXED32:case O.UINT32:return i("number"==typeof t),t;case O.FLOAT:case O.DOUBLE:return i("number"==typeof t),Number.isNaN(t)?"NaN":t===Number.POSITIVE_INFINITY?"Infinity":t===Number.NEGATIVE_INFINITY?"-Infinity":t;case O.STRING:return i("string"==typeof t),t;case O.BOOL:return i("boolean"==typeof t),t;case O.UINT64:case O.FIXED64:case O.INT64:case O.SFIXED64:case O.SINT64:return i("bigint"==typeof t||"string"==typeof t||"number"==typeof t),t.toString();case O.BYTES:return i(t instanceof Uint8Array),B.enc(t)}}const le=Symbol("@bufbuild/protobuf/unknown-fields"),ue={readUnknownFields:!0,readerFactory:e=>new L(e)},he={writeUnknownFields:!0,writerFactory:()=>new A};function pe(e){return e?Object.assign(Object.assign({},ue),e):ue}function me(e){return e?Object.assign(Object.assign({},he),e):he}function ge(e,t,i,n,s){let{repeated:r,localName:o}=i;switch(i.oneof&&((e=e[i.oneof.localName]).case!=o&&delete e.value,e.case=o,o="value"),i.kind){case"scalar":case"enum":const a="enum"==i.kind?O.INT32:i.T;let c=ke;if("scalar"==i.kind&&i.L>0&&(c=ve),r){let i=e[o];if(n==D.LengthDelimited&&a!=O.STRING&&a!=O.BYTES){let e=t.uint32()+t.pos;for(;t.pos<e;)i.push(c(t,a))}else i.push(c(t,a))}else e[o]=c(t,a);break;case"message":const d=i.T;r?e[o].push(fe(t,new d,s,i)):J(e[o])?fe(t,e[o],s,i):(e[o]=fe(t,new d,s,i),!d.fieldWrapper||i.oneof||i.repeated||(e[o]=d.fieldWrapper.unwrapField(e[o])));break;case"map":let[l,u]=function(e,t,i){const n=t.uint32(),s=t.pos+n;let r,o;for(;t.pos<s;){const[n]=t.tag();switch(n){case 1:r=ke(t,e.K);break;case 2:switch(e.V.kind){case"scalar":o=ke(t,e.V.T);break;case"enum":o=t.int32();break;case"message":o=fe(t,new e.V.T,i,void 0)}}}void 0===r&&(r=N(e.K,x.BIGINT));"string"!=typeof r&&"number"!=typeof r&&(r=r.toString());if(void 0===o)switch(e.V.kind){case"scalar":o=N(e.V.T,x.BIGINT);break;case"enum":o=e.V.T.values[0].no;break;case"message":o=new e.V.T}return[r,o]}(i,t,s);e[o][l]=u}}function fe(e,t,i,n){const s=t.getType().runtime.bin,r=null==n?void 0:n.delimited;return s.readMessage(t,e,r?n.no:e.uint32(),i,r),t}function ve(e,t){const i=ke(e,t);return"bigint"==typeof i?i.toString():i}function ke(e,t){switch(t){case O.STRING:return e.string();case O.BOOL:return e.bool();case O.DOUBLE:return e.double();case O.FLOAT:return e.float();case O.INT32:return e.int32();case O.INT64:return e.int64();case O.UINT64:return e.uint64();case O.FIXED64:return e.fixed64();case O.BYTES:return e.bytes();case O.FIXED32:return e.fixed32();case O.SFIXED32:return e.sfixed32();case O.SFIXED64:return e.sfixed64();case O.SINT64:return e.sint64();case O.UINT32:return e.uint32();case O.SINT32:return e.sint32()}}function be(e,t,n,s){i(void 0!==t);const r=e.repeated;switch(e.kind){case"scalar":case"enum":let o="enum"==e.kind?O.INT32:e.T;if(r)if(i(Array.isArray(t)),e.packed)!function(e,t,i,n){if(!n.length)return;e.tag(i,D.LengthDelimited).fork();let[,s]=Se(t);for(let t=0;t<n.length;t++)e[s](n[t]);e.join()}(n,o,e.no,t);else for(const i of t)Ce(n,o,e.no,i);else Ce(n,o,e.no,t);break;case"message":if(r){i(Array.isArray(t));for(const i of t)Te(n,s,e,i)}else Te(n,s,e,t);break;case"map":i("object"==typeof t&&null!=t);for(const[i,r]of Object.entries(t))ye(n,s,e,i,r)}}function ye(e,t,n,s,r){e.tag(n.no,D.LengthDelimited),e.fork();let o=s;switch(n.K){case O.INT32:case O.FIXED32:case O.UINT32:case O.SFIXED32:case O.SINT32:o=Number.parseInt(s);break;case O.BOOL:i("true"==s||"false"==s),o="true"==s}switch(Ce(e,n.K,1,o),n.V.kind){case"scalar":Ce(e,n.V.T,2,r);break;case"enum":Ce(e,O.INT32,2,r);break;case"message":i(void 0!==r),e.tag(2,D.LengthDelimited).bytes(r.toBinary(t))}e.join()}function Te(e,t,i,n){const s=Q(i.T,n);i.delimited?e.tag(i.no,D.StartGroup).raw(s.toBinary(t)).tag(i.no,D.EndGroup):e.tag(i.no,D.LengthDelimited).bytes(s.toBinary(t))}function Ce(e,t,n,s){i(void 0!==s);let[r,o]=Se(t);e.tag(n,r)[o](s)}function Se(e){let t=D.Varint;switch(e){case O.BYTES:case O.STRING:t=D.LengthDelimited;break;case O.DOUBLE:case O.FIXED64:case O.SFIXED64:t=D.Bit64;break;case O.FIXED32:case O.SFIXED32:case O.FLOAT:t=D.Bit32}return[t,O[e].toLowerCase()]}function Ee(e){if(void 0===e)return e;if(J(e))return e.clone();if(e instanceof Uint8Array){const t=new Uint8Array(e.byteLength);return t.set(e),t}return e}function we(e){return e instanceof Uint8Array?e:new Uint8Array(e)}class Pe{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 i of this.list())i.oneof?i.oneof!==t&&(t=i.oneof,e.push(t)):e.push(i)}return this.members}}function Re(e,t){const i=Oe(e);return t?i:_e(Ne(i))}const Ie=Oe;function Oe(e){let t=!1;const i=[];for(let n=0;n<e.length;n++){let s=e.charAt(n);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":i.push(s),t=!1;break;default:t&&(t=!1,s=s.toUpperCase()),i.push(s)}}return i.join("")}const xe=new Set(["constructor","toString","toJSON","valueOf"]),De=new Set(["getType","clone","equals","fromBinary","fromJson","fromJsonString","toBinary","toJson","toJsonString","toObject"]),Me=e=>"".concat(e,"$"),Ne=e=>De.has(e)?Me(e):e,_e=e=>xe.has(e)?Me(e):e;class Ae{constructor(e){this.kind="oneof",this.repeated=!1,this.packed=!1,this.opt=!1,this.req=!1,this.default=void 0,this.fields=[],this.name=e,this.localName=Re(e,!1)}addField(e){i(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 Le=(Ue=e=>new Pe(e,(e=>function(e,t){var i,n,s,r,o,a;const c=[];let d;for(const t of"function"==typeof e?e():e){const e=t;if(e.localName=Re(t.name,void 0!==t.oneof),e.jsonName=null!==(i=t.jsonName)&&void 0!==i?i:Ie(t.name),e.repeated=null!==(n=t.repeated)&&void 0!==n&&n,"scalar"==t.kind&&(e.L=null!==(s=t.L)&&void 0!==s?s:x.BIGINT),e.delimited=null!==(r=t.delimited)&&void 0!==r&&r,e.req=null!==(o=t.req)&&void 0!==o&&o,e.opt=null!==(a=t.opt)&&void 0!==a&&a,void 0===t.packed&&(e.packed="enum"==t.kind||"scalar"==t.kind&&t.T!=O.BYTES&&t.T!=O.STRING),void 0!==t.oneof){const i="string"==typeof t.oneof?t.oneof:t.oneof.name;d&&d.name==i||(d=new Ae(i)),e.oneof=d,d.addField(e)}c.push(e)}return c}(e))),je=e=>{for(const t of e.getType().fields.byMember()){if(t.opt)continue;const i=t.localName,n=e;if(t.repeated)n[i]=[];else switch(t.kind){case"oneof":n[i]={case:void 0};break;case"enum":n[i]=0;break;case"map":n[i]={};break;case"scalar":n[i]=N(t.T,t.L)}}},{syntax:"proto3",json:{makeReadOptions:X,makeWriteOptions:$,readMessage(e,t,i,n){if(null==t||Array.isArray(t)||"object"!=typeof t)throw new Error("cannot decode message ".concat(e.typeName," from JSON: ").concat(te(t)));n=null!=n?n:new e;const s=new Map,r=i.typeRegistry;for(const[o,a]of Object.entries(t)){const t=e.fields.findJsonName(o);if(t){if(t.oneof){if(null===a&&"scalar"==t.kind)continue;const i=s.get(t.oneof);if(void 0!==i)throw new Error("cannot decode message ".concat(e.typeName,' from JSON: multiple keys for oneof "').concat(t.oneof.name,'" present: "').concat(i,'", "').concat(o,'"'));s.set(t.oneof,o)}ie(n,a,t,i,e)}else{let t=!1;if((null==r?void 0:r.findExtension)&&o.startsWith("[")&&o.endsWith("]")){const s=r.findExtension(o.substring(1,o.length-1));if(s&&s.extendee.typeName==e.typeName){t=!0;const[e,r]=U(s);ie(e,a,s.field,i,s),q(n,s,r(),i)}}if(!t&&!i.ignoreUnknownFields)throw new Error("cannot decode message ".concat(e.typeName,' from JSON: key "').concat(o,'" is unknown'))}}return n},writeMessage(e,t){const i=e.getType(),n={};let s;try{for(s of i.fields.byNumber()){if(!G(s,e)){if(s.req)throw"required field not set";if(!t.emitDefaultValues)continue;if(!oe(s))continue}const i=ae(s,s.oneof?e[s.oneof.localName].value:e[s.localName],t);void 0!==i&&(n[t.useProtoFieldName?s.name:s.jsonName]=i)}const r=t.typeRegistry;if(null==r?void 0:r.findExtensionFor)for(const s of i.runtime.bin.listUnknownFields(e)){const o=r.findExtensionFor(i.typeName,s.no);if(o&&K(e,o)){const i=V(e,o,t),s=ae(o.field,i,t);void 0!==s&&(n[o.field.jsonName]=s)}}}catch(e){const t=s?"cannot encode field ".concat(i.typeName,".").concat(s.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 n},readScalar:(e,t,i)=>se(e,t,null!=i?i:x.BIGINT,!0),writeScalar(e,t,i){if(void 0!==t)return i||_(e,t)?de(e,t):void 0},debug:te},bin:{makeReadOptions:pe,makeWriteOptions:me,listUnknownFields(e){var t;return null!==(t=e[le])&&void 0!==t?t:[]},discardUnknownFields(e){delete e[le]},writeUnknownFields(e,t){const i=e[le];if(i)for(const e of i)t.tag(e.no,e.wireType).raw(e.data)},onUnknownField(e,t,i,n){const s=e;Array.isArray(s[le])||(s[le]=[]),s[le].push({no:t,wireType:i,data:n})},readMessage(e,t,i,n,s){const r=e.getType(),o=s?t.len:t.pos+i;let a,c;for(;t.pos<o&&([a,c]=t.tag(),!0!==s||c!=D.EndGroup);){const i=r.fields.find(a);if(i)ge(e,t,i,c,n);else{const i=t.skip(c,a);n.readUnknownFields&&this.onUnknownField(e,a,c,i)}}if(s&&(c!=D.EndGroup||a!==i))throw new Error("invalid end group tag")},readField:ge,writeMessage(e,t,i){const n=e.getType();for(const s of n.fields.byNumber())if(G(s,e))be(s,s.oneof?e[s.oneof.localName].value:e[s.localName],t,i);else if(s.req)throw new Error("cannot encode field ".concat(n.typeName,".").concat(s.name," to binary: required field not set"));return i.writeUnknownFields&&this.writeUnknownFields(e,t),t},writeField(e,t,i,n){void 0!==t&&be(e,t,i,n)}},util:Object.assign(Object.assign({},{setEnumType:p,initPartial(e,t){if(void 0===e)return;const i=t.getType();for(const n of i.fields.byMember()){const i=n.localName,s=t,r=e;if(null!=r[i])switch(n.kind){case"oneof":const e=r[i].case;if(void 0===e)continue;const t=n.findField(e);let o=r[i].value;t&&"message"==t.kind&&!J(o,t.T)?o=new t.T(o):t&&"scalar"===t.kind&&t.T===O.BYTES&&(o=we(o)),s[i]={case:e,value:o};break;case"scalar":case"enum":let a=r[i];n.T===O.BYTES&&(a=n.repeated?a.map(we):we(a)),s[i]=a;break;case"map":switch(n.V.kind){case"scalar":case"enum":if(n.V.T===O.BYTES)for(const[e,t]of Object.entries(r[i]))s[i][e]=we(t);else Object.assign(s[i],r[i]);break;case"message":const e=n.V.T;for(const t of Object.keys(r[i])){let n=r[i][t];e.fieldWrapper||(n=new e(n)),s[i][t]=n}}break;case"message":const c=n.T;if(n.repeated)s[i]=r[i].map((e=>J(e,c)?e:new c(e)));else{const e=r[i];c.fieldWrapper?"google.protobuf.BytesValue"===c.typeName?s[i]=we(e):s[i]=e:s[i]=J(e,c)?e:new c(e)}}}},equals:(e,t,i)=>t===i||!(!t||!i)&&e.fields.byMember().every((e=>{const n=t[e.localName],s=i[e.localName];if(e.repeated){if(n.length!==s.length)return!1;switch(e.kind){case"message":return n.every(((t,i)=>e.T.equals(t,s[i])));case"scalar":return n.every(((t,i)=>M(e.T,t,s[i])));case"enum":return n.every(((e,t)=>M(O.INT32,e,s[t])))}throw new Error("repeated cannot contain ".concat(e.kind))}switch(e.kind){case"message":return e.T.equals(n,s);case"enum":return M(O.INT32,n,s);case"scalar":return M(e.T,n,s);case"oneof":if(n.case!==s.case)return!1;const t=e.findField(n.case);if(void 0===t)return!0;switch(t.kind){case"message":return t.T.equals(n.value,s.value);case"enum":return M(O.INT32,n.value,s.value);case"scalar":return M(t.T,n.value,s.value)}throw new Error("oneof cannot contain ".concat(t.kind));case"map":const i=Object.keys(n).concat(Object.keys(s));switch(e.V.kind){case"message":const t=e.V.T;return i.every((e=>t.equals(n[e],s[e])));case"enum":return i.every((e=>M(O.INT32,n[e],s[e])));case"scalar":const r=e.V.T;return i.every((e=>M(r,n[e],s[e])))}}})),clone(e){const t=e.getType(),i=new t,n=i;for(const i of t.fields.byMember()){const t=e[i.localName];let s;if(i.repeated)s=t.map(Ee);else if("map"==i.kind){s=n[i.localName];for(const[e,i]of Object.entries(t))s[e]=Ee(i)}else s="oneof"==i.kind?i.findField(t.case)?{case:t.case,value:Ee(t.value)}:{case:void 0}:Ee(t);n[i.localName]=s}for(const i of t.runtime.bin.listUnknownFields(e))t.runtime.bin.onUnknownField(n,i.no,i.wireType,i.data);return i}}),{newFieldList:Ue,initFields:je}),makeMessageType(e,t,i){return function(e,t,i,n){var s;const r=null!==(s=null==n?void 0:n.localName)&&void 0!==s?s:t.substring(t.lastIndexOf(".")+1),o={[r]:function(t){e.util.initFields(this),e.util.initPartial(t,this)}}[r];return Object.setPrototypeOf(o.prototype,new v),Object.assign(o,{runtime:e,typeName:t,fields:e.util.newFieldList(i),fromBinary:(e,t)=>(new o).fromBinary(e,t),fromJson:(e,t)=>(new o).fromJson(e,t),fromJsonString:(e,t)=>(new o).fromJsonString(e,t),equals:(t,i)=>e.util.equals(o,t,i)}),o}(this,e,t,i)},makeEnum:g,makeEnumType:m,getEnumType:h,makeExtension(e,t,i){return function(e,t,i,n){let s;return{typeName:t,extendee:i,get field(){if(!s){const i="function"==typeof n?n():n;i.name=t.split(".").pop(),i.jsonName="[".concat(t,"]"),s=e.util.newFieldList([i]).list()[0]}return s},runtime:e}}(this,e,t,i)}});var Ue,je;const Fe=Le.makeMessageType("livekit.MetricsBatch",(()=>[{no:1,name:"str_data",kind:"scalar",T:9,repeated:!0},{no:2,name:"time_series",kind:"message",T:Be,repeated:!0},{no:3,name:"events",kind:"message",T:qe,repeated:!0}])),Be=Le.makeMessageType("livekit.TimeSeriesMetric",(()=>[{no:1,name:"label",kind:"scalar",T:13},{no:2,name:"participant_identity",kind:"scalar",T:13},{no:3,name:"track_sid",kind:"scalar",T:13},{no:4,name:"start_timestamp",kind:"scalar",T:3},{no:5,name:"end_timestamp",kind:"scalar",T:3},{no:6,name:"samples",kind:"message",T:Ve,repeated:!0}])),Ve=Le.makeMessageType("livekit.MetricSample",(()=>[{no:1,name:"timestamp",kind:"scalar",T:3},{no:2,name:"value",kind:"scalar",T:2}])),qe=Le.makeMessageType("livekit.EventMetric",(()=>[{no:1,name:"label",kind:"scalar",T:13},{no:2,name:"participant_identity",kind:"scalar",T:13},{no:3,name:"track_sid",kind:"scalar",T:13},{no:4,name:"start_timestamp",kind:"scalar",T:3},{no:5,name:"end_timestamp",kind:"scalar",T:3,opt:!0},{no:6,name:"metadata",kind:"scalar",T:9}])),Ke=Le.makeEnum("livekit.TrackType",[{no:0,name:"AUDIO"},{no:1,name:"VIDEO"},{no:2,name:"DATA"}]),We=Le.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"}]),Ge=Le.makeEnum("livekit.VideoQuality",[{no:0,name:"LOW"},{no:1,name:"MEDIUM"},{no:2,name:"HIGH"},{no:3,name:"OFF"}]),He=Le.makeEnum("livekit.ConnectionQuality",[{no:0,name:"POOR"},{no:1,name:"GOOD"},{no:2,name:"EXCELLENT"},{no:3,name:"LOST"}]),Je=Le.makeEnum("livekit.ClientConfigSetting",[{no:0,name:"UNSET"},{no:1,name:"DISABLED"},{no:2,name:"ENABLED"}]),Qe=Le.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"},{no:10,name:"ROOM_CLOSED"}]),ze=Le.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"}]),Ye=Le.makeEnum("livekit.SubscriptionError",[{no:0,name:"SE_UNKNOWN"},{no:1,name:"SE_CODEC_UNSUPPORTED"},{no:2,name:"SE_TRACK_NOTFOUND"}]),Xe=Le.makeEnum("livekit.AudioTrackFeature",[{no:0,name:"TF_STEREO"},{no:1,name:"TF_NO_DTX"},{no:2,name:"TF_AUTO_GAIN_CONTROL"},{no:3,name:"TF_ECHO_CANCELLATION"},{no:4,name:"TF_NOISE_SUPPRESSION"},{no:5,name:"TF_ENHANCED_NOISE_CANCELLATION"}]),$e=Le.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:Ze,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:Et}])),Ze=Le.makeMessageType("livekit.Codec",(()=>[{no:1,name:"mime",kind:"scalar",T:9},{no:2,name:"fmtp_line",kind:"scalar",T:9}])),et=Le.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:Le.getEnumType(We),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},{no:12,name:"can_subscribe_metrics",kind:"scalar",T:8}])),tt=Le.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:Le.getEnumType(it)},{no:4,name:"tracks",kind:"message",T:ot,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:et},{no:12,name:"region",kind:"scalar",T:9},{no:13,name:"is_publisher",kind:"scalar",T:8},{no:14,name:"kind",kind:"enum",T:Le.getEnumType(nt)},{no:15,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:16,name:"disconnect_reason",kind:"enum",T:Le.getEnumType(Qe)}])),it=Le.makeEnum("livekit.ParticipantInfo.State",[{no:0,name:"JOINING"},{no:1,name:"JOINED"},{no:2,name:"ACTIVE"},{no:3,name:"DISCONNECTED"}]),nt=Le.makeEnum("livekit.ParticipantInfo.Kind",[{no:0,name:"STANDARD"},{no:1,name:"INGRESS"},{no:2,name:"EGRESS"},{no:3,name:"SIP"},{no:4,name:"AGENT"}]),st=Le.makeEnum("livekit.Encryption.Type",[{no:0,name:"NONE"},{no:1,name:"GCM"},{no:2,name:"CUSTOM"}]),rt=Le.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:at,repeated:!0}])),ot=Le.makeMessageType("livekit.TrackInfo",(()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"type",kind:"enum",T:Le.getEnumType(Ke)},{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:Le.getEnumType(We)},{no:10,name:"layers",kind:"message",T:at,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:rt,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:Le.getEnumType(st)},{no:17,name:"stream",kind:"scalar",T:9},{no:18,name:"version",kind:"message",T:Et},{no:19,name:"audio_features",kind:"enum",T:Le.getEnumType(Xe),repeated:!0}])),at=Le.makeMessageType("livekit.VideoLayer",(()=>[{no:1,name:"quality",kind:"enum",T:Le.getEnumType(Ge)},{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}])),ct=Le.makeMessageType("livekit.DataPacket",(()=>[{no:1,name:"kind",kind:"enum",T:Le.getEnumType(dt)},{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:ht,oneof:"value"},{no:3,name:"speaker",kind:"message",T:lt,oneof:"value"},{no:6,name:"sip_dtmf",kind:"message",T:pt,oneof:"value"},{no:7,name:"transcription",kind:"message",T:mt,oneof:"value"},{no:8,name:"metrics",kind:"message",T:Fe,oneof:"value"}])),dt=Le.makeEnum("livekit.DataPacket.Kind",[{no:0,name:"RELIABLE"},{no:1,name:"LOSSY"}]),lt=Le.makeMessageType("livekit.ActiveSpeakerUpdate",(()=>[{no:1,name:"speakers",kind:"message",T:ut,repeated:!0}])),ut=Le.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}])),ht=Le.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},{no:8,name:"id",kind:"scalar",T:9,opt:!0},{no:9,name:"start_time",kind:"scalar",T:4,opt:!0},{no:10,name:"end_time",kind:"scalar",T:4,opt:!0}])),pt=Le.makeMessageType("livekit.SipDTMF",(()=>[{no:3,name:"code",kind:"scalar",T:13},{no:4,name:"digit",kind:"scalar",T:9}])),mt=Le.makeMessageType("livekit.Transcription",(()=>[{no:2,name:"transcribed_participant_identity",kind:"scalar",T:9},{no:3,name:"track_id",kind:"scalar",T:9},{no:4,name:"segments",kind:"message",T:gt,repeated:!0}])),gt=Le.makeMessageType("livekit.TranscriptionSegment",(()=>[{no:1,name:"id",kind:"scalar",T:9},{no:2,name:"text",kind:"scalar",T:9},{no:3,name:"start_time",kind:"scalar",T:4},{no:4,name:"end_time",kind:"scalar",T:4},{no:5,name:"final",kind:"scalar",T:8},{no:6,name:"language",kind:"scalar",T:9}])),ft=Le.makeMessageType("livekit.ParticipantTracks",(()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"track_sids",kind:"scalar",T:9,repeated:!0}])),vt=Le.makeMessageType("livekit.ServerInfo",(()=>[{no:1,name:"edition",kind:"enum",T:Le.getEnumType(kt)},{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},{no:7,name:"agent_protocol",kind:"scalar",T:5}])),kt=Le.makeEnum("livekit.ServerInfo.Edition",[{no:0,name:"Standard"},{no:1,name:"Cloud"}]),bt=Le.makeMessageType("livekit.ClientInfo",(()=>[{no:1,name:"sdk",kind:"enum",T:Le.getEnumType(yt)},{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}])),yt=Le.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"}]),Tt=Le.makeMessageType("livekit.ClientConfiguration",(()=>[{no:1,name:"video",kind:"message",T:Ct},{no:2,name:"screen",kind:"message",T:Ct},{no:3,name:"resume_connection",kind:"enum",T:Le.getEnumType(Je)},{no:4,name:"disabled_codecs",kind:"message",T:St},{no:5,name:"force_relay",kind:"enum",T:Le.getEnumType(Je)}])),Ct=Le.makeMessageType("livekit.VideoConfiguration",(()=>[{no:1,name:"hardware_encoder",kind:"enum",T:Le.getEnumType(Je)}])),St=Le.makeMessageType("livekit.DisabledCodecs",(()=>[{no:1,name:"codecs",kind:"message",T:Ze,repeated:!0},{no:2,name:"publish",kind:"message",T:Ze,repeated:!0}])),Et=Le.makeMessageType("livekit.TimedVersion",(()=>[{no:1,name:"unix_micro",kind:"scalar",T:3},{no:2,name:"ticks",kind:"scalar",T:5}])),wt=Le.makeEnum("livekit.SignalTarget",[{no:0,name:"PUBLISHER"},{no:1,name:"SUBSCRIBER"}]),Pt=Le.makeEnum("livekit.StreamState",[{no:0,name:"ACTIVE"},{no:1,name:"PAUSED"}]),Rt=Le.makeEnum("livekit.CandidateProtocol",[{no:0,name:"UDP"},{no:1,name:"TCP"},{no:2,name:"TLS"}]),It=Le.makeMessageType("livekit.SignalRequest",(()=>[{no:1,name:"offer",kind:"message",T:jt,oneof:"message"},{no:2,name:"answer",kind:"message",T:jt,oneof:"message"},{no:3,name:"trickle",kind:"message",T:Mt,oneof:"message"},{no:4,name:"add_track",kind:"message",T:Dt,oneof:"message"},{no:5,name:"mute",kind:"message",T:Nt,oneof:"message"},{no:6,name:"subscription",kind:"message",T:Bt,oneof:"message"},{no:7,name:"track_setting",kind:"message",T:Vt,oneof:"message"},{no:8,name:"leave",kind:"message",T:Wt,oneof:"message"},{no:10,name:"update_layers",kind:"message",T:Ht,oneof:"message"},{no:11,name:"subscription_permission",kind:"message",T:ri,oneof:"message"},{no:12,name:"sync_state",kind:"message",T:ai,oneof:"message"},{no:13,name:"simulate",kind:"message",T:di,oneof:"message"},{no:14,name:"ping",kind:"scalar",T:3,oneof:"message"},{no:15,name:"update_metadata",kind:"message",T:Jt,oneof:"message"},{no:16,name:"ping_req",kind:"message",T:li,oneof:"message"},{no:17,name:"update_audio_track",kind:"message",T:qt,oneof:"message"},{no:18,name:"update_video_track",kind:"message",T:Kt,oneof:"message"}])),Ot=Le.makeMessageType("livekit.SignalResponse",(()=>[{no:1,name:"join",kind:"message",T:_t,oneof:"message"},{no:2,name:"answer",kind:"message",T:jt,oneof:"message"},{no:3,name:"offer",kind:"message",T:jt,oneof:"message"},{no:4,name:"trickle",kind:"message",T:Mt,oneof:"message"},{no:5,name:"update",kind:"message",T:Ft,oneof:"message"},{no:6,name:"track_published",kind:"message",T:Lt,oneof:"message"},{no:8,name:"leave",kind:"message",T:Wt,oneof:"message"},{no:9,name:"mute",kind:"message",T:Nt,oneof:"message"},{no:10,name:"speakers_changed",kind:"message",T:zt,oneof:"message"},{no:11,name:"room_update",kind:"message",T:Yt,oneof:"message"},{no:12,name:"connection_quality",kind:"message",T:$t,oneof:"message"},{no:13,name:"stream_state_update",kind:"message",T:ei,oneof:"message"},{no:14,name:"subscribed_quality_update",kind:"message",T:ni,oneof:"message"},{no:15,name:"subscription_permission_update",kind:"message",T:oi,oneof:"message"},{no:16,name:"refresh_token",kind:"scalar",T:9,oneof:"message"},{no:17,name:"track_unpublished",kind:"message",T:Ut,oneof:"message"},{no:18,name:"pong",kind:"scalar",T:3,oneof:"message"},{no:19,name:"reconnect",kind:"message",T:At,oneof:"message"},{no:20,name:"pong_resp",kind:"message",T:ui,oneof:"message"},{no:21,name:"subscription_response",kind:"message",T:mi,oneof:"message"},{no:22,name:"request_response",kind:"message",T:gi,oneof:"message"},{no:23,name:"track_subscribed",kind:"message",T:vi,oneof:"message"}])),xt=Le.makeMessageType("livekit.SimulcastCodec",(()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"cid",kind:"scalar",T:9}])),Dt=Le.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:Le.getEnumType(Ke)},{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:Le.getEnumType(We)},{no:9,name:"layers",kind:"message",T:at,repeated:!0},{no:10,name:"simulcast_codecs",kind:"message",T:xt,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:Le.getEnumType(st)},{no:15,name:"stream",kind:"scalar",T:9}])),Mt=Le.makeMessageType("livekit.TrickleRequest",(()=>[{no:1,name:"candidateInit",kind:"scalar",T:9},{no:2,name:"target",kind:"enum",T:Le.getEnumType(wt)},{no:3,name:"final",kind:"scalar",T:8}])),Nt=Le.makeMessageType("livekit.MuteTrackRequest",(()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"muted",kind:"scalar",T:8}])),_t=Le.makeMessageType("livekit.JoinResponse",(()=>[{no:1,name:"room",kind:"message",T:$e},{no:2,name:"participant",kind:"message",T:tt},{no:3,name:"other_participants",kind:"message",T:tt,repeated:!0},{no:4,name:"server_version",kind:"scalar",T:9},{no:5,name:"ice_servers",kind:"message",T:Qt,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:Tt},{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:vt},{no:13,name:"sif_trailer",kind:"scalar",T:12},{no:14,name:"enabled_publish_codecs",kind:"message",T:Ze,repeated:!0},{no:15,name:"fast_publish",kind:"scalar",T:8}])),At=Le.makeMessageType("livekit.ReconnectResponse",(()=>[{no:1,name:"ice_servers",kind:"message",T:Qt,repeated:!0},{no:2,name:"client_configuration",kind:"message",T:Tt}])),Lt=Le.makeMessageType("livekit.TrackPublishedResponse",(()=>[{no:1,name:"cid",kind:"scalar",T:9},{no:2,name:"track",kind:"message",T:ot}])),Ut=Le.makeMessageType("livekit.TrackUnpublishedResponse",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9}])),jt=Le.makeMessageType("livekit.SessionDescription",(()=>[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"sdp",kind:"scalar",T:9}])),Ft=Le.makeMessageType("livekit.ParticipantUpdate",(()=>[{no:1,name:"participants",kind:"message",T:tt,repeated:!0}])),Bt=Le.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:ft,repeated:!0}])),Vt=Le.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:Le.getEnumType(Ge)},{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}])),qt=Le.makeMessageType("livekit.UpdateLocalAudioTrack",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"features",kind:"enum",T:Le.getEnumType(Xe),repeated:!0}])),Kt=Le.makeMessageType("livekit.UpdateLocalVideoTrack",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"width",kind:"scalar",T:13},{no:3,name:"height",kind:"scalar",T:13}])),Wt=Le.makeMessageType("livekit.LeaveRequest",(()=>[{no:1,name:"can_reconnect",kind:"scalar",T:8},{no:2,name:"reason",kind:"enum",T:Le.getEnumType(Qe)},{no:3,name:"action",kind:"enum",T:Le.getEnumType(Gt)},{no:4,name:"regions",kind:"message",T:hi}])),Gt=Le.makeEnum("livekit.LeaveRequest.Action",[{no:0,name:"DISCONNECT"},{no:1,name:"RESUME"},{no:2,name:"RECONNECT"}]),Ht=Le.makeMessageType("livekit.UpdateVideoLayers",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"layers",kind:"message",T:at,repeated:!0}])),Jt=Le.makeMessageType("livekit.UpdateParticipantMetadata",(()=>[{no:1,name:"metadata",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",T:9},{no:3,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:4,name:"request_id",kind:"scalar",T:13}])),Qt=Le.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}])),zt=Le.makeMessageType("livekit.SpeakersChanged",(()=>[{no:1,name:"speakers",kind:"message",T:ut,repeated:!0}])),Yt=Le.makeMessageType("livekit.RoomUpdate",(()=>[{no:1,name:"room",kind:"message",T:$e}])),Xt=Le.makeMessageType("livekit.ConnectionQualityInfo",(()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"quality",kind:"enum",T:Le.getEnumType(He)},{no:3,name:"score",kind:"scalar",T:2}])),$t=Le.makeMessageType("livekit.ConnectionQualityUpdate",(()=>[{no:1,name:"updates",kind:"message",T:Xt,repeated:!0}])),Zt=Le.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:Le.getEnumType(Pt)}])),ei=Le.makeMessageType("livekit.StreamStateUpdate",(()=>[{no:1,name:"stream_states",kind:"message",T:Zt,repeated:!0}])),ti=Le.makeMessageType("livekit.SubscribedQuality",(()=>[{no:1,name:"quality",kind:"enum",T:Le.getEnumType(Ge)},{no:2,name:"enabled",kind:"scalar",T:8}])),ii=Le.makeMessageType("livekit.SubscribedCodec",(()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"qualities",kind:"message",T:ti,repeated:!0}])),ni=Le.makeMessageType("livekit.SubscribedQualityUpdate",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribed_qualities",kind:"message",T:ti,repeated:!0},{no:3,name:"subscribed_codecs",kind:"message",T:ii,repeated:!0}])),si=Le.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}])),ri=Le.makeMessageType("livekit.SubscriptionPermission",(()=>[{no:1,name:"all_participants",kind:"scalar",T:8},{no:2,name:"track_permissions",kind:"message",T:si,repeated:!0}])),oi=Le.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}])),ai=Le.makeMessageType("livekit.SyncState",(()=>[{no:1,name:"answer",kind:"message",T:jt},{no:2,name:"subscription",kind:"message",T:Bt},{no:3,name:"publish_tracks",kind:"message",T:Lt,repeated:!0},{no:4,name:"data_channels",kind:"message",T:ci,repeated:!0},{no:5,name:"offer",kind:"message",T:jt},{no:6,name:"track_sids_disabled",kind:"scalar",T:9,repeated:!0}])),ci=Le.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:Le.getEnumType(wt)}])),di=Le.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:Le.getEnumType(Rt),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"},{no:9,name:"leave_request_full_reconnect",kind:"scalar",T:8,oneof:"scenario"}])),li=Le.makeMessageType("livekit.Ping",(()=>[{no:1,name:"timestamp",kind:"scalar",T:3},{no:2,name:"rtt",kind:"scalar",T:3}])),ui=Le.makeMessageType("livekit.Pong",(()=>[{no:1,name:"last_ping_timestamp",kind:"scalar",T:3},{no:2,name:"timestamp",kind:"scalar",T:3}])),hi=Le.makeMessageType("livekit.RegionSettings",(()=>[{no:1,name:"regions",kind:"message",T:pi,repeated:!0}])),pi=Le.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}])),mi=Le.makeMessageType("livekit.SubscriptionResponse",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"err",kind:"enum",T:Le.getEnumType(Ye)}])),gi=Le.makeMessageType("livekit.RequestResponse",(()=>[{no:1,name:"request_id",kind:"scalar",T:13},{no:2,name:"reason",kind:"enum",T:Le.getEnumType(fi)},{no:3,name:"message",kind:"scalar",T:9}])),fi=Le.makeEnum("livekit.RequestResponse.Reason",[{no:0,name:"OK"},{no:1,name:"NOT_FOUND"},{no:2,name:"NOT_ALLOWED"},{no:3,name:"LIMIT_EXCEEDED"}]),vi=Le.makeMessageType("livekit.TrackSubscribed",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9}]));var ki="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function bi(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var yi={exports:{}};!function(e){var t,i;t=ki,i=function(){var e=function(){},t="undefined",i=typeof window!==t&&typeof window.navigator!==t&&/Trident\/|MSIE /.test(window.navigator.userAgent),n=["trace","debug","info","warn","error"],s={},r=null;function o(e,t){var i=e[t];if("function"==typeof i.bind)return i.bind(e);try{return Function.prototype.bind.call(i,e)}catch(t){return function(){return Function.prototype.apply.apply(i,[e,arguments])}}}function a(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function c(){for(var i=this.getLevel(),s=0;s<n.length;s++){var r=n[s];this[r]=s<i?e:this.methodFactory(r,i,this.name)}if(this.log=this.debug,typeof console===t&&i<this.levels.SILENT)return"No console available for logging"}function d(e){return function(){typeof console!==t&&(c.call(this),this[e].apply(this,arguments))}}function l(n,s,r){return function(n){return"debug"===n&&(n="log"),typeof console!==t&&("trace"===n&&i?a:void 0!==console[n]?o(console,n):void 0!==console.log?o(console,"log"):e)}(n)||d.apply(this,arguments)}function u(e,i){var o,a,d,u=this,h="loglevel";function p(){var e;if(typeof window!==t&&h){try{e=window.localStorage[h]}catch(e){}if(typeof e===t)try{var i=window.document.cookie,n=encodeURIComponent(h),s=i.indexOf(n+"=");-1!==s&&(e=/^([^;]+)/.exec(i.slice(s+n.length+1))[1])}catch(e){}return void 0===u.levels[e]&&(e=void 0),e}}function m(e){var t=e;if("string"==typeof t&&void 0!==u.levels[t.toUpperCase()]&&(t=u.levels[t.toUpperCase()]),"number"==typeof t&&t>=0&&t<=u.levels.SILENT)return t;throw new TypeError("log.setLevel() called with invalid level: "+e)}"string"==typeof e?h+=":"+e:"symbol"==typeof e&&(h=void 0),u.name=e,u.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},u.methodFactory=i||l,u.getLevel=function(){return null!=d?d:null!=a?a:o},u.setLevel=function(e,i){return d=m(e),!1!==i&&function(e){var i=(n[e]||"silent").toUpperCase();if(typeof window!==t&&h){try{return void(window.localStorage[h]=i)}catch(e){}try{window.document.cookie=encodeURIComponent(h)+"="+i+";"}catch(e){}}}(d),c.call(u)},u.setDefaultLevel=function(e){a=m(e),p()||u.setLevel(e,!1)},u.resetLevel=function(){d=null,function(){if(typeof window!==t&&h){try{window.localStorage.removeItem(h)}catch(e){}try{window.document.cookie=encodeURIComponent(h)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch(e){}}}(),c.call(u)},u.enableAll=function(e){u.setLevel(u.levels.TRACE,e)},u.disableAll=function(e){u.setLevel(u.levels.SILENT,e)},u.rebuild=function(){if(r!==u&&(o=m(r.getLevel())),c.call(u),r===u)for(var e in s)s[e].rebuild()},o=m(r?r.getLevel():"WARN");var g=p();null!=g&&(d=m(g)),c.call(u)}(r=new u).getLogger=function(e){if("symbol"!=typeof e&&"string"!=typeof e||""===e)throw new TypeError("You must supply a name when creating a logger.");var t=s[e];return t||(t=s[e]=new u(e,r.methodFactory)),t};var h=typeof window!==t?window.log:void 0;return r.noConflict=function(){return typeof window!==t&&window.log===r&&(window.log=h),r},r.getLoggers=function(){return s},r.default=r,r},e.exports?e.exports=i():t.log=i()}(yi);var Ti,Ci,Si=yi.exports;e.LogLevel=void 0,(Ti=e.LogLevel||(e.LogLevel={}))[Ti.trace=0]="trace",Ti[Ti.debug=1]="debug",Ti[Ti.info=2]="info",Ti[Ti.warn=3]="warn",Ti[Ti.error=4]="error",Ti[Ti.silent=5]="silent",e.LoggerNames=void 0,(Ci=e.LoggerNames||(e.LoggerNames={})).Default="livekit",Ci.Room="livekit-room",Ci.Participant="livekit-participant",Ci.Track="livekit-track",Ci.Publication="livekit-track-publication",Ci.Engine="livekit-engine",Ci.Signal="livekit-signal",Ci.PCManager="livekit-pc-manager",Ci.PCTransport="livekit-pc-transport",Ci.E2EE="lk-e2ee";let Ei=Si.getLogger("livekit");const wi=Object.values(e.LoggerNames).map((e=>Si.getLogger(e)));function Pi(e){const t=Si.getLogger(e);return t.setDefaultLevel(Ei.getLevel()),t}Ei.setDefaultLevel(e.LogLevel.info);const Ri=Si.getLogger("lk-e2ee"),Ii=7e3,Oi=[0,300,1200,2700,4800,Ii,Ii,Ii,Ii,Ii];class xi{constructor(e){this._retryDelays=void 0!==e?[...e]:Oi}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 Di(e,t,i,n){return new(i||(i=Promise))((function(s,r){function o(e){try{c(n.next(e))}catch(e){r(e)}}function a(e){try{c(n.throw(e))}catch(e){r(e)}}function c(e){var t;e.done?s(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}c((n=n.apply(e,t||[])).next())}))}function Mi(e){var t="function"==typeof Symbol&&Symbol.iterator,i=t&&e[t],n=0;if(i)return i.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function Ni(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t,i=e[Symbol.asyncIterator];return i?i.call(e):(e=Mi(e),t={},n("next"),n("throw"),n("return"),t[Symbol.asyncIterator]=function(){return this},t);function n(i){t[i]=e[i]&&function(t){return new Promise((function(n,s){(function(e,t,i,n){Promise.resolve(n).then((function(t){e({value:t,done:i})}),t)})(n,s,(t=e[i](t)).done,t.value)}))}}}"function"==typeof SuppressedError&&SuppressedError;var _i,Ai={exports:{}},Li="object"==typeof Reflect?Reflect:null,Ui=Li&&"function"==typeof Li.apply?Li.apply:function(e,t,i){return Function.prototype.apply.call(e,t,i)};_i=Li&&"function"==typeof Li.ownKeys?Li.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var ji=Number.isNaN||function(e){return e!=e};function Fi(){Fi.init.call(this)}Ai.exports=Fi,Ai.exports.once=function(e,t){return new Promise((function(i,n){function s(i){e.removeListener(t,r),n(i)}function r(){"function"==typeof e.removeListener&&e.removeListener("error",s),i([].slice.call(arguments))}zi(e,t,r,{once:!0}),"error"!==t&&function(e,t,i){"function"==typeof e.on&&zi(e,"error",t,i)}(e,s,{once:!0})}))},Fi.EventEmitter=Fi,Fi.prototype._events=void 0,Fi.prototype._eventsCount=0,Fi.prototype._maxListeners=void 0;var Bi=10;function Vi(e){if("function"!=typeof e)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function qi(e){return void 0===e._maxListeners?Fi.defaultMaxListeners:e._maxListeners}function Ki(e,t,i,n){var s,r,o,a;if(Vi(i),void 0===(r=e._events)?(r=e._events=Object.create(null),e._eventsCount=0):(void 0!==r.newListener&&(e.emit("newListener",t,i.listener?i.listener:i),r=e._events),o=r[t]),void 0===o)o=r[t]=i,++e._eventsCount;else if("function"==typeof o?o=r[t]=n?[i,o]:[o,i]:n?o.unshift(i):o.push(i),(s=qi(e))>0&&o.length>s&&!o.warned){o.warned=!0;var c=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");c.name="MaxListenersExceededWarning",c.emitter=e,c.type=t,c.count=o.length,a=c,console&&console.warn&&console.warn(a)}return e}function Wi(){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 Gi(e,t,i){var n={fired:!1,wrapFn:void 0,target:e,type:t,listener:i},s=Wi.bind(n);return s.listener=i,n.wrapFn=s,s}function Hi(e,t,i){var n=e._events;if(void 0===n)return[];var s=n[t];return void 0===s?[]:"function"==typeof s?i?[s.listener||s]:[s]:i?function(e){for(var t=new Array(e.length),i=0;i<t.length;++i)t[i]=e[i].listener||e[i];return t}(s):Qi(s,s.length)}function Ji(e){var t=this._events;if(void 0!==t){var i=t[e];if("function"==typeof i)return 1;if(void 0!==i)return i.length}return 0}function Qi(e,t){for(var i=new Array(t),n=0;n<t;++n)i[n]=e[n];return i}function zi(e,t,i,n){if("function"==typeof e.on)n.once?e.once(t,i):e.on(t,i);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(r){n.once&&e.removeEventListener(t,s),i(r)}))}}Object.defineProperty(Fi,"defaultMaxListeners",{enumerable:!0,get:function(){return Bi},set:function(e){if("number"!=typeof e||e<0||ji(e))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+e+".");Bi=e}}),Fi.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},Fi.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||ji(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},Fi.prototype.getMaxListeners=function(){return qi(this)},Fi.prototype.emit=function(e){for(var t=[],i=1;i<arguments.length;i++)t.push(arguments[i]);var n="error"===e,s=this._events;if(void 0!==s)n=n&&void 0===s.error;else if(!n)return!1;if(n){var r;if(t.length>0&&(r=t[0]),r instanceof Error)throw r;var o=new Error("Unhandled error."+(r?" ("+r.message+")":""));throw o.context=r,o}var a=s[e];if(void 0===a)return!1;if("function"==typeof a)Ui(a,this,t);else{var c=a.length,d=Qi(a,c);for(i=0;i<c;++i)Ui(d[i],this,t)}return!0},Fi.prototype.addListener=function(e,t){return Ki(this,e,t,!1)},Fi.prototype.on=Fi.prototype.addListener,Fi.prototype.prependListener=function(e,t){return Ki(this,e,t,!0)},Fi.prototype.once=function(e,t){return Vi(t),this.on(e,Gi(this,e,t)),this},Fi.prototype.prependOnceListener=function(e,t){return Vi(t),this.prependListener(e,Gi(this,e,t)),this},Fi.prototype.removeListener=function(e,t){var i,n,s,r,o;if(Vi(t),void 0===(n=this._events))return this;if(void 0===(i=n[e]))return this;if(i===t||i.listener===t)0==--this._eventsCount?this._events=Object.create(null):(delete n[e],n.removeListener&&this.emit("removeListener",e,i.listener||t));else if("function"!=typeof i){for(s=-1,r=i.length-1;r>=0;r--)if(i[r]===t||i[r].listener===t){o=i[r].listener,s=r;break}if(s<0)return this;0===s?i.shift():function(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}(i,s),1===i.length&&(n[e]=i[0]),void 0!==n.removeListener&&this.emit("removeListener",e,o||t)}return this},Fi.prototype.off=Fi.prototype.removeListener,Fi.prototype.removeAllListeners=function(e){var t,i,n;if(void 0===(i=this._events))return this;if(void 0===i.removeListener)return 0===arguments.length?(this._events=Object.create(null),this._eventsCount=0):void 0!==i[e]&&(0==--this._eventsCount?this._events=Object.create(null):delete i[e]),this;if(0===arguments.length){var s,r=Object.keys(i);for(n=0;n<r.length;++n)"removeListener"!==(s=r[n])&&this.removeAllListeners(s);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if("function"==typeof(t=i[e]))this.removeListener(e,t);else if(void 0!==t)for(n=t.length-1;n>=0;n--)this.removeListener(e,t[n]);return this},Fi.prototype.listeners=function(e){return Hi(this,e,!0)},Fi.prototype.rawListeners=function(e){return Hi(this,e,!1)},Fi.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):Ji.call(e,t)},Fi.prototype.listenerCount=Ji,Fi.prototype.eventNames=function(){return this._eventsCount>0?_i(this._events):[]};var Yi=Ai.exports;let Xi=!0,$i=!0;function Zi(e,t,i){const n=e.match(t);return n&&n.length>=i&&parseInt(n[i],10)}function en(e,t,i){if(!e.RTCPeerConnection)return;const n=e.RTCPeerConnection.prototype,s=n.addEventListener;n.addEventListener=function(e,n){if(e!==t)return s.apply(this,arguments);const r=e=>{const t=i(e);t&&(n.handleEvent?n.handleEvent(t):n(t))};return this._eventMap=this._eventMap||{},this._eventMap[t]||(this._eventMap[t]=new Map),this._eventMap[t].set(n,r),s.apply(this,[e,r])};const r=n.removeEventListener;n.removeEventListener=function(e,i){if(e!==t||!this._eventMap||!this._eventMap[t])return r.apply(this,arguments);if(!this._eventMap[t].has(i))return r.apply(this,arguments);const n=this._eventMap[t].get(i);return this._eventMap[t].delete(i),0===this._eventMap[t].size&&delete this._eventMap[t],0===Object.keys(this._eventMap).length&&delete this._eventMap,r.apply(this,[e,n])},Object.defineProperty(n,"on"+t,{get(){return this["_on"+t]},set(e){this["_on"+t]&&(this.removeEventListener(t,this["_on"+t]),delete this["_on"+t]),e&&this.addEventListener(t,this["_on"+t]=e)},enumerable:!0,configurable:!0})}function tn(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(Xi=e,e?"adapter.js logging disabled":"adapter.js logging enabled")}function nn(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):($i=!e,"adapter.js deprecation warnings "+(e?"disabled":"enabled"))}function sn(){if("object"==typeof window){if(Xi)return;"undefined"!=typeof console&&"function"==typeof console.log&&console.log.apply(console,arguments)}}function rn(e,t){$i&&console.warn(e+" is deprecated, please use "+t+" instead.")}function on(e){return"[object Object]"===Object.prototype.toString.call(e)}function an(e){return on(e)?Object.keys(e).reduce((function(t,i){const n=on(e[i]),s=n?an(e[i]):e[i],r=n&&!Object.keys(s).length;return void 0===s||r?t:Object.assign(t,{[i]:s})}),{}):e}function cn(e,t,i){t&&!i.has(t.id)&&(i.set(t.id,t),Object.keys(t).forEach((n=>{n.endsWith("Id")?cn(e,e.get(t[n]),i):n.endsWith("Ids")&&t[n].forEach((t=>{cn(e,e.get(t),i)}))})))}function dn(e,t,i){const n=i?"outbound-rtp":"inbound-rtp",s=new Map;if(null===t)return s;const r=[];return e.forEach((e=>{"track"===e.type&&e.trackIdentifier===t.id&&r.push(e)})),r.forEach((t=>{e.forEach((i=>{i.type===n&&i.trackId===t.id&&cn(e,i,s)}))})),s}const ln=sn;function un(e,t){const i=e&&e.navigator;if(!i.mediaDevices)return;const n=function(e){if("object"!=typeof e||e.mandatory||e.optional)return e;const t={};return Object.keys(e).forEach((i=>{if("require"===i||"advanced"===i||"mediaSource"===i)return;const n="object"==typeof e[i]?e[i]:{ideal:e[i]};void 0!==n.exact&&"number"==typeof n.exact&&(n.min=n.max=n.exact);const s=function(e,t){return e?e+t.charAt(0).toUpperCase()+t.slice(1):"deviceId"===t?"sourceId":t};if(void 0!==n.ideal){t.optional=t.optional||[];let e={};"number"==typeof n.ideal?(e[s("min",i)]=n.ideal,t.optional.push(e),e={},e[s("max",i)]=n.ideal,t.optional.push(e)):(e[s("",i)]=n.ideal,t.optional.push(e))}void 0!==n.exact&&"number"!=typeof n.exact?(t.mandatory=t.mandatory||{},t.mandatory[s("",i)]=n.exact):["min","max"].forEach((e=>{void 0!==n[e]&&(t.mandatory=t.mandatory||{},t.mandatory[s(e,i)]=n[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,i){t in e&&!(i in e)&&(e[i]=e[t],delete e[t])};t((e=JSON.parse(JSON.stringify(e))).audio,"autoGainControl","googAutoGainControl"),t(e.audio,"noiseSuppression","googNoiseSuppression"),e.audio=n(e.audio)}if(e&&"object"==typeof e.video){let r=e.video.facingMode;r=r&&("object"==typeof r?r:{ideal:r});const o=t.version<66;if(r&&("user"===r.exact||"environment"===r.exact||"user"===r.ideal||"environment"===r.ideal)&&(!i.mediaDevices.getSupportedConstraints||!i.mediaDevices.getSupportedConstraints().facingMode||o)){let t;if(delete e.video.facingMode,"environment"===r.exact||"environment"===r.ideal?t=["back","rear"]:"user"!==r.exact&&"user"!==r.ideal||(t=["front"]),t)return i.mediaDevices.enumerateDevices().then((i=>{let o=(i=i.filter((e=>"videoinput"===e.kind))).find((e=>t.some((t=>e.label.toLowerCase().includes(t)))));return!o&&i.length&&t.includes("back")&&(o=i[i.length-1]),o&&(e.video.deviceId=r.exact?{exact:o.deviceId}:{ideal:o.deviceId}),e.video=n(e.video),ln("chrome: "+JSON.stringify(e)),s(e)}))}e.video=n(e.video)}return ln("chrome: "+JSON.stringify(e)),s(e)},r=function(e){return t.version>=64?e:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[e.name]||e.name,message:e.message,constraint:e.constraint||e.constraintName,toString(){return this.name+(this.message&&": ")+this.message}}};if(i.getUserMedia=function(e,t,n){s(e,(e=>{i.webkitGetUserMedia(e,t,(e=>{n&&n(r(e))}))}))}.bind(i),i.mediaDevices.getUserMedia){const e=i.mediaDevices.getUserMedia.bind(i.mediaDevices);i.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(r(e))))))}}}function hn(e){e.MediaStream=e.MediaStream||e.webkitMediaStream}function pn(e){if("object"==typeof e&&e.RTCPeerConnection&&!("ontrack"in e.RTCPeerConnection.prototype)){Object.defineProperty(e.RTCPeerConnection.prototype,"ontrack",{get(){return this._ontrack},set(e){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=e)},enumerable:!0,configurable:!0});const t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=t=>{t.stream.addEventListener("addtrack",(i=>{let n;n=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find((e=>e.track&&e.track.id===i.track.id)):{track:i.track};const s=new Event("track");s.track=i.track,s.receiver=n,s.transceiver={receiver:n},s.streams=[t.stream],this.dispatchEvent(s)})),t.stream.getTracks().forEach((i=>{let n;n=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find((e=>e.track&&e.track.id===i.id)):{track:i};const s=new Event("track");s.track=i,s.receiver=n,s.transceiver={receiver:n},s.streams=[t.stream],this.dispatchEvent(s)}))},this.addEventListener("addstream",this._ontrackpoly)),t.apply(this,arguments)}}else en(e,"track",(e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e)))}function mn(e){if("object"==typeof e&&e.RTCPeerConnection&&!("getSenders"in e.RTCPeerConnection.prototype)&&"createDTMFSender"in e.RTCPeerConnection.prototype){const t=function(e,t){return{track:t,get dtmf(){return void 0===this._dtmf&&("audio"===t.kind?this._dtmf=e.createDTMFSender(t):this._dtmf=null),this._dtmf},_pc:e}};if(!e.RTCPeerConnection.prototype.getSenders){e.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};const i=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,n){let s=i.apply(this,arguments);return s||(s=t(this,e),this._senders.push(s)),s};const n=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){n.apply(this,arguments);const t=this._senders.indexOf(e);-1!==t&&this._senders.splice(t,1)}}const i=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._senders=this._senders||[],i.apply(this,[e]),e.getTracks().forEach((e=>{this._senders.push(t(this,e))}))};const n=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){this._senders=this._senders||[],n.apply(this,[e]),e.getTracks().forEach((e=>{const t=this._senders.find((t=>t.track===e));t&&this._senders.splice(this._senders.indexOf(t),1)}))}}else if("object"==typeof e&&e.RTCPeerConnection&&"getSenders"in e.RTCPeerConnection.prototype&&"createDTMFSender"in e.RTCPeerConnection.prototype&&e.RTCRtpSender&&!("dtmf"in e.RTCRtpSender.prototype)){const t=e.RTCPeerConnection.prototype.getSenders;e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e},Object.defineProperty(e.RTCRtpSender.prototype,"dtmf",{get(){return void 0===this._dtmf&&("audio"===this.track.kind?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}}function gn(e){if(!("object"==typeof e&&e.RTCPeerConnection&&e.RTCRtpSender&&e.RTCRtpReceiver))return;if(!("getStats"in e.RTCRtpSender.prototype)){const t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e});const i=e.RTCPeerConnection.prototype.addTrack;i&&(e.RTCPeerConnection.prototype.addTrack=function(){const e=i.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){const e=this;return this._pc.getStats().then((t=>dn(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}),en(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){const e=this;return this._pc.getStats().then((t=>dn(t,e.track,!1)))}}if(!("getStats"in e.RTCRtpSender.prototype)||!("getStats"in e.RTCRtpReceiver.prototype))return;const t=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof e.MediaStreamTrack){const e=arguments[0];let t,i,n;return this.getSenders().forEach((i=>{i.track===e&&(t?n=!0:t=i)})),this.getReceivers().forEach((t=>(t.track===e&&(i?n=!0:i=t),t.track===e))),n||t&&i?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):t?t.getStats():i?i.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return t.apply(this,arguments)}}function fn(e){e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map((e=>this._shimmedLocalStreams[e][0]))};const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,i){if(!i)return t.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};const n=t.apply(this,arguments);return this._shimmedLocalStreams[i.id]?-1===this._shimmedLocalStreams[i.id].indexOf(n)&&this._shimmedLocalStreams[i.id].push(n):this._shimmedLocalStreams[i.id]=[i,n],n};const i=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._shimmedLocalStreams=this._shimmedLocalStreams||{},e.getTracks().forEach((e=>{if(this.getSenders().find((t=>t.track===e)))throw new DOMException("Track already exists.","InvalidAccessError")}));const t=this.getSenders();i.apply(this,arguments);const n=this.getSenders().filter((e=>-1===t.indexOf(e)));this._shimmedLocalStreams[e.id]=[e].concat(n)};const n=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[e.id],n.apply(this,arguments)};const s=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},e&&Object.keys(this._shimmedLocalStreams).forEach((t=>{const i=this._shimmedLocalStreams[t].indexOf(e);-1!==i&&this._shimmedLocalStreams[t].splice(i,1),1===this._shimmedLocalStreams[t].length&&delete this._shimmedLocalStreams[t]})),s.apply(this,arguments)}}function vn(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return fn(e);const i=e.RTCPeerConnection.prototype.getLocalStreams;e.RTCPeerConnection.prototype.getLocalStreams=function(){const e=i.apply(this);return this._reverseStreams=this._reverseStreams||{},e.map((e=>this._reverseStreams[e.id]))};const n=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(t){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},t.getTracks().forEach((e=>{if(this.getSenders().find((t=>t.track===e)))throw new DOMException("Track already exists.","InvalidAccessError")})),!this._reverseStreams[t.id]){const i=new e.MediaStream(t.getTracks());this._streams[t.id]=i,this._reverseStreams[i.id]=t,t=i}n.apply(this,[t])};const s=e.RTCPeerConnection.prototype.removeStream;function r(e,t){let i=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((t=>{const n=e._reverseStreams[t],s=e._streams[n.id];i=i.replace(new RegExp(s.id,"g"),n.id)})),new RTCSessionDescription({type:t.type,sdp:i})}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,i){if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");const n=[].slice.call(arguments,1);if(1!==n.length||!n[0].getTracks().find((e=>e===t)))throw new DOMException("The adapter.js addTrack polyfill only supports a single stream which is associated with the specified track.","NotSupportedError");if(this.getSenders().find((e=>e.track===t)))throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};const s=this._streams[i.id];if(s)s.addTrack(t),Promise.resolve().then((()=>{this.dispatchEvent(new Event("negotiationneeded"))}));else{const n=new e.MediaStream([t]);this._streams[i.id]=n,this._reverseStreams[n.id]=i,this.addStream(n)}return this.getSenders().find((e=>e.track===t))},["createOffer","createAnswer"].forEach((function(t){const i=e.RTCPeerConnection.prototype[t],n={[t](){const e=arguments;return arguments.length&&"function"==typeof arguments[0]?i.apply(this,[t=>{const i=r(this,t);e[0].apply(null,[i])},t=>{e[1]&&e[1].apply(null,t)},arguments[2]]):i.apply(this,arguments).then((e=>r(this,e)))}};e.RTCPeerConnection.prototype[t]=n[t]}));const o=e.RTCPeerConnection.prototype.setLocalDescription;e.RTCPeerConnection.prototype.setLocalDescription=function(){return arguments.length&&arguments[0].type?(arguments[0]=function(e,t){let i=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((t=>{const n=e._reverseStreams[t],s=e._streams[n.id];i=i.replace(new RegExp(n.id,"g"),s.id)})),new RTCSessionDescription({type:t.type,sdp:i})}(this,arguments[0]),o.apply(this,arguments)):o.apply(this,arguments)};const a=Object.getOwnPropertyDescriptor(e.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(e.RTCPeerConnection.prototype,"localDescription",{get(){const e=a.get.apply(this);return""===e.type?e:r(this,e)}}),e.RTCPeerConnection.prototype.removeTrack=function(e){if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!e._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(!(e._pc===this))throw new DOMException("Sender was not created by this connection.","InvalidAccessError");let t;this._streams=this._streams||{},Object.keys(this._streams).forEach((i=>{this._streams[i].getTracks().find((t=>e.track===t))&&(t=this._streams[i])})),t&&(1===t.getTracks().length?this.removeStream(this._reverseStreams[t.id]):t.removeTrack(e.track),this.dispatchEvent(new Event("negotiationneeded")))}}function kn(e,t){!e.RTCPeerConnection&&e.webkitRTCPeerConnection&&(e.RTCPeerConnection=e.webkitRTCPeerConnection),e.RTCPeerConnection&&t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach((function(t){const i=e.RTCPeerConnection.prototype[t],n={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),i.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=n[t]}))}function bn(e,t){en(e,"negotiationneeded",(e=>{const i=e.target;if(!(t.version<72||i.getConfiguration&&"plan-b"===i.getConfiguration().sdpSemantics)||"stable"===i.signalingState)return e}))}var yn=Object.freeze({__proto__:null,fixNegotiationNeeded:bn,shimAddTrackRemoveTrack:vn,shimAddTrackRemoveTrackWithNative:fn,shimGetSendersWithDtmf:mn,shimGetUserMedia:un,shimMediaStream:hn,shimOnTrack:pn,shimPeerConnection:kn,shimSenderReceiverGetStats:gn});function Tn(e,t){const i=e&&e.navigator,n=e&&e.MediaStreamTrack;if(i.getUserMedia=function(e,t,n){rn("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),i.mediaDevices.getUserMedia(e).then(t,n)},!(t.version>55&&"autoGainControl"in i.mediaDevices.getSupportedConstraints())){const e=function(e,t,i){t in e&&!(i in e)&&(e[i]=e[t],delete e[t])},t=i.mediaDevices.getUserMedia.bind(i.mediaDevices);if(i.mediaDevices.getUserMedia=function(i){return"object"==typeof i&&"object"==typeof i.audio&&(i=JSON.parse(JSON.stringify(i)),e(i.audio,"autoGainControl","mozAutoGainControl"),e(i.audio,"noiseSuppression","mozNoiseSuppression")),t(i)},n&&n.prototype.getSettings){const t=n.prototype.getSettings;n.prototype.getSettings=function(){const i=t.apply(this,arguments);return e(i,"mozAutoGainControl","autoGainControl"),e(i,"mozNoiseSuppression","noiseSuppression"),i}}if(n&&n.prototype.applyConstraints){const t=n.prototype.applyConstraints;n.prototype.applyConstraints=function(i){return"audio"===this.kind&&"object"==typeof i&&(i=JSON.parse(JSON.stringify(i)),e(i,"autoGainControl","mozAutoGainControl"),e(i,"noiseSuppression","mozNoiseSuppression")),t.apply(this,[i])}}}}function Cn(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 Sn(e,t){if("object"!=typeof e||!e.RTCPeerConnection&&!e.mozRTCPeerConnection)return;!e.RTCPeerConnection&&e.mozRTCPeerConnection&&(e.RTCPeerConnection=e.mozRTCPeerConnection),t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach((function(t){const i=e.RTCPeerConnection.prototype[t],n={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),i.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=n[t]}));const i={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},n=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){const[e,s,r]=arguments;return n.apply(this,[e||null]).then((e=>{if(t.version<53&&!s)try{e.forEach((e=>{e.type=i[e.type]||e.type}))}catch(t){if("TypeError"!==t.name)throw t;e.forEach(((t,n)=>{e.set(n,Object.assign({},t,{type:i[t.type]||t.type}))}))}return e})).then(s,r)}}function En(e){if("object"!=typeof e||!e.RTCPeerConnection||!e.RTCRtpSender)return;if(e.RTCRtpSender&&"getStats"in e.RTCRtpSender.prototype)return;const t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e});const i=e.RTCPeerConnection.prototype.addTrack;i&&(e.RTCPeerConnection.prototype.addTrack=function(){const e=i.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function wn(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}),en(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function Pn(e){e.RTCPeerConnection&&!("removeStream"in e.RTCPeerConnection.prototype)&&(e.RTCPeerConnection.prototype.removeStream=function(e){rn("removeStream","removeTrack"),this.getSenders().forEach((t=>{t.track&&e.getTracks().includes(t.track)&&this.removeTrack(t)}))})}function Rn(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)}function In(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.addTransceiver;t&&(e.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let e=arguments[1]&&arguments[1].sendEncodings;void 0===e&&(e=[]),e=[...e];const i=e.length>0;i&&e.forEach((e=>{if("rid"in e){if(!/^[a-z0-9]{0,16}$/i.test(e.rid))throw new TypeError("Invalid RID value provided.")}if("scaleResolutionDownBy"in e&&!(parseFloat(e.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in e&&!(parseFloat(e.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")}));const n=t.apply(this,arguments);if(i){const{sender:t}=n,i=t.getParameters();(!("encodings"in i)||1===i.encodings.length&&0===Object.keys(i.encodings[0]).length)&&(i.encodings=e,t.sendEncodings=e,this.setParametersPromises.push(t.setParameters(i).then((()=>{delete t.sendEncodings})).catch((()=>{delete t.sendEncodings}))))}return n})}function On(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 xn(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 Dn(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 Mn=Object.freeze({__proto__:null,shimAddTransceiver:In,shimCreateAnswer:Dn,shimCreateOffer:xn,shimGetDisplayMedia:function(e,t){e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||e.navigator.mediaDevices&&(e.navigator.mediaDevices.getDisplayMedia=function(i){if(!i||!i.video){const e=new DOMException("getDisplayMedia without video constraints is undefined");return e.name="NotFoundError",e.code=8,Promise.reject(e)}return!0===i.video?i.video={mediaSource:t}:i.video.mediaSource=t,e.navigator.mediaDevices.getUserMedia(i)})},shimGetParameters:On,shimGetUserMedia:Tn,shimOnTrack:Cn,shimPeerConnection:Sn,shimRTCDataChannel:Rn,shimReceiverGetStats:wn,shimRemoveStream:Pn,shimSenderGetStats:En});function Nn(e){if("object"==typeof e&&e.RTCPeerConnection){if("getLocalStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in e.RTCPeerConnection.prototype)){const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addStream=function(e){this._localStreams||(this._localStreams=[]),this._localStreams.includes(e)||this._localStreams.push(e),e.getAudioTracks().forEach((i=>t.call(this,i,e))),e.getVideoTracks().forEach((i=>t.call(this,i,e)))},e.RTCPeerConnection.prototype.addTrack=function(e){for(var i=arguments.length,n=new Array(i>1?i-1:0),s=1;s<i;s++)n[s-1]=arguments[s];return n&&n.forEach((e=>{this._localStreams?this._localStreams.includes(e)||this._localStreams.push(e):this._localStreams=[e]})),t.apply(this,arguments)}}"removeStream"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.removeStream=function(e){this._localStreams||(this._localStreams=[]);const t=this._localStreams.indexOf(e);if(-1===t)return;this._localStreams.splice(t,1);const i=e.getTracks();this.getSenders().forEach((e=>{i.includes(e.track)&&this.removeTrack(e)}))})}}function _n(e){if("object"==typeof e&&e.RTCPeerConnection&&("getRemoteStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!("onaddstream"in e.RTCPeerConnection.prototype))){Object.defineProperty(e.RTCPeerConnection.prototype,"onaddstream",{get(){return this._onaddstream},set(e){this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=e),this.addEventListener("track",this._onaddstreampoly=e=>{e.streams.forEach((e=>{if(this._remoteStreams||(this._remoteStreams=[]),this._remoteStreams.includes(e))return;this._remoteStreams.push(e);const t=new Event("addstream");t.stream=e,this.dispatchEvent(t)}))})}});const t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){const e=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(t){t.streams.forEach((t=>{if(e._remoteStreams||(e._remoteStreams=[]),e._remoteStreams.indexOf(t)>=0)return;e._remoteStreams.push(t);const i=new Event("addstream");i.stream=t,e.dispatchEvent(i)}))}),t.apply(e,arguments)}}}function An(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype,i=t.createOffer,n=t.createAnswer,s=t.setLocalDescription,r=t.setRemoteDescription,o=t.addIceCandidate;t.createOffer=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},t.createAnswer=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};let a=function(e,t,i){const n=s.apply(this,[e]);return i?(n.then(t,i),Promise.resolve()):n};t.setLocalDescription=a,a=function(e,t,i){const n=r.apply(this,[e]);return i?(n.then(t,i),Promise.resolve()):n},t.setRemoteDescription=a,a=function(e,t,i){const n=o.apply(this,[e]);return i?(n.then(t,i),Promise.resolve()):n},t.addIceCandidate=a}function Ln(e){const t=e&&e.navigator;if(t.mediaDevices&&t.mediaDevices.getUserMedia){const e=t.mediaDevices,i=e.getUserMedia.bind(e);t.mediaDevices.getUserMedia=e=>i(Un(e))}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=function(e,i,n){t.mediaDevices.getUserMedia(e).then(i,n)}.bind(t))}function Un(e){return e&&void 0!==e.video?Object.assign({},e,{video:an(e.video)}):e}function jn(e){if(!e.RTCPeerConnection)return;const t=e.RTCPeerConnection;e.RTCPeerConnection=function(e,i){if(e&&e.iceServers){const t=[];for(let i=0;i<e.iceServers.length;i++){let n=e.iceServers[i];void 0===n.urls&&n.url?(rn("RTCIceServer.url","RTCIceServer.urls"),n=JSON.parse(JSON.stringify(n)),n.urls=n.url,delete n.url,t.push(n)):t.push(e.iceServers[i])}e.iceServers=t}return new t(e,i)},e.RTCPeerConnection.prototype=t.prototype,"generateCertificate"in t&&Object.defineProperty(e.RTCPeerConnection,"generateCertificate",{get:()=>t.generateCertificate})}function Fn(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 Bn(e){const t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(e){if(e){void 0!==e.offerToReceiveAudio&&(e.offerToReceiveAudio=!!e.offerToReceiveAudio);const t=this.getTransceivers().find((e=>"audio"===e.receiver.track.kind));!1===e.offerToReceiveAudio&&t?"sendrecv"===t.direction?t.setDirection?t.setDirection("sendonly"):t.direction="sendonly":"recvonly"===t.direction&&(t.setDirection?t.setDirection("inactive"):t.direction="inactive"):!0!==e.offerToReceiveAudio||t||this.addTransceiver("audio",{direction:"recvonly"}),void 0!==e.offerToReceiveVideo&&(e.offerToReceiveVideo=!!e.offerToReceiveVideo);const i=this.getTransceivers().find((e=>"video"===e.receiver.track.kind));!1===e.offerToReceiveVideo&&i?"sendrecv"===i.direction?i.setDirection?i.setDirection("sendonly"):i.direction="sendonly":"recvonly"===i.direction&&(i.setDirection?i.setDirection("inactive"):i.direction="inactive"):!0!==e.offerToReceiveVideo||i||this.addTransceiver("video",{direction:"recvonly"})}return t.apply(this,arguments)}}function Vn(e){"object"!=typeof e||e.AudioContext||(e.AudioContext=e.webkitAudioContext)}var qn=Object.freeze({__proto__:null,shimAudioContext:Vn,shimCallbacksAPI:An,shimConstraints:Un,shimCreateOfferLegacy:Bn,shimGetUserMedia:Ln,shimLocalStreamsAPI:Nn,shimRTCIceServerUrls:jn,shimRemoteStreamsAPI:_n,shimTrackEventTransceiver:Fn}),Kn={exports:{}};!function(e){const t={generateIdentifier:function(){return Math.random().toString(36).substring(2,12)}};t.localCName=t.generateIdentifier(),t.splitLines=function(e){return e.trim().split("\n").map((e=>e.trim()))},t.splitSections=function(e){return e.split("\nm=").map(((e,t)=>(t>0?"m="+e:e).trim()+"\r\n"))},t.getDescription=function(e){const i=t.splitSections(e);return i&&i[0]},t.getMediaSections=function(e){const i=t.splitSections(e);return i.shift(),i},t.matchPrefix=function(e,i){return t.splitLines(e).filter((e=>0===e.indexOf(i)))},t.parseCandidate=function(e){let t;t=0===e.indexOf("a=candidate:")?e.substring(12).split(" "):e.substring(10).split(" ");const i={foundation:t[0],component:{1:"rtp",2:"rtcp"}[t[1]]||t[1],protocol:t[2].toLowerCase(),priority:parseInt(t[3],10),ip:t[4],address:t[4],port:parseInt(t[5],10),type:t[7]};for(let e=8;e<t.length;e+=2)switch(t[e]){case"raddr":i.relatedAddress=t[e+1];break;case"rport":i.relatedPort=parseInt(t[e+1],10);break;case"tcptype":i.tcpType=t[e+1];break;case"ufrag":i.ufrag=t[e+1],i.usernameFragment=t[e+1];break;default:void 0===i[t[e]]&&(i[t[e]]=t[e+1])}return i},t.writeCandidate=function(e){const t=[];t.push(e.foundation);const i=e.component;"rtp"===i?t.push(1):"rtcp"===i?t.push(2):t.push(i),t.push(e.protocol.toUpperCase()),t.push(e.priority),t.push(e.address||e.ip),t.push(e.port);const n=e.type;return t.push("typ"),t.push(n),"host"!==n&&e.relatedAddress&&e.relatedPort&&(t.push("raddr"),t.push(e.relatedAddress),t.push("rport"),t.push(e.relatedPort)),e.tcpType&&"tcp"===e.protocol.toLowerCase()&&(t.push("tcptype"),t.push(e.tcpType)),(e.usernameFragment||e.ufrag)&&(t.push("ufrag"),t.push(e.usernameFragment||e.ufrag)),"candidate:"+t.join(" ")},t.parseIceOptions=function(e){return e.substring(14).split(" ")},t.parseRtpMap=function(e){let t=e.substring(9).split(" ");const i={payloadType:parseInt(t.shift(),10)};return t=t[0].split("/"),i.name=t[0],i.clockRate=parseInt(t[1],10),i.channels=3===t.length?parseInt(t[2],10):1,i.numChannels=i.channels,i},t.writeRtpMap=function(e){let t=e.payloadType;void 0!==e.preferredPayloadType&&(t=e.preferredPayloadType);const i=e.channels||e.numChannels||1;return"a=rtpmap:"+t+" "+e.name+"/"+e.clockRate+(1!==i?"/"+i:"")+"\r\n"},t.parseExtmap=function(e){const t=e.substring(9).split(" ");return{id:parseInt(t[0],10),direction:t[0].indexOf("/")>0?t[0].split("/")[1]:"sendrecv",uri:t[1],attributes:t.slice(2).join(" ")}},t.writeExtmap=function(e){return"a=extmap:"+(e.id||e.preferredId)+(e.direction&&"sendrecv"!==e.direction?"/"+e.direction:"")+" "+e.uri+(e.attributes?" "+e.attributes:"")+"\r\n"},t.parseFmtp=function(e){const t={};let i;const n=e.substring(e.indexOf(" ")+1).split(";");for(let e=0;e<n.length;e++)i=n[e].trim().split("="),t[i[0].trim()]=i[1];return t},t.writeFmtp=function(e){let t="",i=e.payloadType;if(void 0!==e.preferredPayloadType&&(i=e.preferredPayloadType),e.parameters&&Object.keys(e.parameters).length){const n=[];Object.keys(e.parameters).forEach((t=>{void 0!==e.parameters[t]?n.push(t+"="+e.parameters[t]):n.push(t)})),t+="a=fmtp:"+i+" "+n.join(";")+"\r\n"}return t},t.parseRtcpFb=function(e){const t=e.substring(e.indexOf(" ")+1).split(" ");return{type:t.shift(),parameter:t.join(" ")}},t.writeRtcpFb=function(e){let t="",i=e.payloadType;return void 0!==e.preferredPayloadType&&(i=e.preferredPayloadType),e.rtcpFeedback&&e.rtcpFeedback.length&&e.rtcpFeedback.forEach((e=>{t+="a=rtcp-fb:"+i+" "+e.type+(e.parameter&&e.parameter.length?" "+e.parameter:"")+"\r\n"})),t},t.parseSsrcMedia=function(e){const t=e.indexOf(" "),i={ssrc:parseInt(e.substring(7,t),10)},n=e.indexOf(":",t);return n>-1?(i.attribute=e.substring(t+1,n),i.value=e.substring(n+1)):i.attribute=e.substring(t+1),i},t.parseSsrcGroup=function(e){const t=e.substring(13).split(" ");return{semantics:t.shift(),ssrcs:t.map((e=>parseInt(e,10)))}},t.getMid=function(e){const i=t.matchPrefix(e,"a=mid:")[0];if(i)return i.substring(6)},t.parseFingerprint=function(e){const t=e.substring(14).split(" ");return{algorithm:t[0].toLowerCase(),value:t[1].toUpperCase()}},t.getDtlsParameters=function(e,i){return{role:"auto",fingerprints:t.matchPrefix(e+i,"a=fingerprint:").map(t.parseFingerprint)}},t.writeDtlsParameters=function(e,t){let i="a=setup:"+t+"\r\n";return e.fingerprints.forEach((e=>{i+="a=fingerprint:"+e.algorithm+" "+e.value+"\r\n"})),i},t.parseCryptoLine=function(e){const t=e.substring(9).split(" ");return{tag:parseInt(t[0],10),cryptoSuite:t[1],keyParams:t[2],sessionParams:t.slice(3)}},t.writeCryptoLine=function(e){return"a=crypto:"+e.tag+" "+e.cryptoSuite+" "+("object"==typeof e.keyParams?t.writeCryptoKeyParams(e.keyParams):e.keyParams)+(e.sessionParams?" "+e.sessionParams.join(" "):"")+"\r\n"},t.parseCryptoKeyParams=function(e){if(0!==e.indexOf("inline:"))return null;const t=e.substring(7).split("|");return{keyMethod:"inline",keySalt:t[0],lifeTime:t[1],mkiValue:t[2]?t[2].split(":")[0]:void 0,mkiLength:t[2]?t[2].split(":")[1]:void 0}},t.writeCryptoKeyParams=function(e){return e.keyMethod+":"+e.keySalt+(e.lifeTime?"|"+e.lifeTime:"")+(e.mkiValue&&e.mkiLength?"|"+e.mkiValue+":"+e.mkiLength:"")},t.getCryptoParameters=function(e,i){return t.matchPrefix(e+i,"a=crypto:").map(t.parseCryptoLine)},t.getIceParameters=function(e,i){const n=t.matchPrefix(e+i,"a=ice-ufrag:")[0],s=t.matchPrefix(e+i,"a=ice-pwd:")[0];return n&&s?{usernameFragment:n.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 i={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},n=t.splitLines(e)[0].split(" ");i.profile=n[2];for(let s=3;s<n.length;s++){const r=n[s],o=t.matchPrefix(e,"a=rtpmap:"+r+" ")[0];if(o){const n=t.parseRtpMap(o),s=t.matchPrefix(e,"a=fmtp:"+r+" ");switch(n.parameters=s.length?t.parseFmtp(s[0]):{},n.rtcpFeedback=t.matchPrefix(e,"a=rtcp-fb:"+r+" ").map(t.parseRtcpFb),i.codecs.push(n),n.name.toUpperCase()){case"RED":case"ULPFEC":i.fecMechanisms.push(n.name.toUpperCase())}}}t.matchPrefix(e,"a=extmap:").forEach((e=>{i.headerExtensions.push(t.parseExtmap(e))}));const s=t.matchPrefix(e,"a=rtcp-fb:* ").map(t.parseRtcpFb);return i.codecs.forEach((e=>{s.forEach((t=>{e.rtcpFeedback.find((e=>e.type===t.type&&e.parameter===t.parameter))||e.rtcpFeedback.push(t)}))})),i},t.writeRtpDescription=function(e,i){let n="";n+="m="+e+" ",n+=i.codecs.length>0?"9":"0",n+=" "+(i.profile||"UDP/TLS/RTP/SAVPF")+" ",n+=i.codecs.map((e=>void 0!==e.preferredPayloadType?e.preferredPayloadType:e.payloadType)).join(" ")+"\r\n",n+="c=IN IP4 0.0.0.0\r\n",n+="a=rtcp:9 IN IP4 0.0.0.0\r\n",i.codecs.forEach((e=>{n+=t.writeRtpMap(e),n+=t.writeFmtp(e),n+=t.writeRtcpFb(e)}));let s=0;return i.codecs.forEach((e=>{e.maxptime>s&&(s=e.maxptime)})),s>0&&(n+="a=maxptime:"+s+"\r\n"),i.headerExtensions&&i.headerExtensions.forEach((e=>{n+=t.writeExtmap(e)})),n},t.parseRtpEncodingParameters=function(e){const i=[],n=t.parseRtpParameters(e),s=-1!==n.fecMechanisms.indexOf("RED"),r=-1!==n.fecMechanisms.indexOf("ULPFEC"),o=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"cname"===e.attribute)),a=o.length>0&&o[0].ssrc;let c;const d=t.matchPrefix(e,"a=ssrc-group:FID").map((e=>e.substring(17).split(" ").map((e=>parseInt(e,10)))));d.length>0&&d[0].length>1&&d[0][0]===a&&(c=d[0][1]),n.codecs.forEach((e=>{if("RTX"===e.name.toUpperCase()&&e.parameters.apt){let t={ssrc:a,codecPayloadType:parseInt(e.parameters.apt,10)};a&&c&&(t.rtx={ssrc:c}),i.push(t),s&&(t=JSON.parse(JSON.stringify(t)),t.fec={ssrc:a,mechanism:r?"red+ulpfec":"red"},i.push(t))}})),0===i.length&&a&&i.push({ssrc:a});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,i.forEach((e=>{e.maxBitrate=l}))),i},t.parseRtcpParameters=function(e){const i={},n=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"cname"===e.attribute))[0];n&&(i.cname=n.value,i.ssrc=n.ssrc);const s=t.matchPrefix(e,"a=rtcp-rsize");i.reducedSize=s.length>0,i.compound=0===s.length;const r=t.matchPrefix(e,"a=rtcp-mux");return i.mux=r.length>0,i},t.writeRtcpParameters=function(e){let t="";return e.reducedSize&&(t+="a=rtcp-rsize\r\n"),e.mux&&(t+="a=rtcp-mux\r\n"),void 0!==e.ssrc&&e.cname&&(t+="a=ssrc:"+e.ssrc+" cname:"+e.cname+"\r\n"),t},t.parseMsid=function(e){let i;const n=t.matchPrefix(e,"a=msid:");if(1===n.length)return i=n[0].substring(7).split(" "),{stream:i[0],track:i[1]};const s=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"msid"===e.attribute));return s.length>0?(i=s[0].value.split(" "),{stream:i[0],track:i[1]}):void 0},t.parseSctpDescription=function(e){const i=t.parseMLine(e),n=t.matchPrefix(e,"a=max-message-size:");let s;n.length>0&&(s=parseInt(n[0].substring(19),10)),isNaN(s)&&(s=65536);const r=t.matchPrefix(e,"a=sctp-port:");if(r.length>0)return{port:parseInt(r[0].substring(12),10),protocol:i.fmt,maxMessageSize:s};const o=t.matchPrefix(e,"a=sctpmap:");if(o.length>0){const e=o[0].substring(10).split(" ");return{port:parseInt(e[0],10),protocol:e[1],maxMessageSize:s}}},t.writeSctpDescription=function(e,t){let i=[];return i="DTLS/SCTP"!==e.protocol?["m="+e.kind+" 9 "+e.protocol+" "+t.protocol+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctp-port:"+t.port+"\r\n"]:["m="+e.kind+" 9 "+e.protocol+" "+t.port+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctpmap:"+t.port+" "+t.protocol+" 65535\r\n"],void 0!==t.maxMessageSize&&i.push("a=max-message-size:"+t.maxMessageSize+"\r\n"),i.join("")},t.generateSessionId=function(){return Math.random().toString().substr(2,22)},t.writeSessionBoilerplate=function(e,i,n){let s;const r=void 0!==i?i:2;s=e||t.generateSessionId();return"v=0\r\no="+(n||"thisisadapterortc")+" "+s+" "+r+" IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\n"},t.getDirection=function(e,i){const n=t.splitLines(e);for(let e=0;e<n.length;e++)switch(n[e]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return n[e].substring(2)}return i?t.getDirection(i):"sendrecv"},t.getKind=function(e){return t.splitLines(e)[0].split(" ")[0].substring(2)},t.isRejected=function(e){return"0"===e.split(" ",2)[1]},t.parseMLine=function(e){const i=t.splitLines(e)[0].substring(2).split(" ");return{kind:i[0],port:parseInt(i[1],10),protocol:i[2],fmt:i.slice(3).join(" ")}},t.parseOLine=function(e){const i=t.matchPrefix(e,"o=")[0].substring(2).split(" ");return{username:i[0],sessionId:i[1],sessionVersion:parseInt(i[2],10),netType:i[3],addressType:i[4],address:i[5]}},t.isValidSDP=function(e){if("string"!=typeof e||0===e.length)return!1;const i=t.splitLines(e);for(let e=0;e<i.length;e++)if(i[e].length<2||"="!==i[e].charAt(1))return!1;return!0},e.exports=t}(Kn);var Wn=Kn.exports,Gn=bi(Wn),Hn=t({__proto__:null,default:Gn},[Wn]);function Jn(e){if(!e.RTCIceCandidate||e.RTCIceCandidate&&"foundation"in e.RTCIceCandidate.prototype)return;const t=e.RTCIceCandidate;e.RTCIceCandidate=function(e){if("object"==typeof e&&e.candidate&&0===e.candidate.indexOf("a=")&&((e=JSON.parse(JSON.stringify(e))).candidate=e.candidate.substring(2)),e.candidate&&e.candidate.length){const i=new t(e),n=Gn.parseCandidate(e.candidate);for(const e in n)e in i||Object.defineProperty(i,e,{value:n[e]});return i.toJSON=function(){return{candidate:i.candidate,sdpMid:i.sdpMid,sdpMLineIndex:i.sdpMLineIndex,usernameFragment:i.usernameFragment}},i}return new t(e)},e.RTCIceCandidate.prototype=t.prototype,en(e,"icecandidate",(t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new e.RTCIceCandidate(t.candidate),writable:"false"}),t)))}function Qn(e){!e.RTCIceCandidate||e.RTCIceCandidate&&"relayProtocol"in e.RTCIceCandidate.prototype||en(e,"icecandidate",(e=>{if(e.candidate){const t=Gn.parseCandidate(e.candidate.candidate);"relay"===t.type&&(e.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[t.priority>>24])}return e}))}function zn(e,t){if(!e.RTCPeerConnection)return;"sctp"in e.RTCPeerConnection.prototype||Object.defineProperty(e.RTCPeerConnection.prototype,"sctp",{get(){return void 0===this._sctp?null:this._sctp}});const i=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,"chrome"===t.browser&&t.version>=76){const{sdpSemantics:e}=this.getConfiguration();"plan-b"===e&&Object.defineProperty(this,"sctp",{get(){return void 0===this._sctp?null:this._sctp},enumerable:!0,configurable:!0})}if(function(e){if(!e||!e.sdp)return!1;const t=Gn.splitSections(e.sdp);return t.shift(),t.some((e=>{const t=Gn.parseMLine(e);return t&&"application"===t.kind&&-1!==t.protocol.indexOf("SCTP")}))}(arguments[0])){const e=function(e){const t=e.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(null===t||t.length<2)return-1;const i=parseInt(t[1],10);return i!=i?-1:i}(arguments[0]),i=function(e){let i=65536;return"firefox"===t.browser&&(i=t.version<57?-1===e?16384:2147483637:t.version<60?57===t.version?65535:65536:2147483637),i}(e),n=function(e,i){let n=65536;"firefox"===t.browser&&57===t.version&&(n=65535);const s=Gn.matchPrefix(e.sdp,"a=max-message-size:");return s.length>0?n=parseInt(s[0].substring(19),10):"firefox"===t.browser&&-1!==i&&(n=2147483637),n}(arguments[0],e);let s;s=0===i&&0===n?Number.POSITIVE_INFINITY:0===i||0===n?Math.max(i,n):Math.min(i,n);const r={};Object.defineProperty(r,"maxMessageSize",{get:()=>s}),this._sctp=r}return i.apply(this,arguments)}}function Yn(e){if(!e.RTCPeerConnection||!("createDataChannel"in e.RTCPeerConnection.prototype))return;function t(e,t){const i=e.send;e.send=function(){const n=arguments[0],s=n.length||n.size||n.byteLength;if("open"===e.readyState&&t.sctp&&s>t.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+t.sctp.maxMessageSize+" bytes)");return i.apply(e,arguments)}}const i=e.RTCPeerConnection.prototype.createDataChannel;e.RTCPeerConnection.prototype.createDataChannel=function(){const e=i.apply(this,arguments);return t(e,this),e},en(e,"datachannel",(e=>(t(e.channel,e.target),e)))}function Xn(e){if(!e.RTCPeerConnection||"connectionState"in e.RTCPeerConnection.prototype)return;const t=e.RTCPeerConnection.prototype;Object.defineProperty(t,"connectionState",{get(){return{completed:"connected",checking:"connecting"}[this.iceConnectionState]||this.iceConnectionState},enumerable:!0,configurable:!0}),Object.defineProperty(t,"onconnectionstatechange",{get(){return this._onconnectionstatechange||null},set(e){this._onconnectionstatechange&&(this.removeEventListener("connectionstatechange",this._onconnectionstatechange),delete this._onconnectionstatechange),e&&this.addEventListener("connectionstatechange",this._onconnectionstatechange=e)},enumerable:!0,configurable:!0}),["setLocalDescription","setRemoteDescription"].forEach((e=>{const i=t[e];t[e]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=e=>{const t=e.target;if(t._lastConnectionState!==t.connectionState){t._lastConnectionState=t.connectionState;const i=new Event("connectionstatechange",e);t.dispatchEvent(i)}return e},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),i.apply(this,arguments)}}))}function $n(e,t){if(!e.RTCPeerConnection)return;if("chrome"===t.browser&&t.version>=71)return;if("safari"===t.browser&&t.version>=605)return;const i=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(t){if(t&&t.sdp&&-1!==t.sdp.indexOf("\na=extmap-allow-mixed")){const i=t.sdp.split("\n").filter((e=>"a=extmap-allow-mixed"!==e.trim())).join("\n");e.RTCSessionDescription&&t instanceof e.RTCSessionDescription?arguments[0]=new e.RTCSessionDescription({type:t.type,sdp:i}):t.sdp=i}return i.apply(this,arguments)}}function Zn(e,t){if(!e.RTCPeerConnection||!e.RTCPeerConnection.prototype)return;const i=e.RTCPeerConnection.prototype.addIceCandidate;i&&0!==i.length&&(e.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?("chrome"===t.browser&&t.version<78||"firefox"===t.browser&&t.version<68||"safari"===t.browser)&&arguments[0]&&""===arguments[0].candidate?Promise.resolve():i.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}function es(e,t){if(!e.RTCPeerConnection||!e.RTCPeerConnection.prototype)return;const i=e.RTCPeerConnection.prototype.setLocalDescription;i&&0!==i.length&&(e.RTCPeerConnection.prototype.setLocalDescription=function(){let e=arguments[0]||{};if("object"!=typeof e||e.type&&e.sdp)return i.apply(this,arguments);if(e={type:e.type,sdp:e.sdp},!e.type)switch(this.signalingState){case"stable":case"have-local-offer":case"have-remote-pranswer":e.type="offer";break;default:e.type="answer"}if(e.sdp||"offer"!==e.type&&"answer"!==e.type)return i.apply(this,[e]);return("offer"===e.type?this.createOffer:this.createAnswer).apply(this).then((e=>i.apply(this,[e])))})}var ts=Object.freeze({__proto__:null,removeExtmapAllowMixed:$n,shimAddIceCandidateNullOrEmpty:Zn,shimConnectionState:Xn,shimMaxMessageSize:zn,shimParameterlessSetLocalDescription:es,shimRTCIceCandidate:Jn,shimRTCIceCandidateRelayProtocol:Qn,shimSendThrowTypeError:Yn});!function(){let{window:e}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{shimChrome:!0,shimFirefox:!0,shimSafari:!0};const i=sn,n=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:i}=e;if(i.userAgentData&&i.userAgentData.brands){const e=i.userAgentData.brands.find((e=>"Chromium"===e.brand));if(e)return{browser:"chrome",version:parseInt(e.version,10)}}if(i.mozGetUserMedia)t.browser="firefox",t.version=Zi(i.userAgent,/Firefox\/(\d+)\./,1);else if(i.webkitGetUserMedia||!1===e.isSecureContext&&e.webkitRTCPeerConnection)t.browser="chrome",t.version=Zi(i.userAgent,/Chrom(e|ium)\/(\d+)\./,2);else{if(!e.RTCPeerConnection||!i.userAgent.match(/AppleWebKit\/(\d+)\./))return t.browser="Not a supported browser.",t;t.browser="safari",t.version=Zi(i.userAgent,/AppleWebKit\/(\d+)\./,1),t.supportsUnifiedPlan=e.RTCRtpTransceiver&&"currentDirection"in e.RTCRtpTransceiver.prototype}return t}(e),s={browserDetails:n,commonShim:ts,extractVersion:Zi,disableLog:tn,disableWarnings:nn,sdp:Hn};switch(n.browser){case"chrome":if(!yn||!kn||!t.shimChrome)return i("Chrome shim is not included in this adapter release."),s;if(null===n.version)return i("Chrome shim can not determine version, not shimming."),s;i("adapter.js shimming chrome."),s.browserShim=yn,Zn(e,n),es(e),un(e,n),hn(e),kn(e,n),pn(e),vn(e,n),mn(e),gn(e),bn(e,n),Jn(e),Qn(e),Xn(e),zn(e,n),Yn(e),$n(e,n);break;case"firefox":if(!Mn||!Sn||!t.shimFirefox)return i("Firefox shim is not included in this adapter release."),s;i("adapter.js shimming firefox."),s.browserShim=Mn,Zn(e,n),es(e),Tn(e,n),Sn(e,n),Cn(e),Pn(e),En(e),wn(e),Rn(e),In(e),On(e),xn(e),Dn(e),Jn(e),Xn(e),zn(e,n),Yn(e);break;case"safari":if(!qn||!t.shimSafari)return i("Safari shim is not included in this adapter release."),s;i("adapter.js shimming safari."),s.browserShim=qn,Zn(e,n),es(e),jn(e),Bn(e),An(e),Nn(e),_n(e),Fn(e),Ln(e),Vn(e),Jn(e),Qn(e),zn(e,n),Yn(e),$n(e,n);break;default:i("Unsupported browser!")}}({window:"undefined"==typeof window?void 0:window});const is="AES-GCM",ns="lk_e2ee",ss={sharedKey:!1,ratchetSalt:"LKFrameEncryptionKey",ratchetWindowSize:8,failureTolerance:10,keyringSize:16};var rs,os;function as(){return ds()||cs()}function cs(){return void 0!==window.RTCRtpScriptTransform}function ds(){return void 0!==window.RTCRtpSender&&void 0!==window.RTCRtpSender.prototype.createEncodedStreams}function ls(e){return Di(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 us(e){return Di(this,void 0,void 0,(function*(){return yield crypto.subtle.importKey("raw",e,"HKDF",!1,["deriveBits","deriveKey"])}))}function hs(e,t){const i=(new TextEncoder).encode(t);switch(e){case"HKDF":return{name:"HKDF",salt:i,hash:"SHA-256",info:new ArrayBuffer(128)};case"PBKDF2":return{name:"PBKDF2",salt:i,hash:"SHA-256",iterations:1e5};default:throw new Error("algorithm ".concat(e," is currently unsupported"))}}e.KeyProviderEvent=void 0,(rs=e.KeyProviderEvent||(e.KeyProviderEvent={})).SetKey="setKey",rs.RatchetRequest="ratchetRequest",rs.KeyRatcheted="keyRatcheted",e.KeyHandlerEvent=void 0,(e.KeyHandlerEvent||(e.KeyHandlerEvent={})).KeyRatcheted="keyRatcheted",e.EncryptionEvent=void 0,(os=e.EncryptionEvent||(e.EncryptionEvent={})).ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",os.EncryptionError="encryptionError",e.CryptorEvent=void 0,(e.CryptorEvent||(e.CryptorEvent={})).Error="cryptorError";class ps extends Yi.EventEmitter{constructor(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};super(),this.onKeyRatcheted=(e,t)=>{Ei.debug("key ratcheted event received",{material:e,keyIndex:t})},this.keyInfoMap=new Map,this.options=Object.assign(Object.assign({},ss),t),this.on(e.KeyProviderEvent.KeyRatcheted,this.onKeyRatcheted)}onSetEncryptionKey(t,i,n){const s={key:t,participantIdentity:i,keyIndex:n};if(!this.options.sharedKey&&!i)throw new Error("participant identity needs to be passed for encryption key if sharedKey option is false");this.keyInfoMap.set("".concat(null!=i?i:"shared","-").concat(null!=n?n:0),s),this.emit(e.KeyProviderEvent.SetKey,s)}getKeys(){return Array.from(this.keyInfoMap.values())}getOptions(){return this.options}ratchetKey(t,i){this.emit(e.KeyProviderEvent.RatchetRequest,t,i)}}class ms extends Error{constructor(e,t){super(t||"an error has occured"),this.code=e}}class gs extends ms{constructor(e,t,i){super(1,e),this.status=i,this.reason=t}}class fs extends ms{constructor(e){super(21,null!=e?e:"device is unsupported")}}class vs extends ms{constructor(e){super(20,null!=e?e:"track is invalid")}}class ks extends ms{constructor(e){super(10,null!=e?e:"unsupported server")}}class bs extends ms{constructor(e){super(12,null!=e?e:"unexpected connection state")}}class ys extends ms{constructor(e){super(13,null!=e?e:"unable to negotiate")}}class Ts extends ms{constructor(e,t){super(15,e),this.reason=t}}var Cs,Ss,Es,ws,Ps,Rs;e.MediaDeviceFailure=void 0,(Cs=e.MediaDeviceFailure||(e.MediaDeviceFailure={})).PermissionDenied="PermissionDenied",Cs.NotFound="NotFound",Cs.DeviceInUse="DeviceInUse",Cs.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.CryptorErrorReason=void 0,(Ss=e.CryptorErrorReason||(e.CryptorErrorReason={}))[Ss.InvalidKey=0]="InvalidKey",Ss[Ss.MissingKey=1]="MissingKey",Ss[Ss.InternalError=2]="InternalError";function Is(e,t,i){var n,s,r;void 0===t&&(t=50),void 0===i&&(i={});var o=null!=(n=i.isImmediate)&&n,a=null!=(s=i.callback)&&s,c=i.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),i=this;return new Promise((function(n,s){var c=o&&void 0===r;if(void 0!==r&&clearTimeout(r),r=setTimeout((function(){if(r=void 0,d=Date.now(),!o){var n=e.apply(i,t);a&&a(n),l.forEach((function(e){return(0,e.resolve)(n)})),l=[]}}),u()),c){var h=e.apply(i,t);return a&&a(h),n(h)}l.push({resolve:n,reject:s})}))};return h.cancel=function(e){void 0!==r&&clearTimeout(r),l.forEach((function(t){return(0,t.reject)(e)})),l=[]},h}e.RoomEvent=void 0,(Es=e.RoomEvent||(e.RoomEvent={})).Connected="connected",Es.Reconnecting="reconnecting",Es.SignalReconnecting="signalReconnecting",Es.Reconnected="reconnected",Es.Disconnected="disconnected",Es.ConnectionStateChanged="connectionStateChanged",Es.MediaDevicesChanged="mediaDevicesChanged",Es.ParticipantConnected="participantConnected",Es.ParticipantDisconnected="participantDisconnected",Es.TrackPublished="trackPublished",Es.TrackSubscribed="trackSubscribed",Es.TrackSubscriptionFailed="trackSubscriptionFailed",Es.TrackUnpublished="trackUnpublished",Es.TrackUnsubscribed="trackUnsubscribed",Es.TrackMuted="trackMuted",Es.TrackUnmuted="trackUnmuted",Es.LocalTrackPublished="localTrackPublished",Es.LocalTrackUnpublished="localTrackUnpublished",Es.LocalAudioSilenceDetected="localAudioSilenceDetected",Es.ActiveSpeakersChanged="activeSpeakersChanged",Es.ParticipantMetadataChanged="participantMetadataChanged",Es.ParticipantNameChanged="participantNameChanged",Es.ParticipantAttributesChanged="participantAttributesChanged",Es.RoomMetadataChanged="roomMetadataChanged",Es.DataReceived="dataReceived",Es.SipDTMFReceived="sipDTMFReceived",Es.TranscriptionReceived="transcriptionReceived",Es.ConnectionQualityChanged="connectionQualityChanged",Es.TrackStreamStateChanged="trackStreamStateChanged",Es.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",Es.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",Es.AudioPlaybackStatusChanged="audioPlaybackChanged",Es.VideoPlaybackStatusChanged="videoPlaybackChanged",Es.MediaDevicesError="mediaDevicesError",Es.ParticipantPermissionsChanged="participantPermissionsChanged",Es.SignalConnected="signalConnected",Es.RecordingStatusChanged="recordingStatusChanged",Es.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",Es.EncryptionError="encryptionError",Es.DCBufferStatusChanged="dcBufferStatusChanged",Es.ActiveDeviceChanged="activeDeviceChanged",Es.LocalTrackSubscribed="localTrackSubscribed",e.ParticipantEvent=void 0,(ws=e.ParticipantEvent||(e.ParticipantEvent={})).TrackPublished="trackPublished",ws.TrackSubscribed="trackSubscribed",ws.TrackSubscriptionFailed="trackSubscriptionFailed",ws.TrackUnpublished="trackUnpublished",ws.TrackUnsubscribed="trackUnsubscribed",ws.TrackMuted="trackMuted",ws.TrackUnmuted="trackUnmuted",ws.LocalTrackPublished="localTrackPublished",ws.LocalTrackUnpublished="localTrackUnpublished",ws.ParticipantMetadataChanged="participantMetadataChanged",ws.ParticipantNameChanged="participantNameChanged",ws.DataReceived="dataReceived",ws.SipDTMFReceived="sipDTMFReceived",ws.TranscriptionReceived="transcriptionReceived",ws.IsSpeakingChanged="isSpeakingChanged",ws.ConnectionQualityChanged="connectionQualityChanged",ws.TrackStreamStateChanged="trackStreamStateChanged",ws.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",ws.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",ws.MediaDevicesError="mediaDevicesError",ws.AudioStreamAcquired="audioStreamAcquired",ws.ParticipantPermissionsChanged="participantPermissionsChanged",ws.PCTrackAdded="pcTrackAdded",ws.AttributesChanged="attributesChanged",ws.LocalTrackSubscribed="localTrackSubscribed",e.EngineEvent=void 0,(Ps=e.EngineEvent||(e.EngineEvent={})).TransportsCreated="transportsCreated",Ps.Connected="connected",Ps.Disconnected="disconnected",Ps.Resuming="resuming",Ps.Resumed="resumed",Ps.Restarting="restarting",Ps.Restarted="restarted",Ps.SignalResumed="signalResumed",Ps.SignalRestarted="signalRestarted",Ps.Closing="closing",Ps.MediaTrackAdded="mediaTrackAdded",Ps.ActiveSpeakersUpdate="activeSpeakersUpdate",Ps.DataPacketReceived="dataPacketReceived",Ps.RTPVideoMapUpdate="rtpVideoMapUpdate",Ps.DCBufferStatusChanged="dcBufferStatusChanged",Ps.ParticipantUpdate="participantUpdate",Ps.RoomUpdate="roomUpdate",Ps.SpeakersChanged="speakersChanged",Ps.StreamStateChanged="streamStateChanged",Ps.ConnectionQualityUpdate="connectionQualityUpdate",Ps.SubscriptionError="subscriptionError",Ps.SubscriptionPermissionUpdate="subscriptionPermissionUpdate",Ps.RemoteMute="remoteMute",Ps.SubscribedQualityUpdate="subscribedQualityUpdate",Ps.LocalTrackUnpublished="localTrackUnpublished",Ps.LocalTrackSubscribed="localTrackSubscribed",Ps.Offline="offline",Ps.SignalRequestResponse="signalRequestResponse",e.TrackEvent=void 0,(Rs=e.TrackEvent||(e.TrackEvent={})).Message="message",Rs.Muted="muted",Rs.Unmuted="unmuted",Rs.Restarted="restarted",Rs.Ended="ended",Rs.Subscribed="subscribed",Rs.Unsubscribed="unsubscribed",Rs.UpdateSettings="updateSettings",Rs.UpdateSubscription="updateSubscription",Rs.AudioPlaybackStarted="audioPlaybackStarted",Rs.AudioPlaybackFailed="audioPlaybackFailed",Rs.AudioSilenceDetected="audioSilenceDetected",Rs.VisibilityChanged="visibilityChanged",Rs.VideoDimensionsChanged="videoDimensionsChanged",Rs.VideoPlaybackStarted="videoPlaybackStarted",Rs.VideoPlaybackFailed="videoPlaybackFailed",Rs.ElementAttached="elementAttached",Rs.ElementDetached="elementDetached",Rs.UpstreamPaused="upstreamPaused",Rs.UpstreamResumed="upstreamResumed",Rs.SubscriptionPermissionChanged="subscriptionPermissionChanged",Rs.SubscriptionStatusChanged="subscriptionStatusChanged",Rs.SubscriptionFailed="subscriptionFailed",Rs.TrackProcessorUpdate="trackProcessorUpdate",Rs.AudioTrackFeatureUpdate="audioTrackFeatureUpdate",Rs.TranscriptionReceived="transcriptionReceived",Rs.TimeSyncUpdate="timeSyncUpdate";const Os=/version\/(\d+(\.?_?\d+)+)/i;let xs;function Ds(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(void 0===e&&"undefined"==typeof navigator)return;const i=(null!=e?e:navigator.userAgent).toLowerCase();if(void 0===xs||t){const e=Ms.find((e=>{let{test:t}=e;return t.test(i)}));xs=null==e?void 0:e.describe(i)}return xs}const Ms=[{test:/firefox|iceweasel|fxios/i,describe:e=>({name:"Firefox",version:Ns(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,e),os:e.toLowerCase().includes("fxios")?"iOS":void 0,osVersion:_s(e)})},{test:/chrom|crios|crmo/i,describe:e=>({name:"Chrome",version:Ns(/(?:chrome|chromium|crios|crmo)\/(\d+(\.?_?\d+)+)/i,e),os:e.toLowerCase().includes("crios")?"iOS":void 0,osVersion:_s(e)})},{test:/safari|applewebkit/i,describe:e=>({name:"Safari",version:Ns(Os,e),os:e.includes("mobile/")?"iOS":"macOS",osVersion:_s(e)})}];function Ns(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1;const n=t.match(e);return n&&n.length>=i&&n[i]||""}function _s(e){return e.includes("mac os")?Ns(/\(.+?(\d+_\d+(:?_\d+)?)/,e,1).replace(/_/g,"."):void 0}const As="2.5.2";class Ls{}Ls.setTimeout=function(){return setTimeout(...arguments)},Ls.setInterval=function(){return setInterval(...arguments)},Ls.clearTimeout=function(){return clearTimeout(...arguments)},Ls.clearInterval=function(){return clearInterval(...arguments)};class Us{constructor(e,t,i,n,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===i)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:i,maxFramerate:n,priority:s}}}get resolution(){return{width:this.width,height:this.height,frameRate:this.encoding.maxFramerate,aspectRatio:this.aspectRatio}}}const js=["vp8","h264"],Fs=["vp8","h264","vp9","av1"];function Bs(e){return!!js.find((t=>t===e))}var Vs;e.AudioPresets=void 0,(Vs=e.AudioPresets||(e.AudioPresets={})).telephone={maxBitrate:12e3},Vs.speech={maxBitrate:2e4},Vs.music={maxBitrate:32e3},Vs.musicStereo={maxBitrate:48e3},Vs.musicHighQuality={maxBitrate:64e3},Vs.musicHighQualityStereo={maxBitrate:96e3};const qs={h90:new Us(160,90,9e4,20),h180:new Us(320,180,16e4,20),h216:new Us(384,216,18e4,20),h360:new Us(640,360,45e4,20),h540:new Us(960,540,8e5,25),h720:new Us(1280,720,17e5,30),h1080:new Us(1920,1080,3e6,30),h1440:new Us(2560,1440,5e6,30),h2160:new Us(3840,2160,8e6,30)},Ks={h120:new Us(160,120,7e4,20),h180:new Us(240,180,125e3,20),h240:new Us(320,240,14e4,20),h360:new Us(480,360,33e4,20),h480:new Us(640,480,5e5,20),h540:new Us(720,540,6e5,25),h720:new Us(960,720,13e5,30),h1080:new Us(1440,1080,23e5,30),h1440:new Us(1920,1440,38e5,30)},Ws={h360fps3:new Us(640,360,2e5,3,"medium"),h360fps15:new Us(640,360,4e5,15,"medium"),h720fps5:new Us(1280,720,8e5,5,"medium"),h720fps15:new Us(1280,720,15e5,15,"medium"),h720fps30:new Us(1280,720,2e6,30,"medium"),h1080fps15:new Us(1920,1080,25e5,15,"medium"),h1080fps30:new Us(1920,1080,5e6,30,"medium"),original:new Us(0,0,7e6,30,"medium")};const Gs=[];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 Hs extends Yi.EventEmitter{constructor(t,i){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};var s;super(),this.attachedElements=[],this.isMuted=!1,this.streamState=Hs.StreamState.Active,this.isInBackground=!1,this._currentBitrate=0,this.log=Ei,this.appVisibilityChangedListener=()=>{this.backgroundTimeout&&clearTimeout(this.backgroundTimeout),"hidden"===document.visibilityState?this.backgroundTimeout=setTimeout((()=>this.handleAppVisibilityChanged()),5e3):this.handleAppVisibilityChanged()},this.log=Pi(null!==(s=n.loggerName)&&void 0!==s?s:e.LoggerNames.Track),this.loggerContextCb=n.loggerContextCb,this.setMaxListeners(100),this.kind=i,this._mediaStreamTrack=t,this._mediaStreamID=t.id,this.source=Hs.Source.Unknown}get logContext(){var e;return Object.assign(Object.assign({},null===(e=this.loggerContextCb)||void 0===e?void 0:e.call(this)),nr(this))}get currentBitrate(){return this._currentBitrate}get mediaStreamTrack(){return this._mediaStreamTrack}get mediaStreamID(){return this._mediaStreamID}attach(t){let i="audio";this.kind===Hs.Kind.Video&&(i="video"),0===this.attachedElements.length&&this.kind===Hs.Kind.Video&&this.addAppVisibilityListener(),t||("audio"===i&&(Gs.forEach((e=>{null!==e.parentElement||t||(t=e)})),t&&Gs.splice(Gs.indexOf(t),1)),t||(t=document.createElement(i))),this.attachedElements.includes(t)||this.attachedElements.push(t),Js(this.mediaStreamTrack,t);const n=t.srcObject.getTracks(),s=n.some((e=>"audio"===e.kind));return t.play().then((()=>{this.emit(s?e.TrackEvent.AudioPlaybackStarted:e.TrackEvent.VideoPlaybackStarted)})).catch((i=>{"NotAllowedError"===i.name?this.emit(s?e.TrackEvent.AudioPlaybackFailed:e.TrackEvent.VideoPlaybackFailed,i):"AbortError"===i.name?Ei.debug("".concat(s?"audio":"video"," playback aborted, likely due to new play request")):Ei.warn("could not playback ".concat(s?"audio":"video"),i),s&&t&&n.some((e=>"video"===e.kind))&&"NotAllowedError"===i.name&&(t.muted=!0,t.play().catch((()=>{})))})),this.emit(e.TrackEvent.ElementAttached,t),t}detach(t){try{if(t){Qs(this.mediaStreamTrack,t);const i=this.attachedElements.indexOf(t);return i>=0&&(this.attachedElements.splice(i,1),this.recycleElement(t),this.emit(e.TrackEvent.ElementDetached,t)),t}const i=[];return this.attachedElements.forEach((t=>{Qs(this.mediaStreamTrack,t),i.push(t),this.recycleElement(t),this.emit(e.TrackEvent.ElementDetached,t)})),this.attachedElements=[],i}finally{0===this.attachedElements.length&&this.removeAppVisibilityListener()}}stop(){this.stopMonitor(),this._mediaStreamTrack.stop()}enable(){this._mediaStreamTrack.enabled=!0}disable(){this._mediaStreamTrack.enabled=!1}stopMonitor(){this.monitorInterval&&clearInterval(this.monitorInterval),this.timeSyncHandle&&cancelAnimationFrame(this.timeSyncHandle)}updateLoggerOptions(e){e.loggerName&&(this.log=Pi(e.loggerName)),e.loggerContextCb&&(this.loggerContextCb=e.loggerContextCb)}recycleElement(e){if(e instanceof HTMLAudioElement){let t=!0;e.pause(),Gs.forEach((e=>{e.parentElement||(t=!1)})),t&&Gs.push(e)}}handleAppVisibilityChanged(){return Di(this,void 0,void 0,(function*(){this.isInBackground="hidden"===document.visibilityState,this.isInBackground||this.kind!==Hs.Kind.Video||setTimeout((()=>this.attachedElements.forEach((e=>e.play().catch((()=>{}))))),0)}))}addAppVisibilityListener(){vr()?(this.isInBackground="hidden"===document.visibilityState,document.addEventListener("visibilitychange",this.appVisibilityChangedListener)):this.isInBackground=!1}removeAppVisibilityListener(){vr()&&document.removeEventListener("visibilitychange",this.appVisibilityChangedListener)}}function Js(e,t){let i,n;i=t.srcObject instanceof MediaStream?t.srcObject:new MediaStream,n="audio"===e.kind?i.getAudioTracks():i.getVideoTracks(),n.includes(e)||(n.forEach((e=>{i.removeTrack(e)})),i.addTrack(e)),mr()&&t instanceof HTMLVideoElement||(t.autoplay=!0),t.muted=0===i.getAudioTracks().length,t instanceof HTMLVideoElement&&(t.playsInline=!0),t.srcObject!==i&&(t.srcObject=i,(mr()||pr())&&t instanceof HTMLVideoElement&&setTimeout((()=>{t.srcObject=i,t.play().catch((()=>{}))}),0))}function Qs(e,t){if(t.srcObject instanceof MediaStream){const i=t.srcObject;i.removeTrack(e),i.getTracks().length>0?t.srcObject=i:t.srcObject=null}}function zs(e,t,i){var n;const s=null!==(n=function(e){if(void 0!==e)return"function"==typeof structuredClone?structuredClone(e):JSON.parse(JSON.stringify(e))}(e))&&void 0!==n?n:{};return!0===s.audio&&(s.audio={}),!0===s.video&&(s.video={}),s.audio&&Ys(s.audio,t),s.video&&Ys(s.video,i),s}function Ys(e,t){return Object.keys(t).forEach((i=>{void 0===e[i]&&(e[i]=t[i])})),e}function Xs(e){const t={};if(e.video)if("object"==typeof e.video){const i={},n=i,s=e.video;Object.keys(s).forEach((e=>{if("resolution"===e)Ys(n,s.resolution);else n[e]=s[e]})),t.video=i}else t.video=e.video;else t.video=!1;return e.audio?"object"==typeof e.audio?t.audio=e.audio:t.audio=!0:t.audio=!1,t}function $s(){const e="undefined"!=typeof window&&(window.AudioContext||window.webkitAudioContext);if(e)return new e({latencyHint:"interactive"})}function Zs(e){return e===Hs.Source.Microphone?"audioinput":e===Hs.Source.Camera?"videoinput":void 0}function er(e){var t,i;let n=null===(t=e.video)||void 0===t||t;return e.resolution&&e.resolution.width>0&&e.resolution.height>0&&(n="boolean"==typeof n?{}:n,n=mr()?Object.assign(Object.assign({},n),{width:{max:e.resolution.width},height:{max:e.resolution.height},frameRate:e.resolution.frameRate}):Object.assign(Object.assign({},n),{width:{ideal:e.resolution.width},height:{ideal:e.resolution.height},frameRate:e.resolution.frameRate})),{audio:null!==(i=e.audio)&&void 0!==i&&i,video:n,controller:e.controller,selfBrowserSurface:e.selfBrowserSurface,surfaceSwitching:e.surfaceSwitching,systemAudio:e.systemAudio,preferCurrentTab:e.preferCurrentTab}}function tr(e){const t=e.split("/")[1].toLowerCase();if(!Fs.includes(t))throw Error("Video codec not supported: ".concat(t));return t}function ir(e){const t=[];return e.forEach((e=>{void 0!==e.track&&t.push(new Lt({cid:e.track.mediaStreamID,track:e.trackInfo}))})),t}function nr(e){return e instanceof Hs?{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?nr(e.track):{})}}!function(e){let t,i,n;!function(e){e.Audio="audio",e.Video="video",e.Unknown="unknown"}(t=e.Kind||(e.Kind={})),function(e){e.Camera="camera",e.Microphone="microphone",e.ScreenShare="screen_share",e.ScreenShareAudio="screen_share_audio",e.Unknown="unknown"}(i=e.Source||(e.Source={})),function(e){e.Active="active",e.Paused="paused",e.Unknown="unknown"}(n=e.StreamState||(e.StreamState={})),e.kindToProto=function(e){switch(e){case t.Audio:return Ke.AUDIO;case t.Video:return Ke.VIDEO;default:return Ke.DATA}},e.kindFromProto=function(e){switch(e){case Ke.AUDIO:return t.Audio;case Ke.VIDEO:return t.Video;default:return t.Unknown}},e.sourceToProto=function(e){switch(e){case i.Camera:return We.CAMERA;case i.Microphone:return We.MICROPHONE;case i.ScreenShare:return We.SCREEN_SHARE;case i.ScreenShareAudio:return We.SCREEN_SHARE_AUDIO;default:return We.UNKNOWN}},e.sourceFromProto=function(e){switch(e){case We.CAMERA:return i.Camera;case We.MICROPHONE:return i.Microphone;case We.SCREEN_SHARE:return i.ScreenShare;case We.SCREEN_SHARE_AUDIO:return i.ScreenShareAudio;default:return i.Unknown}},e.streamStateFromProto=function(e){switch(e){case Pt.ACTIVE:return n.Active;case Pt.PAUSED:return n.Paused;default:return n.Unknown}}}(Hs||(Hs={}));const sr="https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension";function rr(e){return Di(this,void 0,void 0,(function*(){return new Promise((t=>Ls.setTimeout(t,e)))}))}function or(){return"addTransceiver"in RTCPeerConnection.prototype}function ar(){return"addTrack"in RTCPeerConnection.prototype}function cr(){if(!("getCapabilities"in RTCRtpSender))return!1;if(mr())return!1;const e=RTCRtpSender.getCapabilities("video");let t=!1;if(e)for(const i of e.codecs)if("video/AV1"===i.mimeType){t=!0;break}return t}function dr(){if(!("getCapabilities"in RTCRtpSender))return!1;if(pr())return!1;if(mr()){const e=Ds();if((null==e?void 0:e.version)&&Sr(e.version,"16")<0)return!1}const e=RTCRtpSender.getCapabilities("video");let t=!1;if(e)for(const i of e.codecs)if("video/VP9"===i.mimeType){t=!0;break}return t}function lr(e){return"av1"===e||"vp9"===e}function ur(e){return!!document&&(e||(e=document.createElement("audio")),"setSinkId"in e)}function hr(){return"undefined"!=typeof RTCPeerConnection&&(or()||ar())}function pr(){var e;return"Firefox"===(null===(e=Ds())||void 0===e?void 0:e.name)}function mr(){var e;return"Safari"===(null===(e=Ds())||void 0===e?void 0:e.name)}function gr(){const e=Ds();return"Safari"===(null==e?void 0:e.name)&&e.version.startsWith("17.")}function fr(){var e,t;return!!vr()&&(null!==(t=null===(e=navigator.userAgentData)||void 0===e?void 0:e.mobile)&&void 0!==t?t:/Tablet|iPad|Mobile|Android|BlackBerry/.test(navigator.userAgent))}function vr(){return"undefined"!=typeof document}function kr(){return"ReactNative"==navigator.product}function br(e){return e.hostname.endsWith(".livekit.cloud")||e.hostname.endsWith(".livekit.run")}function yr(){if(global&&global.LiveKitReactNativeGlobal)return global.LiveKitReactNativeGlobal}function Tr(){if(!kr())return;let e=yr();return e?e.platform:void 0}function Cr(){if(vr())return window.devicePixelRatio;if(kr()){let e=yr();if(e)return e.devicePixelRatio}return 1}function Sr(e,t){const i=e.split("."),n=t.split("."),s=Math.min(i.length,n.length);for(let e=0;e<s;++e){const t=parseInt(i[e],10),r=parseInt(n[e],10);if(t>r)return 1;if(t<r)return-1;if(e===s-1&&t===r)return 0}return""===e&&""!==t?-1:""===t?1:i.length==n.length?0:i.length<n.length?-1:1}function Er(e){for(const t of e)t.target.handleResize(t)}function wr(e){for(const t of e)t.target.handleVisibilityChanged(t)}let Pr=null;const Rr=()=>(Pr||(Pr=new ResizeObserver(Er)),Pr);let Ir=null;const Or=()=>(Ir||(Ir=new IntersectionObserver(wr,{root:null,rootMargin:"0px"})),Ir);let xr,Dr;function Mr(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:16,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:16,i=arguments.length>2&&void 0!==arguments[2]&&arguments[2],n=arguments.length>3&&void 0!==arguments[3]&&arguments[3];const s=document.createElement("canvas");s.width=e,s.height=t;const r=s.getContext("2d");null==r||r.fillRect(0,0,s.width,s.height),n&&r&&(r.beginPath(),r.arc(e/2,t/2,50,0,2*Math.PI,!0),r.closePath(),r.fillStyle="grey",r.fill());const o=s.captureStream(),[a]=o.getTracks();if(!a)throw Error("Could not get empty media stream video track");return a.enabled=i,a}function Nr(){if(!Dr){const e=new AudioContext,t=e.createOscillator(),i=e.createGain();i.gain.setValueAtTime(0,0);const n=e.createMediaStreamDestination();if(t.connect(i),i.connect(n),t.start(),[Dr]=n.stream.getAudioTracks(),!Dr)throw Error("Could not get empty media stream audio track");Dr.enabled=!1}return Dr.clone()}class _r{constructor(e,t){this.onFinally=t,this.promise=new Promise(((t,i)=>Di(this,void 0,void 0,(function*(){this.resolve=t,this.reject=i,e&&(yield e(t,i))})))).finally((()=>{var e;return null===(e=this.onFinally)||void 0===e?void 0:e.call(this)}))}}class Ar{constructor(){this._locking=Promise.resolve(),this._locks=0}isLocked(){return this._locks>0}lock(){let e;this._locks+=1;const t=new Promise((t=>e=()=>{this._locks-=1,t()})),i=this._locking.then((()=>e));return this._locking=this._locking.then((()=>t)),i}}function Lr(e){if("string"==typeof e||"number"==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 Ur(e){return e.startsWith("ws")?e.replace(/^(ws)/,"http"):e}const jr="default";class Fr{static getInstance(){return void 0===this.instance&&(this.instance=new Fr),this.instance}getDevices(e){return Di(this,arguments,void 0,(function(e){var t=this;let i=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return function*(){var n;if((null===(n=Fr.userMediaPromiseMap)||void 0===n?void 0:n.size)>0){Ei.debug("awaiting getUserMedia promise");try{e?yield Fr.userMediaPromiseMap.get(e):yield Promise.all(Fr.userMediaPromiseMap.values())}catch(e){Ei.warn("error waiting for media permissons")}}let s=yield navigator.mediaDevices.enumerateDevices();if(i&&(!mr()||!t.hasDeviceInUse(e))){if(0===s.filter((t=>t.kind===e)).length||s.some((t=>{const i=""===t.label,n=!e||t.kind===e;return i&&n}))){const t={video:"audioinput"!==e&&"audiooutput"!==e,audio:"videoinput"!==e},i=yield navigator.mediaDevices.getUserMedia(t);s=yield navigator.mediaDevices.enumerateDevices(),i.getTracks().forEach((e=>{e.stop()}))}}return e&&(s=s.filter((t=>t.kind===e))),s}()}))}normalizeDeviceId(e,t,i){return Di(this,void 0,void 0,(function*(){if(t!==jr)return t;const n=yield this.getDevices(e),s=n.find((e=>e.deviceId===jr));if(!s)return void Ei.warn("could not reliably determine default device");const r=n.find((e=>e.deviceId!==jr&&e.groupId===(null!=i?i:s.groupId)));if(r)return null==r?void 0:r.deviceId;Ei.warn("could not reliably determine default device")}))}hasDeviceInUse(e){return e?Fr.userMediaPromiseMap.has(e):Fr.userMediaPromiseMap.size>0}}Fr.mediaDeviceKinds=["audioinput","audiooutput","videoinput"],Fr.userMediaPromiseMap=new Map;class Br extends Hs{get sender(){return this._sender}set sender(e){this._sender=e}get constraints(){return this._constraints}constructor(t,i,n){let s=arguments.length>3&&void 0!==arguments[3]&&arguments[3];super(t,i,arguments.length>4?arguments[4]:void 0),this.manuallyStopped=!1,this._isUpstreamPaused=!1,this.handleTrackMuteEvent=()=>this.debouncedTrackMuteHandler().catch((()=>this.log.debug("track mute bounce got cancelled by an unmute event",this.logContext))),this.debouncedTrackMuteHandler=Is((()=>Di(this,void 0,void 0,(function*(){yield this.pauseUpstream()}))),5e3),this.handleTrackUnmuteEvent=()=>Di(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 Ar,this.pauseUpstreamLock=new Ar,this.processorLock=new Ar,this.restartLock=new Ar,this.setMediaStreamTrack(t,!0),this._constraints=t.getConstraints(),n&&(this._constraints=n)}get id(){return this._mediaStreamTrack.id}get dimensions(){if(this.kind!==Hs.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 Di(this,void 0,void 0,(function*(){if(e===this._mediaStreamTrack&&!t)return;let i;if(this._mediaStreamTrack&&(this.attachedElements.forEach((e=>{Qs(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&&(Js(e,this.processorElement),this.processorElement.muted=!0),yield this.processor.restart({track:e,kind:this.kind,element:this.processorElement}),i=this.processor.processedTrack}finally{t()}}this.sender&&(yield this.sender.replaceTrack(null!=i?i: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=>{Js(null!=i?i:e,t)})))}))}waitForDimensions(){return Di(this,arguments,void 0,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1e3;return function*(){var i;if(e.kind===Hs.Kind.Audio)throw new Error("cannot get dimensions for audio tracks");"iOS"===(null===(i=Ds())||void 0===i?void 0:i.os)&&(yield rr(10));const n=Date.now();for(;Date.now()-n<t;){const t=e.dimensions;if(t)return t;yield rr(50)}throw new vs("unable to get track dimensions after timeout")}()}))}getDeviceId(){return Di(this,arguments,void 0,(function(){var e=this;let t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return function*(){if(e.source===Hs.Source.ScreenShare)return;const{deviceId:i,groupId:n}=e._mediaStreamTrack.getSettings(),s=e.kind===Hs.Kind.Audio?"audioinput":"videoinput";return t?Fr.getInstance().normalizeDeviceId(s,i,n):i}()}))}mute(){return Di(this,void 0,void 0,(function*(){return this.setTrackMuted(!0),this}))}unmute(){return Di(this,void 0,void 0,(function*(){return this.setTrackMuted(!1),this}))}replaceTrack(e,t){return Di(this,void 0,void 0,(function*(){if(!this.sender)throw new vs("unable to replace an unpublished track");let i,n;return"boolean"==typeof t?i=t:void 0!==t&&(i=t.userProvidedTrack,n=t.stopProcessor),this.providedByUser=null==i||i,this.log.debug("replace MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(e),n&&this.processor&&(yield this.stopProcessor()),this}))}restart(t){return Di(this,void 0,void 0,(function*(){this.manuallyStopped=!1;const i=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 i={audio:!1,video:!1};this.kind===Hs.Kind.Video?i.video=t:i.audio=t,this.attachedElements.forEach((e=>{Qs(this.mediaStreamTrack,e)})),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.stop();const n=(yield navigator.mediaDevices.getUserMedia(i)).getTracks()[0];return n.addEventListener("ended",this.handleEnded),this.log.debug("re-acquired MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(n),this._constraints=t,this.emit(e.TrackEvent.Restarted,this),this.manuallyStopped&&(this.log.warn("track was stopped during a restart, stopping restarted track",this.logContext),this.stop()),this}finally{i()}}))}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 Di(this,void 0,void 0,(function*(){yield e.handleAppVisibilityChanged.call(this),fr()&&(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;this.manuallyStopped=!0,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 Di(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=Ds();if("Safari"===(null==t?void 0:t.name)&&Sr(t.version,"12.0")<0)throw new fs("pauseUpstream is not supported on Safari < 12.");yield this.sender.replaceTrack(null)}finally{t()}}))}resumeUpstream(){return Di(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(){return Di(this,void 0,void 0,(function*(){var e;if(!(null===(e=this.sender)||void 0===e?void 0:e.getStats))return;return yield this.sender.getStats()}))}setProcessor(t){return Di(this,arguments,void 0,(function(t){var i=this;let n=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return function*(){var s;const r=yield i.processorLock.lock();try{i.log.debug("setting up processor",i.logContext);const r=document.createElement(i.kind),o={kind:i.kind,track:i._mediaStreamTrack,element:r,audioContext:i.audioContext};if(yield t.init(o),i.log.debug("processor initialized",i.logContext),i.processor&&(yield i.stopProcessor()),"unknown"===i.kind)throw TypeError("cannot set processor on track of unknown kind");if(Js(i._mediaStreamTrack,r),r.muted=!0,r.play().catch((e=>i.log.error("failed to play processor element",Object.assign(Object.assign({},i.logContext),{error:e})))),i.processor=t,i.processorElement=r,i.processor.processedTrack){for(const e of i.attachedElements)e!==i.processorElement&&n&&(Qs(i._mediaStreamTrack,e),Js(i.processor.processedTrack,e));yield null===(s=i.sender)||void 0===s?void 0:s.replaceTrack(i.processor.processedTrack)}i.emit(e.TrackEvent.TrackProcessorUpdate,i.processor)}finally{r()}}()}))}getProcessor(){return this.processor}stopProcessor(){return Di(this,arguments,void 0,(function(){var t=this;let i=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return function*(){var n,s;t.processor&&(t.log.debug("stopping processor",t.logContext),null===(n=t.processor.processedTrack)||void 0===n||n.stop(),yield t.processor.destroy(),t.processor=void 0,i||(null===(s=t.processorElement)||void 0===s||s.remove(),t.processorElement=void 0),yield t._mediaStreamTrack.applyConstraints(t._constraints),yield t.setMediaStreamTrack(t._mediaStreamTrack,!0),t.emit(e.TrackEvent.TrackProcessorUpdate))}()}))}}class Vr extends Yi.EventEmitter{constructor(t){super(),this.onWorkerMessage=t=>{var i,n;const{kind:s,data:r}=t.data;switch(s){case"error":Ei.error(r.error.message),this.emit(e.EncryptionEvent.EncryptionError,r.error);break;case"initAck":r.enabled&&this.keyProvider.getKeys().forEach((e=>{this.postKey(e)}));break;case"enable":if(this.encryptionEnabled!==r.enabled&&r.participantIdentity===(null===(i=this.room)||void 0===i?void 0:i.localParticipant.identity))this.emit(e.EncryptionEvent.ParticipantEncryptionStatusChanged,r.enabled,this.room.localParticipant),this.encryptionEnabled=r.enabled;else if(r.participantIdentity){const t=null===(n=this.room)||void 0===n?void 0:n.getParticipantByIdentity(r.participantIdentity);if(!t)throw TypeError("couldn't set encryption status, participant not found".concat(r.participantIdentity));this.emit(e.EncryptionEvent.ParticipantEncryptionStatusChanged,r.enabled,t)}this.encryptionEnabled&&this.keyProvider.getKeys().forEach((e=>{this.postKey(e)}));break;case"ratchetKey":this.keyProvider.emit(e.KeyProviderEvent.KeyRatcheted,r.material,r.keyIndex)}},this.onWorkerError=t=>{Ei.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(!as())throw new fs("tried to setup end-to-end encryption on an unsupported browser");if(Ei.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:Ri.getLevel()}};this.worker&&(Ei.info("initializing worker",{worker:this.worker}),this.worker.onmessage=this.onWorkerMessage,this.worker.onerror=this.onWorkerError,this.worker.postMessage(t))}}setParticipantCryptorEnabled(e,t){Ei.debug("set e2ee to ".concat(e," for participant ").concat(t)),this.postEnable(e,t)}setSifTrailer(e){e&&0!==e.length?this.postSifTrailer(e):Ei.warn("ignoring server sent trailer as it's empty")}setupEngine(t){t.on(e.EngineEvent.RTPVideoMapUpdate,(e=>{this.postRTPMap(e)}))}setupEventListeners(t,i){t.on(e.RoomEvent.TrackPublished,((e,t)=>this.setParticipantCryptorEnabled(e.trackInfo.encryption!==st.NONE,t.identity))),t.on(e.RoomEvent.ConnectionStateChanged,(i=>{i===e.ConnectionState.Connected&&t.remoteParticipants.forEach((e=>{e.trackPublications.forEach((t=>{this.setParticipantCryptorEnabled(t.trackInfo.encryption!==st.NONE,e.identity)}))}))})).on(e.RoomEvent.TrackUnsubscribed,((e,t,i)=>{var n;const s={kind:"removeTransform",data:{participantIdentity:i.identity,trackId:e.mediaStreamID}};null===(n=this.worker)||void 0===n||n.postMessage(s)})).on(e.RoomEvent.TrackSubscribed,((e,t,i)=>{this.setupE2EEReceiver(e,i.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),i.getKeys().forEach((e=>{this.postKey(e)}))})),t.localParticipant.on(e.ParticipantEvent.LocalTrackPublished,(e=>Di(this,void 0,void 0,(function*(){this.setupE2EESender(e.track,e.track.sender)})))),i.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 i={kind:"ratchetRequest",data:{participantIdentity:e,keyIndex:t}};this.worker.postMessage(i)}postKey(e){let{key:t,participantIdentity:i,keyIndex:n}=e;var s;if(!this.worker)throw Error("could not set key, worker is missing");const r={kind:"setKey",data:{participantIdentity:i,isPublisher:i===(null===(s=this.room)||void 0===s?void 0:s.localParticipant.identity),key:t,keyIndex:n}};this.worker.postMessage(r)}postEnable(e,t){if(!this.worker)throw new ReferenceError("failed to enable e2ee, worker is not ready");{const i={kind:"enable",data:{enabled:e,participantIdentity:t}};this.worker.postMessage(i)}}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 i={kind:"setRTPMap",data:{map:e,participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(i)}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,i){if(e.receiver){if(!(null==i?void 0:i.mimeType)||""===i.mimeType)throw new TypeError("MimeType missing from trackInfo, cannot set up E2EE cryptor");this.handleReceiver(e.receiver,e.mediaStreamID,t,"video"===e.kind?tr(i.mimeType):void 0)}}setupE2EESender(e,t){e instanceof Br&&t?this.handleSender(t,e.mediaStreamID,void 0):t||Ei.warn("early return because sender is not ready")}handleReceiver(e,t,i,n){return Di(this,void 0,void 0,(function*(){if(this.worker){if(cs()){const s={kind:"decode",participantIdentity:i,trackId:t,codec:n};e.transform=new RTCRtpScriptTransform(this.worker,s)}else{if(ns in e&&n){const e={kind:"updateCodec",data:{trackId:t,codec:n,participantIdentity:i}};return void this.worker.postMessage(e)}let s=e.writableStream,r=e.readableStream;if(!s||!r){const t=e.createEncodedStreams();e.writableStream=t.writable,s=t.writable,e.readableStream=t.readable,r=t.readable}const o={kind:"decode",data:{readableStream:r,writableStream:s,trackId:t,codec:n,participantIdentity:i}};this.worker.postMessage(o,[r,s])}e[ns]=!0}}))}handleSender(e,t,i){var n;if(!(ns in e)&&this.worker){if(!(null===(n=this.room)||void 0===n?void 0:n.localParticipant.identity)||""===this.room.localParticipant.identity)throw TypeError("local identity needs to be known in order to set up encrypted sender");if(cs()){Ei.info("initialize script transform");const n={kind:"encode",participantIdentity:this.room.localParticipant.identity,trackId:t,codec:i};e.transform=new RTCRtpScriptTransform(this.worker,n)}else{Ei.info("initialize encoded streams");const n=e.createEncodedStreams(),s={kind:"encode",data:{readableStream:n.readable,writableStream:n.writable,codec:i,trackId:t,participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(s,[n.readable,n.writable])}e[ns]=!0}}}var qr;!function(e){e[e.WAITING=0]="WAITING",e[e.RUNNING=1]="RUNNING",e[e.COMPLETED=2]="COMPLETED"}(qr||(qr={}));class Kr{constructor(){this.pendingTasks=new Map,this.taskMutex=new Ar,this.nextTaskIndex=0}run(e){return Di(this,void 0,void 0,(function*(){const t={id:this.nextTaskIndex++,enqueuedAt:Date.now(),status:qr.WAITING};this.pendingTasks.set(t.id,t);const i=yield this.taskMutex.lock();try{return t.executedAt=Date.now(),t.status=qr.RUNNING,yield e()}finally{t.status=qr.COMPLETED,this.pendingTasks.delete(t.id),i()}}))}flush(){return Di(this,void 0,void 0,(function*(){return this.run((()=>Di(this,void 0,void 0,(function*(){}))))}))}snapshot(){return Array.from(this.pendingTasks.values())}}const Wr=["syncState","trickle","offer","answer","simulate","leave"];var Gr;!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"}(Gr||(Gr={}));class Hr{get currentState(){return this.state}get isDisconnected(){return this.state===Gr.DISCONNECTING||this.state===Gr.DISCONNECTED}get isEstablishingConnection(){return this.state===Gr.CONNECTING||this.state===Gr.RECONNECTING}getNextRequestId(){return this._requestId+=1,this._requestId}constructor(){let t=arguments.length>0&&void 0!==arguments[0]&&arguments[0],i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};var n;this.rtt=0,this.state=Gr.DISCONNECTED,this.log=Ei,this._requestId=0,this.resetCallbacks=()=>{this.onAnswer=void 0,this.onLeave=void 0,this.onLocalTrackPublished=void 0,this.onLocalTrackUnpublished=void 0,this.onNegotiateRequested=void 0,this.onOffer=void 0,this.onRemoteMuteChanged=void 0,this.onSubscribedQualityUpdate=void 0,this.onTokenRefresh=void 0,this.onTrickle=void 0,this.onClose=void 0},this.log=Pi(null!==(n=i.loggerName)&&void 0!==n?n:e.LoggerNames.Signal),this.loggerContextCb=i.loggerContextCb,this.useJSON=t,this.requestQueue=new Kr,this.queuedRequests=[],this.closingLock=new Ar,this.connectionLock=new Ar,this.state=Gr.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,i,n){return Di(this,void 0,void 0,(function*(){this.state=Gr.CONNECTING,this.options=i;return yield this.connect(e,t,i,n)}))}reconnect(e,t,i,n){return Di(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=Gr.RECONNECTING,this.clearPingInterval();return yield this.connect(e,t,Object.assign(Object.assign({},this.options),{reconnect:!0,sid:i,reconnectReason:n}))}))}connect(e,t,i,n){this.connectOptions=i,e=(e=function(e){return e.startsWith("http")?e.replace(/^(http)/,"ws"):e}(e)).replace(/\/$/,""),e+="/rtc";const s=function(e,t,i){var n;const s=new URLSearchParams;s.set("access_token",e),i.reconnect&&(s.set("reconnect","1"),i.sid&&s.set("sid",i.sid));s.set("auto_subscribe",i.autoSubscribe?"1":"0"),s.set("sdk",kr()?"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);i.adaptiveStream&&s.set("adaptive_stream","1");i.reconnectReason&&s.set("reconnect_reason",i.reconnectReason.toString());(null===(n=navigator.connection)||void 0===n?void 0:n.type)&&s.set("network",navigator.connection.type);return"?".concat(s.toString())}(t,function(){var e;const t=new bt({sdk:yt.JS,protocol:15,version:As});return kr()&&(t.os=null!==(e=Tr())&&void 0!==e?e:""),t}(),i);return new Promise(((t,r)=>Di(this,void 0,void 0,(function*(){const o=yield this.connectionLock.lock();try{const o=()=>Di(this,void 0,void 0,(function*(){this.close(),clearTimeout(a),r(new gs("room connection has been cancelled (signal)"))})),a=setTimeout((()=>{this.close(),r(new gs("room connection has timed out (signal)"))}),i.websocketTimeout);(null==n?void 0:n.aborted)&&o(),null==n||n.addEventListener("abort",o),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(a)},this.ws.onerror=t=>Di(this,void 0,void 0,(function*(){if(this.state===Gr.CONNECTED)this.handleWSError(t);else{this.state=Gr.DISCONNECTED,clearTimeout(a);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();r(new gs(e,0,t.status))}else r(new gs("Internal error",2,t.status))}catch(e){r(new gs("server was not reachable",1))}}})),this.ws.onmessage=e=>Di(this,void 0,void 0,(function*(){var s,a,c;let d;if("string"==typeof e.data){const t=JSON.parse(e.data);d=Ot.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=Ot.fromBinary(new Uint8Array(e.data))}if(this.state!==Gr.CONNECTED){let e=!1;if("join"===(null===(s=d.message)||void 0===s?void 0:s.case)?(this.state=Gr.CONNECTED,null==n||n.removeEventListener("abort",o),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===Gr.RECONNECTING&&"leave"!==d.message.case?(this.state=Gr.CONNECTED,null==n||n.removeEventListener("abort",o),this.startPingInterval(),"reconnect"===(null===(a=d.message)||void 0===a?void 0:a.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?r(new gs("Received leave request while trying to (re)connect",4)):i.reconnect||r(new gs("did not receive join response, got ".concat(null===(c=d.message)||void 0===c?void 0:c.case," instead"))),!e)return}this.signalLatency&&(yield rr(this.signalLatency)),this.handleSignalResponse(d)})),this.ws.onclose=e=>{this.isEstablishingConnection&&r(new gs("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{o()}}))))}close(){return Di(this,arguments,void 0,(function(){var e=this;let t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return function*(){const i=yield e.closingLock.lock();try{if(e.clearPingInterval(),t&&(e.state=Gr.DISCONNECTING),e.ws){e.ws.onmessage=null,e.ws.onopen=null,e.ws.onclose=null;const t=new Promise((t=>{e.ws?e.ws.onclose=()=>{t()}:t()}));e.ws.readyState<e.ws.CLOSING&&(e.ws.close(),yield Promise.race([t,rr(250)])),e.ws=void 0}}finally{t&&(e.state=Gr.DISCONNECTED),i()}}()}))}sendOffer(e){this.log.debug("sending offer",Object.assign(Object.assign({},this.logContext),{offerSdp:e.sdp})),this.sendRequest({case:"offer",value:Qr(e)})}sendAnswer(e){return this.log.debug("sending answer",Object.assign(Object.assign({},this.logContext),{answerSdp:e.sdp})),this.sendRequest({case:"answer",value:Qr(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 Mt({candidateInit:JSON.stringify(e),target:t})})}sendMuteTrack(e,t){return this.sendRequest({case:"mute",value:new Nt({sid:e,muted:t})})}sendAddTrack(e){return this.sendRequest({case:"addTrack",value:e})}sendUpdateLocalMetadata(e,t){return Di(this,arguments,void 0,(function(e,t){var i=this;let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return function*(){const s=i.getNextRequestId();return yield i.sendRequest({case:"updateMetadata",value:new Jt({requestId:s,metadata:e,name:t,attributes:n})}),s}()}))}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 Ht({trackSid:e,layers:t})})}sendUpdateSubscriptionPermissions(e,t){return this.sendRequest({case:"subscriptionPermission",value:new ri({allParticipants:e,trackPermissions:t})})}sendSimulateScenario(e){return this.sendRequest({case:"simulate",value:e})}sendPing(){return Promise.all([this.sendRequest({case:"ping",value:I.parse(Date.now())}),this.sendRequest({case:"pingReq",value:new li({timestamp:I.parse(Date.now()),rtt:I.parse(this.rtt)})})])}sendUpdateLocalAudioTrack(e,t){return this.sendRequest({case:"updateAudioTrack",value:new qt({trackSid:e,features:t})})}sendLeave(){return this.sendRequest({case:"leave",value:new Wt({reason:Qe.CLIENT_INITIATED,action:Gt.DISCONNECT})})}sendRequest(e){return Di(this,arguments,void 0,(function(e){var t=this;let i=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return function*(){const n=!i&&!function(e){const t=Wr.indexOf(e.case)>=0;return Ei.trace("request allowed to bypass queue:",{canPass:t,req:e}),t}(e);if(n&&t.state===Gr.RECONNECTING)return void t.queuedRequests.push((()=>Di(t,void 0,void 0,(function*(){yield this.sendRequest(e,!0)}))));if(i||(yield t.requestQueue.flush()),t.signalLatency&&(yield rr(t.signalLatency)),!t.ws||t.ws.readyState!==t.ws.OPEN)return void t.log.error("cannot send signal request before connected, type: ".concat(null==e?void 0:e.case),t.logContext);const s=new It({message:e});try{t.useJSON?t.ws.send(s.toJsonString()):t.ws.send(s.toBinary())}catch(e){t.log.error("error sending signal message",Object.assign(Object.assign({},t.logContext),{error:e}))}}()}))}handleSignalResponse(e){var t,i;const n=e.message;if(null==n)return void this.log.debug("received unsupported message",this.logContext);let s=!1;if("answer"===n.case){const e=Jr(n.value);this.onAnswer&&this.onAnswer(e)}else if("offer"===n.case){const e=Jr(n.value);this.onOffer&&this.onOffer(e)}else if("trickle"===n.case){const e=JSON.parse(n.value.candidateInit);this.onTrickle&&this.onTrickle(e,n.value.target)}else"update"===n.case?this.onParticipantUpdate&&this.onParticipantUpdate(null!==(t=n.value.participants)&&void 0!==t?t:[]):"trackPublished"===n.case?this.onLocalTrackPublished&&this.onLocalTrackPublished(n.value):"speakersChanged"===n.case?this.onSpeakersChanged&&this.onSpeakersChanged(null!==(i=n.value.speakers)&&void 0!==i?i:[]):"leave"===n.case?this.onLeave&&this.onLeave(n.value):"mute"===n.case?this.onRemoteMuteChanged&&this.onRemoteMuteChanged(n.value.sid,n.value.muted):"roomUpdate"===n.case?this.onRoomUpdate&&n.value.room&&this.onRoomUpdate(n.value.room):"connectionQuality"===n.case?this.onConnectionQuality&&this.onConnectionQuality(n.value):"streamStateUpdate"===n.case?this.onStreamStateUpdate&&this.onStreamStateUpdate(n.value):"subscribedQualityUpdate"===n.case?this.onSubscribedQualityUpdate&&this.onSubscribedQualityUpdate(n.value):"subscriptionPermissionUpdate"===n.case?this.onSubscriptionPermissionUpdate&&this.onSubscriptionPermissionUpdate(n.value):"refreshToken"===n.case?this.onTokenRefresh&&this.onTokenRefresh(n.value):"trackUnpublished"===n.case?this.onLocalTrackUnpublished&&this.onLocalTrackUnpublished(n.value):"subscriptionResponse"===n.case?this.onSubscriptionError&&this.onSubscriptionError(n.value):"pong"===n.case||("pongResp"===n.case?(this.rtt=Date.now()-Number.parseInt(n.value.lastPingTimestamp.toString()),this.resetPingTimeout(),s=!0):"requestResponse"===n.case?this.onRequestResponse&&this.onRequestResponse(n.value):"trackSubscribed"===n.case?this.onLocalTrackSubscribed&&this.onLocalTrackSubscribed(n.value.trackSid):this.log.debug("unsupported message",Object.assign(Object.assign({},this.logContext),{msgCase:n.case})));s||this.resetPingTimeout()}setReconnected(){for(;this.queuedRequests.length>0;){const e=this.queuedRequests.shift();e&&this.requestQueue.run(e)}}handleOnClose(e){return Di(this,void 0,void 0,(function*(){if(this.state===Gr.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=Ls.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&&Ls.clearTimeout(this.pingTimeout)}startPingInterval(){this.clearPingInterval(),this.resetPingTimeout(),this.pingIntervalDuration?(this.log.debug("start ping interval",this.logContext),this.pingInterval=Ls.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&&Ls.clearInterval(this.pingInterval)}}function Jr(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 Qr(e){return new jt({sdp:e.sdp,type:e.type})}var zr={},Yr={exports:{}},Xr=Yr.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(Xr).forEach((function(e){Xr[e].forEach((function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")}))}));var $r=Yr.exports;!function(e){var t=function(e){return String(Number(e))===e?Number(e):e},i=function(e,i,n){var s=e.name&&e.names;e.push&&!i[e.push]?i[e.push]=[]:s&&!i[e.name]&&(i[e.name]={});var r=e.push?{}:s?i[e.name]:i;!function(e,i,n,s){if(s&&!n)i[s]=t(e[1]);else for(var r=0;r<n.length;r+=1)null!=e[r+1]&&(i[n[r]]=t(e[r+1]))}(n.match(e.reg),r,e.names,e.name),e.push&&i[e.push].push(r)},n=$r,s=RegExp.prototype.test.bind(/^([a-z])=(.*)/);e.parse=function(e){var t={},r=[],o=t;return e.split(/(\r\n|\r|\n)/).filter(s).forEach((function(e){var t=e[0],s=e.slice(2);"m"===t&&(r.push({rtp:[],fmtp:[]}),o=r[r.length-1]);for(var a=0;a<(n[t]||[]).length;a+=1){var c=n[t][a];if(c.reg.test(s))return i(c,o,s)}})),t.media=r,t};var r=function(e,i){var n=i.split(/=(.+)/,2);return 2===n.length?e[n[0]]=t(n[1]):1===n.length&&i.length>1&&(e[n[0]]=void 0),e};e.parseParams=function(e){return e.split(/;\s?/).reduce(r,{})},e.parseFmtpConfig=e.parseParams,e.parsePayloads=function(e){return e.toString().split(" ").map(Number)},e.parseRemoteCandidates=function(e){for(var i=[],n=e.split(" ").map(t),s=0;s<n.length;s+=3)i.push({component:n[s],ip:n[s+1],port:n[s+2]});return i},e.parseImageAttributes=function(e){return e.split(" ").map((function(e){return e.substring(1,e.length-1).split(",").reduce(r,{})}))},e.parseSimulcastStreamList=function(e){return e.split(";").map((function(e){return e.split(",").map((function(e){var i,n=!1;return"~"!==e[0]?i=t(e):(i=t(e.substring(1,e.length)),n=!0),{scid:i,paused:n}}))}))}}(zr);var Zr=$r,eo=/%[sdv%]/g,to=function(e){var t=1,i=arguments,n=i.length;return e.replace(eo,(function(e){if(t>=n)return e;var s=i[t];switch(t+=1,e){case"%%":return"%";case"%s":return String(s);case"%d":return Number(s);case"%v":return""}}))},io=function(e,t,i){var n=[e+"="+(t.format instanceof Function?t.format(t.push?i:i[t.name]):t.format)];if(t.names)for(var s=0;s<t.names.length;s+=1){var r=t.names[s];t.name?n.push(i[t.name][r]):n.push(i[t.names[s]])}else n.push(i[t.name]);return to.apply(null,n)},no=["v","o","s","i","u","e","p","c","b","t","r","z","a"],so=["i","c","b","a"],ro=zr,oo=function(e,t){t=t||{},null==e.version&&(e.version=0),null==e.name&&(e.name=" "),e.media.forEach((function(e){null==e.payloads&&(e.payloads="")}));var i=t.outerOrder||no,n=t.innerOrder||so,s=[];return i.forEach((function(t){Zr[t].forEach((function(i){i.name in e&&null!=e[i.name]?s.push(io(t,i,e)):i.push in e&&null!=e[i.push]&&e[i.push].forEach((function(e){s.push(io(t,i,e))}))}))})),e.media.forEach((function(e){s.push(io("m",Zr.m[0],e)),n.forEach((function(t){Zr[t].forEach((function(i){i.name in e&&null!=e[i.name]?s.push(io(t,i,e)):i.push in e&&null!=e[i.push]&&e[i.push].forEach((function(e){s.push(io(t,i,e))}))}))}))})),s.join("\r\n")+"\r\n"},ao=oo,co=ro.parse;const lo="negotiationStarted",uo="negotiationComplete",ho="rtpVideoPayloadTypes";class po extends Yi.EventEmitter{get pc(){return this._pc||(this._pc=this.createPC()),this._pc}constructor(t){let i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};var n;super(),this.log=Ei,this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate=!1,this.trackBitrates=[],this.remoteStereoMids=[],this.remoteNackMids=[],this.negotiate=Is((e=>Di(this,void 0,void 0,(function*(){this.emit(lo);try{yield this.createAndSendOffer()}catch(t){if(!e)throw t;e(t)}}))),20),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=Pi(null!==(n=i.loggerName)&&void 0!==n?n:e.LoggerNames.PCTransport),this.loggerOptions=i,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 Di(this,void 0,void 0,(function*(){if(this.pc.remoteDescription&&!this.restartingIce)return this.pc.addIceCandidate(e);this.pendingCandidates.push(e)}))}setRemoteDescription(e){return Di(this,void 0,void 0,(function*(){var t;let i;if("offer"===e.type){let{stereoMids:t,nackMids:i}=function(e){var t;const i=[],n=[],s=co(null!==(t=e.sdp)&&void 0!==t?t:"");let r=0;return s.media.forEach((e=>{var t;"audio"===e.type&&(e.rtp.some((e=>"opus"===e.codec&&(r=e.payload,!0))),(null===(t=e.rtcpFb)||void 0===t?void 0:t.some((e=>e.payload===r&&"nack"===e.type)))&&n.push(e.mid),e.fmtp.some((t=>t.payload===r&&(t.config.includes("sprop-stereo=1")&&i.push(e.mid),!0))))})),{stereoMids:i,nackMids:n}}(e);this.remoteStereoMids=t,this.remoteNackMids=i}else if("answer"===e.type){const n=co(null!==(t=e.sdp)&&void 0!==t?t:"");n.media.forEach((e=>{"audio"===e.type&&this.trackBitrates.some((t=>{if(!t.transceiver||e.mid!=t.transceiver.mid)return!1;let i=0;if(e.rtp.some((e=>e.codec.toUpperCase()===t.codec.toUpperCase()&&(i=e.payload,!0))),0===i)return!0;let n=!1;for(const s of e.fmtp)if(s.payload===i){s.config=s.config.split(";").filter((e=>!e.includes("maxaveragebitrate"))).join(";"),t.maxbr>0&&(s.config+=";maxaveragebitrate=".concat(1e3*t.maxbr)),n=!0;break}return n||t.maxbr>0&&e.fmtp.push({payload:i,config:"maxaveragebitrate=".concat(1e3*t.maxbr)}),!0}))})),i=ao(n)}if(yield this.setMungedSDP(e,i,!0),this.pendingCandidates.forEach((e=>{this.pc.addIceCandidate(e)})),this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate)this.renegotiate=!1,yield this.createAndSendOffer();else if("answer"===e.type&&(this.emit(uo),e.sdp)){co(e.sdp).media.forEach((e=>{"video"===e.type&&this.emit(ho,e.rtp)}))}}))}createAndSendOffer(e){return Di(this,void 0,void 0,(function*(){var t;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 i=yield this.pc.createOffer(e);this.log.debug("original offer",Object.assign({sdp:i.sdp},this.logContext));const n=co(null!==(t=i.sdp)&&void 0!==t?t:"");n.media.forEach((e=>{"audio"===e.type?mo(e,[],[]):"video"===e.type&&this.trackBitrates.some((t=>{if(!e.msid||!t.cid||!e.msid.includes(t.cid))return!1;let i=0;if(e.rtp.some((e=>e.codec.toUpperCase()===t.codec.toUpperCase()&&(i=e.payload,!0))),0===i)return!0;if(lr(t.codec)&&function(e){var t,i;let n=0;const s=null===(t=e.ext)||void 0===t?void 0:t.some((e=>e.uri===sr||(e.value>n&&(n=e.value),!1)));s||null===(i=e.ext)||void 0===i||i.push({value:n+1,uri:sr})}(e),"av1"!==t.codec)return!0;const n=Math.round(.7*t.maxbr);for(const t of e.fmtp)if(t.payload===i){t.config.includes("x-google-start-bitrate")||(t.config+=";x-google-start-bitrate=".concat(n));break}return!0}))})),yield this.setMungedSDP(i,ao(n)),this.onOffer(i)}))}createAndSetAnswer(){return Di(this,void 0,void 0,(function*(){var e;const t=yield this.pc.createAnswer(),i=co(null!==(e=t.sdp)&&void 0!==e?e:"");return i.media.forEach((e=>{"audio"===e.type&&mo(e,this.remoteStereoMids,this.remoteNackMids)})),yield this.setMungedSDP(t,ao(i)),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 bs("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 bs("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(){return Di(this,void 0,void 0,(function*(){var e;if(!this._pc)return;let t="";const i=new Map,n=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),i.set(e.id,e);break;case"remote-candidate":n.set(e.id,"".concat(e.address,":").concat(e.port))}})),""===t)return;const s=null===(e=i.get(t))||void 0===e?void 0:e.remoteCandidateId;return void 0!==s?n.get(s):void 0}))}setMungedSDP(e,t,i){return Di(this,void 0,void 0,(function*(){if(t){const n=e.sdp;e.sdp=t;try{return this.log.debug("setting munged ".concat(i?"remote":"local"," description"),this.logContext),void(i?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e))}catch(i){this.log.warn("not able to set ".concat(e.type,", falling back to unmodified sdp"),Object.assign(Object.assign({},this.logContext),{error:i,sdp:t})),e.sdp=n}}try{i?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e)}catch(t){let n="unknown error";t instanceof Error?n=t.message:"string"==typeof t&&(n=t);const s={error:n,sdp:e.sdp};throw!i&&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 ys(n)}}))}}function mo(e,t,i){let n=0;e.rtp.some((e=>"opus"===e.codec&&(n=e.payload,!0))),n>0&&(e.rtcpFb||(e.rtcpFb=[]),i.includes(e.mid)&&!e.rtcpFb.some((e=>e.payload===n&&"nack"===e.type))&&e.rtcpFb.push({payload:n,type:"nack"}),t.includes(e.mid)&&e.fmtp.some((e=>e.payload===n&&(e.config.includes("stereo=1")||(e.config+=";stereo=1"),!0))))}const go="vp8",fo={audioPreset:e.AudioPresets.music,dtx:!0,red:!0,forceStereo:!1,simulcast:!0,screenShareEncoding:Ws.h1080fps15.encoding,stopMicTrackOnMute:!1,videoCodec:go,backupCodec:!0},vo={autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0},ko={resolution:qs.h720.resolution},bo={adaptiveStream:!1,dynacast:!1,stopLocalTrackOnUnpublish:!0,reconnectPolicy:new xi,disconnectOnPageLeave:!0,webAudioMix:!1},yo={autoSubscribe:!0,maxRetries:1,peerConnectionTimeout:15e3,websocketTimeout:15e3};var To;!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"}(To||(To={}));class Co{get needsPublisher(){return this.isPublisherConnectionRequired}get needsSubscriber(){return this.isSubscriberConnectionRequired}get currentState(){return this.state}constructor(t,i,n){var s;this.peerConnectionTimeout=yo.peerConnectionTimeout,this.log=Ei,this.updateState=()=>{var e;const t=this.state,i=this.requiredTransports.map((e=>e.getConnectionState()));i.every((e=>"connected"===e))?this.state=To.CONNECTED:i.some((e=>"failed"===e))?this.state=To.FAILED:i.some((e=>"connecting"===e))?this.state=To.CONNECTING:i.every((e=>"closed"===e))?this.state=To.CLOSED:i.some((e=>"closed"===e))?this.state=To.CLOSING:i.every((e=>"new"===e))&&(this.state=To.NEW),t!==this.state&&(this.log.debug("pc state change: from ".concat(To[t]," to ").concat(To[this.state]),this.logContext),null===(e=this.onStateChange)||void 0===e||e.call(this,this.state,this.publisher.getConnectionState(),this.subscriber.getConnectionState()))},this.log=Pi(null!==(s=n.loggerName)&&void 0!==s?s:e.LoggerNames.PCManager),this.loggerOptions=n,this.isPublisherConnectionRequired=!i,this.isSubscriberConnectionRequired=i,this.publisher=new po(t,n),this.subscriber=new po(t,n),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,wt.PUBLISHER)},this.subscriber.onIceCandidate=e=>{var t;null===(t=this.onIceCandidate)||void 0===t||t.call(this,e,wt.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=To.NEW,this.connectionLock=new Ar,this.remoteOfferLock=new Ar}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 Di(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 Di(this,void 0,void 0,(function*(){this.subscriber.restartingIce=!0,this.needsPublisher&&(yield this.createAndSendPublisherOffer({iceRestart:!0}))}))}addIceCandidate(e,t){return Di(this,void 0,void 0,(function*(){t===wt.PUBLISHER?yield this.publisher.addIceCandidate(e):yield this.subscriber.addIceCandidate(e)}))}createSubscriberAnswerFromOffer(e){return Di(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()}));const t=yield this.remoteOfferLock.lock();try{yield this.subscriber.setRemoteDescription(e);return yield this.subscriber.createAndSetAnswer()}finally{t()}}))}updateConfiguration(e,t){this.publisher.setConfiguration(e),this.subscriber.setConfiguration(e),t&&this.triggerIceRestart()}ensurePCTransportConnection(e,t){return Di(this,void 0,void 0,(function*(){var i;const n=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===(i=this.requiredTransports)||void 0===i?void 0:i.map((i=>this.ensureTransportConnected(i,e,t))))}finally{n()}}))}negotiate(e){return Di(this,void 0,void 0,(function*(){return new Promise(((t,i)=>Di(this,void 0,void 0,(function*(){const n=setTimeout((()=>{i("negotiation timed out")}),this.peerConnectionTimeout);e.signal.addEventListener("abort",(()=>{clearTimeout(n),i("negotiation aborted")})),this.publisher.once(lo,(()=>{e.signal.aborted||this.publisher.once(uo,(()=>{clearTimeout(n),t()}))})),yield this.publisher.negotiate((e=>{clearTimeout(n),i(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===wt.PUBLISHER||e===wt.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){return Di(this,arguments,void 0,(function(e,t){var i=this;let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:this.peerConnectionTimeout;return function*(){if("connected"!==e.getConnectionState())return new Promise(((e,s)=>Di(i,void 0,void 0,(function*(){const i=()=>{this.log.warn("abort transport connection",this.logContext),Ls.clearTimeout(r),s(new gs("room connection has been cancelled",3))};(null==t?void 0:t.signal.aborted)&&i(),null==t||t.signal.addEventListener("abort",i);const r=Ls.setTimeout((()=>{null==t||t.signal.removeEventListener("abort",i),s(new gs("could not establish pc connection"))}),n);for(;this.state!==To.CONNECTED;)if(yield rr(50),null==t?void 0:t.signal.aborted)return void s(new gs("room connection has been cancelled",3));Ls.clearTimeout(r),null==t||t.signal.removeEventListener("abort",i),e()}))))}()}))}}const So=2e3;function Eo(e,t){if(!t)return 0;let i,n;return"bytesReceived"in e?(i=e.bytesReceived,n=t.bytesReceived):"bytesSent"in e&&(i=e.bytesSent,n=t.bytesSent),void 0===i||void 0===n||void 0===e.timestamp||void 0===t.timestamp?0:8*(i-n)*1e3/(e.timestamp-t.timestamp)}class wo extends Br{get enhancedNoiseCancellation(){return this.isKrispNoiseFilterEnabled}constructor(t,i){let n=!(arguments.length>2&&void 0!==arguments[2])||arguments[2],s=arguments.length>3?arguments[3]:void 0,r=arguments.length>4?arguments[4]:void 0;super(t,Hs.Kind.Audio,i,n,r),this.stopOnMute=!1,this.isKrispNoiseFilterEnabled=!1,this.monitorSender=()=>Di(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=Eo(e,this.prevStats)),this.prevStats=e})),this.handleKrispNoiseFilterEnable=()=>{this.isKrispNoiseFilterEnabled=!0,this.log.debug("Krisp noise filter enabled",this.logContext),this.emit(e.TrackEvent.AudioTrackFeatureUpdate,this,Xe.TF_ENHANCED_NOISE_CANCELLATION,!0)},this.handleKrispNoiseFilterDisable=()=>{this.isKrispNoiseFilterEnabled=!1,this.log.debug("Krisp noise filter disabled",this.logContext),this.emit(e.TrackEvent.AudioTrackFeatureUpdate,this,Xe.TF_ENHANCED_NOISE_CANCELLATION,!1)},this.audioContext=s,this.checkForSilence()}setDeviceId(e){return Di(this,void 0,void 0,(function*(){return this._constraints.deviceId===e&&this._mediaStreamTrack.getSettings().deviceId===Lr(e)||(this._constraints.deviceId=e,this.isMuted||(yield this.restartTrack()),this.isMuted||Lr(e)===this._mediaStreamTrack.getSettings().deviceId)}))}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return Di(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===Hs.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 Di(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!==Lr(this._constraints.deviceId);return this.source!==Hs.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 Di(this,void 0,void 0,(function*(){let t;if(e){const i=Xs({audio:e});"boolean"!=typeof i.audio&&(t=i.audio)}yield this.restart(t)}))}restart(e){const t=Object.create(null,{restart:{get:()=>super.restart}});return Di(this,void 0,void 0,(function*(){const i=yield t.restart.call(this,e);return this.checkForSilence(),i}))}startMonitor(){vr()&&(this.monitorInterval||(this.monitorInterval=setInterval((()=>{this.monitorSender()}),So)))}setProcessor(t){return Di(this,void 0,void 0,(function*(){var i;const n=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 n={kind:this.kind,track:this._mediaStreamTrack,audioContext:this.audioContext};this.log.debug("setting up audio processor ".concat(t.name),this.logContext),yield t.init(n),this.processor=t,this.processor.processedTrack&&(yield null===(i=this.sender)||void 0===i?void 0:i.replaceTrack(this.processor.processedTrack),this.processor.processedTrack.addEventListener("enable-lk-krisp-noise-filter",this.handleKrispNoiseFilterEnable),this.processor.processedTrack.addEventListener("disable-lk-krisp-noise-filter",this.handleKrispNoiseFilterDisable)),this.emit(e.TrackEvent.TrackProcessorUpdate,this.processor)}finally{n()}}))}setAudioContext(e){this.audioContext=e}getSenderStats(){return Di(this,void 0,void 0,(function*(){var e;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 Di(this,void 0,void 0,(function*(){const t=yield function(e){return Di(this,arguments,void 0,(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:200;return function*(){const i=$s();if(i){const n=i.createAnalyser();n.fftSize=2048;const s=n.frequencyBinCount,r=new Uint8Array(s);i.createMediaStreamSource(new MediaStream([e.mediaStreamTrack])).connect(n),yield rr(t),n.getByteTimeDomainData(r);const o=r.some((e=>128!==e&&0!==e));return i.close(),!o}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 Po(e,t,i){switch(e.kind){case"audio":return new wo(e,t,!1,void 0,i);case"video":return new Fo(e,t,!1,i);default:throw new vs("unsupported track type: ".concat(e.kind))}}const Ro=Object.values(qs),Io=Object.values(Ks),Oo=Object.values(Ws),xo=[qs.h180,qs.h360],Do=[Ks.h180,Ks.h360],Mo=e=>[{scaleResolutionDownBy:2,fps:e.encoding.maxFramerate}].map((t=>{var i,n;return new Us(Math.floor(e.width/t.scaleResolutionDownBy),Math.floor(e.height/t.scaleResolutionDownBy),Math.max(15e4,Math.floor(e.encoding.maxBitrate/(Math.pow(t.scaleResolutionDownBy,2)*((null!==(i=e.encoding.maxFramerate)&&void 0!==i?i:30)/(null!==(n=t.fps)&&void 0!==n?n:30))))),t.fps,e.encoding.priority)})),No=["q","h","f"];function _o(e,t,i,n){var s,r;let o=null==n?void 0:n.videoEncoding;e&&(o=null==n?void 0:n.screenShareEncoding);const a=null==n?void 0:n.simulcast,c=null==n?void 0:n.scalabilityMode,d=null==n?void 0:n.videoCodec;if(!o&&!a&&!c||!t||!i)return[{}];o||(o=function(e,t,i,n){const s=function(e,t,i){if(e)return Oo;const n=t>i?t/i:i/t;if(Math.abs(n-16/9)<Math.abs(n-4/3))return Ro;return Io}(e,t,i);let{encoding:r}=s[0];const o=Math.max(t,i);for(let e=0;e<s.length;e+=1){const t=s[e];if(r=t.encoding,t.width>=o)break}if(n)switch(n){case"av1":r=Object.assign({},r),r.maxBitrate=.7*r.maxBitrate;break;case"vp9":r=Object.assign({},r),r.maxBitrate=.85*r.maxBitrate}return r}(e,t,i,d),Ei.debug("using video encoding",o));const l=new Us(t,i,o.maxBitrate,o.maxFramerate,o.priority);if(c&&lr(d)){const e=new jo(c),t=[];if(e.spatial>3)throw new Error("unsupported scalabilityMode: ".concat(c));const i=Ds();if(mr()||kr()||"Chrome"===(null==i?void 0:i.name)&&Sr(null==i?void 0:i.version,"113")<0){const i="h"==e.suffix?2:3;for(let n=0;n<e.spatial;n+=1)t.push({rid:No[2-n],maxBitrate:o.maxBitrate/Math.pow(i,n),maxFramerate:l.encoding.maxFramerate});t[0].scalabilityMode=c}else t.push({maxBitrate:o.maxBitrate,maxFramerate:l.encoding.maxFramerate,scalabilityMode:c});return l.encoding.priority&&(t[0].priority=l.encoding.priority,t[0].networkPriority=l.encoding.priority),Ei.debug("using svc encoding",{encodings:t}),t}if(!a)return[o];let u,h=[];if(h=e?null!==(s=Uo(null==n?void 0:n.screenShareSimulcastLayers))&&void 0!==s?s:Ao(e,l):null!==(r=Uo(null==n?void 0:n.videoSimulcastLayers))&&void 0!==r?r:Ao(e,l),h.length>0){const e=h[0];h.length>1&&([,u]=h);const n=Math.max(t,i);if(n>=960&&u)return Lo(t,i,[e,u,l]);if(n>=480)return Lo(t,i,[e,l])}return Lo(t,i,[l])}function Ao(e,t){if(e)return Mo(t);const{width:i,height:n}=t,s=i>n?i/n:n/i;return Math.abs(s-16/9)<Math.abs(s-4/3)?xo:Do}function Lo(e,t,i){const n=[];if(i.forEach(((i,s)=>{if(s>=No.length)return;const r=Math.min(e,t),o={rid:No[s],scaleResolutionDownBy:Math.max(1,r/Math.min(i.width,i.height)),maxBitrate:i.encoding.maxBitrate};i.encoding.maxFramerate&&(o.maxFramerate=i.encoding.maxFramerate);const a=pr()||0===s;i.encoding.priority&&a&&(o.priority=i.encoding.priority,o.networkPriority=i.encoding.priority),n.push(o)})),kr()&&"ios"===Tr()){let e;n.forEach((t=>{e?t.maxFramerate&&t.maxFramerate>e&&(e=t.maxFramerate):e=t.maxFramerate}));let t=!0;n.forEach((i=>{var n;i.maxFramerate!=e&&(t&&(t=!1,Ei.info("Simulcast on iOS React-Native requires all encodings to share the same framerate.")),Ei.info('Setting framerate of encoding "'.concat(null!==(n=i.rid)&&void 0!==n?n:"",'" to ').concat(e)),i.maxFramerate=e)}))}return n}function Uo(e){if(e)return e.sort(((e,t)=>{const{encoding:i}=e,{encoding:n}=t;return i.maxBitrate>n.maxBitrate?1:i.maxBitrate<n.maxBitrate?-1:i.maxBitrate===n.maxBitrate&&i.maxFramerate&&n.maxFramerate?i.maxFramerate>n.maxFramerate?1:-1:0}))}class jo{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 Fo extends Br{get sender(){return this._sender}set sender(e){this._sender=e,this.degradationPreference&&this.setDegradationPreference(this.degradationPreference)}constructor(e,t){let i=!(arguments.length>2&&void 0!==arguments[2])||arguments[2],n=arguments.length>3?arguments[3]:void 0;super(e,Hs.Kind.Video,t,i,n),this.simulcastCodecs=new Map,this.degradationPreference="balanced",this.monitorSender=()=>Di(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,i)=>{var n;const s=null===(n=this.prevStats)||void 0===n?void 0:n.get(i);e+=Eo(t,s)})),this._currentBitrate=e}this.prevStats=t})),this.senderLock=new Ar}get isSimulcast(){return!!(this.sender&&this.sender.getParameters().encodings.length>1)}startMonitor(e){var t;if(this.signalClient=e,!vr())return;const i=null===(t=this.sender)||void 0===t?void 0:t.getParameters();i&&(this.encodings=i.encodings),this.monitorInterval||(this.monitorInterval=setInterval((()=>{this.monitorSender()}),So))}stop(){this._mediaStreamTrack.getConstraints(),this.simulcastCodecs.forEach((e=>{e.mediaStreamTrack.stop()})),super.stop()}pauseUpstream(){const e=Object.create(null,{pauseUpstream:{get:()=>super.pauseUpstream}});return Di(this,void 0,void 0,(function*(){var t,i,n,s,r;yield e.pauseUpstream.call(this);try{for(var o,a=!0,c=Ni(this.simulcastCodecs.values());!(t=(o=yield c.next()).done);a=!0){s=o.value,a=!1;const e=s;yield null===(r=e.sender)||void 0===r?void 0:r.replaceTrack(null)}}catch(e){i={error:e}}finally{try{a||t||!(n=c.return)||(yield n.call(c))}finally{if(i)throw i.error}}}))}resumeUpstream(){const e=Object.create(null,{resumeUpstream:{get:()=>super.resumeUpstream}});return Di(this,void 0,void 0,(function*(){var t,i,n,s,r;yield e.resumeUpstream.call(this);try{for(var o,a=!0,c=Ni(this.simulcastCodecs.values());!(t=(o=yield c.next()).done);a=!0){s=o.value,a=!1;const e=s;yield null===(r=e.sender)||void 0===r?void 0:r.replaceTrack(e.mediaStreamTrack)}}catch(e){i={error:e}}finally{try{a||t||!(n=c.return)||(yield n.call(c))}finally{if(i)throw i.error}}}))}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return Di(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!==Hs.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 Di(this,void 0,void 0,(function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.source!==Hs.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(){return Di(this,void 0,void 0,(function*(){var e;if(!(null===(e=this.sender)||void 0===e?void 0:e.getStats))return[];const t=[],i=yield this.sender.getStats();return i.forEach((e=>{var n;if("outbound-rtp"===e.type){const s={type:"video",streamId:e.id,frameHeight:e.frameHeight,frameWidth:e.frameWidth,framesPerSecond:e.framesPerSecond,framesSent:e.framesSent,firCount:e.firCount,pliCount:e.pliCount,nackCount:e.nackCount,packetsSent:e.packetsSent,bytesSent:e.bytesSent,qualityLimitationReason:e.qualityLimitationReason,qualityLimitationDurations:e.qualityLimitationDurations,qualityLimitationResolutionChanges:e.qualityLimitationResolutionChanges,rid:null!==(n=e.rid)&&void 0!==n?n:e.id,retransmittedPacketsSent:e.retransmittedPacketsSent,targetBitrate:e.targetBitrate,timestamp:e.timestamp},r=i.get(e.remoteId);r&&(s.jitter=r.jitter,s.packetsLost=r.packetsLost,s.roundTripTime=r.roundTripTime),t.push(s)}})),t.sort(((e,t)=>{var i,n;return(null!==(i=t.frameWidth)&&void 0!==i?i:0)-(null!==(n=e.frameWidth)&&void 0!==n?n:0)})),t}))}setPublishingQuality(t){const i=[];for(let n=e.VideoQuality.LOW;n<=e.VideoQuality.HIGH;n+=1)i.push(new ti({quality:n,enabled:n<=t}));this.log.debug("setting publishing quality. max quality ".concat(t),this.logContext),this.setPublishingLayers(i)}setDeviceId(e){return Di(this,void 0,void 0,(function*(){return this._constraints.deviceId===e&&this._mediaStreamTrack.getSettings().deviceId===Lr(e)||(this._constraints.deviceId=e,this.isMuted||(yield this.restartTrack()),this.isMuted||Lr(e)===this._mediaStreamTrack.getSettings().deviceId)}))}restartTrack(e){return Di(this,void 0,void 0,(function*(){var t,i,n,s;let r;if(e){const t=Xs({video:e});"boolean"!=typeof t.video&&(r=t.video)}yield this.restart(r);try{for(var o,a=!0,c=Ni(this.simulcastCodecs.values());!(t=(o=yield c.next()).done);a=!0){s=o.value,a=!1;const e=s;e.sender&&(e.mediaStreamTrack=this.mediaStreamTrack.clone(),yield e.sender.replaceTrack(e.mediaStreamTrack))}}catch(e){i={error:e}}finally{try{a||t||!(n=c.return)||(yield n.call(c))}finally{if(i)throw i.error}}}))}setProcessor(e){const t=Object.create(null,{setProcessor:{get:()=>super.setProcessor}});return Di(this,arguments,void 0,(function(e){var i=this;let n=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return function*(){var s,r,o,a,c,d;if(yield t.setProcessor.call(i,e,n),null===(c=i.processor)||void 0===c?void 0:c.processedTrack)try{for(var l,u=!0,h=Ni(i.simulcastCodecs.values());!(s=(l=yield h.next()).done);u=!0){a=l.value,u=!1;const e=a;yield null===(d=e.sender)||void 0===d?void 0:d.replaceTrack(i.processor.processedTrack)}}catch(e){r={error:e}}finally{try{u||s||!(o=h.return)||(yield o.call(h))}finally{if(r)throw r.error}}}()}))}setDegradationPreference(e){return Di(this,void 0,void 0,(function*(){if(this.degradationPreference=e,this.sender)try{this.log.debug("setting degradationPreference to ".concat(e),this.logContext);const t=this.sender.getParameters();t.degradationPreference=e,this.sender.setParameters(t)}catch(e){this.log.warn("failed to set degradationPreference",Object.assign({error:e},this.logContext))}}))}addSimulcastTrack(e,t){if(this.simulcastCodecs.has(e))return void this.log.error("".concat(e," already added, skipping adding simulcast codec"),this.logContext);const i={codec:e,mediaStreamTrack:this.mediaStreamTrack.clone(),sender:void 0,encodings:t};return this.simulcastCodecs.set(e,i),i}setSimulcastTrackSender(e,t){const i=this.simulcastCodecs.get(e);i&&(i.sender=t,setTimeout((()=>{this.subscribedCodecs&&this.setPublishingCodecs(this.subscribedCodecs)}),5e3))}setPublishingCodecs(e){return Di(this,void 0,void 0,(function*(){var t,i,n,s,r,o,a;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,i=Ni(e);!(s=(n=yield i.next()).done);t=!0){a=n.value,t=!1;const e=a;if(this.codec&&this.codec!==e.codec){const t=this.simulcastCodecs.get(e.codec);if(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 Bo(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){r={error:e}}finally{try{t||s||!(o=i.return)||(yield o.call(i))}finally{if(r)throw r.error}}return c}))}setPublishingLayers(e){return Di(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 Bo(this.sender,this.encodings,e,this.senderLock,this.log,this.logContext))}))}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return Di(this,void 0,void 0,(function*(){yield e.handleAppVisibilityChanged.call(this),fr()&&this.isInBackground&&this.source===Hs.Source.Camera&&(this._mediaStreamTrack.enabled=!1)}))}}function Bo(e,t,i,n,s,r){return Di(this,void 0,void 0,(function*(){const o=yield n.lock();s.debug("setPublishingLayersForSender",Object.assign(Object.assign({},r),{sender:e,qualities:i,senderEncodings:t}));try{const n=e.getParameters(),{encodings:o}=n;if(!o)return;if(o.length!==t.length)return void s.warn("cannot set publishing layers, encodings mismatch",Object.assign(Object.assign({},r),{encodings:o,senderEncodings:t}));let a=!1;!1&&o[0].scalabilityMode||o.forEach(((e,n)=>{var o;let c=null!==(o=e.rid)&&void 0!==o?o:"";""===c&&(c="q");const d=Vo(c),l=i.find((e=>e.quality===d));l&&e.active!==l.enabled&&(a=!0,e.active=l.enabled,s.debug("setting layer ".concat(l.quality," to ").concat(e.active?"enabled":"disabled"),r),pr()&&(l.enabled?(e.scaleResolutionDownBy=t[n].scaleResolutionDownBy,e.maxBitrate=t[n].maxBitrate,e.maxFrameRate=t[n].maxFrameRate):(e.scaleResolutionDownBy=4,e.maxBitrate=10,e.maxFrameRate=2)))})),a&&(n.encodings=o,s.debug("setting encodings",Object.assign(Object.assign({},r),{encodings:n.encodings})),yield e.setParameters(n))}finally{o()}}))}function Vo(t){switch(t){case"f":default:return e.VideoQuality.HIGH;case"h":return e.VideoQuality.MEDIUM;case"q":return e.VideoQuality.LOW}}function qo(t,i,n,s){if(!n)return[new at({quality:e.VideoQuality.HIGH,width:t,height:i,bitrate:0,ssrc:0})];if(s){const s=n[0].scalabilityMode,r=new jo(s),o=[],a="h"==r.suffix?1.5:2,c="h"==r.suffix?2:3;for(let s=0;s<r.spatial;s+=1)o.push(new at({quality:Math.min(e.VideoQuality.HIGH,r.spatial-1)-s,width:Math.ceil(t/Math.pow(a,s)),height:Math.ceil(i/Math.pow(a,s)),bitrate:n[0].maxBitrate?Math.ceil(n[0].maxBitrate/Math.pow(c,s)):0,ssrc:0}));return o}return n.map((e=>{var n,s,r;const o=null!==(n=e.scaleResolutionDownBy)&&void 0!==n?n:1;let a=Vo(null!==(s=e.rid)&&void 0!==s?s:"");return new at({quality:a,width:Math.ceil(t/o),height:Math.ceil(i/o),bitrate:null!==(r=e.maxBitrate)&&void 0!==r?r:0,ssrc:0})}))}const Ko="_lossy",Wo="_reliable",Go="leave-reconnect";var Ho;!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"}(Ho||(Ho={}));class Jo extends Yi.EventEmitter{get isClosed(){return this._isClosed}get pendingReconnect(){return!!this.reconnectTimeout}constructor(t){var i;super(),this.options=t,this.rtcConfig={},this.peerConnectionTimeout=yo.peerConnectionTimeout,this.fullReconnectOnNext=!1,this.subscriberPrimary=!1,this.pcState=Ho.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=Ei,this.handleDataChannel=e=>Di(this,[e],void 0,(function(e){var t=this;let{channel:i}=e;return function*(){if(i){if(i.label===Wo)t.reliableDCSub=i;else{if(i.label!==Ko)return;t.lossyDCSub=i}t.log.debug("on data channel ".concat(i.id,", ").concat(i.label),t.logContext),i.onmessage=t.handleDataMessage}}()})),this.handleDataMessage=t=>Di(this,void 0,void 0,(function*(){var i,n;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 r=ct.fromBinary(new Uint8Array(s));"speaker"===(null===(i=r.value)||void 0===i?void 0:i.case)?this.emit(e.EngineEvent.ActiveSpeakersUpdate,r.value.value.speakers):("user"===(null===(n=r.value)||void 0===n?void 0:n.case)&&function(e,t){const i=e.participantIdentity?e.participantIdentity:t.participantIdentity;e.participantIdentity=i,t.participantIdentity=i;const n=0!==e.destinationIdentities.length?e.destinationIdentities:t.destinationIdentities;e.destinationIdentities=n,t.destinationIdentities=n}(r,r.value.value),this.emit(e.EngineEvent.DataPacketReceived,r))}finally{s()}})),this.handleDataError=e=>{const t=0===e.currentTarget.maxRetransmits?"lossy":"reliable";if(e instanceof ErrorEvent&&e.error){const{error:i}=e.error;this.log.error("DataChannel error on ".concat(t,": ").concat(e.message),Object.assign(Object.assign({},this.logContext),{error:i}))}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?dt.LOSSY:dt.RELIABLE;this.updateAndEmitDCBufferStatus(t)},this.handleDisconnect=(t,i)=>{if(this._isClosed)return;this.log.warn("".concat(t," disconnected"),this.logContext),0===this.reconnectAttempts&&(this.reconnectStart=Date.now());const n=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 r=this.getNextRetryDelay({elapsedMs:s,retryCount:this.reconnectAttempts});null!==r?(t===Go&&(r=0),this.log.debug("reconnecting in ".concat(r,"ms"),this.logContext),this.clearReconnectTimeout(),this.token&&this.regionUrlProvider&&this.regionUrlProvider.updateToken(this.token),this.reconnectTimeout=Ls.setTimeout((()=>this.attemptReconnect(i).finally((()=>this.reconnectTimeout=void 0))),r)):n(s)},this.waitForRestarted=()=>new Promise(((t,i)=>{this.pcState===Ho.Connected&&t();const n=()=>{this.off(e.EngineEvent.Disconnected,s),t()},s=()=>{this.off(e.EngineEvent.Restarted,n),i()};this.once(e.EngineEvent.Restarted,n),this.once(e.EngineEvent.Disconnected,s)})),this.updateAndEmitDCBufferStatus=t=>{const i=this.isBufferStatusLow(t);void 0!==i&&i!==this.dcBufferStatus.get(t)&&(this.dcBufferStatus.set(t,i),this.emit(e.EngineEvent.DCBufferStatusChanged,i,t))},this.isBufferStatusLow=e=>{const t=this.dataChannelForKind(e);if(t)return t.bufferedAmount<=t.bufferedAmountLowThreshold},this.handleBrowserOnLine=()=>{this.client.currentState===Gr.RECONNECTING&&(this.clearReconnectTimeout(),this.attemptReconnect(ze.RR_SIGNAL_DISCONNECTED))},this.log=Pi(null!==(i=t.loggerName)&&void 0!==i?i:e.LoggerNames.Engine),this.loggerOptions={loggerName:t.loggerName,loggerContextCb:()=>this.logContext},this.client=new Hr(void 0,this.loggerOptions),this.client.signalLatency=this.options.expSignalLatency,this.reconnectPolicy=this.options.reconnectPolicy,this.registerOnLineListener(),this.closingLock=new Ar,this.dataProcessLock=new Ar,this.dcBufferStatus=new Map([[dt.LOSSY,!0],[dt.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),this.client.onRequestResponse=t=>this.emit(e.EngineEvent.SignalRequestResponse,t)}get logContext(){var e,t,i,n,s,r,o,a;return{room:null===(t=null===(e=this.latestJoinResponse)||void 0===e?void 0:e.room)||void 0===t?void 0:t.name,roomID:null===(n=null===(i=this.latestJoinResponse)||void 0===i?void 0:i.room)||void 0===n?void 0:n.sid,participant:null===(r=null===(s=this.latestJoinResponse)||void 0===s?void 0:s.participant)||void 0===r?void 0:r.identity,pID:null===(a=null===(o=this.latestJoinResponse)||void 0===o?void 0:o.participant)||void 0===a?void 0:a.sid}}join(e,t,i,n){return Di(this,void 0,void 0,(function*(){this.url=e,this.token=t,this.signalOpts=i,this.maxJoinAttempts=i.maxRetries;try{this.joinAttempts+=1,this.setupSignalClientCallbacks();const s=yield this.client.join(e,t,i,n);return this._isClosed=!1,this.latestJoinResponse=s,this.subscriberPrimary=s.subscriberPrimary,this.pcManager||(yield this.configure(s)),this.subscriberPrimary&&!s.fastPublish||this.negotiate(),this.clientConfiguration=s.clientConfiguration,s}catch(s){if(s instanceof gs&&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,i,n);throw s}}))}close(){return Di(this,void 0,void 0,(function*(){const t=yield this.closingLock.lock();if(this.isClosed)t();else try{this._isClosed=!0,this.emit(e.EngineEvent.Closing),this.removeAllListeners(),this.deregisterOnLineListener(),this.clearPendingReconnect(),yield this.cleanupPeerConnections(),yield this.cleanupClient()}finally{t()}}))}cleanupPeerConnections(){return Di(this,void 0,void 0,(function*(){var e;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 Di(this,void 0,void 0,(function*(){yield this.client.close(),this.client.resetCallbacks()}))}addTrack(e){if(this.pendingTrackResolvers[e.cid])throw new vs("a track with the same ID has already been published");return new Promise(((t,i)=>{const n=setTimeout((()=>{delete this.pendingTrackResolvers[e.cid],i(new gs("publication of local track timed out, no response from server"))}),1e4);this.pendingTrackResolvers[e.cid]={resolve:e=>{clearTimeout(n),t(e)},reject:()=>{clearTimeout(n),i(new Error("Cancelled publication by calling unpublish"))}},this.client.sendAddTrack(e)}))}removeTrack(e){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(){return Di(this,void 0,void 0,(function*(){var e;return null===(e=this.pcManager)||void 0===e?void 0:e.getConnectedAddress()}))}setRegionUrlProvider(e){this.regionUrlProvider=e}configure(t){return Di(this,void 0,void 0,(function*(){var i,n;if(this.pcManager&&this.pcManager.currentState!==To.NEW)return;this.participantSid=null===(i=t.participant)||void 0===i?void 0:i.sid;const s=this.makeRTCConfiguration(t);var r;this.pcManager=new Co(s,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=(i,n,s)=>Di(this,void 0,void 0,(function*(){if(this.log.debug("primary PC state changed ".concat(i),this.logContext),["closed","disconnected","failed"].includes(n)&&(this.publisherConnectionPromise=void 0),i===To.CONNECTED){const i=this.pcState===Ho.New;this.pcState=Ho.Connected,i&&this.emit(e.EngineEvent.Connected,t)}else i===To.FAILED&&this.pcState===Ho.Connected&&(this.pcState=Ho.Disconnected,this.handleDisconnect("peerconnection failed","failed"===s?ze.RR_SUBSCRIBER_FAILED:ze.RR_PUBLISHER_FAILED));const r=this.client.isDisconnected||this.client.currentState===Gr.RECONNECTING,o=[To.FAILED,To.CLOSING,To.CLOSED].includes(i);r&&o&&!this._isClosed&&this.emit(e.EngineEvent.Offline)})),this.pcManager.onTrack=t=>{this.emit(e.EngineEvent.MediaTrackAdded,t.track,t.streams[0],t.receiver)},void 0!==(r=null===(n=t.serverInfo)||void 0===n?void 0:n.protocol)&&r>13||this.createDataChannels()}))}setupSignalClientCallbacks(){this.client.onAnswer=e=>Di(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=>Di(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:i}=this.pendingTrackResolvers[e.cid];delete this.pendingTrackResolvers[e.cid],i(e.track)},this.client.onLocalTrackUnpublished=t=>{this.emit(e.EngineEvent.LocalTrackUnpublished,t)},this.client.onLocalTrackSubscribed=t=>{this.emit(e.EngineEvent.LocalTrackSubscribed,t)},this.client.onTokenRefresh=e=>{this.token=e},this.client.onRemoteMuteChanged=(t,i)=>{this.emit(e.EngineEvent.RemoteMute,t,i)},this.client.onSubscribedQualityUpdate=t=>{this.emit(e.EngineEvent.SubscribedQualityUpdate,t)},this.client.onClose=()=>{this.handleDisconnect("signal",ze.RR_SIGNAL_DISCONNECTED)},this.client.onLeave=t=>{switch(this.log.debug("client leave request",Object.assign(Object.assign({},this.logContext),{reason:null==t?void 0:t.reason})),t.regions&&this.regionUrlProvider&&(this.log.debug("updating regions",this.logContext),this.regionUrlProvider.setServerReportedRegions(t.regions)),t.action){case Gt.DISCONNECT:this.emit(e.EngineEvent.Disconnected,null==t?void 0:t.reason),this.close();break;case Gt.RECONNECT:this.fullReconnectOnNext=!0,this.handleDisconnect(Go);break;case Gt.RESUME:this.handleDisconnect(Go)}}}makeRTCConfiguration(e){var t;const i=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),i.encodedInsertableStreams=!0),e.iceServers&&!i.iceServers){const t=[];e.iceServers.forEach((e=>{const i={urls:e.urls};e.username&&(i.username=e.username),e.credential&&(i.credential=e.credential),t.push(i)})),i.iceServers=t}return e.clientConfiguration&&e.clientConfiguration.forceRelay===Je.ENABLED&&(i.iceTransportPolicy="relay"),i.sdpSemantics="unified-plan",i.continualGatheringPolicy="gather_continually",i}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(Ko,{ordered:!0,maxRetransmits:0}),this.reliableDC=this.pcManager.createPublisherDataChannel(Wo,{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)}createSender(e,t,i){return Di(this,void 0,void 0,(function*(){if(or()){return yield this.createTransceiverRTCRtpSender(e,t,i)}if(ar()){this.log.warn("using add-track fallback",this.logContext);return yield this.createRTCRtpSender(e.mediaStreamTrack)}throw new bs("Required webRTC APIs not supported on this device")}))}createSimulcastSender(e,t,i,n){return Di(this,void 0,void 0,(function*(){if(or())return this.createSimulcastTransceiverSender(e,t,i,n);if(ar())return this.log.debug("using add-track fallback",this.logContext),this.createRTCRtpSender(e.mediaStreamTrack);throw new bs("Cannot stream on this device")}))}createTransceiverRTCRtpSender(e,t,i){return Di(this,void 0,void 0,(function*(){if(!this.pcManager)throw new bs("publisher is closed");const n=[];e.mediaStream&&n.push(e.mediaStream),e instanceof Fo&&(e.codec=t.videoCodec);const s={direction:"sendonly",streams:n};i&&(s.sendEncodings=i);return(yield this.pcManager.addPublisherTransceiver(e.mediaStreamTrack,s)).sender}))}createSimulcastTransceiverSender(e,t,i,n){return Di(this,void 0,void 0,(function*(){if(!this.pcManager)throw new bs("publisher is closed");const s={direction:"sendonly"};n&&(s.sendEncodings=n);const r=yield this.pcManager.addPublisherTransceiver(t.mediaStreamTrack,s);if(i.videoCodec)return e.setSimulcastTrackSender(i.videoCodec,r.sender),r.sender}))}createRTCRtpSender(e){return Di(this,void 0,void 0,(function*(){if(!this.pcManager)throw new bs("publisher is closed");return this.pcManager.addPublisherTrack(e)}))}attemptReconnect(t){return Di(this,void 0,void 0,(function*(){var i,n,s;if(!this._isClosed)if(this.attemptingReconnect)Ei.warn("already attempting reconnect, returning early",this.logContext);else{(null===(i=this.clientConfiguration)||void 0===i?void 0:i.resumeConnection)!==Je.DISABLED&&(null!==(s=null===(n=this.pcManager)||void 0===n?void 0:n.currentState)&&void 0!==s?s:To.NEW)!==To.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 i=!0;t instanceof bs?(this.log.debug("received unrecoverable error",Object.assign(Object.assign({},this.logContext),{error:t})),i=!1):t instanceof Qo||(this.fullReconnectOnNext=!0),i?this.handleDisconnect("reconnect",ze.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){return Di(this,void 0,void 0,(function*(){var i,n,s;try{if(!this.url||!this.token)throw new bs("could not reconnect, url or token not saved");let n;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 Qo;n=yield this.join(null!=t?t:this.url,this.token,this.signalOpts)}catch(e){if(e instanceof gs&&0===e.reason)throw new bs("could not reconnect, token might be expired");throw new Qo}if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(this.client.setReconnected(),this.emit(e.EngineEvent.SignalRestarted,n),yield this.waitForPCReconnected(),this.client.currentState!==Gr.CONNECTED)throw new Qo("Signal connection got severed during reconnect");null===(i=this.regionUrlProvider)||void 0===i||i.resetAttempts(),this.emit(e.EngineEvent.Restarted)}catch(e){const t=yield null===(n=this.regionUrlProvider)||void 0===n?void 0:n.getNextBestRegionUrl();if(t)return void(yield this.restartConnection(t));throw null===(s=this.regionUrlProvider)||void 0===s||s.resetAttempts(),e}}))}resumeConnection(t){return Di(this,void 0,void 0,(function*(){var i;if(!this.url||!this.token)throw new bs("could not reconnect, url or token not saved");if(!this.pcManager)throw new bs("publisher and subscriber connections unset");let n;this.log.info("resuming signal connection, attempt ".concat(this.reconnectAttempts),this.logContext),this.emit(e.EngineEvent.Resuming);try{this.setupSignalClientCallbacks(),n=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 gs&&0===e.reason)throw new bs("could not reconnect, token might be expired");if(e instanceof gs&&4===e.reason)throw e;throw new Qo(t)}if(this.emit(e.EngineEvent.SignalResumed),n){const e=this.makeRTCConfiguration(n);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!==Gr.CONNECTED)throw new Qo("Signal connection got severed during reconnect");this.client.setReconnected(),"open"===(null===(i=this.reliableDC)||void 0===i?void 0:i.readyState)&&null===this.reliableDC.id&&this.createDataChannels(),this.emit(e.EngineEvent.Resumed)}))}waitForPCInitialConnection(e,t){return Di(this,void 0,void 0,(function*(){if(!this.pcManager)throw new bs("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(t,e)}))}waitForPCReconnected(){return Di(this,void 0,void 0,(function*(){this.pcState=Ho.Reconnecting,this.log.debug("waiting for peer connection to reconnect",this.logContext);try{if(yield rr(2e3),!this.pcManager)throw new bs("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(void 0,this.peerConnectionTimeout),this.pcState=Ho.Connected}catch(e){throw this.pcState=Ho.Disconnected,new gs("could not establish PC connection, ".concat(e.message))}}))}sendDataPacket(e,t){return Di(this,void 0,void 0,(function*(){const i=e.toBinary();yield this.ensurePublisherConnected(t);const n=this.dataChannelForKind(t);n&&n.send(i),this.updateAndEmitDCBufferStatus(t)}))}ensureDataTransportConnected(e){return Di(this,arguments,void 0,(function(e){var t=this;let i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.subscriberPrimary;return function*(){var n;if(!t.pcManager)throw new bs("PC manager is closed");const s=i?t.pcManager.subscriber:t.pcManager.publisher,r=i?"Subscriber":"Publisher";if(!s)throw new gs("".concat(r," connection not set"));let o=!1;i||t.dataChannelForKind(e,i)||(t.createDataChannels(),o=!0),o||i||t.pcManager.publisher.isICEConnected||"checking"===t.pcManager.publisher.getICEConnectionState()||(o=!0),o&&t.negotiate();const a=t.dataChannelForKind(e,i);if("open"===(null==a?void 0:a.readyState))return;const c=(new Date).getTime()+t.peerConnectionTimeout;for(;(new Date).getTime()<c;){if(s.isICEConnected&&"open"===(null===(n=t.dataChannelForKind(e,i))||void 0===n?void 0:n.readyState))return;yield rr(50)}throw new gs("could not establish ".concat(r," connection, state: ").concat(s.getICEConnectionState()))}()}))}ensurePublisherConnected(e){return Di(this,void 0,void 0,(function*(){this.publisherConnectionPromise||(this.publisherConnectionPromise=this.ensureDataTransportConnected(e,!1)),yield this.publisherConnectionPromise}))}verifyTransport(){return!!this.pcManager&&(this.pcManager.currentState===To.CONNECTED&&!(!this.client.ws||this.client.ws.readyState===WebSocket.CLOSED))}negotiate(){return Di(this,void 0,void 0,(function*(){return new Promise(((t,i)=>Di(this,void 0,void 0,(function*(){if(!this.pcManager)return void i(new ys("PC manager is closed"));this.pcManager.requirePublisher(),0!=this.pcManager.publisher.getTransceivers().length||this.lossyDC||this.reliableDC||this.createDataChannels();const n=new AbortController,s=()=>{n.abort(),this.log.debug("engine disconnected while negotiation was ongoing",this.logContext),t()};this.isClosed&&i("cannot negotiate on closed engine"),this.on(e.EngineEvent.Closing,s),this.pcManager.publisher.once(ho,(t=>{const i=new Map;t.forEach((e=>{const t=e.codec.toLowerCase();var n;n=t,Fs.includes(n)&&i.set(e.payload,t)})),this.emit(e.EngineEvent.RTPVideoMapUpdate,i)}));try{yield this.pcManager.negotiate(n),t()}catch(e){e instanceof ys&&(this.fullReconnectOnNext=!0),this.handleDisconnect("negotiation",ze.RR_UNKNOWN),i(e)}finally{this.off(e.EngineEvent.Closing,s)}}))))}))}dataChannelForKind(e,t){if(t){if(e===dt.LOSSY)return this.lossyDCSub;if(e===dt.RELIABLE)return this.reliableDCSub}else{if(e===dt.LOSSY)return this.lossyDC;if(e===dt.RELIABLE)return this.reliableDC}}sendSyncState(e,t){var i,n;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(),r=this.pcManager.subscriber.getRemoteDescription(),o=null===(n=null===(i=this.signalOpts)||void 0===i?void 0:i.autoSubscribe)||void 0===n||n,a=new Array,c=new Array;e.forEach((e=>{e.isDesired!==o&&a.push(e.trackSid),e.isEnabled||c.push(e.trackSid)})),this.client.sendSyncState(new ai({answer:s?Qr({sdp:s.sdp,type:s.type}):void 0,offer:r?Qr({sdp:r.sdp,type:r.type}):void 0,subscription:new Bt({trackSids:a,subscribe:!o,participantTracks:[]}),publishTracks:ir(t),dataChannels:this.dataChannelsInfo(),trackSidsDisabled:c}))}failNext(){this.shouldFailNext=!0}dataChannelsInfo(){const e=[],t=(t,i)=>{void 0!==(null==t?void 0:t.id)&&null!==t.id&&e.push(new ci({label:t.label,id:t.id,target:i}))};return t(this.dataChannelForKind(dt.LOSSY),wt.PUBLISHER),t(this.dataChannelForKind(dt.RELIABLE),wt.PUBLISHER),t(this.dataChannelForKind(dt.LOSSY,!0),wt.SUBSCRIBER),t(this.dataChannelForKind(dt.RELIABLE,!0),wt.SUBSCRIBER),e}clearReconnectTimeout(){this.reconnectTimeout&&Ls.clearTimeout(this.reconnectTimeout)}clearPendingReconnect(){this.clearReconnectTimeout(),this.reconnectAttempts=0}registerOnLineListener(){vr()&&window.addEventListener("online",this.handleBrowserOnLine)}deregisterOnLineListener(){vr()&&window.removeEventListener("online",this.handleBrowserOnLine)}}class Qo extends Error{}class zo{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 br(this.serverUrl)}getServerUrl(){return this.serverUrl}getNextBestRegionUrl(e){return Di(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),Ei.debug("next region: ".concat(e.region)),e.url}return null}))}resetAttempts(){this.attemptedRegions=[]}fetchRegionSettings(e){return Di(this,void 0,void 0,(function*(){const t=yield fetch("".concat((i=this.serverUrl,"".concat(i.protocol.replace("ws","http"),"//").concat(i.host,"/settings")),"/regions"),{headers:{authorization:"Bearer ".concat(this.token)},signal:e});var i;if(t.ok){const e=yield t.json();return this.lastUpdateAt=Date.now(),e}throw new gs("Could not fetch region settings: ".concat(t.statusText),401===t.status?0:void 0,t.status)}))}setServerReportedRegions(e){this.regionSettings=e,this.lastUpdateAt=Date.now()}}class Yo extends Hs{constructor(e,t,i,n,s){super(e,i,s),this.sid=t,this.receiver=n}setMuted(t){this.isMuted!==t&&(this.isMuted=t,this._mediaStreamTrack.enabled=!t,this.emit(t?e.TrackEvent.Muted:e.TrackEvent.Unmuted,this))}setMediaStream(t){this.mediaStream=t;const i=n=>{n.track===this._mediaStreamTrack&&(t.removeEventListener("removetrack",i),this.receiver&&"playoutDelayHint"in this.receiver&&(this.receiver.playoutDelayHint=void 0),this.receiver=void 0,this._currentBitrate=0,this.emit(e.TrackEvent.Ended,this))};t.addEventListener("removetrack",i)}start(){this.startMonitor(),super.enable()}stop(){this.stopMonitor(),super.disable()}getRTCStatsReport(){return Di(this,void 0,void 0,(function*(){var e;if(!(null===(e=this.receiver)||void 0===e?void 0:e.getStats))return;return yield this.receiver.getStats()}))}setPlayoutDelay(e){this.receiver?"playoutDelayHint"in this.receiver?this.receiver.playoutDelayHint=e:this.log.warn("Playout delay not supported in this browser"):this.log.warn("Cannot set playout delay, track already ended")}getPlayoutDelay(){if(this.receiver){if("playoutDelayHint"in this.receiver)return this.receiver.playoutDelayHint;this.log.warn("Playout delay not supported in this browser")}else this.log.warn("Cannot get playout delay, track already ended");return 0}startMonitor(){this.monitorInterval||(this.monitorInterval=setInterval((()=>this.monitorReceiver()),So)),"undefined"!=typeof RTCRtpReceiver&&"getSynchronizationSources"in RTCRtpReceiver&&this.registerTimeSyncUpdate()}registerTimeSyncUpdate(){const t=()=>{var i;this.timeSyncHandle=requestAnimationFrame((()=>t()));const n=null===(i=this.receiver)||void 0===i?void 0:i.getSynchronizationSources()[0];if(n){const{timestamp:t,rtpTimestamp:i}=n;i&&this.rtpTimestamp!==i&&(this.emit(e.TrackEvent.TimeSyncUpdate,{timestamp:t,rtpTimestamp:i}),this.rtpTimestamp=i)}};t()}}class Xo extends Yo{constructor(e,t,i,n,s,r){super(e,t,Hs.Kind.Audio,i,r),this.monitorReceiver=()=>Di(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=Eo(e,this.prevStats)),this.prevStats=e})),this.audioContext=n,this.webAudioPluginNodes=[],s&&(this.sinkId=s.deviceId)}setVolume(e){var t;for(const i of this.attachedElements)this.audioContext?null===(t=this.gainNode)||void 0===t||t.gain.setTargetAtTime(e,0,.1):i.volume=e;kr()&&this._mediaStreamTrack._setVolume(e),this.elementVolume=e}getVolume(){if(this.elementVolume)return this.elementVolume;if(kr())return 1;let e=0;return this.attachedElements.forEach((t=>{t.volume>e&&(e=t.volume)})),e}setSinkId(e){return Di(this,void 0,void 0,(function*(){this.sinkId=e,yield Promise.all(this.attachedElements.map((t=>{if(ur(t))return t.setSinkId(e)})))}))}attach(e){const t=0===this.attachedElements.length;return e?super.attach(e):e=super.attach(),this.sinkId&&ur(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,i){this.disconnectWebAudio(),this.sourceNode=t.createMediaStreamSource(i.srcObject);let n=this.sourceNode;this.webAudioPluginNodes.forEach((e=>{n.connect(e),n=e})),this.gainNode=t.createGain(),n.connect(this.gainNode),this.gainNode.connect(t.destination),this.elementVolume&&this.gainNode.gain.setTargetAtTime(this.elementVolume,0,.1),"running"!==t.state&&t.resume().then((()=>{"running"!==t.state&&this.emit(e.TrackEvent.AudioPlaybackFailed,new Error("Audio Context couldn't be started automatically"))})).catch((t=>{this.emit(e.TrackEvent.AudioPlaybackFailed,t)}))}disconnectWebAudio(){var e,t;null===(e=this.gainNode)||void 0===e||e.disconnect(),null===(t=this.sourceNode)||void 0===t||t.disconnect(),this.gainNode=void 0,this.sourceNode=void 0}getReceiverStats(){return Di(this,void 0,void 0,(function*(){if(!this.receiver||!this.receiver.getStats)return;let e;return(yield this.receiver.getStats()).forEach((t=>{"inbound-rtp"===t.type&&(e={type:"audio",timestamp:t.timestamp,jitter:t.jitter,bytesReceived:t.bytesReceived,concealedSamples:t.concealedSamples,concealmentEvents:t.concealmentEvents,silentConcealedSamples:t.silentConcealedSamples,silentConcealmentEvents:t.silentConcealmentEvents,totalAudioEnergy:t.totalAudioEnergy,totalSamplesDuration:t.totalSamplesDuration})})),e}))}}class $o extends Yo{constructor(e,t,i,n,s){super(e,t,Hs.Kind.Video,i,s),this.elementInfos=[],this.monitorReceiver=()=>Di(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=Eo(e,this.prevStats)),this.prevStats=e})),this.debouncedHandleResize=Is((()=>{this.updateDimensions()}),100),this.adaptiveStreamSettings=n}get isAdaptiveStream(){return void 0!==this.adaptiveStreamSettings}get mediaStreamTrack(){return this._mediaStreamTrack}setMuted(e){super.setMuted(e),this.attachedElements.forEach((t=>{e?Qs(this._mediaStreamTrack,t):Js(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 Zo(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 Di(this,void 0,void 0,(function*(){if(!this.receiver||!this.receiver.getStats)return;const e=yield this.receiver.getStats();let t,i="",n=new Map;return e.forEach((e=>{"inbound-rtp"===e.type?(i=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&&n.set(e.id,e)})),t&&""!==i&&n.get(i)&&(t.mimeType=n.get(i).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 Di(this,void 0,void 0,(function*(){yield e.handleAppVisibilityChanged.call(this),this.isAdaptiveStream&&this.updateVisibility()}))}updateVisibility(){var t,i;const n=this.elementInfos.reduce(((e,t)=>Math.max(e,t.visibilityChangedAt||0)),0),s=!(null!==(i=null===(t=this.adaptiveStreamSettings)||void 0===t?void 0:t.pauseVideoInBackground)&&void 0!==i&&!i)&&this.isInBackground,r=this.elementInfos.some((e=>e.pictureInPicture)),o=this.elementInfos.some((e=>e.visible))&&!s||r;this.lastVisible!==o&&(!o&&Date.now()-n<100?Ls.setTimeout((()=>{this.updateVisibility()}),100):(this.lastVisible=o,this.emit(e.TrackEvent.VisibilityChanged,o,this)))}updateDimensions(){var t,i;let n=0,s=0;const r=this.getPixelDensity();for(const e of this.elementInfos){const t=e.width()*r,i=e.height()*r;t+i>n+s&&(n=t,s=i)}(null===(t=this.lastDimensions)||void 0===t?void 0:t.width)===n&&(null===(i=this.lastDimensions)||void 0===i?void 0:i.height)===s||(this.lastDimensions={width:n,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 Cr();if(!t){return Cr()>2?2:1}return t}}class Zo{get visible(){return this.isPiP||this.isIntersecting}get pictureInPicture(){return this.isPiP}constructor(e,t){this.onVisibilityChanged=e=>{var t;const{target:i,isIntersecting:n}=e;i===this.element&&(this.isIntersecting=n,this.visibilityChangedAt=Date.now(),null===(t=this.handleVisibilityChanged)||void 0===t||t.call(this))},this.onEnterPiP=()=>{var e;this.isPiP=!0,null===(e=this.handleVisibilityChanged)||void 0===e||e.call(this)},this.onLeavePiP=()=>{var e;this.isPiP=!1,null===(e=this.handleVisibilityChanged)||void 0===e||e.call(this)},this.element=e,this.isIntersecting=null!=t?t:ea(e),this.isPiP=vr()&&document.pictureInPictureElement===e,this.visibilityChangedAt=0}width(){return this.element.clientWidth}height(){return this.element.clientHeight}observe(){this.isIntersecting=ea(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,Or().observe(this.element),Rr().observe(this.element),this.element.addEventListener("enterpictureinpicture",this.onEnterPiP),this.element.addEventListener("leavepictureinpicture",this.onLeavePiP)}stopObserving(){var e,t;null===(e=Or())||void 0===e||e.unobserve(this.element),null===(t=Rr())||void 0===t||t.unobserve(this.element),this.element.removeEventListener("enterpictureinpicture",this.onEnterPiP),this.element.removeEventListener("leavepictureinpicture",this.onLeavePiP)}}function ea(e){let t=e.offsetTop,i=e.offsetLeft;const n=e.offsetWidth,s=e.offsetHeight,{hidden:r}=e,{opacity:o,display:a}=getComputedStyle(e);for(;e.offsetParent;)t+=(e=e.offsetParent).offsetTop,i+=e.offsetLeft;return t<window.pageYOffset+window.innerHeight&&i<window.pageXOffset+window.innerWidth&&t+s>window.pageYOffset&&i+n>window.pageXOffset&&!r&&(""===o||parseFloat(o)>0)&&"none"!==a}class ta extends Yi.EventEmitter{constructor(t,i,n,s){var r;super(),this.metadataMuted=!1,this.encryption=st.NONE,this.log=Ei,this.handleMuted=()=>{this.emit(e.TrackEvent.Muted)},this.handleUnmuted=()=>{this.emit(e.TrackEvent.Unmuted)},this.log=Pi(null!==(r=null==s?void 0:s.loggerName)&&void 0!==r?r:e.LoggerNames.Publication),this.loggerContextCb=this.loggerContextCb,this.setMaxListeners(100),this.kind=t,this.trackSid=i,this.trackName=n,this.source=Hs.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)),nr(this))}get isMuted(){return this.metadataMuted}get isEnabled(){return!0}get isSubscribed(){return void 0!==this.track}get isEncrypted(){return this.encryption!==st.NONE}get audioTrack(){if(this.track instanceof wo||this.track instanceof Xo)return this.track}get videoTrack(){if(this.track instanceof Fo||this.track instanceof $o)return this.track}updateInfo(e){this.trackSid=e.sid,this.trackName=e.name,this.source=Hs.sourceFromProto(e.source),this.mimeType=e.mimeType,this.kind===Hs.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,i;(t=e.SubscriptionStatus||(e.SubscriptionStatus={})).Desired="desired",t.Subscribed="subscribed",t.Unsubscribed="unsubscribed",(i=e.PermissionStatus||(e.PermissionStatus={})).Allowed="allowed",i.NotAllowed="not_allowed"}(ta||(ta={}));class ia extends ta{get isUpstreamPaused(){var e;return null===(e=this.track)||void 0===e?void 0:e.isUpstreamPaused}constructor(t,i,n,s){super(t,i.sid,i.name,s),this.track=void 0,this.handleTrackEnded=()=>{this.emit(e.TrackEvent.Ended)},this.updateInfo(i),this.setTrack(n)}setTrack(t){this.track&&this.track.off(e.TrackEvent.Ended,this.handleTrackEnded),super.setTrack(t),t&&t.on(e.TrackEvent.Ended,this.handleTrackEnded)}get isMuted(){return this.track?this.track.isMuted:super.isMuted}get audioTrack(){return super.audioTrack}get videoTrack(){return super.videoTrack}mute(){return Di(this,void 0,void 0,(function*(){var e;return null===(e=this.track)||void 0===e?void 0:e.mute()}))}unmute(){return Di(this,void 0,void 0,(function*(){var e;return null===(e=this.track)||void 0===e?void 0:e.unmute()}))}pauseUpstream(){return Di(this,void 0,void 0,(function*(){var e;yield null===(e=this.track)||void 0===e?void 0:e.pauseUpstream()}))}resumeUpstream(){return Di(this,void 0,void 0,(function*(){var e;yield null===(e=this.track)||void 0===e?void 0:e.resumeUpstream()}))}getTrackFeatures(){var e;if(this.track instanceof wo){const t=this.track.mediaStreamTrack.getSettings(),i=new Set;return t.autoGainControl&&i.add(Xe.TF_AUTO_GAIN_CONTROL),t.echoCancellation&&i.add(Xe.TF_ECHO_CANCELLATION),t.noiseSuppression&&i.add(Xe.TF_NOISE_SUPPRESSION),t.channelCount&&t.channelCount>1&&i.add(Xe.TF_STEREO),(null===(e=this.options)||void 0===e?void 0:e.dtx)||i.add(Xe.TF_STEREO),this.track.enhancedNoiseCancellation&&i.add(Xe.TF_ENHANCED_NOISE_CANCELLATION),Array.from(i.values())}return[]}}function na(e){let t,i;return"object"==typeof e.audio&&e.audio.processor&&(t=e.audio.processor),"object"==typeof e.video&&e.video.processor&&(i=e.video.processor),{audioProcessor:t,videoProcessor:i}}function sa(e){return Di(this,void 0,void 0,(function*(){var t,i;null!=e||(e={}),null!==(t=e.audio)&&void 0!==t||(e.audio=!0),null!==(i=e.video)&&void 0!==i||(e.video=!0);const{audioProcessor:n,videoProcessor:s}=na(e),r=zs(e,vo,ko),o=Xs(r),a=navigator.mediaDevices.getUserMedia(o);e.audio&&(Fr.userMediaPromiseMap.set("audioinput",a),a.catch((()=>Fr.userMediaPromiseMap.delete("audioinput")))),e.video&&(Fr.userMediaPromiseMap.set("videoinput",a),a.catch((()=>Fr.userMediaPromiseMap.delete("videoinput"))));const c=yield a;return Promise.all(c.getTracks().map((e=>Di(this,void 0,void 0,(function*(){const t="audio"===e.kind;let i;t?r.audio:r.video;const a=t?o.audio:o.video;"boolean"!=typeof a&&(i=a),i?i.deviceId=e.getSettings().deviceId:i={deviceId:e.getSettings().deviceId};const d=Po(e,i);return d.kind===Hs.Kind.Video?d.source=Hs.Source.Camera:d.kind===Hs.Kind.Audio&&(d.source=Hs.Source.Microphone),d.mediaStream=c,d instanceof wo&&n?yield d.setProcessor(n):d instanceof Fo&&s&&(yield d.setProcessor(s)),d})))))}))}function ra(e){return Di(this,void 0,void 0,(function*(){return(yield sa({audio:!1,video:e}))[0]}))}function oa(e){return Di(this,void 0,void 0,(function*(){return(yield sa({audio:e,video:!1}))[0]}))}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 aa extends Yi.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;return(null===(e=this.permissions)||void 0===e?void 0:e.agent)||this.kind===nt.AGENT}get kind(){return this._kind}get attributes(){return Object.freeze(Object.assign({},this._attributes))}constructor(t,i,n,s,r){let o=arguments.length>5&&void 0!==arguments[5]?arguments[5]:nt.STANDARD;var a;super(),this.audioLevel=0,this.isSpeaking=!1,this._connectionQuality=e.ConnectionQuality.Unknown,this.log=Ei,this.log=Pi(null!==(a=null==r?void 0:r.loggerName)&&void 0!==a?a:e.LoggerNames.Participant),this.loggerOptions=r,this.setMaxListeners(100),this.sid=t,this.identity=i,this.name=n,this.metadata=s,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this._kind=o,this._attributes={}}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(Hs.Source.Camera);return!(null===(e=null==t?void 0:t.isMuted)||void 0===e||e)}get isMicrophoneEnabled(){var e;const t=this.getTrackPublication(Hs.Source.Microphone);return!(null===(e=null==t?void 0:t.isMuted)||void 0===e||e)}get isScreenShareEnabled(){return!!this.getTrackPublication(Hs.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),this._setAttributes(e.attributes),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 i=this.metadata!==t,n=this.metadata;this.metadata=t,i&&this.emit(e.ParticipantEvent.ParticipantMetadataChanged,n)}_setName(t){const i=this.name!==t;this.name=t,i&&this.emit(e.ParticipantEvent.ParticipantNameChanged,t)}_setAttributes(t){const i=function(e,t){var i;void 0===e&&(e={}),void 0===t&&(t={});const n=[...Object.keys(t),...Object.keys(e)],s={};for(const r of n)e[r]!==t[r]&&(s[r]=null!==(i=t[r])&&void 0!==i?i:"");return s}(t,this.attributes);this._attributes=t,Object.keys(i).length>0&&this.emit(e.ParticipantEvent.AttributesChanged,i)}setPermissions(t){var i,n,s,r,o;const a=this.permissions,c=t.canPublish!==(null===(i=this.permissions)||void 0===i?void 0:i.canPublish)||t.canSubscribe!==(null===(n=this.permissions)||void 0===n?void 0:n.canSubscribe)||t.canPublishData!==(null===(s=this.permissions)||void 0===s?void 0:s.canPublishData)||t.hidden!==(null===(r=this.permissions)||void 0===r?void 0:r.hidden)||t.recorder!==(null===(o=this.permissions)||void 0===o?void 0:o.recorder)||t.canPublishSources.length!==this.permissions.canPublishSources.length||t.canPublishSources.some(((e,t)=>{var i;return e!==(null===(i=this.permissions)||void 0===i?void 0:i.canPublishSources[t])}));return this.permissions=t,c&&this.emit(e.ParticipantEvent.ParticipantPermissionsChanged,a),c}setIsSpeaking(t){t!==this.isSpeaking&&(this.isSpeaking=t,t&&(this.lastSpokeAt=new Date),this.emit(e.ParticipantEvent.IsSpeakingChanged,t))}setConnectionQuality(t){const i=this._connectionQuality;this._connectionQuality=function(t){switch(t){case He.EXCELLENT:return e.ConnectionQuality.Excellent;case He.GOOD:return e.ConnectionQuality.Good;case He.POOR:return e.ConnectionQuality.Poor;case He.LOST:return e.ConnectionQuality.Lost;default:return e.ConnectionQuality.Unknown}}(t),i!==this._connectionQuality&&this.emit(e.ParticipantEvent.ConnectionQualityChanged,this._connectionQuality)}setAudioContext(e){this.audioContext=e,this.audioTrackPublications.forEach((t=>(t.track instanceof Xo||t.track instanceof wo)&&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 i=t;switch(i.track&&(i.track.sid=t.trackSid),this.trackPublications.set(t.trackSid,t),t.kind){case Hs.Kind.Audio:this.audioTrackPublications.set(t.trackSid,t);break;case Hs.Kind.Video:this.videoTrackPublications.set(t.trackSid,t)}}}class ca extends aa{constructor(e,t,i,n){super(e,t,void 0,void 0,{loggerName:n.loggerName,loggerContextCb:()=>this.engine.logContext}),this.pendingPublishing=new Set,this.pendingPublishPromises=new Map,this.participantTrackPermissions=[],this.allParticipantsAllowedToSubscribe=!0,this.encryptionType=st.NONE,this.enabledPublishVideoCodecs=[],this.handleReconnecting=()=>{this.reconnectFuture||(this.reconnectFuture=new _r)},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.handleSignalRequestResponse=e=>{const{requestId:t,reason:i,message:n}=e,s=this.pendingSignalRequests.get(t);s&&(i!==fi.OK&&s.reject(new Ts(n,i)),this.pendingSignalRequests.delete(t))},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,i,n;if(!e.participantSid&&!e.participantIdentity)throw new Error("Invalid track permission, must provide at least one of participantIdentity and participantSid");return new si({participantIdentity:null!==(t=e.participantIdentity)&&void 0!==t?t:"",participantSid:null!==(i=e.participantSid)&&void 0!==i?i:"",allTracks:null!==(n=e.allowAll)&&void 0!==n&&n,trackSids:e.allowedTrackSids||[]})}(e))))},this.onTrackUnmuted=e=>{this.onTrackMuted(e,e.isUpstreamPaused)},this.onTrackMuted=(e,t)=>{void 0===t&&(t=!0),e.sid?this.engine.updateMuteStatus(e.sid,t):this.log.error("could not update mute status for unpublished track",Object.assign(Object.assign({},this.logContext),nr(e)))},this.onTrackUpstreamPaused=e=>{this.log.debug("upstream paused",Object.assign(Object.assign({},this.logContext),nr(e))),this.onTrackMuted(e,!0)},this.onTrackUpstreamResumed=e=>{this.log.debug("upstream resumed",Object.assign(Object.assign({},this.logContext),nr(e))),this.onTrackMuted(e,e.isMuted)},this.onTrackFeatureUpdate=e=>{const t=this.audioTrackPublications.get(e.sid);t?this.engine.client.sendUpdateLocalAudioTrack(t.trackSid,t.getTrackFeatures()):this.log.warn("Could not update local audio track settings, missing publication for track ".concat(e.sid),this.logContext)},this.handleSubscribedQualityUpdate=e=>Di(this,void 0,void 0,(function*(){var t,i,n,s,r,o;if(!(null===(r=this.roomOptions)||void 0===r?void 0:r.dynacast))return;const a=this.videoTrackPublications.get(e.trackSid);if(a)if(e.subscribedCodecs.length>0){if(!a.videoTrack)return;const r=yield a.videoTrack.setPublishingCodecs(e.subscribedCodecs);try{for(var c,d=!0,l=Ni(r);!(t=(c=yield l.next()).done);d=!0){s=c.value,d=!1;const e=s;Bs(e)&&(this.log.debug("publish ".concat(e," for ").concat(a.videoTrack.sid),Object.assign(Object.assign({},this.logContext),nr(a))),yield this.publishAdditionalCodecForTrack(a.videoTrack,e,a.options))}}catch(e){i={error:e}}finally{try{d||t||!(n=l.return)||(yield n.call(l))}finally{if(i)throw i.error}}}else e.subscribedQualities.length>0&&(yield null===(o=a.videoTrack)||void 0===o?void 0:o.setPublishingLayers(e.subscribedQualities));else 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=>Di(this,void 0,void 0,(function*(){if(e.source===Hs.Source.ScreenShare||e.source===Hs.Source.ScreenShareAudio)this.log.debug("unpublishing local track due to TrackEnded",Object.assign(Object.assign({},this.logContext),nr(e))),this.unpublishTrack(e);else if(e.isUserProvided)yield e.mute();else if(e instanceof wo||e instanceof Fo)try{if(vr())try{const t=yield null===navigator||void 0===navigator?void 0:navigator.permissions.query({name:e.source===Hs.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),nr(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),nr(e))),e instanceof wo?yield e.restartTrack({deviceId:"default"}):yield e.restartTrack())}catch(t){this.log.warn("could not restart track, muting instead",Object.assign(Object.assign({},this.logContext),nr(e))),yield e.mute()}})),this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this.engine=i,this.roomOptions=n,this.setupEngine(i),this.activeDeviceMap=new Map,this.pendingSignalRequests=new Map}get lastCameraError(){return this.cameraError}get lastMicrophoneError(){return this.microphoneError}get isE2EEEnabled(){return this.encryptionType!==st.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 i=this.trackPublications.get(e);i&&i.track&&(t?i.mute():i.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).on(e.EngineEvent.SignalRequestResponse,this.handleSignalRequestResponse)}setMetadata(e){return Di(this,void 0,void 0,(function*(){yield this.requestMetadataUpdate({metadata:e})}))}setName(e){return Di(this,void 0,void 0,(function*(){yield this.requestMetadataUpdate({name:e})}))}setAttributes(e){return Di(this,void 0,void 0,(function*(){yield this.requestMetadataUpdate({attributes:e})}))}requestMetadataUpdate(e){return Di(this,arguments,void 0,(function(e){var t=this;let{metadata:i,name:n,attributes:s}=e;return function*(){return new Promise(((e,r)=>Di(t,void 0,void 0,(function*(){var t,o;try{let a=!1;const c=yield this.engine.client.sendUpdateLocalMetadata(null!==(t=null!=i?i:this.metadata)&&void 0!==t?t:"",null!==(o=null!=n?n:this.name)&&void 0!==o?o:"",s),d=performance.now();for(this.pendingSignalRequests.set(c,{resolve:e,reject:e=>{r(e),a=!0},values:{name:n,metadata:i,attributes:s}});performance.now()-d<5e3&&!a;){if((!n||this.name===n)&&(!i||this.metadata===i)&&(!s||Object.entries(s).every((e=>{let[t,i]=e;return this.attributes[t]===i}))))return this.pendingSignalRequests.delete(c),void e();yield rr(50)}r(new Ts("Request to update local metadata timed out","TimeoutError"))}catch(e){e instanceof Error&&r(e)}}))))}()}))}setCameraEnabled(e,t,i){return this.setTrackEnabled(Hs.Source.Camera,e,t,i)}setMicrophoneEnabled(e,t,i){return this.setTrackEnabled(Hs.Source.Microphone,e,t,i)}setScreenShareEnabled(e,t,i){return this.setTrackEnabled(Hs.Source.ScreenShare,e,t,i)}setPermissions(t){const i=this.permissions,n=super.setPermissions(t);return n&&i&&this.emit(e.ParticipantEvent.ParticipantPermissionsChanged,i),n}setE2EEEnabled(e){return Di(this,void 0,void 0,(function*(){this.encryptionType=e?st.GCM:st.NONE,yield this.republishAllTracks(void 0,!1)}))}setTrackEnabled(t,i,n,s){return Di(this,void 0,void 0,(function*(){var r,o;this.log.debug("setTrackEnabled",Object.assign(Object.assign({},this.logContext),{source:t,enabled:i}));let a=this.getTrackPublication(t);if(i)if(a)yield a.unmute();else{let i;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 Hs.Source.Camera:i=yield this.createTracks({video:null===(r=n)||void 0===r||r});break;case Hs.Source.Microphone:i=yield this.createTracks({audio:null===(o=n)||void 0===o||o});break;case Hs.Source.ScreenShare:i=yield this.createScreenTracks(Object.assign({},n));break;default:throw new vs(t)}const e=[];for(const t of i)this.log.info("publishing track",Object.assign(Object.assign({},this.logContext),nr(t))),e.push(this.publishTrack(t,s));const c=yield Promise.all(e);[a]=c}catch(t){throw null==i||i.forEach((e=>{e.stop()})),t instanceof Error&&!(t instanceof vs)&&this.emit(e.ParticipantEvent.MediaDevicesError,t),t}finally{this.pendingPublishing.delete(t)}}else if(a&&a.track)if(t===Hs.Source.ScreenShare){a=yield this.unpublishTrack(a.track);const e=this.getTrackPublication(Hs.Source.ScreenShareAudio);e&&e.track&&this.unpublishTrack(e.track)}else yield a.mute();return a}))}enableCameraAndMicrophone(){return Di(this,void 0,void 0,(function*(){if(!this.pendingPublishing.has(Hs.Source.Camera)&&!this.pendingPublishing.has(Hs.Source.Microphone)){this.pendingPublishing.add(Hs.Source.Camera),this.pendingPublishing.add(Hs.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(Hs.Source.Camera),this.pendingPublishing.delete(Hs.Source.Microphone)}}}))}createTracks(t){return Di(this,void 0,void 0,(function*(){var i,n;null!=t||(t={});const{audioProcessor:s,videoProcessor:r}=na(t),o=zs(t,null===(i=this.roomOptions)||void 0===i?void 0:i.audioCaptureDefaults,null===(n=this.roomOptions)||void 0===n?void 0:n.videoCaptureDefaults),a=Xs(o);let c;try{c=yield navigator.mediaDevices.getUserMedia(a)}catch(e){throw e instanceof Error&&(a.audio&&(this.microphoneError=e),a.video&&(this.cameraError=e)),e}return a.audio&&(this.microphoneError=void 0,this.emit(e.ParticipantEvent.AudioStreamAcquired)),a.video&&(this.cameraError=void 0),Promise.all(c.getTracks().map((e=>Di(this,void 0,void 0,(function*(){const t="audio"===e.kind;let i;t?o.audio:o.video;const n=t?a.audio:a.video;"boolean"!=typeof n&&(i=n);const d=Po(e,i,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});return d.kind===Hs.Kind.Video?d.source=Hs.Source.Camera:d.kind===Hs.Kind.Audio&&(d.source=Hs.Source.Microphone,d.setAudioContext(this.audioContext)),d.mediaStream=c,d instanceof wo&&s?yield d.setProcessor(s):d instanceof Fo&&r&&(yield d.setProcessor(r)),d})))))}))}createScreenTracks(t){return Di(this,void 0,void 0,(function*(){if(void 0===t&&(t={}),void 0===navigator.mediaDevices.getDisplayMedia)throw new fs("getDisplayMedia not supported");void 0!==t.resolution||gr()||(t.resolution=Ws.h1080fps30.resolution);const i=er(t),n=yield navigator.mediaDevices.getDisplayMedia(i),s=n.getVideoTracks();if(0===s.length)throw new vs("no video track found");const r=new Fo(s[0],void 0,!1,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});r.source=Hs.Source.ScreenShare,t.contentHint&&(r.mediaStreamTrack.contentHint=t.contentHint);const o=[r];if(n.getAudioTracks().length>0){this.emit(e.ParticipantEvent.AudioStreamAcquired);const t=new wo(n.getAudioTracks()[0],void 0,!1,this.audioContext,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});t.source=Hs.Source.ScreenShareAudio,o.push(t)}return o}))}publishTrack(e,t){return Di(this,void 0,void 0,(function*(){var i,n,s,r;let o,a;if(e instanceof wo&&e.setAudioContext(this.audioContext),yield null===(i=this.reconnectFuture)||void 0===i?void 0:i.promise,e instanceof Br&&this.pendingPublishPromises.has(e)&&(yield this.pendingPublishPromises.get(e)),e instanceof MediaStreamTrack)o=e.getConstraints();else{let t;switch(o=e.constraints,e.source){case Hs.Source.Microphone:t="audioinput";break;case Hs.Source.Camera:t="videoinput"}t&&this.activeDeviceMap.has(t)&&(o=Object.assign(Object.assign({},o),{deviceId:this.activeDeviceMap.get(t)}))}if(e instanceof MediaStreamTrack)switch(e.kind){case"audio":e=new wo(e,o,!0,this.audioContext,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});break;case"video":e=new Fo(e,o,!0,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});break;default:throw new vs("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&&(a=t)})),a)return this.log.warn("track has already been published, skipping",Object.assign(Object.assign({},this.logContext),nr(a))),a;const c="channelCount"in e.mediaStreamTrack.getSettings()&&2===e.mediaStreamTrack.getSettings().channelCount||2===e.mediaStreamTrack.getConstraints().channelCount,d=null!==(n=null==t?void 0:t.forceStereo)&&void 0!==n?n: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),nr(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!==(r=t.red)&&void 0!==r||(t.red=!1));const l=Object.assign(Object.assign({},this.roomOptions.publishDefaults),t);!function(){const e=Ds(),t="17.2";if(e)return"Safari"!==e.name&&"iOS"!==e.os||!!("iOS"===e.os&&e.osVersion&&Sr(t,e.osVersion)>=0)||"Safari"===e.name&&Sr(t,e.version)>=0}()&&this.roomOptions.e2ee&&(this.log.info("End-to-end encryption is set up, simulcast publishing will be disabled on Safari versions and iOS browsers running iOS < v17.2",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,i,n){return Di(this,void 0,void 0,(function*(){var s,r,o,a,c,d,l,u,h,p;Array.from(this.trackPublications.values()).find((e=>t instanceof Br&&e.source===t.source))&&t.source!==Hs.Source.Unknown&&this.log.info("publishing a second track with the same source: ".concat(t.source),Object.assign(Object.assign({},this.logContext),nr(t))),i.stopMicTrackOnMute&&t instanceof wo&&(t.stopOnMute=!0),t.source===Hs.Source.ScreenShare&&pr()&&(i.simulcast=!1),"av1"!==i.videoCodec||cr()||(i.videoCodec=void 0),"vp9"!==i.videoCodec||dr()||(i.videoCodec=void 0),void 0===i.videoCodec&&(i.videoCodec=go),this.enabledPublishVideoCodecs.length>0&&(this.enabledPublishVideoCodecs.some((e=>i.videoCodec===tr(e.mime)))||(i.videoCodec=tr(this.enabledPublishVideoCodecs[0].mime)));const m=i.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),t.on(e.TrackEvent.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate);const g=new Dt({cid:t.mediaStreamTrack.id,name:i.name,type:Hs.kindToProto(t.kind),muted:t.isMuted,source:Hs.sourceToProto(t.source),disableDtx:!(null===(s=i.dtx)||void 0===s||s),encryption:this.encryptionType,stereo:n,disableRed:this.isE2EEEnabled||!(null===(r=i.red)||void 0===r||r),stream:null==i?void 0:i.stream});let f;if(t.kind===Hs.Kind.Video){let e={width:0,height:0};try{e=yield t.waitForDimensions()}catch(i){const n=null!==(a=null===(o=this.roomOptions.videoCaptureDefaults)||void 0===o?void 0:o.resolution)&&void 0!==a?a:qs.h720.resolution;e={width:n.width,height:n.height},this.log.error("could not determine track dimensions, using defaults",Object.assign(Object.assign(Object.assign({},this.logContext),nr(t)),{dims:e}))}g.width=e.width,g.height=e.height,t instanceof Fo&&(lr(m)&&(t.source===Hs.Source.ScreenShare&&(i.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),nr(t))))),i.scalabilityMode=null!==(c=i.scalabilityMode)&&void 0!==c?c:"L3T3_KEY"),g.simulcastCodecs=[new xt({codec:m,cid:t.mediaStreamTrack.id})],!0===i.backupCodec&&(i.backupCodec={codec:go}),i.backupCodec&&m!==i.backupCodec.codec&&g.encryption===st.NONE&&(this.roomOptions.dynacast||(this.roomOptions.dynacast=!0),g.simulcastCodecs.push(new xt({codec:i.backupCodec.codec,cid:""})))),f=_o(t.source===Hs.Source.ScreenShare,g.width,g.height,i),g.layers=qo(g.width,g.height,f,lr(i.videoCodec))}else t.kind===Hs.Kind.Audio&&(f=[{maxBitrate:null===(d=i.audioPreset)||void 0===d?void 0:d.maxBitrate,priority:null!==(u=null===(l=i.audioPreset)||void 0===l?void 0:l.priority)&&void 0!==u?u:"high",networkPriority:null!==(p=null===(h=i.audioPreset)||void 0===h?void 0:h.priority)&&void 0!==p?p:"high"}]);if(!this.engine||this.engine.isClosed)throw new bs("cannot publish track when not connected");const v=()=>Di(this,void 0,void 0,(function*(){var e,n,s;if(!this.engine.pcManager)throw new bs("pcManager is not ready");if(t.sender=yield this.engine.createSender(t,i,f),t instanceof Fo&&(null!==(e=i.degradationPreference)&&void 0!==e||(i.degradationPreference=function(e){return e.source===Hs.Source.ScreenShare||e.constraints.height&&Lr(e.constraints.height)>=1080?"maintain-resolution":"balanced"}(t)),t.setDegradationPreference(i.degradationPreference)),f)if(pr()&&t.kind===Hs.Kind.Audio){let e;for(const i of this.engine.pcManager.publisher.getTransceivers())if(i.sender===t.sender){e=i;break}e&&this.engine.pcManager.publisher.setTrackCodecBitrate({transceiver:e,codec:"opus",maxbr:(null===(n=f[0])||void 0===n?void 0:n.maxBitrate)?f[0].maxBitrate/1e3:0})}else t.codec&&lr(t.codec)&&(null===(s=f[0])||void 0===s?void 0:s.maxBitrate)&&this.engine.pcManager.publisher.setTrackCodecBitrate({cid:g.cid,codec:t.codec,maxbr:f[0].maxBitrate/1e3});yield this.engine.negotiate()}));let k;if(this.enabledPublishVideoCodecs.length>0){k=(yield Promise.all([this.engine.addTrack(g),v()]))[0]}else{let e;if(k=yield this.engine.addTrack(g),k.codecs.forEach((t=>{void 0===e&&(e=t.mimeType)})),e&&t.kind===Hs.Kind.Video){const n=tr(e);n!==m&&(this.log.debug("falling back to server selected codec",Object.assign(Object.assign(Object.assign({},this.logContext),nr(t)),{codec:n})),i.videoCodec=n,f=_o(t.source===Hs.Source.ScreenShare,g.width,g.height,i))}yield v()}const b=new ia(t.kind,k,t,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});return b.options=i,t.sid=k.sid,this.log.debug("publishing ".concat(t.kind," with encodings"),Object.assign(Object.assign({},this.logContext),{encodings:f,trackInfo:k})),t instanceof Fo?t.startMonitor(this.engine.client):t instanceof wo&&t.startMonitor(),this.addTrackPublication(b),this.emit(e.ParticipantEvent.LocalTrackPublished,b),b}))}get isLocal(){return!0}publishAdditionalCodecForTrack(e,t,i){return Di(this,void 0,void 0,(function*(){var n;if(this.encryptionType!==st.NONE)return;let s;if(this.trackPublications.forEach((t=>{t.track&&t.track===e&&(s=t)})),!s)throw new vs("track is not published");if(!(e instanceof Fo))throw new vs("track is not a video track");const r=Object.assign(Object.assign({},null===(n=this.roomOptions)||void 0===n?void 0:n.publishDefaults),i),o=function(e,t,i){var n,s,r,o;if(!i.backupCodec||!0===i.backupCodec||i.backupCodec.codec===i.videoCodec)return;t!==i.backupCodec.codec&&Ei.warn("requested a different codec than specified as backup",{serverRequested:t,backup:i.backupCodec.codec}),i.videoCodec=t,i.videoEncoding=i.backupCodec.encoding;const a=e.mediaStreamTrack.getSettings(),c=null!==(n=a.width)&&void 0!==n?n:null===(s=e.dimensions)||void 0===s?void 0:s.width,d=null!==(r=a.height)&&void 0!==r?r:null===(o=e.dimensions)||void 0===o?void 0:o.height;return _o(e.source===Hs.Source.ScreenShare,c,d,i)}(e,t,r);if(!o)return void this.log.info("backup codec has been disabled, ignoring request to add additional codec for track",Object.assign(Object.assign({},this.logContext),nr(e)));const a=e.addSimulcastTrack(t,o);if(!a)return;const c=new Dt({cid:a.mediaStreamTrack.id,type:Hs.kindToProto(e.kind),muted:e.isMuted,source:Hs.sourceToProto(e.source),sid:e.sid,simulcastCodecs:[{codec:r.videoCodec,cid:a.mediaStreamTrack.id}]});if(c.layers=qo(c.width,c.height,o),!this.engine||this.engine.isClosed)throw new bs("cannot publish track when not connected");const d=(yield Promise.all([this.engine.addTrack(c),(()=>Di(this,void 0,void 0,(function*(){yield this.engine.createSimulcastSender(e,a,r,o),yield this.engine.negotiate()})))()]))[0];this.log.debug("published ".concat(t," for track ").concat(e.sid),Object.assign(Object.assign({},this.logContext),{encodings:o,trackInfo:d}))}))}unpublishTrack(t,i){return Di(this,void 0,void 0,(function*(){var n,s;if(t instanceof Br){const e=this.pendingPublishPromises.get(t);e&&(this.log.info("awaiting publish promise before attempting to unpublish",Object.assign(Object.assign({},this.logContext),nr(t))),yield e)}const r=this.getPublicationForTrack(t),o=r?nr(r):void 0;if(this.log.debug("unpublishing track",Object.assign(Object.assign({},this.logContext),o)),!r||!r.track)return void this.log.warn("track was not unpublished because no publication was found",Object.assign(Object.assign({},this.logContext),o));(t=r.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),t.off(e.TrackEvent.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate),void 0===i&&(i=null===(s=null===(n=this.roomOptions)||void 0===n?void 0:n.stopLocalTrackOnUnpublish)||void 0===s||s),i&&t.stop();let a=!1;const c=t.sender;if(t.sender=void 0,this.engine.pcManager&&this.engine.pcManager.currentState<To.FAILED&&c)try{for(const e of this.engine.pcManager.publisher.getTransceivers())e.sender===c&&(e.direction="inactive",a=!0);if(this.engine.removeTrack(c)&&(a=!0),t instanceof Fo){for(const[,e]of t.simulcastCodecs)e.sender&&(this.engine.removeTrack(e.sender)&&(a=!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),o),{error:e}))}switch(this.trackPublications.delete(r.trackSid),r.kind){case Hs.Kind.Audio:this.audioTrackPublications.delete(r.trackSid);break;case Hs.Kind.Video:this.videoTrackPublications.delete(r.trackSid)}return this.emit(e.ParticipantEvent.LocalTrackUnpublished,r),r.setTrack(void 0),a&&(yield this.engine.negotiate()),r}))}unpublishTracks(e){return Di(this,void 0,void 0,(function*(){return(yield Promise.all(e.map((e=>this.unpublishTrack(e))))).filter((e=>e instanceof ia))}))}republishAllTracks(e){return Di(this,arguments,void 0,(function(e){var t=this;let i=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return function*(){const n=[];t.trackPublications.forEach((t=>{t.track&&(e&&(t.options=Object.assign(Object.assign({},t.options),e)),n.push(t))})),yield Promise.all(n.map((e=>Di(t,void 0,void 0,(function*(){const t=e.track;yield this.unpublishTrack(t,!1),i&&!t.isMuted&&t.source!==Hs.Source.ScreenShare&&t.source!==Hs.Source.ScreenShareAudio&&(t instanceof wo||t instanceof Fo)&&!t.isUserProvided&&(this.log.debug("restarting existing track",Object.assign(Object.assign({},this.logContext),{track:e.trackSid})),yield t.restartTrack()),yield this.publishTrack(t,e.options)})))))}()}))}publishData(e){return Di(this,arguments,void 0,(function(e){var t=this;let i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){const n=i.reliable?dt.RELIABLE:dt.LOSSY,s=i.destinationIdentities,r=i.topic,o=new ct({kind:n,value:{case:"user",value:new ht({participantIdentity:t.identity,payload:e,destinationIdentities:s,topic:r})}});yield t.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()}setEnabledPublishCodecs(e){this.enabledPublishVideoCodecs=e.filter((e=>"video"===e.mime.split("/")[0].toLowerCase()))}updateInfo(e){return e.sid===this.sid&&(!!super.updateInfo(e)&&(e.tracks.forEach((e=>{var t,i;const n=this.trackPublications.get(e.sid);if(n){const s=n.isMuted||null!==(i=null===(t=n.track)||void 0===t?void 0:t.isUpstreamPaused)&&void 0!==i&&i;s!==e.muted&&(this.log.debug("updating server mute state after reconcile",Object.assign(Object.assign(Object.assign({},this.logContext),nr(n)),{mutedOnServer:s})),this.engine.client.sendMuteTrack(e.sid,s))}})),!0))}getPublicationForTrack(e){let t;return this.trackPublications.forEach((i=>{const n=i.track;n&&(e instanceof MediaStreamTrack?(n instanceof wo||n instanceof Fo)&&n.mediaStreamTrack===e&&(t=i):e===n&&(t=i))})),t}}class da extends ta{constructor(t,i,n,s){super(t,i.sid,i.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=n,this.updateInfo(i)}setSubscribed(t){const i=this.subscriptionStatus,n=this.permissionStatus;this.subscribed=t,t&&(this.allowed=!0);const s=new Bt({trackSids:[this.trackSid],subscribe:this.subscribed,participantTracks:[new ft({participantSid:"",trackSids:[this.trackSid]})]});this.emit(e.TrackEvent.UpdateSubscription,s),this.emitSubscriptionUpdateIfChanged(i),this.emitPermissionUpdateIfChanged(n)}get subscriptionStatus(){return!1===this.subscribed?ta.SubscriptionStatus.Unsubscribed:super.isSubscribed?ta.SubscriptionStatus.Subscribed:ta.SubscriptionStatus.Desired}get permissionStatus(){return this.allowed?ta.PermissionStatus.Allowed:ta.PermissionStatus.NotAllowed}get isSubscribed(){return!1!==this.subscribed&&super.isSubscribed}get isDesired(){return!1!==this.subscribed}get isEnabled(){return!this.disabled}setEnabled(e){this.isManualOperationAllowed()&&this.disabled!==!e&&(this.disabled=!e,this.emitTrackUpdate())}setVideoQuality(e){this.isManualOperationAllowed()&&this.currentVideoQuality!==e&&(this.currentVideoQuality=e,this.videoDimensions=void 0,this.emitTrackUpdate())}setVideoDimensions(e){var t,i;this.isManualOperationAllowed()&&((null===(t=this.videoDimensions)||void 0===t?void 0:t.width)===e.width&&(null===(i=this.videoDimensions)||void 0===i?void 0:i.height)===e.height||(this.track instanceof $o&&(this.videoDimensions=e),this.currentVideoQuality=void 0,this.emitTrackUpdate()))}setVideoFPS(e){this.isManualOperationAllowed()&&this.track instanceof $o&&this.fps!==e&&(this.fps=e,this.emitTrackUpdate())}get videoQuality(){return this.currentVideoQuality}setTrack(t){const i=this.subscriptionStatus,n=this.permissionStatus,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(n),this.emitSubscriptionUpdateIfChanged(i))}setAllowed(e){const t=this.subscriptionStatus,i=this.permissionStatus;this.allowed=e,this.emitPermissionUpdateIfChanged(i),this.emitSubscriptionUpdateIfChanged(t)}setSubscriptionError(t){this.emit(e.TrackEvent.SubscriptionFailed,t)}updateInfo(t){super.updateInfo(t);const i=this.metadataMuted;this.metadataMuted=t.muted,this.track?this.track.setMuted(t.muted):i!==t.muted&&this.emit(t.muted?e.TrackEvent.Muted:e.TrackEvent.Unmuted)}emitSubscriptionUpdateIfChanged(t){const i=this.subscriptionStatus;t!==i&&this.emit(e.TrackEvent.SubscriptionStatusChanged,i,t)}emitPermissionUpdateIfChanged(t){this.permissionStatus!==t&&this.emit(e.TrackEvent.SubscriptionPermissionChanged,this.permissionStatus,t)}isManualOperationAllowed(){return this.kind===Hs.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 $o&&this.track.isAdaptiveStream}emitTrackUpdate(){const t=new Vt({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 la extends aa{static fromParticipantInfo(e,t,i){return new la(e,t.sid,t.identity,t.name,t.metadata,i,t.kind)}get logContext(){return Object.assign(Object.assign({},super.logContext),{rpID:this.sid,remoteParticipant:this.identity})}constructor(e,t,i,n,s,r){super(t,i||"",n,s,r,arguments.length>6&&void 0!==arguments[6]?arguments[6]:nt.STANDARD),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),nr(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,(i=>{this.emit(e.ParticipantEvent.TrackSubscriptionPermissionChanged,t,i)})),t.on(e.TrackEvent.SubscriptionStatusChanged,(i=>{this.emit(e.ParticipantEvent.TrackSubscriptionStatusChanged,t,i)})),t.on(e.TrackEvent.Subscribed,(i=>{this.emit(e.ParticipantEvent.TrackSubscribed,i,t)})),t.on(e.TrackEvent.Unsubscribed,(i=>{this.emit(e.ParticipantEvent.TrackUnsubscribed,i,t)})),t.on(e.TrackEvent.SubscriptionFailed,(i=>{this.emit(e.ParticipantEvent.TrackSubscriptionFailed,t.trackSid,i)}))}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]:Hs.Source.Microphone;this.volumeMap.set(t,e);const i=this.getTrackPublication(t);i&&i.track&&i.track.setVolume(e)}getVolume(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:Hs.Source.Microphone;const t=this.getTrackPublication(e);return t&&t.track?t.track.getVolume():this.volumeMap.get(e)}addSubscribedMediaTrack(t,i,n,s,r,o){let a=this.getTrackPublicationBySid(i);if(a||i.startsWith("TR")||this.trackPublications.forEach((e=>{a||t.kind!==e.kind.toString()||(a=e)})),!a)return 0===o?(this.log.error("could not find published track",Object.assign(Object.assign({},this.logContext),{trackSid:i})),void this.emit(e.ParticipantEvent.TrackSubscriptionFailed,i)):(void 0===o&&(o=20),void setTimeout((()=>{this.addSubscribedMediaTrack(t,i,n,s,r,o-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),nr(a))),void this.emit(e.ParticipantEvent.TrackSubscriptionFailed,i);let c;return c="video"===t.kind?new $o(t,i,s,r):new Xo(t,i,s,this.audioContext,this.audioOutput),c.source=a.source,c.isMuted=a.isMuted,c.setMediaStream(n),c.start(),a.setTrack(c),this.volumeMap.has(a.source)&&c instanceof Xo&&c.setVolume(this.volumeMap.get(a.source)),a}get hasMetadata(){return!!this.participantInfo}getTrackPublicationBySid(e){return this.trackPublications.get(e)}updateInfo(t){if(!super.updateInfo(t))return!1;const i=new Map,n=new Map;return t.tracks.forEach((e=>{var t,s;let r=this.getTrackPublicationBySid(e.sid);if(r)r.updateInfo(e);else{const i=Hs.kindFromProto(e.type);if(!i)return;r=new da(i,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}),r.updateInfo(e),n.set(e.sid,r);const o=Array.from(this.trackPublications.values()).find((e=>e.source===(null==r?void 0:r.source)));o&&r.source!==Hs.Source.Unknown&&this.log.debug("received a second track publication for ".concat(this.identity," with the same source: ").concat(r.source),Object.assign(Object.assign({},this.logContext),{oldTrack:nr(o),newTrack:nr(r)})),this.addTrackPublication(r)}i.set(e.sid,r)})),this.trackPublications.forEach((e=>{i.has(e.trackSid)||(this.log.trace("detected removed track on remote participant, unpublishing",Object.assign(Object.assign({},this.logContext),nr(e))),this.unpublishTrack(e.trackSid,!0))})),n.forEach((t=>{this.emit(e.ParticipantEvent.TrackPublished,t)})),!0}unpublishTrack(t,i){const n=this.trackPublications.get(t);if(!n)return;const{track:s}=n;switch(s&&(s.stop(),n.setTrack(void 0)),this.trackPublications.delete(t),n.kind){case Hs.Kind.Audio:this.audioTrackPublications.delete(t);break;case Hs.Kind.Video:this.videoTrackPublications.delete(t)}i&&this.emit(e.ParticipantEvent.TrackUnpublished,n)}setAudioOutput(e){return Di(this,void 0,void 0,(function*(){this.audioOutput=e;const t=[];this.audioTrackPublications.forEach((i=>{var n;i.track instanceof Xo&&t.push(i.track.setSinkId(null!==(n=e.deviceId)&&void 0!==n?n:"default"))})),yield Promise.all(t)}))}emit(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),n=1;n<t;n++)i[n-1]=arguments[n];return this.log.trace("participant event",Object.assign(Object.assign({},this.logContext),{event:e,args:i})),super.emit(e,...i)}}var ua;e.ConnectionState=void 0,(ua=e.ConnectionState||(e.ConnectionState={})).Disconnected="disconnected",ua.Connecting="connecting",ua.Connected="connected",ua.Reconnecting="reconnecting",ua.SignalReconnecting="signalReconnecting";class ha extends Yi.EventEmitter{constructor(t){var i,n,s;super(),i=this,this.state=e.ConnectionState.Disconnected,this.activeSpeakers=[],this.isE2EEEnabled=!1,this.audioEnabled=!0,this.isVideoPlaybackBlocked=!1,this.log=Ei,this.bufferedEvents=[],this.isResuming=!1,this.connect=(t,i,n)=>Di(this,void 0,void 0,(function*(){var s;if(!hr())throw kr()?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 r=yield this.disconnectLock.lock();if(this.state===e.ConnectionState.Connected)return this.log.info("already connected to room ".concat(this.name),this.logContext),r(),Promise.resolve();if(this.connectFuture)return r(),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),br(new URL(t))&&(void 0===this.regionUrlProvider?this.regionUrlProvider=new zo(t,i):this.regionUrlProvider.updateToken(i),this.regionUrlProvider.fetchRegionSettings().then((e=>{var t;null===(t=this.regionUrlProvider)||void 0===t||t.setServerReportedRegions(e)})).catch((e=>{this.log.warn("could not fetch region settings",Object.assign(Object.assign({},this.logContext),{error:e}))})));const o=(e,s,a)=>Di(this,void 0,void 0,(function*(){var c,d;this.abortController&&this.abortController.abort();const l=new AbortController;this.abortController=l,null==r||r();try{yield this.attemptConnection(null!=a?a:t,i,n,l),this.abortController=void 0,e()}catch(t){if(this.regionUrlProvider&&t instanceof gs&&3!==t.reason&&0!==t.reason){let i=null;try{i=yield this.regionUrlProvider.getNextBestRegionUrl(null===(c=this.abortController)||void 0===c?void 0:c.signal)}catch(e){if(e instanceof gs&&(401===e.status||3===e.reason))return this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),void s(e)}i&&!(null===(d=this.abortController)||void 0===d?void 0:d.signal.aborted)?(this.log.info("Initial connection failed with ConnectionError: ".concat(t.message,". Retrying with another region: ").concat(i),this.logContext),this.recreateEngine(),yield o(e,s,i)):(this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),s(t))}else this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),s(t)}})),a=this.regionUrl;return this.regionUrl=void 0,this.connectFuture=new _r(((e,t)=>{o(e,t,a)}),(()=>{this.clearConnectionFutures()})),this.connectFuture.promise})),this.connectSignal=(e,t,i,n,s,r)=>Di(this,void 0,void 0,(function*(){var o,a,c;const d=yield i.join(e,t,{autoSubscribe:n.autoSubscribe,adaptiveStream:"object"==typeof s.adaptiveStream||s.adaptiveStream,maxRetries:n.maxRetries,e2eeEnabled:!!this.e2eeManager,websocketTimeout:n.websocketTimeout},r.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,i]=e;return"".concat(t,": ").concat(i)})).join(", ")),{room:null===(o=d.room)||void 0===o?void 0:o.name,roomSid:null===(a=d.room)||void 0===a?void 0:a.sid,identity:null===(c=d.participant)||void 0===c?void 0:c.identity}),!d.serverVersion)throw new ks("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.localParticipant.setEnabledPublishCodecs(e.enabledPublishCodecs),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,i,n,s)=>Di(this,void 0,void 0,(function*(){var r,o,a;this.state===e.ConnectionState.Reconnecting||this.isResuming||(null===(r=this.engine)||void 0===r?void 0:r.pendingReconnect)?(this.log.info("Reconnection attempt replaced by new connection attempt",this.logContext),this.recreateEngine()):this.maybeCreateEngine(),(null===(o=this.regionUrlProvider)||void 0===o?void 0:o.isCloud())&&this.engine.setRegionUrlProvider(this.regionUrlProvider),this.acquireAudioContext(),this.connOptions=Object.assign(Object.assign({},yo),n),this.connOptions.rtcConfig&&(this.engine.rtcConfig=this.connOptions.rtcConfig),this.connOptions.peerConnectionTimeout&&(this.engine.peerConnectionTimeout=this.connOptions.peerConnectionTimeout);try{const n=yield this.connectSignal(t,i,this.engine,this.connOptions,this.options,s);this.applyJoinResponse(n),this.setupLocalParticipantEvents(),this.emit(e.RoomEvent.SignalConnected)}catch(e){yield this.engine.close(),this.recreateEngine();const t=new gs("could not establish signal connection");throw e instanceof Error&&(t.message="".concat(t.message,": ").concat(e.message)),e instanceof gs&&(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 gs("Connection attempt aborted");try{yield this.engine.waitForPCInitialConnection(this.connOptions.peerConnectionTimeout,s)}catch(e){throw yield this.engine.close(),this.recreateEngine(),e}vr()&&this.options.disconnectOnPageLeave&&(window.addEventListener("pagehide",this.onPageLeave),window.addEventListener("beforeunload",this.onPageLeave)),vr()&&(document.addEventListener("freeze",this.onPageLeave),null===(a=navigator.mediaDevices)||void 0===a||a.addEventListener("devicechange",this.handleDeviceChange)),this.setAndEmitConnectionState(e.ConnectionState.Connected),this.emit(e.RoomEvent.Connected),this.registerConnectionReconcile()})),this.disconnect=function(){for(var t=arguments.length,n=new Array(t),s=0;s<t;s++)n[s]=arguments[s];return Di(i,[...n],void 0,(function(){var t=this;let i=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return function*(){var n,s,r,o;const a=yield t.disconnectLock.lock();try{if(t.state===e.ConnectionState.Disconnected)return void t.log.debug("already disconnected",t.logContext);t.log.info("disconnect from room",Object.assign({},t.logContext)),(t.state===e.ConnectionState.Connecting||t.state===e.ConnectionState.Reconnecting||t.isResuming)&&(t.log.warn("abort connection attempt",t.logContext),null===(n=t.abortController)||void 0===n||n.abort(),null===(r=null===(s=t.connectFuture)||void 0===s?void 0:s.reject)||void 0===r||r.call(s,new gs("Client initiated disconnect")),t.connectFuture=void 0),(null===(o=t.engine)||void 0===o?void 0:o.client.isDisconnected)||(yield t.engine.client.sendLeave()),t.engine&&(yield t.engine.close()),t.handleDisconnect(i,Qe.CLIENT_INITIATED),t.engine=void 0}finally{a()}}()}))},this.onPageLeave=()=>Di(this,void 0,void 0,(function*(){this.log.info("Page leave detected, disconnecting",this.logContext),yield this.disconnect()})),this.startAudio=()=>Di(this,void 0,void 0,(function*(){const t=[],i=Ds();if(i&&"iOS"===i.os){const i="livekit-dummy-audio-el";let n=document.getElementById(i);if(!n){n=document.createElement("audio"),n.id=i,n.autoplay=!0,n.hidden=!0;const t=Nr();t.enabled=!0;const s=new MediaStream([t]);n.srcObject=s,document.addEventListener("visibilitychange",(()=>{n&&(n.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(n),this.once(e.RoomEvent.Disconnected,(()=>{null==n||n.remove(),n=null}))}t.push(n)}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=()=>Di(this,void 0,void 0,(function*(){const e=[];for(const t of this.remoteParticipants.values())t.videoTrackPublications.forEach((t=>{var i;null===(i=t.track)||void 0===i||i.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=>Di(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 i=this.remoteParticipants.get(e.identity);e.state===it.DISCONNECTED?this.handleParticipantDisconnected(e.identity,i):i=this.getOrCreateParticipant(e.identity,e)}))},this.handleActiveSpeakersUpdate=t=>{const i=[],n={};t.forEach((e=>{if(n[e.sid]=!0,e.sid===this.localParticipant.sid)this.localParticipant.audioLevel=e.level,this.localParticipant.setIsSpeaking(!0),i.push(this.localParticipant);else{const t=this.getRemoteParticipantBySid(e.sid);t&&(t.audioLevel=e.level,t.setIsSpeaking(!0),i.push(t))}})),n[this.localParticipant.sid]||(this.localParticipant.audioLevel=0,this.localParticipant.setIsSpeaking(!1)),this.remoteParticipants.forEach((e=>{n[e.sid]||(e.audioLevel=0,e.setIsSpeaking(!1))})),this.activeSpeakers=i,this.emitWhenConnected(e.RoomEvent.ActiveSpeakersChanged,i)},this.handleSpeakersChanged=t=>{const i=new Map;this.activeSpeakers.forEach((e=>{const t=this.remoteParticipants.get(e.identity);t&&t.sid!==e.sid||i.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?i.set(e.sid,t):i.delete(e.sid))}));const n=Array.from(i.values());n.sort(((e,t)=>t.audioLevel-e.audioLevel)),this.activeSpeakers=n,this.emitWhenConnected(e.RoomEvent.ActiveSpeakersChanged,n)},this.handleStreamStateUpdate=t=>{t.streamStates.forEach((t=>{const i=this.getRemoteParticipantBySid(t.participantSid);if(!i)return;const n=i.getTrackPublicationBySid(t.trackSid);n&&n.track&&(n.track.streamState=Hs.streamStateFromProto(t.state),i.emit(e.ParticipantEvent.TrackStreamStateChanged,n,n.track.streamState),this.emitWhenConnected(e.RoomEvent.TrackStreamStateChanged,n,n.track.streamState,i))}))},this.handleSubscriptionPermissionUpdate=e=>{const t=this.getRemoteParticipantBySid(e.participantSid);if(!t)return;const i=t.getTrackPublicationBySid(e.trackSid);i&&i.setAllowed(e.allowed)},this.handleSubscriptionError=e=>{const t=Array.from(this.remoteParticipants.values()).find((t=>t.trackPublications.has(e.trackSid)));if(!t)return;const i=t.getTrackPublicationBySid(e.trackSid);i&&i.setSubscriptionError(e.err)},this.handleDataPacket=e=>{const t=this.remoteParticipants.get(e.participantIdentity);"user"===e.value.case?this.handleUserPacket(t,e.value.value,e.kind):"transcription"===e.value.case?this.handleTranscription(t,e.value.value):"sipDtmf"===e.value.case&&this.handleSipDtmf(t,e.value.value)},this.handleUserPacket=(t,i,n)=>{this.emit(e.RoomEvent.DataReceived,i.payload,t,n,i.topic),null==t||t.emit(e.ParticipantEvent.DataReceived,i.payload,n)},this.handleSipDtmf=(t,i)=>{this.emit(e.RoomEvent.SipDTMFReceived,i,t),null==t||t.emit(e.ParticipantEvent.SipDTMFReceived,i)},this.bufferedSegments=new Map,this.handleTranscription=(t,i)=>{const n=i.transcribedParticipantIdentity===this.localParticipant.identity?this.localParticipant:this.getParticipantByIdentity(i.transcribedParticipantIdentity),s=null==n?void 0:n.trackPublications.get(i.trackId),r=function(e,t){return e.segments.map((e=>{let{id:i,text:n,language:s,startTime:r,endTime:o,final:a}=e;var c;const d=null!==(c=t.get(i))&&void 0!==c?c:Date.now(),l=Date.now();return a?t.delete(i):t.set(i,d),{id:i,text:n,startTime:Number.parseInt(r.toString()),endTime:Number.parseInt(o.toString()),final:a,language:s,firstReceivedTime:d,lastReceivedTime:l}}))}(i,this.transcriptionReceivedTimes);null==s||s.emit(e.TrackEvent.TranscriptionReceived,r),null==n||n.emit(e.ParticipantEvent.TranscriptionReceived,r,s),this.emit(e.RoomEvent.TranscriptionReceived,r,n,s)},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=()=>Di(this,void 0,void 0,(function*(){const t=yield Fr.getInstance().getDevices(),i=["audiooutput"];for(let e of i){const i=t.filter((t=>t.kind===e));i.length>0&&!i.find((t=>t.deviceId===this.getActiveDevice(e)))&&(yield this.switchActiveDevice(e,i[0].deviceId))}this.emit(e.RoomEvent.MediaDevicesChanged)})),this.handleRoomUpdate=t=>{const i=this.roomInfo;this.roomInfo=t,i&&i.metadata!==t.metadata&&this.emitWhenConnected(e.RoomEvent.RoomMetadataChanged,t.metadata),(null==i?void 0:i.activeRecording)!==t.activeRecording&&this.emitWhenConnected(e.RoomEvent.RecordingStatusChanged,t.activeRecording)},this.handleConnectionQualityUpdate=e=>{e.updates.forEach((e=>{if(e.participantSid===this.localParticipant.sid)return void this.localParticipant.setConnectionQuality(e.quality);const t=this.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.onLocalAttributesChanged=t=>{this.emit(e.RoomEvent.ParticipantAttributesChanged,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=>Di(this,void 0,void 0,(function*(){var i,n,s,r,o,a;if(null===(i=t.track)||void 0===i||i.on(e.TrackEvent.TrackProcessorUpdate,this.onTrackProcessorUpdate),null===(n=t.track)||void 0===n||n.on(e.TrackEvent.Restarted,this.onLocalTrackRestarted),null===(o=null===(r=null===(s=t.track)||void 0===s?void 0:s.getProcessor())||void 0===r?void 0:r.onPublish)||void 0===o||o.call(r,this),this.emit(e.RoomEvent.LocalTrackPublished,t,this.localParticipant),t.track instanceof wo){(yield t.track.checkForSilence())&&this.emit(e.RoomEvent.LocalAudioSilenceDetected,t)}const c=yield null===(a=t.track)||void 0===a?void 0:a.getDeviceId(),d=Zs(t.source);d&&c&&c!==this.localParticipant.activeDeviceMap.get(d)&&(this.localParticipant.activeDeviceMap.set(d,c),this.emit(e.RoomEvent.ActiveDeviceChanged,d,c))})),this.onLocalTrackUnpublished=t=>{var i,n;null===(i=t.track)||void 0===i||i.off(e.TrackEvent.TrackProcessorUpdate,this.onTrackProcessorUpdate),null===(n=t.track)||void 0===n||n.off(e.TrackEvent.Restarted,this.onLocalTrackRestarted),this.emit(e.RoomEvent.LocalTrackUnpublished,t,this.localParticipant)},this.onLocalTrackRestarted=t=>Di(this,void 0,void 0,(function*(){const i=yield t.getDeviceId(!1),n=Zs(t.source);n&&i&&i!==this.localParticipant.activeDeviceMap.get(n)&&(this.log.debug("local track restarted, setting ".concat(n," ").concat(i," active"),this.logContext),this.localParticipant.activeDeviceMap.set(n,i),this.emit(e.RoomEvent.ActiveDeviceChanged,n,i))})),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({},bo),t),this.log=Pi(null!==(n=this.options.loggerName)&&void 0!==n?n:e.LoggerNames.Room),this.transcriptionReceivedTimes=new Map,this.options.audioCaptureDefaults=Object.assign(Object.assign({},vo),null==t?void 0:t.audioCaptureDefaults),this.options.videoCaptureDefaults=Object.assign(Object.assign({},ko),null==t?void 0:t.videoCaptureDefaults),this.options.publishDefaults=Object.assign(Object.assign({},fo),null==t?void 0:t.publishDefaults),this.maybeCreateEngine(),this.disconnectLock=new Ar,this.localParticipant=new ca("","",this.engine,this.options),this.options.videoCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("videoinput",Lr(this.options.videoCaptureDefaults.deviceId)),this.options.audioCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("audioinput",Lr(this.options.audioCaptureDefaults.deviceId)),(null===(s=this.options.audioOutput)||void 0===s?void 0:s.deviceId)&&this.switchActiveDevice("audiooutput",Lr(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 Di(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 Vr(this.options.e2ee),this.e2eeManager.on(e.EncryptionEvent.ParticipantEncryptionStatusChanged,((t,i)=>{i instanceof ca&&(this.isE2EEEnabled=t),this.emit(e.RoomEvent.ParticipantEncryptionStatusChanged,t,i)})),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 Di(this,void 0,void 0,(function*(){return this.state===e.ConnectionState.Disconnected?"":this.roomInfo&&""!==this.roomInfo.sid?this.roomInfo.sid:new Promise(((t,i)=>{const n=i=>{""!==i.sid&&(this.engine.off(e.EngineEvent.RoomUpdate,n),t(i.sid))};this.engine.on(e.EngineEvent.RoomUpdate,n),this.once(e.RoomEvent.Disconnected,(()=>{this.engine.off(e.EngineEvent.RoomUpdate,n),i("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 Jo(this.options),this.engine.on(e.EngineEvent.ParticipantUpdate,this.handleParticipantUpdates).on(e.EngineEvent.RoomUpdate,this.handleRoomUpdate).on(e.EngineEvent.SpeakersChanged,this.handleSpeakersChanged).on(e.EngineEvent.StreamStateChanged,this.handleStreamStateUpdate).on(e.EngineEvent.ConnectionQualityUpdate,this.handleConnectionQualityUpdate).on(e.EngineEvent.SubscriptionError,this.handleSubscriptionError).on(e.EngineEvent.SubscriptionPermissionUpdate,this.handleSubscriptionPermissionUpdate).on(e.EngineEvent.MediaTrackAdded,((e,t,i)=>{this.onTrackAdded(e,t,i)})).on(e.EngineEvent.Disconnected,(e=>{this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e)})).on(e.EngineEvent.ActiveSpeakersUpdate,this.handleActiveSpeakersUpdate).on(e.EngineEvent.DataPacketReceived,this.handleDataPacket).on(e.EngineEvent.Resuming,(()=>{this.clearConnectionReconcile(),this.isResuming=!0,this.log.info("Resuming signal connection",this.logContext),this.setAndEmitConnectionState(e.ConnectionState.SignalReconnecting)&&this.emit(e.RoomEvent.SignalReconnecting)})).on(e.EngineEvent.Resumed,(()=>{this.registerConnectionReconcile(),this.isResuming=!1,this.log.info("Resumed signal connection",this.logContext),this.updateSubscriptions(),this.emitBufferedEvents(),this.setAndEmitConnectionState(e.ConnectionState.Connected)&&this.emit(e.RoomEvent.Reconnected)})).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,i)=>{this.emit(e.RoomEvent.DCBufferStatusChanged,t,i)})).on(e.EngineEvent.LocalTrackSubscribed,(t=>{const i=this.localParticipant.getTrackPublications().find((e=>{let{trackSid:i}=e;return i===t}));i?(this.localParticipant.emit(e.ParticipantEvent.LocalTrackSubscribed,i),this.emitWhenConnected(e.RoomEvent.LocalTrackSubscribed,i,this.localParticipant)):this.log.warn("could not find local track subscription for subscribed event",this.logContext)})),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 Fr.getInstance().getDevices(e,t)}prepareConnection(t,i){return Di(this,void 0,void 0,(function*(){if(this.state===e.ConnectionState.Disconnected){this.log.debug("prepareConnection to ".concat(t),this.logContext);try{if(br(new URL(t))&&i){this.regionUrlProvider=new zo(t,i);const n=yield this.regionUrlProvider.getNextBestRegionUrl();n&&this.state===e.ConnectionState.Disconnected&&(this.regionUrl=n,yield fetch(Ur(n),{method:"HEAD"}),this.log.debug("prepared connection to ".concat(n),this.logContext))}else yield fetch(Ur(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 Di(this,void 0,void 0,(function*(){let i,n=()=>{};switch(e){case"signal-reconnect":yield this.engine.client.handleOnClose("simulate disconnect");break;case"speaker":i=new di({scenario:{case:"speakerUpdate",value:3}});break;case"node-failure":i=new di({scenario:{case:"nodeFailure",value:!0}});break;case"server-leave":i=new di({scenario:{case:"serverLeave",value:!0}});break;case"migration":i=new di({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":n=()=>Di(this,void 0,void 0,(function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")})),i=new di({scenario:{case:"disconnectSignalOnResume",value:!0}});break;case"disconnect-signal-on-resume-no-messages":n=()=>Di(this,void 0,void 0,(function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")})),i=new di({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":i=new di({scenario:{case:"switchCandidateProtocol",value:"force-tls"===e?2:1}}),n=()=>Di(this,void 0,void 0,(function*(){const e=this.engine.client.onLeave;e&&e(new Wt({reason:Qe.CLIENT_INITIATED,action:Gt.RECONNECT}))}));break;case"subscriber-bandwidth":if(void 0===t||"number"!=typeof t)throw new Error("subscriber-bandwidth requires a number as argument");i=new di({scenario:{case:"subscriberBandwidth",value:BigInt(t)}});break;case"leave-full-reconnect":i=new di({scenario:{case:"leaveRequestFullReconnect",value:!0}})}i&&(yield this.engine.client.sendSimulateScenario(i),yield n())}))}get canPlaybackAudio(){return this.audioEnabled}get canPlaybackVideo(){return!this.isVideoPlaybackBlocked}getActiveDevice(e){return this.localParticipant.activeDeviceMap.get(e)}switchActiveDevice(t,i){return Di(this,arguments,void 0,(function(t,i){var n=this;let s=arguments.length>2&&void 0!==arguments[2]&&arguments[2];return function*(){var r,o,a,c,d,l,u;let h=!1,p=!0;const m=s?{exact:i}:i;if("audioinput"===t){const e=null!==(r=n.getActiveDevice(t))&&void 0!==r?r:n.options.audioCaptureDefaults.deviceId;n.options.audioCaptureDefaults.deviceId=m,h=e!==m;const i=Array.from(n.localParticipant.audioTrackPublications.values()).filter((e=>e.source===Hs.Source.Microphone));try{p=(yield Promise.all(i.map((e=>{var t;return null===(t=e.audioTrack)||void 0===t?void 0:t.setDeviceId(m)})))).every((e=>!0===e))}catch(t){throw n.options.audioCaptureDefaults.deviceId=e,t}}else if("videoinput"===t){const e=null!==(o=n.getActiveDevice(t))&&void 0!==o?o:n.options.videoCaptureDefaults.deviceId;n.options.videoCaptureDefaults.deviceId=m,h=e!==m;const i=Array.from(n.localParticipant.videoTrackPublications.values()).filter((e=>e.source===Hs.Source.Camera));try{p=(yield Promise.all(i.map((e=>{var t;return null===(t=e.videoTrack)||void 0===t?void 0:t.setDeviceId(m)})))).every((e=>!0===e))}catch(t){throw n.options.videoCaptureDefaults.deviceId=e,t}}else if("audiooutput"===t){if(!ur()&&!n.options.webAudioMix||n.options.webAudioMix&&n.audioContext&&!("setSinkId"in n.audioContext))throw new Error("cannot switch audio output, setSinkId not supported");n.options.webAudioMix&&(i=null!==(a=yield Fr.getInstance().normalizeDeviceId("audiooutput",i))&&void 0!==a?a:""),null!==(c=(u=n.options).audioOutput)&&void 0!==c||(u.audioOutput={});const e=null!==(d=n.getActiveDevice(t))&&void 0!==d?d:n.options.audioOutput.deviceId;n.options.audioOutput.deviceId=i,h=e!==m;try{n.options.webAudioMix&&(null===(l=n.audioContext)||void 0===l||l.setSinkId(i)),yield Promise.all(Array.from(n.remoteParticipants.values()).map((e=>e.setAudioOutput({deviceId:i}))))}catch(t){throw n.options.audioOutput.deviceId=e,t}}return h&&p&&(n.localParticipant.activeDeviceMap.set(t,i),n.emit(e.RoomEvent.ActiveDeviceChanged,t,i)),p}()}))}setupLocalParticipantEvents(){this.localParticipant.on(e.ParticipantEvent.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).on(e.ParticipantEvent.ParticipantNameChanged,this.onLocalParticipantNameChanged).on(e.ParticipantEvent.AttributesChanged,this.onLocalAttributesChanged).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,i,n){if(this.state===e.ConnectionState.Connecting||this.state===e.ConnectionState.Reconnecting){const s=()=>{this.onTrackAdded(t,i,n),r()},r=()=>{this.off(e.RoomEvent.Reconnected,s),this.off(e.RoomEvent.Connected,s),this.off(e.RoomEvent.Disconnected,r)};return this.once(e.RoomEvent.Reconnected,s),this.once(e.RoomEvent.Connected,s),void this.once(e.RoomEvent.Disconnected,r)}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,""]}(i.id),r=s[0];let o=s[1],a=t.id;if(o&&o.startsWith("TR")&&(a=o),r===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===r));if(!c)return void this.log.error("Tried to add a track for a participant, that's not present. Sid: ".concat(r),this.logContext);let d;this.options.adaptiveStream&&(d="object"==typeof this.options.adaptiveStream?this.options.adaptiveStream:{}),c.addSubscribedMediaTrack(t,a,i,n,d)}handleDisconnect(){let t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0],i=arguments.length>1?arguments[1]:void 0;var n;if(this.clearConnectionReconcile(),this.isResuming=!1,this.bufferedEvents=[],this.transcriptionReceivedTimes.clear(),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 i,n;e.track&&this.localParticipant.unpublishTrack(e.track,t),t&&(null===(i=e.track)||void 0===i||i.detach(),null===(n=e.track)||void 0===n||n.stop())})),this.localParticipant.off(e.ParticipantEvent.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).off(e.ParticipantEvent.ParticipantNameChanged,this.onLocalParticipantNameChanged).off(e.ParticipantEvent.AttributesChanged,this.onLocalAttributesChanged).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),vr()&&(window.removeEventListener("beforeunload",this.onPageLeave),window.removeEventListener("pagehide",this.onPageLeave),window.removeEventListener("freeze",this.onPageLeave),null===(n=navigator.mediaDevices)||void 0===n||n.removeEventListener("devicechange",this.handleDeviceChange))}finally{this.setAndEmitConnectionState(e.ConnectionState.Disconnected),this.emit(e.RoomEvent.Disconnected,i)}}}handleParticipantDisconnected(t,i){this.remoteParticipants.delete(t),i&&(i.trackPublications.forEach((e=>{i.unpublishTrack(e.trackSid,!0)})),this.emit(e.RoomEvent.ParticipantDisconnected,i))}acquireAudioContext(){return Di(this,void 0,void 0,(function*(){var t,i;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=$s())&&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 n="running"===(null===(i=this.audioContext)||void 0===i?void 0:i.state);n!==this.canPlaybackAudio&&(this.audioEnabled=n,this.emit(e.RoomEvent.AudioPlaybackStatusChanged,n))}))}createParticipant(e,t){var i;let n;return n=t?la.fromParticipantInfo(this.engine.client,t,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}):new la(this.engine.client,"",e,void 0,void 0,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}),this.options.webAudioMix&&n.setAudioContext(this.audioContext),(null===(i=this.options.audioOutput)||void 0===i?void 0:i.deviceId)&&n.setAudioOutput(this.options.audioOutput).catch((e=>this.log.warn("Could not set audio output: ".concat(e.message),this.logContext))),n}getOrCreateParticipant(t,i){if(this.remoteParticipants.has(t)){const e=this.remoteParticipants.get(t);if(i){e.updateInfo(i)&&this.sidToIdentity.set(i.sid,i.identity)}return e}const n=this.createParticipant(t,i);return this.remoteParticipants.set(t,n),this.sidToIdentity.set(i.sid,i.identity),this.emitWhenConnected(e.RoomEvent.ParticipantConnected,n),n.on(e.ParticipantEvent.TrackPublished,(t=>{this.emitWhenConnected(e.RoomEvent.TrackPublished,t,n)})).on(e.ParticipantEvent.TrackSubscribed,((t,i)=>{t.kind===Hs.Kind.Audio?(t.on(e.TrackEvent.AudioPlaybackStarted,this.handleAudioPlaybackStarted),t.on(e.TrackEvent.AudioPlaybackFailed,this.handleAudioPlaybackFailed)):t.kind===Hs.Kind.Video&&(t.on(e.TrackEvent.VideoPlaybackFailed,this.handleVideoPlaybackFailed),t.on(e.TrackEvent.VideoPlaybackStarted,this.handleVideoPlaybackStarted)),this.emit(e.RoomEvent.TrackSubscribed,t,i,n)})).on(e.ParticipantEvent.TrackUnpublished,(t=>{this.emit(e.RoomEvent.TrackUnpublished,t,n)})).on(e.ParticipantEvent.TrackUnsubscribed,((t,i)=>{this.emit(e.RoomEvent.TrackUnsubscribed,t,i,n)})).on(e.ParticipantEvent.TrackSubscriptionFailed,(t=>{this.emit(e.RoomEvent.TrackSubscriptionFailed,t,n)})).on(e.ParticipantEvent.TrackMuted,(t=>{this.emitWhenConnected(e.RoomEvent.TrackMuted,t,n)})).on(e.ParticipantEvent.TrackUnmuted,(t=>{this.emitWhenConnected(e.RoomEvent.TrackUnmuted,t,n)})).on(e.ParticipantEvent.ParticipantMetadataChanged,(t=>{this.emitWhenConnected(e.RoomEvent.ParticipantMetadataChanged,t,n)})).on(e.ParticipantEvent.ParticipantNameChanged,(t=>{this.emitWhenConnected(e.RoomEvent.ParticipantNameChanged,t,n)})).on(e.ParticipantEvent.AttributesChanged,(t=>{this.emitWhenConnected(e.RoomEvent.ParticipantAttributesChanged,t,n)})).on(e.ParticipantEvent.ConnectionQualityChanged,(t=>{this.emitWhenConnected(e.RoomEvent.ConnectionQualityChanged,t,n)})).on(e.ParticipantEvent.ParticipantPermissionsChanged,(t=>{this.emitWhenConnected(e.RoomEvent.ParticipantPermissionsChanged,t,n)})).on(e.ParticipantEvent.TrackSubscriptionStatusChanged,((t,i)=>{this.emitWhenConnected(e.RoomEvent.TrackSubscriptionStatusChanged,t,i,n)})).on(e.ParticipantEvent.TrackSubscriptionFailed,((t,i)=>{this.emit(e.RoomEvent.TrackSubscriptionFailed,t,n,i)})).on(e.ParticipantEvent.TrackSubscriptionPermissionChanged,((t,i)=>{this.emitWhenConnected(e.RoomEvent.TrackSubscriptionPermissionChanged,t,i,n)})),i&&n.updateInfo(i),n}sendSyncState(){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 da&&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=Ls.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)))}),4e3)}clearConnectionReconcile(){this.connectionReconcileInterval&&Ls.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,i]=e;this.emit(t,...i)})),this.bufferedEvents=[]}emitWhenConnected(t){for(var i=arguments.length,n=new Array(i>1?i-1:0),s=1;s<i;s++)n[s-1]=arguments[s];if(this.state===e.ConnectionState.Reconnecting||this.isResuming||!this.engine||this.engine.pendingReconnect)this.bufferedEvents.push([t,n]);else if(this.state===e.ConnectionState.Connected)return this.emit(t,...n);return!1}simulateParticipants(t){return Di(this,void 0,void 0,(function*(){var i,n;const s=Object.assign({audio:!0,video:!0,useRealTracks:!1},t.publish),r=Object.assign({count:9,audio:!1,video:!0,aspectRatios:[1.66,1.7,1.3]},t.participants);if(this.handleDisconnect(),this.roomInfo=new $e({sid:"RM_SIMULATED",name:"simulated-room",emptyTimeout:0,maxParticipants:0,creationTime:I.parse((new Date).getTime()),metadata:"",numParticipants:1,numPublishers:1,turnPassword:"",enabledCodecs:[],activeRecording:!1}),this.localParticipant.updateInfo(new tt({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 ia(Hs.Kind.Video,new ot({source:We.CAMERA,sid:Math.floor(1e4*Math.random()).toString(),type:Ke.AUDIO,name:"video-dummy"}),new Fo(s.useRealTracks?(yield window.navigator.mediaDevices.getUserMedia({video:!0})).getVideoTracks()[0]:Mr(160*(null!==(i=r.aspectRatios[0])&&void 0!==i?i: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 ia(Hs.Kind.Audio,new ot({source:We.MICROPHONE,sid:Math.floor(1e4*Math.random()).toString(),type:Ke.AUDIO}),new wo(s.useRealTracks?(yield navigator.mediaDevices.getUserMedia({audio:!0})).getAudioTracks()[0]:Nr(),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<r.count-1;e+=1){let t=new tt({sid:Math.floor(1e4*Math.random()).toString(),identity:"simulated-".concat(e),state:it.ACTIVE,tracks:[],joinedAt:I.parse(Date.now())});const i=this.getOrCreateParticipant(t.identity,t);if(r.video){const s=Mr(160*(null!==(n=r.aspectRatios[e%r.aspectRatios.length])&&void 0!==n?n:1),160,!1,!0),o=new ot({source:We.CAMERA,sid:Math.floor(1e4*Math.random()).toString(),type:Ke.AUDIO});i.addSubscribedMediaTrack(s,o.sid,new MediaStream([s]),new RTCRtpReceiver),t.tracks=[...t.tracks,o]}if(r.audio){const e=Nr(),n=new ot({source:We.MICROPHONE,sid:Math.floor(1e4*Math.random()).toString(),type:Ke.AUDIO});i.addSubscribedMediaTrack(e,n.sid,new MediaStream([e]),new RTCRtpReceiver),t.tracks=[...t.tracks,n]}i.updateInfo(t)}}))}emit(t){for(var i=arguments.length,n=new Array(i>1?i-1:0),s=1;s<i;s++)n[s-1]=arguments[s];if(t!==e.RoomEvent.ActiveSpeakersChanged){const e=pa(n).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,...n)}}function pa(e){return e.map((e=>{if(e)return Array.isArray(e)?pa(e):"object"==typeof e?"logContext"in e&&e.logContext:e}))}var ma;e.CheckStatus=void 0,(ma=e.CheckStatus||(e.CheckStatus={}))[ma.IDLE=0]="IDLE",ma[ma.RUNNING=1]="RUNNING",ma[ma.SKIPPED=2]="SKIPPED",ma[ma.SUCCESS=3]="SUCCESS",ma[ma.FAILED=4]="FAILED";class ga extends Yi.EventEmitter{constructor(t,i){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};super(),this.status=e.CheckStatus.IDLE,this.logs=[],this.errorsAsWarnings=!1,this.url=t,this.token=i,this.name=this.constructor.name,this.room=new ha(n.roomOptions),this.connectOptions=n.connectOptions,n.errorsAsWarnings&&(this.errorsAsWarnings=n.errorsAsWarnings)}run(t){return Di(this,void 0,void 0,(function*(){if(this.status!==e.CheckStatus.IDLE)throw Error("check is running already");this.setStatus(e.CheckStatus.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!==e.CheckStatus.SKIPPED&&this.setStatus(this.isSuccess()?e.CheckStatus.SUCCESS:e.CheckStatus.FAILED),t&&t(),this.getInfo()}))}isSuccess(){return!this.logs.some((e=>"error"===e.level))}connect(){return Di(this,void 0,void 0,(function*(){return this.room.state===e.ConnectionState.Connected||(yield this.room.connect(this.url,this.token,this.connectOptions)),this.room}))}disconnect(){return Di(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(e.CheckStatus.SKIPPED)}appendMessage(e){this.logs.push({level:"info",message:e}),this.emit("update",this.getInfo())}appendWarning(e){this.logs.push({level:"warning",message:e}),this.emit("update",this.getInfo())}appendError(e){this.logs.push({level:"error",message:e}),this.emit("update",this.getInfo())}setStatus(e){this.status=e,this.emit("update",this.getInfo())}get engine(){var e;return null===(e=this.room)||void 0===e?void 0:e.engine}getInfo(){return{logs:this.logs,name:this.name,status:this.status,description:this.description}}}class fa extends ga{get description(){return"Can publish audio"}perform(){return Di(this,void 0,void 0,(function*(){var e;const t=yield this.connect(),i=yield oa();t.localParticipant.publishTrack(i),yield new Promise((e=>setTimeout(e,3e3)));const n=yield null===(e=i.sender)||void 0===e?void 0:e.getStats();if(!n)throw new Error("Could not get RTCStats");let s=0;if(n.forEach((e=>{"outbound-rtp"!==e.type||"audio"!==e.kind&&(e.kind||"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 va extends ga{get description(){return"Can publish video"}perform(){return Di(this,void 0,void 0,(function*(){var e;const t=yield this.connect(),i=yield ra();t.localParticipant.publishTrack(i),yield new Promise((e=>setTimeout(e,5e3)));const n=yield null===(e=i.sender)||void 0===e?void 0:e.getStats();if(!n)throw new Error("Could not get RTCStats");let s=0;if(n.forEach((e=>{"outbound-rtp"!==e.type||"video"!==e.kind&&(e.kind||"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 ka extends ga{get description(){return"Resuming connection after interruption"}perform(){return Di(this,void 0,void 0,(function*(){var t;const i=yield this.connect();let n,s=!1,r=!1;const o=new Promise((e=>{setTimeout(e,5e3),n=e})),a=()=>{s=!0};i.on(e.RoomEvent.SignalReconnecting,a).on(e.RoomEvent.Reconnecting,a).on(e.RoomEvent.Reconnected,(()=>{r=!0,n(!0)})),null===(t=i.engine.client.ws)||void 0===t||t.close();const c=i.engine.client.onClose;if(c&&c(""),yield o,!s)throw new Error("Did not attempt to reconnect");if(!r||i.state!==e.ConnectionState.Connected)throw this.appendWarning("reconnection is only possible in Redis-based configurations"),new Error("Not able to reconnect")}))}}class ba extends ga{get description(){return"Can connect via TURN"}perform(){return Di(this,void 0,void 0,(function*(){var e,t;const i=new Hr,n=yield i.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3});let s=!1,r=!1,o=!1;for(let e of n.iceServers)for(let t of e.urls)t.startsWith("turn:")?(r=!0,o=!0):t.startsWith("turns:")&&(r=!0,o=!0,s=!0),t.startsWith("stun:")&&(o=!0);o?r&&!s&&this.appendWarning("TURN is configured server side, but TURN/TLS is unavailable."):this.appendWarning("No STUN servers configured on server side."),yield i.close(),(null===(t=null===(e=this.connectOptions)||void 0===e?void 0:e.rtcConfig)||void 0===t?void 0:t.iceServers)||r?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 ya extends ga{get description(){return"Establishing WebRTC connection"}perform(){return Di(this,void 0,void 0,(function*(){let t=!1,i=!1;this.room.on(e.RoomEvent.SignalConnected,(()=>{const e=this.room.engine.client.onTrickle;this.room.engine.client.onTrickle=(n,s)=>{if(n.candidate){const e=new RTCIceCandidate(n);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&&(i=!0):s+=" (private)"),this.appendMessage(s)}e&&e(n,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(),Ei.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"),i||this.appendWarning("No public IPv4 UDP candidates were found. Your server is likely not configured correctly")}))}}class Ta extends ga{get description(){return"Connecting to signal connection via WebSocket"}perform(){return Di(this,void 0,void 0,(function*(){var e,t,i;(this.url.startsWith("ws:")||this.url.startsWith("http:"))&&this.appendWarning("Server is insecure, clients may block connections to it");let n=new Hr;const s=yield n.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)===kt.Cloud&&(null===(t=s.serverInfo)||void 0===t?void 0:t.region)&&this.appendMessage("LiveKit Cloud: ".concat(null===(i=s.serverInfo)||void 0===i?void 0:i.region)),yield n.close()}))}}class Ca extends Yi.EventEmitter{constructor(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};super(),this.options={},this.checkResults=new Map,this.url=e,this.token=t,this.options=i}getNextCheckId(){const t=this.checkResults.size;return this.checkResults.set(t,{logs:[],status:e.CheckStatus.IDLE,name:"",description:""}),t}updateCheck(e,t){this.checkResults.set(e,t),this.emit("checkUpdate",e,t)}isSuccess(){return Array.from(this.checkResults.values()).every((t=>t.status!==e.CheckStatus.FAILED))}getResults(){return Array.from(this.checkResults.values())}createAndRunCheck(e){return Di(this,void 0,void 0,(function*(){const t=this.getNextCheckId(),i=new e(this.url,this.token,this.options),n=e=>{this.updateCheck(t,e)};i.on("update",n);const s=yield i.run();return i.off("update",n),s}))}checkWebsocket(){return Di(this,void 0,void 0,(function*(){return this.createAndRunCheck(Ta)}))}checkWebRTC(){return Di(this,void 0,void 0,(function*(){return this.createAndRunCheck(ya)}))}checkTURN(){return Di(this,void 0,void 0,(function*(){return this.createAndRunCheck(ba)}))}checkReconnect(){return Di(this,void 0,void 0,(function*(){return this.createAndRunCheck(ka)}))}checkPublishAudio(){return Di(this,void 0,void 0,(function*(){return this.createAndRunCheck(fa)}))}checkPublishVideo(){return Di(this,void 0,void 0,(function*(){return this.createAndRunCheck(va)}))}}const Sa=new Map([["obs virtual camera",{facingMode:"environment",confidence:"medium"}]]),Ea=new Map([["iphone",{facingMode:"environment",confidence:"medium"}],["ipad",{facingMode:"environment",confidence:"medium"}]]);function wa(e){var t;const i=e.trim().toLowerCase();if(""!==i)return Sa.has(i)?Sa.get(i):null===(t=Array.from(Ea.entries()).find((e=>{let[t]=e;return i.includes(t)})))||void 0===t?void 0:t[1]}e.BaseKeyProvider=ps,e.Checker=ga,e.ConnectionCheck=Ca,e.ConnectionError=gs,e.CriticalTimers=Ls,e.CryptorError=class extends ms{constructor(t){let i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:e.CryptorErrorReason.InternalError,n=arguments.length>2?arguments[2]:void 0;super(40,t),this.reason=i,this.participantIdentity=n}},e.DataPacket_Kind=dt,e.DefaultReconnectPolicy=xi,e.DeviceUnsupportedError=fs,e.DisconnectReason=Qe,e.ExternalE2EEKeyProvider=class extends ps{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 Di(this,void 0,void 0,(function*(){const t="string"==typeof e?yield ls(e):yield us(e);this.onSetEncryptionKey(t)}))}},e.LivekitError=ms,e.LocalAudioTrack=wo,e.LocalParticipant=ca,e.LocalTrack=Br,e.LocalTrackPublication=ia,e.LocalVideoTrack=Fo,e.Mutex=Ar,e.NegotiationError=ys,e.Participant=aa,e.ParticipantKind=nt,e.PublishDataError=class extends ms{constructor(e){super(13,null!=e?e:"unable to publish data")}},e.RemoteAudioTrack=Xo,e.RemoteParticipant=la,e.RemoteTrack=Yo,e.RemoteTrackPublication=da,e.RemoteVideoTrack=$o,e.Room=ha,e.ScreenSharePresets=Ws,e.SignalRequestError=Ts,e.SubscriptionError=Ye,e.Track=Hs,e.TrackInvalidError=vs,e.TrackPublication=ta,e.UnexpectedConnectionState=bs,e.UnsupportedServer=ks,e.VideoPreset=Us,e.VideoPresets=qs,e.VideoPresets43=Ks,e.attachToElement=Js,e.createAudioAnalyser=function(e,t){const i=Object.assign({cloneTrack:!1,fftSize:2048,smoothingTimeConstant:.8,minDecibels:-100,maxDecibels:-80},t),n=$s();if(!n)throw new Error("Audio Context not supported on this browser");const s=i.cloneTrack?e.mediaStreamTrack.clone():e.mediaStreamTrack,r=n.createMediaStreamSource(new MediaStream([s])),o=n.createAnalyser();o.minDecibels=i.minDecibels,o.maxDecibels=i.maxDecibels,o.fftSize=i.fftSize,o.smoothingTimeConstant=i.smoothingTimeConstant,r.connect(o);const a=new Uint8Array(o.frequencyBinCount);return{calculateVolume:()=>{o.getByteFrequencyData(a);let e=0;for(const t of a)e+=Math.pow(t/255,2);return Math.sqrt(e/a.length)},analyser:o,cleanup:()=>Di(this,void 0,void 0,(function*(){yield n.close(),i.cloneTrack&&s.stop()}))}},e.createE2EEKey=function(){return window.crypto.getRandomValues(new Uint8Array(32))},e.createKeyMaterialFromBuffer=us,e.createKeyMaterialFromString=ls,e.createLocalAudioTrack=oa,e.createLocalScreenTracks=function(e){return Di(this,void 0,void 0,(function*(){if(void 0===e&&(e={}),void 0!==e.resolution||gr()||(e.resolution=Ws.h1080fps30.resolution),void 0===navigator.mediaDevices.getDisplayMedia)throw new fs("getDisplayMedia not supported");const t=er(e),i=yield navigator.mediaDevices.getDisplayMedia(t),n=i.getVideoTracks();if(0===n.length)throw new vs("no video track found");const s=new Fo(n[0],void 0,!1);s.source=Hs.Source.ScreenShare;const r=[s];if(i.getAudioTracks().length>0){const e=new wo(i.getAudioTracks()[0],void 0,!1);e.source=Hs.Source.ScreenShareAudio,r.push(e)}return r}))},e.createLocalTracks=sa,e.createLocalVideoTrack=ra,e.deriveKeys=function(e,t){return Di(this,void 0,void 0,(function*(){const i=hs(e.algorithm.name,t),n=yield crypto.subtle.deriveKey(i,e,{name:is,length:128},!1,["encrypt","decrypt"]);return{material:e,encryptionKey:n}}))},e.detachTrack=Qs,e.extractProcessorsFromOptions=na,e.facingModeFromDeviceLabel=wa,e.facingModeFromLocalTrack=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};var i;const n=e instanceof Br?e.mediaStreamTrack:e,s=n.getSettings();let r={facingMode:null!==(i=t.defaultFacingMode)&&void 0!==i?i:"user",confidence:"low"};if("facingMode"in s){const e=s.facingMode;Ei.trace("rawFacingMode",{rawFacingMode:e}),e&&"string"==typeof e&&function(e){const t=["user","environment","left","right"];return void 0===e||t.includes(e)}(e)&&(r={facingMode:e,confidence:"high"})}if(["low","medium"].includes(r.confidence)){Ei.trace("Try to get facing mode from device label: (".concat(n.label,")"));const e=wa(n.label);void 0!==e&&(r=e)}return r},e.getBrowser=Ds,e.getEmptyAudioStreamTrack=Nr,e.getEmptyVideoStreamTrack=function(){return xr||(xr=Mr()),xr.clone()},e.getLogger=Pi,e.importKey=function(e){return Di(this,arguments,void 0,(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{name:is},i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"encrypt";return function*(){return crypto.subtle.importKey("raw",e,t,!1,"derive"===i?["deriveBits","deriveKey"]:["encrypt","decrypt"])}()}))},e.isBackupCodec=Bs,e.isBrowserSupported=hr,e.isE2EESupported=as,e.isInsertableStreamSupported=ds,e.isScriptTransformSupported=cs,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 i=e.length,n=0;n<e.length;)i-n>=3&&!e[n]&&!e[n+1]&&3==e[n+2]?(t.push(e[n++]),t.push(e[n++]),n++):t.push(e[n++]);return new Uint8Array(t)},e.protocolVersion=15,e.ratchet=function(e,t){return Di(this,void 0,void 0,(function*(){const i=hs(e.algorithm.name,t);return crypto.subtle.deriveBits(i,e,256)}))},e.setLogExtension=function(t,i){(i?[i]:wi).forEach((i=>{const n=i.methodFactory;i.methodFactory=(i,s,r)=>{const o=n(i,s,r),a=e.LogLevel[i],c=a>=s&&a<e.LogLevel.silent;return(e,i)=>{i?o(e,i):o(e),c&&t(a,e,i)}},i.setLevel(i.getLevel())}))},e.setLogLevel=function(e,t){if(t)Si.getLogger(t).setLevel(e);else for(const t of wi)t.setLevel(e)},e.supportsAV1=cr,e.supportsAdaptiveStream=function(){return void 0!==typeof ResizeObserver&&void 0!==typeof IntersectionObserver},e.supportsDynacast=function(){return or()},e.supportsVP9=dr,e.version=As,e.videoCodecs=Fs,e.writeRbsp=function(e){const t=[];for(var i=0,n=0;n<e.length;++n){var s=e[n];s<=3&&i>=2&&(t.push(3),i=0),t.push(s),0==s?++i:i=0}return new Uint8Array(t)}}));
|
2
2
|
//# sourceMappingURL=livekit-client.umd.js.map
|