!function(e){"function"==typeof define&&define.amd?define(e):e()}((function(){"use strict";function e(e,t,n,r){return new(n||(n=Promise))((function(i,a){function o(e){try{c(r.next(e))}catch(e){a(e)}}function s(e){try{c(r.throw(e))}catch(e){a(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,s)}c((r=r.apply(e,t||[])).next())}))}"function"==typeof SuppressedError&&SuppressedError;var t,n={exports:{}};var r,i,a,o,s,c=(t||(t=1,i=n.exports,a=function(){var e=function(){},t="undefined",n=typeof window!==t&&typeof window.navigator!==t&&/Trident\/|MSIE /.test(window.navigator.userAgent),r=["trace","debug","info","warn","error"],i={},a=null;function o(e,t){var n=e[t];if("function"==typeof n.bind)return n.bind(e);try{return Function.prototype.bind.call(n,e)}catch(t){return function(){return Function.prototype.apply.apply(n,[e,arguments])}}}function s(){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 n=this.getLevel(),i=0;i=0&&t<=l.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),l.name=e,l.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},l.methodFactory=n||u,l.getLevel=function(){return null!=d?d:null!=s?s:o},l.setLevel=function(e,n){return d=p(e),!1!==n&&function(e){var n=(r[e]||"silent").toUpperCase();if(typeof window!==t&&h){try{return void(window.localStorage[h]=n)}catch(e){}try{window.document.cookie=encodeURIComponent(h)+"="+n+";"}catch(e){}}}(d),c.call(l)},l.setDefaultLevel=function(e){s=p(e),f()||l.setLevel(e,!1)},l.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(l)},l.enableAll=function(e){l.setLevel(l.levels.TRACE,e)},l.disableAll=function(e){l.setLevel(l.levels.SILENT,e)},l.rebuild=function(){if(a!==l&&(o=p(a.getLevel())),c.call(l),a===l)for(var e in i)i[e].rebuild()},o=p(a?a.getLevel():"WARN");var y=f();null!=y&&(d=p(y)),c.call(l)}(a=new l).getLogger=function(e){if("symbol"!=typeof e&&"string"!=typeof e||""===e)throw new TypeError("You must supply a name when creating a logger.");var t=i[e];return t||(t=i[e]=new l(e,a.methodFactory)),t};var h=typeof window!==t?window.log:void 0;return a.noConflict=function(){return typeof window!==t&&window.log===a&&(window.log=h),a},a.getLoggers=function(){return i},a.default=a,a},(r=n).exports?r.exports=a():i.log=a()),n.exports);!function(e){e[e.trace=0]="trace",e[e.debug=1]="debug",e[e.info=2]="info",e[e.warn=3]="warn",e[e.error=4]="error",e[e.silent=5]="silent"}(o||(o={})),function(e){e.Default="livekit",e.Room="livekit-room",e.TokenSource="livekit-token-source",e.Participant="livekit-participant",e.Track="livekit-track",e.Publication="livekit-track-publication",e.Engine="livekit-engine",e.Signal="livekit-signal",e.PCManager="livekit-pc-manager",e.PCTransport="livekit-pc-transport",e.E2EE="lk-e2ee",e.DataTracks="livekit-data-tracks"}(s||(s={}));let d=c.getLogger(s.Default);function u(e,t){const n=c.getLogger(e);return n.setDefaultLevel(d.getLevel()),n}Object.values(s).map((e=>c.getLogger(e))),d.setDefaultLevel(o.info);const l=c.getLogger(s.E2EE);var h,f=Object.defineProperty,p=(e,t,n)=>((e,t,n)=>t in e?f(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n)(e,"symbol"!=typeof t?t+"":t,n);class y{constructor(){p(this,"_locking"),p(this,"_locks"),this._locking=Promise.resolve(),this._locks=0}isLocked(){return this._locks>0}lock(){let e;this._locks+=1;const t=new Promise((t=>e=()=>{this._locks-=1,t()})),n=this._locking.then((()=>e));return this._locking=this._locking.then((()=>t)),n}}!function(e){e[e.WAITING=0]="WAITING",e[e.RUNNING=1]="RUNNING",e[e.COMPLETED=2]="COMPLETED"}(h||(h={}));const m="AES-GCM",g={key:10,delta:3,audio:1,empty:0},b={sharedKey:!1,ratchetSalt:"LKFrameEncryptionKey",ratchetWindowSize:8,failureTolerance:10,keyringSize:16,keySize:128};function v(e,t){if(!e)throw new Error(t)}function k(e){if("number"!=typeof e)throw new Error("invalid int 32: "+typeof e);if(!Number.isInteger(e)||e>2147483647||e<-2147483648)throw new Error("invalid int 32: "+e)}function w(e){if("number"!=typeof e)throw new Error("invalid uint 32: "+typeof e);if(!Number.isInteger(e)||e>4294967295||e<0)throw new Error("invalid uint 32: "+e)}function T(e){if("number"!=typeof e)throw new Error("invalid float 32: "+typeof e);if(Number.isFinite(e)&&(e>34028234663852886e22||e<-34028234663852886e22))throw new Error("invalid float 32: "+e)}const S=Symbol("@bufbuild/protobuf/enum-type");function I(e){const t=e[S];return v(t,"missing enum type on enum object"),t}function E(e,t,n,r){e[S]=N(t,n.map((t=>({no:t.no,name:t.name,localName:e[t.no]}))))}function N(e,t,n){const r=Object.create(null),i=Object.create(null),a=[];for(const e of t){const t=L(e);a.push(t),r[e.name]=t,i[e.no]=t}return{typeName:e,values:a,findName:e=>r[e],findNumber:e=>i[e]}}function A(e,t,n){const r={};for(const e of t){const t=L(e);r[t.localName]=t.no,r[t.no]=t.localName}return E(r,e,t),r}function L(e){return"localName"in e?e:Object.assign(Object.assign({},e),{localName:e.name})}class C{equals(e){return this.getType().runtime.util.equals(this.getType(),this,e)}clone(){return this.getType().runtime.util.clone(this)}fromBinary(e,t){const n=this.getType().runtime.bin,r=n.makeReadOptions(t);return n.readMessage(this,r.readerFactory(e),e.byteLength,r),this}fromJson(e,t){const n=this.getType(),r=n.runtime.json,i=r.makeReadOptions(t);return r.readMessage(n,e,i,this),this}fromJsonString(e,t){let n;try{n=JSON.parse(e)}catch(e){throw new Error("cannot decode ".concat(this.getType().typeName," from JSON: ").concat(e instanceof Error?e.message:String(e)))}return this.fromJson(n,t)}toBinary(e){const t=this.getType().runtime.bin,n=t.makeWriteOptions(e),r=n.writerFactory();return t.writeMessage(this,r,n),r.finish()}toJson(e){const t=this.getType().runtime.json,n=t.makeWriteOptions(e);return t.writeMessage(this,n)}toJsonString(e){var t;const n=this.toJson(e);return JSON.stringify(n,null,null!==(t=null==e?void 0:e.prettySpaces)&&void 0!==t?t:0)}toJSON(){return this.toJson({emitDefaultValues:!0})}getType(){return Object.getPrototypeOf(this).constructor}}function R(){let e=0,t=0;for(let n=0;n<28;n+=7){let r=this.buf[this.pos++];if(e|=(127&r)<>4,!(128&n))return this.assertBounds(),[e,t];for(let n=3;n<=31;n+=7){let r=this.buf[this.pos++];if(t|=(127&r)<>>r,a=!(i>>>7==0&&0==t),o=255&(a?128|i:i);if(n.push(o),!a)return}const r=e>>>28&15|(7&t)<<4,i=!!(t>>3);if(n.push(255&(i?128|r:r)),i){for(let e=3;e<31;e+=7){const r=t>>>e,i=!(r>>>7==0),a=255&(i?128|r:r);if(n.push(a),!i)return}n.push(t>>>31&1)}}const O=4294967296;function _(e){const t="-"===e[0];t&&(e=e.slice(1));const n=1e6;let r=0,i=0;function a(t,a){const o=Number(e.slice(t,a));i*=n,r=r*n+o,r>=O&&(i+=r/O|0,r%=O)}return a(-24,-18),a(-18,-12),a(-12,-6),a(-6),t?P(r,i):D(r,i)}function F(e,t){var n=function(e,t){return{lo:e>>>0,hi:t>>>0}}(e,t);if(e=n.lo,(t=n.hi)<=2097151)return String(O*t+e);const r=16777215&(e>>>24|t<<8),i=t>>16&65535;let a=(16777215&e)+6777216*r+6710656*i,o=r+8147497*i,s=2*i;const c=1e7;return a>=c&&(o+=Math.floor(a/c),a%=c),o>=c&&(s+=Math.floor(o/c),o%=c),s.toString()+M(o)+M(a)}function D(e,t){return{lo:0|e,hi:0|t}}function P(e,t){return t=~t,e?e=1+~e:t+=1,D(e,t)}const M=e=>{const t=String(e);return"0000000".slice(t.length)+t};function x(e,t){if(e>=0){for(;e>127;)t.push(127&e|128),e>>>=7;t.push(e)}else{for(let n=0;n<9;n++)t.push(127&e|128),e>>=7;t.push(1)}}function B(){let e=this.buf[this.pos++],t=127&e;if(!(128&e))return this.assertBounds(),t;if(e=this.buf[this.pos++],t|=(127&e)<<7,!(128&e))return this.assertBounds(),t;if(e=this.buf[this.pos++],t|=(127&e)<<14,!(128&e))return this.assertBounds(),t;if(e=this.buf[this.pos++],t|=(127&e)<<21,!(128&e))return this.assertBounds(),t;e=this.buf[this.pos++],t|=(15&e)<<28;for(let t=5;128&e&&t<10;t++)e=this.buf[this.pos++];if(128&e)throw new Error("invalid varint");return this.assertBounds(),t>>>0}const K=function(){const e=new DataView(new ArrayBuffer(8));if("function"==typeof BigInt&&"function"==typeof e.getBigInt64&&"function"==typeof e.getBigUint64&&"function"==typeof e.setBigInt64&&"function"==typeof e.setBigUint64&&("object"!=typeof process||"object"!=typeof process.env||"1"!==process.env.BUF_BIGINT_DISABLE)){const t=BigInt("-9223372036854775808"),n=BigInt("9223372036854775807"),r=BigInt("0"),i=BigInt("18446744073709551615");return{zero:BigInt(0),supported:!0,parse(e){const r="bigint"==typeof e?e:BigInt(e);if(r>n||ri||t(e.setInt32(0,t,!0),e.setInt32(4,n,!0),e.getBigInt64(0,!0)),uDec:(t,n)=>(e.setInt32(0,t,!0),e.setInt32(4,n,!0),e.getBigUint64(0,!0))}}const t=e=>v(/^-?[0-9]+$/.test(e),"int64 invalid: ".concat(e)),n=e=>v(/^[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),_(e)),uEnc:e=>("string"!=typeof e&&(e=e.toString()),n(e),_(e)),dec:(e,t)=>function(e,t){let n=D(e,t);const r=2147483648&n.hi;r&&(n=P(n.lo,n.hi));const i=F(n.lo,n.hi);return r?"-"+i:i}(e,t),uDec:(e,t)=>F(e,t)}}();var j,V,W;function q(e,t,n){if(t===n)return!0;if(e==j.BYTES){if(!(t instanceof Uint8Array&&n instanceof Uint8Array))return!1;if(t.length!==n.length)return!1;for(let e=0;ee.length)&&(t=e.length);for(var n=0,r=Array(t);n>>0)}raw(e){return this.buf.length&&(this.chunks.push(new Uint8Array(this.buf)),this.buf=[]),this.chunks.push(e),this}uint32(e){for(w(e);e>127;)this.buf.push(127&e|128),e>>>=7;return this.buf.push(e),this}int32(e){return k(e),x(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){T(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){w(e);let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!0),this.raw(t)}sfixed32(e){k(e);let t=new Uint8Array(4);return new DataView(t.buffer).setInt32(0,e,!0),this.raw(t)}sint32(e){return k(e),x(e=(e<<1^e>>31)>>>0,this.buf),this}sfixed64(e){let t=new Uint8Array(8),n=new DataView(t.buffer),r=K.enc(e);return n.setInt32(0,r.lo,!0),n.setInt32(4,r.hi,!0),this.raw(t)}fixed64(e){let t=new Uint8Array(8),n=new DataView(t.buffer),r=K.uEnc(e);return n.setInt32(0,r.lo,!0),n.setInt32(4,r.hi,!0),this.raw(t)}int64(e){let t=K.enc(e);return U(t.lo,t.hi,this.buf),this}sint64(e){let t=K.enc(e),n=t.hi>>31;return U(t.lo<<1^n,(t.hi<<1|t.lo>>>31)^n,this.buf),this}uint64(e){let t=K.uEnc(e);return U(t.lo,t.hi,this.buf),this}}class Y{constructor(e,t){this.varint64=R,this.uint32=B,this.buf=e,this.len=e.length,this.pos=0,this.view=new DataView(e.buffer,e.byteOffset,e.byteLength),this.textDecoder=null!=t?t:new TextDecoder}tag(){let e=this.uint32(),t=e>>>3,n=7&e;if(t<=0||n<0||n>5)throw new Error("illegal tag: field no "+t+" wire type "+n);return[t,n]}skip(e,t){let n=this.pos;switch(e){case W.Varint:for(;128&this.buf[this.pos++];);break;case W.Bit64:this.pos+=4;case W.Bit32:this.pos+=4;break;case W.LengthDelimited:let n=this.uint32();this.pos+=n;break;case W.StartGroup:for(;;){const e=H(this.tag(),2),n=e[0],r=e[1];if(r===W.EndGroup){if(void 0!==t&&n!==t)throw new Error("invalid end group tag");break}this.skip(r,n)}break;default:throw new Error("cant skip wire type "+e)}return this.assertBounds(),this.buf.subarray(n,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 K.dec(...this.varint64())}uint64(){return K.uDec(...this.varint64())}sint64(){let e=H(this.varint64(),2),t=e[0],n=e[1],r=-(1&t);return t=(t>>>1|(1&n)<<31)^r,n=n>>>1^r,K.dec(t,n)}bool(){let e=H(this.varint64(),2),t=e[0],n=e[1];return 0!==t||0!==n}fixed32(){return this.view.getUint32((this.pos+=4)-4,!0)}sfixed32(){return this.view.getInt32((this.pos+=4)-4,!0)}fixed64(){return K.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return K.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 Q(e){const t=e.field.localName,n=Object.create(null);return n[t]=function(e){const t=e.field;if(t.repeated)return[];if(void 0!==t.default)return t.default;switch(t.kind){case"enum":return t.T.values[0].no;case"scalar":return G(t.T,t.L);case"message":const e=t.T,n=new e;return e.fieldWrapper?e.fieldWrapper.unwrapField(n):n;case"map":throw"map fields are not allowed to be extensions"}}(e),[n,()=>n[t]]}let $="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),Z=[];for(let e=0;e<$.length;e++)Z[$[e].charCodeAt(0)]=e;Z["-".charCodeAt(0)]=$.indexOf("+"),Z["_".charCodeAt(0)]=$.indexOf("/");const ee={dec(e){let t=3*e.length/4;"="==e[e.length-2]?t-=2:"="==e[e.length-1]&&(t-=1);let n,r=new Uint8Array(t),i=0,a=0,o=0;for(let t=0;t>4,o=n,a=2;break;case 2:r[i++]=(15&o)<<4|(60&n)>>2,o=n,a=3;break;case 3:r[i++]=(3&o)<<6|n,a=0}}if(1==a)throw Error("invalid base64 string.");return r.subarray(0,i)},enc(e){let t,n="",r=0,i=0;for(let a=0;a>2],i=(3&t)<<4,r=1;break;case 1:n+=$[i|t>>4],i=(15&t)<<2,r=2;break;case 2:n+=$[i|t>>6],n+=$[63&t],r=0}return r&&(n+=$[i],n+="=",1==r&&(n+="=")),n}};function te(e,t,n){ie(t,e);const r=t.runtime.bin.makeReadOptions(n),i=function(e,t){if(!t.repeated&&("enum"==t.kind||"scalar"==t.kind)){for(let n=e.length-1;n>=0;--n)if(e[n].no==t.no)return[e[n]];return[]}return e.filter((e=>e.no===t.no))}(e.getType().runtime.bin.listUnknownFields(e),t.field),a=H(Q(t),2),o=a[0],s=a[1];for(const e of i)t.runtime.bin.readField(o,r.readerFactory(e.data),t.field,e.wireType,r);return s()}function ne(e,t,n,r){ie(t,e);const i=t.runtime.bin.makeReadOptions(r),a=t.runtime.bin.makeWriteOptions(r);if(re(e,t)){const n=e.getType().runtime.bin.listUnknownFields(e).filter((e=>e.no!=t.field.no));e.getType().runtime.bin.discardUnknownFields(e);for(const t of n)e.getType().runtime.bin.onUnknownField(e,t.no,t.wireType,t.data)}const o=a.writerFactory();let s=t.field;s.opt||s.repeated||"enum"!=s.kind&&"scalar"!=s.kind||(s=Object.assign(Object.assign({},t.field),{opt:!0})),t.runtime.bin.writeField(s,n,o,a);const c=i.readerFactory(o.finish());for(;c.pose.no==t.field.no))}function ie(e,t){v(e.extendee.typeName==t.getType().typeName,"extension ".concat(e.typeName," can only be applied to message ").concat(e.extendee.typeName))}function ae(e,t){const n=e.localName;if(e.repeated)return t[n].length>0;if(e.oneof)return t[e.oneof.localName].case===n;switch(e.kind){case"enum":case"scalar":return e.opt||e.req?void 0!==t[n]:"enum"==e.kind?t[n]!==e.T.values[0].no:!X(e.T,t[n]);case"message":return void 0!==t[n];case"map":return Object.keys(t[n]).length>0}}function oe(e,t){const n=e.localName,r=!e.opt&&!e.req;if(e.repeated)t[n]=[];else if(e.oneof)t[e.oneof.localName]={case:void 0};else switch(e.kind){case"map":t[n]={};break;case"enum":t[n]=r?e.T.values[0].no:void 0;break;case"scalar":t[n]=r?G(e.T,e.L):void 0;break;case"message":t[n]=void 0}}function se(e,t){if(null===e||"object"!=typeof e)return!1;if(!Object.getOwnPropertyNames(C.prototype).every((t=>t in e&&"function"==typeof e[t])))return!1;const n=e.getType();return null!==n&&"function"==typeof n&&"typeName"in n&&"string"==typeof n.typeName&&(void 0===t||n.typeName==t.typeName)}function ce(e,t){return se(t)||!e.fieldWrapper?t:e.fieldWrapper.wrapField(t)}j.DOUBLE,j.FLOAT,j.INT64,j.UINT64,j.INT32,j.UINT32,j.BOOL,j.STRING,j.BYTES;const de={ignoreUnknownFields:!1},ue={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0};function le(e){return e?Object.assign(Object.assign({},de),e):de}function he(e){return e?Object.assign(Object.assign({},ue),e):ue}const fe=Symbol(),pe=Symbol();function ye(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 me(e,t,n,r,i){let a=n.localName;if(n.repeated){if(v("map"!=n.kind),null===t)return;if(!Array.isArray(t))throw new Error("cannot decode field ".concat(i.typeName,".").concat(n.name," from JSON: ").concat(ye(t)));const o=e[a];for(const e of t){if(null===e)throw new Error("cannot decode field ".concat(i.typeName,".").concat(n.name," from JSON: ").concat(ye(e)));switch(n.kind){case"message":o.push(n.T.fromJson(e,r));break;case"enum":const t=ve(n.T,e,r.ignoreUnknownFields,!0);t!==pe&&o.push(t);break;case"scalar":try{o.push(be(n.T,e,n.L,!0))}catch(t){let r="cannot decode field ".concat(i.typeName,".").concat(n.name," from JSON: ").concat(ye(e));throw t instanceof Error&&t.message.length>0&&(r+=": ".concat(t.message)),new Error(r)}}}}else if("map"==n.kind){if(null===t)return;if("object"!=typeof t||Array.isArray(t))throw new Error("cannot decode field ".concat(i.typeName,".").concat(n.name," from JSON: ").concat(ye(t)));const s=e[a];for(const e of Object.entries(t)){var o=H(e,2);const a=o[0],c=o[1];if(null===c)throw new Error("cannot decode field ".concat(i.typeName,".").concat(n.name," from JSON: map value null"));let d;try{d=ge(n.K,a)}catch(e){let r="cannot decode map key for field ".concat(i.typeName,".").concat(n.name," from JSON: ").concat(ye(t));throw e instanceof Error&&e.message.length>0&&(r+=": ".concat(e.message)),new Error(r)}switch(n.V.kind){case"message":s[d]=n.V.T.fromJson(c,r);break;case"enum":const e=ve(n.V.T,c,r.ignoreUnknownFields,!0);e!==pe&&(s[d]=e);break;case"scalar":try{s[d]=be(n.V.T,c,V.BIGINT,!0)}catch(e){let r="cannot decode map value for field ".concat(i.typeName,".").concat(n.name," from JSON: ").concat(ye(t));throw e instanceof Error&&e.message.length>0&&(r+=": ".concat(e.message)),new Error(r)}}}}else switch(n.oneof&&(e=e[n.oneof.localName]={case:a},a="value"),n.kind){case"message":const o=n.T;if(null===t&&"google.protobuf.Value"!=o.typeName)return;let s=e[a];se(s)?s.fromJson(t,r):(e[a]=s=o.fromJson(t,r),o.fieldWrapper&&!n.oneof&&(e[a]=o.fieldWrapper.unwrapField(s)));break;case"enum":const c=ve(n.T,t,r.ignoreUnknownFields,!1);switch(c){case fe:oe(n,e);break;case pe:break;default:e[a]=c}break;case"scalar":try{const r=be(n.T,t,n.L,!1);if(r===fe)oe(n,e);else e[a]=r}catch(e){let r="cannot decode field ".concat(i.typeName,".").concat(n.name," from JSON: ").concat(ye(t));throw e instanceof Error&&e.message.length>0&&(r+=": ".concat(e.message)),new Error(r)}}}function ge(e,t){if(e===j.BOOL)switch(t){case"true":t=!0;break;case"false":t=!1}return be(e,t,V.BIGINT,!0).toString()}function be(e,t,n,r){if(null===t)return r?G(e,n):fe;switch(e){case j.DOUBLE:case j.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 r=Number(t);if(Number.isNaN(r))break;if(!Number.isFinite(r))break;return e==j.FLOAT&&T(r),r;case j.INT32:case j.FIXED32:case j.SFIXED32:case j.SINT32:case j.UINT32:let i;if("number"==typeof t?i=t:"string"==typeof t&&t.length>0&&t.trim().length===t.length&&(i=Number(t)),void 0===i)break;return e==j.UINT32||e==j.FIXED32?w(i):k(i),i;case j.INT64:case j.SFIXED64:case j.SINT64:if("number"!=typeof t&&"string"!=typeof t)break;const a=K.parse(t);return n?a.toString():a;case j.FIXED64:case j.UINT64:if("number"!=typeof t&&"string"!=typeof t)break;const o=K.uParse(t);return n?o.toString():o;case j.BOOL:if("boolean"!=typeof t)break;return t;case j.STRING:if("string"!=typeof t)break;try{encodeURIComponent(t)}catch(e){throw new Error("invalid UTF8")}return t;case j.BYTES:if(""===t)return new Uint8Array(0);if("string"!=typeof t)break;return ee.dec(t)}throw new Error}function ve(e,t,n,r){if(null===t)return"google.protobuf.NullValue"==e.typeName?0:r?e.values[0].no:fe;switch(typeof t){case"number":if(Number.isInteger(t))return t;break;case"string":const r=e.findName(t);if(void 0!==r)return r.no;if(n)return pe}throw new Error("cannot decode enum ".concat(e.typeName," from JSON: ").concat(ye(t)))}function ke(e){return!(!e.repeated&&"map"!=e.kind)||!e.oneof&&("message"!=e.kind&&(!e.opt&&!e.req))}function we(e,t,n){if("map"==e.kind){v("object"==typeof t&&null!=t);const o={},s=Object.entries(t);switch(e.V.kind){case"scalar":for(const t of s){var r=H(t,2);const n=r[0],i=r[1];o[n.toString()]=Se(e.V.T,i)}break;case"message":for(const e of s){var i=H(e,2);const t=i[0],r=i[1];o[t.toString()]=r.toJson(n)}break;case"enum":const t=e.V.T;for(const e of s){var a=H(e,2);const r=a[0],i=a[1];o[r.toString()]=Te(t,i,n.enumAsInteger)}}return n.emitDefaultValues||s.length>0?o:void 0}if(e.repeated){v(Array.isArray(t));const r=[];switch(e.kind){case"scalar":for(let n=0;n0?r:void 0}switch(e.kind){case"scalar":return Se(e.T,t);case"enum":return Te(e.T,t,n.enumAsInteger);case"message":return ce(e.T,t).toJson(n)}}function Te(e,t,n){var r;if(v("number"==typeof t),"google.protobuf.NullValue"==e.typeName)return null;if(n)return t;const i=e.findNumber(t);return null!==(r=null==i?void 0:i.name)&&void 0!==r?r:t}function Se(e,t){switch(e){case j.INT32:case j.SFIXED32:case j.SINT32:case j.FIXED32:case j.UINT32:return v("number"==typeof t),t;case j.FLOAT:case j.DOUBLE:return v("number"==typeof t),Number.isNaN(t)?"NaN":t===Number.POSITIVE_INFINITY?"Infinity":t===Number.NEGATIVE_INFINITY?"-Infinity":t;case j.STRING:return v("string"==typeof t),t;case j.BOOL:return v("boolean"==typeof t),t;case j.UINT64:case j.FIXED64:case j.INT64:case j.SFIXED64:case j.SINT64:return v("bigint"==typeof t||"string"==typeof t||"number"==typeof t),t.toString();case j.BYTES:return v(t instanceof Uint8Array),ee.enc(t)}}const Ie=Symbol("@bufbuild/protobuf/unknown-fields"),Ee={readUnknownFields:!0,readerFactory:e=>new Y(e)},Ne={writeUnknownFields:!0,writerFactory:()=>new z};function Ae(e){return e?Object.assign(Object.assign({},Ee),e):Ee}function Le(e){return e?Object.assign(Object.assign({},Ne),e):Ne}function Ce(e,t,n,r,i){let a=n.repeated,o=n.localName;switch(n.oneof&&((e=e[n.oneof.localName]).case!=o&&delete e.value,e.case=o,o="value"),n.kind){case"scalar":case"enum":const s="enum"==n.kind?j.INT32:n.T;let c=Oe;if("scalar"==n.kind&&n.L>0&&(c=Ue),a){let n=e[o];if(r==W.LengthDelimited&&s!=j.STRING&&s!=j.BYTES){let e=t.uint32()+t.pos;for(;t.pose.no-t.no))),this.numbersAsc}byMember(){if(!this.members){this.members=[];const e=this.members;let t;for(const n of this.list())n.oneof?n.oneof!==t&&(t=n.oneof,e.push(t)):e.push(n)}return this.members}}function je(e,t){const n=We(e);return t?n:He(Je(n))}const Ve=We;function We(e){let t=!1;const n=[];for(let r=0;r"".concat(e,"$"),Je=e=>Ge.has(e)?Xe(e):e,He=e=>qe.has(e)?Xe(e):e;class ze{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=je(e,!1)}addField(e){v(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;enew Ke(e,(e=>function(e){var t,n,r,i,a,o;const s=[];let c;for(const d of"function"==typeof e?e():e){const e=d;if(e.localName=je(d.name,void 0!==d.oneof),e.jsonName=null!==(t=d.jsonName)&&void 0!==t?t:Ve(d.name),e.repeated=null!==(n=d.repeated)&&void 0!==n&&n,"scalar"==d.kind&&(e.L=null!==(r=d.L)&&void 0!==r?r:V.BIGINT),e.delimited=null!==(i=d.delimited)&&void 0!==i&&i,e.req=null!==(a=d.req)&&void 0!==a&&a,e.opt=null!==(o=d.opt)&&void 0!==o&&o,void 0===d.packed&&(e.packed="enum"==d.kind||"scalar"==d.kind&&d.T!=j.BYTES&&d.T!=j.STRING),void 0!==d.oneof){const t="string"==typeof d.oneof?d.oneof:d.oneof.name;c&&c.name==t||(c=new ze(t)),e.oneof=c,c.addField(e)}s.push(e)}return s}(e))),$e=e=>{for(const t of e.getType().fields.byMember()){if(t.opt)continue;const n=t.localName,r=e;if(t.repeated)r[n]=[];else switch(t.kind){case"oneof":r[n]={case:void 0};break;case"enum":r[n]=0;break;case"map":r[n]={};break;case"scalar":r[n]=G(t.T,t.L)}}},{syntax:"proto3",json:{makeReadOptions:le,makeWriteOptions:he,readMessage(e,t,n,r){if(null==t||Array.isArray(t)||"object"!=typeof t)throw new Error("cannot decode message ".concat(e.typeName," from JSON: ").concat(ye(t)));r=null!=r?r:new e;const i=new Map,a=n.typeRegistry;for(const s of Object.entries(t)){var o=H(s,2);const t=o[0],c=o[1],d=e.fields.findJsonName(t);if(d){if(d.oneof){if(null===c&&"scalar"==d.kind)continue;const n=i.get(d.oneof);if(void 0!==n)throw new Error("cannot decode message ".concat(e.typeName,' from JSON: multiple keys for oneof "').concat(d.oneof.name,'" present: "').concat(n,'", "').concat(t,'"'));i.set(d.oneof,t)}me(r,c,d,n,e)}else{let i=!1;if((null==a?void 0:a.findExtension)&&t.startsWith("[")&&t.endsWith("]")){const o=a.findExtension(t.substring(1,t.length-1));if(o&&o.extendee.typeName==e.typeName){i=!0;const e=H(Q(o),2),t=e[0],a=e[1];me(t,c,o.field,n,o),ne(r,o,a(),n)}}if(!i&&!n.ignoreUnknownFields)throw new Error("cannot decode message ".concat(e.typeName,' from JSON: key "').concat(t,'" is unknown'))}}return r},writeMessage(e,t){const n=e.getType(),r={};let i;try{for(i of n.fields.byNumber()){if(!ae(i,e)){if(i.req)throw"required field not set";if(!t.emitDefaultValues)continue;if(!ke(i))continue}const n=we(i,i.oneof?e[i.oneof.localName].value:e[i.localName],t);void 0!==n&&(r[t.useProtoFieldName?i.name:i.jsonName]=n)}const a=t.typeRegistry;if(null==a?void 0:a.findExtensionFor)for(const i of n.runtime.bin.listUnknownFields(e)){const o=a.findExtensionFor(n.typeName,i.no);if(o&&re(e,o)){const n=te(e,o,t),i=we(o.field,n,t);void 0!==i&&(r[o.field.jsonName]=i)}}}catch(e){const t=i?"cannot encode field ".concat(n.typeName,".").concat(i.name," to JSON"):"cannot encode message ".concat(n.typeName," to JSON"),r=e instanceof Error?e.message:String(e);throw new Error(t+(r.length>0?": ".concat(r):""))}return r},readScalar:(e,t,n)=>be(e,t,null!=n?n:V.BIGINT,!0),writeScalar(e,t,n){if(void 0!==t)return n||X(e,t)?Se(e,t):void 0},debug:ye},bin:{makeReadOptions:Ae,makeWriteOptions:Le,listUnknownFields(e){var t;return null!==(t=e[Ie])&&void 0!==t?t:[]},discardUnknownFields(e){delete e[Ie]},writeUnknownFields(e,t){const n=e[Ie];if(n)for(const e of n)t.tag(e.no,e.wireType).raw(e.data)},onUnknownField(e,t,n,r){const i=e;Array.isArray(i[Ie])||(i[Ie]=[]),i[Ie].push({no:t,wireType:n,data:r})},readMessage(e,t,n,r,i){const a=e.getType(),o=i?t.len:t.pos+n;let s,c;for(;t.posse(e,d)?e:new d(e)));else{const e=o[n];d.fieldWrapper?"google.protobuf.BytesValue"===d.typeName?a[n]=Be(e):a[n]=e:a[n]=se(e,d)?e:new d(e)}}}},equals:(e,t,n)=>t===n||!(!t||!n)&&e.fields.byMember().every((e=>{const r=t[e.localName],i=n[e.localName];if(e.repeated){if(r.length!==i.length)return!1;switch(e.kind){case"message":return r.every(((t,n)=>e.T.equals(t,i[n])));case"scalar":return r.every(((t,n)=>q(e.T,t,i[n])));case"enum":return r.every(((e,t)=>q(j.INT32,e,i[t])))}throw new Error("repeated cannot contain ".concat(e.kind))}switch(e.kind){case"message":let t=r,n=i;return e.T.fieldWrapper&&(void 0===t||se(t)||(t=e.T.fieldWrapper.wrapField(t)),void 0===n||se(n)||(n=e.T.fieldWrapper.wrapField(n))),e.T.equals(t,n);case"enum":return q(j.INT32,r,i);case"scalar":return q(e.T,r,i);case"oneof":if(r.case!==i.case)return!1;const a=e.findField(r.case);if(void 0===a)return!0;switch(a.kind){case"message":return a.T.equals(r.value,i.value);case"enum":return q(j.INT32,r.value,i.value);case"scalar":return q(a.T,r.value,i.value)}throw new Error("oneof cannot contain ".concat(a.kind));case"map":const o=Object.keys(r).concat(Object.keys(i));switch(e.V.kind){case"message":const t=e.V.T;return o.every((e=>t.equals(r[e],i[e])));case"enum":return o.every((e=>q(j.INT32,r[e],i[e])));case"scalar":const n=e.V.T;return o.every((e=>q(n,r[e],i[e])))}}})),clone(e){const t=e.getType(),n=new t,r=n;for(const n of t.fields.byMember()){const t=e[n.localName];let a;if(n.repeated)a=t.map(xe);else if("map"==n.kind){a=r[n.localName];for(const e of Object.entries(t)){var i=H(e,2);const t=i[0],n=i[1];a[t]=xe(n)}}else a="oneof"==n.kind?n.findField(t.case)?{case:t.case,value:xe(t.value)}:{case:void 0}:xe(t);r[n.localName]=a}for(const n of t.runtime.bin.listUnknownFields(e))t.runtime.bin.onUnknownField(r,n.no,n.wireType,n.data);return n}}),{newFieldList:Qe,initFields:$e}),makeMessageType(e,t,n){return function(e,t,n,r){var i;const a=null!==(i=null==r?void 0:r.localName)&&void 0!==i?i:t.substring(t.lastIndexOf(".")+1),o={[a]:function(t){e.util.initFields(this),e.util.initPartial(t,this)}}[a];return Object.setPrototypeOf(o.prototype,new C),Object.assign(o,{runtime:e,typeName:t,fields:e.util.newFieldList(n),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,n)=>e.util.equals(o,t,n)}),o}(this,e,t,n)},makeEnum:A,makeEnumType:N,getEnumType:I,makeExtension(e,t,n){return function(e,t,n,r){let i;return{typeName:t,extendee:n,get field(){if(!i){const n="function"==typeof r?r():r;n.name=t.split(".").pop(),n.jsonName="[".concat(t,"]"),i=e.util.newFieldList([n]).list()[0]}return i},runtime:e}}(this,e,t,n)}});var Qe,$e;const Ze=Ye.makeEnum("livekit.TrackType",[{no:0,name:"AUDIO"},{no:1,name:"VIDEO"},{no:2,name:"DATA"}]),et=Ye.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"}]),tt=Ye.makeEnum("livekit.StreamState",[{no:0,name:"ACTIVE"},{no:1,name:"PAUSED"}]);class nt extends Error{constructor(e,t,n){super(t||"an error has occurred"),this.name="LiveKitError",this.code=e,void 0!==(null==n?void 0:n.cause)&&(this.cause=null==n?void 0:n.cause)}}var rt,it,at,ot,st,ct,dt,ut;!function(e){e[e.NotAllowed=0]="NotAllowed",e[e.ServerUnreachable=1]="ServerUnreachable",e[e.InternalError=2]="InternalError",e[e.Cancelled=3]="Cancelled",e[e.LeaveRequest=4]="LeaveRequest",e[e.Timeout=5]="Timeout",e[e.WebSocket=6]="WebSocket",e[e.ServiceNotFound=7]="ServiceNotFound"}(rt||(rt={})),function(e){e[e.AlreadyOpened=0]="AlreadyOpened",e[e.AbnormalEnd=1]="AbnormalEnd",e[e.DecodeFailed=2]="DecodeFailed",e[e.LengthExceeded=3]="LengthExceeded",e[e.Incomplete=4]="Incomplete",e[e.HandlerAlreadyRegistered=7]="HandlerAlreadyRegistered",e[e.EncryptionTypeMismatch=8]="EncryptionTypeMismatch"}(it||(it={})),function(e){e.PermissionDenied="PermissionDenied",e.NotFound="NotFound",e.DeviceInUse="DeviceInUse",e.Other="Other"}(at||(at={})),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}}(at||(at={})),function(e){e[e.InvalidKey=0]="InvalidKey",e[e.MissingKey=1]="MissingKey",e[e.InternalError=2]="InternalError"}(ot||(ot={}));class lt extends nt{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:ot.InternalError,n=arguments.length>2?arguments[2]:void 0;super(40,e),this.reason=t,this.participantIdentity=n}}function ht(e){return"type"in e}function ft(e,t){const n=(new TextEncoder).encode(t);switch(e){case"HKDF":return{name:"HKDF",salt:n,hash:"SHA-256",info:new ArrayBuffer(128)};case"PBKDF2":return{name:"PBKDF2",salt:n,hash:"SHA-256",iterations:1e5};default:throw new Error("algorithm ".concat(e," is currently unsupported"))}}function pt(t,n){return e(this,void 0,void 0,(function*(){const e=ft(t.algorithm.name,n.ratchetSalt),r=yield crypto.subtle.deriveKey(e,t,{name:m,length:n.keySize},!1,["encrypt","decrypt"]);return{material:t,encryptionKey:r}}))}!function(e){e.SetKey="setKey",e.RatchetRequest="ratchetRequest",e.KeyRatcheted="keyRatcheted"}(st||(st={})),function(e){e.KeyRatcheted="keyRatcheted"}(ct||(ct={})),function(e){e.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",e.EncryptionError="encryptionError"}(dt||(dt={})),function(e){e.Error="cryptorError"}(ut||(ut={}));class yt{static makeIV(e){const t=new ArrayBuffer(12),n=new DataView(t),r=crypto.getRandomValues(new Uint32Array(1));return n.setUint32(0,r[0]),n.setUint32(4,e),n.setUint32(8,e-yt.sendCount%65535),yt.sendCount++,t}static encrypt(t,n){return e(this,void 0,void 0,(function*(){const e=yt.makeIV(performance.now()),r=yield n.getKeySet();if(!r)throw new Error("No key set found");const i=yield crypto.subtle.encrypt({name:m,iv:e},r.encryptionKey,new Uint8Array(t));return{payload:new Uint8Array(i),iv:new Uint8Array(e),keyIndex:n.getCurrentKeyIndex()}}))}static decrypt(t,n,r){return e(this,arguments,void 0,(function(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0,i=arguments.length>4?arguments[4]:void 0,a=arguments.length>5&&void 0!==arguments[5]?arguments[5]:{ratchetCount:0};return function*(){const o=yield n.getKeySet(r);if(!o)throw new Error("No key set found");try{const n=yield crypto.subtle.decrypt({name:m,iv:t},o.encryptionKey,new Uint8Array(e));return{payload:new Uint8Array(n)}}catch(s){if(n.keyProviderOptions.ratchetWindowSize>0){if(a.ratchetCount0&&c.length>i&&!c.warned){c.warned=!0;var u=new Error("Possible EventEmitter memory leak detected. "+c.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");u.name="MaxListenersExceededWarning",u.emitter=e,u.type=t,u.count=c.length,d=u,console&&console.warn&&console.warn(d)}return e}function d(){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 u(e,t,n){var r={fired:!1,wrapFn:void 0,target:e,type:t,listener:n},i=d.bind(r);return i.listener=n,r.wrapFn=i,i}function l(e,t,n){var r=e._events;if(void 0===r)return[];var i=r[t];return void 0===i?[]:"function"==typeof i?n?[i.listener||i]:[i]:n?function(e){for(var t=new Array(e.length),n=0;n0&&(o=t[0]),o instanceof Error)throw o;var s=new Error("Unhandled error."+(o?" ("+o.message+")":""));throw s.context=o,s}var c=a[e];if(void 0===c)return!1;if("function"==typeof c)n(c,this,t);else{var d=c.length,u=f(c,d);for(r=0;r=0;a--)if(n[a]===t||n[a].listener===t){s=n[a].listener,i=a;break}if(i<0)return this;0===i?n.shift():function(e,t){for(;t+1=0;r--)this.removeListener(e,t[r]);return this},i.prototype.listeners=function(e){return l(this,e,!0)},i.prototype.rawListeners=function(e){return l(this,e,!1)},i.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):h.call(e,t)},i.prototype.listenerCount=h,i.prototype.eventNames=function(){return this._eventsCount>0?e(this._events):[]},gt.exports}();class wt extends(vt=Promise){constructor(e){super(e)}catch(e){return super.catch(e)}static reject(e){return super.reject(e)}static all(e){return super.all(e)}static race(e){return super.race(e)}}bt=wt,wt.resolve=e=>Reflect.get(vt,"resolve",bt).call(bt,e);const Tt=/version\/(\d+(\.?_?\d+)+)/i;let St;function It(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if("undefined"==typeof navigator)return;const n=navigator.userAgent.toLowerCase();if(void 0===St||t){const e=Et.find((e=>e.test.test(n)));St=null==e?void 0:e.describe(n)}return St}const Et=[{test:/firefox|iceweasel|fxios/i,describe:e=>({name:"Firefox",version:Nt(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,e),os:e.toLowerCase().includes("fxios")?"iOS":void 0,osVersion:At(e)})},{test:/chrom|crios|crmo/i,describe:e=>({name:"Chrome",version:Nt(/(?:chrome|chromium|crios|crmo)\/(\d+(\.?_?\d+)+)/i,e),os:e.toLowerCase().includes("crios")?"iOS":void 0,osVersion:At(e)})},{test:/safari|applewebkit/i,describe:e=>({name:"Safari",version:Nt(Tt,e),os:e.includes("mobile/")?"iOS":"macOS",osVersion:At(e)})}];function Nt(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1;const r=t.match(e);return r&&r.length>=n&&r[n]||""}function At(e){return e.includes("mac os")?Nt(/\(.+?(\d+_\d+(:?_\d+)?)/,e,1).replace(/_/g,"."):void 0}var Lt,Ct,Rt,Ut;!function(e){e.Connected="connected",e.Reconnecting="reconnecting",e.SignalReconnecting="signalReconnecting",e.Reconnected="reconnected",e.Disconnected="disconnected",e.ConnectionStateChanged="connectionStateChanged",e.Moved="moved",e.MediaDevicesChanged="mediaDevicesChanged",e.ParticipantConnected="participantConnected",e.ParticipantDisconnected="participantDisconnected",e.TrackPublished="trackPublished",e.TrackSubscribed="trackSubscribed",e.TrackSubscriptionFailed="trackSubscriptionFailed",e.TrackUnpublished="trackUnpublished",e.TrackUnsubscribed="trackUnsubscribed",e.TrackMuted="trackMuted",e.TrackUnmuted="trackUnmuted",e.LocalTrackPublished="localTrackPublished",e.LocalTrackUnpublished="localTrackUnpublished",e.LocalAudioSilenceDetected="localAudioSilenceDetected",e.ActiveSpeakersChanged="activeSpeakersChanged",e.ParticipantMetadataChanged="participantMetadataChanged",e.ParticipantNameChanged="participantNameChanged",e.ParticipantAttributesChanged="participantAttributesChanged",e.ParticipantActive="participantActive",e.RoomMetadataChanged="roomMetadataChanged",e.DataReceived="dataReceived",e.SipDTMFReceived="sipDTMFReceived",e.TranscriptionReceived="transcriptionReceived",e.ConnectionQualityChanged="connectionQualityChanged",e.TrackStreamStateChanged="trackStreamStateChanged",e.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",e.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",e.AudioPlaybackStatusChanged="audioPlaybackChanged",e.VideoPlaybackStatusChanged="videoPlaybackChanged",e.MediaDevicesError="mediaDevicesError",e.ParticipantPermissionsChanged="participantPermissionsChanged",e.SignalConnected="signalConnected",e.RecordingStatusChanged="recordingStatusChanged",e.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",e.EncryptionError="encryptionError",e.DCBufferStatusChanged="dcBufferStatusChanged",e.ActiveDeviceChanged="activeDeviceChanged",e.ChatMessage="chatMessage",e.LocalTrackSubscribed="localTrackSubscribed",e.MetricsReceived="metricsReceived",e.DataTrackPublished="dataTrackPublished",e.DataTrackUnpublished="dataTrackUnpublished",e.LocalDataTrackPublished="localDataTrackPublished",e.LocalDataTrackUnpublished="localDataTrackUnpublished"}(Lt||(Lt={})),function(e){e.TrackPublished="trackPublished",e.TrackSubscribed="trackSubscribed",e.TrackSubscriptionFailed="trackSubscriptionFailed",e.TrackUnpublished="trackUnpublished",e.TrackUnsubscribed="trackUnsubscribed",e.TrackMuted="trackMuted",e.TrackUnmuted="trackUnmuted",e.LocalTrackPublished="localTrackPublished",e.LocalTrackUnpublished="localTrackUnpublished",e.LocalTrackCpuConstrained="localTrackCpuConstrained",e.LocalSenderCreated="localSenderCreated",e.ParticipantMetadataChanged="participantMetadataChanged",e.ParticipantNameChanged="participantNameChanged",e.DataReceived="dataReceived",e.SipDTMFReceived="sipDTMFReceived",e.TranscriptionReceived="transcriptionReceived",e.IsSpeakingChanged="isSpeakingChanged",e.ConnectionQualityChanged="connectionQualityChanged",e.TrackStreamStateChanged="trackStreamStateChanged",e.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",e.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",e.TrackCpuConstrained="trackCpuConstrained",e.MediaDevicesError="mediaDevicesError",e.AudioStreamAcquired="audioStreamAcquired",e.ParticipantPermissionsChanged="participantPermissionsChanged",e.PCTrackAdded="pcTrackAdded",e.AttributesChanged="attributesChanged",e.LocalTrackSubscribed="localTrackSubscribed",e.ChatMessage="chatMessage",e.Active="active"}(Ct||(Ct={})),function(e){e.TransportsCreated="transportsCreated",e.Connected="connected",e.Disconnected="disconnected",e.Resuming="resuming",e.Resumed="resumed",e.Restarting="restarting",e.Restarted="restarted",e.SignalResumed="signalResumed",e.SignalRestarted="signalRestarted",e.Closing="closing",e.MediaTrackAdded="mediaTrackAdded",e.ActiveSpeakersUpdate="activeSpeakersUpdate",e.DataPacketReceived="dataPacketReceived",e.RTPVideoMapUpdate="rtpVideoMapUpdate",e.DCBufferStatusChanged="dcBufferStatusChanged",e.ParticipantUpdate="participantUpdate",e.RoomUpdate="roomUpdate",e.SpeakersChanged="speakersChanged",e.StreamStateChanged="streamStateChanged",e.ConnectionQualityUpdate="connectionQualityUpdate",e.SubscriptionError="subscriptionError",e.SubscriptionPermissionUpdate="subscriptionPermissionUpdate",e.RemoteMute="remoteMute",e.SubscribedQualityUpdate="subscribedQualityUpdate",e.LocalTrackUnpublished="localTrackUnpublished",e.LocalTrackSubscribed="localTrackSubscribed",e.Offline="offline",e.SignalRequestResponse="signalRequestResponse",e.SignalConnected="signalConnected",e.RoomMoved="roomMoved",e.PublishDataTrackResponse="publishDataTrackResponse",e.UnPublishDataTrackResponse="unPublishDataTrackResponse",e.DataTrackSubscriberHandles="dataTrackSubscriberHandles",e.DataTrackPacketReceived="dataTrackPacketReceived",e.Joined="joined",e.TokenRefreshed="tokenRefreshed",e.ServerRegionsReported="serverRegionsReported"}(Rt||(Rt={})),function(e){e.Message="message",e.Muted="muted",e.Unmuted="unmuted",e.Restarted="restarted",e.Ended="ended",e.Subscribed="subscribed",e.Unsubscribed="unsubscribed",e.CpuConstrained="cpuConstrained",e.UpdateSettings="updateSettings",e.UpdateSubscription="updateSubscription",e.AudioPlaybackStarted="audioPlaybackStarted",e.AudioPlaybackFailed="audioPlaybackFailed",e.AudioSilenceDetected="audioSilenceDetected",e.VisibilityChanged="visibilityChanged",e.VideoDimensionsChanged="videoDimensionsChanged",e.VideoPlaybackStarted="videoPlaybackStarted",e.VideoPlaybackFailed="videoPlaybackFailed",e.ElementAttached="elementAttached",e.ElementDetached="elementDetached",e.UpstreamPaused="upstreamPaused",e.UpstreamResumed="upstreamResumed",e.SubscriptionPermissionChanged="subscriptionPermissionChanged",e.SubscriptionStatusChanged="subscriptionStatusChanged",e.SubscriptionFailed="subscriptionFailed",e.TrackProcessorUpdate="trackProcessorUpdate",e.AudioTrackFeatureUpdate="audioTrackFeatureUpdate",e.TranscriptionReceived="transcriptionReceived",e.TimeSyncUpdate="timeSyncUpdate",e.PreConnectBufferFlushed="preConnectBufferFlushed"}(Ut||(Ut={}));class Ot{constructor(e,t,n,r,i){if("object"==typeof e)this.width=e.width,this.height=e.height,this.aspectRatio=e.aspectRatio,this.encoding={maxBitrate:e.maxBitrate,maxFramerate:e.maxFramerate,priority:e.priority};else{if(void 0===t||void 0===n)throw new TypeError("Unsupported options: provide at least width, height and maxBitrate");this.width=e,this.height=t,this.aspectRatio=e/t,this.encoding={maxBitrate:n,maxFramerate:r,priority:i}}}get resolution(){return{width:this.width,height:this.height,frameRate:this.encoding.maxFramerate,aspectRatio:this.aspectRatio}}}const _t=["vp8","h264","vp9","av1","h265"];var Ft,Dt;function Pt(e){return"mediaStreamTrack"in e?{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?Pt(e.track):{})}}!function(e){e[e.PREFER_REGRESSION=0]="PREFER_REGRESSION",e[e.SIMULCAST=1]="SIMULCAST",e[e.REGRESSION=2]="REGRESSION"}(Ft||(Ft={})),function(e){e.telephone={maxBitrate:12e3},e.speech={maxBitrate:24e3},e.music={maxBitrate:48e3},e.musicStereo={maxBitrate:64e3},e.musicHighQuality={maxBitrate:96e3},e.musicHighQualityStereo={maxBitrate:128e3}}(Dt||(Dt={})),new Ot(160,90,9e4,20),new Ot(320,180,16e4,20),new Ot(384,216,18e4,20),new Ot(640,360,45e4,20),new Ot(960,540,8e5,25),new Ot(1280,720,17e5,30),new Ot(1920,1080,3e6,30),new Ot(2560,1440,5e6,30),new Ot(3840,2160,8e6,30),new Ot(160,120,7e4,20),new Ot(240,180,125e3,20),new Ot(320,240,14e4,20),new Ot(480,360,33e4,20),new Ot(640,480,5e5,20),new Ot(720,540,6e5,25),new Ot(960,720,13e5,30),new Ot(1440,1080,23e5,30),new Ot(1920,1440,38e5,30),new Ot(640,360,2e5,3,"medium"),new Ot(640,360,4e5,15,"medium"),new Ot(1280,720,8e5,5,"medium"),new Ot(1280,720,15e5,15,"medium"),new Ot(1280,720,2e6,30,"medium"),new Ot(1920,1080,25e5,15,"medium"),new Ot(1920,1080,5e6,30,"medium"),new Ot(0,0,7e6,30,"medium");const Mt=[];var xt;!function(e){e[e.LOW=0]="LOW",e[e.MEDIUM=1]="MEDIUM",e[e.HIGH=2]="HIGH"}(xt||(xt={}));class Bt extends kt.EventEmitter{get streamState(){return this._streamState}setStreamState(e){this._streamState=e}constructor(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};var r;super(),this.attachedElements=[],this.isMuted=!1,this._streamState=Bt.StreamState.Active,this.isInBackground=!1,this._currentBitrate=0,this.log=d,this.appVisibilityChangedListener=()=>{this.backgroundTimeout&&clearTimeout(this.backgroundTimeout),"hidden"===document.visibilityState?this.backgroundTimeout=setTimeout((()=>this.handleAppVisibilityChanged()),5e3):this.handleAppVisibilityChanged()},this.log=u(null!==(r=n.loggerName)&&void 0!==r?r:s.Track),this.loggerContextCb=n.loggerContextCb,this.setMaxListeners(100),this.kind=t,this._mediaStreamTrack=e,this._mediaStreamID=e.id,this.source=Bt.Source.Unknown}get logContext(){var e;return Object.assign(Object.assign({},null===(e=this.loggerContextCb)||void 0===e?void 0:e.call(this)),Pt(this))}get currentBitrate(){return this._currentBitrate}get mediaStreamTrack(){return this._mediaStreamTrack}get mediaStreamID(){return this._mediaStreamID}attach(e){let t="audio";this.kind===Bt.Kind.Video&&(t="video"),0===this.attachedElements.length&&this.kind===Bt.Kind.Video&&this.addAppVisibilityListener(),e||("audio"===t&&(Mt.forEach((t=>{null!==t.parentElement||e||(e=t)})),e&&Mt.splice(Mt.indexOf(e),1)),e||(e=document.createElement(t))),this.attachedElements.includes(e)||this.attachedElements.push(e),function(e,t){let n,r;n=t.srcObject instanceof MediaStream?t.srcObject:new MediaStream;r="audio"===e.kind?n.getAudioTracks():n.getVideoTracks();r.includes(e)||(r.forEach((e=>{n.removeTrack(e)})),n.addTrack(e));jt()&&t instanceof HTMLVideoElement||(t.autoplay=!0);t.muted=0===n.getAudioTracks().length,t instanceof HTMLVideoElement&&(t.playsInline=!0);t.srcObject!==n&&(t.srcObject=n,(jt()||function(){var e;return"Firefox"===(null===(e=It())||void 0===e?void 0:e.name)}())&&t instanceof HTMLVideoElement&&setTimeout((()=>{t.srcObject=n,t.play().catch((()=>{}))}),0))}(this.mediaStreamTrack,e);const n=e.srcObject.getTracks(),r=n.some((e=>"audio"===e.kind));return e.play().then((()=>{this.emit(r?Ut.AudioPlaybackStarted:Ut.VideoPlaybackStarted)})).catch((t=>{"NotAllowedError"===t.name?this.emit(r?Ut.AudioPlaybackFailed:Ut.VideoPlaybackFailed,t):"AbortError"===t.name?d.debug("".concat(r?"audio":"video"," playback aborted, likely due to new play request")):d.warn("could not playback ".concat(r?"audio":"video"),t),r&&e&&n.some((e=>"video"===e.kind))&&"NotAllowedError"===t.name&&(e.muted=!0,e.play().catch((()=>{})))})),this.emit(Ut.ElementAttached,e),e}detach(e){try{if(e){Kt(this.mediaStreamTrack,e);const t=this.attachedElements.indexOf(e);return t>=0&&(this.attachedElements.splice(t,1),this.recycleElement(e),this.emit(Ut.ElementDetached,e)),e}const t=[];return this.attachedElements.forEach((e=>{Kt(this.mediaStreamTrack,e),t.push(e),this.recycleElement(e),this.emit(Ut.ElementDetached,e)})),this.attachedElements=[],t}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=u(e.loggerName)),e.loggerContextCb&&(this.loggerContextCb=e.loggerContextCb)}recycleElement(e){if(e instanceof HTMLAudioElement){let t=!0;e.pause(),Mt.forEach((e=>{e.parentElement||(t=!1)})),t&&Mt.push(e)}}handleAppVisibilityChanged(){return e(this,void 0,void 0,(function*(){this.isInBackground="hidden"===document.visibilityState,this.isInBackground||this.kind!==Bt.Kind.Video||setTimeout((()=>this.attachedElements.forEach((e=>e.play().catch((()=>{}))))),0)}))}addAppVisibilityListener(){Vt()?(this.isInBackground="hidden"===document.visibilityState,document.addEventListener("visibilitychange",this.appVisibilityChangedListener)):this.isInBackground=!1}removeAppVisibilityListener(){Vt()&&document.removeEventListener("visibilitychange",this.appVisibilityChangedListener)}}function Kt(e,t){if(t.srcObject instanceof MediaStream){const n=t.srcObject;n.removeTrack(e),n.getTracks().length>0?t.srcObject=n:t.srcObject=null}}function jt(){var e;return"Safari"===(null===(e=It())||void 0===e?void 0:e.name)}function Vt(){return"undefined"!=typeof document}function Wt(e){return!(!(null==e?void 0:e.timestamp)&&!(null==e?void 0:e.frameId))}!function(e){let t,n,r;!function(e){e.Audio="audio",e.Video="video",e.Unknown="unknown"}(t=e.Kind||(e.Kind={})),function(e){e.Camera="camera",e.Microphone="microphone",e.ScreenShare="screen_share",e.ScreenShareAudio="screen_share_audio",e.Unknown="unknown"}(n=e.Source||(e.Source={})),function(e){e.Active="active",e.Paused="paused",e.Unknown="unknown"}(r=e.StreamState||(e.StreamState={})),e.kindToProto=function(e){switch(e){case t.Audio:return Ze.AUDIO;case t.Video:return Ze.VIDEO;default:return Ze.DATA}},e.kindFromProto=function(e){switch(e){case Ze.AUDIO:return t.Audio;case Ze.VIDEO:return t.Video;default:return t.Unknown}},e.sourceToProto=function(e){switch(e){case n.Camera:return et.CAMERA;case n.Microphone:return et.MICROPHONE;case n.ScreenShare:return et.SCREEN_SHARE;case n.ScreenShareAudio:return et.SCREEN_SHARE_AUDIO;default:return et.UNKNOWN}},e.sourceFromProto=function(e){switch(e){case et.CAMERA:return n.Camera;case et.MICROPHONE:return n.Microphone;case et.SCREEN_SHARE:return n.ScreenShare;case et.SCREEN_SHARE_AUDIO:return n.ScreenShareAudio;default:return n.Unknown}},e.streamStateFromProto=function(e){switch(e){case tt.ACTIVE:return r.Active;case tt.PAUSED:return r.Paused;default:return r.Unknown}}}(Bt||(Bt={}));const qt=Uint8Array.from(["L".charCodeAt(0),"K".charCodeAt(0),"T".charCodeAt(0),"S".charCodeAt(0)]);function Gt(e,t,n){const r=t!==BigInt(0),i=0!==n;if(!r&&!i)return e;const a=(r?10:0)+(i?6:0)+5,o=new Uint8Array(e.length+a);let s=0;return o.set(e,s),s+=e.length,r&&(o[s++]=254,o[s++]=247,function(e,t,n){const r=Number(n>>BigInt(32)&BigInt(4294967295)),i=Number(n&BigInt(4294967295));e[t]=r>>>24^255,e[t+1]=r>>>16&255^255,e[t+2]=r>>>8&255^255,e[t+3]=255&r^255,e[t+4]=i>>>24^255,e[t+5]=i>>>16&255^255,e[t+6]=i>>>8&255^255,e[t+7]=255&i^255}(o,s,t),s+=8),i&&(o[s++]=253,o[s++]=251,function(e,t,n){for(let r=3;r>=0;r-=1)e[t+(3-r)]=n>>8*r&255^255}(o,s,n),s+=4),o[s++]=255^a,o.set(qt,s),o}function Xt(e){const t=e instanceof Uint8Array?e:new Uint8Array(e);if(t.length<5)return{data:t};if(!function(e,t){for(let n=0;nt.length)return{data:t};const r=t.length-n,i=t.length-5,a=t.subarray(0,r);let o=r,s=!1;const c={userTimestamp:BigInt(0),frameId:0};for(;o+2<=i;){const e=255^t[o++],n=255^t[o++];if(o+n>i)break;1===e&&8===n?(c.userTimestamp=Jt(t,o),s=!0):2===e&&4===n&&(c.frameId=Ht(t,o,n),s=!0),o+=n}return s?{data:a,metadata:c}:{data:t}}function Jt(e,t){const n=BigInt(((255^e[t])<<24|(255^e[t+1])<<16|(255^e[t+2])<<8|255^e[t+3])>>>0),r=BigInt(((255^e[t+4])<<24|(255^e[t+5])<<16|(255^e[t+6])<<8|255^e[t+7])>>>0);return n<>>0}function zt(e){try{const t=e.getMetadata();if("number"==typeof t.synchronizationSource)return t.synchronizationSource}catch(e){}return 0}var Yt,Qt;function $t(e){return 31&e}function Zt(e){return e>>1&63}function en(e){return e===Yt.SLICE_IDR||e===Yt.SLICE_NON_IDR}function tn(e){return e===Qt.TRAIL_N||e===Qt.TRAIL_R||e===Qt.TSA_N||e===Qt.TSA_R||e===Qt.STSA_N||e===Qt.STSA_R||e===Qt.RADL_N||e===Qt.RADL_R||e===Qt.RASL_N||e===Qt.RASL_R||e===Qt.BLA_W_LP||e===Qt.BLA_W_RADL||e===Qt.BLA_N_LP||e===Qt.IDR_W_RADL||e===Qt.IDR_N_LP||e===Qt.CRA_NUT}function nn(e,t){const n=function(e){const t=[];let n=0,r=0,i=e.length-3;for(;r=i&&(r=e.length);let a=r;for(;a>n&&0===e[a-1];)a--;if(0===n){if(a!==n)throw TypeError("byte stream contains leading data")}else t.push(n);let o=3;re.toString(16).padStart(2,"0"))).join("")}))}(t);switch(n){case rn:return"vp8";case an:case on:case sn:return"h264";case cn:return"opus";default:return null}}))}const un=new Map;class ln extends kt.EventEmitter{encodeFunction(e,t){throw Error("not implemented for subclass")}decodeFunction(e,t){throw Error("not implemented for subclass")}}class hn extends ln{constructor(e){var t;super(),this.hasFrameMetadata=!1,this.frameMetadataFrameId=0,this.lastErrorTimestamp=new Map,this.errorCounts=new Map,this.ERROR_THROTTLE_MS=1e3,this.MAX_ERRORS_PER_MINUTE=5,this.ERROR_WINDOW_MS=6e4,this.loggedNALUFallbacks=new Set,this.sendCounts=new Map,this.keys=e.keys,this.participantIdentity=e.participantIdentity,this.rtpMap=new Map,this.keyProviderOptions=e.keyProviderOptions,this.sifTrailer=null!==(t=e.sifTrailer)&&void 0!==t?t:Uint8Array.from([])}get logContext(){return{participant:this.participantIdentity,mediaTrackId:this.trackId,fallbackCodec:this.videoCodec}}setParticipant(e,t){l.debug("setting new participant on cryptor",Object.assign(Object.assign({},this.logContext),{newParticipant:e,hadPreviousParticipant:!!this.participantIdentity})),this.participantIdentity&&this.participantIdentity!==e&&(l.warn("cryptor has already a participant set, cleaning up before switching",{oldParticipant:this.participantIdentity,newParticipant:e,trackId:this.trackId}),this.unsetParticipant()),this.participantIdentity=e,this.keys=t}unsetParticipant(){l.debug("unsetting participant",this.logContext),this.currentTransform&&(this.currentTransform=void 0),this.participantIdentity=void 0,this.lastErrorTimestamp=new Map,this.errorCounts=new Map}isEnabled(){return this.participantIdentity?un.get(this.participantIdentity):void 0}getParticipantIdentity(){return this.participantIdentity}getTrackId(){return this.trackId}setVideoCodec(e){this.videoCodec=e}setRtpMap(e){this.rtpMap=e}setHasFrameMetadata(e){this.hasFrameMetadata=e}setFrameMetadataOpts(e){this.frameMetadataOpts=e,this.frameMetadataFrameId=0}setupTransform(e,t,n,r,i,a,o){if(a&&(l.info("setting codec on cryptor to",{codec:a}),this.videoCodec=a),"encode"===e&&this.setFrameMetadataOpts(o),l.debug("Setting up frame cryptor transform",Object.assign({operation:e,passedTrackId:r,codec:a,isReuse:i,hasCurrentTransform:!!this.currentTransform},this.logContext)),this.trackId=r,i&&this.currentTransform&&t===this.currentTransform.readable&&n===this.currentTransform.writable)return void l.debug("reusing existing transform",Object.assign(Object.assign({},this.logContext),{trackId:r}));const s=Symbol("transform"),c="encode"===e?this.encodeFunction:this.decodeFunction,d=new TransformStream({transform:c.bind(this)});this.currentTransform={readable:t,writable:n,transformer:d,trackId:r,symbol:s},t.pipeThrough(d).pipeTo(n).catch((e=>{e instanceof TypeError&&"Destination stream closed"===e.message?l.debug("destination stream closed"):(l.warn("transform error",Object.assign({error:e},this.logContext)),this.emit(ut.Error,e instanceof lt?e:new lt(e.message,void 0,this.participantIdentity)))})).finally((()=>{var e;(null===(e=this.currentTransform)||void 0===e?void 0:e.symbol)===s&&(l.debug("transform completed",Object.assign(Object.assign({},this.logContext),{trackId:r})),this.currentTransform=void 0)}))}setSifTrailer(e){l.debug("setting SIF trailer",Object.assign(Object.assign({},this.logContext),{trailer:e})),this.sifTrailer=e}shouldEmitError(e){var t,n;const r=Date.now(),i=null!==(t=this.lastErrorTimestamp.get(e))&&void 0!==t?t:0,a=null!==(n=this.errorCounts.get(e))&&void 0!==n?n:0;return r-i>this.ERROR_WINDOW_MS?(this.errorCounts.set(e,0),this.lastErrorTimestamp.set(e,r),!0):!(r-i=this.MAX_ERRORS_PER_MINUTE?(a===this.MAX_ERRORS_PER_MINUTE&&(l.warn("Suppressing further decryption errors for ".concat(this.participantIdentity),Object.assign(Object.assign({},this.logContext),{errorKey:e})),this.errorCounts.set(e,a+1)),!1):(this.lastErrorTimestamp.set(e,r),this.errorCounts.set(e,a+1),!0))}emitThrottledError(e){var t;const n="".concat(this.participantIdentity,"-").concat(e.reason,"-decrypt");if(this.shouldEmitError(n)){const r=null!==(t=this.errorCounts.get(n))&&void 0!==t?t:0;r>1&&l.debug("Decryption error (".concat(r," occurrences in window)"),Object.assign(Object.assign({},this.logContext),{reason:ot[e.reason]})),this.emit(ut.Error,e)}}encodeFunction(t,n){return e(this,void 0,void 0,(function*(){var e;if(0===t.data.byteLength)return n.enqueue(t);if(!this.isEnabled())return this.appendFrameMetadata(t),n.enqueue(t);const r=this.keys.getKeySet();if(!r)return void this.emitThrottledError(new lt("key set not found for ".concat(this.participantIdentity," at index ").concat(this.keys.getCurrentKeyIndex()),ot.MissingKey,this.participantIdentity));const i=r.encryptionKey,a=this.keys.getCurrentKeyIndex();if(i){const r=this.makeIV(null!==(e=t.getMetadata().synchronizationSource)&&void 0!==e?e:-1,t.timestamp);let s=this.getUnencryptedBytes(t);const c=new Uint8Array(t.data,0,s.unencryptedBytes),d=new Uint8Array(2);d[0]=12,d[1]=a;try{const e=yield crypto.subtle.encrypt({name:m,iv:r,additionalData:new Uint8Array(t.data,0,c.byteLength)},i,new Uint8Array(t.data,s.unencryptedBytes));let a=new Uint8Array(e.byteLength+r.byteLength+d.byteLength);a.set(new Uint8Array(e)),a.set(new Uint8Array(r),e.byteLength),a.set(d,e.byteLength+r.byteLength),s.requiresNALUProcessing&&(a=function(e){const t=[];for(var n=0,r=0;r=2&&(t.push(3),n=0),t.push(i),0==i?++n:n=0}return new Uint8Array(t)}(a));var o=new Uint8Array(c.byteLength+a.byteLength);return o.set(c),o.set(a,c.byteLength),t.data=o.buffer,this.appendFrameMetadata(t),n.enqueue(t)}catch(e){l.error(e)}}else l.debug("failed to encrypt, emitting error",this.logContext),this.emitThrottledError(new lt("encryption key missing for encoding",ot.MissingKey,this.participantIdentity))}))}appendFrameMetadata(e){var t;Wt(this.frameMetadataOpts)&&ht(e)&&((null===(t=this.frameMetadataOpts)||void 0===t?void 0:t.frameId)&&(this.frameMetadataFrameId=4294967295===this.frameMetadataFrameId?1:this.frameMetadataFrameId+1),function(e,t,n){if(!Wt(t)||0===e.data.byteLength)return!1;const r=(null==t?void 0:t.timestamp)?BigInt(Date.now())*BigInt(1e3):BigInt(0),i=(null==t?void 0:t.frameId)?n:0,a=new Uint8Array(e.data),o=Gt(a,r,i);o.byteLength!==a.byteLength&&(e.data=o.buffer.slice(o.byteOffset,o.byteOffset+o.byteLength))}(e,this.frameMetadataOpts,this.frameMetadataFrameId))}decodeFunction(t,n){return e(this,void 0,void 0,(function*(){if(this.hasFrameMetadata&&ht(t))try{const e=function(e,t){if(0===e.data.byteLength)return{};const n=Xt(e.data);if(!n.metadata)return{};const r=n.data.buffer.slice(n.data.byteOffset,n.data.byteOffset+n.data.byteLength),i=function(e){try{const t=e.getMetadata();if("number"==typeof t.rtpTimestamp)return t.rtpTimestamp;if("number"==typeof t.timestamp)return t.timestamp}catch(e){}if("number"==typeof e.timestamp)return e.timestamp}(e);return void 0!==i&&t?{data:r,payload:{trackId:t,rtpTimestamp:i,ssrc:zt(e),metadata:n.metadata}}:{data:r}}(t,this.trackId);if(e.data&&(t.data=e.data),e.payload&&this.participantIdentity){const t={kind:"packetTrailerMetadata",data:e.payload};postMessage(t)}}catch(e){}if(!this.isEnabled()||0===t.data.byteLength)return n.enqueue(t);if(function(e,t){if(0===t.byteLength)return!1;const n=new Uint8Array(e.slice(e.byteLength-t.byteLength));return t.every(((e,t)=>e===n[t]))}(t.data,this.sifTrailer))return t.data=t.data.slice(0,t.data.byteLength-this.sifTrailer.byteLength),(yield dn(t.data))?(l.debug("enqueue SIF",this.logContext),n.enqueue(t)):void l.warn("Unexpected SIF frame payload, dropping frame",this.logContext);const e=new Uint8Array(t.data)[t.data.byteLength-1];if(!this.keys.hasInvalidKeyAtIndex(e))if(this.keys.getKeySet(e))try{const r=yield this.decryptFrame(t,e);if(this.keys.decryptionSuccess(e),r)return n.enqueue(r)}catch(t){t instanceof lt&&t.reason===ot.InvalidKey?this.keys.hasValidKey&&(this.emitThrottledError(t),this.keys.decryptionFailure(e)):l.warn("decoding frame failed",{error:t})}else l.warn("skipping decryption due to missing key at index ".concat(e)),this.emitThrottledError(new lt("missing key at index ".concat(e," for participant ").concat(this.participantIdentity),ot.MissingKey,this.participantIdentity)),this.keys.decryptionFailure(e)}))}decryptFrame(t,n){return e(this,arguments,void 0,(function(e,t){var n=this;let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:void 0,i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{ratchetCount:0};return function*(){var a;const o=n.keys.getKeySet(t);if(!i.encryptionKey&&!o)throw new TypeError("no encryption key found for decryption of ".concat(n.participantIdentity));let s=n.getUnencryptedBytes(e);try{const t=new Uint8Array(e.data,0,s.unencryptedBytes);var c=new Uint8Array(e.data,t.length,e.data.byteLength-t.length);if(s.requiresNALUProcessing&&function(e){for(var t=0;t=3&&!e[r]&&!e[r+1]&&3==e[r+2]?(t.push(e[r++]),t.push(e[r++]),r++):t.push(e[r++]);return new Uint8Array(t)}(c);const n=new Uint8Array(t.byteLength+c.byteLength);n.set(t),n.set(c,t.byteLength),e.data=n.buffer}const n=new Uint8Array(e.data,e.data.byteLength-2,2),r=n[0],d=new Uint8Array(e.data,e.data.byteLength-r-n.byteLength,r),u=t.byteLength,l=e.data.byteLength-(t.byteLength+r+n.byteLength),h=yield crypto.subtle.decrypt({name:m,iv:d,additionalData:new Uint8Array(e.data,0,t.byteLength)},null!==(a=i.encryptionKey)&&void 0!==a?a:o.encryptionKey,new Uint8Array(e.data,u,l)),f=new ArrayBuffer(t.byteLength+h.byteLength),p=new Uint8Array(f);return p.set(new Uint8Array(e.data,0,t.byteLength)),p.set(new Uint8Array(h),t.byteLength),e.data=f,e}catch(a){if(n.keyProviderOptions.ratchetWindowSize>0){if(i.ratchetCount256)throw new TypeError("Keyring size needs to be between 1 and 256");this.cryptoKeyRing=new Array(t.keyringSize).fill(void 0),this.decryptionFailureCounts=new Array(t.keyringSize).fill(0),this.keyProviderOptions=t,this.ratchetPromiseMap=new Map,this.participantIdentity=e}hasInvalidKeyAtIndex(e){return this.keyProviderOptions.failureTolerance>=0&&this.decryptionFailureCounts[e]>this.keyProviderOptions.failureTolerance}decryptionFailure(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.currentKeyIndex;this.keyProviderOptions.failureTolerance<0||(this.decryptionFailureCounts[e]+=1,this.decryptionFailureCounts[e]>this.keyProviderOptions.failureTolerance&&l.warn("key for ".concat(this.participantIdentity," at index ").concat(e," is being marked as invalid")))}decryptionSuccess(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.currentKeyIndex;this.resetKeyStatus(e)}resetKeyStatus(e){void 0===e?this.decryptionFailureCounts.fill(0):this.decryptionFailureCounts[e]=0}ratchetKey(t){let n=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];const r=null!=t?t:this.getCurrentKeyIndex(),i=this.ratchetPromiseMap.get(r);if(void 0!==i)return i;const a=new Promise(((t,i)=>e(this,void 0,void 0,(function*(){try{const i=this.getKeySet(r);if(!i)throw new TypeError("Cannot ratchet key without a valid keyset of participant ".concat(this.participantIdentity));const a=i.material,o=yield function(t,n){return e(this,void 0,void 0,(function*(){const e=ft(t.algorithm.name,n);return crypto.subtle.deriveBits(e,t,256)}))}(a,this.keyProviderOptions.ratchetSalt),s=yield function(t){return e(this,arguments,void 0,(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{name:m},n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"encrypt";return function*(){return crypto.subtle.importKey("raw",e,t,!1,"derive"===n?["deriveBits","deriveKey"]:["encrypt","decrypt"])}()}))}(o,a.algorithm.name,"derive"),c={chainKey:o,cryptoKey:s};n&&(yield this.setKeyFromMaterial(s,r,c)),t(c)}catch(e){i(e)}finally{this.ratchetPromiseMap.delete(r)}}))));return this.ratchetPromiseMap.set(r,a),a}setKey(t){return e(this,arguments,void 0,(function(e){var t=this;let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,r=!(arguments.length>2&&void 0!==arguments[2])||arguments[2];return function*(){yield t.setKeyFromMaterial(e,n,null,r),r&&t.resetKeyStatus(n)}()}))}setKeyFromMaterial(t,n){return e(this,arguments,void 0,(function(e,t){var n=this;let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null,i=!(arguments.length>3&&void 0!==arguments[3])||arguments[3];return function*(){const a=yield pt(e,n.keyProviderOptions),o=t>=0?t%n.cryptoKeyRing.length:n.currentKeyIndex;l.debug("setting new key with index ".concat(t),{usage:e.usages,algorithm:e.algorithm,ratchetSalt:n.keyProviderOptions.ratchetSalt}),n.setKeySet(a,o,r),o>=0&&i&&(n.currentKeyIndex=o)}()}))}setKeySet(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null;this.cryptoKeyRing[t%this.cryptoKeyRing.length]=e,n&&this.emit(ct.KeyRatcheted,n,this.participantIdentity,t)}setCurrentKeyIndex(t){return e(this,void 0,void 0,(function*(){this.currentKeyIndex=t%this.cryptoKeyRing.length,this.resetKeyStatus(t)}))}getCurrentKeyIndex(){return this.currentKeyIndex}getKeySet(e){return this.cryptoKeyRing[null!=e?e:this.currentKeyIndex]}}const pn=[],yn=new Map;let mn,gn,bn=new class{constructor(){this.pendingTasks=new Map,this.taskMutex=new y,this.nextTaskIndex=0}run(t){return e(this,void 0,void 0,(function*(){const e={id:this.nextTaskIndex++,enqueuedAt:Date.now(),status:h.WAITING};this.pendingTasks.set(e.id,e);const n=yield this.taskMutex.lock();try{return e.executedAt=Date.now(),e.status=h.RUNNING,yield t()}finally{e.status=h.COMPLETED,this.pendingTasks.delete(e.id),n()}}))}flush(){return e(this,void 0,void 0,(function*(){return this.run((()=>e(this,void 0,void 0,(function*(){}))))}))}snapshot(){return Array.from(this.pendingTasks.values())}},vn=!1,kn=b,wn=new Map;function Tn(e,t){let n=pn.filter((e=>e.getTrackId()===t));if(n.length>1){const r=n.map((e=>({participant:e.getParticipantIdentity()}))).join(",");l.error("Found multiple cryptors for the same trackID ".concat(t,". target participant: ").concat(e," "),{participants:r})}let r=n[0];if(r)e!==r.getParticipantIdentity()&&r.setParticipant(e,Sn(e));else{if(l.info("creating new cryptor for",{participantIdentity:e,trackId:t}),!kn)throw Error("Missing keyProvider options");r=new hn({participantIdentity:e,keys:Sn(e),keyProviderOptions:kn,sifTrailer:gn}),r.setRtpMap(wn),function(e){e.on(ut.Error,(e=>{const t={kind:"error",data:{error:new Error("".concat(ot[e.reason],": ").concat(e.message)),participantIdentity:e.participantIdentity}};postMessage(t)}))}(r),pn.push(r)}return r}function Sn(e){if(vn)return In();let t=yn.get(e);return t||(t=new fn(e,kn),t.on(ct.KeyRatcheted,En),yn.set(e,t)),t}function In(){return mn||(l.debug("creating new shared key handler"),mn=new fn("shared-key",kn)),mn}function En(e,t,n){postMessage({kind:"ratchetKey",data:{participantIdentity:t,keyIndex:n,ratchetResult:e}})}l.setDefaultLevel("info"),onmessage=t=>{bn.run((()=>e(void 0,void 0,void 0,(function*(){const n=t.data,r=n.kind,i=n.data;switch(r){case"init":l.setLevel(i.loglevel),l.info("worker initialized"),kn=i.keyProviderOptions,vn=!!i.keyProviderOptions.sharedKey;postMessage({kind:"initAck",data:{enabled:false}});break;case"enable":o=i.enabled,s=i.participantIdentity,l.debug("setting encryption enabled for all tracks of ".concat(s),{enable:o}),un.set(s,o),l.info("updated e2ee enabled status for ".concat(i.participantIdentity," to ").concat(i.enabled)),postMessage(t.data);break;case"decode":let n=Tn(i.participantIdentity,i.trackId);n.setHasFrameMetadata(i.hasPacketTrailer),n.setupTransform(r,i.readableStream,i.writableStream,i.trackId,i.isReuse,i.codec);break;case"encode":let c=Tn(i.participantIdentity,i.trackId);c.setHasFrameMetadata(i.hasPacketTrailer),c.setupTransform(r,i.readableStream,i.writableStream,i.trackId,i.isReuse,i.codec,i.packetTrailer);break;case"encryptDataRequest":const d=yield yt.encrypt(i.payload,Sn(i.participantIdentity)),u=d.payload,h=d.iv,f=d.keyIndex;console.log("encrypted payload",{original:i.payload,encrypted:u,iv:h}),postMessage({kind:"encryptDataResponse",data:{payload:u,iv:h,keyIndex:f,uuid:i.uuid}});break;case"decryptDataRequest":try{const e=(yield yt.decrypt(i.payload,i.iv,Sn(i.participantIdentity),i.keyIndex)).payload;postMessage({kind:"decryptDataResponse",data:{payload:e,uuid:i.uuid}})}catch(e){l.error("DataCryptor decryption failed",{error:e,participantIdentity:i.participantIdentity,uuid:i.uuid}),postMessage({kind:"error",data:{error:e instanceof Error?e:new Error(String(e)),uuid:i.uuid}})}break;case"setKey":vn?yield function(t,n,r){return e(this,void 0,void 0,(function*(){l.info("set shared key",{index:n}),yield In().setKey(t,n,r)}))}(i.key,i.keyIndex,i.updateCurrentKeyIndex):i.participantIdentity?(l.info("set participant sender key ".concat(i.participantIdentity," index ").concat(i.keyIndex)),yield Sn(i.participantIdentity).setKey(i.key,i.keyIndex,i.updateCurrentKeyIndex)):l.error("no participant Id was provided and shared key usage is disabled");break;case"removeTransform":!function(e,t){const n=pn.filter((n=>n.getParticipantIdentity()===t&&n.getTrackId()===e));n.length>1&&l.error("Found multiple cryptors for the same participant and trackID combination",{trackId:e,participantIdentity:t});const r=n[0];r?r.unsetParticipant():l.warn("Could not unset participant on cryptor",{trackId:e,participantIdentity:t})}(i.trackId,i.participantIdentity);break;case"updateCodec":const p=Tn(i.participantIdentity,i.trackId);p.setVideoCodec(i.codec),p.setHasFrameMetadata(i.hasPacketTrailer),l.info("updated codec",{participantIdentity:i.participantIdentity,trackId:i.trackId,codec:i.codec,hasPacketTrailer:i.hasPacketTrailer});break;case"setRTPMap":wn=i.map,pn.forEach((e=>{e.getParticipantIdentity()===i.participantIdentity&&e.setRtpMap(i.map)}));break;case"ratchetRequest":!function(t){e(this,void 0,void 0,(function*(){if(vn){const e=In();yield e.ratchetKey(t.keyIndex),e.resetKeyStatus()}else if(t.participantIdentity){const e=Sn(t.participantIdentity);yield e.ratchetKey(t.keyIndex),e.resetKeyStatus()}else l.error("no participant Id was provided for ratchet request and shared key usage is disabled")}))}(i);break;case"setSifTrailer":a=i.trailer,gn=a,pn.forEach((e=>{e.setSifTrailer(a)}))}var a,o,s}))))},self.RTCTransformEvent&&(self.onrtctransform=t=>{const n=t.transformer,r=n.options,i=r.kind,a=r.participantIdentity,o=r.trackId,s=r.codec,c=r.hasPacketTrailer;bn.run((()=>e(void 0,void 0,void 0,(function*(){const e=Tn(a,o);e.setHasFrameMetadata(c),l.debug("onrtctransform setup",{participantIdentity:a,trackId:o,codec:s}),e.setupTransform(i,n.readable,n.writable,o,!1,s,"encode"===i?r.packetTrailer:void 0)}))))})})); //# sourceMappingURL=livekit-client.e2ee.worker.js.map